refactor: atomic, DRY, and logging improvements
- Shared Redis channel constants as single source of truth (redis-channels.ts) - commandHandler.ts split into VoiceHandler, MediaHandler, GuildHandler, ModerationHandler with handler-registry.ts dispatch - messageStore.ts (1322 lines) split into domain-specific DB files: messages.db.ts, attachments.db.ts, reviews.db.ts, moderation-actions.db.ts, retention.db.ts - recorder.ts startSpeaking callback extracted into speakingHandler.ts, streamSetup.ts, segmentFinalizer.ts - autoDeleteManager.ts split into autoDeleteEligibility.ts, autoDeleteNotify.ts, autoDeleteLogger.ts - Added createChildLogger() logging across 8 service files - Backend messages.repository.ts migrated from raw SQL to Drizzle ORM - Fixed biome.json to exclude packages/**/dist/* from lint - Fixed config.ts GUILD_ID pre-existing type error Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
7108f6bb47
commit
b68789fffc
@@ -15,6 +15,10 @@ class MascotChatService {
|
||||
context: MascotChatContext | undefined,
|
||||
userId: string,
|
||||
): Promise<string> {
|
||||
logger.info(
|
||||
{ userId, messageLength: message.length },
|
||||
"processMessage called",
|
||||
);
|
||||
const recentContext = await this.getRecentConversationContext(userId);
|
||||
const serverInsights = await mascotChatRepository.getServerInsights(
|
||||
context?.guildId,
|
||||
@@ -34,6 +38,7 @@ class MascotChatService {
|
||||
}
|
||||
|
||||
async saveConversation(input: SaveConversationInput): Promise<void> {
|
||||
logger.info({ userId: input.userId }, "saveConversation called");
|
||||
await mascotChatRepository.saveConversation(input);
|
||||
}
|
||||
|
||||
@@ -41,10 +46,12 @@ class MascotChatService {
|
||||
userId: string,
|
||||
limit: number,
|
||||
): Promise<MascotChatHistoryRow[]> {
|
||||
logger.debug({ userId, limit }, "getChatHistory called");
|
||||
return mascotChatRepository.getChatHistory(userId, limit);
|
||||
}
|
||||
|
||||
async clearChatHistory(userId: string): Promise<void> {
|
||||
logger.info({ userId }, "clearChatHistory called");
|
||||
await mascotChatRepository.clearChatHistory(userId);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import {
|
||||
COMMAND_MEDIA_QUEUE,
|
||||
COMMAND_MEDIA_SKIP,
|
||||
COMMAND_MEDIA_STOP,
|
||||
COMMAND_MEDIA_VOLUME,
|
||||
MEDIA_STATUS_KEY,
|
||||
} from "@bete/shared";
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import { publishCommand, readRedisStatus } from "../../shared/redis/index.js";
|
||||
|
||||
@@ -41,10 +48,11 @@ const DEFAULT_STATE: MediaState = {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Read media status from Redis key "media:status" set by discord-gateway.
|
||||
* Read media status from Redis key `media:status` set by discord-gateway.
|
||||
*/
|
||||
export async function getStatus(): Promise<MediaState> {
|
||||
const cached = await readRedisStatus("media:status");
|
||||
logger.debug("getStatus called");
|
||||
const cached = await readRedisStatus(MEDIA_STATUS_KEY);
|
||||
|
||||
if (cached) {
|
||||
const rawPlaying = cached.playing;
|
||||
@@ -71,8 +79,9 @@ export async function queue(
|
||||
source: string,
|
||||
mode: "music" | "screen" = "music",
|
||||
): Promise<MediaState> {
|
||||
logger.info({ source, mode }, "queue called");
|
||||
const reply = await publishCommand<MediaState>(
|
||||
"media:queue",
|
||||
COMMAND_MEDIA_QUEUE,
|
||||
{ source, mode },
|
||||
DEFAULT_COMMAND_TIMEOUT_MS,
|
||||
);
|
||||
@@ -97,8 +106,9 @@ export async function queue(
|
||||
* Skip current track via Redis command to discord-gateway.
|
||||
*/
|
||||
export async function skip(): Promise<MediaState> {
|
||||
logger.info("skip called");
|
||||
const reply = await publishCommand<MediaState>(
|
||||
"media:skip",
|
||||
COMMAND_MEDIA_SKIP,
|
||||
{},
|
||||
DEFAULT_COMMAND_TIMEOUT_MS,
|
||||
);
|
||||
@@ -120,8 +130,9 @@ export async function skip(): Promise<MediaState> {
|
||||
* Stop playback via Redis command to discord-gateway.
|
||||
*/
|
||||
export async function stop(): Promise<MediaState> {
|
||||
logger.info("stop called");
|
||||
const reply = await publishCommand<MediaState>(
|
||||
"media:stop",
|
||||
COMMAND_MEDIA_STOP,
|
||||
{},
|
||||
DEFAULT_COMMAND_TIMEOUT_MS,
|
||||
);
|
||||
@@ -143,8 +154,9 @@ export async function stop(): Promise<MediaState> {
|
||||
* Set volume via Redis command to discord-gateway.
|
||||
*/
|
||||
export async function setVolume(volume: number): Promise<MediaState> {
|
||||
logger.info({ volume }, "setVolume called");
|
||||
const reply = await publishCommand<MediaState>(
|
||||
"media:volume",
|
||||
COMMAND_MEDIA_VOLUME,
|
||||
{ volume },
|
||||
DEFAULT_COMMAND_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import type { PageResult } from "@bete/shared";
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import { getPool } from "../../shared/database/index.js";
|
||||
import { and, desc, eq, inArray, lt, ne, type SQL } from "drizzle-orm";
|
||||
import {
|
||||
bigint as pgBigint,
|
||||
integer as pgInteger,
|
||||
real as pgReal,
|
||||
pgTable,
|
||||
text as pgText,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { getDatabase } from "../../shared/database/index.js";
|
||||
import type {
|
||||
MessageCreate,
|
||||
MessageQuery,
|
||||
@@ -9,6 +17,71 @@ import type {
|
||||
|
||||
const logger = createChildLogger("messages.repository");
|
||||
|
||||
/**
|
||||
* Local table definitions mirroring services/discord-gateway/src/shared/database/schema.ts.
|
||||
* These are query-building references only — schema source of truth remains in discord-gateway.
|
||||
*/
|
||||
const messages = pgTable("messages", {
|
||||
id: pgText("id").primaryKey(),
|
||||
guild_id: pgText("guild_id").notNull(),
|
||||
channel_id: pgText("channel_id").notNull(),
|
||||
thread_id: pgText("thread_id"),
|
||||
user_id: pgText("user_id").notNull(),
|
||||
username: pgText("username").notNull(),
|
||||
avatar_url: pgText("avatar_url"),
|
||||
content: pgText("content").notNull(),
|
||||
edited_content: pgText("edited_content"),
|
||||
created_at: pgBigint("created_at", { mode: "number" }).notNull(),
|
||||
edited_at: pgBigint("edited_at", { mode: "number" }),
|
||||
deleted_at: pgBigint("deleted_at", { mode: "number" }),
|
||||
type: pgText("type", {
|
||||
enum: ["text", "edited", "deleted"],
|
||||
})
|
||||
.notNull()
|
||||
.default("text"),
|
||||
metadata: pgText("metadata"),
|
||||
ai_status: pgText("ai_status", {
|
||||
enum: ["pending", "processing", "clean", "warn", "flagged", "error"],
|
||||
})
|
||||
.notNull()
|
||||
.default("pending"),
|
||||
ai_moderation_flags: pgText("ai_moderation_flags"),
|
||||
ai_moderation_score: pgReal("ai_moderation_score"),
|
||||
ai_analysis: pgText("ai_analysis"),
|
||||
ai_categories: pgText("ai_categories"),
|
||||
ai_severity: pgText("ai_severity", {
|
||||
enum: ["none", "low", "medium", "high", "critical"],
|
||||
}),
|
||||
ai_confidence: pgReal("ai_confidence"),
|
||||
ai_recommended_action: pgText("ai_recommended_action", {
|
||||
enum: ["none", "monitor", "warn", "review", "delete", "escalate"],
|
||||
}),
|
||||
ai_analyzed_at: pgBigint("ai_analyzed_at", { mode: "number" }),
|
||||
ai_error: pgText("ai_error"),
|
||||
});
|
||||
|
||||
const attachments = pgTable("attachments", {
|
||||
id: pgText("id").primaryKey(),
|
||||
message_id: pgText("message_id").notNull(),
|
||||
guild_id: pgText("guild_id").notNull(),
|
||||
channel_id: pgText("channel_id").notNull(),
|
||||
thread_id: pgText("thread_id"),
|
||||
user_id: pgText("user_id").notNull(),
|
||||
filename: pgText("filename").notNull(),
|
||||
size: pgInteger("size").notNull(),
|
||||
type: pgText("type").notNull(),
|
||||
discord_url: pgText("discord_url").notNull(),
|
||||
uploaded_url: pgText("uploaded_url"),
|
||||
upload_status: pgText("upload_status", {
|
||||
enum: ["pending", "uploaded", "failed"],
|
||||
})
|
||||
.notNull()
|
||||
.default("pending"),
|
||||
upload_error: pgText("upload_error"),
|
||||
created_at: pgBigint("created_at", { mode: "number" }).notNull(),
|
||||
uploaded_at: pgBigint("uploaded_at", { mode: "number" }),
|
||||
});
|
||||
|
||||
export interface AttachmentResult {
|
||||
id: string;
|
||||
message_id: string;
|
||||
@@ -60,45 +133,37 @@ export class MessagesRepository {
|
||||
async findMany(
|
||||
query: MessageQuery,
|
||||
): Promise<PageResult<ReturnType<typeof mapMessageRow>>> {
|
||||
const pool = getPool();
|
||||
const db = getDatabase();
|
||||
const limit = query.limit ?? 50;
|
||||
const clauses: string[] = [];
|
||||
const params: (string | number)[] = [];
|
||||
let p = 1;
|
||||
const conditions: SQL[] = [];
|
||||
|
||||
if (query.guildId) {
|
||||
clauses.push(`guild_id = $${p}`);
|
||||
params.push(query.guildId);
|
||||
p++;
|
||||
conditions.push(eq(messages.guild_id, query.guildId));
|
||||
}
|
||||
if (query.channelId) {
|
||||
clauses.push(`channel_id = $${p}`);
|
||||
params.push(query.channelId);
|
||||
p++;
|
||||
conditions.push(eq(messages.channel_id, query.channelId));
|
||||
}
|
||||
if (query.userId) {
|
||||
clauses.push(`user_id = $${p}`);
|
||||
params.push(query.userId);
|
||||
p++;
|
||||
conditions.push(eq(messages.user_id, query.userId));
|
||||
}
|
||||
if (query.status) {
|
||||
clauses.push(`ai_status = $${p}`);
|
||||
params.push(query.status);
|
||||
p++;
|
||||
conditions.push(eq(messages.ai_status, query.status));
|
||||
}
|
||||
if (query.cursor) {
|
||||
clauses.push(`created_at < $${p}`);
|
||||
params.push(Number(query.cursor));
|
||||
p++;
|
||||
conditions.push(lt(messages.created_at, Number(query.cursor)));
|
||||
}
|
||||
|
||||
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
||||
const { rows } = await pool.query(
|
||||
`SELECT * FROM messages ${where} ORDER BY created_at DESC LIMIT $${p}`,
|
||||
[...params, limit + 1],
|
||||
);
|
||||
const where = conditions.length > 0 ? and(...conditions) : undefined;
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(where)
|
||||
.orderBy(desc(messages.created_at))
|
||||
.limit(limit + 1);
|
||||
|
||||
const data = rows.slice(0, limit).map(mapMessageRow);
|
||||
const data = rows
|
||||
.slice(0, limit)
|
||||
.map((r) => mapMessageRow(r as Record<string, unknown>));
|
||||
const nextCursor =
|
||||
rows.length > limit ? String(rows[limit].created_at) : null;
|
||||
|
||||
@@ -107,37 +172,39 @@ export class MessagesRepository {
|
||||
}
|
||||
|
||||
async findById(id: string) {
|
||||
const pool = getPool();
|
||||
const { rows } = await pool.query(`SELECT * FROM messages WHERE id = $1`, [
|
||||
id,
|
||||
]);
|
||||
const db = getDatabase();
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(eq(messages.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
return mapMessageRow(rows[0] as Record<string, unknown>);
|
||||
if (!row) return null;
|
||||
return mapMessageRow(row as Record<string, unknown>);
|
||||
}
|
||||
|
||||
async findByChannel(
|
||||
channelId: string,
|
||||
query: MessageQuery,
|
||||
): Promise<PageResult<ReturnType<typeof mapMessageRow>>> {
|
||||
const pool = getPool();
|
||||
const db = getDatabase();
|
||||
const limit = query.limit ?? 50;
|
||||
const clauses: string[] = ["channel_id = $1"];
|
||||
const params: (string | number)[] = [channelId];
|
||||
let p = 2;
|
||||
const conditions: SQL[] = [eq(messages.channel_id, channelId)];
|
||||
|
||||
if (query.cursor) {
|
||||
clauses.push(`created_at < $${p}`);
|
||||
params.push(Number(query.cursor));
|
||||
p++;
|
||||
conditions.push(lt(messages.created_at, Number(query.cursor)));
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT * FROM messages ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY created_at DESC LIMIT $${p}`,
|
||||
[...params, limit + 1],
|
||||
);
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(messages.created_at))
|
||||
.limit(limit + 1);
|
||||
|
||||
const data = rows.slice(0, limit).map(mapMessageRow);
|
||||
const data = rows
|
||||
.slice(0, limit)
|
||||
.map((r) => mapMessageRow(r as Record<string, unknown>));
|
||||
const nextCursor =
|
||||
rows.length > limit ? String(rows[limit].created_at) : null;
|
||||
|
||||
@@ -145,74 +212,67 @@ export class MessagesRepository {
|
||||
}
|
||||
|
||||
async create(data: MessageCreate) {
|
||||
const pool = getPool();
|
||||
const db = getDatabase();
|
||||
const id = crypto.randomUUID();
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO messages (
|
||||
id, guild_id, channel_id, thread_id, user_id, username, avatar_url,
|
||||
content, edited_content, created_at, edited_at, deleted_at, type,
|
||||
metadata, ai_status
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
||||
RETURNING *`,
|
||||
[
|
||||
id,
|
||||
data.guildId,
|
||||
data.channelId,
|
||||
data.threadId ?? null,
|
||||
data.userId,
|
||||
data.username,
|
||||
data.avatarUrl ?? null,
|
||||
data.content,
|
||||
null,
|
||||
Date.now(),
|
||||
null,
|
||||
null,
|
||||
data.type,
|
||||
null,
|
||||
"pending",
|
||||
],
|
||||
);
|
||||
|
||||
return mapMessageRow(rows[0] as Record<string, unknown>);
|
||||
const [row] = await db
|
||||
.insert(messages)
|
||||
.values({
|
||||
id,
|
||||
guild_id: data.guildId,
|
||||
channel_id: data.channelId,
|
||||
thread_id: data.threadId ?? null,
|
||||
user_id: data.userId,
|
||||
username: data.username,
|
||||
avatar_url: data.avatarUrl ?? null,
|
||||
content: data.content,
|
||||
edited_content: null,
|
||||
created_at: Date.now(),
|
||||
edited_at: null,
|
||||
deleted_at: null,
|
||||
type: data.type ?? "text",
|
||||
metadata: null,
|
||||
ai_status: "pending",
|
||||
})
|
||||
.returning();
|
||||
|
||||
return mapMessageRow(row as Record<string, unknown>);
|
||||
}
|
||||
|
||||
async update(id: string, data: MessageUpdate) {
|
||||
const pool = getPool();
|
||||
const db = getDatabase();
|
||||
|
||||
// Map camelCase schema keys to snake_case DB columns
|
||||
const columnMap: Record<keyof MessageUpdate, string> = {
|
||||
editedContent: "edited_content",
|
||||
aiStatus: "ai_status",
|
||||
aiAnalysis: "ai_analysis",
|
||||
aiCategories: "ai_categories",
|
||||
aiSeverity: "ai_severity",
|
||||
aiConfidence: "ai_confidence",
|
||||
};
|
||||
const setData: Partial<typeof messages.$inferInsert> = {};
|
||||
|
||||
const sets: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let p = 1;
|
||||
|
||||
const keys = Object.keys(data) as (keyof MessageUpdate)[];
|
||||
for (const key of keys) {
|
||||
const val = data[key];
|
||||
if (val !== undefined) {
|
||||
sets.push(`${columnMap[key]} = $${p}`);
|
||||
params.push(val);
|
||||
p++;
|
||||
}
|
||||
if (data.editedContent !== undefined) {
|
||||
setData.edited_content = data.editedContent;
|
||||
}
|
||||
if (data.aiStatus !== undefined) {
|
||||
setData.ai_status = data.aiStatus;
|
||||
}
|
||||
if (data.aiAnalysis !== undefined) {
|
||||
setData.ai_analysis = data.aiAnalysis;
|
||||
}
|
||||
if (data.aiCategories !== undefined) {
|
||||
setData.ai_categories = data.aiCategories;
|
||||
}
|
||||
if (data.aiSeverity !== undefined) {
|
||||
setData.ai_severity = data.aiSeverity;
|
||||
}
|
||||
if (data.aiConfidence !== undefined) {
|
||||
setData.ai_confidence = data.aiConfidence;
|
||||
}
|
||||
|
||||
if (sets.length === 0) return this.findById(id);
|
||||
if (Object.keys(setData).length === 0) return this.findById(id);
|
||||
|
||||
params.push(id);
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE messages SET ${sets.join(", ")} WHERE id = $${p} RETURNING *`,
|
||||
params,
|
||||
);
|
||||
const [row] = await db
|
||||
.update(messages)
|
||||
.set(setData)
|
||||
.where(eq(messages.id, id))
|
||||
.returning();
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
return mapMessageRow(rows[0] as Record<string, unknown>);
|
||||
if (!row) return null;
|
||||
return mapMessageRow(row as Record<string, unknown>);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,36 +287,27 @@ export class MessagesRepository {
|
||||
channelId?: string;
|
||||
messageIds?: string[];
|
||||
}): Promise<number> {
|
||||
const pool = getPool();
|
||||
const clauses: string[] = ["ai_status = 'error'"];
|
||||
const params: (string | number)[] = [];
|
||||
let p = 1;
|
||||
const db = getDatabase();
|
||||
const conditions: SQL[] = [eq(messages.ai_status, "error")];
|
||||
|
||||
if (opts.messageIds && opts.messageIds.length > 0) {
|
||||
const placeholders = opts.messageIds.map((_, i) => `$${p + i}`);
|
||||
clauses.push(`id IN (${placeholders.join(", ")})`);
|
||||
params.push(...opts.messageIds);
|
||||
p += opts.messageIds.length;
|
||||
conditions.push(inArray(messages.id, opts.messageIds));
|
||||
}
|
||||
if (opts.guildId) {
|
||||
clauses.push(`guild_id = $${p}`);
|
||||
params.push(opts.guildId);
|
||||
p++;
|
||||
conditions.push(eq(messages.guild_id, opts.guildId));
|
||||
}
|
||||
if (opts.channelId) {
|
||||
clauses.push(`channel_id = $${p}`);
|
||||
params.push(opts.channelId);
|
||||
p++;
|
||||
conditions.push(eq(messages.channel_id, opts.channelId));
|
||||
}
|
||||
|
||||
const where = clauses.join(" AND ");
|
||||
const { rowCount } = await pool.query(
|
||||
`UPDATE messages SET ai_status = 'pending' WHERE ${where}`,
|
||||
params,
|
||||
);
|
||||
const result = await db
|
||||
.update(messages)
|
||||
.set({ ai_status: "pending" })
|
||||
.where(and(...conditions));
|
||||
|
||||
logger.info({ count: rowCount ?? 0, ...opts }, "Batch reanalyze triggered");
|
||||
return rowCount ?? 0;
|
||||
const count = result.rowCount ?? 0;
|
||||
logger.info({ count, ...opts }, "Batch reanalyze triggered");
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -264,13 +315,11 @@ export class MessagesRepository {
|
||||
* Skips messages already in 'pending' state to avoid write amplification.
|
||||
*/
|
||||
async markForReanalysis(id: string): Promise<void> {
|
||||
const pool = getPool();
|
||||
await pool.query(
|
||||
`UPDATE messages SET ai_status = 'pending'
|
||||
WHERE id = $1 AND ai_status != 'pending'`,
|
||||
[id],
|
||||
);
|
||||
logger.debug({ id }, "Message marked for re-analysis");
|
||||
const db = getDatabase();
|
||||
await db
|
||||
.update(messages)
|
||||
.set({ ai_status: "pending" })
|
||||
.where(and(eq(messages.id, id), ne(messages.ai_status, "pending")));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,65 +330,64 @@ export class MessagesRepository {
|
||||
channelId?: string,
|
||||
limit: number = 20,
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const pool = getPool();
|
||||
const db = getDatabase();
|
||||
const conditions: SQL[] = [
|
||||
inArray(messages.ai_status, ["warn", "flagged"]),
|
||||
];
|
||||
|
||||
if (channelId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, guild_id, channel_id, user_id, username, avatar_url,
|
||||
content, type, created_at, ai_status, ai_severity,
|
||||
ai_confidence, ai_analysis
|
||||
FROM messages
|
||||
WHERE ai_status IN ('warn', 'flagged')
|
||||
AND channel_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2`,
|
||||
[channelId, limit],
|
||||
);
|
||||
return rows;
|
||||
conditions.push(eq(messages.channel_id, channelId));
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, guild_id, channel_id, user_id, username, avatar_url,
|
||||
content, type, created_at, ai_status, ai_severity,
|
||||
ai_confidence, ai_analysis
|
||||
FROM messages
|
||||
WHERE ai_status IN ('warn', 'flagged')
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1`,
|
||||
[limit],
|
||||
);
|
||||
return rows;
|
||||
const rows = await db
|
||||
.select({
|
||||
id: messages.id,
|
||||
guild_id: messages.guild_id,
|
||||
channel_id: messages.channel_id,
|
||||
user_id: messages.user_id,
|
||||
username: messages.username,
|
||||
avatar_url: messages.avatar_url,
|
||||
content: messages.content,
|
||||
type: messages.type,
|
||||
created_at: messages.created_at,
|
||||
ai_status: messages.ai_status,
|
||||
ai_severity: messages.ai_severity,
|
||||
ai_confidence: messages.ai_confidence,
|
||||
ai_analysis: messages.ai_analysis,
|
||||
})
|
||||
.from(messages)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(messages.created_at))
|
||||
.limit(limit);
|
||||
|
||||
return rows as unknown as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<boolean> {
|
||||
const pool = getPool();
|
||||
const { rowCount } = await pool.query(
|
||||
`DELETE FROM messages WHERE id = $1`,
|
||||
[id],
|
||||
);
|
||||
return (rowCount ?? 0) > 0;
|
||||
const db = getDatabase();
|
||||
const result = await db.delete(messages).where(eq(messages.id, id));
|
||||
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
}
|
||||
|
||||
async getAttachmentsByChannel(
|
||||
channelId: string,
|
||||
query: MessageQuery,
|
||||
): Promise<PageResult<AttachmentResult>> {
|
||||
const pool = getPool();
|
||||
const db = getDatabase();
|
||||
const limit = query.limit ?? 50;
|
||||
const clauses: string[] = ["channel_id = $1"];
|
||||
const params: (string | number)[] = [channelId];
|
||||
let p = 2;
|
||||
const conditions: SQL[] = [eq(attachments.channel_id, channelId)];
|
||||
|
||||
if (query.cursor) {
|
||||
clauses.push(`created_at < $${p}`);
|
||||
params.push(Number(query.cursor));
|
||||
p++;
|
||||
conditions.push(lt(attachments.created_at, Number(query.cursor)));
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT * FROM attachments ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY created_at DESC LIMIT $${p}`,
|
||||
[...params, limit + 1],
|
||||
);
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(attachments)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(attachments.created_at))
|
||||
.limit(limit + 1);
|
||||
|
||||
const data = rows.map((r) => ({
|
||||
id: String(r.id ?? ""),
|
||||
|
||||
@@ -6,6 +6,7 @@ const logger = createChildLogger("recordings.service");
|
||||
|
||||
export class RecordingsService {
|
||||
async getRecent(limit = 50) {
|
||||
logger.info({ limit }, "getRecent called");
|
||||
const db = getDatabase();
|
||||
logger.debug({ limit }, "Fetching recent voice recordings");
|
||||
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
import {
|
||||
COMMAND_GUILDS_LIST,
|
||||
COMMAND_GUILDS_TEXT_CHANNELS,
|
||||
COMMAND_VOICE_CHANNELS,
|
||||
COMMAND_VOICE_CONNECT,
|
||||
COMMAND_VOICE_DISCONNECT,
|
||||
VOICE_STATUS_KEY,
|
||||
} from "@bete/shared";
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import { getPool } from "../../shared/database/index.js";
|
||||
import { publishCommand, readRedisStatus } from "../../shared/redis/index.js";
|
||||
@@ -28,7 +36,8 @@ export interface VoiceStatus {
|
||||
* Falls back to database (distinct guild_id from messages) if gateway unreachable.
|
||||
*/
|
||||
export async function getGuilds(): Promise<Guild[]> {
|
||||
const reply = await publishCommand<Guild[]>("guilds:list", {});
|
||||
logger.info("getGuilds called");
|
||||
const reply = await publishCommand<Guild[]>(COMMAND_GUILDS_LIST, {});
|
||||
if (reply?.success && reply.data && reply.data.length > 0) return reply.data;
|
||||
|
||||
// Fallback: Postgres with synthetic names
|
||||
@@ -52,7 +61,8 @@ export async function getGuilds(): Promise<Guild[]> {
|
||||
* Falls back to database if gateway unreachable.
|
||||
*/
|
||||
export async function getTextChannels(guildId: string): Promise<Channel[]> {
|
||||
const reply = await publishCommand<Channel[]>("guilds:text-channels", {
|
||||
logger.info({ guildId }, "getTextChannels called");
|
||||
const reply = await publishCommand<Channel[]>(COMMAND_GUILDS_TEXT_CHANNELS, {
|
||||
guildId,
|
||||
});
|
||||
if (reply?.success && reply.data && reply.data.length > 0) return reply.data;
|
||||
@@ -79,7 +89,10 @@ export async function getTextChannels(guildId: string): Promise<Channel[]> {
|
||||
* Get voice channels — query from discord-gateway via Redis command.
|
||||
*/
|
||||
export async function getVoiceChannels(guildId: string): Promise<Channel[]> {
|
||||
const reply = await publishCommand<Channel[]>("voice:channels", { guildId });
|
||||
logger.info({ guildId }, "getVoiceChannels called");
|
||||
const reply = await publishCommand<Channel[]>(COMMAND_VOICE_CHANNELS, {
|
||||
guildId,
|
||||
});
|
||||
return reply?.success && reply.data ? reply.data : [];
|
||||
}
|
||||
|
||||
@@ -87,7 +100,8 @@ export async function getVoiceChannels(guildId: string): Promise<Channel[]> {
|
||||
* Get current voice connection status from Redis cache set by discord-gateway.
|
||||
*/
|
||||
export async function getVoiceStatus(): Promise<VoiceStatus> {
|
||||
const cached = await readRedisStatus("voice:status");
|
||||
logger.debug("getVoiceStatus called");
|
||||
const cached = await readRedisStatus(VOICE_STATUS_KEY);
|
||||
if (cached) return cached as unknown as VoiceStatus;
|
||||
return {
|
||||
connected: false,
|
||||
@@ -104,14 +118,15 @@ export async function connectVoice(
|
||||
guildId: string,
|
||||
channelId: string,
|
||||
): Promise<VoiceStatus> {
|
||||
const reply = await publishCommand<VoiceStatus>("voice:connect", {
|
||||
logger.info({ guildId, channelId }, "connectVoice called");
|
||||
const reply = await publishCommand<VoiceStatus>(COMMAND_VOICE_CONNECT, {
|
||||
guildId,
|
||||
channelId,
|
||||
});
|
||||
if (reply?.success && reply.data) return reply.data;
|
||||
|
||||
// Fallback: read from Redis status key
|
||||
const cached = await readRedisStatus("voice:status");
|
||||
const cached = await readRedisStatus(VOICE_STATUS_KEY);
|
||||
return (
|
||||
(cached as unknown as VoiceStatus) ?? {
|
||||
connected: false,
|
||||
@@ -126,10 +141,11 @@ export async function connectVoice(
|
||||
* Disconnect from voice via Redis command to discord-gateway.
|
||||
*/
|
||||
export async function disconnectVoice(): Promise<VoiceStatus> {
|
||||
const reply = await publishCommand<VoiceStatus>("voice:disconnect", {});
|
||||
logger.info("disconnectVoice called");
|
||||
const reply = await publishCommand<VoiceStatus>(COMMAND_VOICE_DISCONNECT, {});
|
||||
if (reply?.success && reply.data) return reply.data;
|
||||
|
||||
const cached = await readRedisStatus("voice:status");
|
||||
const cached = await readRedisStatus(VOICE_STATUS_KEY);
|
||||
return (
|
||||
(cached as unknown as VoiceStatus) ?? {
|
||||
connected: false,
|
||||
|
||||
@@ -1,28 +1,16 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
BACKEND_COMMAND,
|
||||
BACKEND_COMMAND_REPLY_PREFIX,
|
||||
type CommandMessage,
|
||||
type CommandReply,
|
||||
} from "@bete/shared";
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import Redis from "ioredis";
|
||||
import { config } from "../config/index.js";
|
||||
|
||||
const logger = createChildLogger("redis.command-channel");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface CommandMessage {
|
||||
id: string;
|
||||
type: string;
|
||||
payload: Record<string, unknown>;
|
||||
replyChannel: string;
|
||||
}
|
||||
|
||||
export interface CommandReply<T = unknown> {
|
||||
id: string;
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal Redis clients (singletons)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -74,7 +62,7 @@ export async function publishCommand<T = unknown>(
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const replyChannel = `backend:command:reply:${id}`;
|
||||
const replyChannel = `${BACKEND_COMMAND_REPLY_PREFIX}${id}`;
|
||||
const command: CommandMessage = {
|
||||
id,
|
||||
type: commandType,
|
||||
@@ -125,7 +113,7 @@ export async function publishCommand<T = unknown>(
|
||||
.subscribe(replyChannel)
|
||||
.then(() => {
|
||||
pub
|
||||
.publish("backend:command", JSON.stringify(command))
|
||||
.publish(BACKEND_COMMAND, JSON.stringify(command))
|
||||
.then(() => {
|
||||
logger.debug({ id, commandType }, "Command published");
|
||||
})
|
||||
@@ -175,7 +163,7 @@ export async function publishCommandNoReply(
|
||||
replyChannel: "",
|
||||
};
|
||||
|
||||
await getPublisher().publish("backend:command", JSON.stringify(command));
|
||||
await getPublisher().publish(BACKEND_COMMAND, JSON.stringify(command));
|
||||
logger.debug({ id, commandType }, "Command published (no reply)");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
import {
|
||||
DISCORD_ANALYSIS_QUEUE_STATUS,
|
||||
DISCORD_ATTACHMENT_CREATED,
|
||||
DISCORD_ATTACHMENT_UPLOADED,
|
||||
DISCORD_MESSAGE_ANALYZED,
|
||||
DISCORD_MESSAGE_CREATED,
|
||||
DISCORD_MESSAGE_DELETED,
|
||||
DISCORD_MESSAGE_UPDATED,
|
||||
DISCORD_VOICE_ACTIVE_USER,
|
||||
DISCORD_VOICE_PCM,
|
||||
DISCORD_VOICE_STARTED,
|
||||
DISCORD_VOICE_STOPPED,
|
||||
DISCORD_VOICE_UPLOADED,
|
||||
} from "@bete/shared";
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import Redis from "ioredis";
|
||||
import { config } from "../shared/config/index.js";
|
||||
@@ -11,21 +25,21 @@ interface ChannelMapping {
|
||||
}
|
||||
|
||||
const SUBSCRIPTIONS: ChannelMapping[] = [
|
||||
{ channel: "discord:message:created", eventType: "message_created" },
|
||||
{ channel: "discord:message:updated", eventType: "message_updated" },
|
||||
{ channel: "discord:message:deleted", eventType: "message_deleted" },
|
||||
{ channel: "discord:message:analyzed", eventType: "message_analyzed" },
|
||||
{ channel: "discord:attachment:created", eventType: "attachment_created" },
|
||||
{ channel: "discord:attachment:uploaded", eventType: "attachment_uploaded" },
|
||||
{ channel: "discord:voice:started", eventType: "voice_recording_started" },
|
||||
{ channel: "discord:voice:stopped", eventType: "voice_recording_stopped" },
|
||||
{ channel: "discord:voice:uploaded", eventType: "voice_recording_uploaded" },
|
||||
{ channel: DISCORD_MESSAGE_CREATED, eventType: "message_created" },
|
||||
{ channel: DISCORD_MESSAGE_UPDATED, eventType: "message_updated" },
|
||||
{ channel: DISCORD_MESSAGE_DELETED, eventType: "message_deleted" },
|
||||
{ channel: DISCORD_MESSAGE_ANALYZED, eventType: "message_analyzed" },
|
||||
{ channel: DISCORD_ATTACHMENT_CREATED, eventType: "attachment_created" },
|
||||
{ channel: DISCORD_ATTACHMENT_UPLOADED, eventType: "attachment_uploaded" },
|
||||
{ channel: DISCORD_VOICE_STARTED, eventType: "voice_recording_started" },
|
||||
{ channel: DISCORD_VOICE_STOPPED, eventType: "voice_recording_stopped" },
|
||||
{ channel: DISCORD_VOICE_UPLOADED, eventType: "voice_recording_uploaded" },
|
||||
{
|
||||
channel: "discord:analysis:queue_status",
|
||||
channel: DISCORD_ANALYSIS_QUEUE_STATUS,
|
||||
eventType: "analysis_queue_status",
|
||||
},
|
||||
{ channel: "discord:voice:active_user", eventType: "voice_active_user" },
|
||||
{ channel: "discord:voice:pcm", eventType: "voice_pcm_data" },
|
||||
{ channel: DISCORD_VOICE_ACTIVE_USER, eventType: "voice_active_user" },
|
||||
{ channel: DISCORD_VOICE_PCM, eventType: "voice_pcm_data" },
|
||||
];
|
||||
|
||||
let subscriber: Redis | null = null;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Server } from "node:http";
|
||||
import { BACKEND_COMMAND, BACKEND_VOICE_TRANSMIT } from "@bete/shared";
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
import { setBroadcastFunctions } from "./broadcast.js";
|
||||
@@ -92,7 +93,7 @@ export function createWebSocketServer(server: Server): WebSocketServer {
|
||||
const publisher = getCommandPublisher();
|
||||
publisher
|
||||
.publish(
|
||||
"backend:voice:transmit",
|
||||
BACKEND_VOICE_TRANSMIT,
|
||||
JSON.stringify({
|
||||
type: "pcm",
|
||||
buffer: message.buffer,
|
||||
@@ -114,7 +115,7 @@ export function createWebSocketServer(server: Server): WebSocketServer {
|
||||
const commandId = `cmd-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||
publisher
|
||||
.publish(
|
||||
"backend:command",
|
||||
BACKEND_COMMAND,
|
||||
JSON.stringify({
|
||||
id: commandId,
|
||||
type: message.command,
|
||||
|
||||
Reference in New Issue
Block a user