Open History to see the last commit
1#!/usr/bin/env node
2/**
3 * Public git mirror of the catalog (issue #343). Fetches
4 * `GET /v1/admin/export`, writes one file per entity into a data repo
5 * checkout, and prints the commit message on stdout:
6 *
7 * providers/<provider>.json
8 * models/<provider>/<modelId>.json
9 * schemas/<provider>/<endpointId>.json
10 * feed.json the export's latestChange, plus the /v1/changes ids
11 * already listed in a commit message
12 *
13 * The export already leaves out per-poll fields and sorts keys; files here
14 * are pretty-printed with a trailing newline, so the same export always
15 * writes the same bytes. The three entity folders are rewritten from
16 * scratch, so a removed entity shows up as a deleted file.
17 *
18 * The message lists every /v1/changes id no earlier commit listed. A
19 * change's createdAt is when its poll STARTED and ids are random, so a
20 * (createdAt, id) cursor would skip rows a running poll inserts later.
21 * Instead each run re-reads the feed from LOOKBACK_SECONDS before the
22 * newest createdAt seen and drops ids already listed. The export is not
23 * one snapshot either: files can hold a change a later commit lists.
24 * Admin-keyed requests skip the rate limit, so paging the feed is free.
25 *
26 * Before touching the tree it refuses an export that would delete most of
27 * the mirror (a fresh or wrong D1 still answers 200) unless
28 * MIRROR_ALLOW_SHRINK=1, and a latestChange that is gone or moved
29 * backwards (provider rows cascade-delete their changes): delete feed.json
30 * by hand to re-seed from that export.
31 *
32 * Self-contained (no repo imports): the data repo's workflow runs it from a
33 * sparse checkout of this file (scripts/mirror/catalog-mirror.yml).
34 *
35 * MODELSCHEMAS_ADMIN_KEY=… node scripts/mirror-catalog.ts <data-repo-dir>
36 * MODELSCHEMAS_URL defaults to https://modelschemas.openstory.workers.dev
37 */
38import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
39import { dirname, join } from 'node:path'
40
41export interface ChangeRef {
42 id: string
43 createdAt: number
44}
45
46export interface FeedChange extends ChangeRef {
47 type: string
48 summary: string
49}
50
51interface ExportBody {
52 latestChange: ChangeRef | null
53 providers: Array<{ id: string }>
54 models: Array<{ id: string; provider: string }>
55 schemas: Array<{ provider: string; endpointId: string }>
56}
57
58/** What the mirror has listed so far (feed.json). */
59export interface FeedState {
60 latestChange: ChangeRef | null
61 /** Newest createdAt any listed change had. */
62 highWater: number | null
63 /** Listed changes with createdAt within LOOKBACK_SECONDS of highWater. */
64 listed: Array<ChangeRef>
65}
66
67export const ENTITY_DIRS = ['providers', 'models', 'schemas'] as const
68export const FEED_FILE = 'feed.json'
69/**
70 * ponytail: a poll that inserts changes more than an hour after it starts
71 * would have rows missed; Workers cron invocations end well before that.
72 */
73export const LOOKBACK_SECONDS = 3600
74
75function fail(message: string): never {
76 throw new Error(`mirror: ${message}`)
77}
78
79function isRecord(value: unknown): value is Record<string, unknown> {
80 return typeof value === 'object' && value !== null && !Array.isArray(value)
81}
82
83function changeRef(value: unknown, what: string): ChangeRef | null {
84 if (value === null) return null
85 if (
86 isRecord(value) &&
87 typeof value.id === 'string' &&
88 Number.isInteger(value.createdAt)
89 ) {
90 return { id: value.id, createdAt: value.createdAt as number }
91 }
92 return fail(`${what} is not null or { id, createdAt }`)
93}
94
95function rows<T>(value: unknown, keys: Array<string>, what: string): Array<T> {
96 if (!Array.isArray(value)) fail(`${what} is not an array`)
97 for (const item of value) {
98 if (!isRecord(item) || keys.some((key) => typeof item[key] !== 'string')) {
99 fail(`${what} row lacks string ${keys.join(', ')}`)
100 }
101 }
102 return value as Array<T>
103}
104
105/** The export body, checked: a cast would commit a wrong shape. */
106export function parseExport(value: unknown): ExportBody {
107 if (!isRecord(value) || !('latestChange' in value)) {
108 fail('export body has no latestChange')
109 }
110 const providers = rows<{ id: string }>(
111 value.providers,
112 ['id'],
113 'export providers',
114 )
115 if (providers.length === 0) fail('export has no providers')
116 return {
117 latestChange: changeRef(value.latestChange, 'export latestChange'),
118 providers,
119 models: rows(value.models, ['id', 'provider'], 'export models'),
120 schemas: rows(value.schemas, ['provider', 'endpointId'], 'export schemas'),
121 }
122}
123
124function parseFeedPage(value: unknown) {
125 if (
126 !isRecord(value) ||
127 !(value.nextCursor === null || typeof value.nextCursor === 'string')
128 ) {
129 fail('/v1/changes page lacks nextCursor')
130 }
131 const changes = rows<FeedChange>(
132 value.changes,
133 ['id', 'type', 'summary'],
134 '/v1/changes',
135 )
136 for (const change of changes) changeRef(change, '/v1/changes row')
137 return { changes, nextCursor: value.nextCursor }
138}
139
140export function parseFeedState(text: string | null): FeedState {
141 if (text === null) return { latestChange: null, highWater: null, listed: [] }
142 const value: unknown = JSON.parse(text)
143 if (
144 !isRecord(value) ||
145 !(value.highWater === null || Number.isInteger(value.highWater)) ||
146 !Array.isArray(value.listed)
147 ) {
148 fail(`${FEED_FILE} lacks highWater or listed`)
149 }
150 return {
151 latestChange: changeRef(value.latestChange, `${FEED_FILE} latestChange`),
152 highWater: value.highWater as number | null,
153 listed: value.listed.map(
154 (ref: unknown) =>
155 changeRef(ref, `${FEED_FILE} listed row`) ??
156 fail(`${FEED_FILE} listed row is null`),
157 ),
158 }
159}
160
161function pretty(value: unknown): string {
162 return `${JSON.stringify(value, null, 2)}\n`
163}
164
165/** Ids become path segments; refuse anything that could leave its folder. */
166function safeSegments(id: string): string {
167 const parts = id.split('/')
168 if (
169 id === '' ||
170 id.includes('\\') ||
171 parts.some((part) => part === '' || part === '.' || part === '..')
172 ) {
173 fail(`unsafe id for a file path: ${JSON.stringify(id)}`)
174 }
175 return id
176}
177
178/** Every entity file (path → contents) for one export body. */
179export function mirrorFiles(body: ExportBody): Map<string, string> {
180 const files = new Map<string, string>()
181 const add = (path: string, value: unknown) => {
182 if (files.has(path)) fail(`two entities write ${path}`)
183 files.set(path, pretty(value))
184 }
185 for (const provider of body.providers) {
186 add(`providers/${safeSegments(provider.id)}.json`, provider)
187 }
188 for (const model of body.models) {
189 add(
190 `models/${safeSegments(model.provider)}/${safeSegments(model.id)}.json`,
191 model,
192 )
193 }
194 for (const schema of body.schemas) {
195 add(
196 `schemas/${safeSegments(schema.provider)}/${safeSegments(schema.endpointId)}.json`,
197 schema,
198 )
199 }
200 return files
201}
202
203/** Feed order: newest first by createdAt, then id. */
204function after(a: ChangeRef, b: ChangeRef): boolean {
205 return (
206 a.createdAt > b.createdAt || (a.createdAt === b.createdAt && a.id > b.id)
207 )
208}
209
210/**
211 * Refuse a run that would rewrite history: the latest change gone or moved
212 * backwards, or under half of today's entity files left.
213 */
214export function refuseRun(
215 previous: ChangeRef | null,
216 latest: ChangeRef | null,
217 existingFiles: number,
218 newFiles: number,
219 allowShrink: boolean,
220) {
221 const reseed = `delete ${FEED_FILE} to re-seed from this export`
222 if (previous && !latest) {
223 fail(
224 `export has no latestChange but the mirror is at ${previous.id}; ${reseed}`,
225 )
226 }
227 if (previous && latest && after(previous, latest)) {
228 fail(
229 `latestChange moved backwards from ${previous.id} to ${latest.id}; ${reseed}`,
230 )
231 }
232 if (!allowShrink && newFiles < existingFiles / 2) {
233 fail(
234 `export has ${newFiles} entity files, the mirror ${existingFiles}; rerun with MIRROR_ALLOW_SHRINK=1 if that is real`,
235 )
236 }
237}
238
239/**
240 * Changes from the feed window that no earlier commit listed, and the
241 * state to store. `window` is every row with createdAt >= the previous
242 * highWater minus LOOKBACK_SECONDS.
243 */
244export function newChanges(
245 state: FeedState,
246 window: Array<FeedChange>,
247 latestChange: ChangeRef | null,
248): { listed: Array<FeedChange>; state: FeedState } {
249 const seen = new Set(state.listed.map((ref) => ref.id))
250 const listed = window.filter((change) => !seen.has(change.id))
251 const highWater = Math.max(
252 state.highWater ?? -Infinity,
253 ...window.map((change) => change.createdAt),
254 )
255 // Listed refs drop out once they fall behind the next run's window.
256 const keep = [...state.listed, ...listed]
257 .filter((ref) => ref.createdAt >= highWater - LOOKBACK_SECONDS)
258 .map(({ id, createdAt }) => ({ id, createdAt }))
259 .sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1))
260 return {
261 listed,
262 state: {
263 latestChange,
264 highWater: Number.isFinite(highWater) ? highWater : null,
265 listed: keep,
266 },
267 }
268}
269
270export function commitMessage(
271 seeded: boolean,
272 latest: ChangeRef | null,
273 listed: Array<FeedChange>,
274): string {
275 if (seeded) {
276 return latest === null
277 ? 'Catalog snapshot (no changes recorded yet)\n'
278 : `Catalog snapshot up to change ${latest.id}\n`
279 }
280 if (listed.length === 0) return 'Catalog refresh (no new /v1/changes)\n'
281 const lines = listed.map((c) => `- ${c.id} ${c.type}: ${c.summary}`)
282 return `Catalog: ${listed.length} change${listed.length === 1 ? '' : 's'}\n\n/v1/changes ids recorded since the last mirror commit:\n${lines.join('\n')}\n`
283}
284
285async function readOptional(path: string): Promise<string | null> {
286 return readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => {
287 if (error.code === 'ENOENT') return null
288 throw error
289 })
290}
291
292async function countEntityFiles(dir: string): Promise<number> {
293 let count = 0
294 for (const entity of ENTITY_DIRS) {
295 const names = await readdir(join(dir, entity), { recursive: true }).catch(
296 (error: NodeJS.ErrnoException) => {
297 if (error.code === 'ENOENT') return []
298 throw error
299 },
300 )
301 count += names.filter((name) => name.endsWith('.json')).length
302 }
303 return count
304}
305
306async function main() {
307 const [dir] = process.argv.slice(2)
308 const adminKey = process.env.MODELSCHEMAS_ADMIN_KEY
309 if (!dir || !adminKey) {
310 fail(
311 'usage: MODELSCHEMAS_ADMIN_KEY=… node scripts/mirror-catalog.ts <data-repo-dir>',
312 )
313 }
314 const base =
315 process.env.MODELSCHEMAS_URL ?? 'https://modelschemas.openstory.workers.dev'
316 const get = async (path: string): Promise<unknown> => {
317 const response = await fetch(new URL(path, base), {
318 headers: { 'X-Admin-Key': adminKey },
319 })
320 if (!response.ok) {
321 fail(`GET ${path}: ${response.status} ${await response.text()}`)
322 }
323 // A stream error mid-body makes this throw, so a cut body writes nothing.
324 return response.json()
325 }
326
327 const stateText = await readOptional(join(dir, FEED_FILE))
328 const state = parseFeedState(stateText)
329
330 const body = parseExport(await get('/v1/admin/export'))
331 const files = mirrorFiles(body)
332 refuseRun(
333 state.latestChange,
334 body.latestChange,
335 await countEntityFiles(dir),
336 files.size,
337 process.env.MIRROR_ALLOW_SHRINK === '1',
338 )
339
340 // Read the feed before touching the tree: a failure leaves it as it was.
341 // A first run lists nothing and starts the window at the newest change.
342 const since =
343 state.highWater === null
344 ? (body.latestChange?.createdAt ?? null)
345 : state.highWater - LOOKBACK_SECONDS
346 const window: Array<FeedChange> = []
347 if (since !== null) {
348 let next: string | null = `/v1/changes?since=${since}&limit=200`
349 while (next) {
350 const page = parseFeedPage(await get(next))
351 window.push(...page.changes)
352 next = page.nextCursor
353 ? `/v1/changes?since=${since}&limit=200&cursor=${encodeURIComponent(page.nextCursor)}`
354 : null
355 }
356 }
357 const seeded = stateText === null
358 const result = newChanges(state, window, body.latestChange)
359
360 for (const entity of ENTITY_DIRS) {
361 await rm(join(dir, entity), { recursive: true, force: true })
362 }
363 for (const [path, contents] of files) {
364 await mkdir(dirname(join(dir, path)), { recursive: true })
365 await writeFile(join(dir, path), contents)
366 }
367 await writeFile(join(dir, FEED_FILE), pretty(result.state))
368 process.stdout.write(commitMessage(seeded, body.latestChange, result.listed))
369}
370
371if (import.meta.main) await main()