Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

shadow-store.ts

87 lines · 2.8 KB · TypeScript
/**
 * 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<void>
	recent(limit: number): Promise<ShadowRow[]>
}

const MAX_ROWS = 2000
type Row = Record<string, unknown>

async function sql(query: string, bindings: Array<string | number | null> = []): Promise<Row[]> {
	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<void> | null = null
function ensureSchema(): Promise<void> {
	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<void> {
	try {
		await shadowStore().put(row)
	} catch (error) {
		console.log(JSON.stringify({ at: 'github-events/shadow', error: error instanceof Error ? error.message : String(error) }))
	}
}