@fabrika/auth-core 0.9.0-cloudflare.2 → 0.9.0-cloudflare.3

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 CHANGED
@@ -28,7 +28,7 @@ export const OPS_METHOD = 'POST'
28
28
  export const OPS_CONTENT_TYPE = 'application/json'
29
29
 
30
30
  /** The operations the object serves, each at `opsPath(operation)`. */
31
- export const OPS_OPERATIONS = ['inspect', 'state', 'migrate'] as const
31
+ export const OPS_OPERATIONS = ['inspect', 'state', 'migrate', 'export', 'import', 'restore', 'timers'] as const
32
32
 
33
33
  export type OpsOperation = (typeof OPS_OPERATIONS)[number]
34
34
 
@@ -207,7 +207,7 @@ export interface OpsScheduler {
207
207
  readonly alarm: string | null
208
208
  }
209
209
 
210
- /** A job's last run and its outcome. */
210
+ /** A job's last run and its outcome: a contract job, or a framework job such as `fabrika-file-sweep`. */
211
211
  export interface OpsJob {
212
212
  readonly job: string
213
213
  readonly lastStatus: 'succeeded' | 'failed' | null
@@ -324,6 +324,862 @@ export function parseOpsContentView(body: unknown): OpsContentView | null {
324
324
  return view === null ? null : { ...view, bootFailure }
325
325
  }
326
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
+ /**
590
+ * Every name a `CHECK` constraint of the table's SQL reads, ASCII-lowercase and unquoted (keywords included), so a
591
+ * column it does not list cannot change what a `CHECK` answers. Empty for a table without one; `null` from a reader
592
+ * that cannot tell, which counts as naming every column.
593
+ */
594
+ readonly checkNames: readonly string[] | null
595
+ readonly columns: readonly OpsDumpSchemaColumn[]
596
+ readonly indexes: readonly OpsDumpSchemaIndex[]
597
+ readonly foreignKeys: readonly OpsDumpSchemaForeignKey[]
598
+ }
599
+
600
+ /** Every table a dump holds: `sqlite_schema`'s tables but SQLite's internal ones, `sqlite_sequence` excepted, and `_cf_`'s. */
601
+ export interface OpsDumpSchema {
602
+ readonly tables: readonly OpsDumpSchemaTable[]
603
+ }
604
+
605
+ /** How one table is dumped and loaded. */
606
+ export interface OpsDumpTablePlan {
607
+ readonly name: string
608
+ /** The name that reads the rowid: the `INTEGER PRIMARY KEY` column, else the first of `rowid`, `_rowid_`, `oid` no column takes. */
609
+ readonly keyset: string
610
+ /** Every column that is not generated, in declaration order: a row is the rowid, then these. */
611
+ readonly columns: readonly string[]
612
+ /** The columns of the foreign keys inside a cycle, which a part writes `NULL` and the link pass sets, in declaration order. */
613
+ readonly deferred: readonly string[]
614
+ }
615
+
616
+ /** The tables of a dump in load order: every parent outside a table's own cycle comes before it. */
617
+ export interface OpsDumpPlan {
618
+ readonly tables: readonly OpsDumpTablePlan[]
619
+ }
620
+
621
+ /**
622
+ * The one rule both the producer, at export `begin`, and the importer, at import `begin`, apply to a schema: the plan
623
+ * a dump is written and loaded by, or an `unsupported_schema` refusal naming the table. A foreign key whose parent lies
624
+ * in its own table's cycle (the table itself included) is loaded `NULL` and linked once every row is in, so each of its
625
+ * columns must take a temporary `NULL`: nullable, outside the primary key, referenced by no foreign key, named by no
626
+ * `CHECK`, in a table without a `NOT NULL` generated column, a generated column a `CHECK` names, or a partial, expression
627
+ * or generated-column unique index. A `WITHOUT ROWID` or
628
+ * virtual table, a table without a name that reads its rowid, a foreign key to a table outside the dump or without the
629
+ * named key, and a foreign key checked only at commit are refused.
630
+ */
631
+ export function planOpsDump(schema: OpsDumpSchema): OpsDumpPlan | OpsDataRefusal {
632
+ const sorted = [...schema.tables].sort((left, right) => compareNames(left.name, right.name))
633
+ if (!sorted.every((table) => TABLE_NAME.test(table.name)) || !distinct(sorted.map((table) => table.name))) return unsupported(null)
634
+ const byName = new Map(sorted.map((table) => [table.name, table]))
635
+ const tables: DescribedTable[] = []
636
+ for (const table of sorted) {
637
+ const keyset = table.virtual || table.withoutRowid ? null : rowidName(table)
638
+ const parents = resolveForeignKeys(table, byName)
639
+ if (keyset === null || parents === null) return unsupported(table.name)
640
+ tables.push({ table, keyset, parents })
641
+ }
642
+ const cycle = cycleIds(tables)
643
+ const referenced = new Set(tables.flatMap(({ parents }) => parents.flatMap((key) => key.references.map((column) => columnKey(key.parent, column)))))
644
+ const plans: OpsDumpTablePlan[] = []
645
+ for (const { table, keyset, parents } of loadOrder(tables, cycle)) {
646
+ const inCycle = parents.filter((key) => cycle.get(key.parent) === cycle.get(table.name))
647
+ const deferredNames = new Set(inCycle.flatMap((key) => key.columns.map(asciiLower)))
648
+ const deferred = table.columns.filter((column) => deferredNames.has(asciiLower(column.name)))
649
+ if (deferred.length > 0 && !takesTemporaryNull(table, deferred, referenced)) return unsupported(table.name)
650
+ plans.push({
651
+ name: table.name,
652
+ keyset,
653
+ columns: table.columns.filter((column) => !column.generated).map((column) => column.name),
654
+ deferred: deferred.map((column) => column.name),
655
+ })
656
+ }
657
+ return { tables: plans }
658
+ }
659
+
660
+ /** Where a dump or a verification stands in a table: the last rowid read, and the count and hash folded so far. */
661
+ export interface OpsDumpCursor {
662
+ readonly table: string
663
+ /** The rowid of the last row read, as decimal text; `null` before the table's first row. */
664
+ readonly after: string | null
665
+ readonly rows: number
666
+ readonly hash: string
667
+ }
668
+
669
+ /** A table a dump holds, with its exact row count and its hash. */
670
+ export interface OpsDumpTable {
671
+ readonly name: string
672
+ readonly rows: number
673
+ readonly hash: string
674
+ }
675
+
676
+ /** A part of a dump's data object: its number from 1, its size in bytes and the SHA-256 hex of its bytes. */
677
+ export interface OpsDumpPart {
678
+ readonly part: number
679
+ readonly size: number
680
+ readonly sha256: string
681
+ }
682
+
683
+ /** A part as R2 accepted it; Control completes the upload with the ETags. */
684
+ export interface OpsUploadedPart extends OpsDumpPart {
685
+ readonly etag: string
686
+ }
687
+
688
+ /** One `sqlite_schema` entry with SQL: an automatic index has none and is not listed. */
689
+ export interface OpsDumpSchemaEntry {
690
+ readonly type: 'table' | 'index' | 'trigger' | 'view'
691
+ readonly name: string
692
+ readonly table: string
693
+ readonly sql: string
694
+ }
695
+
696
+ /** `manifest.json`, written beside the data once its upload completed. `tables` is in load order. */
697
+ export interface OpsDumpManifest {
698
+ readonly format: typeof OPS_DUMP_FORMAT
699
+ readonly dump: string
700
+ readonly object: string
701
+ readonly consistent: boolean
702
+ readonly createdAt: string
703
+ /** The object's bookmark when the dump began. */
704
+ readonly bookmark: string
705
+ readonly release: string
706
+ readonly contractDigest: string
707
+ readonly ddl: readonly OpsDumpSchemaEntry[]
708
+ readonly migrations: readonly OpsMigration[]
709
+ readonly tables: readonly OpsDumpTable[]
710
+ readonly parts: readonly OpsDumpPart[]
711
+ }
712
+
713
+ /**
714
+ * A manifest Control holds or an answer carries; every table's DDL lists it, its parts are whole, and its
715
+ * `JSON.stringify` is at most `OPS_DUMP_MANIFEST_MAX_BYTES` in UTF-8, wherever it came from.
716
+ */
717
+ export function parseOpsDumpManifest(body: unknown): OpsDumpManifest | null {
718
+ if (!exactKeys(body, MANIFEST_KEYS) || prop(body, 'format') !== OPS_DUMP_FORMAT) return null
719
+ const dump = readMatch(prop(body, 'dump'), UUID)
720
+ const object = parseApplicationObjectName(prop(body, 'object'))
721
+ const consistent = prop(body, 'consistent')
722
+ const createdAt = readTimestamp(prop(body, 'createdAt'))
723
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
724
+ const release = readMatch(prop(body, 'release'), FRAMEWORK_RELEASE_PATTERN)
725
+ const contractDigest = prop(body, 'contractDigest')
726
+ const ddl = readList(prop(body, 'ddl'), readSchemaEntry)
727
+ const migrations = readList(prop(body, 'migrations'), readMigration)
728
+ const tables = readTables(prop(body, 'tables'))
729
+ const parts = readWholeParts(prop(body, 'parts'), readDumpPart)
730
+ if (
731
+ dump === null || object === null || typeof consistent !== 'boolean' || createdAt === null || bookmark === null || release === null
732
+ || typeof contractDigest !== 'string' || !isDigest(contractDigest) || ddl === null || migrations === null || tables === null || parts === null
733
+ ) {
734
+ return null
735
+ }
736
+ const declared = ddl.filter((entry) => entry.type === 'table').map((entry) => entry.name)
737
+ if (!distinct(ddl.map((entry) => `${entry.type} ${entry.name}`)) || !sameNames(declared, tables.map((table) => table.name))) return null
738
+ const manifest: OpsDumpManifest = {
739
+ format: OPS_DUMP_FORMAT,
740
+ dump,
741
+ object,
742
+ consistent,
743
+ createdAt,
744
+ bookmark,
745
+ release,
746
+ contractDigest,
747
+ ddl,
748
+ migrations,
749
+ tables,
750
+ parts,
751
+ }
752
+ return utf8Length(JSON.stringify(manifest)) <= OPS_DUMP_MANIFEST_MAX_BYTES ? manifest : null
753
+ }
754
+
755
+ /** A manifest's text as R2 holds it, refused above `OPS_DUMP_MANIFEST_MAX_BYTES` before it is parsed. */
756
+ export function readOpsDumpManifest(text: string): OpsDumpManifest | null {
757
+ if (utf8Length(text) > OPS_DUMP_MANIFEST_MAX_BYTES) return null
758
+ return parseOpsDumpManifest(parseJson(text))
759
+ }
760
+
761
+ /** What every export step names: a consistent backup carries the published generation, a diagnostic export none. */
762
+ export interface OpsExportScope {
763
+ readonly object: string
764
+ readonly generation: number | null
765
+ readonly consistent: boolean
766
+ readonly dump: string
767
+ }
768
+
769
+ /** Starts the multipart upload of the dump's data. */
770
+ export interface OpsExportBegin extends OpsExportScope {
771
+ readonly step: 'begin'
772
+ }
773
+
774
+ /** Fills part `part` from `cursor`, `null` only for the first part; a retry replaces the part. */
775
+ export interface OpsExportPart extends OpsExportScope {
776
+ readonly step: 'part'
777
+ readonly uploadId: string
778
+ readonly part: number
779
+ readonly cursor: OpsDumpCursor | null
780
+ }
781
+
782
+ /** Completes the upload from the parts and tables Control recorded, and writes the manifest. */
783
+ export interface OpsExportComplete extends OpsExportScope {
784
+ readonly step: 'complete'
785
+ readonly uploadId: string
786
+ readonly bookmark: string
787
+ readonly parts: readonly OpsUploadedPart[]
788
+ readonly tables: readonly OpsDumpTable[]
789
+ }
790
+
791
+ /** `POST /__fabrika/ops/export`: one step of a dump. */
792
+ export type OpsExportRequest = OpsExportBegin | OpsExportPart | OpsExportComplete
793
+
794
+ export interface OpsExportBeginAck {
795
+ readonly step: 'begin'
796
+ readonly uploadId: string
797
+ readonly bookmark: string
798
+ }
799
+
800
+ /** The part written, the tables it finished in load order, and where the next part starts: `null` once all is read. */
801
+ export interface OpsExportPartAck {
802
+ readonly step: 'part'
803
+ readonly uploaded: OpsUploadedPart
804
+ readonly tables: readonly OpsDumpTable[]
805
+ readonly next: OpsDumpCursor | null
806
+ }
807
+
808
+ export interface OpsExportCompleteAck {
809
+ readonly step: 'complete'
810
+ readonly manifest: OpsDumpManifest
811
+ }
812
+
813
+ export function parseOpsExportRequest(body: unknown): OpsExportRequest | null {
814
+ const scope = readExportScope(body)
815
+ if (scope === null) return null
816
+ switch (prop(body, 'step')) {
817
+ case 'begin':
818
+ return exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step']) ? { ...scope, step: 'begin' } : null
819
+ case 'part': {
820
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'part', 'cursor'])) return null
821
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
822
+ const part = readPartNumber(prop(body, 'part'))
823
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
824
+ if (uploadId === null || part === null || cursor === undefined || (part === 1) !== (cursor === null)) return null
825
+ return { ...scope, step: 'part', uploadId, part, cursor }
826
+ }
827
+ case 'complete': {
828
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'bookmark', 'parts', 'tables'])) return null
829
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
830
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
831
+ const parts = readWholeParts(prop(body, 'parts'), readUploadedPart)
832
+ const tables = readTables(prop(body, 'tables'))
833
+ if (uploadId === null || bookmark === null || parts === null || tables === null) return null
834
+ return { ...scope, step: 'complete', uploadId, bookmark, parts, tables }
835
+ }
836
+ default:
837
+ return null
838
+ }
839
+ }
840
+
841
+ export function parseOpsExportBeginAck(body: unknown): OpsExportBeginAck | null {
842
+ if (!exactKeys(body, ['step', 'uploadId', 'bookmark']) || prop(body, 'step') !== 'begin') return null
843
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
844
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
845
+ return uploadId === null || bookmark === null ? null : { step: 'begin', uploadId, bookmark }
846
+ }
847
+
848
+ export function parseOpsExportPartAck(body: unknown): OpsExportPartAck | null {
849
+ if (!exactKeys(body, ['step', 'uploaded', 'tables', 'next']) || prop(body, 'step') !== 'part') return null
850
+ const uploaded = readUploadedPart(prop(body, 'uploaded'))
851
+ const tables = readTables(prop(body, 'tables'))
852
+ const next = readNullable(prop(body, 'next'), readCursor)
853
+ if (uploaded === null || tables === null || next === undefined || continuesFinished(tables, next)) return null
854
+ // Only the last part may be short: R2 refuses an upload whose other parts differ in size.
855
+ if (next !== null && uploaded.size !== OPS_DUMP_PART_SIZE) return null
856
+ return { step: 'part', uploaded, tables, next }
857
+ }
858
+
859
+ export function parseOpsExportCompleteAck(body: unknown): OpsExportCompleteAck | null {
860
+ if (!exactKeys(body, ['step', 'manifest']) || prop(body, 'step') !== 'complete') return null
861
+ const manifest = parseOpsDumpManifest(prop(body, 'manifest'))
862
+ return manifest === null ? null : { step: 'complete', manifest }
863
+ }
864
+
865
+ /** The consistent backup an import loads: always under `__fabrika/backups/`. */
866
+ export interface OpsDumpSource {
867
+ readonly object: string
868
+ readonly dump: string
869
+ }
870
+
871
+ /** What every import step names: the fresh target, published `inspect` under the operation's generation, and the backup. */
872
+ export interface OpsImportScope {
873
+ readonly object: string
874
+ readonly generation: number
875
+ readonly source: OpsDumpSource
876
+ }
877
+
878
+ /** Verifies the manifest, checks the target is fresh, and migrates it to the manifest's ledger. */
879
+ export interface OpsImportBegin extends OpsImportScope {
880
+ readonly step: 'begin'
881
+ }
882
+
883
+ /** Loads part `part`, writing a foreign key the load order cannot satisfy as `NULL`. */
884
+ export interface OpsImportPart extends OpsImportScope {
885
+ readonly step: 'part'
886
+ readonly part: number
887
+ }
888
+
889
+ /** Sets the foreign keys part `part` wrote as `NULL`, once every part is loaded. */
890
+ export interface OpsImportLink extends OpsImportScope {
891
+ readonly step: 'link'
892
+ readonly part: number
893
+ }
894
+
895
+ /** Reads the loaded tables back from `cursor`, `null` at the start, and compares counts and hashes with the manifest. */
896
+ export interface OpsImportVerify extends OpsImportScope {
897
+ readonly step: 'verify'
898
+ readonly cursor: OpsDumpCursor | null
899
+ }
900
+
901
+ /** Clears the import marker once every table verified, so Control may open the object. */
902
+ export interface OpsImportComplete extends OpsImportScope {
903
+ readonly step: 'complete'
904
+ }
905
+
906
+ /** Wipes an `inspect` object that holds an import marker and serves no traffic, with `deleteAll()`. */
907
+ export interface OpsImportDiscard {
908
+ readonly step: 'discard'
909
+ readonly object: string
910
+ readonly generation: number
911
+ }
912
+
913
+ /** `POST /__fabrika/ops/import`: one step of loading a consistent backup into a fresh object. */
914
+ export type OpsImportRequest = OpsImportBegin | OpsImportPart | OpsImportLink | OpsImportVerify | OpsImportComplete | OpsImportDiscard
915
+
916
+ export interface OpsImportBeginAck {
917
+ readonly step: 'begin'
918
+ readonly parts: number
919
+ }
920
+
921
+ /** `deferred` counts the loaded rows whose deferred foreign keys wait for the link pass. */
922
+ export interface OpsImportPartAck {
923
+ readonly step: 'part'
924
+ readonly part: number
925
+ readonly rows: number
926
+ readonly deferred: number
927
+ }
928
+
929
+ export interface OpsImportLinkAck {
930
+ readonly step: 'link'
931
+ readonly part: number
932
+ readonly rows: number
933
+ }
934
+
935
+ /** The tables verified in this step, each matching the manifest, and where the next step starts: `null` once all match. */
936
+ export interface OpsImportVerifyAck {
937
+ readonly step: 'verify'
938
+ readonly tables: readonly OpsDumpTable[]
939
+ readonly next: OpsDumpCursor | null
940
+ }
941
+
942
+ export interface OpsImportCompleteAck {
943
+ readonly step: 'complete'
944
+ readonly source: OpsDumpSource
945
+ }
946
+
947
+ export interface OpsImportDiscardAck {
948
+ readonly step: 'discard'
949
+ }
950
+
951
+ export function parseOpsImportRequest(body: unknown): OpsImportRequest | null {
952
+ const step = prop(body, 'step')
953
+ const object = parseApplicationObjectName(prop(body, 'object'))
954
+ const generation = readGeneration(prop(body, 'generation'))
955
+ if (object === null || generation === null) return null
956
+ if (step === 'discard') return exactKeys(body, ['step', 'object', 'generation']) ? { step, object, generation } : null
957
+ const source = readSource(prop(body, 'source'))
958
+ if (source === null) return null
959
+ const scope = { object, generation, source }
960
+ switch (step) {
961
+ case 'begin':
962
+ case 'complete':
963
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step']) ? { ...scope, step } : null
964
+ case 'part':
965
+ case 'link': {
966
+ const part = readPartNumber(prop(body, 'part'))
967
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'part']) && part !== null ? { ...scope, step, part } : null
968
+ }
969
+ case 'verify': {
970
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
971
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'cursor']) && cursor !== undefined ? { ...scope, step, cursor } : null
972
+ }
973
+ default:
974
+ return null
975
+ }
976
+ }
977
+
978
+ export function parseOpsImportBeginAck(body: unknown): OpsImportBeginAck | null {
979
+ const parts = readPartNumber(prop(body, 'parts'))
980
+ return exactKeys(body, ['step', 'parts']) && prop(body, 'step') === 'begin' && parts !== null ? { step: 'begin', parts } : null
981
+ }
982
+
983
+ export function parseOpsImportPartAck(body: unknown): OpsImportPartAck | null {
984
+ if (!exactKeys(body, ['step', 'part', 'rows', 'deferred']) || prop(body, 'step') !== 'part') return null
985
+ const part = readPartNumber(prop(body, 'part'))
986
+ const rows = readCount(prop(body, 'rows'))
987
+ const deferred = readCount(prop(body, 'deferred'))
988
+ return part === null || rows === null || deferred === null ? null : { step: 'part', part, rows, deferred }
989
+ }
990
+
991
+ export function parseOpsImportLinkAck(body: unknown): OpsImportLinkAck | null {
992
+ if (!exactKeys(body, ['step', 'part', 'rows']) || prop(body, 'step') !== 'link') return null
993
+ const part = readPartNumber(prop(body, 'part'))
994
+ const rows = readCount(prop(body, 'rows'))
995
+ return part === null || rows === null ? null : { step: 'link', part, rows }
996
+ }
997
+
998
+ export function parseOpsImportVerifyAck(body: unknown): OpsImportVerifyAck | null {
999
+ if (!exactKeys(body, ['step', 'tables', 'next']) || prop(body, 'step') !== 'verify') return null
1000
+ const tables = readTables(prop(body, 'tables'))
1001
+ const next = readNullable(prop(body, 'next'), readCursor)
1002
+ if (tables === null || next === undefined || continuesFinished(tables, next)) return null
1003
+ return { step: 'verify', tables, next }
1004
+ }
1005
+
1006
+ export function parseOpsImportCompleteAck(body: unknown): OpsImportCompleteAck | null {
1007
+ const source = readSource(prop(body, 'source'))
1008
+ return exactKeys(body, ['step', 'source']) && prop(body, 'step') === 'complete' && source !== null ? { step: 'complete', source } : null
1009
+ }
1010
+
1011
+ export function parseOpsImportDiscardAck(body: unknown): OpsImportDiscardAck | null {
1012
+ return exactKeys(body, ['step']) && prop(body, 'step') === 'discard' ? { step: 'discard' } : null
1013
+ }
1014
+
1015
+ /**
1016
+ * Writes the sentinel (the operation's id) into the object's KV storage, and answers the current bookmark and the
1017
+ * bookmark of `at`, which Control records before it arms anything.
1018
+ */
1019
+ export interface OpsRestorePrepare {
1020
+ readonly step: 'prepare'
1021
+ readonly object: string
1022
+ readonly generation: number
1023
+ readonly sentinel: string
1024
+ readonly at: string
1025
+ }
1026
+
1027
+ /** Arms the restore of `target` for the next session, answers, then resets the object. */
1028
+ export interface OpsRestoreArm {
1029
+ readonly step: 'arm'
1030
+ readonly object: string
1031
+ readonly generation: number
1032
+ readonly sentinel: string
1033
+ readonly target: string
1034
+ }
1035
+
1036
+ /** Reads, after the reset, whether the sentinel is still there. It writes nothing, so it carries no generation. */
1037
+ export interface OpsRestoreVerify {
1038
+ readonly step: 'verify'
1039
+ readonly object: string
1040
+ readonly sentinel: string
1041
+ }
1042
+
1043
+ /** `POST /__fabrika/ops/restore`: one step of rewinding an `inspect` object that serves no traffic. */
1044
+ export type OpsRestoreRequest = OpsRestorePrepare | OpsRestoreArm | OpsRestoreVerify
1045
+
1046
+ export interface OpsRestorePrepareAck {
1047
+ readonly step: 'prepare'
1048
+ readonly current: string
1049
+ readonly target: string
1050
+ }
1051
+
1052
+ /** May be lost to the reset; `verify` reconciles. */
1053
+ export interface OpsRestoreArmAck {
1054
+ readonly step: 'arm'
1055
+ readonly undo: string
1056
+ }
1057
+
1058
+ /** A sentinel still present means the restore did not happen. */
1059
+ export interface OpsRestoreVerifyAck {
1060
+ readonly step: 'verify'
1061
+ readonly sentinel: 'present' | 'absent'
1062
+ readonly bookmark: string
1063
+ }
1064
+
1065
+ export function parseOpsRestoreRequest(body: unknown): OpsRestoreRequest | null {
1066
+ const step = prop(body, 'step')
1067
+ const object = parseApplicationObjectName(prop(body, 'object'))
1068
+ const sentinel = readMatch(prop(body, 'sentinel'), UUID)
1069
+ if (object === null || sentinel === null) return null
1070
+ if (step === 'verify') return exactKeys(body, ['step', 'object', 'sentinel']) ? { step, object, sentinel } : null
1071
+ const generation = readGeneration(prop(body, 'generation'))
1072
+ if (generation === null) return null
1073
+ if (step === 'prepare') {
1074
+ const at = readTimestamp(prop(body, 'at'))
1075
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'at']) && at !== null ? { step, object, generation, sentinel, at } : null
1076
+ }
1077
+ if (step === 'arm') {
1078
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1079
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'target']) && target !== null
1080
+ ? { step, object, generation, sentinel, target }
1081
+ : null
1082
+ }
1083
+ return null
1084
+ }
1085
+
1086
+ export function parseOpsRestorePrepareAck(body: unknown): OpsRestorePrepareAck | null {
1087
+ if (!exactKeys(body, ['step', 'current', 'target']) || prop(body, 'step') !== 'prepare') return null
1088
+ const current = readMatch(prop(body, 'current'), OPAQUE_TOKEN)
1089
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1090
+ return current === null || target === null ? null : { step: 'prepare', current, target }
1091
+ }
1092
+
1093
+ export function parseOpsRestoreArmAck(body: unknown): OpsRestoreArmAck | null {
1094
+ const undo = readMatch(prop(body, 'undo'), OPAQUE_TOKEN)
1095
+ return exactKeys(body, ['step', 'undo']) && prop(body, 'step') === 'arm' && undo !== null ? { step: 'arm', undo } : null
1096
+ }
1097
+
1098
+ export function parseOpsRestoreVerifyAck(body: unknown): OpsRestoreVerifyAck | null {
1099
+ if (!exactKeys(body, ['step', 'sentinel', 'bookmark']) || prop(body, 'step') !== 'verify') return null
1100
+ const sentinel = readEnum(prop(body, 'sentinel'), SENTINEL_STATES)
1101
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
1102
+ return sentinel === null || bookmark === null ? null : { step: 'verify', sentinel, bookmark }
1103
+ }
1104
+
1105
+ /** The most timers one answer lists; the rest are counted in `omitted`. */
1106
+ export const OPS_TIMERS_CAP = 500
1107
+ /** A timer's stack keeps at most this many frames, the ones nearest the call that registered the work. */
1108
+ export const OPS_TIMER_STACK_MAX_FRAMES = 20
1109
+ /** A timer's stack is at most this many UTF-8 bytes, cut after it is scrubbed. */
1110
+ export const OPS_TIMER_STACK_MAX_BYTES = 4 * 1024
1111
+
1112
+ /** `POST /__fabrika/ops/timers`: reads the tracker, or with `track` switches it on or off first. In memory only. */
1113
+ export interface OpsTimersRequest {
1114
+ readonly object: string
1115
+ readonly track: boolean | null
1116
+ }
1117
+
1118
+ /** A pending timer or `waitUntil` promise and the stack that registered it, which may name application code: content. */
1119
+ export interface OpsTimer {
1120
+ readonly kind: 'timeout' | 'interval' | 'waitUntil'
1121
+ readonly since: string
1122
+ /** `null` exactly for `waitUntil`. */
1123
+ readonly delayMs: number | null
1124
+ readonly stack: string
1125
+ }
1126
+
1127
+ /** The object's live timers, oldest first (`data.content.read`). */
1128
+ export interface OpsTimersView {
1129
+ readonly tracking: boolean
1130
+ readonly timers: readonly OpsTimer[]
1131
+ readonly omitted: number
1132
+ }
1133
+
1134
+ export function parseOpsTimersRequest(body: unknown): OpsTimersRequest | null {
1135
+ const object = parseApplicationObjectName(prop(body, 'object'))
1136
+ const track = prop(body, 'track')
1137
+ return exactKeys(body, ['object', 'track']) && object !== null && (track === null || typeof track === 'boolean') ? { object, track } : null
1138
+ }
1139
+
1140
+ export function parseOpsTimersView(body: unknown): OpsTimersView | null {
1141
+ if (!exactKeys(body, ['tracking', 'timers', 'omitted'])) return null
1142
+ const tracking = prop(body, 'tracking')
1143
+ const raw = prop(body, 'timers')
1144
+ const timers = Array.isArray(raw) && raw.length <= OPS_TIMERS_CAP ? readList(raw, readTimer) : null
1145
+ const omitted = readCount(prop(body, 'omitted'))
1146
+ return typeof tracking !== 'boolean' || timers === null || omitted === null ? null : { tracking, timers, omitted }
1147
+ }
1148
+
1149
+ /** The status of a data operation's refusal. It is answered only after authentication. */
1150
+ export const OPS_DATA_REFUSED_STATUS = 422
1151
+
1152
+ /** Why the object refused an export, import or restore step. */
1153
+ export const OPS_DATA_REFUSALS = [
1154
+ 'wrong_mode',
1155
+ 'serving_object',
1156
+ 'unsupported_schema',
1157
+ 'not_fresh',
1158
+ 'no_import',
1159
+ 'invalid_manifest',
1160
+ 'fuzzy_dump',
1161
+ 'part_mismatch',
1162
+ 'ledger_mismatch',
1163
+ 'schema_mismatch',
1164
+ 'verify_mismatch',
1165
+ 'bookmark_unavailable',
1166
+ 'row_too_large',
1167
+ ] as const
1168
+
1169
+ export type OpsDataRefusalReason = (typeof OPS_DATA_REFUSALS)[number]
1170
+
1171
+ /** The body of a data refusal; `table` names the table at fault, an identifier and never a value. */
1172
+ export interface OpsDataRefusal {
1173
+ readonly refused: OpsDataRefusalReason
1174
+ readonly table: string | null
1175
+ }
1176
+
1177
+ export function parseOpsDataRefusal(body: unknown): OpsDataRefusal | null {
1178
+ const refused = readEnum(prop(body, 'refused'), OPS_DATA_REFUSALS)
1179
+ const table = readNullable(prop(body, 'table'), (value) => readMatch(value, TABLE_NAME))
1180
+ return exactKeys(body, ['refused', 'table']) && refused !== null && table !== undefined ? { refused, table } : null
1181
+ }
1182
+
327
1183
  const VIEW_KEYS = ['release', 'maintenance', 'database', 'migrations', 'scheduler', 'jobs', 'files', 'webhooks', 'bootFailure']
328
1184
  const FILE_STATUSES: readonly OpsFileStatus[] = ['pending', 'quarantined', 'live', 'rejected']
329
1185
  const WEBHOOK_STATES = ['claimed', 'completed'] as const
@@ -338,6 +1194,41 @@ const CONTRACT_NAME = /^[A-Za-z][A-Za-z0-9_]*$/
338
1194
  const MIGRATION_BUNDLE = /^[a-z][a-z0-9-]*$/
339
1195
  const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
340
1196
  const MIGRATION_CHECKSUM = /^[0-9a-f]{64}$/
1197
+ const SHA256_HEX = /^[0-9a-f]{64}$/
1198
+ /** A dump id or a sentinel: a UUID as Control writes one. */
1199
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
1200
+ /** A token R2 or the object hands out and nobody reads into: an upload id, an ETag, a bookmark. Printable ASCII, no space. */
1201
+ const OPAQUE_TOKEN = /^[!-~]{1,1024}$/
1202
+ /** The decimal text `cast(c as text)` writes for an integer: no leading zero, no `-0`. */
1203
+ const INT64_TEXT = /^(?:0|-?[1-9][0-9]{0,18})$/
1204
+ const INT64_MIN = -(2n ** 63n)
1205
+ const INT64_MAX = 2n ** 63n - 1n
1206
+ /**
1207
+ * `hex(c)` of a blob, and `hex(CAST(c AS BLOB))` of text. Bun's regex engine answers `false` for `^(?:[0-9A-F]{2})*$`
1208
+ * on a string of a few megabytes, so the pairing is a length check.
1209
+ */
1210
+ function isBytesHex(value: string): boolean {
1211
+ return value.length % 2 === 0 && /^[0-9A-F]*$/.test(value)
1212
+ }
1213
+ const MANIFEST_KEYS = [
1214
+ 'format',
1215
+ 'dump',
1216
+ 'object',
1217
+ 'consistent',
1218
+ 'createdAt',
1219
+ 'bookmark',
1220
+ 'release',
1221
+ 'contractDigest',
1222
+ 'ddl',
1223
+ 'migrations',
1224
+ 'tables',
1225
+ 'parts',
1226
+ ]
1227
+ const EXPORT_SCOPE_KEYS = ['object', 'generation', 'consistent', 'dump']
1228
+ const IMPORT_SCOPE_KEYS = ['object', 'generation', 'source']
1229
+ const SCHEMA_TYPES = ['table', 'index', 'trigger', 'view'] as const
1230
+ const SENTINEL_STATES = ['present', 'absent'] as const
1231
+ const TIMER_KINDS = ['timeout', 'interval', 'waitUntil'] as const
341
1232
 
342
1233
  /** Every field of the view but the boot failure, whose form differs between the two views. */
343
1234
  function readViewFields(body: unknown): Omit<OpsView, 'bootFailure'> | null {
@@ -399,9 +1290,13 @@ function readScheduler(value: unknown): OpsScheduler | null {
399
1290
  return raw !== null && alarm === null ? null : { alarm }
400
1291
  }
401
1292
 
1293
+ /** A framework job of the application runtime (`fabrika-file-sweep`): reserved by its `-`, which no contract job name holds. */
1294
+ const FRAMEWORK_JOB_NAME = /^fabrika-[a-z][a-z0-9-]{0,55}$/
1295
+
402
1296
  function readJob(value: unknown): OpsJob | null {
403
1297
  if (!exactKeys(value, ['job', 'lastStatus', 'lastStartedAt', 'lastFinishedAt', 'lastDurationMs'])) return null
404
- const job = readMatch(prop(value, 'job'), WORKLOAD_NAME)
1298
+ const raw = prop(value, 'job')
1299
+ const job = readMatch(raw, WORKLOAD_NAME) ?? readMatch(raw, FRAMEWORK_JOB_NAME)
405
1300
  const lastStatus = readNullable(prop(value, 'lastStatus'), (status) => readEnum(status, JOB_STATUSES))
406
1301
  const lastStartedAt = readNullable(prop(value, 'lastStartedAt'), readTimestamp)
407
1302
  const lastFinishedAt = readNullable(prop(value, 'lastFinishedAt'), readTimestamp)
@@ -495,3 +1390,322 @@ function readTimestamp(value: unknown): string | null {
495
1390
  const instant = new Date(value)
496
1391
  return !Number.isNaN(instant.getTime()) && instant.toISOString() === value ? value : null
497
1392
  }
1393
+
1394
+ /** `undefined` for text that is no JSON; every reader refuses it. */
1395
+ function parseJson(text: string): unknown {
1396
+ try {
1397
+ return JSON.parse(text)
1398
+ } catch {
1399
+ return undefined
1400
+ }
1401
+ }
1402
+
1403
+ // The errors name the rule a value broke and never the value, which is a tenant's data.
1404
+ function encodeValue(value: OpsDumpValue): string | null {
1405
+ if (value === null) return null
1406
+ switch (value.type) {
1407
+ case 'integer':
1408
+ if (!isInt64Text(value.value)) throw new Error('a dump integer must be the decimal text of a 64-bit integer')
1409
+ return `i:${value.value}`
1410
+ case 'real':
1411
+ if (Number.isNaN(value.value)) throw new Error('a dump real must not be NaN')
1412
+ return `r:${realText(value.value)}`
1413
+ case 'text':
1414
+ if (!isBytesHex(value.value)) throw new Error('dump text must be the upper-case hex of its bytes')
1415
+ return `t:${value.value}`
1416
+ case 'blob':
1417
+ if (!isBytesHex(value.value)) throw new Error('a dump blob must be upper-case hex')
1418
+ return `b:${value.value}`
1419
+ }
1420
+ }
1421
+
1422
+ /** ECMAScript's shortest text that reads back as the same double, with the sign of a negative zero kept. */
1423
+ function realText(value: number): string {
1424
+ return Object.is(value, -0) ? '-0' : String(value)
1425
+ }
1426
+
1427
+ function isInt64Text(text: string): boolean {
1428
+ if (!INT64_TEXT.test(text)) return false
1429
+ const value = BigInt(text)
1430
+ return value >= INT64_MIN && value <= INT64_MAX
1431
+ }
1432
+
1433
+ /** `undefined` for an encoded value outside the rules; `null` is SQL's NULL. */
1434
+ function readValue(raw: unknown): OpsDumpValue | undefined {
1435
+ if (raw === null) return null
1436
+ if (typeof raw !== 'string') return undefined
1437
+ const text = raw.slice(2)
1438
+ switch (raw.slice(0, 2)) {
1439
+ case 'i:':
1440
+ return isInt64Text(text) ? { type: 'integer', value: text } : undefined
1441
+ case 'r:': {
1442
+ const value = Number(text)
1443
+ return !Number.isNaN(value) && realText(value) === text ? { type: 'real', value } : undefined
1444
+ }
1445
+ case 't:':
1446
+ return isBytesHex(text) ? { type: 'text', value: text } : undefined
1447
+ case 'b:':
1448
+ return isBytesHex(text) ? { type: 'blob', value: text } : undefined
1449
+ default:
1450
+ return undefined
1451
+ }
1452
+ }
1453
+
1454
+ function readRowValues(raw: unknown): OpsDumpValue[] | null {
1455
+ if (!Array.isArray(raw)) return null
1456
+ const values: OpsDumpValue[] = []
1457
+ for (const item of raw) {
1458
+ const value = readValue(item)
1459
+ if (value === undefined) return null
1460
+ values.push(value)
1461
+ }
1462
+ return values
1463
+ }
1464
+
1465
+ function readCursor(value: unknown): OpsDumpCursor | null {
1466
+ if (!exactKeys(value, ['table', 'after', 'rows', 'hash'])) return null
1467
+ const table = readMatch(prop(value, 'table'), TABLE_NAME)
1468
+ const after = readNullable(prop(value, 'after'), readRowid)
1469
+ const rows = readCount(prop(value, 'rows'))
1470
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1471
+ if (table === null || after === undefined || rows === null || hash === null) return null
1472
+ // Before a table's first row nothing is folded; past a row, at least that row is.
1473
+ if ((after === null) !== (rows === 0) || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1474
+ return { table, after, rows, hash }
1475
+ }
1476
+
1477
+ function readRowid(value: unknown): string | null {
1478
+ return typeof value === 'string' && isInt64Text(value) ? value : null
1479
+ }
1480
+
1481
+ /** Tables in load order, each named once. */
1482
+ function readTables(value: unknown): readonly OpsDumpTable[] | null {
1483
+ const tables = readList(value, readDumpTable)
1484
+ return tables !== null && distinct(tables.map((table) => table.name)) ? tables : null
1485
+ }
1486
+
1487
+ function readDumpTable(value: unknown): OpsDumpTable | null {
1488
+ if (!exactKeys(value, ['name', 'rows', 'hash'])) return null
1489
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1490
+ const rows = readCount(prop(value, 'rows'))
1491
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1492
+ if (name === null || rows === null || hash === null || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1493
+ return { name, rows, hash }
1494
+ }
1495
+
1496
+ function readDumpPart(value: unknown): OpsDumpPart | null {
1497
+ if (!exactKeys(value, ['part', 'size', 'sha256'])) return null
1498
+ return readPartFields(value)
1499
+ }
1500
+
1501
+ function readUploadedPart(value: unknown): OpsUploadedPart | null {
1502
+ if (!exactKeys(value, ['part', 'size', 'sha256', 'etag'])) return null
1503
+ const fields = readPartFields(value)
1504
+ const etag = readMatch(prop(value, 'etag'), OPAQUE_TOKEN)
1505
+ return fields === null || etag === null ? null : { ...fields, etag }
1506
+ }
1507
+
1508
+ function readPartFields(value: unknown): OpsDumpPart | null {
1509
+ const part = readPartNumber(prop(value, 'part'))
1510
+ const size = readCount(prop(value, 'size'))
1511
+ const sha256 = readMatch(prop(value, 'sha256'), SHA256_HEX)
1512
+ return part === null || size === null || size === 0 || size > OPS_DUMP_PART_SIZE || sha256 === null ? null : { part, size, sha256 }
1513
+ }
1514
+
1515
+ /** Every part of an upload: numbered 1 to n without a gap, each of the fixed size but the last. */
1516
+ function readWholeParts<T extends OpsDumpPart>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1517
+ const parts = readList(value, read)
1518
+ if (parts === null || parts.length === 0 || parts.length > OPS_DUMP_MAX_PARTS) return null
1519
+ const whole = parts.every((part, index) => part.part === index + 1 && (index === parts.length - 1 || part.size === OPS_DUMP_PART_SIZE))
1520
+ return whole ? parts : null
1521
+ }
1522
+
1523
+ function readPartNumber(value: unknown): number | null {
1524
+ const part = readGeneration(value)
1525
+ return part !== null && part <= OPS_DUMP_MAX_PARTS ? part : null
1526
+ }
1527
+
1528
+ function readSchemaEntry(value: unknown): OpsDumpSchemaEntry | null {
1529
+ if (!exactKeys(value, ['type', 'name', 'table', 'sql'])) return null
1530
+ const type = readEnum(prop(value, 'type'), SCHEMA_TYPES)
1531
+ const name = prop(value, 'name')
1532
+ const table = prop(value, 'table')
1533
+ const sql = prop(value, 'sql')
1534
+ if (type === null || typeof name !== 'string' || name === '' || typeof table !== 'string' || table === '' || typeof sql !== 'string' || sql === '') {
1535
+ return null
1536
+ }
1537
+ // A table's entry names itself; an index or a trigger names any table or view, which the importer compares as text.
1538
+ if (type === 'table' && (name !== table || !TABLE_NAME.test(name))) return null
1539
+ return { type, name, table, sql }
1540
+ }
1541
+
1542
+ function readExportScope(body: unknown): OpsExportScope | null {
1543
+ const object = parseApplicationObjectName(prop(body, 'object'))
1544
+ const generation = readNullable(prop(body, 'generation'), readGeneration)
1545
+ const consistent = prop(body, 'consistent')
1546
+ const dump = readMatch(prop(body, 'dump'), UUID)
1547
+ if (object === null || generation === undefined || typeof consistent !== 'boolean' || dump === null) return null
1548
+ return consistent === (generation !== null) ? { object, generation, consistent, dump } : null
1549
+ }
1550
+
1551
+ function readSource(value: unknown): OpsDumpSource | null {
1552
+ if (!exactKeys(value, ['object', 'dump'])) return null
1553
+ const object = parseApplicationObjectName(prop(value, 'object'))
1554
+ const dump = readMatch(prop(value, 'dump'), UUID)
1555
+ return object === null || dump === null ? null : { object, dump }
1556
+ }
1557
+
1558
+ function boundedStack(stack: string): boolean {
1559
+ return new TextEncoder().encode(stack).length <= OPS_TIMER_STACK_MAX_BYTES && stack.split('\n').length <= OPS_TIMER_STACK_MAX_FRAMES
1560
+ }
1561
+
1562
+ function readTimer(value: unknown): OpsTimer | null {
1563
+ if (!exactKeys(value, ['kind', 'since', 'delayMs', 'stack'])) return null
1564
+ const kind = readEnum(prop(value, 'kind'), TIMER_KINDS)
1565
+ const since = readTimestamp(prop(value, 'since'))
1566
+ const delayMs = readNullable(prop(value, 'delayMs'), readCount)
1567
+ const stack = prop(value, 'stack')
1568
+ if (kind === null || since === null || delayMs === undefined || typeof stack !== 'string' || !boundedStack(stack)) return null
1569
+ return (kind === 'waitUntil') === (delayMs === null) ? { kind, since, delayMs, stack } : null
1570
+ }
1571
+
1572
+ /** A foreign key with its parent's columns named. */
1573
+ interface ResolvedForeignKey {
1574
+ readonly parent: string
1575
+ readonly columns: readonly string[]
1576
+ readonly references: readonly string[]
1577
+ }
1578
+
1579
+ interface DescribedTable {
1580
+ readonly table: OpsDumpSchemaTable
1581
+ readonly keyset: string
1582
+ readonly parents: readonly ResolvedForeignKey[]
1583
+ }
1584
+
1585
+ const ROWID_NAMES = ['rowid', '_rowid_', 'oid']
1586
+
1587
+ function unsupported(table: string | null): OpsDataRefusal {
1588
+ return { refused: 'unsupported_schema', table }
1589
+ }
1590
+
1591
+ /** A rowid table's `INTEGER PRIMARY KEY` is the rowid itself; any other primary key gets an automatic index (`origin` `pk`). */
1592
+ function rowidName(table: OpsDumpSchemaTable): string | null {
1593
+ const key = table.columns.filter((column) => column.primaryKey > 0)
1594
+ const [only] = key
1595
+ if (key.length === 1 && only !== undefined && asciiLower(only.type) === 'integer' && !table.indexes.some((index) => index.origin === 'pk')) {
1596
+ return only.name
1597
+ }
1598
+ const taken = new Set(table.columns.map((column) => asciiLower(column.name)))
1599
+ return ROWID_NAMES.find((name) => !taken.has(name)) ?? null
1600
+ }
1601
+
1602
+ function resolveForeignKeys(table: OpsDumpSchemaTable, tables: ReadonlyMap<string, OpsDumpSchemaTable>): readonly ResolvedForeignKey[] | null {
1603
+ const keys: ResolvedForeignKey[] = []
1604
+ for (const key of table.foreignKeys) {
1605
+ const parent = tables.get(asciiLower(key.parent))
1606
+ if (parent === undefined || key.initiallyDeferred || key.columns.length === 0) return null
1607
+ const primaryKey = parent.columns.filter((column) => column.primaryKey > 0).sort((left, right) => left.primaryKey - right.primaryKey)
1608
+ const references = key.references ?? primaryKey.map((column) => column.name)
1609
+ if (references.length !== key.columns.length) return null
1610
+ keys.push({ parent: parent.name, columns: key.columns, references })
1611
+ }
1612
+ return keys
1613
+ }
1614
+
1615
+ /** Each table's cycle, named by its first table: two tables share one exactly when each reaches the other through parents. */
1616
+ function cycleIds(tables: readonly DescribedTable[]): ReadonlyMap<string, string> {
1617
+ const parents = new Map(tables.map(({ table, parents }) => [table.name, parents]))
1618
+ const reach = new Map<string, ReadonlySet<string>>()
1619
+ for (const { table } of tables) {
1620
+ const seen = new Set<string>()
1621
+ const pending = [table.name]
1622
+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
1623
+ for (const key of parents.get(name) ?? []) {
1624
+ if (!seen.has(key.parent)) {
1625
+ seen.add(key.parent)
1626
+ pending.push(key.parent)
1627
+ }
1628
+ }
1629
+ }
1630
+ reach.set(table.name, seen)
1631
+ }
1632
+ const ids = new Map<string, string>()
1633
+ for (const { table } of tables) {
1634
+ const first = tables.find(({ table: other }) => reach.get(table.name)?.has(other.name) === true && reach.get(other.name)?.has(table.name) === true)
1635
+ ids.set(table.name, first === undefined || compareNames(first.table.name, table.name) > 0 ? table.name : first.table.name)
1636
+ }
1637
+ return ids
1638
+ }
1639
+
1640
+ /** Repeatedly the first table by name whose every parent outside its own cycle is placed. */
1641
+ function loadOrder(tables: readonly DescribedTable[], cycle: ReadonlyMap<string, string>): readonly DescribedTable[] {
1642
+ const placed = new Set<string>()
1643
+ const order: DescribedTable[] = []
1644
+ while (order.length < tables.length) {
1645
+ const next = tables.find(({ table, parents }) =>
1646
+ !placed.has(table.name) && parents.every((key) => placed.has(key.parent) || cycle.get(key.parent) === cycle.get(table.name))
1647
+ )
1648
+ // The cycles form a directed acyclic graph, so one always has every outside parent placed.
1649
+ if (next === undefined) throw new Error('a foreign-key graph without a table to place')
1650
+ placed.add(next.table.name)
1651
+ order.push(next)
1652
+ }
1653
+ return order
1654
+ }
1655
+
1656
+ /** Whether every deferred column of `table` can hold `NULL` from its part until the link pass, with nothing to violate. */
1657
+ function takesTemporaryNull(table: OpsDumpSchemaTable, deferred: readonly OpsDumpSchemaColumn[], referenced: ReadonlySet<string>): boolean {
1658
+ // A `CHECK` answers the same for a `NULL` in a column it does not read; a generated column may read a deferred one.
1659
+ const checkReads = (column: OpsDumpSchemaColumn): boolean => table.checkNames === null || table.checkNames.includes(asciiLower(column.name))
1660
+ if (table.columns.some((column) => column.generated && (column.notNull || checkReads(column)))) return false
1661
+ // A generated column that reads a deferred one may take one value for many rows while that column is `NULL`.
1662
+ const generated = new Set(table.columns.filter((column) => column.generated).map((column) => asciiLower(column.name)))
1663
+ const indexedGenerated = (index: OpsDumpSchemaIndex): boolean => index.columns.some((name) => name !== null && generated.has(asciiLower(name)))
1664
+ if (table.indexes.some((index) => index.unique && (index.partial || index.columns.includes(null) || indexedGenerated(index)))) return false
1665
+ return deferred.every((column) =>
1666
+ !column.notNull && column.primaryKey === 0 && !referenced.has(columnKey(table.name, column.name)) && !checkReads(column)
1667
+ )
1668
+ }
1669
+
1670
+ function columnKey(table: string, column: string): string {
1671
+ return `${table}\n${asciiLower(column)}`
1672
+ }
1673
+
1674
+ /** SQLite compares identifiers case-insensitively in ASCII only. */
1675
+ function asciiLower(value: string): string {
1676
+ return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase())
1677
+ }
1678
+
1679
+ /** Code-unit order, which no locale changes. */
1680
+ function compareNames(left: string, right: string): number {
1681
+ return left < right ? -1 : left > right ? 1 : 0
1682
+ }
1683
+
1684
+ function quoteIdentifier(name: string): string {
1685
+ return `"${name.replaceAll('"', '""')}"`
1686
+ }
1687
+
1688
+ function hexBytes(hex: string): Uint8Array {
1689
+ if (!isBytesHex(hex)) throw new Error('dump bytes must be upper-case hex')
1690
+ const bytes = new Uint8Array(hex.length / 2)
1691
+ for (let index = 0; index < bytes.length; index++) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16)
1692
+ return bytes
1693
+ }
1694
+
1695
+ /** Whether a cursor resumes a table the same answer reports finished. */
1696
+ function continuesFinished(tables: readonly OpsDumpTable[], next: OpsDumpCursor | null): boolean {
1697
+ return next !== null && tables.some((table) => table.name === next.table)
1698
+ }
1699
+
1700
+ function utf8Length(text: string): number {
1701
+ return new TextEncoder().encode(text).length
1702
+ }
1703
+
1704
+ function distinct(values: readonly string[]): boolean {
1705
+ return new Set(values).size === values.length
1706
+ }
1707
+
1708
+ function sameNames(left: readonly string[], right: readonly string[]): boolean {
1709
+ const names = new Set(left)
1710
+ return distinct(left) && distinct(right) && left.length === right.length && right.every((name) => names.has(name))
1711
+ }