fix: auto-fix code quality [skip ci]

This commit is contained in:
asepharyana committed 2026-09-23 22:11:00 +07:00
1 parent 771783d991
commit 401155b501
12 files changed
+200 -235

No files matched your search

+1 -105
View File
@@ -1,6 +1,4 @@
import { Client } from "discord.js-selfbot-v13";
import { inArray, lt } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { ConfigError, DatabaseError } from "@/shared/errors/index";
import { createChildLogger } from "@/shared/logger/index";
import {
@@ -36,117 +34,15 @@ import { registerPresenceCapture } from "../modules/user-presence/index.js";
import { config } from "../shared/config/config.js";
import {
closeDatabase,
getDatabase,
initializeDatabase,
} from "../shared/database/drizzle.js";
import { runMigrations } from "../shared/database/migrate.js";
import type * as schema from "../shared/database/schema.js";
import { attachmentsTable, messagesTable } from "../shared/database/schema.js";
import { createDiscordClientOptions } from "../shared/discord/clientOptions.js";
import { startRetentionCleanup } from "./retention.js";
import { createGracefulShutdown } from "./shutdown.js";
const logger = createChildLogger("discord-gateway");
// ─── Retention Cleanup ─────────────────────────────────────────────────────
async function deleteExpiredRecords(
table: any,
timestampField: any,
days: number | undefined,
dryRun: boolean,
label: string,
): Promise<void> {
if (!days || days <= 0) {
logger.debug({ label }, `Retention disabled for ${label}`);
return;
}
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
const db = getDatabase() as unknown as NodePgDatabase<typeof schema>;
const expired = await db
.select({ id: table.id })
.from(table)
.where(lt(timestampField, cutoff))
.limit(1000);
if (expired.length === 0) {
logger.debug({ label }, `No expired ${label} found`);
return;
}
logger.info({ count: expired.length, label }, `Found expired ${label}`);
if (dryRun) {
logger.info(
{ count: expired.length, label },
`[DRY RUN] Would delete ${expired.length} ${label}`,
);
return;
}
try {
await db.delete(table).where(
inArray(
table.id,
expired.map((r) => r.id),
),
);
logger.info({ count: expired.length, label }, `Deleted expired ${label}`);
} catch (err) {
logger.error({ err, label }, `Failed to delete expired ${label}`);
}
}
function startRetentionCleanup(): void {
const intervalMs = config.RETENTION_CLEANUP_INTERVAL_MS;
const dryRun = config.RETENTION_DRY_RUN;
logger.info(
{
intervalMs,
dryRun,
messagesDays: config.RETENTION_MESSAGES_DAYS,
attachmentsDays: config.RETENTION_ATTACHMENTS_DAYS,
},
"Starting retention cleanup scheduler",
);
async function runCleanupTick(): Promise<void> {
await deleteExpiredRecords(
messagesTable,
messagesTable.created_at,
config.RETENTION_MESSAGES_DAYS,
dryRun,
"messages",
);
await deleteExpiredRecords(
attachmentsTable,
attachmentsTable.created_at,
config.RETENTION_ATTACHMENTS_DAYS,
dryRun,
"attachments",
);
}
// Run immediately on start, then schedule
runCleanupTick().catch((error) => {
logger.error(
{ error: error instanceof Error ? error.message : String(error) },
"Initial retention cleanup tick failed",
);
});
setInterval(() => {
runCleanupTick().catch((error) => {
logger.error(
{ error: error instanceof Error ? error.message : String(error) },
"Retention cleanup tick failed",
);
});
}, intervalMs);
}
// ─── Bootstrap ─────────────────────────────────────────────────────────────
export async function initializeDiscordGateway() {
+22 -4
View File
@@ -1,5 +1,8 @@
import { inArray, lt } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import type {
NodePgDatabase,
NodePgQueryResultHKT,
} from "drizzle-orm/node-postgres";
import { createChildLogger } from "@/shared/logger/index";
import { config } from "../shared/config/config.js";
import { getDatabase } from "../shared/database/drizzle.js";
@@ -8,11 +11,26 @@ import { attachmentsTable, messagesTable } from "../shared/database/schema.js";
const logger = createChildLogger("discord-gateway");
/** DB handle typed with the full schema so table/column refs resolve. */
type GatewayDatabase = NodePgDatabase<typeof schema>;
/** Tables eligible for retention cleanup: string `id` + numeric `created_at`. */
type RetentionTable = typeof messagesTable | typeof attachmentsTable;
type RetentionTimestampColumn =
| typeof messagesTable.created_at
| typeof attachmentsTable.created_at;
// ─── Retention Cleanup ─────────────────────────────────────────────────────
/**
* Delete rows older than `days` in `table`, in batches of up to 1000 ids.
* When `dryRun` is set, logs what would be deleted without deleting.
* Returns immediately (no-op) when `days` is unset or <= 0.
*/
async function deleteExpiredRecords(
table: any,
timestampField: any,
table: RetentionTable,
timestampField: RetentionTimestampColumn,
days: number | undefined,
dryRun: boolean,
label: string,
@@ -23,7 +41,7 @@ async function deleteExpiredRecords(
}
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
const db = getDatabase() as unknown as NodePgDatabase<typeof schema>;
const db = getDatabase() as unknown as GatewayDatabase;
const expired = await db
.select({ id: table.id })
+7 -2
View File
@@ -18,10 +18,15 @@ export interface GracefulShutdownOptions {
stopMetricsServer?: StopMetricsServer;
}
export function createGracefulShutdown(options: GracefulShutdownOptions) {
export type GracefulShutdown = (signal: string) => Promise<void>;
/** Create a shutdown handler that can only be triggered once. */
export function createGracefulShutdown(
options: GracefulShutdownOptions,
): GracefulShutdown {
let isShuttingDown = false;
return async function gracefulShutdown(signal: string) {
return async function gracefulShutdown(signal: string): Promise<void> {
if (isShuttingDown) {
options.logger.warn(`Already shutting down, ignoring ${signal}`);
return;
@@ -32,9 +32,9 @@ export class CommandHandler {
// connection for SUBSCRIBE mode — a subscribed connection cannot perform
// publish/set operations. This connection listens on backend:command for
// inbound requests from the backend.
this.redisSub = new Redis(config.REDIS_URL); // Dedicated Redis connection needed because: Redis requires a dedicated
// PUBLISH connection (cannot share with redisSub which is in SUBSCRIBE mode).
// Handles command reply publishing and voice/media status key updates.
this.redisSub = new Redis(config.REDIS_URL);
// A second dedicated connection for PUBLISH — a connection in SUBSCRIBE
// mode cannot publish, so replies go out on this one.
this.redisPub = new Redis(config.REDIS_URL);
this.redisSub.on("error", (err) => {
@@ -85,6 +85,11 @@ export class CommandHandler {
// ---- Command dispatch ----
/** Normalize an unknown thrown value to a readable message. */
private static errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
private async handleCommand(raw: string): Promise<void> {
let cmd: CommandMessage;
try {
@@ -112,7 +117,7 @@ export class CommandHandler {
};
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const message = CommandHandler.errorMessage(err);
logger.error(
{ commandId: cmd.id, error: message },
"Command execution failed",