feat: update application initialization for drizzle

This commit is contained in:
MythEclipse
2026-05-14 15:43:16 +07:00
parent 1c4b0afbce
commit 9ff0f0bede
4 changed files with 23 additions and 28 deletions

View File

@@ -4,7 +4,7 @@ import "@snazzah/davey";
import "dotenv/config"; import "dotenv/config";
import { Client } from "discord.js-selfbot-v13"; import { Client } from "discord.js-selfbot-v13";
import { config } from "./config"; import { config } from "./config";
import { getDatabase } from "./database/adapter"; import { initializeDatabase, closeDatabase } from "./database/drizzle";
import { createChildLogger } from "./logger"; import { createChildLogger } from "./logger";
import { startPendingAIAnalysisWorker } from "./moderation/aiAnalyzer"; import { startPendingAIAnalysisWorker } from "./moderation/aiAnalyzer";
import { syncBacklogMessages } from "./moderation/backlogSync"; import { syncBacklogMessages } from "./moderation/backlogSync";
@@ -26,7 +26,6 @@ const client = new Client();
const voiceController = new VoiceController(client); const voiceController = new VoiceController(client);
let isShuttingDown = false; let isShuttingDown = false;
let db: Awaited<ReturnType<typeof getDatabase>> | null = null;
async function gracefulShutdown(signal: string) { async function gracefulShutdown(signal: string) {
if (isShuttingDown) { if (isShuttingDown) {
@@ -39,10 +38,8 @@ async function gracefulShutdown(signal: string) {
try { try {
logger.info("Closing database..."); logger.info("Closing database...");
if (db) { await closeDatabase();
await db.close(); logger.info("Database closed");
logger.info("Database closed");
}
logger.info("Stopping voice connection..."); logger.info("Stopping voice connection...");
await voiceController.disconnect(); await voiceController.disconnect();
@@ -67,8 +64,8 @@ async function gracefulShutdown(signal: string) {
async function initializeApp() { async function initializeApp() {
try { try {
logger.info("Initializing database adapter"); logger.info("Initializing database");
db = await getDatabase(); await initializeDatabase();
logger.info({ type: config.DATABASE_TYPE }, "Database initialized"); logger.info({ type: config.DATABASE_TYPE }, "Database initialized");
} catch (err) { } catch (err) {
logger.error({ error: err }, "Failed to initialize database"); logger.error({ error: err }, "Failed to initialize database");
@@ -77,9 +74,9 @@ async function initializeApp() {
client.on("ready", async () => { client.on("ready", async () => {
logger.info({ user: client.user?.tag }, "Bot logged in"); logger.info({ user: client.user?.tag }, "Bot logged in");
registerMessageCapture(client, db!); registerMessageCapture(client);
startPendingAIAnalysisWorker(); startPendingAIAnalysisWorker();
syncBacklogMessages(client, db!).catch((error) => { syncBacklogMessages(client).catch((error) => {
logger.warn({ error }, "Backlog sync failed"); logger.warn({ error }, "Backlog sync failed");
}); });
await startWebserver(config.WEBSERVER_PORT, client, voiceController); await startWebserver(config.WEBSERVER_PORT, client, voiceController);

View File

@@ -1,13 +1,11 @@
import type { Client, Message } from "discord.js-selfbot-v13"; import type { Client, Message } from "discord.js-selfbot-v13";
import { config } from "../config"; import { config } from "../config";
import { createChildLogger } from "../logger"; import { createChildLogger } from "../logger";
import type { SqliteDatabase } from "../muxer-queue";
import { captureMessage } from "./messageCapture"; import { captureMessage } from "./messageCapture";
const logger = createChildLogger("backlog-sync"); const logger = createChildLogger("backlog-sync");
async function syncChannelMessages( async function syncChannelMessages(
db: SqliteDatabase,
channel: any, channel: any,
cutoffTime: number, cutoffTime: number,
): Promise<number> { ): Promise<number> {
@@ -31,7 +29,7 @@ async function syncChannelMessages(
continue; continue;
} }
await captureMessage(db, message, "text"); await captureMessage(message, "text");
synced++; synced++;
} }
@@ -44,7 +42,6 @@ async function syncChannelMessages(
export async function syncBacklogMessages( export async function syncBacklogMessages(
client: Client, client: Client,
db: SqliteDatabase,
): Promise<void> { ): Promise<void> {
if (!config.MONITOR_GUILD_ID) { if (!config.MONITOR_GUILD_ID) {
logger.warn("MONITOR_GUILD_ID not configured, skipping backlog sync"); logger.warn("MONITOR_GUILD_ID not configured, skipping backlog sync");
@@ -68,7 +65,6 @@ export async function syncBacklogMessages(
export async function syncSelectedChannelBacklog( export async function syncSelectedChannelBacklog(
client: Client, client: Client,
db: SqliteDatabase,
guildId: string, guildId: string,
channelId: string, channelId: string,
): Promise<number> { ): Promise<number> {
@@ -91,7 +87,7 @@ export async function syncSelectedChannelBacklog(
); );
try { try {
const count = await syncChannelMessages(db, channel as any, cutoffTime); const count = await syncChannelMessages(channel as any, cutoffTime);
logger.info( logger.info(
{ channelId, count }, { channelId, count },
"Backlog sync completed for selected channel", "Backlog sync completed for selected channel",

View File

@@ -1,7 +1,9 @@
import type { Client, Message } from "discord.js-selfbot-v13"; import type { Client, Message } from "discord.js-selfbot-v13";
import { config } from "../config"; import { config } from "../config";
import { createChildLogger } from "../logger"; import { createChildLogger } from "../logger";
import type { SqliteDatabase } from "../muxer-queue"; import { getDatabase } from "../database/drizzle";
import { messagesTable } from "../database/schema";
import { eq } from "drizzle-orm";
import { queueMessageAnalysis } from "./aiAnalyzer"; import { queueMessageAnalysis } from "./aiAnalyzer";
import { import {
getDisplayContent, getDisplayContent,
@@ -14,7 +16,6 @@ import type { AttachmentRecord, MessageRecord } from "./types";
const logger = createChildLogger("message-capture"); const logger = createChildLogger("message-capture");
export async function captureMessage( export async function captureMessage(
db: SqliteDatabase,
message: Message, message: Message,
type: "text" | "edited" | "deleted", type: "text" | "edited" | "deleted",
): Promise<void> { ): Promise<void> {
@@ -95,14 +96,13 @@ export async function captureMessage(
export function registerMessageCapture( export function registerMessageCapture(
client: Client, client: Client,
db: SqliteDatabase,
): void { ): void {
client.on("messageCreate", async (message) => { client.on("messageCreate", async (message) => {
if (!message.guildId || message.guildId !== config.MONITOR_GUILD_ID) return; if (!message.guildId || message.guildId !== config.MONITOR_GUILD_ID) return;
if (message.author?.bot) return; if (message.author?.bot) return;
try { try {
await captureMessage(db, message, "text"); await captureMessage(message, "text");
} catch (error) { } catch (error) {
logger.error( logger.error(
{ {
@@ -121,12 +121,15 @@ export function registerMessageCapture(
try { try {
const { updateMessageAsEdited } = await import("./messageStore"); const { updateMessageAsEdited } = await import("./messageStore");
const db = getDatabase() as any;
const existing = db const existing = await db
.prepare("SELECT id FROM messages WHERE id = ?") .select()
.get(newMessage.id) as { id: string } | undefined; .from(messagesTable)
.where(eq(messagesTable.id, newMessage.id))
.limit(1);
if (existing) { if (existing.length > 0) {
const editedAt = Date.now(); const editedAt = Date.now();
await updateMessageAsEdited( await updateMessageAsEdited(
newMessage.id, newMessage.id,
@@ -144,7 +147,7 @@ export function registerMessageCapture(
}); });
} }
} else if (newMessage.author) { } else if (newMessage.author) {
await captureMessage(db, newMessage as Message, "text"); await captureMessage(newMessage as Message, "text");
} }
} catch (error) { } catch (error) {
logger.error( logger.error(

View File

@@ -14,10 +14,11 @@ import {
getMessagesByChannel, getMessagesByChannel,
} from "./moderation/messageStore"; } from "./moderation/messageStore";
import { import {
getDatabase, getDatabase as getMuxerDatabase,
getPersistedValue, getPersistedValue,
setPersistedValue, setPersistedValue,
} from "./muxer-queue"; } from "./muxer-queue";
import { getDatabase } from "./database/drizzle";
import { discordPlayer } from "./player"; import { discordPlayer } from "./player";
import type { VoiceController } from "./voiceController"; import type { VoiceController } from "./voiceController";
@@ -260,7 +261,6 @@ export async function startWebserver(
// Moderation API endpoints // Moderation API endpoints
app.get("/api/messages", async (req, res, next) => { app.get("/api/messages", async (req, res, next) => {
try { try {
const db = await getDatabase();
const { const {
channel, channel,
type, type,
@@ -325,7 +325,6 @@ export async function startWebserver(
const count = await syncSelectedChannelBacklog( const count = await syncSelectedChannelBacklog(
_client, _client,
await getDatabase(),
guildId, guildId,
channelId, channelId,
); );