Skip to content
← Public packages

@kentcdodds/exchange-threads

Open or join kody.exchange threads from Kody and get woken by webhook: multi-thread watches with once/batch/each firing and webhook, Discord, Cursor, or job targets. No polling.

FollowFork

Files

watch-store.ts

181 lines · 5.3 KB · TypeScript
import {
	emptyCursor,
	normalizeNames,
	type NotifyTarget,
	type Watch,
} from './watch-config.ts'
import type { Storage } from './shared.ts'

const LEGACY_KEY = 'inboundWatch'
const LEGACY_MIGRATED_KEY = 'inboundWatchMigratedAt'
export const LEGACY_ARMED_AT = '1970-01-01T00:00:00.000Z'

export async function ensureWatchSchema(bucket: Storage) {
	await bucket.sql(`
		CREATE TABLE IF NOT EXISTS watches (
			thread_id TEXT PRIMARY KEY,
			watch_json TEXT NOT NULL,
			version INTEGER NOT NULL DEFAULT 0,
			updated_at TEXT NOT NULL
		)
	`)
	await bucket.sql(`
		CREATE TABLE IF NOT EXISTS self_agents (
			thread_id TEXT NOT NULL,
			agent_id TEXT NOT NULL,
			added_at TEXT NOT NULL,
			PRIMARY KEY (thread_id, agent_id)
		)
	`)
	await migrateLegacyWatch(bucket)
}

function str(value: unknown) {
	return typeof value === 'string' && value.trim() ? value.trim() : null
}

/**
 * 1.x kept one watch in kv `inboundWatch`. Copy it into `watches` once, as a
 * one-shot watch with its fired state, so a live watch keeps working exactly as
 * before. The kv row is left in place so a rollback to 1.x still sees it.
 */
export function legacyToWatch(value: string): Watch | null {
	let parsed: Record<string, unknown>
	try {
		parsed = JSON.parse(value) as Record<string, unknown>
	} catch {
		return null
	}
	const threadId = str(parsed.threadId)
	const viewUrl = str(parsed.viewUrl)
	if (!threadId || !viewUrl) return null
	const notifiedAt = str(parsed.notifiedAt)
	const cursorAgentId = str(parsed.cursorAgentId)
	const targets: NotifyTarget[] = [{ type: 'discord' }]
	if (cursorAgentId) targets.push({ type: 'cursor', agentId: cursorAgentId })
	const skip = Array.isArray(parsed.skipFromNames)
		? normalizeNames(parsed.skipFromNames)
		: ['cursor']
	const now = new Date().toISOString()
	return {
		threadId,
		viewUrl,
		skipFromNames: skip,
		fire: 'once',
		minIntervalSeconds: 0,
		rewakeAfterSeconds: 300,
		includeSystem: true,
		note: null,
		targets,
		armedAt: LEGACY_ARMED_AT,
		updatedAt: now,
		cursor: emptyCursor(),
		batchOpenSince: null,
		pendingSinceWake: 0,
		lastFiredAt: notifiedAt,
		fireCount: notifiedAt ? 1 : 0,
		spent: Boolean(notifiedAt),
		lastResults: [],
		legacy: true,
	}
}

async function kvGet(bucket: Storage, key: string) {
	const result = await bucket.sql('SELECT value FROM kv WHERE key = ?', [key])
	const value = result.rows[0]?.value
	return typeof value === 'string' ? value : null
}

async function migrateLegacyWatch(bucket: Storage) {
	if (await kvGet(bucket, LEGACY_MIGRATED_KEY)) return
	const legacy = await kvGet(bucket, LEGACY_KEY)
	const watch = legacy ? legacyToWatch(legacy) : null
	if (watch) {
		await bucket.sql(
			`INSERT INTO watches (thread_id, watch_json, version, updated_at)
			 VALUES (?, ?, 0, ?)
			 ON CONFLICT(thread_id) DO NOTHING`,
			[watch.threadId, JSON.stringify(watch), watch.updatedAt],
		)
	}
	await bucket.sql(
		'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING',
		[LEGACY_MIGRATED_KEY, new Date().toISOString()],
	)
}

export type StoredWatch = { watch: Watch; version: number }

function parseRow(row: Record<string, unknown> | undefined): StoredWatch | null {
	if (!row || typeof row.watch_json !== 'string') return null
	try {
		return { watch: JSON.parse(row.watch_json) as Watch, version: Number(row.version ?? 0) }
	} catch {
		return null
	}
}

export async function getWatch(bucket: Storage, threadId: string) {
	const result = await bucket.sql(
		'SELECT watch_json, version FROM watches WHERE thread_id = ?',
		[threadId],
	)
	return parseRow(result.rows[0])
}

export async function listWatches(bucket: Storage) {
	const result = await bucket.sql(
		'SELECT watch_json, version FROM watches ORDER BY updated_at DESC LIMIT 100',
	)
	return result.rows
		.map((row) => parseRow(row))
		.filter((row): row is StoredWatch => row !== null)
		.map((row) => row.watch)
}

export async function putWatch(bucket: Storage, watch: Watch) {
	await bucket.sql(
		`INSERT INTO watches (thread_id, watch_json, version, updated_at)
		 VALUES (?, ?, 0, ?)
		 ON CONFLICT(thread_id) DO UPDATE SET
		   watch_json = excluded.watch_json,
		   version = watches.version + 1,
		   updated_at = excluded.updated_at`,
		[watch.threadId, JSON.stringify(watch), watch.updatedAt],
	)
}

/** Optimistic write: true only if nobody changed the row since `version`. */
export async function casWatch(bucket: Storage, watch: Watch, version: number) {
	const result = await bucket.sql(
		`UPDATE watches SET watch_json = ?, version = version + 1, updated_at = ?
		 WHERE thread_id = ? AND version = ?
		 RETURNING thread_id`,
		[JSON.stringify(watch), watch.updatedAt, watch.threadId, version],
	)
	return result.rows.length > 0
}

export async function deleteWatch(bucket: Storage, threadId: string) {
	const result = await bucket.sql(
		'DELETE FROM watches WHERE thread_id = ? RETURNING thread_id',
		[threadId],
	)
	return result.rows.length > 0
}

export async function addSelfAgent(bucket: Storage, threadId: string, agentId: string) {
	await bucket.sql(
		`INSERT INTO self_agents (thread_id, agent_id, added_at) VALUES (?, ?, ?)
		 ON CONFLICT(thread_id, agent_id) DO NOTHING`,
		[threadId, agentId, new Date().toISOString()],
	)
}

export async function getSelfAgents(bucket: Storage, threadId: string) {
	const result = await bucket.sql(
		'SELECT agent_id FROM self_agents WHERE thread_id = ?',
		[threadId],
	)
	return result.rows.map((row) => String(row.agent_id))
}