File size: 11,941 Bytes
c4ae742 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | // apps/api/src/queue/store.ts
// Storage contract plus the SQLite implementation used for local/single-node
// development. Multi-instance deployments use PostgresStore from
// ./postgres-store.js via store-factory.ts.
import Database from "better-sqlite3";
import { mkdirSync, existsSync } from "node:fs";
import { dirname } from "node:path";
import { randomUUID } from "node:crypto";
export type Awaitable<T> = T | Promise<T>;
export type JobStatus = "pending" | "running" | "completed" | "cancelled";
export type ItemStatus =
| "queued"
| "running"
| "judging"
| "completed"
| "failed"
| "stopped";
export type DetectedMode = "api" | "mcp";
export interface JobRow {
id: string;
status: JobStatus;
options_snapshot: string; // JSON, never contains apiKey
created_at: number;
updated_at: number;
}
export interface ItemRow {
id: string;
job_id: string;
ord: number;
filename: string;
upload_path: string;
detected_mode: DetectedMode;
status: ItemStatus;
evidence_path: string | null;
task_package_path: string | null;
judge_result_path: string | null;
export_zip_path: string | null;
error_preview: string | null;
error_details_path: string | null;
attempt_count: number;
last_stage: string | null;
created_at: number;
updated_at: number;
}
export interface SetItemStatusMeta {
lastStage?: string | null;
errorDetailsPath?: string | null;
}
export interface Store {
close(): Awaitable<void>;
createJob(optionsSnapshot: object): Awaitable<JobRow>;
getJob(id: string): Awaitable<JobRow | null>;
setJobStatus(id: string, status: JobStatus): Awaitable<void>;
updateJobOptions(id: string, optionsSnapshot: object): Awaitable<void>;
listResumableJobs(): Awaitable<JobRow[]>;
recoverInterruptedJob(id: string): Awaitable<void>;
createItem(input: {
jobId: string;
ord: number;
filename: string;
uploadPath: string;
detectedMode: DetectedMode;
}): Awaitable<ItemRow>;
getItem(id: string): Awaitable<ItemRow | null>;
listItemsByJob(jobId: string): Awaitable<ItemRow[]>;
setItemStatus(
id: string,
status: ItemStatus,
errorPreview?: string,
meta?: SetItemStatusMeta,
): Awaitable<void>;
setItemPaths(
id: string,
paths: Partial<{
evidencePath: string;
taskPackagePath: string;
judgeResultPath: string;
exportZipPath: string;
}>,
): Awaitable<void>;
takeNextQueuedItem(jobId: string): Awaitable<ItemRow | null>;
resetItemForRetry(id: string): Awaitable<void>;
}
const SCHEMA_SQL = `
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
status TEXT NOT NULL,
options_snapshot TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
ord INTEGER NOT NULL,
filename TEXT NOT NULL,
upload_path TEXT NOT NULL,
detected_mode TEXT NOT NULL,
status TEXT NOT NULL,
evidence_path TEXT,
task_package_path TEXT,
judge_result_path TEXT,
export_zip_path TEXT,
error_preview TEXT,
error_details_path TEXT,
attempt_count INTEGER NOT NULL DEFAULT 0,
last_stage TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_items_job_ord ON items(job_id, ord);
CREATE INDEX IF NOT EXISTS idx_items_status ON items(status);
CREATE INDEX IF NOT EXISTS idx_items_job_status_ord ON items(job_id, status, ord);
`;
const ERROR_PREVIEW_MAX = 2 * 1024;
export function nowMs() {
return Date.now();
}
export function truncateError(s: string | null | undefined): string | null {
if (!s) return null;
return s.length > ERROR_PREVIEW_MAX
? s.slice(0, ERROR_PREVIEW_MAX) + "...(truncated)"
: s;
}
function hasColumn(db: Database.Database, table: string, column: string): boolean {
const rows = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name?: string }>;
return rows.some((row) => row.name === column);
}
function ensureSqliteColumns(db: Database.Database): void {
const additions: Array<[string, string]> = [
["error_details_path", "ALTER TABLE items ADD COLUMN error_details_path TEXT"],
["attempt_count", "ALTER TABLE items ADD COLUMN attempt_count INTEGER NOT NULL DEFAULT 0"],
["last_stage", "ALTER TABLE items ADD COLUMN last_stage TEXT"],
];
additions.forEach(([column, sql]) => {
if (!hasColumn(db, "items", column)) db.exec(sql);
});
}
function normalizeItemRow(row: ItemRow): ItemRow {
return {
...row,
attempt_count: Number(row.attempt_count || 0),
error_details_path: row.error_details_path ?? null,
last_stage: row.last_stage ?? null,
};
}
export class SqliteStore implements Store {
private db: Database.Database;
constructor(sqlitePath: string) {
if (!existsSync(dirname(sqlitePath))) {
mkdirSync(dirname(sqlitePath), { recursive: true });
}
this.db = new Database(sqlitePath);
this.db.exec(SCHEMA_SQL);
ensureSqliteColumns(this.db);
}
close(): void {
this.db.close();
}
// jobs
createJob(optionsSnapshot: object): JobRow {
const id = randomUUID();
const t = nowMs();
const job: JobRow = {
id,
status: "pending",
options_snapshot: JSON.stringify(optionsSnapshot),
created_at: t,
updated_at: t,
};
this.db
.prepare(
"INSERT INTO jobs (id, status, options_snapshot, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
)
.run(job.id, job.status, job.options_snapshot, job.created_at, job.updated_at);
return job;
}
getJob(id: string): JobRow | null {
const row = this.db.prepare("SELECT * FROM jobs WHERE id = ?").get(id) as JobRow | undefined;
return row ?? null;
}
setJobStatus(id: string, status: JobStatus): void {
this.db
.prepare("UPDATE jobs SET status = ?, updated_at = ? WHERE id = ?")
.run(status, nowMs(), id);
}
updateJobOptions(id: string, optionsSnapshot: object): void {
this.db
.prepare("UPDATE jobs SET options_snapshot = ?, updated_at = ? WHERE id = ?")
.run(JSON.stringify(optionsSnapshot), nowMs(), id);
}
listResumableJobs(): JobRow[] {
return this.db
.prepare("SELECT * FROM jobs WHERE status = 'running' ORDER BY created_at")
.all() as JobRow[];
}
recoverInterruptedJob(id: string): void {
const t = nowMs();
const tx = this.db.transaction((jobId: string) => {
this.db
.prepare(
`UPDATE items
SET status = 'queued',
error_preview = NULL,
last_stage = 'recovered',
updated_at = ?
WHERE job_id = ? AND status IN ('running', 'judging')`,
)
.run(t, jobId);
this.db
.prepare("UPDATE jobs SET status = 'running', updated_at = ? WHERE id = ?")
.run(t, jobId);
});
tx(id);
}
// items
createItem(input: {
jobId: string;
ord: number;
filename: string;
uploadPath: string;
detectedMode: DetectedMode;
}): ItemRow {
const id = randomUUID();
const t = nowMs();
const row: ItemRow = {
id,
job_id: input.jobId,
ord: input.ord,
filename: input.filename,
upload_path: input.uploadPath,
detected_mode: input.detectedMode,
status: "queued",
evidence_path: null,
task_package_path: null,
judge_result_path: null,
export_zip_path: null,
error_preview: null,
error_details_path: null,
attempt_count: 0,
last_stage: null,
created_at: t,
updated_at: t,
};
this.db
.prepare(
`INSERT INTO items
(id, job_id, ord, filename, upload_path, detected_mode, status,
evidence_path, task_package_path, judge_result_path, export_zip_path,
error_preview, error_details_path, attempt_count, last_stage, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
row.id,
row.job_id,
row.ord,
row.filename,
row.upload_path,
row.detected_mode,
row.status,
row.evidence_path,
row.task_package_path,
row.judge_result_path,
row.export_zip_path,
row.error_preview,
row.error_details_path,
row.attempt_count,
row.last_stage,
row.created_at,
row.updated_at,
);
return row;
}
getItem(id: string): ItemRow | null {
const row = this.db.prepare("SELECT * FROM items WHERE id = ?").get(id) as ItemRow | undefined;
return row ? normalizeItemRow(row) : null;
}
listItemsByJob(jobId: string): ItemRow[] {
return (
this.db
.prepare("SELECT * FROM items WHERE job_id = ? ORDER BY ord ASC")
.all(jobId) as ItemRow[]
).map(normalizeItemRow);
}
setItemStatus(
id: string,
status: ItemStatus,
errorPreview?: string,
meta: SetItemStatusMeta = {},
): void {
this.db
.prepare(
`UPDATE items
SET status = ?,
error_preview = ?,
last_stage = COALESCE(?, last_stage),
error_details_path = COALESCE(?, error_details_path),
updated_at = ?
WHERE id = ?`,
)
.run(
status,
truncateError(errorPreview),
meta.lastStage ?? null,
meta.errorDetailsPath ?? null,
nowMs(),
id,
);
}
setItemPaths(
id: string,
paths: Partial<{
evidencePath: string;
taskPackagePath: string;
judgeResultPath: string;
exportZipPath: string;
}>,
): void {
const fields: string[] = [];
const values: unknown[] = [];
if (paths.evidencePath !== undefined) {
fields.push("evidence_path = ?");
values.push(paths.evidencePath);
}
if (paths.taskPackagePath !== undefined) {
fields.push("task_package_path = ?");
values.push(paths.taskPackagePath);
}
if (paths.judgeResultPath !== undefined) {
fields.push("judge_result_path = ?");
values.push(paths.judgeResultPath);
}
if (paths.exportZipPath !== undefined) {
fields.push("export_zip_path = ?");
values.push(paths.exportZipPath);
}
if (!fields.length) return;
fields.push("updated_at = ?");
values.push(nowMs());
values.push(id);
this.db.prepare(`UPDATE items SET ${fields.join(", ")} WHERE id = ?`).run(...values);
}
takeNextQueuedItem(jobId: string): ItemRow | null {
const tx = this.db.transaction((id: string) => {
const row = this.db
.prepare(
"SELECT * FROM items WHERE job_id = ? AND status = 'queued' ORDER BY ord ASC LIMIT 1",
)
.get(id) as ItemRow | undefined;
if (!row) return null;
const t = nowMs();
this.db
.prepare(
`UPDATE items
SET status = 'running',
attempt_count = attempt_count + 1,
error_preview = NULL,
last_stage = 'running',
updated_at = ?
WHERE id = ?`,
)
.run(t, row.id);
return normalizeItemRow({
...row,
status: "running" as const,
attempt_count: Number(row.attempt_count || 0) + 1,
last_stage: "running",
updated_at: t,
});
});
return tx(jobId);
}
resetItemForRetry(id: string): void {
this.db
.prepare(
`UPDATE items
SET status = 'queued',
error_preview = NULL,
error_details_path = NULL,
attempt_count = 0,
last_stage = NULL,
evidence_path = NULL,
task_package_path = NULL,
judge_result_path = NULL,
export_zip_path = NULL,
updated_at = ?
WHERE id = ?`,
)
.run(nowMs(), id);
}
}
|