/** * Side-by-side record of what the factory's own GitHub webhook decided and * what the `@kody/github.*` event path decided for the same delivery. One SQL * row per (delivery, side), so the two writers never race on one JSON blob. */ import { packageStorage } from 'kody:runtime' export type ShadowSide = 'webhook' | 'event' export type ShadowRow = { deliveryId: string; side: ShadowSide; decision: string; topic: string; at: string; detail: string } export type ShadowStore = { put(row: ShadowRow): Promise recent(limit: number): Promise } const MAX_ROWS = 2000 type Row = Record async function sql(query: string, bindings: Array = []): Promise { const result = (await packageStorage().sql(query, bindings)) as { rows?: unknown[] } | unknown[] | null if (!result) return [] if (Array.isArray(result)) return result as Row[] return Array.isArray(result.rows) ? (result.rows as Row[]) : [] } let ready: Promise | null = null function ensureSchema(): Promise { ready ??= sql( `CREATE TABLE IF NOT EXISTS github_event_shadow ( delivery_id TEXT NOT NULL, side TEXT NOT NULL, decision TEXT NOT NULL, topic TEXT NOT NULL, at TEXT NOT NULL, detail TEXT NOT NULL, PRIMARY KEY (delivery_id, side) )`, ).then(() => undefined).catch((error) => { ready = null throw error }) return ready } const sqlStore: ShadowStore = { async put(row) { await ensureSchema() await sql( 'INSERT OR REPLACE INTO github_event_shadow (delivery_id, side, decision, topic, at, detail) VALUES (?, ?, ?, ?, ?, ?)', [row.deliveryId.slice(0, 120), row.side, row.decision.slice(0, 500), row.topic.slice(0, 120), row.at, row.detail.slice(0, 2000)], ) await sql( 'DELETE FROM github_event_shadow WHERE rowid NOT IN (SELECT rowid FROM github_event_shadow ORDER BY at DESC LIMIT ?)', [MAX_ROWS], ) }, async recent(limit) { await ensureSchema() const rows = await sql('SELECT delivery_id, side, decision, topic, at, detail FROM github_event_shadow ORDER BY at DESC LIMIT ?', [limit]) return rows.map((r) => ({ deliveryId: String(r.delivery_id), side: r.side === 'event' ? 'event' : 'webhook', decision: String(r.decision), topic: String(r.topic), at: String(r.at), detail: String(r.detail), })) }, } let override: ShadowStore | null = null /** Test seam. */ export function setShadowStoreForTests(store: ShadowStore | null) { override = store } export function shadowStore(): ShadowStore { return override ?? sqlStore } /** Record without ever throwing: shadow bookkeeping must not break intake. */ export async function recordShadow(row: ShadowRow): Promise { try { await shadowStore().put(row) } catch (error) { console.log(JSON.stringify({ at: 'github-events/shadow', error: error instanceof Error ? error.message : String(error) })) } }