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

store.ts

220 lines · 8.1 KB · TypeScript
/**
 * SQL storage for signal records. One row per inbound signal with its
 * routing decision and destination results.
 */
import { packageStorage } from 'kody:runtime'
import { MAX_RECORDS, type DestinationResult, type RoutingDecision, type SignalRecord, type SignalStatus } from './types.ts'

type Row = Record<string, unknown>
type Binding = string | number | boolean | null

async function sql(query: string, bindings: Binding[] = []): 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 schemaReady: Promise<void> | null = null

export function initRecordsSchema(): Promise<void> {
	schemaReady ??= createSchema().catch((error) => {
		schemaReady = null
		throw error
	})
	return schemaReady
}

export function resetRecordsSchemaCache(): void {
	schemaReady = null
}

async function createSchema() {
	await sql(`CREATE TABLE IF NOT EXISTS signal_records (
		id TEXT PRIMARY KEY,
		source_id TEXT NOT NULL,
		received_at TEXT NOT NULL,
		verified INTEGER NOT NULL DEFAULT 0,
		payload_digest TEXT NOT NULL,
		redacted_payload TEXT NOT NULL,
		routing_decision_json TEXT,
		destination_results_json TEXT NOT NULL DEFAULT '[]',
		status TEXT NOT NULL DEFAULT 'received',
		error TEXT,
		project_id TEXT,
		title TEXT
	)`)
	await sql('CREATE INDEX IF NOT EXISTS signal_records_source ON signal_records (source_id, received_at)')
	await sql('CREATE INDEX IF NOT EXISTS signal_records_status ON signal_records (status, received_at)')
	await sql('CREATE INDEX IF NOT EXISTS signal_records_project ON signal_records (project_id, received_at)')
	await sql(`CREATE TABLE IF NOT EXISTS signal_rejection_counters (
		source_id TEXT PRIMARY KEY,
		count INTEGER NOT NULL DEFAULT 0,
		last_at TEXT NOT NULL,
		last_error TEXT
	)`)
}

function str(value: unknown): string | null {
	return value == null || value === '' ? null : String(value)
}

function safeJson<T>(raw: unknown, fallback: T): T {
	if (raw == null || raw === '') return fallback
	try {
		const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
		return parsed as T
	} catch {
		return fallback
	}
}

function parseRecord(row: Row): SignalRecord {
	return {
		id: String(row.id),
		sourceId: String(row.source_id),
		receivedAt: String(row.received_at),
		verified: row.verified === 1 || row.verified === true,
		payloadDigest: String(row.payload_digest),
		redactedPayload: String(row.redacted_payload || ''),
		routingDecision: safeJson<RoutingDecision | null>(row.routing_decision_json, null),
		destinationResults: safeJson<DestinationResult[]>(row.destination_results_json, []),
		status: String(row.status || 'received') as SignalStatus,
		error: str(row.error),
		projectId: str(row.project_id),
		title: str(row.title),
	}
}

export async function insertRecord(record: SignalRecord): Promise<void> {
	await initRecordsSchema()
	await sql(
		`INSERT INTO signal_records (id, source_id, received_at, verified, payload_digest, redacted_payload, routing_decision_json, destination_results_json, status, error, project_id, title)
		 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		[
			record.id,
			record.sourceId,
			record.receivedAt,
			record.verified ? 1 : 0,
			record.payloadDigest,
			record.redactedPayload,
			record.routingDecision ? JSON.stringify(record.routingDecision) : null,
			JSON.stringify(record.destinationResults),
			record.status,
			record.error,
			record.projectId,
			record.title,
		],
	)
}

export async function updateRecord(id: string, patch: Partial<Pick<SignalRecord, 'routingDecision' | 'destinationResults' | 'status' | 'error' | 'projectId' | 'title'>>): Promise<SignalRecord | null> {
	await initRecordsSchema()
	const sets: string[] = []
	const bindings: Binding[] = []
	if (patch.routingDecision !== undefined) { sets.push('routing_decision_json = ?'); bindings.push(JSON.stringify(patch.routingDecision)) }
	if (patch.destinationResults !== undefined) { sets.push('destination_results_json = ?'); bindings.push(JSON.stringify(patch.destinationResults)) }
	if (patch.status !== undefined) { sets.push('status = ?'); bindings.push(patch.status) }
	if (patch.error !== undefined) { sets.push('error = ?'); bindings.push(patch.error) }
	if (patch.projectId !== undefined) { sets.push('project_id = ?'); bindings.push(patch.projectId) }
	if (patch.title !== undefined) { sets.push('title = ?'); bindings.push(patch.title) }
	if (sets.length === 0) return getRecord(id)
	bindings.push(id)
	await sql(`UPDATE signal_records SET ${sets.join(', ')} WHERE id = ?`, bindings)
	return getRecord(id)
}

export async function getRecord(id: string): Promise<SignalRecord | null> {
	await initRecordsSchema()
	const rows = await sql('SELECT * FROM signal_records WHERE id = ?', [id])
	return rows[0] ? parseRecord(rows[0]) : null
}

export type ListRecordsOpts = {
	sourceId?: string
	status?: SignalStatus
	projectId?: string
	limit?: number
	before?: string
}

export async function listRecords(opts: ListRecordsOpts = {}): Promise<SignalRecord[]> {
	await initRecordsSchema()
	const where: string[] = []
	const bindings: Binding[] = []
	if (opts.sourceId) { where.push('source_id = ?'); bindings.push(opts.sourceId) }
	if (opts.status) { where.push('status = ?'); bindings.push(opts.status) }
	if (opts.projectId) { where.push('project_id = ?'); bindings.push(opts.projectId) }
	if (opts.before) { where.push('received_at < ?'); bindings.push(opts.before) }
	bindings.push(Math.min(Math.max(opts.limit ?? 50, 1), 200))
	const rows = await sql(
		`SELECT * FROM signal_records ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY received_at DESC LIMIT ?`,
		bindings,
	)
	return rows.map(parseRecord)
}

export async function countRecords(opts: { sourceId?: string; status?: SignalStatus; projectId?: string } = {}): Promise<number> {
	await initRecordsSchema()
	const where: string[] = []
	const bindings: Binding[] = []
	if (opts.sourceId) { where.push('source_id = ?'); bindings.push(opts.sourceId) }
	if (opts.status) { where.push('status = ?'); bindings.push(opts.status) }
	if (opts.projectId) { where.push('project_id = ?'); bindings.push(opts.projectId) }
	const rows = await sql(
		`SELECT COUNT(*) as cnt FROM signal_records ${where.length ? `WHERE ${where.join(' AND ')}` : ''}`,
		bindings,
	)
	return Number(rows[0]?.cnt ?? 0)
}

/** Delete the oldest records beyond the cap. */
export async function evictOldRecords(): Promise<number> {
	await initRecordsSchema()
	const countRows = await sql('SELECT COUNT(*) as cnt FROM signal_records')
	const total = Number(countRows[0]?.cnt ?? 0)
	if (total <= MAX_RECORDS) return 0
	const excess = total - MAX_RECORDS
	await sql(
		`DELETE FROM signal_records WHERE id IN (SELECT id FROM signal_records ORDER BY received_at ASC LIMIT ?)`,
		[excess],
	)
	return excess
}

export type RejectionCounter = { sourceId: string; count: number; lastAt: string; lastError: string | null }

export async function incrementRejection(sourceId: string, error: string): Promise<void> {
	await initRecordsSchema()
	const now = new Date().toISOString()
	await sql(
		`INSERT INTO signal_rejection_counters (source_id, count, last_at, last_error)
		 VALUES (?, 1, ?, ?)
		 ON CONFLICT(source_id) DO UPDATE SET count = count + 1, last_at = ?, last_error = ?`,
		[sourceId, now, error.slice(0, 200), now, error.slice(0, 200)],
	)
}

export async function getRejectionCounter(sourceId: string): Promise<RejectionCounter | null> {
	await initRecordsSchema()
	const rows = await sql('SELECT * FROM signal_rejection_counters WHERE source_id = ?', [sourceId])
	const row = rows[0]
	if (!row) return null
	return {
		sourceId: String(row.source_id),
		count: Number(row.count ?? 0),
		lastAt: String(row.last_at),
		lastError: str(row.last_error),
	}
}

export async function listRejectionCounters(): Promise<RejectionCounter[]> {
	await initRecordsSchema()
	const rows = await sql('SELECT * FROM signal_rejection_counters ORDER BY last_at DESC')
	return rows.map((row) => ({
		sourceId: String(row.source_id),
		count: Number(row.count ?? 0),
		lastAt: String(row.last_at),
		lastError: str(row.last_error),
	}))
}