Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 | 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 163x 167x 113x 25x 29x 44x 44x 70x 70x 43x 43x 60x 60x 598x 87x 505x 199x 199x 199x 30x 30x 30x 169x 169x 30x 40x 40x 40x 1x 1x 39x 39x 39x 39x 93x 4x 33x 95x 95x 95x 8x 8x 87x 87x 85x 87x 87x 87x 87x 87x 163x 162x 97x 12x 12x 12x 11x 85x 85x 85x 85x 163x 163x 108x 108x 6x 7x 7x 10x 7x 7x 7x 10x 103x 102x 102x 102x 102x 240x 238x 238x 102x 102x 102x 238x 238x 8x 102x 102x 230x 230x 97x 97x 97x 230x 4x 92x 53x 53x 53x 53x 53x 181x 53x 53x 181x 181x 9x 9x 172x 181x 181x 53x 53x 39x 229x 39x 1x 1x 38x 10x 10x 28x 1x 27x 19x 8x 8x 8x 8x 8x 8x 11x 11x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 2x 2x 2x 1x 1x 1x 12x 12x 10x 10x 12x 1x 1x 1x 1x 1x 1x 27x 27x 6x 6x 6x 6x 31x 14x 14x 6x 25x 25x 25x 19x 3x 3x 16x 16x 25x 2x 2x 6x 19x 6x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x | "use client";
// decisionFlusher — ONE module-level drain engine per realm; the ONLY code
// that drains queued decisions/dispositions (spec §3.2, F12); `directSubmit`
// sends one un-queued entry when storage is unavailable (F18).
//
// Single-flight is promise-based, not skip-based: a caller that finds a drain
// in flight for the same queue awaits the SAME promise. A drain resolves only
// when every entry visible at call time (plus same-key entries enqueued
// mid-drain — the loop re-reads storage until empty) is acked, quarantined, or
// the failure taxonomy says stop.
//
// Cross-tab exclusion: every drain iteration — the re-read, the request, and
// the ack-removal/quarantine mutations — runs inside
// withWebLock('adored.flush.v1.{curatorId}.{sessionId}'), so one tab's
// ack-removal can never clobber another tab's concurrent enqueue (enqueue
// stays synchronous and lock-free; removal re-reads under the lock). Backoff
// waits happen OUTSIDE the lock so a stalled tab never starves the others.
//
// Notices are sticky per tab and read as one snapshot (subscribeNoticeSet/getNoticeSet — the only
// notice API; purses-w7ss.30): the engine keeps the current line per kind per collection, and a
// surface reads the set whenever it renders. An entry stands until dismissed (dismissNotice) or
// resolved (a 2xx clears auth_required); a reload clears them all.
import { useEffect } from "react";
import { withWebLock } from "@/lib/web-lock";
import { BatchEntrySchema, type BatchResult } from "@/lib/decision-batch-schema";
import {
PENDING_CHANGED_EVENT,
deleteQueue,
pendingStorageKey,
quarantineEntries,
readQueue,
readQueueCollectionId,
removeEntries,
type PendingEntry,
type QueueKey,
} from "./decisionQueue";
export interface DrainOptions {
recovery?: boolean;
keepalive?: boolean;
}
export type AckOutcome =
| { status: "created" | "duplicate" }
| { status: "rejected"; reason?: string };
// collectionId: the collection whose queue raised it (the envelope's stamp), so a surface shows only
// its own collection's lines (purses-w7ss.31); undefined only for a queue that predates stamping.
// Two kinds are global and carry none: auth_required (signing in is per person) and
// closed_session_discarded (answers that are gone must never wait for a page the person may not open).
export type FlushNotice =
| { kind: "rejected_unknown_item"; count: number; collectionId: string | undefined }
| { kind: "quarantined"; count: number; collectionId: string | undefined }
| { kind: "session_conflict"; sessionId: string; collectionId: string | undefined } // mid-round batch 409; names its sort so it never holds another
| { kind: "closed_session_discarded" } // recovery batch 409: a closed sort's waiting answers were let go
| { kind: "disposition_superseded"; collectionId: string | undefined } // disposition POST 409 (PreferenceExistsError)
| { kind: "auth_required" };
export const BACKOFF_MS = [1_000, 4_000, 15_000, 60_000] as const;
export const FLUSH_PENDING_THRESHOLD = 5;
export const FLUSH_AFTER_OLDEST_MS = 4_000;
const BATCH_CHUNK = 50;
type DecisionEntry = Extract<PendingEntry, { kind: "decision" }>;
type DispositionEntry = Extract<PendingEntry, { kind: "disposition" }>;
// created/duplicate/rejected all ACK the entry (removed); everything else is
// the failure taxonomy: continue (mutated, take the next head), backoff
// (network/5xx — wait outside the lock, then retry), stop (401/403/mid-round
// 409/unnamed 4xx — preserve the queue and end the drain), done (queue empty
// or recovery disposal).
type StepResult = "done" | "continue" | "stop" | "backoff";
// One drain's state. `opts` is the drain's own copy: a recovery caller that joins it upgrades
// `recovery` (purses-w7ss.32). `collectionId` scopes the notices it raises (purses-w7ss.31).
interface DrainRun {
opts: DrainOptions;
collectionId: string | undefined;
rejected: number;
quarantined: number;
}
// ---- module-level engine state (per JS realm) -------------------------------
const drains = new Map<string, { promise: Promise<void>; run: DrainRun }>();
const attempts = new Map<string, number>();
const backoffPreempts = new Map<string, () => void>();
const keepaliveNext = new Set<string>();
const currentNotices = new Map<string, FlushNotice>(); // keyed by noticeKey
const ackWaiters = new Map<string, Array<(o: AckOutcome) => void>>();
const ackOutcomes = new Map<string, AckOutcome>();
const ACK_OUTCOME_BUFFER = 200;
// Entries currently inside an active request (sent, not yet classified) — the
// undo-as-revisit introspection seam (F19): queued = in storage AND not here.
const inFlightEntries = new Set<string>();
function lockName(key: QueueKey): string {
return `adored.flush.v1.${key.curatorId}.${key.sessionId}`;
}
// Global kinds key by kind alone (one line everywhere); a conflict keys by its sort too, so a later
// conflict from another sort in the same collection never replaces it (and never silently releases
// CompareChoice's hold); the rest key by kind + collection (purses-w7ss.31).
export function noticeKey(n: FlushNotice): string {
switch (n.kind) {
case "auth_required":
case "closed_session_discarded":
return n.kind;
case "session_conflict":
return `${n.kind}\u0000${n.collectionId ?? ""}\u0000${n.sessionId}`;
default:
return `${n.kind}\u0000${n.collectionId ?? ""}`;
}
}
// The current set as an immutable snapshot (useSyncExternalStore), so adds AND clears reach a
// mounted surface.
let noticeSet: readonly FlushNotice[] = [];
const noticeSetListeners = new Set<() => void>();
function publishNoticeSet(): void {
noticeSet = [...currentNotices.values()];
for (const listener of [...noticeSetListeners]) listener();
}
function emitNotice(notice: FlushNotice): void {
currentNotices.set(noticeKey(notice), notice);
publishNoticeSet();
}
export function subscribeNoticeSet(listener: () => void): () => void {
noticeSetListeners.add(listener);
return () => void noticeSetListeners.delete(listener);
}
export function getNoticeSet(): readonly FlushNotice[] {
return noticeSet;
}
export function dismissNotice(notice: FlushNotice): void {
if (currentNotices.delete(noticeKey(notice))) publishNoticeSet();
}
function ackId(storageKey: string, clientKey: string): string {
return `${storageKey}\u0000${clientKey}`;
}
function resolveAck(storageKey: string, clientKey: string, outcome: AckOutcome): void {
const id = ackId(storageKey, clientKey);
const waiters = ackWaiters.get(id);
if (waiters !== undefined) {
ackWaiters.delete(id);
for (const waiter of waiters) waiter(outcome);
return;
}
// Nobody waiting yet — buffer so an awaitAck issued just after the ack (the
// compare surface enqueues, triggers, then awaits) still resolves.
ackOutcomes.set(id, outcome);
Iif (ackOutcomes.size > ACK_OUTCOME_BUFFER) {
const oldest = ackOutcomes.keys().next().value;
if (oldest !== undefined) ackOutcomes.delete(oldest);
}
}
export function isInFlight(key: QueueKey, clientKey: string): boolean {
return inFlightEntries.has(ackId(pendingStorageKey(key), clientKey));
}
export function awaitAck(key: QueueKey, clientKey: string): Promise<AckOutcome> {
const id = ackId(pendingStorageKey(key), clientKey);
const buffered = ackOutcomes.get(id);
if (buffered !== undefined) {
ackOutcomes.delete(id);
return Promise.resolve(buffered);
}
return new Promise<AckOutcome>((resolve) => {
const waiters = ackWaiters.get(id) ?? [];
waiters.push(resolve);
ackWaiters.set(id, waiters);
});
}
// ---- drain ------------------------------------------------------------------
export function drain(keys: QueueKey[], opts: DrainOptions = {}): Promise<void> {
if (keys.length === 1) return drainKey(keys[0], opts); // preserve promise identity for single-flight callers
return Promise.all(keys.map((key) => drainKey(key, opts))).then(() => undefined);
}
export function triggerFlush(key: QueueKey): Promise<void> {
return drain([key]);
}
function drainKey(key: QueueKey, opts: DrainOptions): Promise<void> {
const storageKey = pendingStorageKey(key);
const inFlight = drains.get(storageKey);
if (inFlight !== undefined) {
// A recovery caller joining a live drain makes it a recovery drain (one-way): a 409 then means a
// closed sort's answers to let go, not a mid-round conflict to hold (purses-w7ss.32).
if (opts.recovery) inFlight.run.opts.recovery = true;
return inFlight.promise;
}
const run: DrainRun = { opts: { ...opts }, collectionId: readQueueCollectionId(key), rejected: 0, quarantined: 0 };
const promise = runDrain(key, run).finally(() => {
Eif (drains.get(storageKey)?.promise === promise) drains.delete(storageKey);
});
drains.set(storageKey, { promise, run });
return promise;
}
async function runDrain(key: QueueKey, run: DrainRun): Promise<void> {
const storageKey = pendingStorageKey(key);
try {
for (;;) {
const step = await withWebLock(lockName(key), () => performStep(key, run));
if (step === "continue") continue;
if (step === "backoff") {
const attempt = attempts.get(storageKey) ?? 0;
attempts.set(storageKey, attempt + 1);
await backoffWait(storageKey, BACKOFF_MS[Math.min(attempt, BACKOFF_MS.length - 1)]);
continue;
}
return; // "done" | "stop"
}
} finally {
// One notice per kind per drain (F9) — a set of rejections/quarantines
// collapses to a single quiet line.
const { collectionId } = run;
if (run.rejected > 0) emitNotice({ kind: "rejected_unknown_item", count: run.rejected, collectionId });
if (run.quarantined > 0) emitNotice({ kind: "quarantined", count: run.quarantined, collectionId });
}
}
async function performStep(key: QueueKey, drainRun: DrainRun): Promise<StepResult> {
const entries = readQueue(key); // re-read from storage under the lock, every iteration
if (entries.length === 0) return "done";
const head = entries[0];
if (head.kind === "decision") return flushDecisionRun(key, entries, drainRun);
return flushDisposition(key, head, drainRun);
}
function quarantine(key: QueueKey, entries: PendingEntry[], drainRun: DrainRun): void {
quarantineEntries(key, entries);
removeEntries(
key,
entries.map((e) => e.clientKey),
);
drainRun.quarantined += entries.length;
const storageKey = pendingStorageKey(key);
for (const entry of entries) {
resolveAck(storageKey, entry.clientKey, { status: "rejected", reason: "quarantined" });
}
}
function consumeKeepalive(storageKey: string, opts: DrainOptions): boolean {
if (keepaliveNext.delete(storageKey)) return true;
return opts.keepalive === true;
}
async function flushDecisionRun(
key: QueueKey,
entries: PendingEntry[],
drainRun: DrainRun,
): Promise<StepResult> {
const storageKey = pendingStorageKey(key);
// Longest contiguous run of decision entries from the head, chunked ≤50,
// order kept — a disposition entry flushes alone between runs.
const run: DecisionEntry[] = [];
for (const entry of entries) {
if (entry.kind !== "decision") break;
run.push(entry);
if (run.length === BATCH_CHUNK) break;
}
// Pre-flush validation with the SHARED schema (spec §3.1): stale-shape
// entries (a deploy mid-session) are quarantined, never sent, never retried.
const valid: DecisionEntry[] = [];
const offenders: PendingEntry[] = [];
for (const entry of run) {
const parsed = BatchEntrySchema.safeParse({
type: entry.type,
decision: entry.decision,
clientKey: entry.clientKey,
});
if (parsed.success) valid.push(entry);
else offenders.push(entry);
}
if (offenders.length > 0) quarantine(key, offenders, drainRun);
if (valid.length === 0) return "continue";
const flightIds = valid.map((e) => ackId(storageKey, e.clientKey));
for (const id of flightIds) inFlightEntries.add(id);
try {
let res: Response;
try {
res = await fetch(`/api/sessions/${key.sessionId}/decisions/batch`, {
method: "POST",
headers: { "Content-Type": "application/json" },
keepalive: consumeKeepalive(storageKey, drainRun.opts),
body: JSON.stringify({
decisions: valid.map((e) => ({ type: e.type, decision: e.decision, clientKey: e.clientKey })),
}),
});
} catch {
return "backoff"; // network — queue intact (and back to merely queued), retry on the pinned schedule
}
if (res.ok) {
attempts.set(storageKey, 0); // success resets the backoff schedule
dismissNotice({ kind: "auth_required" }); // signed in again
let results: BatchResult[] = [];
try {
results = ((await res.json()) as { results?: BatchResult[] }).results ?? [];
} catch {
results = [];
}
const byClientKey = new Map(results.map((r) => [r.clientKey, r]));
const ackedKeys: string[] = [];
for (const entry of valid) {
const result = byClientKey.get(entry.clientKey);
// An entry the server didn't echo is treated as duplicate: the partial
// unique index makes a replay harmless, while re-queueing it forever
// would wedge the drain.
let outcome: AckOutcome;
if (result?.status === "rejected") {
outcome = { status: "rejected", reason: result.reason };
drainRun.rejected += 1;
} else {
outcome = { status: result?.status === "created" ? "created" : "duplicate" };
}
ackedKeys.push(entry.clientKey);
resolveAck(storageKey, entry.clientKey, outcome);
}
removeEntries(key, ackedKeys); // exactly the acked keys — re-read + filter under the lock
return "continue";
}
return handleBatchFailure(key, res.status, valid, drainRun);
} finally {
for (const id of flightIds) inFlightEntries.delete(id);
}
}
function handleBatchFailure(
key: QueueKey,
status: number,
sent: DecisionEntry[],
drainRun: DrainRun,
): StepResult {
if (status === 400) {
// Whole-batch shape rejection. Everything sent already passed the shared
// schema locally in this same lock iteration (safeParse is deterministic),
// so re-validating here can find no offender — this is client/server
// skew, and retrying would hot-loop. Quarantine the whole chunk;
// resurfacing is the reconciliation (spec §3.1).
quarantine(key, sent, drainRun);
return "continue";
}
if (status === 401) {
emitNotice({ kind: "auth_required" });
return "stop"; // preserve until re-auth
}
if (status === 403) {
return "stop"; // preserve for this queue; retained until GC, never deleted live
}
if (status === 409) {
if (drainRun.opts.recovery) {
// Terminal-session disposal: surface once, then discard. Its own kind, not a conflict, and
// global: no surface is that closed sort's, so every surface must say it. A comparison still
// awaiting one of these answers learns it never landed, so no "it's safe" outlives it
// (purses-w7ss.35).
const storageKey = pendingStorageKey(key);
for (const entry of readQueue(key)) {
resolveAck(storageKey, entry.clientKey, { status: "rejected", reason: "closed" });
}
emitNotice({ kind: "closed_session_discarded" });
deleteQueue(key);
return "done";
}
emitNotice({ kind: "session_conflict", sessionId: key.sessionId, collectionId: drainRun.collectionId });
return "stop"; // mid-round: stop gently, preserve
}
Eif (status >= 500) return "backoff";
// Unnamed 4xx (e.g. 404 — session gone): preserve and stop; GC owns cleanup.
return "stop";
}
async function flushDisposition(
key: QueueKey,
entry: DispositionEntry,
drainRun: DrainRun,
): Promise<StepResult> {
const storageKey = pendingStorageKey(key);
const collectionId = readQueueCollectionId(key);
Iif (collectionId === undefined) {
// Unroutable without a collection — same terminal shelf as a stale shape.
quarantine(key, [entry], drainRun);
return "continue";
}
const flightId = ackId(storageKey, entry.clientKey);
inFlightEntries.add(flightId);
let res: Response;
try {
Iif (entry.disposition === "clear") {
res = await fetch(`/api/collections/${collectionId}/dispositions/${entry.itemId}`, {
method: "DELETE",
keepalive: consumeKeepalive(storageKey, drainRun.opts),
});
} else {
res = await fetch(`/api/collections/${collectionId}/dispositions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
keepalive: consumeKeepalive(storageKey, drainRun.opts),
body: JSON.stringify({ itemId: entry.itemId, disposition: entry.disposition }),
});
}
} catch {
return "backoff";
} finally {
inFlightEntries.delete(flightId);
}
if (res.ok) {
attempts.set(storageKey, 0);
dismissNotice({ kind: "auth_required" }); // signed in again
removeEntries(key, [entry.clientKey]);
return "continue";
}
if (res.status === 409) {
// PreferenceExistsError: the item was triaged before this disposition
// flushed — permanent, per-entry (disposed ⇔ untriaged). Remove it, one
// gentle notice, and the drain CONTINUES: recovery of [set_aside X (409),
// triage Y] never discards Y (F4).
removeEntries(key, [entry.clientKey]);
emitNotice({ kind: "disposition_superseded", collectionId: drainRun.collectionId });
return "continue";
}
Eif (res.status === 404) {
removeEntries(key, [entry.clientKey]); // item gone — drop silently, continue
return "continue";
}
if (res.status === 400) {
quarantine(key, [entry], drainRun);
return "continue";
}
if (res.status === 401) {
emitNotice({ kind: "auth_required" });
return "stop";
}
if (res.status === 403) return "stop";
if (res.status >= 500) return "backoff";
return "stop";
}
// ---- backoff (preemptible by pagehide) ---------------------------------------
function backoffWait(storageKey: string, ms: number): Promise<void> {
return new Promise<void>((resolve) => {
const timer = setTimeout(() => {
backoffPreempts.delete(storageKey);
resolve();
}, ms);
backoffPreempts.set(storageKey, () => {
clearTimeout(timer);
backoffPreempts.delete(storageKey);
resolve();
});
});
}
function preemptBackoff(key: QueueKey): void {
const storageKey = pendingStorageKey(key);
keepaliveNext.add(storageKey); // the preempted iteration's request must survive the unload
backoffPreempts.get(storageKey)?.();
}
// ---- triggers hook ------------------------------------------------------------
// Triggers ONLY (spec §3.2): ≥5 pending · 4 s after the oldest pending entry ·
// pagehide/visibilitychange:hidden → keepalive drain that preempts an active
// backoff wait. Round-end / compare / pause callers use triggerFlush directly.
export function useDecisionFlusher(key: QueueKey): void {
const { curatorId, sessionId, collectionId } = key;
useEffect(() => {
const effectKey: QueueKey = { curatorId, sessionId, collectionId };
const storageKey = pendingStorageKey(effectKey);
let timer: ReturnType<typeof setTimeout> | null = null;
const clearTimer = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
};
const schedule = () => {
clearTimer();
const entries = readQueue(effectKey);
if (entries.length === 0) return;
if (entries.length >= FLUSH_PENDING_THRESHOLD) {
void drain([effectKey]);
return;
}
const oldestAt = Date.parse(entries[0].enqueuedAt);
const dueIn = Number.isFinite(oldestAt)
? Math.max(0, oldestAt + FLUSH_AFTER_OLDEST_MS - Date.now())
: 0;
timer = setTimeout(() => {
timer = null;
void drain([effectKey]);
}, dueIn);
};
const onPendingChanged = (event: Event) => {
Eif ((event as CustomEvent<string>).detail === storageKey) schedule();
};
const flushForUnload = () => {
preemptBackoff(effectKey);
void drain([effectKey], { keepalive: true });
};
const onVisibilityChange = () => {
if (document.visibilityState === "hidden") flushForUnload();
};
window.addEventListener(PENDING_CHANGED_EVENT, onPendingChanged);
window.addEventListener("pagehide", flushForUnload);
document.addEventListener("visibilitychange", onVisibilityChange);
schedule(); // pick up anything already queued at mount (e.g. a reload)
return () => {
clearTimer();
window.removeEventListener(PENDING_CHANGED_EVENT, onPendingChanged);
window.removeEventListener("pagehide", flushForUnload);
document.removeEventListener("visibilitychange", onVisibilityChange);
};
}, [curatorId, sessionId, collectionId]);
}
|