PEP-62: write chat cursors only when they move

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 19:21:23 +05:00
parent 5cfc2cb269
commit b4b31ea88c

View File

@ -326,7 +326,9 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
};
// events
let cursor = (await getSetting<number>(db, CURSOR_EVENTS)) ?? (await initialCursor(db, events, now));
// Cursors are written only when they move: a no-op sync doesn't wake the other processes.
const savedEvents = await getSetting<number>(db, CURSOR_EVENTS);
let cursor = savedEvents ?? (await initialCursor(db, events, now));
for (;;) {
// Read the newest id first: a row committed after it is picked up by the next call.
const [top] = await db.select({ max: sql<number | null>`max(${events.id})` }).from(events);
@ -355,10 +357,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo);
if (rows.length < BATCH) break;
}
await setSetting(db, CURSOR_EVENTS, cursor);
if (cursor !== savedEvents) await setSetting(db, CURSOR_EVENTS, cursor);
// questions
let qCursor = (await getSetting<number>(db, CURSOR_QUESTIONS)) ?? (await initialCursor(db, questions, now));
const savedQuestions = await getSetting<number>(db, CURSOR_QUESTIONS);
let qCursor = savedQuestions ?? (await initialCursor(db, questions, now));
for (;;) {
const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH);
for (const q of rows) {
@ -379,10 +382,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
}
if (rows.length < BATCH) break;
}
await setSetting(db, CURSOR_QUESTIONS, qCursor);
if (qCursor !== savedQuestions) await setSetting(db, CURSOR_QUESTIONS, qCursor);
// releases and incidents: one message per (id, status); the window overlaps a little.
const since = new Date(((await getSetting<number>(db, CURSOR_OBJECTS)) ?? now.getTime() - DAY) - 60_000);
const savedObjects = await getSetting<number>(db, CURSOR_OBJECTS);
const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000);
for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
await add({
@ -407,7 +411,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
dedupeKey: `incident:${i.id}:${i.status}`,
});
}
await setSetting(db, CURSOR_OBJECTS, now.getTime());
// Moved at most every 30 s (the window overlaps by a minute, so nothing is lost).
if (savedObjects == null || now.getTime() - savedObjects >= 30_000) await setSetting(db, CURSOR_OBJECTS, now.getTime());
if (added) await notify(db, { type: "chat_message", messageId: 0 });
return added;
}