fix(moderation): remove manual reanalyze triggers — auto-recovery only
Manual per-message and batch reanalyze buttons/endpoints let anyone re-queue arbitrary messages for LLM analysis, burning AI credits on spam. Removed: - FE: Reanalyze buttons in message list, search panel, and messages page - FE: useReanalyze/useReanalyzeBatch hooks + messagesApi methods - BE: POST /api/messages/:id/reanalyze and /reanalyze-batch endpoints - BE: markForReanalysis/reanalyzeErrorBatch service+repository methods Recovery of failed messages is fully automatic: the discord-gateway startPendingAIAnalysisWorker retries 'pending' (batch path) and 'error/analysis_incomplete' (individual path) messages on AI_ANALYSIS_RECOVERY_INTERVAL_MS.
This commit is contained in:
@@ -6,7 +6,6 @@ import {
|
||||
isNull,
|
||||
like,
|
||||
lt,
|
||||
ne,
|
||||
notInArray,
|
||||
or,
|
||||
type SQL,
|
||||
@@ -223,58 +222,6 @@ export class MessagesRepository {
|
||||
return mapMessageRow(row as Record<string, unknown>);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk-reset ai_status from 'error' to 'pending' so the DG recovery worker
|
||||
* picks them up on its next poll cycle.
|
||||
*
|
||||
* Accepts optional scope filters (guildId, channelId) or a list of explicit
|
||||
* message IDs. Returns the count of rows that were actually updated.
|
||||
*/
|
||||
async reanalyzeErrorBatch(opts: {
|
||||
guildId?: string;
|
||||
channelId?: string;
|
||||
messageIds?: string[];
|
||||
}): Promise<number> {
|
||||
const db = getDatabase();
|
||||
const conditions: SQL[] = [eq(pgMessagesTable.ai_status, "error")];
|
||||
|
||||
if (opts.messageIds && opts.messageIds.length > 0) {
|
||||
conditions.push(inArray(pgMessagesTable.id, opts.messageIds));
|
||||
}
|
||||
if (opts.guildId) {
|
||||
conditions.push(eq(pgMessagesTable.guild_id, opts.guildId));
|
||||
}
|
||||
if (opts.channelId) {
|
||||
conditions.push(eq(pgMessagesTable.channel_id, opts.channelId));
|
||||
}
|
||||
|
||||
const result = await db
|
||||
.update(pgMessagesTable)
|
||||
.set({ ai_status: "pending" })
|
||||
.where(and(...conditions));
|
||||
|
||||
const count = result.rowCount ?? 0;
|
||||
logger.info({ count, ...opts }, "Batch reanalyze triggered");
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a single message for re-analysis by resetting ai_status to 'pending'.
|
||||
* Skips messages already in 'pending' state to avoid write amplification.
|
||||
*/
|
||||
async markForReanalysis(id: string): Promise<void> {
|
||||
const db = getDatabase();
|
||||
await db
|
||||
.update(pgMessagesTable)
|
||||
.set({ ai_status: "pending" })
|
||||
.where(
|
||||
and(
|
||||
eq(pgMessagesTable.id, id),
|
||||
ne(pgMessagesTable.ai_status, "pending"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve messages flagged for review (ai_status IN ('warn', 'flagged')).
|
||||
* Optionally filtered by channelId, with configurable limit.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Request, Response, Router } from "express";
|
||||
import express from "express";
|
||||
import { createChildLogger } from "@/shared/logger/index";
|
||||
import { asyncHandler, validateBody } from "../../shared/middlewares/index.js";
|
||||
import { asyncHandler } from "../../shared/middlewares/index.js";
|
||||
import {
|
||||
handleGetAttachmentsByChannel,
|
||||
handleGetImageMessages,
|
||||
@@ -9,27 +9,10 @@ import {
|
||||
handleGetMessagesByChannel,
|
||||
handleListMessages,
|
||||
} from "./messages.controller.js";
|
||||
import { reanalyzeBatchSchema } from "./messages.schema.js";
|
||||
import { messagesService } from "./messages.service.js";
|
||||
|
||||
const logger = createChildLogger("messages.routes");
|
||||
|
||||
/**
|
||||
* Per-message in-flight guard for the single reanalyze endpoint.
|
||||
* Prevents concurrent spam-clicks from issuing duplicate UPDATE + recovery
|
||||
* worker triggers for the same message.
|
||||
*/
|
||||
const reanalyzeInFlight = new Set<string>();
|
||||
|
||||
/**
|
||||
* Per-scope in-flight guard for the batch reanalyze endpoint.
|
||||
* Scope key = "guildId:channelId" (empty string used for undefined parts).
|
||||
* Two concurrent batch-reanalyze requests for the same scope are rejected
|
||||
* with 409 so the recovery worker is not triggered multiple times for the
|
||||
* same set of error messages.
|
||||
*/
|
||||
const reanalyzeBatchInFlight = new Set<string>();
|
||||
|
||||
export function createMessagesRouter(): Router {
|
||||
const router = express.Router();
|
||||
|
||||
@@ -51,74 +34,6 @@ export function createMessagesRouter(): Router {
|
||||
// (uses /detail/ prefix to avoid collision with :channelId route above)
|
||||
router.get("/messages/detail/:id", handleGetMessageById);
|
||||
|
||||
// POST /api/messages/reanalyze-batch — Bulk retry all errored messages
|
||||
// MUST be registered BEFORE /messages/:id/reanalyze so "reanalyze-batch"
|
||||
// is not captured as an :id param.
|
||||
router.post(
|
||||
"/messages/reanalyze-batch",
|
||||
validateBody(reanalyzeBatchSchema),
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const { guildId, channelId, messageIds } = req.body as {
|
||||
guildId?: string;
|
||||
channelId?: string;
|
||||
messageIds?: string[];
|
||||
};
|
||||
|
||||
// Idempotency guard: one concurrent batch-reanalyze per scope.
|
||||
// Prevents two admin sessions clicking simultaneously from each
|
||||
// triggering the recovery worker for the same set of messages.
|
||||
const scopeKey = `${guildId ?? ""}:${channelId ?? ""}`;
|
||||
if (reanalyzeBatchInFlight.has(scopeKey)) {
|
||||
res
|
||||
.status(409)
|
||||
.json({ error: "REANALYZE_BATCH_IN_PROGRESS", scope: scopeKey });
|
||||
return;
|
||||
}
|
||||
|
||||
reanalyzeBatchInFlight.add(scopeKey);
|
||||
let count = 0;
|
||||
try {
|
||||
count = await messagesService.reanalyzeErrorBatch({
|
||||
guildId,
|
||||
channelId,
|
||||
messageIds,
|
||||
});
|
||||
} finally {
|
||||
reanalyzeBatchInFlight.delete(scopeKey);
|
||||
}
|
||||
|
||||
logger.info({ count, guildId, channelId }, "Batch reanalyze completed");
|
||||
res.status(200).json({ ok: true, count });
|
||||
}),
|
||||
);
|
||||
|
||||
// POST /api/messages/:id/reanalyze - Mark single message for re-analysis
|
||||
router.post(
|
||||
"/messages/:id/reanalyze",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const id = String(req.params.id ?? "");
|
||||
if (!id) {
|
||||
res.status(400).json({ error: "MISSING_ID" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Idempotency guard: reject concurrent duplicate requests for the same ID.
|
||||
if (reanalyzeInFlight.has(id)) {
|
||||
res.status(409).json({ error: "REANALYZE_IN_PROGRESS", messageId: id });
|
||||
return;
|
||||
}
|
||||
|
||||
reanalyzeInFlight.add(id);
|
||||
try {
|
||||
await messagesService.markForReanalysis(id);
|
||||
} finally {
|
||||
reanalyzeInFlight.delete(id);
|
||||
}
|
||||
|
||||
res.status(200).json({ ok: true });
|
||||
}),
|
||||
);
|
||||
|
||||
// GET /api/review - Get flagged/warned messages for review
|
||||
router.get(
|
||||
"/review",
|
||||
|
||||
@@ -38,13 +38,6 @@ export const messageUpdateSchema = z.object({
|
||||
aiConfidence: z.number().optional(),
|
||||
});
|
||||
|
||||
export const reanalyzeBatchSchema = z.object({
|
||||
guildId: z.string().optional(),
|
||||
channelId: z.string().optional(),
|
||||
messageIds: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
export type MessageQuery = z.infer<typeof messageQuerySchema>;
|
||||
export type MessageCreate = z.infer<typeof messageCreateSchema>;
|
||||
export type MessageUpdate = z.infer<typeof messageUpdateSchema>;
|
||||
export type ReanalyzeBatchInput = z.infer<typeof reanalyzeBatchSchema>;
|
||||
|
||||
@@ -58,15 +58,6 @@ export class MessagesService {
|
||||
return messagesRepository.getImageMessages(guildId, limit);
|
||||
}
|
||||
|
||||
async markForReanalysis(id: string): Promise<void> {
|
||||
if (!id) {
|
||||
throw new ValidationError("message ID is required");
|
||||
}
|
||||
|
||||
logger.debug({ id }, "Marking message for re-analysis");
|
||||
await messagesRepository.markForReanalysis(id);
|
||||
}
|
||||
|
||||
async getReviewMessages(
|
||||
channelId?: string,
|
||||
limit?: number,
|
||||
@@ -74,25 +65,6 @@ export class MessagesService {
|
||||
logger.debug({ channelId, limit }, "Getting review messages");
|
||||
return messagesRepository.getReviewMessages(channelId, limit);
|
||||
}
|
||||
|
||||
async reanalyzeErrorBatch(opts: {
|
||||
guildId?: string;
|
||||
channelId?: string;
|
||||
messageIds?: string[];
|
||||
}) {
|
||||
if (
|
||||
!opts.guildId &&
|
||||
!opts.channelId &&
|
||||
(!opts.messageIds || opts.messageIds.length === 0)
|
||||
) {
|
||||
throw new ValidationError(
|
||||
"At least one of guildId, channelId, or messageIds[] is required",
|
||||
);
|
||||
}
|
||||
|
||||
logger.info(opts, "Batch reanalyzing errored messages");
|
||||
return messagesRepository.reanalyzeErrorBatch(opts);
|
||||
}
|
||||
}
|
||||
|
||||
export const messagesService = new MessagesService();
|
||||
|
||||
Reference in New Issue
Block a user