@fabrika/auth-core 0.9.0-dev.5 → 0.9.0-dev.50
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/package.json +3 -2
- package/src/agent.ts +89 -0
- package/src/canonical-path.ts +18 -0
- package/src/client-address.ts +74 -0
- package/src/contract-canonical.ts +168 -2
- package/src/contract-encoding.ts +181 -0
- package/src/contract.ts +220 -17
- package/src/egress.ts +97 -0
- package/src/endpoint-digest.ts +22 -2
- package/src/framework-release.ts +70 -0
- package/src/framework-variables.ts +14 -0
- package/src/iam-mail.ts +354 -0
- package/src/index.ts +7 -0
- package/src/installation-endpoint.ts +3 -2
- package/src/locale.ts +13 -1
- package/src/managed-environment.ts +11 -0
- package/src/membership.ts +12 -4
- package/src/oauth.ts +19 -0
- package/src/ops.ts +487 -16
- package/src/permissions.ts +42 -0
- package/src/public-egress.ts +168 -0
- package/src/requirement.ts +12 -4
- package/src/rpc.ts +137 -9
- package/src/scope-values.ts +123 -0
- package/src/sha256.ts +52 -14
- package/src/token.ts +195 -14
- package/src/types.ts +72 -1
- package/src/wire.ts +2 -1
- package/types/src/agent.d.ts +37 -0
- package/types/src/canonical-path.d.ts +6 -0
- package/types/src/client-address.d.ts +7 -0
- package/types/src/contract-canonical.d.ts +11 -1
- package/types/src/contract-encoding.d.ts +18 -0
- package/types/src/contract.d.ts +205 -16
- package/types/src/egress.d.ts +27 -0
- package/types/src/endpoint-digest.d.ts +5 -0
- package/types/src/framework-release.d.ts +23 -0
- package/types/src/framework-variables.d.ts +6 -1
- package/types/src/iam-mail.d.ts +92 -0
- package/types/src/index.d.ts +7 -0
- package/types/src/installation-endpoint.d.ts +3 -2
- package/types/src/locale.d.ts +11 -1
- package/types/src/managed-environment.d.ts +1 -1
- package/types/src/membership.d.ts +8 -3
- package/types/src/oauth.d.ts +11 -0
- package/types/src/ops.d.ts +133 -8
- package/types/src/permissions.d.ts +12 -0
- package/types/src/public-egress.d.ts +31 -0
- package/types/src/requirement.d.ts +5 -4
- package/types/src/rpc.d.ts +113 -6
- package/types/src/scope-values.d.ts +61 -0
- package/types/src/sha256.d.ts +10 -0
- package/types/src/token.d.ts +70 -8
- package/types/src/types.d.ts +48 -1
- package/types/src/wire.d.ts +2 -1
package/src/ops.ts
CHANGED
|
@@ -111,6 +111,12 @@ export function OPS_STATE_KEY(object: string): string {
|
|
|
111
111
|
return `__fabrika/ops/${object}.json`
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
+
/** The R2 key, in the environment's bucket, of the migration record of `object` (ADR-0069 §3). */
|
|
115
|
+
export function OPS_MIGRATION_RECORD_KEY(object: string): string {
|
|
116
|
+
if (parseApplicationObjectName(object) === null) throw new Error('a migration record key needs a valid object name')
|
|
117
|
+
return `__fabrika/ops/${object}.migration.json`
|
|
118
|
+
}
|
|
119
|
+
|
|
114
120
|
/** The maintenance modes, from the most permissive. */
|
|
115
121
|
export const OPS_MODES = ['open', 'read-only', 'closed', 'inspect'] as const
|
|
116
122
|
|
|
@@ -177,10 +183,72 @@ export interface OpsMigration {
|
|
|
177
183
|
readonly appliedAt: string
|
|
178
184
|
}
|
|
179
185
|
|
|
180
|
-
/**
|
|
186
|
+
/**
|
|
187
|
+
* Sent once the migrations ran and the application booted, with the new ledger. `record` is the object's migration
|
|
188
|
+
* record, `null` when it has none; a release before the migrating boot omits it. `version` is the id of the Worker
|
|
189
|
+
* version that answers, `null` without the version metadata binding; a release before it omits it.
|
|
190
|
+
*/
|
|
181
191
|
export interface OpsMigrateAck {
|
|
182
192
|
readonly generation: number
|
|
183
193
|
readonly migrations: readonly OpsMigration[]
|
|
194
|
+
readonly record?: OpsMigrationRecord | null
|
|
195
|
+
readonly version?: string | null
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A file a migration record names: the ledger row's identity and checksum. */
|
|
199
|
+
export interface OpsMigrationFile {
|
|
200
|
+
readonly bundle: string
|
|
201
|
+
readonly name: string
|
|
202
|
+
readonly checksum: string
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* What became of a record's transaction: `diverged`, the ledger holds some of its rows (a release before the gate
|
|
207
|
+
* migrated over it); `rewound`, an in-place rewind took the object back to the record's bookmark (ADR-0070 §9).
|
|
208
|
+
*/
|
|
209
|
+
export const OPS_MIGRATION_OUTCOMES = ['committed', 'rolled_back', 'diverged', 'rewound'] as const
|
|
210
|
+
|
|
211
|
+
export type OpsMigrationOutcome = (typeof OPS_MIGRATION_OUTCOMES)[number]
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The migration record (ADR-0069 §3), stored in the environment's bucket and answered by `migrate`: what one migrating
|
|
215
|
+
* boot did, written before its transaction and completed after it.
|
|
216
|
+
*/
|
|
217
|
+
export interface OpsMigrationRecord {
|
|
218
|
+
/** A UUIDv7 per record; every later put of the record names it. */
|
|
219
|
+
readonly id: string
|
|
220
|
+
/** The id of the Worker version that wrote it; `null` where the runtime has no version metadata, which no rewind accepts. */
|
|
221
|
+
readonly version: string | null
|
|
222
|
+
/** The bookmark before the transaction, the only target of the in-place rewind; `null` where the runtime has none. */
|
|
223
|
+
readonly bookmark: string | null
|
|
224
|
+
/** The digest of the ledger the boot started from (`@fabrika/db`'s `sqliteLedgerDigest`). */
|
|
225
|
+
readonly startDigest: string
|
|
226
|
+
readonly files: readonly OpsMigrationFile[]
|
|
227
|
+
readonly at: string
|
|
228
|
+
readonly outcome: OpsMigrationOutcome | null
|
|
229
|
+
/** With `committed` (and `rewound` after it) only: the bookmark after the commit, or at the reconciliation that found it. */
|
|
230
|
+
readonly committedBookmark: string | null
|
|
231
|
+
/** When a version first booted over the outcome; never with `rewound`. */
|
|
232
|
+
readonly booted: string | null
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Why a migrating boot failed; `record_unwritable` names only the put before the transaction. */
|
|
236
|
+
export const OPS_MIGRATION_FAILURES = ['rolled_back', 'committed', 'record_unwritable'] as const
|
|
237
|
+
|
|
238
|
+
export type OpsMigrationFailureReason = (typeof OPS_MIGRATION_FAILURES)[number]
|
|
239
|
+
|
|
240
|
+
/** The status of a failed migrating boot, answered only by the release that holds the record. */
|
|
241
|
+
export const OPS_MIGRATION_FAILED_STATUS = 422
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The body of a failed migrating boot: the record as it stands, or as the boot tried to write it. `version` is the id of
|
|
245
|
+
* the Worker version that answers, as in `OpsMigrateAck`; a release before it omits it.
|
|
246
|
+
*/
|
|
247
|
+
export interface OpsMigrationFailure {
|
|
248
|
+
readonly refused: 'migration_failed'
|
|
249
|
+
readonly reason: OpsMigrationFailureReason
|
|
250
|
+
readonly record: OpsMigrationRecord
|
|
251
|
+
readonly version?: string | null
|
|
184
252
|
}
|
|
185
253
|
|
|
186
254
|
export interface OpsMaintenance {
|
|
@@ -302,10 +370,62 @@ export function parseOpsStaleRefusal(body: unknown): OpsStaleRefusal | null {
|
|
|
302
370
|
}
|
|
303
371
|
|
|
304
372
|
export function parseOpsMigrateAck(body: unknown): OpsMigrateAck | null {
|
|
305
|
-
|
|
373
|
+
const withRecord = hasKey(body, 'record')
|
|
374
|
+
const withVersion = hasKey(body, 'version')
|
|
375
|
+
if (!exactKeys(body, ['generation', 'migrations', ...(withRecord ? ['record'] : []), ...(withVersion ? ['version'] : [])])) return null
|
|
306
376
|
const generation = readGeneration(prop(body, 'generation'))
|
|
307
377
|
const migrations = readList(prop(body, 'migrations'), readMigration)
|
|
308
|
-
|
|
378
|
+
const record = withRecord ? readNullable(prop(body, 'record'), parseOpsMigrationRecord) : null
|
|
379
|
+
const version = withVersion ? readResponderVersion(prop(body, 'version')) : null
|
|
380
|
+
if (generation === null || migrations === null || record === undefined || version === undefined) return null
|
|
381
|
+
return { generation, migrations, ...(withRecord ? { record } : {}), ...(withVersion ? { version } : {}) }
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** A stored or answered migration record, parsed strictly: its fields must also agree with each other. */
|
|
385
|
+
export function parseOpsMigrationRecord(body: unknown): OpsMigrationRecord | null {
|
|
386
|
+
const keys = ['id', 'version', 'bookmark', 'startDigest', 'files', 'at', 'outcome', 'committedBookmark', 'booted']
|
|
387
|
+
if (!exactKeys(body, keys)) return null
|
|
388
|
+
const id = readMatch(prop(body, 'id'), UUID)
|
|
389
|
+
const version = readNullable(prop(body, 'version'), (value) => readMatch(value, WORKER_VERSION_ID))
|
|
390
|
+
const bookmark = readNullable(prop(body, 'bookmark'), (value) => readMatch(value, OPAQUE_TOKEN))
|
|
391
|
+
const startDigest = readMatch(prop(body, 'startDigest'), SHA256_HEX)
|
|
392
|
+
const files = readList(prop(body, 'files'), readMigrationFile)
|
|
393
|
+
const at = readTimestamp(prop(body, 'at'))
|
|
394
|
+
const outcome = readNullable(prop(body, 'outcome'), (value) => readEnum(value, OPS_MIGRATION_OUTCOMES))
|
|
395
|
+
const committedBookmark = readNullable(prop(body, 'committedBookmark'), (value) => readMatch(value, OPAQUE_TOKEN))
|
|
396
|
+
const booted = readNullable(prop(body, 'booted'), readTimestamp)
|
|
397
|
+
if (
|
|
398
|
+
id === null || version === undefined || bookmark === undefined || startDigest === null || files === null || files.length === 0 || at === null
|
|
399
|
+
|| outcome === undefined || committedBookmark === undefined || booted === undefined
|
|
400
|
+
) {
|
|
401
|
+
return null
|
|
402
|
+
}
|
|
403
|
+
const committed = outcome === 'committed' || outcome === 'rewound'
|
|
404
|
+
if ((committedBookmark !== null && !committed) || (booted !== null && (outcome === null || outcome === 'rewound'))) return null
|
|
405
|
+
return { id, version, bookmark, startDigest, files, at, outcome, committedBookmark, booted }
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** A failed migrating boot's answer; its reason must be what its record says. */
|
|
409
|
+
export function parseOpsMigrationFailure(body: unknown): OpsMigrationFailure | null {
|
|
410
|
+
const withVersion = hasKey(body, 'version')
|
|
411
|
+
const keys = ['refused', 'reason', 'record', ...(withVersion ? ['version'] : [])]
|
|
412
|
+
if (!exactKeys(body, keys) || prop(body, 'refused') !== 'migration_failed') return null
|
|
413
|
+
const reason = readEnum(prop(body, 'reason'), OPS_MIGRATION_FAILURES)
|
|
414
|
+
const record = parseOpsMigrationRecord(prop(body, 'record'))
|
|
415
|
+
const version = withVersion ? readResponderVersion(prop(body, 'version')) : null
|
|
416
|
+
if (reason === null || record === null || version === undefined) return null
|
|
417
|
+
const agrees = reason === 'record_unwritable'
|
|
418
|
+
? record.outcome === null
|
|
419
|
+
: reason === 'committed'
|
|
420
|
+
? record.outcome === 'committed' && record.booted === null
|
|
421
|
+
: record.outcome === reason
|
|
422
|
+
if (!agrees) return null
|
|
423
|
+
return withVersion ? { refused: 'migration_failed', reason, record, version } : { refused: 'migration_failed', reason, record }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** The answering Worker version's id, `null` without the binding; `undefined` when it does not parse. */
|
|
427
|
+
function readResponderVersion(value: unknown): string | null | undefined {
|
|
428
|
+
return readNullable(value, (raw) => readMatch(raw, WORKER_VERSION_ID))
|
|
309
429
|
}
|
|
310
430
|
|
|
311
431
|
export function parseOpsView(body: unknown): OpsView | null {
|
|
@@ -402,6 +522,71 @@ export function readOpsDumpValue(type: unknown, value: unknown): OpsDumpValue {
|
|
|
402
522
|
throw new Error('a projected dump value does not match its type')
|
|
403
523
|
}
|
|
404
524
|
|
|
525
|
+
/**
|
|
526
|
+
* The most result columns, and the most parameters, one statement of workerd's SQLite takes; a table holds at most as
|
|
527
|
+
* many columns.
|
|
528
|
+
*/
|
|
529
|
+
export const OPS_SQLITE_MAX_COLUMNS = 100
|
|
530
|
+
|
|
531
|
+
/** The most columns of a table one statement of a page read projects: two result columns each, beside the rowid twice. */
|
|
532
|
+
export const OPS_DUMP_READ_COLUMNS = (OPS_SQLITE_MAX_COLUMNS - 2) / 2
|
|
533
|
+
|
|
534
|
+
/** One row of a keyset page: its rowid as decimal text, then the rowid and every column as the dump writes them. */
|
|
535
|
+
export interface OpsDumpPageRow {
|
|
536
|
+
readonly rowid: string
|
|
537
|
+
readonly values: readonly OpsDumpValue[]
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Runs one statement of a page read, with the parameters of the read's condition, and answers its rows. */
|
|
541
|
+
export type OpsDumpPageQuery = (sql: string) => readonly Readonly<Record<string, unknown>>[]
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* One keyset page of `table`: the first `limit` rows by rowid that `condition` (`WHERE …`, or empty) admits, read the
|
|
545
|
+
* way the producer and the importer's verification both read them. Each column reads as two result columns, so a table
|
|
546
|
+
* wider than `OPS_DUMP_READ_COLUMNS` reads in several statements over the same rows, which the caller runs in one
|
|
547
|
+
* synchronous turn, so no write falls between them. The common table expression names every result column, which an
|
|
548
|
+
* expression alone does not.
|
|
549
|
+
*/
|
|
550
|
+
export function readOpsDumpPage(query: OpsDumpPageQuery, table: OpsDumpTablePlan, condition: string, limit: number): OpsDumpPageRow[] {
|
|
551
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('a dump page reads at least one row')
|
|
552
|
+
const keyset = quoteIdentifier(table.keyset)
|
|
553
|
+
const reads: { readonly start: number; readonly count: number; readonly rows: readonly Readonly<Record<string, unknown>>[] }[] = []
|
|
554
|
+
for (let start = 0; start === 0 || start < table.columns.length; start += OPS_DUMP_READ_COLUMNS) {
|
|
555
|
+
const columns = table.columns.slice(start, start + OPS_DUMP_READ_COLUMNS)
|
|
556
|
+
const names = columns.flatMap((_, offset) => [`t${start + offset}`, `v${start + offset}`])
|
|
557
|
+
const projections = [keyset, `CAST(${keyset} AS TEXT)`, ...columns.map(opsDumpColumnProjection)]
|
|
558
|
+
const rows = query(
|
|
559
|
+
`WITH page(${['k', 'r', ...names].join(', ')}) AS (SELECT ${projections.join(', ')} FROM main.${quoteIdentifier(table.name)} ${condition}
|
|
560
|
+
ORDER BY ${keyset} LIMIT ${limit}) SELECT ${['r', ...names].join(', ')} FROM page ORDER BY k`,
|
|
561
|
+
)
|
|
562
|
+
reads.push({ start, count: columns.length, rows })
|
|
563
|
+
}
|
|
564
|
+
const first = reads[0]?.rows ?? []
|
|
565
|
+
if (reads.some(({ rows }) => rows.length !== first.length)) throw new Error('the reads of one dump page disagree on its rows')
|
|
566
|
+
return first.map((row, index) => {
|
|
567
|
+
const rowid = readOpsDumpValue('integer', row['r'])
|
|
568
|
+
if (rowid === null || rowid.type !== 'integer') throw new Error('a rowid reads as an integer')
|
|
569
|
+
const values: OpsDumpValue[] = [rowid]
|
|
570
|
+
for (const { start, count, rows } of reads) {
|
|
571
|
+
const read = rows[index]
|
|
572
|
+
if (read?.['r'] !== rowid.value) throw new Error('the reads of one dump page disagree on its rows')
|
|
573
|
+
for (let column = start; column < start + count; column++) {
|
|
574
|
+
values.push(readOpsDumpValue(read[`t${column}`], read[`v${column}`]))
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return { rowid: rowid.value, values }
|
|
578
|
+
})
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* The SQL that names a dump's rowid inline, so a row of a table at `OPS_SQLITE_MAX_COLUMNS` binds no more parameters
|
|
583
|
+
* than it has columns. It is the checked decimal text in a string literal, cast as `opsDumpValueBinding` casts it.
|
|
584
|
+
*/
|
|
585
|
+
export function opsDumpRowidSql(rowid: OpsDumpValue): string {
|
|
586
|
+
if (rowid === null || rowid.type !== 'integer' || !isInt64Text(rowid.value)) throw new Error('a dump rowid must be an integer')
|
|
587
|
+
return `CAST('${rowid.value}' AS INTEGER)`
|
|
588
|
+
}
|
|
589
|
+
|
|
405
590
|
/** What a statement binds for one value of a dump. */
|
|
406
591
|
export type OpsDumpParam = string | number | Uint8Array | null
|
|
407
592
|
|
|
@@ -521,8 +706,12 @@ export interface OpsDumpSchemaTable {
|
|
|
521
706
|
readonly name: string
|
|
522
707
|
readonly virtual: boolean
|
|
523
708
|
readonly withoutRowid: boolean
|
|
524
|
-
/**
|
|
525
|
-
|
|
709
|
+
/**
|
|
710
|
+
* Every name a `CHECK` constraint of the table's SQL reads, ASCII-lowercase and unquoted (keywords included), so a
|
|
711
|
+
* column it does not list cannot change what a `CHECK` answers. Empty for a table without one; `null` from a reader
|
|
712
|
+
* that cannot tell, which counts as naming every column.
|
|
713
|
+
*/
|
|
714
|
+
readonly checkNames: readonly string[] | null
|
|
526
715
|
readonly columns: readonly OpsDumpSchemaColumn[]
|
|
527
716
|
readonly indexes: readonly OpsDumpSchemaIndex[]
|
|
528
717
|
readonly foreignKeys: readonly OpsDumpSchemaForeignKey[]
|
|
@@ -553,8 +742,9 @@ export interface OpsDumpPlan {
|
|
|
553
742
|
* The one rule both the producer, at export `begin`, and the importer, at import `begin`, apply to a schema: the plan
|
|
554
743
|
* a dump is written and loaded by, or an `unsupported_schema` refusal naming the table. A foreign key whose parent lies
|
|
555
744
|
* 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,
|
|
557
|
-
*
|
|
745
|
+
* columns must take a temporary `NULL`: nullable, outside the primary key, referenced by no foreign key, named by no
|
|
746
|
+
* `CHECK`, in a table without a `NOT NULL` generated column, a generated column a `CHECK` names, or a partial, expression
|
|
747
|
+
* or generated-column unique index. A `WITHOUT ROWID` or
|
|
558
748
|
* virtual table, a table without a name that reads its rowid, a foreign key to a table outside the dump or without the
|
|
559
749
|
* named key, and a foreign key checked only at commit are refused.
|
|
560
750
|
*/
|
|
@@ -946,7 +1136,7 @@ export function parseOpsImportDiscardAck(body: unknown): OpsImportDiscardAck | n
|
|
|
946
1136
|
* Writes the sentinel (the operation's id) into the object's KV storage, and answers the current bookmark and the
|
|
947
1137
|
* bookmark of `at`, which Control records before it arms anything.
|
|
948
1138
|
*/
|
|
949
|
-
export interface
|
|
1139
|
+
export interface OpsRestorePrepareAt {
|
|
950
1140
|
readonly step: 'prepare'
|
|
951
1141
|
readonly object: string
|
|
952
1142
|
readonly generation: number
|
|
@@ -954,6 +1144,20 @@ export interface OpsRestorePrepare {
|
|
|
954
1144
|
readonly at: string
|
|
955
1145
|
}
|
|
956
1146
|
|
|
1147
|
+
/**
|
|
1148
|
+
* The in-place rewind of a failed migration (ADR-0070 §9): `record` names the object's migration record, whose bookmark
|
|
1149
|
+
* is the target, and the object checks every guard of the rewind before it writes the sentinel.
|
|
1150
|
+
*/
|
|
1151
|
+
export interface OpsRestorePrepareRecord {
|
|
1152
|
+
readonly step: 'prepare'
|
|
1153
|
+
readonly object: string
|
|
1154
|
+
readonly generation: number
|
|
1155
|
+
readonly sentinel: string
|
|
1156
|
+
readonly record: string
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
export type OpsRestorePrepare = OpsRestorePrepareAt | OpsRestorePrepareRecord
|
|
1160
|
+
|
|
957
1161
|
/** Arms the restore of `target` for the next session, answers, then resets the object. */
|
|
958
1162
|
export interface OpsRestoreArm {
|
|
959
1163
|
readonly step: 'arm'
|
|
@@ -961,13 +1165,19 @@ export interface OpsRestoreArm {
|
|
|
961
1165
|
readonly generation: number
|
|
962
1166
|
readonly sentinel: string
|
|
963
1167
|
readonly target: string
|
|
1168
|
+
/** The migration record of an in-place rewind, whose guards the object checks again; absent for a side restore. */
|
|
1169
|
+
readonly record?: string
|
|
964
1170
|
}
|
|
965
1171
|
|
|
966
|
-
/**
|
|
1172
|
+
/**
|
|
1173
|
+
* Reads, after the reset, whether the sentinel is still there; it carries no generation. With `record`, an in-place
|
|
1174
|
+
* rewind's, an absent sentinel also records `rewound` in that migration record, its only write.
|
|
1175
|
+
*/
|
|
967
1176
|
export interface OpsRestoreVerify {
|
|
968
1177
|
readonly step: 'verify'
|
|
969
1178
|
readonly object: string
|
|
970
1179
|
readonly sentinel: string
|
|
1180
|
+
readonly record?: string
|
|
971
1181
|
}
|
|
972
1182
|
|
|
973
1183
|
/** `POST /__fabrika/ops/restore`: one step of rewinding an `inspect` object that serves no traffic. */
|
|
@@ -997,18 +1207,31 @@ export function parseOpsRestoreRequest(body: unknown): OpsRestoreRequest | null
|
|
|
997
1207
|
const object = parseApplicationObjectName(prop(body, 'object'))
|
|
998
1208
|
const sentinel = readMatch(prop(body, 'sentinel'), UUID)
|
|
999
1209
|
if (object === null || sentinel === null) return null
|
|
1000
|
-
if (step === 'verify')
|
|
1210
|
+
if (step === 'verify') {
|
|
1211
|
+
if (exactKeys(body, ['step', 'object', 'sentinel', 'record'])) {
|
|
1212
|
+
const record = readMatch(prop(body, 'record'), UUID)
|
|
1213
|
+
return record === null ? null : { step, object, sentinel, record }
|
|
1214
|
+
}
|
|
1215
|
+
return exactKeys(body, ['step', 'object', 'sentinel']) ? { step, object, sentinel } : null
|
|
1216
|
+
}
|
|
1001
1217
|
const generation = readGeneration(prop(body, 'generation'))
|
|
1002
1218
|
if (generation === null) return null
|
|
1003
1219
|
if (step === 'prepare') {
|
|
1220
|
+
if (exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'record'])) {
|
|
1221
|
+
const record = readMatch(prop(body, 'record'), UUID)
|
|
1222
|
+
return record === null ? null : { step, object, generation, sentinel, record }
|
|
1223
|
+
}
|
|
1004
1224
|
const at = readTimestamp(prop(body, 'at'))
|
|
1005
1225
|
return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'at']) && at !== null ? { step, object, generation, sentinel, at } : null
|
|
1006
1226
|
}
|
|
1007
1227
|
if (step === 'arm') {
|
|
1008
1228
|
const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1229
|
+
if (target === null) return null
|
|
1230
|
+
if (exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'target', 'record'])) {
|
|
1231
|
+
const record = readMatch(prop(body, 'record'), UUID)
|
|
1232
|
+
return record === null ? null : { step, object, generation, sentinel, target, record }
|
|
1233
|
+
}
|
|
1234
|
+
return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'target']) ? { step, object, generation, sentinel, target } : null
|
|
1012
1235
|
}
|
|
1013
1236
|
return null
|
|
1014
1237
|
}
|
|
@@ -1094,6 +1317,11 @@ export const OPS_DATA_REFUSALS = [
|
|
|
1094
1317
|
'verify_mismatch',
|
|
1095
1318
|
'bookmark_unavailable',
|
|
1096
1319
|
'row_too_large',
|
|
1320
|
+
// The in-place rewind (ADR-0070 §9): the record is not the one named, or not `committed` without `booted`; the record
|
|
1321
|
+
// has no version, or another Worker version runs than the one that wrote it; the target is not the record's bookmark.
|
|
1322
|
+
'not_rewindable',
|
|
1323
|
+
'version_changed',
|
|
1324
|
+
'wrong_target',
|
|
1097
1325
|
] as const
|
|
1098
1326
|
|
|
1099
1327
|
export type OpsDataRefusalReason = (typeof OPS_DATA_REFUSALS)[number]
|
|
@@ -1124,6 +1352,8 @@ const CONTRACT_NAME = /^[A-Za-z][A-Za-z0-9_]*$/
|
|
|
1124
1352
|
const MIGRATION_BUNDLE = /^[a-z][a-z0-9-]*$/
|
|
1125
1353
|
const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
|
|
1126
1354
|
const MIGRATION_CHECKSUM = /^[0-9a-f]{64}$/
|
|
1355
|
+
/** A Worker version id as Cloudflare's version metadata answers it. */
|
|
1356
|
+
const WORKER_VERSION_ID = /^[A-Za-z0-9-]{1,64}$/
|
|
1127
1357
|
const SHA256_HEX = /^[0-9a-f]{64}$/
|
|
1128
1358
|
/** A dump id or a sentinel: a UUID as Control writes one. */
|
|
1129
1359
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
@@ -1213,6 +1443,14 @@ function readMigration(value: unknown): OpsMigration | null {
|
|
|
1213
1443
|
return bundle === null || name === null || checksum === null || appliedAt === null ? null : { bundle, name, checksum, appliedAt }
|
|
1214
1444
|
}
|
|
1215
1445
|
|
|
1446
|
+
function readMigrationFile(value: unknown): OpsMigrationFile | null {
|
|
1447
|
+
if (!exactKeys(value, ['bundle', 'name', 'checksum'])) return null
|
|
1448
|
+
const bundle = readMatch(prop(value, 'bundle'), MIGRATION_BUNDLE)
|
|
1449
|
+
const name = readMatch(prop(value, 'name'), MIGRATION_NAME)
|
|
1450
|
+
const checksum = readMatch(prop(value, 'checksum'), MIGRATION_CHECKSUM)
|
|
1451
|
+
return bundle === null || name === null || checksum === null ? null : { bundle, name, checksum }
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1216
1454
|
function readScheduler(value: unknown): OpsScheduler | null {
|
|
1217
1455
|
if (!exactKeys(value, ['alarm'])) return null
|
|
1218
1456
|
const raw = prop(value, 'alarm')
|
|
@@ -1269,6 +1507,10 @@ function readBootFailureContent(value: unknown): OpsBootFailureContent | undefin
|
|
|
1269
1507
|
}
|
|
1270
1508
|
|
|
1271
1509
|
/** Whether `value` is a plain object holding exactly `keys`: no key missing, none unknown. */
|
|
1510
|
+
function hasKey(value: unknown, key: string): boolean {
|
|
1511
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.hasOwn(value, key)
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1272
1514
|
function exactKeys(value: unknown, keys: readonly string[]): boolean {
|
|
1273
1515
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
1274
1516
|
const own = Object.keys(value)
|
|
@@ -1583,11 +1825,240 @@ function loadOrder(tables: readonly DescribedTable[], cycle: ReadonlyMap<string,
|
|
|
1583
1825
|
return order
|
|
1584
1826
|
}
|
|
1585
1827
|
|
|
1828
|
+
/**
|
|
1829
|
+
* The schema `planOpsDump` reads, from the PRAGMAs workerd admits, of every table a dump holds. An `INITIALLY DEFERRED`
|
|
1830
|
+
* clause is read from the table's SQL outside its quotes and comments, and marks every foreign key of its table; the
|
|
1831
|
+
* names a `CHECK` reads come from the same SQL (`checkNamesOf`).
|
|
1832
|
+
*/
|
|
1833
|
+
export function describeOpsDumpSchema(query: OpsDumpSchemaQuery): OpsDumpSchema {
|
|
1834
|
+
const tables: OpsDumpSchemaTable[] = []
|
|
1835
|
+
for (const row of query('PRAGMA table_list')) {
|
|
1836
|
+
const name = schemaText(row['name'])
|
|
1837
|
+
const type = schemaText(row['type'])
|
|
1838
|
+
if (schemaText(row['schema']) !== 'main' || type === 'view' || !dumpedTable(name)) {
|
|
1839
|
+
continue
|
|
1840
|
+
}
|
|
1841
|
+
const virtual = type === 'virtual'
|
|
1842
|
+
const sql = query(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`, name)[0]?.['sql']
|
|
1843
|
+
const clauses = typeof sql === 'string' ? unquotedSql(sql) : null
|
|
1844
|
+
tables.push({
|
|
1845
|
+
name,
|
|
1846
|
+
virtual,
|
|
1847
|
+
withoutRowid: schemaFlag(row['wr']),
|
|
1848
|
+
checkNames: typeof sql === 'string' ? checkNamesOf(sql) : null,
|
|
1849
|
+
// A virtual table is refused whatever it holds, and its module may not be loaded to describe it.
|
|
1850
|
+
columns: virtual ? [] : describeColumns(query, name),
|
|
1851
|
+
indexes: virtual ? [] : describeIndexes(query, name),
|
|
1852
|
+
foreignKeys: virtual ? [] : describeForeignKeys(query, name, clauses === null || /\binitially\s+deferred\b/i.test(clauses)),
|
|
1853
|
+
})
|
|
1854
|
+
}
|
|
1855
|
+
return { tables }
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
function describeColumns(query: OpsDumpSchemaQuery, table: string): OpsDumpSchemaColumn[] {
|
|
1859
|
+
return query(`PRAGMA table_xinfo(${sqlLiteral(table)})`).map((row) => {
|
|
1860
|
+
const hidden = schemaInteger(row['hidden'])
|
|
1861
|
+
return {
|
|
1862
|
+
name: schemaText(row['name']),
|
|
1863
|
+
type: schemaText(row['type']),
|
|
1864
|
+
notNull: schemaFlag(row['notnull']),
|
|
1865
|
+
primaryKey: schemaInteger(row['pk']),
|
|
1866
|
+
generated: hidden === 2 || hidden === 3,
|
|
1867
|
+
}
|
|
1868
|
+
})
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
function describeIndexes(query: OpsDumpSchemaQuery, table: string): OpsDumpSchemaIndex[] {
|
|
1872
|
+
return query(`PRAGMA index_list(${sqlLiteral(table)})`).map((row) => {
|
|
1873
|
+
const origin = row['origin']
|
|
1874
|
+
if (origin !== 'c' && origin !== 'u' && origin !== 'pk') {
|
|
1875
|
+
throw new Error('PRAGMA index_list answered an origin SQLite does not write')
|
|
1876
|
+
}
|
|
1877
|
+
const columns = query(`PRAGMA index_xinfo(${sqlLiteral(schemaText(row['name']))})`)
|
|
1878
|
+
.filter((column) => schemaFlag(column['key']))
|
|
1879
|
+
.sort((left, right) => schemaInteger(left['seqno']) - schemaInteger(right['seqno']))
|
|
1880
|
+
.map((column) => typeof column['name'] === 'string' ? column['name'] : null)
|
|
1881
|
+
return { unique: schemaFlag(row['unique']), origin, partial: schemaFlag(row['partial']), columns }
|
|
1882
|
+
})
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
function describeForeignKeys(query: OpsDumpSchemaQuery, table: string, initiallyDeferred: boolean): OpsDumpSchemaForeignKey[] {
|
|
1886
|
+
const keys = new Map<number, { parent: string; rows: { seq: number; from: string; to: string | null }[] }>()
|
|
1887
|
+
for (const row of query(`PRAGMA foreign_key_list(${sqlLiteral(table)})`)) {
|
|
1888
|
+
const id = schemaInteger(row['id'])
|
|
1889
|
+
const to = row['to']
|
|
1890
|
+
const entry = { seq: schemaInteger(row['seq']), from: schemaText(row['from']), to: typeof to === 'string' ? to : null }
|
|
1891
|
+
const key = keys.get(id)
|
|
1892
|
+
if (key === undefined) {
|
|
1893
|
+
keys.set(id, { parent: schemaText(row['table']), rows: [entry] })
|
|
1894
|
+
} else {
|
|
1895
|
+
key.rows.push(entry)
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
return [...keys.entries()].sort(([left], [right]) => left - right).map(([, key]) => {
|
|
1899
|
+
const rows = key.rows.sort((left, right) => left.seq - right.seq)
|
|
1900
|
+
const references = rows.flatMap((row) => row.to === null ? [] : [row.to])
|
|
1901
|
+
if (references.length !== 0 && references.length !== rows.length) {
|
|
1902
|
+
throw new Error('PRAGMA foreign_key_list named the parent columns of a key only in part')
|
|
1903
|
+
}
|
|
1904
|
+
return { parent: key.parent, columns: rows.map((row) => row.from), references: references.length === 0 ? null : references, initiallyDeferred }
|
|
1905
|
+
})
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
type SqlToken =
|
|
1909
|
+
| { readonly kind: 'name'; readonly text: string; readonly quoted: boolean }
|
|
1910
|
+
| { readonly kind: 'open' | 'close' | 'other' }
|
|
1911
|
+
|
|
1912
|
+
const WORD_CHAR = /[A-Za-z0-9_$\u0080-\uffff]/
|
|
1913
|
+
|
|
1914
|
+
/**
|
|
1915
|
+
* The names the `CHECK` clauses of a table's `sql` read: every word and quoted identifier between a `CHECK` keyword's
|
|
1916
|
+
* parentheses, ASCII-lowercase, keywords and numbers included, so it lists at least every column a `CHECK` reads. A
|
|
1917
|
+
* string literal and a comment name nothing; a double-quoted string, which SQLite may read as either, counts as a name.
|
|
1918
|
+
* `null` when the text does not scan (an unclosed quote, comment or parenthesis), which counts as naming every column.
|
|
1919
|
+
*/
|
|
1920
|
+
export function checkNamesOf(sql: string): string[] | null {
|
|
1921
|
+
const tokens = sqlTokens(sql)
|
|
1922
|
+
if (tokens === null) return null
|
|
1923
|
+
const names: string[] = []
|
|
1924
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
1925
|
+
const token = tokens[index]
|
|
1926
|
+
if (token?.kind !== 'name' || token.quoted || asciiLower(token.text) !== 'check' || tokens[index + 1]?.kind !== 'open') continue
|
|
1927
|
+
let depth = 0
|
|
1928
|
+
let end = index + 1
|
|
1929
|
+
for (; end < tokens.length; end++) {
|
|
1930
|
+
const inner = tokens[end]
|
|
1931
|
+
if (inner?.kind === 'open') depth++
|
|
1932
|
+
else if (inner?.kind === 'close' && --depth === 0) break
|
|
1933
|
+
else if (inner?.kind === 'name') names.push(asciiLower(inner.text))
|
|
1934
|
+
}
|
|
1935
|
+
if (end === tokens.length) return null
|
|
1936
|
+
index = end
|
|
1937
|
+
}
|
|
1938
|
+
return names
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
/** `sql` as words, quoted identifiers and parentheses; string literals, comments and whitespace dropped. */
|
|
1942
|
+
function sqlTokens(sql: string): SqlToken[] | null {
|
|
1943
|
+
const tokens: SqlToken[] = []
|
|
1944
|
+
let index = 0
|
|
1945
|
+
while (index < sql.length) {
|
|
1946
|
+
const char = sql.charAt(index)
|
|
1947
|
+
if (sql.startsWith('--', index)) {
|
|
1948
|
+
const end = sql.indexOf('\n', index)
|
|
1949
|
+
index = end < 0 ? sql.length : end + 1
|
|
1950
|
+
} else if (sql.startsWith('/*', index)) {
|
|
1951
|
+
const end = sql.indexOf('*/', index + 2)
|
|
1952
|
+
if (end < 0) return null
|
|
1953
|
+
index = end + 2
|
|
1954
|
+
} else if (char === "'" || char === '"' || char === '`' || char === '[') {
|
|
1955
|
+
const close = char === '[' ? ']' : char
|
|
1956
|
+
let end = index + 1
|
|
1957
|
+
let text = ''
|
|
1958
|
+
for (;;) {
|
|
1959
|
+
const next = sql.indexOf(close, end)
|
|
1960
|
+
if (next < 0) return null
|
|
1961
|
+
text += sql.slice(end, next)
|
|
1962
|
+
if (close !== ']' && sql.charAt(next + 1) === close) {
|
|
1963
|
+
text += close
|
|
1964
|
+
end = next + 2
|
|
1965
|
+
continue
|
|
1966
|
+
}
|
|
1967
|
+
end = next + 1
|
|
1968
|
+
break
|
|
1969
|
+
}
|
|
1970
|
+
if (char !== "'") tokens.push({ kind: 'name', text, quoted: true })
|
|
1971
|
+
index = end
|
|
1972
|
+
} else if (WORD_CHAR.test(char)) {
|
|
1973
|
+
let end = index + 1
|
|
1974
|
+
while (end < sql.length && WORD_CHAR.test(sql.charAt(end))) end++
|
|
1975
|
+
tokens.push({ kind: 'name', text: sql.slice(index, end), quoted: false })
|
|
1976
|
+
index = end
|
|
1977
|
+
} else {
|
|
1978
|
+
if (char === '(') tokens.push({ kind: 'open' })
|
|
1979
|
+
else if (char === ')') tokens.push({ kind: 'close' })
|
|
1980
|
+
else if (!/\s/.test(char)) tokens.push({ kind: 'other' })
|
|
1981
|
+
index++
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
return tokens
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
/** `sql` with its string literals, quoted identifiers and comments blanked, so a keyword search finds only clauses. */
|
|
1988
|
+
function unquotedSql(sql: string): string {
|
|
1989
|
+
let out = ''
|
|
1990
|
+
let index = 0
|
|
1991
|
+
while (index < sql.length) {
|
|
1992
|
+
const char = sql.charAt(index)
|
|
1993
|
+
const close = char === "'" ? "'" : char === '"' ? '"' : char === '`' ? '`' : char === '[' ? ']' : null
|
|
1994
|
+
if (close !== null) {
|
|
1995
|
+
let end = index + 1
|
|
1996
|
+
for (;;) {
|
|
1997
|
+
end = sql.indexOf(close, end)
|
|
1998
|
+
if (end < 0 || close === ']' || sql.charAt(end + 1) !== close) break
|
|
1999
|
+
end += 2
|
|
2000
|
+
}
|
|
2001
|
+
index = end < 0 ? sql.length : end + 1
|
|
2002
|
+
out += ' '
|
|
2003
|
+
} else if (sql.startsWith('--', index)) {
|
|
2004
|
+
const end = sql.indexOf('\n', index)
|
|
2005
|
+
index = end < 0 ? sql.length : end + 1
|
|
2006
|
+
out += ' '
|
|
2007
|
+
} else if (sql.startsWith('/*', index)) {
|
|
2008
|
+
const end = sql.indexOf('*/', index + 2)
|
|
2009
|
+
index = end < 0 ? sql.length : end + 2
|
|
2010
|
+
out += ' '
|
|
2011
|
+
} else {
|
|
2012
|
+
out += char
|
|
2013
|
+
index++
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
return out
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
/** One statement's rows, as a Durable Object's `sql.exec(...).toArray()` or a `bun:sqlite` query answers them. */
|
|
2020
|
+
export type OpsDumpSchemaQuery = (sql: string, ...bindings: string[]) => readonly Readonly<Record<string, unknown>>[]
|
|
2021
|
+
|
|
2022
|
+
/** Whether a dump holds `name`: no SQLite internal table but `sqlite_sequence`, and none of Cloudflare's `_cf_` ones. */
|
|
2023
|
+
function dumpedTable(name: string): boolean {
|
|
2024
|
+
return !name.startsWith('_cf_') && (!name.startsWith('sqlite_') || name === 'sqlite_sequence')
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
function sqlLiteral(value: string): string {
|
|
2028
|
+
return `'${value.replaceAll("'", "''")}'`
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
// SQLite's own answers: a value of another type is a broken runtime, never input to refuse.
|
|
2032
|
+
function schemaText(value: unknown): string {
|
|
2033
|
+
if (typeof value !== 'string') {
|
|
2034
|
+
throw new Error('SQLite answered a schema name or SQL that is not text')
|
|
2035
|
+
}
|
|
2036
|
+
return value
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
function schemaInteger(value: unknown): number {
|
|
2040
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
|
|
2041
|
+
throw new Error('SQLite answered a schema number that is not an integer')
|
|
2042
|
+
}
|
|
2043
|
+
return value
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
function schemaFlag(value: unknown): boolean {
|
|
2047
|
+
return schemaInteger(value) !== 0
|
|
2048
|
+
}
|
|
2049
|
+
|
|
1586
2050
|
/** Whether every deferred column of `table` can hold `NULL` from its part until the link pass, with nothing to violate. */
|
|
1587
2051
|
function takesTemporaryNull(table: OpsDumpSchemaTable, deferred: readonly OpsDumpSchemaColumn[], referenced: ReadonlySet<string>): boolean {
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
2052
|
+
// A `CHECK` answers the same for a `NULL` in a column it does not read; a generated column may read a deferred one.
|
|
2053
|
+
const checkReads = (column: OpsDumpSchemaColumn): boolean => table.checkNames === null || table.checkNames.includes(asciiLower(column.name))
|
|
2054
|
+
if (table.columns.some((column) => column.generated && (column.notNull || checkReads(column)))) return false
|
|
2055
|
+
// A generated column that reads a deferred one may take one value for many rows while that column is `NULL`.
|
|
2056
|
+
const generated = new Set(table.columns.filter((column) => column.generated).map((column) => asciiLower(column.name)))
|
|
2057
|
+
const indexedGenerated = (index: OpsDumpSchemaIndex): boolean => index.columns.some((name) => name !== null && generated.has(asciiLower(name)))
|
|
2058
|
+
if (table.indexes.some((index) => index.unique && (index.partial || index.columns.includes(null) || indexedGenerated(index)))) return false
|
|
2059
|
+
return deferred.every((column) =>
|
|
2060
|
+
!column.notNull && column.primaryKey === 0 && !referenced.has(columnKey(table.name, column.name)) && !checkReads(column)
|
|
2061
|
+
)
|
|
1591
2062
|
}
|
|
1592
2063
|
|
|
1593
2064
|
function columnKey(table: string, column: string): string {
|