@fabrika/auth-core 0.9.0-dev.4 → 0.9.0-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ops.ts ADDED
@@ -0,0 +1,1699 @@
1
+ // The ops wire (ADR-0069): the one platform-composed row through which Control reaches an application environment's
2
+ // object on Cloudflare, the requests it sends there and the answers the object gives. Control and the framework both
3
+ // import it, so the two sides parse one shape. Every parser is strict: an unknown key, a missing field or a wrong type
4
+ // refuses the whole value.
5
+
6
+ import { isDigest } from './endpoint-digest'
7
+ import { FRAMEWORK_RELEASE_PATTERN } from './framework-release'
8
+ import { prop } from './json'
9
+ import { sha256Hex } from './sha256'
10
+ import { WORKLOAD_NAME } from './workloads'
11
+
12
+ /** Every ops request's path lies under this prefix, on the environment's own domain. */
13
+ export const OPS_PREFIX = '/__fabrika/ops/'
14
+
15
+ /**
16
+ * The fixed id of the composed row. An authored endpoint id starts with a letter, so no contract can take it. The row's
17
+ * digest is not a constant: proxy-core computes it where every row is digested, from these fields.
18
+ */
19
+ export const OPS_ROW_ID = '__fabrika.ops'
20
+
21
+ /** The composed row's path. */
22
+ export const OPS_ROW_PATH = `${OPS_PREFIX}*`
23
+
24
+ /** The composed row's method. */
25
+ export const OPS_METHOD = 'POST'
26
+
27
+ /** The one content type the composed row admits. */
28
+ export const OPS_CONTENT_TYPE = 'application/json'
29
+
30
+ /** The operations the object serves, each at `opsPath(operation)`. */
31
+ export const OPS_OPERATIONS = ['inspect', 'state', 'migrate', 'export', 'import', 'restore', 'timers'] as const
32
+
33
+ export type OpsOperation = (typeof OPS_OPERATIONS)[number]
34
+
35
+ export function opsPath(operation: OpsOperation): string {
36
+ return `${OPS_PREFIX}${operation}`
37
+ }
38
+
39
+ /** The operation a request path names, or `null` for any other path, which gets `opsRefusal()`. */
40
+ export function parseOpsOperation(path: string): OpsOperation | null {
41
+ return OPS_OPERATIONS.find((operation) => opsPath(operation) === path) ?? null
42
+ }
43
+
44
+ /**
45
+ * The one answer inside the prefix to a missing or wrong key, a wrong endpoint header, an unknown operation and a
46
+ * refused object name: the same status, no body and no headers, so none of them tells the caller which it was.
47
+ */
48
+ export const OPS_REFUSAL_STATUS = 404
49
+
50
+ export function opsRefusal(): Response {
51
+ return new Response(null, { status: OPS_REFUSAL_STATUS })
52
+ }
53
+
54
+ /** Ops key digests: `sha256:<64 hex>` of each key, joined by `,`; one, or two while a rotation reconciles. */
55
+ export type OpsKeyDigests = readonly [string] | readonly [string, string]
56
+
57
+ /** The digest of an ops key, the only form the object holds (`FABRIKA_OPS_KEY_DIGESTS`). */
58
+ export function opsKeyDigest(key: string): string {
59
+ return `sha256:${sha256Hex(key)}`
60
+ }
61
+
62
+ /** The value of `FABRIKA_OPS_KEY_DIGESTS`, or `null` unless it holds one or two distinct digests. */
63
+ export function parseOpsKeyDigests(value: string): OpsKeyDigests | null {
64
+ const [first, second, ...rest] = value.split(',')
65
+ if (first === undefined || !isDigest(first) || rest.length > 0) return null
66
+ if (second === undefined) return [first]
67
+ return isDigest(second) && second !== first ? [first, second] : null
68
+ }
69
+
70
+ /** The value Control writes into `FABRIKA_OPS_KEY_DIGESTS`; throws on a list `parseOpsKeyDigests` would refuse. */
71
+ export function formatOpsKeyDigests(digests: OpsKeyDigests): string {
72
+ const value = digests.join(',')
73
+ if (parseOpsKeyDigests(value) === null) throw new Error('ops key digests must be one or two distinct sha256 digests')
74
+ return value
75
+ }
76
+
77
+ /** The object of ordinary traffic without `FABRIKA_APPLICATION_OBJECT`, and the only one an ops request may name then. */
78
+ export const DEFAULT_APPLICATION_OBJECT = 'application'
79
+
80
+ /** The most names `FABRIKA_APPLICATION_OBJECTS` holds. */
81
+ export const MAX_APPLICATION_OBJECTS = 16
82
+
83
+ /** An object name: lowercase, at most 63 characters, safe as one segment of an R2 key. */
84
+ const APPLICATION_OBJECT_NAME = /^[a-z][a-z0-9-]{0,62}$/
85
+
86
+ export function parseApplicationObjectName(value: unknown): string | null {
87
+ return typeof value === 'string' && APPLICATION_OBJECT_NAME.test(value) ? value : null
88
+ }
89
+
90
+ /** The object of ordinary traffic, and the objects an ops request may name, which include it. */
91
+ export interface ApplicationObjects {
92
+ readonly object: string
93
+ readonly objects: readonly string[]
94
+ }
95
+
96
+ /**
97
+ * `FABRIKA_APPLICATION_OBJECT` and `FABRIKA_APPLICATION_OBJECTS` (distinct names joined by `,`, 1 to 16, holding the
98
+ * first), or `null`. Without either the object is `application`; a deploy writes both, so one alone is refused.
99
+ */
100
+ export function parseApplicationObjects(object: string | undefined, objects: string | undefined): ApplicationObjects | null {
101
+ if (object === undefined && objects === undefined) return { object: DEFAULT_APPLICATION_OBJECT, objects: [DEFAULT_APPLICATION_OBJECT] }
102
+ if (object === undefined || objects === undefined || parseApplicationObjectName(object) === null) return null
103
+ const names = objects.split(',')
104
+ const valid = names.length <= MAX_APPLICATION_OBJECTS && names.every((name) => parseApplicationObjectName(name) !== null)
105
+ return valid && new Set(names).size === names.length && names.includes(object) ? { object, objects: names } : null
106
+ }
107
+
108
+ /** The R2 key, in the environment's bucket, of the maintenance state of `object`. */
109
+ export function OPS_STATE_KEY(object: string): string {
110
+ if (parseApplicationObjectName(object) === null) throw new Error('an ops state key needs a valid object name')
111
+ return `__fabrika/ops/${object}.json`
112
+ }
113
+
114
+ /** The maintenance modes, from the most permissive. */
115
+ export const OPS_MODES = ['open', 'read-only', 'closed', 'inspect'] as const
116
+
117
+ export type OpsMode = (typeof OPS_MODES)[number]
118
+
119
+ /** A table's row count is capped here: a full count bills every row read. A count at the cap means at least the cap. */
120
+ export const OPS_ROW_COUNT_CAP = 100_000
121
+
122
+ /** `POST /__fabrika/ops/inspect`: the projection, or with `content` the content-bearing view (`data.content.read`). */
123
+ export interface OpsInspectRequest {
124
+ readonly object: string
125
+ readonly content: boolean
126
+ }
127
+
128
+ /** `POST /__fabrika/ops/state`: a maintenance transition under a generation Control allocated. */
129
+ export interface OpsStateRequest {
130
+ readonly object: string
131
+ readonly generation: number
132
+ readonly mode: OpsMode
133
+ }
134
+
135
+ /** Sent once the state is published and the drain is over; `stillRunning` counts what ran past the drain's bound. */
136
+ export interface OpsStateAck {
137
+ readonly generation: number
138
+ readonly mode: OpsMode
139
+ readonly stillRunning: number
140
+ }
141
+
142
+ /** `POST /__fabrika/ops/migrate`: run the pending migrations under the published generation. */
143
+ export interface OpsMigrateRequest {
144
+ readonly object: string
145
+ readonly generation: number
146
+ }
147
+
148
+ /** The state a transition is judged against: the object's current generation and mode, `null` before the first. */
149
+ export interface OpsPublishedState {
150
+ readonly generation: number
151
+ readonly mode: OpsMode
152
+ }
153
+
154
+ /**
155
+ * Whether a transition is stale: a lower generation, or the same with another mode. The same generation and mode is a
156
+ * retry, which the object replays.
157
+ */
158
+ export function opsTransitionRefused(current: OpsPublishedState | null, request: OpsPublishedState): boolean {
159
+ if (current === null) return false
160
+ return request.generation < current.generation || (request.generation === current.generation && request.mode !== current.mode)
161
+ }
162
+
163
+ /** The status of a stale refusal. It is answered only after authentication, so it may say what is published. */
164
+ export const OPS_STALE_STATUS = 409
165
+
166
+ /** The body of a stale refusal of a transition or a migration. */
167
+ export interface OpsStaleRefusal {
168
+ readonly refused: 'stale_generation'
169
+ readonly published: OpsPublishedState | null
170
+ }
171
+
172
+ /** One row of the object's migration ledger. */
173
+ export interface OpsMigration {
174
+ readonly bundle: string
175
+ readonly name: string
176
+ readonly checksum: string
177
+ readonly appliedAt: string
178
+ }
179
+
180
+ /** Sent once the migrations ran and the application booted, with the new ledger. */
181
+ export interface OpsMigrateAck {
182
+ readonly generation: number
183
+ readonly migrations: readonly OpsMigration[]
184
+ }
185
+
186
+ export interface OpsMaintenance {
187
+ readonly mode: OpsMode
188
+ /** `null` while no transition was ever published: the object is `open`. */
189
+ readonly generation: number | null
190
+ /** Whether R2 holds this state; `false` while its put is pending. */
191
+ readonly published: boolean
192
+ }
193
+
194
+ export interface OpsTableCount {
195
+ readonly name: string
196
+ /** At most `OPS_ROW_COUNT_CAP`. */
197
+ readonly rows: number
198
+ }
199
+
200
+ export interface OpsDatabase {
201
+ readonly sizeBytes: number
202
+ readonly tables: readonly OpsTableCount[]
203
+ }
204
+
205
+ export interface OpsScheduler {
206
+ /** The current alarm, or `null` when none is set. */
207
+ readonly alarm: string | null
208
+ }
209
+
210
+ /** A job's last run and its outcome: a contract job, or a framework job such as `fabrika-file-sweep`. */
211
+ export interface OpsJob {
212
+ readonly job: string
213
+ readonly lastStatus: 'succeeded' | 'failed' | null
214
+ readonly lastStartedAt: string | null
215
+ readonly lastFinishedAt: string | null
216
+ readonly lastDurationMs: number | null
217
+ }
218
+
219
+ export type OpsFileStatus = 'pending' | 'quarantined' | 'live' | 'rejected'
220
+
221
+ export interface OpsFileCount {
222
+ readonly kind: string
223
+ readonly status: OpsFileStatus
224
+ readonly count: number
225
+ }
226
+
227
+ /** A delivery is `claimed` while it holds a lease, `completed` once its handler's transaction cleared it. */
228
+ export interface OpsWebhookCount {
229
+ readonly webhook: string
230
+ readonly state: 'claimed' | 'completed'
231
+ readonly count: number
232
+ }
233
+
234
+ export interface OpsBootFailure {
235
+ readonly at: string
236
+ }
237
+
238
+ /** The boot failure with the application's error text, which is content. */
239
+ export interface OpsBootFailureContent extends OpsBootFailure {
240
+ readonly message: string
241
+ readonly stack: string | null
242
+ }
243
+
244
+ /**
245
+ * The allowlisted projection (`data.read`): counts, sizes, timestamps, the identifiers the platform or the contract
246
+ * names, and status codes. Every timestamp is ISO 8601 in UTC with milliseconds.
247
+ */
248
+ export interface OpsView {
249
+ readonly release: string
250
+ readonly maintenance: OpsMaintenance
251
+ readonly database: OpsDatabase
252
+ readonly migrations: readonly OpsMigration[]
253
+ readonly scheduler: OpsScheduler
254
+ readonly jobs: readonly OpsJob[]
255
+ readonly files: readonly OpsFileCount[]
256
+ readonly webhooks: readonly OpsWebhookCount[]
257
+ readonly bootFailure: OpsBootFailure | null
258
+ }
259
+
260
+ /** The view a `data.content.read` caller gets: the projection, with the application's error text. */
261
+ export interface OpsContentView extends Omit<OpsView, 'bootFailure'> {
262
+ readonly bootFailure: OpsBootFailureContent | null
263
+ }
264
+
265
+ // A request's `object` is only well-formed here; the handler refuses a name its list does not hold with `opsRefusal()`.
266
+ export function parseOpsInspectRequest(body: unknown): OpsInspectRequest | null {
267
+ const object = parseApplicationObjectName(prop(body, 'object'))
268
+ const content = prop(body, 'content')
269
+ return exactKeys(body, ['object', 'content']) && object !== null && typeof content === 'boolean' ? { object, content } : null
270
+ }
271
+
272
+ export function parseOpsStateRequest(body: unknown): OpsStateRequest | null {
273
+ if (!exactKeys(body, ['object', 'generation', 'mode'])) return null
274
+ const object = parseApplicationObjectName(prop(body, 'object'))
275
+ const generation = readGeneration(prop(body, 'generation'))
276
+ const mode = readMode(prop(body, 'mode'))
277
+ return object === null || generation === null || mode === null ? null : { object, generation, mode }
278
+ }
279
+
280
+ export function parseOpsStateAck(body: unknown): OpsStateAck | null {
281
+ if (!exactKeys(body, ['generation', 'mode', 'stillRunning'])) return null
282
+ const generation = readGeneration(prop(body, 'generation'))
283
+ const mode = readMode(prop(body, 'mode'))
284
+ const stillRunning = readCount(prop(body, 'stillRunning'))
285
+ return generation === null || mode === null || stillRunning === null ? null : { generation, mode, stillRunning }
286
+ }
287
+
288
+ export function parseOpsMigrateRequest(body: unknown): OpsMigrateRequest | null {
289
+ const object = parseApplicationObjectName(prop(body, 'object'))
290
+ const generation = readGeneration(prop(body, 'generation'))
291
+ return exactKeys(body, ['object', 'generation']) && object !== null && generation !== null ? { object, generation } : null
292
+ }
293
+
294
+ export function parseOpsStaleRefusal(body: unknown): OpsStaleRefusal | null {
295
+ if (!exactKeys(body, ['refused', 'published']) || prop(body, 'refused') !== 'stale_generation') return null
296
+ const raw = prop(body, 'published')
297
+ if (raw === null) return { refused: 'stale_generation', published: null }
298
+ if (!exactKeys(raw, ['generation', 'mode'])) return null
299
+ const generation = readGeneration(prop(raw, 'generation'))
300
+ const mode = readMode(prop(raw, 'mode'))
301
+ return generation === null || mode === null ? null : { refused: 'stale_generation', published: { generation, mode } }
302
+ }
303
+
304
+ export function parseOpsMigrateAck(body: unknown): OpsMigrateAck | null {
305
+ if (!exactKeys(body, ['generation', 'migrations'])) return null
306
+ const generation = readGeneration(prop(body, 'generation'))
307
+ const migrations = readList(prop(body, 'migrations'), readMigration)
308
+ return generation === null || migrations === null ? null : { generation, migrations }
309
+ }
310
+
311
+ export function parseOpsView(body: unknown): OpsView | null {
312
+ const failure = prop(body, 'bootFailure')
313
+ const bootFailure = failure === null ? null : readBootFailure(failure)
314
+ if (bootFailure === undefined) return null
315
+ const view = readViewFields(body)
316
+ return view === null ? null : { ...view, bootFailure }
317
+ }
318
+
319
+ export function parseOpsContentView(body: unknown): OpsContentView | null {
320
+ const failure = prop(body, 'bootFailure')
321
+ const bootFailure = failure === null ? null : readBootFailureContent(failure)
322
+ if (bootFailure === undefined) return null
323
+ const view = readViewFields(body)
324
+ return view === null ? null : { ...view, bootFailure }
325
+ }
326
+
327
+ // Dumps (ADR-0070): a consistent backup or a diagnostic export of an object's SQLite, which Control writes step by step
328
+ // into the environment's bucket, and the importer that loads a consistent one into a fresh object. No type here carries
329
+ // a row's values or a file's bytes, except the line and row encodings, which only the object and a download read.
330
+
331
+ /** The version of the dump format: the value, row and line encodings, the table hash and the manifest. */
332
+ export const OPS_DUMP_FORMAT = 1
333
+
334
+ /** The most rows one keyset page reads. */
335
+ export const OPS_DUMP_PAGE_ROWS = 1000
336
+
337
+ /**
338
+ * The size of every part of a dump's data object but the last, which is at most this. R2 refuses a multipart upload
339
+ * whose parts differ in size, and a part below 5 MiB; a 2 MB row, its text and blobs as hex, fits one part uncompressed.
340
+ */
341
+ export const OPS_DUMP_PART_SIZE = 8 * 1024 * 1024
342
+
343
+ /**
344
+ * The most bytes one part decompresses to: its lines, each with its newline. An import step holds a part's every form
345
+ * at once (compressed, decompressed, the lines, the values, the bound bytes), so this bounds its memory well inside an
346
+ * isolate's 128 MB.
347
+ */
348
+ export const OPS_DUMP_PART_MAX_RAW_BYTES = 16 * 1024 * 1024
349
+
350
+ /** The most rows one part holds, which bounds the inserts, and the link updates, of one import step. */
351
+ export const OPS_DUMP_PART_MAX_ROWS = 50_000
352
+
353
+ /** R2's most parts in one multipart upload. */
354
+ export const OPS_DUMP_MAX_PARTS = 10_000
355
+
356
+ /** The largest manifest a reader accepts, in UTF-8 bytes. */
357
+ export const OPS_DUMP_MANIFEST_MAX_BYTES = 4 * 1024 * 1024
358
+
359
+ /** The object a scheduled backup is rehearsed in. Every deploy at a gated release lists it; nothing serves from it. */
360
+ export const OPS_REHEARSAL_OBJECT = 'rehearsal'
361
+
362
+ /** A dump: the object it was taken from, the id Control gave it (a UUID), and whether it is a consistent backup. */
363
+ export interface OpsDumpRef {
364
+ readonly object: string
365
+ readonly dump: string
366
+ readonly consistent: boolean
367
+ }
368
+
369
+ /** The R2 key of a dump's data or manifest: a consistent backup under `__fabrika/backups/`, a diagnostic export under `__fabrika/exports/`. */
370
+ export function OPS_DUMP_KEY(ref: OpsDumpRef, file: 'data' | 'manifest'): string {
371
+ if (parseApplicationObjectName(ref.object) === null || !UUID.test(ref.dump)) throw new Error('a dump key needs a valid object name and dump id')
372
+ return `__fabrika/${ref.consistent ? 'backups' : 'exports'}/${ref.object}/${ref.dump}/${file === 'data' ? 'data.ndjson.gz' : 'manifest.json'}`
373
+ }
374
+
375
+ /**
376
+ * One stored value, as `typeof()` names it. An integer travels as its decimal text, because workerd reads an int64 into
377
+ * a double; a real travels as the double workerd reads exactly. Text and a blob travel as the upper-case hex of their
378
+ * bytes, so text that is not valid UTF-8 keeps every byte.
379
+ */
380
+ export type OpsDumpValue =
381
+ | null
382
+ | { readonly type: 'integer'; readonly value: string }
383
+ | { readonly type: 'real'; readonly value: number }
384
+ | { readonly type: 'text'; readonly value: string }
385
+ | { readonly type: 'blob'; readonly value: string }
386
+
387
+ /**
388
+ * The two result columns a dump reads for `column`: `typeof()` and the value in the form `readOpsDumpValue` takes, an
389
+ * integer as `CAST(c AS TEXT)`, a real as itself, text as `hex(CAST(c AS BLOB))` and a blob as `hex(c)`.
390
+ */
391
+ export function opsDumpColumnProjection(column: string): string {
392
+ const c = quoteIdentifier(column)
393
+ return `typeof(${c}), CASE typeof(${c}) WHEN 'integer' THEN CAST(${c} AS TEXT) WHEN 'real' THEN ${c} WHEN 'text' THEN hex(CAST(${c} AS BLOB)) WHEN 'blob' THEN hex(${c}) END`
394
+ }
395
+
396
+ /** The value `opsDumpColumnProjection` read. Throws, naming no value, on a pair it would not produce. */
397
+ export function readOpsDumpValue(type: unknown, value: unknown): OpsDumpValue {
398
+ if (type === 'null' && value === null) return null
399
+ if (type === 'integer' && typeof value === 'string' && isInt64Text(value)) return { type, value }
400
+ if (type === 'real' && typeof value === 'number' && !Number.isNaN(value)) return { type, value }
401
+ if ((type === 'text' || type === 'blob') && typeof value === 'string' && isBytesHex(value)) return { type, value }
402
+ throw new Error('a projected dump value does not match its type')
403
+ }
404
+
405
+ /**
406
+ * The most result columns, and the most parameters, one statement of workerd's SQLite takes; a table holds at most as
407
+ * many columns.
408
+ */
409
+ export const OPS_SQLITE_MAX_COLUMNS = 100
410
+
411
+ /** The most columns of a table one statement of a page read projects: two result columns each, beside the rowid twice. */
412
+ export const OPS_DUMP_READ_COLUMNS = (OPS_SQLITE_MAX_COLUMNS - 2) / 2
413
+
414
+ /** One row of a keyset page: its rowid as decimal text, then the rowid and every column as the dump writes them. */
415
+ export interface OpsDumpPageRow {
416
+ readonly rowid: string
417
+ readonly values: readonly OpsDumpValue[]
418
+ }
419
+
420
+ /** Runs one statement of a page read, with the parameters of the read's condition, and answers its rows. */
421
+ export type OpsDumpPageQuery = (sql: string) => readonly Readonly<Record<string, unknown>>[]
422
+
423
+ /**
424
+ * One keyset page of `table`: the first `limit` rows by rowid that `condition` (`WHERE …`, or empty) admits, read the
425
+ * way the producer and the importer's verification both read them. Each column reads as two result columns, so a table
426
+ * wider than `OPS_DUMP_READ_COLUMNS` reads in several statements over the same rows, which the caller runs in one
427
+ * synchronous turn, so no write falls between them. The common table expression names every result column, which an
428
+ * expression alone does not.
429
+ */
430
+ export function readOpsDumpPage(query: OpsDumpPageQuery, table: OpsDumpTablePlan, condition: string, limit: number): OpsDumpPageRow[] {
431
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('a dump page reads at least one row')
432
+ const keyset = quoteIdentifier(table.keyset)
433
+ const reads: { readonly start: number; readonly count: number; readonly rows: readonly Readonly<Record<string, unknown>>[] }[] = []
434
+ for (let start = 0; start === 0 || start < table.columns.length; start += OPS_DUMP_READ_COLUMNS) {
435
+ const columns = table.columns.slice(start, start + OPS_DUMP_READ_COLUMNS)
436
+ const names = columns.flatMap((_, offset) => [`t${start + offset}`, `v${start + offset}`])
437
+ const projections = [keyset, `CAST(${keyset} AS TEXT)`, ...columns.map(opsDumpColumnProjection)]
438
+ const rows = query(
439
+ `WITH page(${['k', 'r', ...names].join(', ')}) AS (SELECT ${projections.join(', ')} FROM main.${quoteIdentifier(table.name)} ${condition}
440
+ ORDER BY ${keyset} LIMIT ${limit}) SELECT ${['r', ...names].join(', ')} FROM page ORDER BY k`,
441
+ )
442
+ reads.push({ start, count: columns.length, rows })
443
+ }
444
+ const first = reads[0]?.rows ?? []
445
+ if (reads.some(({ rows }) => rows.length !== first.length)) throw new Error('the reads of one dump page disagree on its rows')
446
+ return first.map((row, index) => {
447
+ const rowid = readOpsDumpValue('integer', row['r'])
448
+ if (rowid === null || rowid.type !== 'integer') throw new Error('a rowid reads as an integer')
449
+ const values: OpsDumpValue[] = [rowid]
450
+ for (const { start, count, rows } of reads) {
451
+ const read = rows[index]
452
+ if (read?.['r'] !== rowid.value) throw new Error('the reads of one dump page disagree on its rows')
453
+ for (let column = start; column < start + count; column++) {
454
+ values.push(readOpsDumpValue(read[`t${column}`], read[`v${column}`]))
455
+ }
456
+ }
457
+ return { rowid: rowid.value, values }
458
+ })
459
+ }
460
+
461
+ /**
462
+ * The SQL that names a dump's rowid inline, so a row of a table at `OPS_SQLITE_MAX_COLUMNS` binds no more parameters
463
+ * than it has columns. It is the checked decimal text in a string literal, cast as `opsDumpValueBinding` casts it.
464
+ */
465
+ export function opsDumpRowidSql(rowid: OpsDumpValue): string {
466
+ if (rowid === null || rowid.type !== 'integer' || !isInt64Text(rowid.value)) throw new Error('a dump rowid must be an integer')
467
+ return `CAST('${rowid.value}' AS INTEGER)`
468
+ }
469
+
470
+ /** What a statement binds for one value of a dump. */
471
+ export type OpsDumpParam = string | number | Uint8Array | null
472
+
473
+ /** The SQL expression that writes a value back and the parameter its `?` binds. */
474
+ export interface OpsDumpBinding {
475
+ readonly sql: string
476
+ readonly param: OpsDumpParam
477
+ }
478
+
479
+ /**
480
+ * How the importer writes a value back, a rowid included, without a double or a JavaScript string in between: an
481
+ * integer as its decimal text through `CAST(? AS INTEGER)`, a real through `CAST(? AS REAL)` (a binder may bind an
482
+ * integral double as an integer), text as its bytes through `CAST(? AS TEXT)`, and a blob as its bytes.
483
+ */
484
+ export function opsDumpValueBinding(value: OpsDumpValue): OpsDumpBinding {
485
+ if (value === null) return { sql: '?', param: null }
486
+ switch (value.type) {
487
+ case 'integer':
488
+ return { sql: 'CAST(? AS INTEGER)', param: value.value }
489
+ case 'real':
490
+ return { sql: 'CAST(? AS REAL)', param: value.value }
491
+ case 'text':
492
+ return { sql: 'CAST(? AS TEXT)', param: hexBytes(value.value) }
493
+ case 'blob':
494
+ return { sql: '?', param: hexBytes(value.value) }
495
+ }
496
+ }
497
+
498
+ /**
499
+ * The canonical encoding of a row, the text a table hash is computed over: a JSON array (`JSON.stringify`, so no
500
+ * whitespace) of `null` or a tagged string per value, `i:<decimal>`, `r:<shortest round-trip double>`, `t:<HEX>` or
501
+ * `b:<HEX>`. A real keeps `-0`, `Infinity` and `-Infinity`; NaN is never stored. Throws, naming no value, on a value
502
+ * outside these rules.
503
+ */
504
+ export function encodeOpsDumpRow(values: readonly OpsDumpValue[]): string {
505
+ return JSON.stringify(values.map(encodeValue))
506
+ }
507
+
508
+ /** The values of a row's canonical encoding, or `null` for any other text, a different spelling of the same row included. */
509
+ export function decodeOpsDumpRow(text: string): readonly OpsDumpValue[] | null {
510
+ const values = readRowValues(parseJson(text))
511
+ return values !== null && encodeOpsDumpRow(values) === text ? values : null
512
+ }
513
+
514
+ /** One line of a dump's NDJSON: a table's row, which is its rowid, then every column that is not generated. */
515
+ export interface OpsDumpLine {
516
+ readonly table: string
517
+ readonly row: readonly OpsDumpValue[]
518
+ }
519
+
520
+ /** The line `{"table":"<name>","row":<canonical row>}`. Throws on a table name outside the data layer's identifier rule. */
521
+ export function encodeOpsDumpLine(line: OpsDumpLine): string {
522
+ if (!TABLE_NAME.test(line.table)) throw new Error('a dump line needs a plain table name')
523
+ return `{"table":${JSON.stringify(line.table)},"row":${encodeOpsDumpRow(line.row)}}`
524
+ }
525
+
526
+ /** A line, or `null` for anything `encodeOpsDumpLine` would not write. */
527
+ export function decodeOpsDumpLine(text: string): OpsDumpLine | null {
528
+ const parsed = parseJson(text)
529
+ if (!exactKeys(parsed, ['table', 'row'])) return null
530
+ const table = readMatch(prop(parsed, 'table'), TABLE_NAME)
531
+ const row = readRowValues(prop(parsed, 'row'))
532
+ if (table === null || row === null) return null
533
+ return encodeOpsDumpLine({ table, row }) === text ? { table, row } : null
534
+ }
535
+
536
+ /** The hash of a table without rows: the SHA-256 of the empty string. */
537
+ export const OPS_EMPTY_TABLE_HASH = sha256Hex('')
538
+
539
+ /**
540
+ * Folds rows, each in its canonical encoding and in keyset order, into a table's hash. Each row's step is the SHA-256 of
541
+ * the previous hash's hex, a newline and the row, so a table read page by page, across steps, folds to one value.
542
+ */
543
+ export function foldOpsTableHash(hash: string, rows: Iterable<string>): string {
544
+ if (!SHA256_HEX.test(hash)) throw new Error('a table hash is 64 lower-case hex digits')
545
+ let current = hash
546
+ for (const row of rows) current = sha256Hex(`${current}\n${row}`)
547
+ return current
548
+ }
549
+
550
+ /** A column as `PRAGMA table_xinfo` describes it. */
551
+ export interface OpsDumpSchemaColumn {
552
+ readonly name: string
553
+ /** The declared type, as written. */
554
+ readonly type: string
555
+ readonly notNull: boolean
556
+ /** The column's position in the primary key from 1, `0` outside it. */
557
+ readonly primaryKey: number
558
+ /** A generated column (`hidden` 2 or 3), which a dump does not carry. */
559
+ readonly generated: boolean
560
+ }
561
+
562
+ /** An index as `PRAGMA index_list` and `PRAGMA index_xinfo` (its key columns) describe it. */
563
+ export interface OpsDumpSchemaIndex {
564
+ readonly unique: boolean
565
+ readonly origin: 'c' | 'u' | 'pk'
566
+ readonly partial: boolean
567
+ /** The key columns in order, `null` for an expression. */
568
+ readonly columns: readonly (string | null)[]
569
+ }
570
+
571
+ /** A foreign key as `PRAGMA foreign_key_list` describes it, its rows grouped by `id` and ordered by `seq`. */
572
+ export interface OpsDumpSchemaForeignKey {
573
+ readonly parent: string
574
+ readonly columns: readonly string[]
575
+ /** The parent's columns (`to`), or `null` when the key names the parent's primary key implicitly. */
576
+ readonly references: readonly string[] | null
577
+ /**
578
+ * Whether the key is `DEFERRABLE INITIALLY DEFERRED`. No PRAGMA reports it: a reader takes it from the table's SQL,
579
+ * and one that cannot tell which key a clause belongs to marks every key of that table.
580
+ */
581
+ readonly initiallyDeferred: boolean
582
+ }
583
+
584
+ /** A table as `PRAGMA table_list` (`type`, `wr`) and the PRAGMAs above describe it. */
585
+ export interface OpsDumpSchemaTable {
586
+ readonly name: string
587
+ readonly virtual: boolean
588
+ readonly withoutRowid: boolean
589
+ /** Whether the table's SQL declares a `CHECK` constraint; a reader that cannot tell answers `true`. */
590
+ readonly checked: boolean
591
+ readonly columns: readonly OpsDumpSchemaColumn[]
592
+ readonly indexes: readonly OpsDumpSchemaIndex[]
593
+ readonly foreignKeys: readonly OpsDumpSchemaForeignKey[]
594
+ }
595
+
596
+ /** Every table a dump holds: `sqlite_schema`'s tables but SQLite's internal ones, `sqlite_sequence` excepted, and `_cf_`'s. */
597
+ export interface OpsDumpSchema {
598
+ readonly tables: readonly OpsDumpSchemaTable[]
599
+ }
600
+
601
+ /** How one table is dumped and loaded. */
602
+ export interface OpsDumpTablePlan {
603
+ readonly name: string
604
+ /** The name that reads the rowid: the `INTEGER PRIMARY KEY` column, else the first of `rowid`, `_rowid_`, `oid` no column takes. */
605
+ readonly keyset: string
606
+ /** Every column that is not generated, in declaration order: a row is the rowid, then these. */
607
+ readonly columns: readonly string[]
608
+ /** The columns of the foreign keys inside a cycle, which a part writes `NULL` and the link pass sets, in declaration order. */
609
+ readonly deferred: readonly string[]
610
+ }
611
+
612
+ /** The tables of a dump in load order: every parent outside a table's own cycle comes before it. */
613
+ export interface OpsDumpPlan {
614
+ readonly tables: readonly OpsDumpTablePlan[]
615
+ }
616
+
617
+ /**
618
+ * The one rule both the producer, at export `begin`, and the importer, at import `begin`, apply to a schema: the plan
619
+ * a dump is written and loaded by, or an `unsupported_schema` refusal naming the table. A foreign key whose parent lies
620
+ * in its own table's cycle (the table itself included) is loaded `NULL` and linked once every row is in, so each of its
621
+ * columns must take a temporary `NULL`: nullable, outside the primary key, referenced by no foreign key, in a table
622
+ * without a `CHECK`, a `NOT NULL` generated column, or a partial or expression unique index. A `WITHOUT ROWID` or
623
+ * virtual table, a table without a name that reads its rowid, a foreign key to a table outside the dump or without the
624
+ * named key, and a foreign key checked only at commit are refused.
625
+ */
626
+ export function planOpsDump(schema: OpsDumpSchema): OpsDumpPlan | OpsDataRefusal {
627
+ const sorted = [...schema.tables].sort((left, right) => compareNames(left.name, right.name))
628
+ if (!sorted.every((table) => TABLE_NAME.test(table.name)) || !distinct(sorted.map((table) => table.name))) return unsupported(null)
629
+ const byName = new Map(sorted.map((table) => [table.name, table]))
630
+ const tables: DescribedTable[] = []
631
+ for (const table of sorted) {
632
+ const keyset = table.virtual || table.withoutRowid ? null : rowidName(table)
633
+ const parents = resolveForeignKeys(table, byName)
634
+ if (keyset === null || parents === null) return unsupported(table.name)
635
+ tables.push({ table, keyset, parents })
636
+ }
637
+ const cycle = cycleIds(tables)
638
+ const referenced = new Set(tables.flatMap(({ parents }) => parents.flatMap((key) => key.references.map((column) => columnKey(key.parent, column)))))
639
+ const plans: OpsDumpTablePlan[] = []
640
+ for (const { table, keyset, parents } of loadOrder(tables, cycle)) {
641
+ const inCycle = parents.filter((key) => cycle.get(key.parent) === cycle.get(table.name))
642
+ const deferredNames = new Set(inCycle.flatMap((key) => key.columns.map(asciiLower)))
643
+ const deferred = table.columns.filter((column) => deferredNames.has(asciiLower(column.name)))
644
+ if (deferred.length > 0 && !takesTemporaryNull(table, deferred, referenced)) return unsupported(table.name)
645
+ plans.push({
646
+ name: table.name,
647
+ keyset,
648
+ columns: table.columns.filter((column) => !column.generated).map((column) => column.name),
649
+ deferred: deferred.map((column) => column.name),
650
+ })
651
+ }
652
+ return { tables: plans }
653
+ }
654
+
655
+ /** Where a dump or a verification stands in a table: the last rowid read, and the count and hash folded so far. */
656
+ export interface OpsDumpCursor {
657
+ readonly table: string
658
+ /** The rowid of the last row read, as decimal text; `null` before the table's first row. */
659
+ readonly after: string | null
660
+ readonly rows: number
661
+ readonly hash: string
662
+ }
663
+
664
+ /** A table a dump holds, with its exact row count and its hash. */
665
+ export interface OpsDumpTable {
666
+ readonly name: string
667
+ readonly rows: number
668
+ readonly hash: string
669
+ }
670
+
671
+ /** A part of a dump's data object: its number from 1, its size in bytes and the SHA-256 hex of its bytes. */
672
+ export interface OpsDumpPart {
673
+ readonly part: number
674
+ readonly size: number
675
+ readonly sha256: string
676
+ }
677
+
678
+ /** A part as R2 accepted it; Control completes the upload with the ETags. */
679
+ export interface OpsUploadedPart extends OpsDumpPart {
680
+ readonly etag: string
681
+ }
682
+
683
+ /** One `sqlite_schema` entry with SQL: an automatic index has none and is not listed. */
684
+ export interface OpsDumpSchemaEntry {
685
+ readonly type: 'table' | 'index' | 'trigger' | 'view'
686
+ readonly name: string
687
+ readonly table: string
688
+ readonly sql: string
689
+ }
690
+
691
+ /** `manifest.json`, written beside the data once its upload completed. `tables` is in load order. */
692
+ export interface OpsDumpManifest {
693
+ readonly format: typeof OPS_DUMP_FORMAT
694
+ readonly dump: string
695
+ readonly object: string
696
+ readonly consistent: boolean
697
+ readonly createdAt: string
698
+ /** The object's bookmark when the dump began. */
699
+ readonly bookmark: string
700
+ readonly release: string
701
+ readonly contractDigest: string
702
+ readonly ddl: readonly OpsDumpSchemaEntry[]
703
+ readonly migrations: readonly OpsMigration[]
704
+ readonly tables: readonly OpsDumpTable[]
705
+ readonly parts: readonly OpsDumpPart[]
706
+ }
707
+
708
+ /**
709
+ * A manifest Control holds or an answer carries; every table's DDL lists it, its parts are whole, and its
710
+ * `JSON.stringify` is at most `OPS_DUMP_MANIFEST_MAX_BYTES` in UTF-8, wherever it came from.
711
+ */
712
+ export function parseOpsDumpManifest(body: unknown): OpsDumpManifest | null {
713
+ if (!exactKeys(body, MANIFEST_KEYS) || prop(body, 'format') !== OPS_DUMP_FORMAT) return null
714
+ const dump = readMatch(prop(body, 'dump'), UUID)
715
+ const object = parseApplicationObjectName(prop(body, 'object'))
716
+ const consistent = prop(body, 'consistent')
717
+ const createdAt = readTimestamp(prop(body, 'createdAt'))
718
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
719
+ const release = readMatch(prop(body, 'release'), FRAMEWORK_RELEASE_PATTERN)
720
+ const contractDigest = prop(body, 'contractDigest')
721
+ const ddl = readList(prop(body, 'ddl'), readSchemaEntry)
722
+ const migrations = readList(prop(body, 'migrations'), readMigration)
723
+ const tables = readTables(prop(body, 'tables'))
724
+ const parts = readWholeParts(prop(body, 'parts'), readDumpPart)
725
+ if (
726
+ dump === null || object === null || typeof consistent !== 'boolean' || createdAt === null || bookmark === null || release === null
727
+ || typeof contractDigest !== 'string' || !isDigest(contractDigest) || ddl === null || migrations === null || tables === null || parts === null
728
+ ) {
729
+ return null
730
+ }
731
+ const declared = ddl.filter((entry) => entry.type === 'table').map((entry) => entry.name)
732
+ if (!distinct(ddl.map((entry) => `${entry.type} ${entry.name}`)) || !sameNames(declared, tables.map((table) => table.name))) return null
733
+ const manifest: OpsDumpManifest = {
734
+ format: OPS_DUMP_FORMAT,
735
+ dump,
736
+ object,
737
+ consistent,
738
+ createdAt,
739
+ bookmark,
740
+ release,
741
+ contractDigest,
742
+ ddl,
743
+ migrations,
744
+ tables,
745
+ parts,
746
+ }
747
+ return utf8Length(JSON.stringify(manifest)) <= OPS_DUMP_MANIFEST_MAX_BYTES ? manifest : null
748
+ }
749
+
750
+ /** A manifest's text as R2 holds it, refused above `OPS_DUMP_MANIFEST_MAX_BYTES` before it is parsed. */
751
+ export function readOpsDumpManifest(text: string): OpsDumpManifest | null {
752
+ if (utf8Length(text) > OPS_DUMP_MANIFEST_MAX_BYTES) return null
753
+ return parseOpsDumpManifest(parseJson(text))
754
+ }
755
+
756
+ /** What every export step names: a consistent backup carries the published generation, a diagnostic export none. */
757
+ export interface OpsExportScope {
758
+ readonly object: string
759
+ readonly generation: number | null
760
+ readonly consistent: boolean
761
+ readonly dump: string
762
+ }
763
+
764
+ /** Starts the multipart upload of the dump's data. */
765
+ export interface OpsExportBegin extends OpsExportScope {
766
+ readonly step: 'begin'
767
+ }
768
+
769
+ /** Fills part `part` from `cursor`, `null` only for the first part; a retry replaces the part. */
770
+ export interface OpsExportPart extends OpsExportScope {
771
+ readonly step: 'part'
772
+ readonly uploadId: string
773
+ readonly part: number
774
+ readonly cursor: OpsDumpCursor | null
775
+ }
776
+
777
+ /** Completes the upload from the parts and tables Control recorded, and writes the manifest. */
778
+ export interface OpsExportComplete extends OpsExportScope {
779
+ readonly step: 'complete'
780
+ readonly uploadId: string
781
+ readonly bookmark: string
782
+ readonly parts: readonly OpsUploadedPart[]
783
+ readonly tables: readonly OpsDumpTable[]
784
+ }
785
+
786
+ /** `POST /__fabrika/ops/export`: one step of a dump. */
787
+ export type OpsExportRequest = OpsExportBegin | OpsExportPart | OpsExportComplete
788
+
789
+ export interface OpsExportBeginAck {
790
+ readonly step: 'begin'
791
+ readonly uploadId: string
792
+ readonly bookmark: string
793
+ }
794
+
795
+ /** The part written, the tables it finished in load order, and where the next part starts: `null` once all is read. */
796
+ export interface OpsExportPartAck {
797
+ readonly step: 'part'
798
+ readonly uploaded: OpsUploadedPart
799
+ readonly tables: readonly OpsDumpTable[]
800
+ readonly next: OpsDumpCursor | null
801
+ }
802
+
803
+ export interface OpsExportCompleteAck {
804
+ readonly step: 'complete'
805
+ readonly manifest: OpsDumpManifest
806
+ }
807
+
808
+ export function parseOpsExportRequest(body: unknown): OpsExportRequest | null {
809
+ const scope = readExportScope(body)
810
+ if (scope === null) return null
811
+ switch (prop(body, 'step')) {
812
+ case 'begin':
813
+ return exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step']) ? { ...scope, step: 'begin' } : null
814
+ case 'part': {
815
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'part', 'cursor'])) return null
816
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
817
+ const part = readPartNumber(prop(body, 'part'))
818
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
819
+ if (uploadId === null || part === null || cursor === undefined || (part === 1) !== (cursor === null)) return null
820
+ return { ...scope, step: 'part', uploadId, part, cursor }
821
+ }
822
+ case 'complete': {
823
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'bookmark', 'parts', 'tables'])) return null
824
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
825
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
826
+ const parts = readWholeParts(prop(body, 'parts'), readUploadedPart)
827
+ const tables = readTables(prop(body, 'tables'))
828
+ if (uploadId === null || bookmark === null || parts === null || tables === null) return null
829
+ return { ...scope, step: 'complete', uploadId, bookmark, parts, tables }
830
+ }
831
+ default:
832
+ return null
833
+ }
834
+ }
835
+
836
+ export function parseOpsExportBeginAck(body: unknown): OpsExportBeginAck | null {
837
+ if (!exactKeys(body, ['step', 'uploadId', 'bookmark']) || prop(body, 'step') !== 'begin') return null
838
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
839
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
840
+ return uploadId === null || bookmark === null ? null : { step: 'begin', uploadId, bookmark }
841
+ }
842
+
843
+ export function parseOpsExportPartAck(body: unknown): OpsExportPartAck | null {
844
+ if (!exactKeys(body, ['step', 'uploaded', 'tables', 'next']) || prop(body, 'step') !== 'part') return null
845
+ const uploaded = readUploadedPart(prop(body, 'uploaded'))
846
+ const tables = readTables(prop(body, 'tables'))
847
+ const next = readNullable(prop(body, 'next'), readCursor)
848
+ if (uploaded === null || tables === null || next === undefined || continuesFinished(tables, next)) return null
849
+ // Only the last part may be short: R2 refuses an upload whose other parts differ in size.
850
+ if (next !== null && uploaded.size !== OPS_DUMP_PART_SIZE) return null
851
+ return { step: 'part', uploaded, tables, next }
852
+ }
853
+
854
+ export function parseOpsExportCompleteAck(body: unknown): OpsExportCompleteAck | null {
855
+ if (!exactKeys(body, ['step', 'manifest']) || prop(body, 'step') !== 'complete') return null
856
+ const manifest = parseOpsDumpManifest(prop(body, 'manifest'))
857
+ return manifest === null ? null : { step: 'complete', manifest }
858
+ }
859
+
860
+ /** The consistent backup an import loads: always under `__fabrika/backups/`. */
861
+ export interface OpsDumpSource {
862
+ readonly object: string
863
+ readonly dump: string
864
+ }
865
+
866
+ /** What every import step names: the fresh target, published `inspect` under the operation's generation, and the backup. */
867
+ export interface OpsImportScope {
868
+ readonly object: string
869
+ readonly generation: number
870
+ readonly source: OpsDumpSource
871
+ }
872
+
873
+ /** Verifies the manifest, checks the target is fresh, and migrates it to the manifest's ledger. */
874
+ export interface OpsImportBegin extends OpsImportScope {
875
+ readonly step: 'begin'
876
+ }
877
+
878
+ /** Loads part `part`, writing a foreign key the load order cannot satisfy as `NULL`. */
879
+ export interface OpsImportPart extends OpsImportScope {
880
+ readonly step: 'part'
881
+ readonly part: number
882
+ }
883
+
884
+ /** Sets the foreign keys part `part` wrote as `NULL`, once every part is loaded. */
885
+ export interface OpsImportLink extends OpsImportScope {
886
+ readonly step: 'link'
887
+ readonly part: number
888
+ }
889
+
890
+ /** Reads the loaded tables back from `cursor`, `null` at the start, and compares counts and hashes with the manifest. */
891
+ export interface OpsImportVerify extends OpsImportScope {
892
+ readonly step: 'verify'
893
+ readonly cursor: OpsDumpCursor | null
894
+ }
895
+
896
+ /** Clears the import marker once every table verified, so Control may open the object. */
897
+ export interface OpsImportComplete extends OpsImportScope {
898
+ readonly step: 'complete'
899
+ }
900
+
901
+ /** Wipes an `inspect` object that holds an import marker and serves no traffic, with `deleteAll()`. */
902
+ export interface OpsImportDiscard {
903
+ readonly step: 'discard'
904
+ readonly object: string
905
+ readonly generation: number
906
+ }
907
+
908
+ /** `POST /__fabrika/ops/import`: one step of loading a consistent backup into a fresh object. */
909
+ export type OpsImportRequest = OpsImportBegin | OpsImportPart | OpsImportLink | OpsImportVerify | OpsImportComplete | OpsImportDiscard
910
+
911
+ export interface OpsImportBeginAck {
912
+ readonly step: 'begin'
913
+ readonly parts: number
914
+ }
915
+
916
+ /** `deferred` counts the loaded rows whose deferred foreign keys wait for the link pass. */
917
+ export interface OpsImportPartAck {
918
+ readonly step: 'part'
919
+ readonly part: number
920
+ readonly rows: number
921
+ readonly deferred: number
922
+ }
923
+
924
+ export interface OpsImportLinkAck {
925
+ readonly step: 'link'
926
+ readonly part: number
927
+ readonly rows: number
928
+ }
929
+
930
+ /** The tables verified in this step, each matching the manifest, and where the next step starts: `null` once all match. */
931
+ export interface OpsImportVerifyAck {
932
+ readonly step: 'verify'
933
+ readonly tables: readonly OpsDumpTable[]
934
+ readonly next: OpsDumpCursor | null
935
+ }
936
+
937
+ export interface OpsImportCompleteAck {
938
+ readonly step: 'complete'
939
+ readonly source: OpsDumpSource
940
+ }
941
+
942
+ export interface OpsImportDiscardAck {
943
+ readonly step: 'discard'
944
+ }
945
+
946
+ export function parseOpsImportRequest(body: unknown): OpsImportRequest | null {
947
+ const step = prop(body, 'step')
948
+ const object = parseApplicationObjectName(prop(body, 'object'))
949
+ const generation = readGeneration(prop(body, 'generation'))
950
+ if (object === null || generation === null) return null
951
+ if (step === 'discard') return exactKeys(body, ['step', 'object', 'generation']) ? { step, object, generation } : null
952
+ const source = readSource(prop(body, 'source'))
953
+ if (source === null) return null
954
+ const scope = { object, generation, source }
955
+ switch (step) {
956
+ case 'begin':
957
+ case 'complete':
958
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step']) ? { ...scope, step } : null
959
+ case 'part':
960
+ case 'link': {
961
+ const part = readPartNumber(prop(body, 'part'))
962
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'part']) && part !== null ? { ...scope, step, part } : null
963
+ }
964
+ case 'verify': {
965
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
966
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'cursor']) && cursor !== undefined ? { ...scope, step, cursor } : null
967
+ }
968
+ default:
969
+ return null
970
+ }
971
+ }
972
+
973
+ export function parseOpsImportBeginAck(body: unknown): OpsImportBeginAck | null {
974
+ const parts = readPartNumber(prop(body, 'parts'))
975
+ return exactKeys(body, ['step', 'parts']) && prop(body, 'step') === 'begin' && parts !== null ? { step: 'begin', parts } : null
976
+ }
977
+
978
+ export function parseOpsImportPartAck(body: unknown): OpsImportPartAck | null {
979
+ if (!exactKeys(body, ['step', 'part', 'rows', 'deferred']) || prop(body, 'step') !== 'part') return null
980
+ const part = readPartNumber(prop(body, 'part'))
981
+ const rows = readCount(prop(body, 'rows'))
982
+ const deferred = readCount(prop(body, 'deferred'))
983
+ return part === null || rows === null || deferred === null ? null : { step: 'part', part, rows, deferred }
984
+ }
985
+
986
+ export function parseOpsImportLinkAck(body: unknown): OpsImportLinkAck | null {
987
+ if (!exactKeys(body, ['step', 'part', 'rows']) || prop(body, 'step') !== 'link') return null
988
+ const part = readPartNumber(prop(body, 'part'))
989
+ const rows = readCount(prop(body, 'rows'))
990
+ return part === null || rows === null ? null : { step: 'link', part, rows }
991
+ }
992
+
993
+ export function parseOpsImportVerifyAck(body: unknown): OpsImportVerifyAck | null {
994
+ if (!exactKeys(body, ['step', 'tables', 'next']) || prop(body, 'step') !== 'verify') return null
995
+ const tables = readTables(prop(body, 'tables'))
996
+ const next = readNullable(prop(body, 'next'), readCursor)
997
+ if (tables === null || next === undefined || continuesFinished(tables, next)) return null
998
+ return { step: 'verify', tables, next }
999
+ }
1000
+
1001
+ export function parseOpsImportCompleteAck(body: unknown): OpsImportCompleteAck | null {
1002
+ const source = readSource(prop(body, 'source'))
1003
+ return exactKeys(body, ['step', 'source']) && prop(body, 'step') === 'complete' && source !== null ? { step: 'complete', source } : null
1004
+ }
1005
+
1006
+ export function parseOpsImportDiscardAck(body: unknown): OpsImportDiscardAck | null {
1007
+ return exactKeys(body, ['step']) && prop(body, 'step') === 'discard' ? { step: 'discard' } : null
1008
+ }
1009
+
1010
+ /**
1011
+ * Writes the sentinel (the operation's id) into the object's KV storage, and answers the current bookmark and the
1012
+ * bookmark of `at`, which Control records before it arms anything.
1013
+ */
1014
+ export interface OpsRestorePrepare {
1015
+ readonly step: 'prepare'
1016
+ readonly object: string
1017
+ readonly generation: number
1018
+ readonly sentinel: string
1019
+ readonly at: string
1020
+ }
1021
+
1022
+ /** Arms the restore of `target` for the next session, answers, then resets the object. */
1023
+ export interface OpsRestoreArm {
1024
+ readonly step: 'arm'
1025
+ readonly object: string
1026
+ readonly generation: number
1027
+ readonly sentinel: string
1028
+ readonly target: string
1029
+ }
1030
+
1031
+ /** Reads, after the reset, whether the sentinel is still there. It writes nothing, so it carries no generation. */
1032
+ export interface OpsRestoreVerify {
1033
+ readonly step: 'verify'
1034
+ readonly object: string
1035
+ readonly sentinel: string
1036
+ }
1037
+
1038
+ /** `POST /__fabrika/ops/restore`: one step of rewinding an `inspect` object that serves no traffic. */
1039
+ export type OpsRestoreRequest = OpsRestorePrepare | OpsRestoreArm | OpsRestoreVerify
1040
+
1041
+ export interface OpsRestorePrepareAck {
1042
+ readonly step: 'prepare'
1043
+ readonly current: string
1044
+ readonly target: string
1045
+ }
1046
+
1047
+ /** May be lost to the reset; `verify` reconciles. */
1048
+ export interface OpsRestoreArmAck {
1049
+ readonly step: 'arm'
1050
+ readonly undo: string
1051
+ }
1052
+
1053
+ /** A sentinel still present means the restore did not happen. */
1054
+ export interface OpsRestoreVerifyAck {
1055
+ readonly step: 'verify'
1056
+ readonly sentinel: 'present' | 'absent'
1057
+ readonly bookmark: string
1058
+ }
1059
+
1060
+ export function parseOpsRestoreRequest(body: unknown): OpsRestoreRequest | null {
1061
+ const step = prop(body, 'step')
1062
+ const object = parseApplicationObjectName(prop(body, 'object'))
1063
+ const sentinel = readMatch(prop(body, 'sentinel'), UUID)
1064
+ if (object === null || sentinel === null) return null
1065
+ if (step === 'verify') return exactKeys(body, ['step', 'object', 'sentinel']) ? { step, object, sentinel } : null
1066
+ const generation = readGeneration(prop(body, 'generation'))
1067
+ if (generation === null) return null
1068
+ if (step === 'prepare') {
1069
+ const at = readTimestamp(prop(body, 'at'))
1070
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'at']) && at !== null ? { step, object, generation, sentinel, at } : null
1071
+ }
1072
+ if (step === 'arm') {
1073
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1074
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'target']) && target !== null
1075
+ ? { step, object, generation, sentinel, target }
1076
+ : null
1077
+ }
1078
+ return null
1079
+ }
1080
+
1081
+ export function parseOpsRestorePrepareAck(body: unknown): OpsRestorePrepareAck | null {
1082
+ if (!exactKeys(body, ['step', 'current', 'target']) || prop(body, 'step') !== 'prepare') return null
1083
+ const current = readMatch(prop(body, 'current'), OPAQUE_TOKEN)
1084
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1085
+ return current === null || target === null ? null : { step: 'prepare', current, target }
1086
+ }
1087
+
1088
+ export function parseOpsRestoreArmAck(body: unknown): OpsRestoreArmAck | null {
1089
+ const undo = readMatch(prop(body, 'undo'), OPAQUE_TOKEN)
1090
+ return exactKeys(body, ['step', 'undo']) && prop(body, 'step') === 'arm' && undo !== null ? { step: 'arm', undo } : null
1091
+ }
1092
+
1093
+ export function parseOpsRestoreVerifyAck(body: unknown): OpsRestoreVerifyAck | null {
1094
+ if (!exactKeys(body, ['step', 'sentinel', 'bookmark']) || prop(body, 'step') !== 'verify') return null
1095
+ const sentinel = readEnum(prop(body, 'sentinel'), SENTINEL_STATES)
1096
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
1097
+ return sentinel === null || bookmark === null ? null : { step: 'verify', sentinel, bookmark }
1098
+ }
1099
+
1100
+ /** The most timers one answer lists; the rest are counted in `omitted`. */
1101
+ export const OPS_TIMERS_CAP = 500
1102
+ /** A timer's stack keeps at most this many frames, the ones nearest the call that registered the work. */
1103
+ export const OPS_TIMER_STACK_MAX_FRAMES = 20
1104
+ /** A timer's stack is at most this many UTF-8 bytes, cut after it is scrubbed. */
1105
+ export const OPS_TIMER_STACK_MAX_BYTES = 4 * 1024
1106
+
1107
+ /** `POST /__fabrika/ops/timers`: reads the tracker, or with `track` switches it on or off first. In memory only. */
1108
+ export interface OpsTimersRequest {
1109
+ readonly object: string
1110
+ readonly track: boolean | null
1111
+ }
1112
+
1113
+ /** A pending timer or `waitUntil` promise and the stack that registered it, which may name application code: content. */
1114
+ export interface OpsTimer {
1115
+ readonly kind: 'timeout' | 'interval' | 'waitUntil'
1116
+ readonly since: string
1117
+ /** `null` exactly for `waitUntil`. */
1118
+ readonly delayMs: number | null
1119
+ readonly stack: string
1120
+ }
1121
+
1122
+ /** The object's live timers, oldest first (`data.content.read`). */
1123
+ export interface OpsTimersView {
1124
+ readonly tracking: boolean
1125
+ readonly timers: readonly OpsTimer[]
1126
+ readonly omitted: number
1127
+ }
1128
+
1129
+ export function parseOpsTimersRequest(body: unknown): OpsTimersRequest | null {
1130
+ const object = parseApplicationObjectName(prop(body, 'object'))
1131
+ const track = prop(body, 'track')
1132
+ return exactKeys(body, ['object', 'track']) && object !== null && (track === null || typeof track === 'boolean') ? { object, track } : null
1133
+ }
1134
+
1135
+ export function parseOpsTimersView(body: unknown): OpsTimersView | null {
1136
+ if (!exactKeys(body, ['tracking', 'timers', 'omitted'])) return null
1137
+ const tracking = prop(body, 'tracking')
1138
+ const raw = prop(body, 'timers')
1139
+ const timers = Array.isArray(raw) && raw.length <= OPS_TIMERS_CAP ? readList(raw, readTimer) : null
1140
+ const omitted = readCount(prop(body, 'omitted'))
1141
+ return typeof tracking !== 'boolean' || timers === null || omitted === null ? null : { tracking, timers, omitted }
1142
+ }
1143
+
1144
+ /** The status of a data operation's refusal. It is answered only after authentication. */
1145
+ export const OPS_DATA_REFUSED_STATUS = 422
1146
+
1147
+ /** Why the object refused an export, import or restore step. */
1148
+ export const OPS_DATA_REFUSALS = [
1149
+ 'wrong_mode',
1150
+ 'serving_object',
1151
+ 'unsupported_schema',
1152
+ 'not_fresh',
1153
+ 'no_import',
1154
+ 'invalid_manifest',
1155
+ 'fuzzy_dump',
1156
+ 'part_mismatch',
1157
+ 'ledger_mismatch',
1158
+ 'schema_mismatch',
1159
+ 'verify_mismatch',
1160
+ 'bookmark_unavailable',
1161
+ 'row_too_large',
1162
+ ] as const
1163
+
1164
+ export type OpsDataRefusalReason = (typeof OPS_DATA_REFUSALS)[number]
1165
+
1166
+ /** The body of a data refusal; `table` names the table at fault, an identifier and never a value. */
1167
+ export interface OpsDataRefusal {
1168
+ readonly refused: OpsDataRefusalReason
1169
+ readonly table: string | null
1170
+ }
1171
+
1172
+ export function parseOpsDataRefusal(body: unknown): OpsDataRefusal | null {
1173
+ const refused = readEnum(prop(body, 'refused'), OPS_DATA_REFUSALS)
1174
+ const table = readNullable(prop(body, 'table'), (value) => readMatch(value, TABLE_NAME))
1175
+ return exactKeys(body, ['refused', 'table']) && refused !== null && table !== undefined ? { refused, table } : null
1176
+ }
1177
+
1178
+ const VIEW_KEYS = ['release', 'maintenance', 'database', 'migrations', 'scheduler', 'jobs', 'files', 'webhooks', 'bootFailure']
1179
+ const FILE_STATUSES: readonly OpsFileStatus[] = ['pending', 'quarantined', 'live', 'rejected']
1180
+ const WEBHOOK_STATES = ['claimed', 'completed'] as const
1181
+ const JOB_STATUSES = ['succeeded', 'failed'] as const
1182
+ /** The form `Date.prototype.toISOString` and SQLite's `%Y-%m-%dT%H:%M:%fZ` both write. */
1183
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
1184
+ /** `@fabrika/db`'s `isPlainIdentifier`: the only table names the data layer admits. */
1185
+ const TABLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/
1186
+ /** The contract build's authored-name rule (`@fabrika/app/contract`), which a file kind follows. */
1187
+ const CONTRACT_NAME = /^[A-Za-z][A-Za-z0-9_]*$/
1188
+ /** `@fabrika/db`'s SQLite migration runner: a bundle name, a migration file name and a file's SHA-256 hex. */
1189
+ const MIGRATION_BUNDLE = /^[a-z][a-z0-9-]*$/
1190
+ const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
1191
+ const MIGRATION_CHECKSUM = /^[0-9a-f]{64}$/
1192
+ const SHA256_HEX = /^[0-9a-f]{64}$/
1193
+ /** A dump id or a sentinel: a UUID as Control writes one. */
1194
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
1195
+ /** A token R2 or the object hands out and nobody reads into: an upload id, an ETag, a bookmark. Printable ASCII, no space. */
1196
+ const OPAQUE_TOKEN = /^[!-~]{1,1024}$/
1197
+ /** The decimal text `cast(c as text)` writes for an integer: no leading zero, no `-0`. */
1198
+ const INT64_TEXT = /^(?:0|-?[1-9][0-9]{0,18})$/
1199
+ const INT64_MIN = -(2n ** 63n)
1200
+ const INT64_MAX = 2n ** 63n - 1n
1201
+ /**
1202
+ * `hex(c)` of a blob, and `hex(CAST(c AS BLOB))` of text. Bun's regex engine answers `false` for `^(?:[0-9A-F]{2})*$`
1203
+ * on a string of a few megabytes, so the pairing is a length check.
1204
+ */
1205
+ function isBytesHex(value: string): boolean {
1206
+ return value.length % 2 === 0 && /^[0-9A-F]*$/.test(value)
1207
+ }
1208
+ const MANIFEST_KEYS = [
1209
+ 'format',
1210
+ 'dump',
1211
+ 'object',
1212
+ 'consistent',
1213
+ 'createdAt',
1214
+ 'bookmark',
1215
+ 'release',
1216
+ 'contractDigest',
1217
+ 'ddl',
1218
+ 'migrations',
1219
+ 'tables',
1220
+ 'parts',
1221
+ ]
1222
+ const EXPORT_SCOPE_KEYS = ['object', 'generation', 'consistent', 'dump']
1223
+ const IMPORT_SCOPE_KEYS = ['object', 'generation', 'source']
1224
+ const SCHEMA_TYPES = ['table', 'index', 'trigger', 'view'] as const
1225
+ const SENTINEL_STATES = ['present', 'absent'] as const
1226
+ const TIMER_KINDS = ['timeout', 'interval', 'waitUntil'] as const
1227
+
1228
+ /** Every field of the view but the boot failure, whose form differs between the two views. */
1229
+ function readViewFields(body: unknown): Omit<OpsView, 'bootFailure'> | null {
1230
+ if (!exactKeys(body, VIEW_KEYS)) return null
1231
+ const release = prop(body, 'release')
1232
+ const maintenance = readMaintenance(prop(body, 'maintenance'))
1233
+ const database = readDatabase(prop(body, 'database'))
1234
+ const migrations = readList(prop(body, 'migrations'), readMigration)
1235
+ const scheduler = readScheduler(prop(body, 'scheduler'))
1236
+ const jobs = readList(prop(body, 'jobs'), readJob)
1237
+ const files = readList(prop(body, 'files'), readFileCount)
1238
+ const webhooks = readList(prop(body, 'webhooks'), readWebhookCount)
1239
+ if (
1240
+ typeof release !== 'string' || !FRAMEWORK_RELEASE_PATTERN.test(release) || maintenance === null || database === null || migrations === null
1241
+ || scheduler === null || jobs === null || files === null || webhooks === null
1242
+ ) {
1243
+ return null
1244
+ }
1245
+ return { release, maintenance, database, migrations, scheduler, jobs, files, webhooks }
1246
+ }
1247
+
1248
+ function readMaintenance(value: unknown): OpsMaintenance | null {
1249
+ if (!exactKeys(value, ['mode', 'generation', 'published'])) return null
1250
+ const mode = readMode(prop(value, 'mode'))
1251
+ const rawGeneration = prop(value, 'generation')
1252
+ const generation = rawGeneration === null ? null : readGeneration(rawGeneration)
1253
+ const published = prop(value, 'published')
1254
+ if (mode === null || (rawGeneration !== null && generation === null) || typeof published !== 'boolean') return null
1255
+ return { mode, generation, published }
1256
+ }
1257
+
1258
+ function readDatabase(value: unknown): OpsDatabase | null {
1259
+ if (!exactKeys(value, ['sizeBytes', 'tables'])) return null
1260
+ const sizeBytes = readCount(prop(value, 'sizeBytes'))
1261
+ const tables = readList(prop(value, 'tables'), readTableCount)
1262
+ return sizeBytes === null || tables === null ? null : { sizeBytes, tables }
1263
+ }
1264
+
1265
+ function readTableCount(value: unknown): OpsTableCount | null {
1266
+ if (!exactKeys(value, ['name', 'rows'])) return null
1267
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1268
+ const rows = readCount(prop(value, 'rows'))
1269
+ return name === null || rows === null || rows > OPS_ROW_COUNT_CAP ? null : { name, rows }
1270
+ }
1271
+
1272
+ function readMigration(value: unknown): OpsMigration | null {
1273
+ if (!exactKeys(value, ['bundle', 'name', 'checksum', 'appliedAt'])) return null
1274
+ const bundle = readMatch(prop(value, 'bundle'), MIGRATION_BUNDLE)
1275
+ const name = readMatch(prop(value, 'name'), MIGRATION_NAME)
1276
+ const checksum = readMatch(prop(value, 'checksum'), MIGRATION_CHECKSUM)
1277
+ const appliedAt = readTimestamp(prop(value, 'appliedAt'))
1278
+ return bundle === null || name === null || checksum === null || appliedAt === null ? null : { bundle, name, checksum, appliedAt }
1279
+ }
1280
+
1281
+ function readScheduler(value: unknown): OpsScheduler | null {
1282
+ if (!exactKeys(value, ['alarm'])) return null
1283
+ const raw = prop(value, 'alarm')
1284
+ const alarm = raw === null ? null : readTimestamp(raw)
1285
+ return raw !== null && alarm === null ? null : { alarm }
1286
+ }
1287
+
1288
+ /** A framework job of the application runtime (`fabrika-file-sweep`): reserved by its `-`, which no contract job name holds. */
1289
+ const FRAMEWORK_JOB_NAME = /^fabrika-[a-z][a-z0-9-]{0,55}$/
1290
+
1291
+ function readJob(value: unknown): OpsJob | null {
1292
+ if (!exactKeys(value, ['job', 'lastStatus', 'lastStartedAt', 'lastFinishedAt', 'lastDurationMs'])) return null
1293
+ const raw = prop(value, 'job')
1294
+ const job = readMatch(raw, WORKLOAD_NAME) ?? readMatch(raw, FRAMEWORK_JOB_NAME)
1295
+ const lastStatus = readNullable(prop(value, 'lastStatus'), (status) => readEnum(status, JOB_STATUSES))
1296
+ const lastStartedAt = readNullable(prop(value, 'lastStartedAt'), readTimestamp)
1297
+ const lastFinishedAt = readNullable(prop(value, 'lastFinishedAt'), readTimestamp)
1298
+ const lastDurationMs = readNullable(prop(value, 'lastDurationMs'), readCount)
1299
+ if (job === null || lastStatus === undefined || lastStartedAt === undefined || lastFinishedAt === undefined || lastDurationMs === undefined) {
1300
+ return null
1301
+ }
1302
+ return { job, lastStatus, lastStartedAt, lastFinishedAt, lastDurationMs }
1303
+ }
1304
+
1305
+ function readFileCount(value: unknown): OpsFileCount | null {
1306
+ if (!exactKeys(value, ['kind', 'status', 'count'])) return null
1307
+ const kind = readMatch(prop(value, 'kind'), CONTRACT_NAME)
1308
+ const status = readEnum(prop(value, 'status'), FILE_STATUSES)
1309
+ const count = readCount(prop(value, 'count'))
1310
+ return kind === null || status === null || count === null ? null : { kind, status, count }
1311
+ }
1312
+
1313
+ function readWebhookCount(value: unknown): OpsWebhookCount | null {
1314
+ if (!exactKeys(value, ['webhook', 'state', 'count'])) return null
1315
+ const webhook = readMatch(prop(value, 'webhook'), WORKLOAD_NAME)
1316
+ const state = readEnum(prop(value, 'state'), WEBHOOK_STATES)
1317
+ const count = readCount(prop(value, 'count'))
1318
+ return webhook === null || state === null || count === null ? null : { webhook, state, count }
1319
+ }
1320
+
1321
+ /** `undefined` for a value that is no boot failure; the caller reads `null` as none before calling. */
1322
+ function readBootFailure(value: unknown): OpsBootFailure | undefined {
1323
+ const at = readTimestamp(prop(value, 'at'))
1324
+ return exactKeys(value, ['at']) && at !== null ? { at } : undefined
1325
+ }
1326
+
1327
+ function readBootFailureContent(value: unknown): OpsBootFailureContent | undefined {
1328
+ if (!exactKeys(value, ['at', 'message', 'stack'])) return undefined
1329
+ const at = readTimestamp(prop(value, 'at'))
1330
+ const message = prop(value, 'message')
1331
+ const stack = prop(value, 'stack')
1332
+ if (at === null || typeof message !== 'string' || (stack !== null && typeof stack !== 'string')) return undefined
1333
+ return { at, message, stack }
1334
+ }
1335
+
1336
+ /** Whether `value` is a plain object holding exactly `keys`: no key missing, none unknown. */
1337
+ function exactKeys(value: unknown, keys: readonly string[]): boolean {
1338
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
1339
+ const own = Object.keys(value)
1340
+ return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key))
1341
+ }
1342
+
1343
+ function readList<T>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1344
+ if (!Array.isArray(value)) return null
1345
+ const items: T[] = []
1346
+ for (const item of value) {
1347
+ const parsed = read(item)
1348
+ if (parsed === null) return null
1349
+ items.push(parsed)
1350
+ }
1351
+ return items
1352
+ }
1353
+
1354
+ /** `null` stays `null`; anything else is read, and `undefined` marks a value `read` refused. */
1355
+ function readNullable<T>(value: unknown, read: (value: unknown) => T | null): T | null | undefined {
1356
+ if (value === null) return null
1357
+ return read(value) ?? undefined
1358
+ }
1359
+
1360
+ function readEnum<T extends string>(value: unknown, members: readonly T[]): T | null {
1361
+ return members.find((member) => member === value) ?? null
1362
+ }
1363
+
1364
+ function readMode(value: unknown): OpsMode | null {
1365
+ return readEnum(value, OPS_MODES)
1366
+ }
1367
+
1368
+ /** A generation Control allocated: a positive safe integer. */
1369
+ function readGeneration(value: unknown): number | null {
1370
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
1371
+ }
1372
+
1373
+ function readCount(value: unknown): number | null {
1374
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null
1375
+ }
1376
+
1377
+ /** An identifier the platform or the contract names, in its owner's format: free text never fits one. */
1378
+ function readMatch(value: unknown, pattern: RegExp): string | null {
1379
+ return typeof value === 'string' && pattern.test(value) ? value : null
1380
+ }
1381
+
1382
+ /** `Date` rolls an impossible date over (`02-31` to `03-03`), so the instant must print back as the same text. */
1383
+ function readTimestamp(value: unknown): string | null {
1384
+ if (typeof value !== 'string' || !TIMESTAMP.test(value)) return null
1385
+ const instant = new Date(value)
1386
+ return !Number.isNaN(instant.getTime()) && instant.toISOString() === value ? value : null
1387
+ }
1388
+
1389
+ /** `undefined` for text that is no JSON; every reader refuses it. */
1390
+ function parseJson(text: string): unknown {
1391
+ try {
1392
+ return JSON.parse(text)
1393
+ } catch {
1394
+ return undefined
1395
+ }
1396
+ }
1397
+
1398
+ // The errors name the rule a value broke and never the value, which is a tenant's data.
1399
+ function encodeValue(value: OpsDumpValue): string | null {
1400
+ if (value === null) return null
1401
+ switch (value.type) {
1402
+ case 'integer':
1403
+ if (!isInt64Text(value.value)) throw new Error('a dump integer must be the decimal text of a 64-bit integer')
1404
+ return `i:${value.value}`
1405
+ case 'real':
1406
+ if (Number.isNaN(value.value)) throw new Error('a dump real must not be NaN')
1407
+ return `r:${realText(value.value)}`
1408
+ case 'text':
1409
+ if (!isBytesHex(value.value)) throw new Error('dump text must be the upper-case hex of its bytes')
1410
+ return `t:${value.value}`
1411
+ case 'blob':
1412
+ if (!isBytesHex(value.value)) throw new Error('a dump blob must be upper-case hex')
1413
+ return `b:${value.value}`
1414
+ }
1415
+ }
1416
+
1417
+ /** ECMAScript's shortest text that reads back as the same double, with the sign of a negative zero kept. */
1418
+ function realText(value: number): string {
1419
+ return Object.is(value, -0) ? '-0' : String(value)
1420
+ }
1421
+
1422
+ function isInt64Text(text: string): boolean {
1423
+ if (!INT64_TEXT.test(text)) return false
1424
+ const value = BigInt(text)
1425
+ return value >= INT64_MIN && value <= INT64_MAX
1426
+ }
1427
+
1428
+ /** `undefined` for an encoded value outside the rules; `null` is SQL's NULL. */
1429
+ function readValue(raw: unknown): OpsDumpValue | undefined {
1430
+ if (raw === null) return null
1431
+ if (typeof raw !== 'string') return undefined
1432
+ const text = raw.slice(2)
1433
+ switch (raw.slice(0, 2)) {
1434
+ case 'i:':
1435
+ return isInt64Text(text) ? { type: 'integer', value: text } : undefined
1436
+ case 'r:': {
1437
+ const value = Number(text)
1438
+ return !Number.isNaN(value) && realText(value) === text ? { type: 'real', value } : undefined
1439
+ }
1440
+ case 't:':
1441
+ return isBytesHex(text) ? { type: 'text', value: text } : undefined
1442
+ case 'b:':
1443
+ return isBytesHex(text) ? { type: 'blob', value: text } : undefined
1444
+ default:
1445
+ return undefined
1446
+ }
1447
+ }
1448
+
1449
+ function readRowValues(raw: unknown): OpsDumpValue[] | null {
1450
+ if (!Array.isArray(raw)) return null
1451
+ const values: OpsDumpValue[] = []
1452
+ for (const item of raw) {
1453
+ const value = readValue(item)
1454
+ if (value === undefined) return null
1455
+ values.push(value)
1456
+ }
1457
+ return values
1458
+ }
1459
+
1460
+ function readCursor(value: unknown): OpsDumpCursor | null {
1461
+ if (!exactKeys(value, ['table', 'after', 'rows', 'hash'])) return null
1462
+ const table = readMatch(prop(value, 'table'), TABLE_NAME)
1463
+ const after = readNullable(prop(value, 'after'), readRowid)
1464
+ const rows = readCount(prop(value, 'rows'))
1465
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1466
+ if (table === null || after === undefined || rows === null || hash === null) return null
1467
+ // Before a table's first row nothing is folded; past a row, at least that row is.
1468
+ if ((after === null) !== (rows === 0) || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1469
+ return { table, after, rows, hash }
1470
+ }
1471
+
1472
+ function readRowid(value: unknown): string | null {
1473
+ return typeof value === 'string' && isInt64Text(value) ? value : null
1474
+ }
1475
+
1476
+ /** Tables in load order, each named once. */
1477
+ function readTables(value: unknown): readonly OpsDumpTable[] | null {
1478
+ const tables = readList(value, readDumpTable)
1479
+ return tables !== null && distinct(tables.map((table) => table.name)) ? tables : null
1480
+ }
1481
+
1482
+ function readDumpTable(value: unknown): OpsDumpTable | null {
1483
+ if (!exactKeys(value, ['name', 'rows', 'hash'])) return null
1484
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1485
+ const rows = readCount(prop(value, 'rows'))
1486
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1487
+ if (name === null || rows === null || hash === null || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1488
+ return { name, rows, hash }
1489
+ }
1490
+
1491
+ function readDumpPart(value: unknown): OpsDumpPart | null {
1492
+ if (!exactKeys(value, ['part', 'size', 'sha256'])) return null
1493
+ return readPartFields(value)
1494
+ }
1495
+
1496
+ function readUploadedPart(value: unknown): OpsUploadedPart | null {
1497
+ if (!exactKeys(value, ['part', 'size', 'sha256', 'etag'])) return null
1498
+ const fields = readPartFields(value)
1499
+ const etag = readMatch(prop(value, 'etag'), OPAQUE_TOKEN)
1500
+ return fields === null || etag === null ? null : { ...fields, etag }
1501
+ }
1502
+
1503
+ function readPartFields(value: unknown): OpsDumpPart | null {
1504
+ const part = readPartNumber(prop(value, 'part'))
1505
+ const size = readCount(prop(value, 'size'))
1506
+ const sha256 = readMatch(prop(value, 'sha256'), SHA256_HEX)
1507
+ return part === null || size === null || size === 0 || size > OPS_DUMP_PART_SIZE || sha256 === null ? null : { part, size, sha256 }
1508
+ }
1509
+
1510
+ /** Every part of an upload: numbered 1 to n without a gap, each of the fixed size but the last. */
1511
+ function readWholeParts<T extends OpsDumpPart>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1512
+ const parts = readList(value, read)
1513
+ if (parts === null || parts.length === 0 || parts.length > OPS_DUMP_MAX_PARTS) return null
1514
+ const whole = parts.every((part, index) => part.part === index + 1 && (index === parts.length - 1 || part.size === OPS_DUMP_PART_SIZE))
1515
+ return whole ? parts : null
1516
+ }
1517
+
1518
+ function readPartNumber(value: unknown): number | null {
1519
+ const part = readGeneration(value)
1520
+ return part !== null && part <= OPS_DUMP_MAX_PARTS ? part : null
1521
+ }
1522
+
1523
+ function readSchemaEntry(value: unknown): OpsDumpSchemaEntry | null {
1524
+ if (!exactKeys(value, ['type', 'name', 'table', 'sql'])) return null
1525
+ const type = readEnum(prop(value, 'type'), SCHEMA_TYPES)
1526
+ const name = prop(value, 'name')
1527
+ const table = prop(value, 'table')
1528
+ const sql = prop(value, 'sql')
1529
+ if (type === null || typeof name !== 'string' || name === '' || typeof table !== 'string' || table === '' || typeof sql !== 'string' || sql === '') {
1530
+ return null
1531
+ }
1532
+ // A table's entry names itself; an index or a trigger names any table or view, which the importer compares as text.
1533
+ if (type === 'table' && (name !== table || !TABLE_NAME.test(name))) return null
1534
+ return { type, name, table, sql }
1535
+ }
1536
+
1537
+ function readExportScope(body: unknown): OpsExportScope | null {
1538
+ const object = parseApplicationObjectName(prop(body, 'object'))
1539
+ const generation = readNullable(prop(body, 'generation'), readGeneration)
1540
+ const consistent = prop(body, 'consistent')
1541
+ const dump = readMatch(prop(body, 'dump'), UUID)
1542
+ if (object === null || generation === undefined || typeof consistent !== 'boolean' || dump === null) return null
1543
+ return consistent === (generation !== null) ? { object, generation, consistent, dump } : null
1544
+ }
1545
+
1546
+ function readSource(value: unknown): OpsDumpSource | null {
1547
+ if (!exactKeys(value, ['object', 'dump'])) return null
1548
+ const object = parseApplicationObjectName(prop(value, 'object'))
1549
+ const dump = readMatch(prop(value, 'dump'), UUID)
1550
+ return object === null || dump === null ? null : { object, dump }
1551
+ }
1552
+
1553
+ function boundedStack(stack: string): boolean {
1554
+ return new TextEncoder().encode(stack).length <= OPS_TIMER_STACK_MAX_BYTES && stack.split('\n').length <= OPS_TIMER_STACK_MAX_FRAMES
1555
+ }
1556
+
1557
+ function readTimer(value: unknown): OpsTimer | null {
1558
+ if (!exactKeys(value, ['kind', 'since', 'delayMs', 'stack'])) return null
1559
+ const kind = readEnum(prop(value, 'kind'), TIMER_KINDS)
1560
+ const since = readTimestamp(prop(value, 'since'))
1561
+ const delayMs = readNullable(prop(value, 'delayMs'), readCount)
1562
+ const stack = prop(value, 'stack')
1563
+ if (kind === null || since === null || delayMs === undefined || typeof stack !== 'string' || !boundedStack(stack)) return null
1564
+ return (kind === 'waitUntil') === (delayMs === null) ? { kind, since, delayMs, stack } : null
1565
+ }
1566
+
1567
+ /** A foreign key with its parent's columns named. */
1568
+ interface ResolvedForeignKey {
1569
+ readonly parent: string
1570
+ readonly columns: readonly string[]
1571
+ readonly references: readonly string[]
1572
+ }
1573
+
1574
+ interface DescribedTable {
1575
+ readonly table: OpsDumpSchemaTable
1576
+ readonly keyset: string
1577
+ readonly parents: readonly ResolvedForeignKey[]
1578
+ }
1579
+
1580
+ const ROWID_NAMES = ['rowid', '_rowid_', 'oid']
1581
+
1582
+ function unsupported(table: string | null): OpsDataRefusal {
1583
+ return { refused: 'unsupported_schema', table }
1584
+ }
1585
+
1586
+ /** A rowid table's `INTEGER PRIMARY KEY` is the rowid itself; any other primary key gets an automatic index (`origin` `pk`). */
1587
+ function rowidName(table: OpsDumpSchemaTable): string | null {
1588
+ const key = table.columns.filter((column) => column.primaryKey > 0)
1589
+ const [only] = key
1590
+ if (key.length === 1 && only !== undefined && asciiLower(only.type) === 'integer' && !table.indexes.some((index) => index.origin === 'pk')) {
1591
+ return only.name
1592
+ }
1593
+ const taken = new Set(table.columns.map((column) => asciiLower(column.name)))
1594
+ return ROWID_NAMES.find((name) => !taken.has(name)) ?? null
1595
+ }
1596
+
1597
+ function resolveForeignKeys(table: OpsDumpSchemaTable, tables: ReadonlyMap<string, OpsDumpSchemaTable>): readonly ResolvedForeignKey[] | null {
1598
+ const keys: ResolvedForeignKey[] = []
1599
+ for (const key of table.foreignKeys) {
1600
+ const parent = tables.get(asciiLower(key.parent))
1601
+ if (parent === undefined || key.initiallyDeferred || key.columns.length === 0) return null
1602
+ const primaryKey = parent.columns.filter((column) => column.primaryKey > 0).sort((left, right) => left.primaryKey - right.primaryKey)
1603
+ const references = key.references ?? primaryKey.map((column) => column.name)
1604
+ if (references.length !== key.columns.length) return null
1605
+ keys.push({ parent: parent.name, columns: key.columns, references })
1606
+ }
1607
+ return keys
1608
+ }
1609
+
1610
+ /** Each table's cycle, named by its first table: two tables share one exactly when each reaches the other through parents. */
1611
+ function cycleIds(tables: readonly DescribedTable[]): ReadonlyMap<string, string> {
1612
+ const parents = new Map(tables.map(({ table, parents }) => [table.name, parents]))
1613
+ const reach = new Map<string, ReadonlySet<string>>()
1614
+ for (const { table } of tables) {
1615
+ const seen = new Set<string>()
1616
+ const pending = [table.name]
1617
+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
1618
+ for (const key of parents.get(name) ?? []) {
1619
+ if (!seen.has(key.parent)) {
1620
+ seen.add(key.parent)
1621
+ pending.push(key.parent)
1622
+ }
1623
+ }
1624
+ }
1625
+ reach.set(table.name, seen)
1626
+ }
1627
+ const ids = new Map<string, string>()
1628
+ for (const { table } of tables) {
1629
+ const first = tables.find(({ table: other }) => reach.get(table.name)?.has(other.name) === true && reach.get(other.name)?.has(table.name) === true)
1630
+ ids.set(table.name, first === undefined || compareNames(first.table.name, table.name) > 0 ? table.name : first.table.name)
1631
+ }
1632
+ return ids
1633
+ }
1634
+
1635
+ /** Repeatedly the first table by name whose every parent outside its own cycle is placed. */
1636
+ function loadOrder(tables: readonly DescribedTable[], cycle: ReadonlyMap<string, string>): readonly DescribedTable[] {
1637
+ const placed = new Set<string>()
1638
+ const order: DescribedTable[] = []
1639
+ while (order.length < tables.length) {
1640
+ const next = tables.find(({ table, parents }) =>
1641
+ !placed.has(table.name) && parents.every((key) => placed.has(key.parent) || cycle.get(key.parent) === cycle.get(table.name))
1642
+ )
1643
+ // The cycles form a directed acyclic graph, so one always has every outside parent placed.
1644
+ if (next === undefined) throw new Error('a foreign-key graph without a table to place')
1645
+ placed.add(next.table.name)
1646
+ order.push(next)
1647
+ }
1648
+ return order
1649
+ }
1650
+
1651
+ /** Whether every deferred column of `table` can hold `NULL` from its part until the link pass, with nothing to violate. */
1652
+ function takesTemporaryNull(table: OpsDumpSchemaTable, deferred: readonly OpsDumpSchemaColumn[], referenced: ReadonlySet<string>): boolean {
1653
+ if (table.checked || table.columns.some((column) => column.generated && column.notNull)) return false
1654
+ if (table.indexes.some((index) => index.unique && (index.partial || index.columns.includes(null)))) return false
1655
+ return deferred.every((column) => !column.notNull && column.primaryKey === 0 && !referenced.has(columnKey(table.name, column.name)))
1656
+ }
1657
+
1658
+ function columnKey(table: string, column: string): string {
1659
+ return `${table}\n${asciiLower(column)}`
1660
+ }
1661
+
1662
+ /** SQLite compares identifiers case-insensitively in ASCII only. */
1663
+ function asciiLower(value: string): string {
1664
+ return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase())
1665
+ }
1666
+
1667
+ /** Code-unit order, which no locale changes. */
1668
+ function compareNames(left: string, right: string): number {
1669
+ return left < right ? -1 : left > right ? 1 : 0
1670
+ }
1671
+
1672
+ function quoteIdentifier(name: string): string {
1673
+ return `"${name.replaceAll('"', '""')}"`
1674
+ }
1675
+
1676
+ function hexBytes(hex: string): Uint8Array {
1677
+ if (!isBytesHex(hex)) throw new Error('dump bytes must be upper-case hex')
1678
+ const bytes = new Uint8Array(hex.length / 2)
1679
+ for (let index = 0; index < bytes.length; index++) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16)
1680
+ return bytes
1681
+ }
1682
+
1683
+ /** Whether a cursor resumes a table the same answer reports finished. */
1684
+ function continuesFinished(tables: readonly OpsDumpTable[], next: OpsDumpCursor | null): boolean {
1685
+ return next !== null && tables.some((table) => table.name === next.table)
1686
+ }
1687
+
1688
+ function utf8Length(text: string): number {
1689
+ return new TextEncoder().encode(text).length
1690
+ }
1691
+
1692
+ function distinct(values: readonly string[]): boolean {
1693
+ return new Set(values).size === values.length
1694
+ }
1695
+
1696
+ function sameNames(left: readonly string[], right: readonly string[]): boolean {
1697
+ const names = new Set(left)
1698
+ return distinct(left) && distinct(right) && left.length === right.length && right.every((name) => names.has(name))
1699
+ }