import { env } from "cloudflare:workers"; import { all } from "./db"; /** * One-shot data backfills that walk every repository once, a page per cron run, so new indexes can cover rows * written before they existed. Progress lives in KV (`backfill:`): the last repository id visited, or * DONE. Readers that need the index consult `backfillDone` and keep their old (slower) path until it is. */ const DONE = "done"; const PAGE = 50; const finished = new Set(); function key(name: string): string { return `backfill:${name}`; } /** False until the backfill has finished, and whenever its state can't be read (callers keep their safe path). */ export async function backfillDone(name: string): Promise { if (finished.has(name)) return true; const state = await Promise.resolve() .then(() => env.KV.get(key(name))) .catch(() => null); if (state === DONE) finished.add(name); return state === DONE; } /** Visits the next page of repositories in id order; call from the cron until it reports done. */ export async function backfillRepos(name: string, visit: (repoId: string) => Promise): Promise { if (await backfillDone(name)) return true; const cursor = (await env.KV.get(key(name))) ?? ""; const repos = await all<{ id: string }>("SELECT id FROM repos WHERE id > ? ORDER BY id LIMIT ?", cursor, PAGE); for (const repo of repos) await visit(repo.id); const done = repos.length < PAGE; await env.KV.put(key(name), done ? DONE : (repos.at(-1)?.id ?? cursor)); if (done) finished.add(name); return done; }