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

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,1634 @@
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
+ /** What a statement binds for one value of a dump. */
406
+ export type OpsDumpParam = string | number | Uint8Array | null
407
+
408
+ /** The SQL expression that writes a value back and the parameter its `?` binds. */
409
+ export interface OpsDumpBinding {
410
+ readonly sql: string
411
+ readonly param: OpsDumpParam
412
+ }
413
+
414
+ /**
415
+ * How the importer writes a value back, a rowid included, without a double or a JavaScript string in between: an
416
+ * integer as its decimal text through `CAST(? AS INTEGER)`, a real through `CAST(? AS REAL)` (a binder may bind an
417
+ * integral double as an integer), text as its bytes through `CAST(? AS TEXT)`, and a blob as its bytes.
418
+ */
419
+ export function opsDumpValueBinding(value: OpsDumpValue): OpsDumpBinding {
420
+ if (value === null) return { sql: '?', param: null }
421
+ switch (value.type) {
422
+ case 'integer':
423
+ return { sql: 'CAST(? AS INTEGER)', param: value.value }
424
+ case 'real':
425
+ return { sql: 'CAST(? AS REAL)', param: value.value }
426
+ case 'text':
427
+ return { sql: 'CAST(? AS TEXT)', param: hexBytes(value.value) }
428
+ case 'blob':
429
+ return { sql: '?', param: hexBytes(value.value) }
430
+ }
431
+ }
432
+
433
+ /**
434
+ * The canonical encoding of a row, the text a table hash is computed over: a JSON array (`JSON.stringify`, so no
435
+ * whitespace) of `null` or a tagged string per value, `i:<decimal>`, `r:<shortest round-trip double>`, `t:<HEX>` or
436
+ * `b:<HEX>`. A real keeps `-0`, `Infinity` and `-Infinity`; NaN is never stored. Throws, naming no value, on a value
437
+ * outside these rules.
438
+ */
439
+ export function encodeOpsDumpRow(values: readonly OpsDumpValue[]): string {
440
+ return JSON.stringify(values.map(encodeValue))
441
+ }
442
+
443
+ /** The values of a row's canonical encoding, or `null` for any other text, a different spelling of the same row included. */
444
+ export function decodeOpsDumpRow(text: string): readonly OpsDumpValue[] | null {
445
+ const values = readRowValues(parseJson(text))
446
+ return values !== null && encodeOpsDumpRow(values) === text ? values : null
447
+ }
448
+
449
+ /** One line of a dump's NDJSON: a table's row, which is its rowid, then every column that is not generated. */
450
+ export interface OpsDumpLine {
451
+ readonly table: string
452
+ readonly row: readonly OpsDumpValue[]
453
+ }
454
+
455
+ /** The line `{"table":"<name>","row":<canonical row>}`. Throws on a table name outside the data layer's identifier rule. */
456
+ export function encodeOpsDumpLine(line: OpsDumpLine): string {
457
+ if (!TABLE_NAME.test(line.table)) throw new Error('a dump line needs a plain table name')
458
+ return `{"table":${JSON.stringify(line.table)},"row":${encodeOpsDumpRow(line.row)}}`
459
+ }
460
+
461
+ /** A line, or `null` for anything `encodeOpsDumpLine` would not write. */
462
+ export function decodeOpsDumpLine(text: string): OpsDumpLine | null {
463
+ const parsed = parseJson(text)
464
+ if (!exactKeys(parsed, ['table', 'row'])) return null
465
+ const table = readMatch(prop(parsed, 'table'), TABLE_NAME)
466
+ const row = readRowValues(prop(parsed, 'row'))
467
+ if (table === null || row === null) return null
468
+ return encodeOpsDumpLine({ table, row }) === text ? { table, row } : null
469
+ }
470
+
471
+ /** The hash of a table without rows: the SHA-256 of the empty string. */
472
+ export const OPS_EMPTY_TABLE_HASH = sha256Hex('')
473
+
474
+ /**
475
+ * 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
476
+ * the previous hash's hex, a newline and the row, so a table read page by page, across steps, folds to one value.
477
+ */
478
+ export function foldOpsTableHash(hash: string, rows: Iterable<string>): string {
479
+ if (!SHA256_HEX.test(hash)) throw new Error('a table hash is 64 lower-case hex digits')
480
+ let current = hash
481
+ for (const row of rows) current = sha256Hex(`${current}\n${row}`)
482
+ return current
483
+ }
484
+
485
+ /** A column as `PRAGMA table_xinfo` describes it. */
486
+ export interface OpsDumpSchemaColumn {
487
+ readonly name: string
488
+ /** The declared type, as written. */
489
+ readonly type: string
490
+ readonly notNull: boolean
491
+ /** The column's position in the primary key from 1, `0` outside it. */
492
+ readonly primaryKey: number
493
+ /** A generated column (`hidden` 2 or 3), which a dump does not carry. */
494
+ readonly generated: boolean
495
+ }
496
+
497
+ /** An index as `PRAGMA index_list` and `PRAGMA index_xinfo` (its key columns) describe it. */
498
+ export interface OpsDumpSchemaIndex {
499
+ readonly unique: boolean
500
+ readonly origin: 'c' | 'u' | 'pk'
501
+ readonly partial: boolean
502
+ /** The key columns in order, `null` for an expression. */
503
+ readonly columns: readonly (string | null)[]
504
+ }
505
+
506
+ /** A foreign key as `PRAGMA foreign_key_list` describes it, its rows grouped by `id` and ordered by `seq`. */
507
+ export interface OpsDumpSchemaForeignKey {
508
+ readonly parent: string
509
+ readonly columns: readonly string[]
510
+ /** The parent's columns (`to`), or `null` when the key names the parent's primary key implicitly. */
511
+ readonly references: readonly string[] | null
512
+ /**
513
+ * Whether the key is `DEFERRABLE INITIALLY DEFERRED`. No PRAGMA reports it: a reader takes it from the table's SQL,
514
+ * and one that cannot tell which key a clause belongs to marks every key of that table.
515
+ */
516
+ readonly initiallyDeferred: boolean
517
+ }
518
+
519
+ /** A table as `PRAGMA table_list` (`type`, `wr`) and the PRAGMAs above describe it. */
520
+ export interface OpsDumpSchemaTable {
521
+ readonly name: string
522
+ readonly virtual: boolean
523
+ readonly withoutRowid: boolean
524
+ /** Whether the table's SQL declares a `CHECK` constraint; a reader that cannot tell answers `true`. */
525
+ readonly checked: boolean
526
+ readonly columns: readonly OpsDumpSchemaColumn[]
527
+ readonly indexes: readonly OpsDumpSchemaIndex[]
528
+ readonly foreignKeys: readonly OpsDumpSchemaForeignKey[]
529
+ }
530
+
531
+ /** Every table a dump holds: `sqlite_schema`'s tables but SQLite's internal ones, `sqlite_sequence` excepted, and `_cf_`'s. */
532
+ export interface OpsDumpSchema {
533
+ readonly tables: readonly OpsDumpSchemaTable[]
534
+ }
535
+
536
+ /** How one table is dumped and loaded. */
537
+ export interface OpsDumpTablePlan {
538
+ readonly name: string
539
+ /** The name that reads the rowid: the `INTEGER PRIMARY KEY` column, else the first of `rowid`, `_rowid_`, `oid` no column takes. */
540
+ readonly keyset: string
541
+ /** Every column that is not generated, in declaration order: a row is the rowid, then these. */
542
+ readonly columns: readonly string[]
543
+ /** The columns of the foreign keys inside a cycle, which a part writes `NULL` and the link pass sets, in declaration order. */
544
+ readonly deferred: readonly string[]
545
+ }
546
+
547
+ /** The tables of a dump in load order: every parent outside a table's own cycle comes before it. */
548
+ export interface OpsDumpPlan {
549
+ readonly tables: readonly OpsDumpTablePlan[]
550
+ }
551
+
552
+ /**
553
+ * The one rule both the producer, at export `begin`, and the importer, at import `begin`, apply to a schema: the plan
554
+ * a dump is written and loaded by, or an `unsupported_schema` refusal naming the table. A foreign key whose parent lies
555
+ * in its own table's cycle (the table itself included) is loaded `NULL` and linked once every row is in, so each of its
556
+ * columns must take a temporary `NULL`: nullable, outside the primary key, referenced by no foreign key, in a table
557
+ * without a `CHECK`, a `NOT NULL` generated column, or a partial or expression unique index. A `WITHOUT ROWID` or
558
+ * virtual table, a table without a name that reads its rowid, a foreign key to a table outside the dump or without the
559
+ * named key, and a foreign key checked only at commit are refused.
560
+ */
561
+ export function planOpsDump(schema: OpsDumpSchema): OpsDumpPlan | OpsDataRefusal {
562
+ const sorted = [...schema.tables].sort((left, right) => compareNames(left.name, right.name))
563
+ if (!sorted.every((table) => TABLE_NAME.test(table.name)) || !distinct(sorted.map((table) => table.name))) return unsupported(null)
564
+ const byName = new Map(sorted.map((table) => [table.name, table]))
565
+ const tables: DescribedTable[] = []
566
+ for (const table of sorted) {
567
+ const keyset = table.virtual || table.withoutRowid ? null : rowidName(table)
568
+ const parents = resolveForeignKeys(table, byName)
569
+ if (keyset === null || parents === null) return unsupported(table.name)
570
+ tables.push({ table, keyset, parents })
571
+ }
572
+ const cycle = cycleIds(tables)
573
+ const referenced = new Set(tables.flatMap(({ parents }) => parents.flatMap((key) => key.references.map((column) => columnKey(key.parent, column)))))
574
+ const plans: OpsDumpTablePlan[] = []
575
+ for (const { table, keyset, parents } of loadOrder(tables, cycle)) {
576
+ const inCycle = parents.filter((key) => cycle.get(key.parent) === cycle.get(table.name))
577
+ const deferredNames = new Set(inCycle.flatMap((key) => key.columns.map(asciiLower)))
578
+ const deferred = table.columns.filter((column) => deferredNames.has(asciiLower(column.name)))
579
+ if (deferred.length > 0 && !takesTemporaryNull(table, deferred, referenced)) return unsupported(table.name)
580
+ plans.push({
581
+ name: table.name,
582
+ keyset,
583
+ columns: table.columns.filter((column) => !column.generated).map((column) => column.name),
584
+ deferred: deferred.map((column) => column.name),
585
+ })
586
+ }
587
+ return { tables: plans }
588
+ }
589
+
590
+ /** Where a dump or a verification stands in a table: the last rowid read, and the count and hash folded so far. */
591
+ export interface OpsDumpCursor {
592
+ readonly table: string
593
+ /** The rowid of the last row read, as decimal text; `null` before the table's first row. */
594
+ readonly after: string | null
595
+ readonly rows: number
596
+ readonly hash: string
597
+ }
598
+
599
+ /** A table a dump holds, with its exact row count and its hash. */
600
+ export interface OpsDumpTable {
601
+ readonly name: string
602
+ readonly rows: number
603
+ readonly hash: string
604
+ }
605
+
606
+ /** A part of a dump's data object: its number from 1, its size in bytes and the SHA-256 hex of its bytes. */
607
+ export interface OpsDumpPart {
608
+ readonly part: number
609
+ readonly size: number
610
+ readonly sha256: string
611
+ }
612
+
613
+ /** A part as R2 accepted it; Control completes the upload with the ETags. */
614
+ export interface OpsUploadedPart extends OpsDumpPart {
615
+ readonly etag: string
616
+ }
617
+
618
+ /** One `sqlite_schema` entry with SQL: an automatic index has none and is not listed. */
619
+ export interface OpsDumpSchemaEntry {
620
+ readonly type: 'table' | 'index' | 'trigger' | 'view'
621
+ readonly name: string
622
+ readonly table: string
623
+ readonly sql: string
624
+ }
625
+
626
+ /** `manifest.json`, written beside the data once its upload completed. `tables` is in load order. */
627
+ export interface OpsDumpManifest {
628
+ readonly format: typeof OPS_DUMP_FORMAT
629
+ readonly dump: string
630
+ readonly object: string
631
+ readonly consistent: boolean
632
+ readonly createdAt: string
633
+ /** The object's bookmark when the dump began. */
634
+ readonly bookmark: string
635
+ readonly release: string
636
+ readonly contractDigest: string
637
+ readonly ddl: readonly OpsDumpSchemaEntry[]
638
+ readonly migrations: readonly OpsMigration[]
639
+ readonly tables: readonly OpsDumpTable[]
640
+ readonly parts: readonly OpsDumpPart[]
641
+ }
642
+
643
+ /**
644
+ * A manifest Control holds or an answer carries; every table's DDL lists it, its parts are whole, and its
645
+ * `JSON.stringify` is at most `OPS_DUMP_MANIFEST_MAX_BYTES` in UTF-8, wherever it came from.
646
+ */
647
+ export function parseOpsDumpManifest(body: unknown): OpsDumpManifest | null {
648
+ if (!exactKeys(body, MANIFEST_KEYS) || prop(body, 'format') !== OPS_DUMP_FORMAT) return null
649
+ const dump = readMatch(prop(body, 'dump'), UUID)
650
+ const object = parseApplicationObjectName(prop(body, 'object'))
651
+ const consistent = prop(body, 'consistent')
652
+ const createdAt = readTimestamp(prop(body, 'createdAt'))
653
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
654
+ const release = readMatch(prop(body, 'release'), FRAMEWORK_RELEASE_PATTERN)
655
+ const contractDigest = prop(body, 'contractDigest')
656
+ const ddl = readList(prop(body, 'ddl'), readSchemaEntry)
657
+ const migrations = readList(prop(body, 'migrations'), readMigration)
658
+ const tables = readTables(prop(body, 'tables'))
659
+ const parts = readWholeParts(prop(body, 'parts'), readDumpPart)
660
+ if (
661
+ dump === null || object === null || typeof consistent !== 'boolean' || createdAt === null || bookmark === null || release === null
662
+ || typeof contractDigest !== 'string' || !isDigest(contractDigest) || ddl === null || migrations === null || tables === null || parts === null
663
+ ) {
664
+ return null
665
+ }
666
+ const declared = ddl.filter((entry) => entry.type === 'table').map((entry) => entry.name)
667
+ if (!distinct(ddl.map((entry) => `${entry.type} ${entry.name}`)) || !sameNames(declared, tables.map((table) => table.name))) return null
668
+ const manifest: OpsDumpManifest = {
669
+ format: OPS_DUMP_FORMAT,
670
+ dump,
671
+ object,
672
+ consistent,
673
+ createdAt,
674
+ bookmark,
675
+ release,
676
+ contractDigest,
677
+ ddl,
678
+ migrations,
679
+ tables,
680
+ parts,
681
+ }
682
+ return utf8Length(JSON.stringify(manifest)) <= OPS_DUMP_MANIFEST_MAX_BYTES ? manifest : null
683
+ }
684
+
685
+ /** A manifest's text as R2 holds it, refused above `OPS_DUMP_MANIFEST_MAX_BYTES` before it is parsed. */
686
+ export function readOpsDumpManifest(text: string): OpsDumpManifest | null {
687
+ if (utf8Length(text) > OPS_DUMP_MANIFEST_MAX_BYTES) return null
688
+ return parseOpsDumpManifest(parseJson(text))
689
+ }
690
+
691
+ /** What every export step names: a consistent backup carries the published generation, a diagnostic export none. */
692
+ export interface OpsExportScope {
693
+ readonly object: string
694
+ readonly generation: number | null
695
+ readonly consistent: boolean
696
+ readonly dump: string
697
+ }
698
+
699
+ /** Starts the multipart upload of the dump's data. */
700
+ export interface OpsExportBegin extends OpsExportScope {
701
+ readonly step: 'begin'
702
+ }
703
+
704
+ /** Fills part `part` from `cursor`, `null` only for the first part; a retry replaces the part. */
705
+ export interface OpsExportPart extends OpsExportScope {
706
+ readonly step: 'part'
707
+ readonly uploadId: string
708
+ readonly part: number
709
+ readonly cursor: OpsDumpCursor | null
710
+ }
711
+
712
+ /** Completes the upload from the parts and tables Control recorded, and writes the manifest. */
713
+ export interface OpsExportComplete extends OpsExportScope {
714
+ readonly step: 'complete'
715
+ readonly uploadId: string
716
+ readonly bookmark: string
717
+ readonly parts: readonly OpsUploadedPart[]
718
+ readonly tables: readonly OpsDumpTable[]
719
+ }
720
+
721
+ /** `POST /__fabrika/ops/export`: one step of a dump. */
722
+ export type OpsExportRequest = OpsExportBegin | OpsExportPart | OpsExportComplete
723
+
724
+ export interface OpsExportBeginAck {
725
+ readonly step: 'begin'
726
+ readonly uploadId: string
727
+ readonly bookmark: string
728
+ }
729
+
730
+ /** The part written, the tables it finished in load order, and where the next part starts: `null` once all is read. */
731
+ export interface OpsExportPartAck {
732
+ readonly step: 'part'
733
+ readonly uploaded: OpsUploadedPart
734
+ readonly tables: readonly OpsDumpTable[]
735
+ readonly next: OpsDumpCursor | null
736
+ }
737
+
738
+ export interface OpsExportCompleteAck {
739
+ readonly step: 'complete'
740
+ readonly manifest: OpsDumpManifest
741
+ }
742
+
743
+ export function parseOpsExportRequest(body: unknown): OpsExportRequest | null {
744
+ const scope = readExportScope(body)
745
+ if (scope === null) return null
746
+ switch (prop(body, 'step')) {
747
+ case 'begin':
748
+ return exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step']) ? { ...scope, step: 'begin' } : null
749
+ case 'part': {
750
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'part', 'cursor'])) return null
751
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
752
+ const part = readPartNumber(prop(body, 'part'))
753
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
754
+ if (uploadId === null || part === null || cursor === undefined || (part === 1) !== (cursor === null)) return null
755
+ return { ...scope, step: 'part', uploadId, part, cursor }
756
+ }
757
+ case 'complete': {
758
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'bookmark', 'parts', 'tables'])) return null
759
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
760
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
761
+ const parts = readWholeParts(prop(body, 'parts'), readUploadedPart)
762
+ const tables = readTables(prop(body, 'tables'))
763
+ if (uploadId === null || bookmark === null || parts === null || tables === null) return null
764
+ return { ...scope, step: 'complete', uploadId, bookmark, parts, tables }
765
+ }
766
+ default:
767
+ return null
768
+ }
769
+ }
770
+
771
+ export function parseOpsExportBeginAck(body: unknown): OpsExportBeginAck | null {
772
+ if (!exactKeys(body, ['step', 'uploadId', 'bookmark']) || prop(body, 'step') !== 'begin') return null
773
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
774
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
775
+ return uploadId === null || bookmark === null ? null : { step: 'begin', uploadId, bookmark }
776
+ }
777
+
778
+ export function parseOpsExportPartAck(body: unknown): OpsExportPartAck | null {
779
+ if (!exactKeys(body, ['step', 'uploaded', 'tables', 'next']) || prop(body, 'step') !== 'part') return null
780
+ const uploaded = readUploadedPart(prop(body, 'uploaded'))
781
+ const tables = readTables(prop(body, 'tables'))
782
+ const next = readNullable(prop(body, 'next'), readCursor)
783
+ if (uploaded === null || tables === null || next === undefined || continuesFinished(tables, next)) return null
784
+ // Only the last part may be short: R2 refuses an upload whose other parts differ in size.
785
+ if (next !== null && uploaded.size !== OPS_DUMP_PART_SIZE) return null
786
+ return { step: 'part', uploaded, tables, next }
787
+ }
788
+
789
+ export function parseOpsExportCompleteAck(body: unknown): OpsExportCompleteAck | null {
790
+ if (!exactKeys(body, ['step', 'manifest']) || prop(body, 'step') !== 'complete') return null
791
+ const manifest = parseOpsDumpManifest(prop(body, 'manifest'))
792
+ return manifest === null ? null : { step: 'complete', manifest }
793
+ }
794
+
795
+ /** The consistent backup an import loads: always under `__fabrika/backups/`. */
796
+ export interface OpsDumpSource {
797
+ readonly object: string
798
+ readonly dump: string
799
+ }
800
+
801
+ /** What every import step names: the fresh target, published `inspect` under the operation's generation, and the backup. */
802
+ export interface OpsImportScope {
803
+ readonly object: string
804
+ readonly generation: number
805
+ readonly source: OpsDumpSource
806
+ }
807
+
808
+ /** Verifies the manifest, checks the target is fresh, and migrates it to the manifest's ledger. */
809
+ export interface OpsImportBegin extends OpsImportScope {
810
+ readonly step: 'begin'
811
+ }
812
+
813
+ /** Loads part `part`, writing a foreign key the load order cannot satisfy as `NULL`. */
814
+ export interface OpsImportPart extends OpsImportScope {
815
+ readonly step: 'part'
816
+ readonly part: number
817
+ }
818
+
819
+ /** Sets the foreign keys part `part` wrote as `NULL`, once every part is loaded. */
820
+ export interface OpsImportLink extends OpsImportScope {
821
+ readonly step: 'link'
822
+ readonly part: number
823
+ }
824
+
825
+ /** Reads the loaded tables back from `cursor`, `null` at the start, and compares counts and hashes with the manifest. */
826
+ export interface OpsImportVerify extends OpsImportScope {
827
+ readonly step: 'verify'
828
+ readonly cursor: OpsDumpCursor | null
829
+ }
830
+
831
+ /** Clears the import marker once every table verified, so Control may open the object. */
832
+ export interface OpsImportComplete extends OpsImportScope {
833
+ readonly step: 'complete'
834
+ }
835
+
836
+ /** Wipes an `inspect` object that holds an import marker and serves no traffic, with `deleteAll()`. */
837
+ export interface OpsImportDiscard {
838
+ readonly step: 'discard'
839
+ readonly object: string
840
+ readonly generation: number
841
+ }
842
+
843
+ /** `POST /__fabrika/ops/import`: one step of loading a consistent backup into a fresh object. */
844
+ export type OpsImportRequest = OpsImportBegin | OpsImportPart | OpsImportLink | OpsImportVerify | OpsImportComplete | OpsImportDiscard
845
+
846
+ export interface OpsImportBeginAck {
847
+ readonly step: 'begin'
848
+ readonly parts: number
849
+ }
850
+
851
+ /** `deferred` counts the loaded rows whose deferred foreign keys wait for the link pass. */
852
+ export interface OpsImportPartAck {
853
+ readonly step: 'part'
854
+ readonly part: number
855
+ readonly rows: number
856
+ readonly deferred: number
857
+ }
858
+
859
+ export interface OpsImportLinkAck {
860
+ readonly step: 'link'
861
+ readonly part: number
862
+ readonly rows: number
863
+ }
864
+
865
+ /** The tables verified in this step, each matching the manifest, and where the next step starts: `null` once all match. */
866
+ export interface OpsImportVerifyAck {
867
+ readonly step: 'verify'
868
+ readonly tables: readonly OpsDumpTable[]
869
+ readonly next: OpsDumpCursor | null
870
+ }
871
+
872
+ export interface OpsImportCompleteAck {
873
+ readonly step: 'complete'
874
+ readonly source: OpsDumpSource
875
+ }
876
+
877
+ export interface OpsImportDiscardAck {
878
+ readonly step: 'discard'
879
+ }
880
+
881
+ export function parseOpsImportRequest(body: unknown): OpsImportRequest | null {
882
+ const step = prop(body, 'step')
883
+ const object = parseApplicationObjectName(prop(body, 'object'))
884
+ const generation = readGeneration(prop(body, 'generation'))
885
+ if (object === null || generation === null) return null
886
+ if (step === 'discard') return exactKeys(body, ['step', 'object', 'generation']) ? { step, object, generation } : null
887
+ const source = readSource(prop(body, 'source'))
888
+ if (source === null) return null
889
+ const scope = { object, generation, source }
890
+ switch (step) {
891
+ case 'begin':
892
+ case 'complete':
893
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step']) ? { ...scope, step } : null
894
+ case 'part':
895
+ case 'link': {
896
+ const part = readPartNumber(prop(body, 'part'))
897
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'part']) && part !== null ? { ...scope, step, part } : null
898
+ }
899
+ case 'verify': {
900
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
901
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'cursor']) && cursor !== undefined ? { ...scope, step, cursor } : null
902
+ }
903
+ default:
904
+ return null
905
+ }
906
+ }
907
+
908
+ export function parseOpsImportBeginAck(body: unknown): OpsImportBeginAck | null {
909
+ const parts = readPartNumber(prop(body, 'parts'))
910
+ return exactKeys(body, ['step', 'parts']) && prop(body, 'step') === 'begin' && parts !== null ? { step: 'begin', parts } : null
911
+ }
912
+
913
+ export function parseOpsImportPartAck(body: unknown): OpsImportPartAck | null {
914
+ if (!exactKeys(body, ['step', 'part', 'rows', 'deferred']) || prop(body, 'step') !== 'part') return null
915
+ const part = readPartNumber(prop(body, 'part'))
916
+ const rows = readCount(prop(body, 'rows'))
917
+ const deferred = readCount(prop(body, 'deferred'))
918
+ return part === null || rows === null || deferred === null ? null : { step: 'part', part, rows, deferred }
919
+ }
920
+
921
+ export function parseOpsImportLinkAck(body: unknown): OpsImportLinkAck | null {
922
+ if (!exactKeys(body, ['step', 'part', 'rows']) || prop(body, 'step') !== 'link') return null
923
+ const part = readPartNumber(prop(body, 'part'))
924
+ const rows = readCount(prop(body, 'rows'))
925
+ return part === null || rows === null ? null : { step: 'link', part, rows }
926
+ }
927
+
928
+ export function parseOpsImportVerifyAck(body: unknown): OpsImportVerifyAck | null {
929
+ if (!exactKeys(body, ['step', 'tables', 'next']) || prop(body, 'step') !== 'verify') return null
930
+ const tables = readTables(prop(body, 'tables'))
931
+ const next = readNullable(prop(body, 'next'), readCursor)
932
+ if (tables === null || next === undefined || continuesFinished(tables, next)) return null
933
+ return { step: 'verify', tables, next }
934
+ }
935
+
936
+ export function parseOpsImportCompleteAck(body: unknown): OpsImportCompleteAck | null {
937
+ const source = readSource(prop(body, 'source'))
938
+ return exactKeys(body, ['step', 'source']) && prop(body, 'step') === 'complete' && source !== null ? { step: 'complete', source } : null
939
+ }
940
+
941
+ export function parseOpsImportDiscardAck(body: unknown): OpsImportDiscardAck | null {
942
+ return exactKeys(body, ['step']) && prop(body, 'step') === 'discard' ? { step: 'discard' } : null
943
+ }
944
+
945
+ /**
946
+ * Writes the sentinel (the operation's id) into the object's KV storage, and answers the current bookmark and the
947
+ * bookmark of `at`, which Control records before it arms anything.
948
+ */
949
+ export interface OpsRestorePrepare {
950
+ readonly step: 'prepare'
951
+ readonly object: string
952
+ readonly generation: number
953
+ readonly sentinel: string
954
+ readonly at: string
955
+ }
956
+
957
+ /** Arms the restore of `target` for the next session, answers, then resets the object. */
958
+ export interface OpsRestoreArm {
959
+ readonly step: 'arm'
960
+ readonly object: string
961
+ readonly generation: number
962
+ readonly sentinel: string
963
+ readonly target: string
964
+ }
965
+
966
+ /** Reads, after the reset, whether the sentinel is still there. It writes nothing, so it carries no generation. */
967
+ export interface OpsRestoreVerify {
968
+ readonly step: 'verify'
969
+ readonly object: string
970
+ readonly sentinel: string
971
+ }
972
+
973
+ /** `POST /__fabrika/ops/restore`: one step of rewinding an `inspect` object that serves no traffic. */
974
+ export type OpsRestoreRequest = OpsRestorePrepare | OpsRestoreArm | OpsRestoreVerify
975
+
976
+ export interface OpsRestorePrepareAck {
977
+ readonly step: 'prepare'
978
+ readonly current: string
979
+ readonly target: string
980
+ }
981
+
982
+ /** May be lost to the reset; `verify` reconciles. */
983
+ export interface OpsRestoreArmAck {
984
+ readonly step: 'arm'
985
+ readonly undo: string
986
+ }
987
+
988
+ /** A sentinel still present means the restore did not happen. */
989
+ export interface OpsRestoreVerifyAck {
990
+ readonly step: 'verify'
991
+ readonly sentinel: 'present' | 'absent'
992
+ readonly bookmark: string
993
+ }
994
+
995
+ export function parseOpsRestoreRequest(body: unknown): OpsRestoreRequest | null {
996
+ const step = prop(body, 'step')
997
+ const object = parseApplicationObjectName(prop(body, 'object'))
998
+ const sentinel = readMatch(prop(body, 'sentinel'), UUID)
999
+ if (object === null || sentinel === null) return null
1000
+ if (step === 'verify') return exactKeys(body, ['step', 'object', 'sentinel']) ? { step, object, sentinel } : null
1001
+ const generation = readGeneration(prop(body, 'generation'))
1002
+ if (generation === null) return null
1003
+ if (step === 'prepare') {
1004
+ const at = readTimestamp(prop(body, 'at'))
1005
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'at']) && at !== null ? { step, object, generation, sentinel, at } : null
1006
+ }
1007
+ if (step === 'arm') {
1008
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1009
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'target']) && target !== null
1010
+ ? { step, object, generation, sentinel, target }
1011
+ : null
1012
+ }
1013
+ return null
1014
+ }
1015
+
1016
+ export function parseOpsRestorePrepareAck(body: unknown): OpsRestorePrepareAck | null {
1017
+ if (!exactKeys(body, ['step', 'current', 'target']) || prop(body, 'step') !== 'prepare') return null
1018
+ const current = readMatch(prop(body, 'current'), OPAQUE_TOKEN)
1019
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1020
+ return current === null || target === null ? null : { step: 'prepare', current, target }
1021
+ }
1022
+
1023
+ export function parseOpsRestoreArmAck(body: unknown): OpsRestoreArmAck | null {
1024
+ const undo = readMatch(prop(body, 'undo'), OPAQUE_TOKEN)
1025
+ return exactKeys(body, ['step', 'undo']) && prop(body, 'step') === 'arm' && undo !== null ? { step: 'arm', undo } : null
1026
+ }
1027
+
1028
+ export function parseOpsRestoreVerifyAck(body: unknown): OpsRestoreVerifyAck | null {
1029
+ if (!exactKeys(body, ['step', 'sentinel', 'bookmark']) || prop(body, 'step') !== 'verify') return null
1030
+ const sentinel = readEnum(prop(body, 'sentinel'), SENTINEL_STATES)
1031
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
1032
+ return sentinel === null || bookmark === null ? null : { step: 'verify', sentinel, bookmark }
1033
+ }
1034
+
1035
+ /** The most timers one answer lists; the rest are counted in `omitted`. */
1036
+ export const OPS_TIMERS_CAP = 500
1037
+ /** A timer's stack keeps at most this many frames, the ones nearest the call that registered the work. */
1038
+ export const OPS_TIMER_STACK_MAX_FRAMES = 20
1039
+ /** A timer's stack is at most this many UTF-8 bytes, cut after it is scrubbed. */
1040
+ export const OPS_TIMER_STACK_MAX_BYTES = 4 * 1024
1041
+
1042
+ /** `POST /__fabrika/ops/timers`: reads the tracker, or with `track` switches it on or off first. In memory only. */
1043
+ export interface OpsTimersRequest {
1044
+ readonly object: string
1045
+ readonly track: boolean | null
1046
+ }
1047
+
1048
+ /** A pending timer or `waitUntil` promise and the stack that registered it, which may name application code: content. */
1049
+ export interface OpsTimer {
1050
+ readonly kind: 'timeout' | 'interval' | 'waitUntil'
1051
+ readonly since: string
1052
+ /** `null` exactly for `waitUntil`. */
1053
+ readonly delayMs: number | null
1054
+ readonly stack: string
1055
+ }
1056
+
1057
+ /** The object's live timers, oldest first (`data.content.read`). */
1058
+ export interface OpsTimersView {
1059
+ readonly tracking: boolean
1060
+ readonly timers: readonly OpsTimer[]
1061
+ readonly omitted: number
1062
+ }
1063
+
1064
+ export function parseOpsTimersRequest(body: unknown): OpsTimersRequest | null {
1065
+ const object = parseApplicationObjectName(prop(body, 'object'))
1066
+ const track = prop(body, 'track')
1067
+ return exactKeys(body, ['object', 'track']) && object !== null && (track === null || typeof track === 'boolean') ? { object, track } : null
1068
+ }
1069
+
1070
+ export function parseOpsTimersView(body: unknown): OpsTimersView | null {
1071
+ if (!exactKeys(body, ['tracking', 'timers', 'omitted'])) return null
1072
+ const tracking = prop(body, 'tracking')
1073
+ const raw = prop(body, 'timers')
1074
+ const timers = Array.isArray(raw) && raw.length <= OPS_TIMERS_CAP ? readList(raw, readTimer) : null
1075
+ const omitted = readCount(prop(body, 'omitted'))
1076
+ return typeof tracking !== 'boolean' || timers === null || omitted === null ? null : { tracking, timers, omitted }
1077
+ }
1078
+
1079
+ /** The status of a data operation's refusal. It is answered only after authentication. */
1080
+ export const OPS_DATA_REFUSED_STATUS = 422
1081
+
1082
+ /** Why the object refused an export, import or restore step. */
1083
+ export const OPS_DATA_REFUSALS = [
1084
+ 'wrong_mode',
1085
+ 'serving_object',
1086
+ 'unsupported_schema',
1087
+ 'not_fresh',
1088
+ 'no_import',
1089
+ 'invalid_manifest',
1090
+ 'fuzzy_dump',
1091
+ 'part_mismatch',
1092
+ 'ledger_mismatch',
1093
+ 'schema_mismatch',
1094
+ 'verify_mismatch',
1095
+ 'bookmark_unavailable',
1096
+ 'row_too_large',
1097
+ ] as const
1098
+
1099
+ export type OpsDataRefusalReason = (typeof OPS_DATA_REFUSALS)[number]
1100
+
1101
+ /** The body of a data refusal; `table` names the table at fault, an identifier and never a value. */
1102
+ export interface OpsDataRefusal {
1103
+ readonly refused: OpsDataRefusalReason
1104
+ readonly table: string | null
1105
+ }
1106
+
1107
+ export function parseOpsDataRefusal(body: unknown): OpsDataRefusal | null {
1108
+ const refused = readEnum(prop(body, 'refused'), OPS_DATA_REFUSALS)
1109
+ const table = readNullable(prop(body, 'table'), (value) => readMatch(value, TABLE_NAME))
1110
+ return exactKeys(body, ['refused', 'table']) && refused !== null && table !== undefined ? { refused, table } : null
1111
+ }
1112
+
1113
+ const VIEW_KEYS = ['release', 'maintenance', 'database', 'migrations', 'scheduler', 'jobs', 'files', 'webhooks', 'bootFailure']
1114
+ const FILE_STATUSES: readonly OpsFileStatus[] = ['pending', 'quarantined', 'live', 'rejected']
1115
+ const WEBHOOK_STATES = ['claimed', 'completed'] as const
1116
+ const JOB_STATUSES = ['succeeded', 'failed'] as const
1117
+ /** The form `Date.prototype.toISOString` and SQLite's `%Y-%m-%dT%H:%M:%fZ` both write. */
1118
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
1119
+ /** `@fabrika/db`'s `isPlainIdentifier`: the only table names the data layer admits. */
1120
+ const TABLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/
1121
+ /** The contract build's authored-name rule (`@fabrika/app/contract`), which a file kind follows. */
1122
+ const CONTRACT_NAME = /^[A-Za-z][A-Za-z0-9_]*$/
1123
+ /** `@fabrika/db`'s SQLite migration runner: a bundle name, a migration file name and a file's SHA-256 hex. */
1124
+ const MIGRATION_BUNDLE = /^[a-z][a-z0-9-]*$/
1125
+ const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
1126
+ const MIGRATION_CHECKSUM = /^[0-9a-f]{64}$/
1127
+ const SHA256_HEX = /^[0-9a-f]{64}$/
1128
+ /** A dump id or a sentinel: a UUID as Control writes one. */
1129
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
1130
+ /** A token R2 or the object hands out and nobody reads into: an upload id, an ETag, a bookmark. Printable ASCII, no space. */
1131
+ const OPAQUE_TOKEN = /^[!-~]{1,1024}$/
1132
+ /** The decimal text `cast(c as text)` writes for an integer: no leading zero, no `-0`. */
1133
+ const INT64_TEXT = /^(?:0|-?[1-9][0-9]{0,18})$/
1134
+ const INT64_MIN = -(2n ** 63n)
1135
+ const INT64_MAX = 2n ** 63n - 1n
1136
+ /**
1137
+ * `hex(c)` of a blob, and `hex(CAST(c AS BLOB))` of text. Bun's regex engine answers `false` for `^(?:[0-9A-F]{2})*$`
1138
+ * on a string of a few megabytes, so the pairing is a length check.
1139
+ */
1140
+ function isBytesHex(value: string): boolean {
1141
+ return value.length % 2 === 0 && /^[0-9A-F]*$/.test(value)
1142
+ }
1143
+ const MANIFEST_KEYS = [
1144
+ 'format',
1145
+ 'dump',
1146
+ 'object',
1147
+ 'consistent',
1148
+ 'createdAt',
1149
+ 'bookmark',
1150
+ 'release',
1151
+ 'contractDigest',
1152
+ 'ddl',
1153
+ 'migrations',
1154
+ 'tables',
1155
+ 'parts',
1156
+ ]
1157
+ const EXPORT_SCOPE_KEYS = ['object', 'generation', 'consistent', 'dump']
1158
+ const IMPORT_SCOPE_KEYS = ['object', 'generation', 'source']
1159
+ const SCHEMA_TYPES = ['table', 'index', 'trigger', 'view'] as const
1160
+ const SENTINEL_STATES = ['present', 'absent'] as const
1161
+ const TIMER_KINDS = ['timeout', 'interval', 'waitUntil'] as const
1162
+
1163
+ /** Every field of the view but the boot failure, whose form differs between the two views. */
1164
+ function readViewFields(body: unknown): Omit<OpsView, 'bootFailure'> | null {
1165
+ if (!exactKeys(body, VIEW_KEYS)) return null
1166
+ const release = prop(body, 'release')
1167
+ const maintenance = readMaintenance(prop(body, 'maintenance'))
1168
+ const database = readDatabase(prop(body, 'database'))
1169
+ const migrations = readList(prop(body, 'migrations'), readMigration)
1170
+ const scheduler = readScheduler(prop(body, 'scheduler'))
1171
+ const jobs = readList(prop(body, 'jobs'), readJob)
1172
+ const files = readList(prop(body, 'files'), readFileCount)
1173
+ const webhooks = readList(prop(body, 'webhooks'), readWebhookCount)
1174
+ if (
1175
+ typeof release !== 'string' || !FRAMEWORK_RELEASE_PATTERN.test(release) || maintenance === null || database === null || migrations === null
1176
+ || scheduler === null || jobs === null || files === null || webhooks === null
1177
+ ) {
1178
+ return null
1179
+ }
1180
+ return { release, maintenance, database, migrations, scheduler, jobs, files, webhooks }
1181
+ }
1182
+
1183
+ function readMaintenance(value: unknown): OpsMaintenance | null {
1184
+ if (!exactKeys(value, ['mode', 'generation', 'published'])) return null
1185
+ const mode = readMode(prop(value, 'mode'))
1186
+ const rawGeneration = prop(value, 'generation')
1187
+ const generation = rawGeneration === null ? null : readGeneration(rawGeneration)
1188
+ const published = prop(value, 'published')
1189
+ if (mode === null || (rawGeneration !== null && generation === null) || typeof published !== 'boolean') return null
1190
+ return { mode, generation, published }
1191
+ }
1192
+
1193
+ function readDatabase(value: unknown): OpsDatabase | null {
1194
+ if (!exactKeys(value, ['sizeBytes', 'tables'])) return null
1195
+ const sizeBytes = readCount(prop(value, 'sizeBytes'))
1196
+ const tables = readList(prop(value, 'tables'), readTableCount)
1197
+ return sizeBytes === null || tables === null ? null : { sizeBytes, tables }
1198
+ }
1199
+
1200
+ function readTableCount(value: unknown): OpsTableCount | null {
1201
+ if (!exactKeys(value, ['name', 'rows'])) return null
1202
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1203
+ const rows = readCount(prop(value, 'rows'))
1204
+ return name === null || rows === null || rows > OPS_ROW_COUNT_CAP ? null : { name, rows }
1205
+ }
1206
+
1207
+ function readMigration(value: unknown): OpsMigration | null {
1208
+ if (!exactKeys(value, ['bundle', 'name', 'checksum', 'appliedAt'])) return null
1209
+ const bundle = readMatch(prop(value, 'bundle'), MIGRATION_BUNDLE)
1210
+ const name = readMatch(prop(value, 'name'), MIGRATION_NAME)
1211
+ const checksum = readMatch(prop(value, 'checksum'), MIGRATION_CHECKSUM)
1212
+ const appliedAt = readTimestamp(prop(value, 'appliedAt'))
1213
+ return bundle === null || name === null || checksum === null || appliedAt === null ? null : { bundle, name, checksum, appliedAt }
1214
+ }
1215
+
1216
+ function readScheduler(value: unknown): OpsScheduler | null {
1217
+ if (!exactKeys(value, ['alarm'])) return null
1218
+ const raw = prop(value, 'alarm')
1219
+ const alarm = raw === null ? null : readTimestamp(raw)
1220
+ return raw !== null && alarm === null ? null : { alarm }
1221
+ }
1222
+
1223
+ /** A framework job of the application runtime (`fabrika-file-sweep`): reserved by its `-`, which no contract job name holds. */
1224
+ const FRAMEWORK_JOB_NAME = /^fabrika-[a-z][a-z0-9-]{0,55}$/
1225
+
1226
+ function readJob(value: unknown): OpsJob | null {
1227
+ if (!exactKeys(value, ['job', 'lastStatus', 'lastStartedAt', 'lastFinishedAt', 'lastDurationMs'])) return null
1228
+ const raw = prop(value, 'job')
1229
+ const job = readMatch(raw, WORKLOAD_NAME) ?? readMatch(raw, FRAMEWORK_JOB_NAME)
1230
+ const lastStatus = readNullable(prop(value, 'lastStatus'), (status) => readEnum(status, JOB_STATUSES))
1231
+ const lastStartedAt = readNullable(prop(value, 'lastStartedAt'), readTimestamp)
1232
+ const lastFinishedAt = readNullable(prop(value, 'lastFinishedAt'), readTimestamp)
1233
+ const lastDurationMs = readNullable(prop(value, 'lastDurationMs'), readCount)
1234
+ if (job === null || lastStatus === undefined || lastStartedAt === undefined || lastFinishedAt === undefined || lastDurationMs === undefined) {
1235
+ return null
1236
+ }
1237
+ return { job, lastStatus, lastStartedAt, lastFinishedAt, lastDurationMs }
1238
+ }
1239
+
1240
+ function readFileCount(value: unknown): OpsFileCount | null {
1241
+ if (!exactKeys(value, ['kind', 'status', 'count'])) return null
1242
+ const kind = readMatch(prop(value, 'kind'), CONTRACT_NAME)
1243
+ const status = readEnum(prop(value, 'status'), FILE_STATUSES)
1244
+ const count = readCount(prop(value, 'count'))
1245
+ return kind === null || status === null || count === null ? null : { kind, status, count }
1246
+ }
1247
+
1248
+ function readWebhookCount(value: unknown): OpsWebhookCount | null {
1249
+ if (!exactKeys(value, ['webhook', 'state', 'count'])) return null
1250
+ const webhook = readMatch(prop(value, 'webhook'), WORKLOAD_NAME)
1251
+ const state = readEnum(prop(value, 'state'), WEBHOOK_STATES)
1252
+ const count = readCount(prop(value, 'count'))
1253
+ return webhook === null || state === null || count === null ? null : { webhook, state, count }
1254
+ }
1255
+
1256
+ /** `undefined` for a value that is no boot failure; the caller reads `null` as none before calling. */
1257
+ function readBootFailure(value: unknown): OpsBootFailure | undefined {
1258
+ const at = readTimestamp(prop(value, 'at'))
1259
+ return exactKeys(value, ['at']) && at !== null ? { at } : undefined
1260
+ }
1261
+
1262
+ function readBootFailureContent(value: unknown): OpsBootFailureContent | undefined {
1263
+ if (!exactKeys(value, ['at', 'message', 'stack'])) return undefined
1264
+ const at = readTimestamp(prop(value, 'at'))
1265
+ const message = prop(value, 'message')
1266
+ const stack = prop(value, 'stack')
1267
+ if (at === null || typeof message !== 'string' || (stack !== null && typeof stack !== 'string')) return undefined
1268
+ return { at, message, stack }
1269
+ }
1270
+
1271
+ /** Whether `value` is a plain object holding exactly `keys`: no key missing, none unknown. */
1272
+ function exactKeys(value: unknown, keys: readonly string[]): boolean {
1273
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
1274
+ const own = Object.keys(value)
1275
+ return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key))
1276
+ }
1277
+
1278
+ function readList<T>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1279
+ if (!Array.isArray(value)) return null
1280
+ const items: T[] = []
1281
+ for (const item of value) {
1282
+ const parsed = read(item)
1283
+ if (parsed === null) return null
1284
+ items.push(parsed)
1285
+ }
1286
+ return items
1287
+ }
1288
+
1289
+ /** `null` stays `null`; anything else is read, and `undefined` marks a value `read` refused. */
1290
+ function readNullable<T>(value: unknown, read: (value: unknown) => T | null): T | null | undefined {
1291
+ if (value === null) return null
1292
+ return read(value) ?? undefined
1293
+ }
1294
+
1295
+ function readEnum<T extends string>(value: unknown, members: readonly T[]): T | null {
1296
+ return members.find((member) => member === value) ?? null
1297
+ }
1298
+
1299
+ function readMode(value: unknown): OpsMode | null {
1300
+ return readEnum(value, OPS_MODES)
1301
+ }
1302
+
1303
+ /** A generation Control allocated: a positive safe integer. */
1304
+ function readGeneration(value: unknown): number | null {
1305
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
1306
+ }
1307
+
1308
+ function readCount(value: unknown): number | null {
1309
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null
1310
+ }
1311
+
1312
+ /** An identifier the platform or the contract names, in its owner's format: free text never fits one. */
1313
+ function readMatch(value: unknown, pattern: RegExp): string | null {
1314
+ return typeof value === 'string' && pattern.test(value) ? value : null
1315
+ }
1316
+
1317
+ /** `Date` rolls an impossible date over (`02-31` to `03-03`), so the instant must print back as the same text. */
1318
+ function readTimestamp(value: unknown): string | null {
1319
+ if (typeof value !== 'string' || !TIMESTAMP.test(value)) return null
1320
+ const instant = new Date(value)
1321
+ return !Number.isNaN(instant.getTime()) && instant.toISOString() === value ? value : null
1322
+ }
1323
+
1324
+ /** `undefined` for text that is no JSON; every reader refuses it. */
1325
+ function parseJson(text: string): unknown {
1326
+ try {
1327
+ return JSON.parse(text)
1328
+ } catch {
1329
+ return undefined
1330
+ }
1331
+ }
1332
+
1333
+ // The errors name the rule a value broke and never the value, which is a tenant's data.
1334
+ function encodeValue(value: OpsDumpValue): string | null {
1335
+ if (value === null) return null
1336
+ switch (value.type) {
1337
+ case 'integer':
1338
+ if (!isInt64Text(value.value)) throw new Error('a dump integer must be the decimal text of a 64-bit integer')
1339
+ return `i:${value.value}`
1340
+ case 'real':
1341
+ if (Number.isNaN(value.value)) throw new Error('a dump real must not be NaN')
1342
+ return `r:${realText(value.value)}`
1343
+ case 'text':
1344
+ if (!isBytesHex(value.value)) throw new Error('dump text must be the upper-case hex of its bytes')
1345
+ return `t:${value.value}`
1346
+ case 'blob':
1347
+ if (!isBytesHex(value.value)) throw new Error('a dump blob must be upper-case hex')
1348
+ return `b:${value.value}`
1349
+ }
1350
+ }
1351
+
1352
+ /** ECMAScript's shortest text that reads back as the same double, with the sign of a negative zero kept. */
1353
+ function realText(value: number): string {
1354
+ return Object.is(value, -0) ? '-0' : String(value)
1355
+ }
1356
+
1357
+ function isInt64Text(text: string): boolean {
1358
+ if (!INT64_TEXT.test(text)) return false
1359
+ const value = BigInt(text)
1360
+ return value >= INT64_MIN && value <= INT64_MAX
1361
+ }
1362
+
1363
+ /** `undefined` for an encoded value outside the rules; `null` is SQL's NULL. */
1364
+ function readValue(raw: unknown): OpsDumpValue | undefined {
1365
+ if (raw === null) return null
1366
+ if (typeof raw !== 'string') return undefined
1367
+ const text = raw.slice(2)
1368
+ switch (raw.slice(0, 2)) {
1369
+ case 'i:':
1370
+ return isInt64Text(text) ? { type: 'integer', value: text } : undefined
1371
+ case 'r:': {
1372
+ const value = Number(text)
1373
+ return !Number.isNaN(value) && realText(value) === text ? { type: 'real', value } : undefined
1374
+ }
1375
+ case 't:':
1376
+ return isBytesHex(text) ? { type: 'text', value: text } : undefined
1377
+ case 'b:':
1378
+ return isBytesHex(text) ? { type: 'blob', value: text } : undefined
1379
+ default:
1380
+ return undefined
1381
+ }
1382
+ }
1383
+
1384
+ function readRowValues(raw: unknown): OpsDumpValue[] | null {
1385
+ if (!Array.isArray(raw)) return null
1386
+ const values: OpsDumpValue[] = []
1387
+ for (const item of raw) {
1388
+ const value = readValue(item)
1389
+ if (value === undefined) return null
1390
+ values.push(value)
1391
+ }
1392
+ return values
1393
+ }
1394
+
1395
+ function readCursor(value: unknown): OpsDumpCursor | null {
1396
+ if (!exactKeys(value, ['table', 'after', 'rows', 'hash'])) return null
1397
+ const table = readMatch(prop(value, 'table'), TABLE_NAME)
1398
+ const after = readNullable(prop(value, 'after'), readRowid)
1399
+ const rows = readCount(prop(value, 'rows'))
1400
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1401
+ if (table === null || after === undefined || rows === null || hash === null) return null
1402
+ // Before a table's first row nothing is folded; past a row, at least that row is.
1403
+ if ((after === null) !== (rows === 0) || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1404
+ return { table, after, rows, hash }
1405
+ }
1406
+
1407
+ function readRowid(value: unknown): string | null {
1408
+ return typeof value === 'string' && isInt64Text(value) ? value : null
1409
+ }
1410
+
1411
+ /** Tables in load order, each named once. */
1412
+ function readTables(value: unknown): readonly OpsDumpTable[] | null {
1413
+ const tables = readList(value, readDumpTable)
1414
+ return tables !== null && distinct(tables.map((table) => table.name)) ? tables : null
1415
+ }
1416
+
1417
+ function readDumpTable(value: unknown): OpsDumpTable | null {
1418
+ if (!exactKeys(value, ['name', 'rows', 'hash'])) return null
1419
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1420
+ const rows = readCount(prop(value, 'rows'))
1421
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1422
+ if (name === null || rows === null || hash === null || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1423
+ return { name, rows, hash }
1424
+ }
1425
+
1426
+ function readDumpPart(value: unknown): OpsDumpPart | null {
1427
+ if (!exactKeys(value, ['part', 'size', 'sha256'])) return null
1428
+ return readPartFields(value)
1429
+ }
1430
+
1431
+ function readUploadedPart(value: unknown): OpsUploadedPart | null {
1432
+ if (!exactKeys(value, ['part', 'size', 'sha256', 'etag'])) return null
1433
+ const fields = readPartFields(value)
1434
+ const etag = readMatch(prop(value, 'etag'), OPAQUE_TOKEN)
1435
+ return fields === null || etag === null ? null : { ...fields, etag }
1436
+ }
1437
+
1438
+ function readPartFields(value: unknown): OpsDumpPart | null {
1439
+ const part = readPartNumber(prop(value, 'part'))
1440
+ const size = readCount(prop(value, 'size'))
1441
+ const sha256 = readMatch(prop(value, 'sha256'), SHA256_HEX)
1442
+ return part === null || size === null || size === 0 || size > OPS_DUMP_PART_SIZE || sha256 === null ? null : { part, size, sha256 }
1443
+ }
1444
+
1445
+ /** Every part of an upload: numbered 1 to n without a gap, each of the fixed size but the last. */
1446
+ function readWholeParts<T extends OpsDumpPart>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1447
+ const parts = readList(value, read)
1448
+ if (parts === null || parts.length === 0 || parts.length > OPS_DUMP_MAX_PARTS) return null
1449
+ const whole = parts.every((part, index) => part.part === index + 1 && (index === parts.length - 1 || part.size === OPS_DUMP_PART_SIZE))
1450
+ return whole ? parts : null
1451
+ }
1452
+
1453
+ function readPartNumber(value: unknown): number | null {
1454
+ const part = readGeneration(value)
1455
+ return part !== null && part <= OPS_DUMP_MAX_PARTS ? part : null
1456
+ }
1457
+
1458
+ function readSchemaEntry(value: unknown): OpsDumpSchemaEntry | null {
1459
+ if (!exactKeys(value, ['type', 'name', 'table', 'sql'])) return null
1460
+ const type = readEnum(prop(value, 'type'), SCHEMA_TYPES)
1461
+ const name = prop(value, 'name')
1462
+ const table = prop(value, 'table')
1463
+ const sql = prop(value, 'sql')
1464
+ if (type === null || typeof name !== 'string' || name === '' || typeof table !== 'string' || table === '' || typeof sql !== 'string' || sql === '') {
1465
+ return null
1466
+ }
1467
+ // A table's entry names itself; an index or a trigger names any table or view, which the importer compares as text.
1468
+ if (type === 'table' && (name !== table || !TABLE_NAME.test(name))) return null
1469
+ return { type, name, table, sql }
1470
+ }
1471
+
1472
+ function readExportScope(body: unknown): OpsExportScope | null {
1473
+ const object = parseApplicationObjectName(prop(body, 'object'))
1474
+ const generation = readNullable(prop(body, 'generation'), readGeneration)
1475
+ const consistent = prop(body, 'consistent')
1476
+ const dump = readMatch(prop(body, 'dump'), UUID)
1477
+ if (object === null || generation === undefined || typeof consistent !== 'boolean' || dump === null) return null
1478
+ return consistent === (generation !== null) ? { object, generation, consistent, dump } : null
1479
+ }
1480
+
1481
+ function readSource(value: unknown): OpsDumpSource | null {
1482
+ if (!exactKeys(value, ['object', 'dump'])) return null
1483
+ const object = parseApplicationObjectName(prop(value, 'object'))
1484
+ const dump = readMatch(prop(value, 'dump'), UUID)
1485
+ return object === null || dump === null ? null : { object, dump }
1486
+ }
1487
+
1488
+ function boundedStack(stack: string): boolean {
1489
+ return new TextEncoder().encode(stack).length <= OPS_TIMER_STACK_MAX_BYTES && stack.split('\n').length <= OPS_TIMER_STACK_MAX_FRAMES
1490
+ }
1491
+
1492
+ function readTimer(value: unknown): OpsTimer | null {
1493
+ if (!exactKeys(value, ['kind', 'since', 'delayMs', 'stack'])) return null
1494
+ const kind = readEnum(prop(value, 'kind'), TIMER_KINDS)
1495
+ const since = readTimestamp(prop(value, 'since'))
1496
+ const delayMs = readNullable(prop(value, 'delayMs'), readCount)
1497
+ const stack = prop(value, 'stack')
1498
+ if (kind === null || since === null || delayMs === undefined || typeof stack !== 'string' || !boundedStack(stack)) return null
1499
+ return (kind === 'waitUntil') === (delayMs === null) ? { kind, since, delayMs, stack } : null
1500
+ }
1501
+
1502
+ /** A foreign key with its parent's columns named. */
1503
+ interface ResolvedForeignKey {
1504
+ readonly parent: string
1505
+ readonly columns: readonly string[]
1506
+ readonly references: readonly string[]
1507
+ }
1508
+
1509
+ interface DescribedTable {
1510
+ readonly table: OpsDumpSchemaTable
1511
+ readonly keyset: string
1512
+ readonly parents: readonly ResolvedForeignKey[]
1513
+ }
1514
+
1515
+ const ROWID_NAMES = ['rowid', '_rowid_', 'oid']
1516
+
1517
+ function unsupported(table: string | null): OpsDataRefusal {
1518
+ return { refused: 'unsupported_schema', table }
1519
+ }
1520
+
1521
+ /** A rowid table's `INTEGER PRIMARY KEY` is the rowid itself; any other primary key gets an automatic index (`origin` `pk`). */
1522
+ function rowidName(table: OpsDumpSchemaTable): string | null {
1523
+ const key = table.columns.filter((column) => column.primaryKey > 0)
1524
+ const [only] = key
1525
+ if (key.length === 1 && only !== undefined && asciiLower(only.type) === 'integer' && !table.indexes.some((index) => index.origin === 'pk')) {
1526
+ return only.name
1527
+ }
1528
+ const taken = new Set(table.columns.map((column) => asciiLower(column.name)))
1529
+ return ROWID_NAMES.find((name) => !taken.has(name)) ?? null
1530
+ }
1531
+
1532
+ function resolveForeignKeys(table: OpsDumpSchemaTable, tables: ReadonlyMap<string, OpsDumpSchemaTable>): readonly ResolvedForeignKey[] | null {
1533
+ const keys: ResolvedForeignKey[] = []
1534
+ for (const key of table.foreignKeys) {
1535
+ const parent = tables.get(asciiLower(key.parent))
1536
+ if (parent === undefined || key.initiallyDeferred || key.columns.length === 0) return null
1537
+ const primaryKey = parent.columns.filter((column) => column.primaryKey > 0).sort((left, right) => left.primaryKey - right.primaryKey)
1538
+ const references = key.references ?? primaryKey.map((column) => column.name)
1539
+ if (references.length !== key.columns.length) return null
1540
+ keys.push({ parent: parent.name, columns: key.columns, references })
1541
+ }
1542
+ return keys
1543
+ }
1544
+
1545
+ /** Each table's cycle, named by its first table: two tables share one exactly when each reaches the other through parents. */
1546
+ function cycleIds(tables: readonly DescribedTable[]): ReadonlyMap<string, string> {
1547
+ const parents = new Map(tables.map(({ table, parents }) => [table.name, parents]))
1548
+ const reach = new Map<string, ReadonlySet<string>>()
1549
+ for (const { table } of tables) {
1550
+ const seen = new Set<string>()
1551
+ const pending = [table.name]
1552
+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
1553
+ for (const key of parents.get(name) ?? []) {
1554
+ if (!seen.has(key.parent)) {
1555
+ seen.add(key.parent)
1556
+ pending.push(key.parent)
1557
+ }
1558
+ }
1559
+ }
1560
+ reach.set(table.name, seen)
1561
+ }
1562
+ const ids = new Map<string, string>()
1563
+ for (const { table } of tables) {
1564
+ const first = tables.find(({ table: other }) => reach.get(table.name)?.has(other.name) === true && reach.get(other.name)?.has(table.name) === true)
1565
+ ids.set(table.name, first === undefined || compareNames(first.table.name, table.name) > 0 ? table.name : first.table.name)
1566
+ }
1567
+ return ids
1568
+ }
1569
+
1570
+ /** Repeatedly the first table by name whose every parent outside its own cycle is placed. */
1571
+ function loadOrder(tables: readonly DescribedTable[], cycle: ReadonlyMap<string, string>): readonly DescribedTable[] {
1572
+ const placed = new Set<string>()
1573
+ const order: DescribedTable[] = []
1574
+ while (order.length < tables.length) {
1575
+ const next = tables.find(({ table, parents }) =>
1576
+ !placed.has(table.name) && parents.every((key) => placed.has(key.parent) || cycle.get(key.parent) === cycle.get(table.name))
1577
+ )
1578
+ // The cycles form a directed acyclic graph, so one always has every outside parent placed.
1579
+ if (next === undefined) throw new Error('a foreign-key graph without a table to place')
1580
+ placed.add(next.table.name)
1581
+ order.push(next)
1582
+ }
1583
+ return order
1584
+ }
1585
+
1586
+ /** Whether every deferred column of `table` can hold `NULL` from its part until the link pass, with nothing to violate. */
1587
+ function takesTemporaryNull(table: OpsDumpSchemaTable, deferred: readonly OpsDumpSchemaColumn[], referenced: ReadonlySet<string>): boolean {
1588
+ if (table.checked || table.columns.some((column) => column.generated && column.notNull)) return false
1589
+ if (table.indexes.some((index) => index.unique && (index.partial || index.columns.includes(null)))) return false
1590
+ return deferred.every((column) => !column.notNull && column.primaryKey === 0 && !referenced.has(columnKey(table.name, column.name)))
1591
+ }
1592
+
1593
+ function columnKey(table: string, column: string): string {
1594
+ return `${table}\n${asciiLower(column)}`
1595
+ }
1596
+
1597
+ /** SQLite compares identifiers case-insensitively in ASCII only. */
1598
+ function asciiLower(value: string): string {
1599
+ return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase())
1600
+ }
1601
+
1602
+ /** Code-unit order, which no locale changes. */
1603
+ function compareNames(left: string, right: string): number {
1604
+ return left < right ? -1 : left > right ? 1 : 0
1605
+ }
1606
+
1607
+ function quoteIdentifier(name: string): string {
1608
+ return `"${name.replaceAll('"', '""')}"`
1609
+ }
1610
+
1611
+ function hexBytes(hex: string): Uint8Array {
1612
+ if (!isBytesHex(hex)) throw new Error('dump bytes must be upper-case hex')
1613
+ const bytes = new Uint8Array(hex.length / 2)
1614
+ for (let index = 0; index < bytes.length; index++) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16)
1615
+ return bytes
1616
+ }
1617
+
1618
+ /** Whether a cursor resumes a table the same answer reports finished. */
1619
+ function continuesFinished(tables: readonly OpsDumpTable[], next: OpsDumpCursor | null): boolean {
1620
+ return next !== null && tables.some((table) => table.name === next.table)
1621
+ }
1622
+
1623
+ function utf8Length(text: string): number {
1624
+ return new TextEncoder().encode(text).length
1625
+ }
1626
+
1627
+ function distinct(values: readonly string[]): boolean {
1628
+ return new Set(values).size === values.length
1629
+ }
1630
+
1631
+ function sameNames(left: readonly string[], right: readonly string[]): boolean {
1632
+ const names = new Set(left)
1633
+ return distinct(left) && distinct(right) && left.length === right.length && right.every((name) => names.has(name))
1634
+ }