/** * #324: graph writes caught while D1 moves. When D1's Durable Object moves to another instance * (a graceful handoff in a self-host cluster, a deploy or an eviction on Cloudflare), a write on * its way gets a transient error (`isTransientD1Error`), and it may or may not have applied. Every * graph write is a CAS anchored on content hashes (AGENTS.md rule 4), so the writer can read its * aim back and know: * * - **applied:** the node has the write's new hash (an insert or update), or is gone (a delete), or * the operation's `op_guards` row exists: report what a successful batch reports; * - **lost:** the node is still at the revision the write read (or absent, for an insert): run the * same statements once more; a second failure is reported as it is; * - **moved:** anything else, someone else's write: report a CAS miss (no changes), so the caller * raises its `ConflictError`, as for any concurrent change. * * No transaction and no new statement shape: one read after the error, and at most one retry. * SQLite drivers never raise a transient error, so this never runs on them. */ import { isTransientD1Error, type RunResult, type SqlDriver, type SqlStatement, } from "@cloudhal/storage"; /** * What a statement writes, for the read-back: a node at a new hash (`fromRev` undefined for an * insert), a node deleted at `fromRev` (no `hash`), or a row that exists once it is written. */ export type WriteAim = | { readonly id: string; readonly hash: string; readonly fromRev?: number | undefined } | { readonly id: string; readonly hash?: undefined; readonly fromRev: number } | { readonly probe: SqlStatement }; /** A statement that carries its aim (the node statement builders attach one). */ export type AimedStatement = SqlStatement & { readonly aim?: WriteAim | undefined }; export type WriteState = "applied" | "lost" | "moved"; /** Where the write stands after a transient error, read with the driver's retried reads. */ export async function writeState(sql: SqlDriver, aim: WriteAim): Promise { if ("probe" in aim) { const row = await sql.get(aim.probe.sql, aim.probe.params ?? []); return row ? "applied" : "lost"; } const row = await sql.get<{ rev: number; hash: string }>( "SELECT rev, hash FROM nodes WHERE id = ?", [aim.id], ); if (aim.hash === undefined) return !row ? "applied" : row.rev === aim.fromRev ? "lost" : "moved"; if (row?.hash === aim.hash) return "applied"; const untouched = aim.fromRev === undefined ? !row : row?.rev === aim.fromRev; return untouched ? "lost" : "moved"; } const aimOf = (s: SqlStatement | undefined) => (s as AimedStatement | undefined)?.aim; const none = (n: number): RunResult[] => Array.from({ length: n }, () => ({ changes: 0, lastRowId: null })); /** * `sql.batch(statements)`, settled after a transient error by the first statement's aim. Applied: * each aimed statement reports 1 change when its own aim is met (the batch is atomic, so the rest * ran too) and 0 otherwise; unaimed statements report 0. Moved: every statement reports 0, a CAS * miss. Without an aim on the first statement the error is thrown as it is. */ export async function casBatch( sql: SqlDriver, statements: readonly AimedStatement[], ): Promise { try { return await sql.batch(statements); } catch (error) { const aim = aimOf(statements[0]); if (!aim || !isTransientD1Error(error)) throw error; const state = await writeState(sql, aim); if (state === "lost") return sql.batch(statements); if (state === "moved") return none(statements.length); return Promise.all( statements.map(async (s) => { const own = aimOf(s); const met = own === aim || (own !== undefined && (await writeState(sql, own)) === "applied"); return { changes: met ? 1 : 0, lastRowId: null }; }), ); } } /** `sql.run` of one aimed statement, settled the same way. */ export async function casRun(sql: SqlDriver, statement: AimedStatement): Promise { const [r] = await casBatchOf(sql, statement); return r ?? { changes: 0, lastRowId: null }; } async function casBatchOf(sql: SqlDriver, statement: AimedStatement): Promise { try { return [await sql.run(statement.sql, statement.params ?? [])]; } catch (error) { const aim = aimOf(statement); if (!aim || !isTransientD1Error(error)) throw error; const state = await writeState(sql, aim); if (state === "lost") return [await sql.run(statement.sql, statement.params ?? [])]; return [{ changes: state === "applied" ? 1 : 0, lastRowId: null }]; } }