@fabrika/db 0.9.0-cloudflare.1 → 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/sqlite-bun.ts CHANGED
@@ -13,6 +13,44 @@ export interface BunSqliteStorage extends SqliteStorage {
13
13
  /** workerd's authorizer refuses these in `sql.exec`: a transaction runs through `transaction` or `transactionSync`. */
14
14
  const TRANSACTION_CONTROL = /(?:^|;)(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(?:begin|commit|end|rollback|savepoint|release)\b/i
15
15
 
16
+ /** workerd's `SQLITE_LIMIT_COLUMN` and `SQLITE_LIMIT_VARIABLE_NUMBER`, both 100. */
17
+ const WORKERD_MAX_COLUMNS = 100
18
+
19
+ /** What may follow a text's last statement: whitespace, comments and semicolons. */
20
+ const NO_STATEMENT = /^(?:\s|;|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*$/
21
+
22
+ /**
23
+ * Runs each statement of `query` in turn and answers the rows of the last one, as a Durable Object's `sql.exec` does.
24
+ * bun:sqlite's `prepare` compiles only the first statement of a text, and its column count cannot tell a migration from a
25
+ * read (`ALTER TABLE … ADD COLUMN … CHECK (…)` reports one column), so the text is split at the end of each compiled
26
+ * statement. `bindings` belong to a text of one statement. Refuses what workerd's SQLite refuses: more than 100 result
27
+ * columns or parameters in one statement.
28
+ */
29
+ export function execStatements(database: Database, query: string, bindings: readonly SQLQueryBindings[] = []): Record<string, unknown>[] {
30
+ let text = query
31
+ for (;;) {
32
+ const statement = database.prepare<Record<string, unknown>, SQLQueryBindings[]>(text)
33
+ try {
34
+ if (statement.columnNames.length > WORKERD_MAX_COLUMNS) {
35
+ throw new Error('too many columns in result set: SQLITE_ERROR')
36
+ }
37
+ if (statement.paramsCount > WORKERD_MAX_COLUMNS) {
38
+ throw new Error('too many SQL variables: SQLITE_ERROR')
39
+ }
40
+ // The compiled statement's own text, with no parameter to expand: the rest of `text` follows it verbatim.
41
+ const compiled = statement.toString()
42
+ const rest = bindings.length === 0 && text.startsWith(compiled) ? text.slice(compiled.length) : ''
43
+ const rows = statement.all(...bindings)
44
+ if (NO_STATEMENT.test(rest)) {
45
+ return rows
46
+ }
47
+ text = rest
48
+ } finally {
49
+ statement.finalize()
50
+ }
51
+ }
52
+ }
53
+
16
54
  function bunBinding(value: SqliteValue): SQLQueryBindings {
17
55
  return value instanceof ArrayBuffer ? new Uint8Array(value) : value
18
56
  }
@@ -41,8 +79,8 @@ interface OpenTransaction {
41
79
  /**
42
80
  * `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
43
81
  * `transaction` runs at a time; one started inside a callback nests in a savepoint, as workerd nests it, and its
44
- * siblings wait for each other. A statement outside one runs at once. A text of several statements runs whole when its
45
- * first statement answers no rows, as a migration's does; otherwise only its first statement runs.
82
+ * siblings wait for each other. A statement outside one runs at once. A text of several statements runs each of them and
83
+ * answers the rows of the last (`execStatements`).
46
84
  */
47
85
  export function bunSqliteStorage(database: Database = new Database(':memory:')): BunSqliteStorage {
48
86
  database.run('PRAGMA foreign_keys = ON')
@@ -54,19 +92,8 @@ export function bunSqliteStorage(database: Database = new Database(':memory:')):
54
92
  if (TRANSACTION_CONTROL.test(query)) {
55
93
  throw new Error('sql.exec runs no transaction statement: use storage.transaction() or storage.transactionSync()')
56
94
  }
57
- const values = bindings.map(bunBinding)
58
95
  const before = totalChanges()
59
- const statement = database.prepare<Record<string, unknown>, SQLQueryBindings[]>(query)
60
- let rows: Record<string, SqliteValue>[] = []
61
- try {
62
- if (statement.columnNames.length > 0) {
63
- rows = statement.all(...values).map(storageRow)
64
- } else {
65
- database.run(query, values)
66
- }
67
- } finally {
68
- statement.finalize()
69
- }
96
+ const rows = execStatements(database, query, bindings.map(bunBinding)).map(storageRow)
70
97
  const rowsWritten = totalChanges() - before
71
98
  return { toArray: () => rows, rowsWritten }
72
99
  }
package/src/sqlite.ts CHANGED
@@ -218,7 +218,7 @@ export function openSqlite(storage: SqliteStorage): Database {
218
218
  const kysely = new Kysely<LooseDB>({ dialect: new SqliteDialect(storage, false) })
219
219
  const reads = new Kysely<LooseDB>({ dialect: new SqliteDialect(storage, true) })
220
220
  const transaction: TransactionRunner = (options, body) => options.readOnly ? body(reads) : storage.transaction(() => body(kysely))
221
- return Database.fromEngine({ dialect: 'sqlite', kysely, compiler: sqliteCompiler, transaction })
221
+ return Database.fromEngine({ dialect: 'sqlite', kysely, compiler: sqliteCompiler, transaction, reads })
222
222
  }
223
223
  // Application modules load after this one: a replaced opener would receive the object's storage.
224
224
  Object.freeze(openSqlite)
package/src/store.ts CHANGED
@@ -53,6 +53,7 @@ import { fileReference } from './file-references'
53
53
  import { webhookTables } from './framework-tables'
54
54
  import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
55
55
  import { fencedTransaction, jobLeases } from './job-leases'
56
+ import { jobWakes, leaseProjection } from './job-wakes'
56
57
  import { linksPredicate, type LinkValue, linkValues } from './links'
57
58
  import {
58
59
  acknowledgement,
@@ -97,7 +98,6 @@ import {
97
98
  type TableModels,
98
99
  tableModels,
99
100
  type Tables,
100
- updatableBy,
101
101
  updateActions,
102
102
  type UpdateValues,
103
103
  type VersionArguments,
@@ -114,6 +114,11 @@ export interface DataLayerRuntime {
114
114
  readonly capabilities: CapabilityAuthority
115
115
  /** Whether the request running now may only read (an export's); its every statement then runs `READ ONLY`. */
116
116
  readonly readOnly?: () => boolean
117
+ /**
118
+ * Runs inside the transaction of every change of a job's wakes or lease, after the change: the Cloudflare driver arms
119
+ * the alarm from `wakes.next(transaction)` there, so the alarm commits with the change. A throw rolls the change back.
120
+ */
121
+ readonly projectWakes?: (transaction: Session) => Promise<void>
117
122
  }
118
123
 
119
124
  /** Empty until the framework connects the layer at boot; every table handle of one `scoped` call shares it. */
@@ -507,12 +512,12 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
507
512
  }
508
513
 
509
514
  /**
510
- * A fragment on an UPDATE or DELETE target: the capability's action is that operation's, and an application table is
511
- * written by an `app` capability only, a dimension or child table never by one. An UPDATE may instead hold a column's
512
- * own write action when every column it assigns declares that action (`updatingRef`'s rule); `assigned` is
513
- * `undefined` before the statement is known, and then any such action is taken.
515
+ * A fragment its author marks as an UPDATE or DELETE target: the capability's action is that operation's, and an
516
+ * application table is written by an `app` capability only, a dimension or child table never by one. An UPDATE may
517
+ * instead hold a column's own write action; which columns the statement sets is the author's and the approver's to
518
+ * keep to that action's (`updatableBy`), as the statement is not read for it.
514
519
  */
515
- function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'update' | 'delete', assigned: readonly string[] | undefined): void {
520
+ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'update' | 'delete'): void {
516
521
  const model = context.model
517
522
  const statement = `${use === 'update' ? 'UPDATE' : 'DELETE'} of ${model.name}`
518
523
  if (grant.kind === 'app' && model.scope.mode !== 'app') {
@@ -539,42 +544,26 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
539
544
  if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
540
545
  throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${grant.action}`)
541
546
  }
542
- if (assigned === undefined) {
543
- return
544
- }
545
- const written = updatableBy(model, grant.action)
546
- const outside: string[] = assigned.length === 0 ? ['no column it can name'] : []
547
- for (let index = 0; index < assigned.length; index++) {
548
- const column = assigned[index]
549
- if (column !== undefined && !inSet(written, column)) outside[outside.length] = column
550
- }
551
- if (outside.length > 0) {
552
- throw new CapabilityError(
553
- 'wrong_action',
554
- `${statement} assigns ${
555
- outside.join(', ')
556
- }, which ${grant.action} does not write: a column's own write action scopes an UPDATE of its columns only`,
557
- )
558
- }
559
547
  }
560
548
 
561
549
  /**
562
550
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
563
551
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
564
552
  * its read action for a `Within`, an action `ctx.db.app` lists it for with an `app` capability, and its read action
565
- * for a scoped site's read of an application table. A fragment on the statement's UPDATE or DELETE target needs that
566
- * operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's column
567
- * and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container grant on
568
- * its own column, or every row for `all`); an `app` capability, and a scoped read of an application table, every row.
553
+ * for a scoped site's read of an application table. A fragment its author marks `use: 'update'` or `'delete'` needs
554
+ * that operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's
555
+ * column and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container
556
+ * grant on its own column, or every row for `all`); an `app` capability, and a scoped read of an application table,
557
+ * every row.
569
558
  */
570
- export function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse, assigned?: readonly string[]): ScopeTerms {
559
+ export function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse): ScopeTerms {
571
560
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
572
561
  const model = context.model
573
562
  if (grant.kind === 'row') {
574
563
  throw new CapabilityError('wrong_capability', `ctx.sql.scope takes a Ref, a Within or an app capability, got ${describeGrant(grant)}`)
575
564
  }
576
565
  if (use !== 'read') {
577
- checkWriteTarget(context, grant, use, assigned)
566
+ checkWriteTarget(context, grant, use)
578
567
  }
579
568
  if (grant.kind === 'app') {
580
569
  if (use === 'read') {
@@ -2188,7 +2177,12 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2188
2177
  if (connection.runtime !== undefined) {
2189
2178
  throw new CapabilityError('layer_unbound', 'the data layer is already connected; only the framework connects it, once, at boot')
2190
2179
  }
2191
- const bound: DataLayerRuntime = freeze({ database: runtime.database, capabilities: runtime.capabilities, readOnly: runtime.readOnly })
2180
+ const bound: DataLayerRuntime = freeze({
2181
+ database: runtime.database,
2182
+ capabilities: runtime.capabilities,
2183
+ readOnly: runtime.readOnly,
2184
+ projectWakes: runtime.projectWakes,
2185
+ })
2192
2186
  connection.runtime = bound
2193
2187
  return freeze({
2194
2188
  locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
@@ -2201,7 +2195,8 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2201
2195
  },
2202
2196
  framework: freeze({
2203
2197
  webhooks: webhookTables(() => runtimeOf(connection)),
2204
- jobs: jobLeases(() => runtimeOf(connection)),
2198
+ jobs: jobLeases(() => runtimeOf(connection), leaseProjection(() => runtimeOf(connection))),
2199
+ wakes: jobWakes(() => runtimeOf(connection)),
2205
2200
  admissions: admissions(() => runtimeOf(connection)),
2206
2201
  files: storedFiles(() => runtimeOf(connection)),
2207
2202
  }),
@@ -12,6 +12,7 @@ import { isPlainIdentifier } from './identifier'
12
12
  import { type DialectTexts, fencedTransaction, SQLITE_NOW, sqliteNowPlus, sqliteTimestamp } from './job-leases'
13
13
  import { FILE_DELETIONS_TABLE, FILES_TABLE } from './migrations'
14
14
  import type { DataLayerRuntime } from './store'
15
+ import { storedTimestamp } from './temporal'
15
16
 
16
17
  const F = FILES_TABLE
17
18
  const D = FILE_DELETIONS_TABLE
@@ -96,10 +97,14 @@ export interface StoredFiles {
96
97
  promote(id: string, sha256: string, version: string): Promise<boolean>
97
98
  deferScan(id: string, attempts: number, after: Date): Promise<boolean>
98
99
  reject(id: string): Promise<boolean>
99
- // The sweep.
100
- /** Objects whose rows a sweep deleted and whose own deletion it did not finish. */
101
- unfinishedDeletions(limit: number): Promise<readonly string[]>
100
+ // The sweep. A queued object key is a tombstone: its object outlives its row by the retention window.
101
+ /** At most `limit` queued object keys recorded at or before `cutoff` (equality is due), oldest first. */
102
+ dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]>
103
+ /** Takes a due key out of the queue before its object is deleted; `false` when a cancel or a requeue got there first. */
104
+ claimDeletion(objectKey: string, cutoff: Date): Promise<boolean>
102
105
  forgetDeletion(objectKey: string): Promise<void>
106
+ /** Takes `objectKeys` out of the queue, so their objects stay: a restore's rows reference them again. The number taken. */
107
+ cancelDeletions(objectKeys: readonly string[]): Promise<number>
103
108
  /** Clears the legacy marker of every migrated file that one of `columns` references: it is an ordinary file now. */
104
109
  adoptReferenced(columns: readonly FileColumnRef[]): Promise<number>
105
110
  /** At most `limit` files past the grace that no column of `columns` references (pending ones included), oldest first. */
@@ -118,6 +123,9 @@ const FOREIGN_KEY_VIOLATION = '23503'
118
123
  const SERVED_COLUMNS = `id::text as id, kind, name, content_type, size, status, object_key, object_version`
119
124
  const SQLITE_SERVED_COLUMNS = `id, kind, name, content_type, size, status, object_key, object_version`
120
125
  const N = SQLITE_NOW
126
+ // A tombstone's instant in whole milliseconds, as SQLite stores it: the sweep's cutoff is a `Date`, and a key recorded
127
+ // in the cutoff's own millisecond is due (equality), not one microsecond past it.
128
+ const RECORDED_NOW = `date_trunc('milliseconds', now())`
121
129
 
122
130
  const SQL_STAGE: DialectTexts = {
123
131
  postgres: `insert into ${F} (id, kind, status, object_key, content_type, name, request, created_at)
@@ -132,7 +140,7 @@ const SQL_WRITTEN: DialectTexts = {
132
140
  }
133
141
 
134
142
  const SQL_ABANDON = `with gone as (delete from ${F} where id = $1::uuid and status = 'pending' and request = $2 returning object_key)
135
- insert into ${D} (object_key, recorded_at) select object_key, now() from gone on conflict (object_key) do nothing returning object_key`
143
+ insert into ${D} (object_key, recorded_at) select object_key, ${RECORDED_NOW} from gone on conflict (object_key) do nothing returning object_key`
136
144
 
137
145
  // SQLite has no data-modifying CTE: the delete and the record of its object are two statements in one transaction.
138
146
  const SQLITE_ABANDON = `delete from ${F} where id = ?1 and status = 'pending' and request = ?2 returning object_key`
@@ -185,9 +193,14 @@ const SQL_REJECT: DialectTexts = {
185
193
  sqlite: `update ${F} set status = 'rejected' where id = ?1 and status = 'quarantined' returning id`,
186
194
  }
187
195
 
188
- const SQL_UNFINISHED: DialectTexts = {
189
- postgres: `select object_key from ${D} order by recorded_at limit $1::int`,
190
- sqlite: `select object_key from ${D} order by recorded_at limit ?1`,
196
+ const SQL_DUE: DialectTexts = {
197
+ postgres: `select object_key from ${D} where recorded_at <= $2::timestamptz order by recorded_at limit $1::int`,
198
+ sqlite: `select object_key from ${D} where recorded_at <= ?2 order by recorded_at limit ?1`,
199
+ }
200
+
201
+ const SQL_CLAIM_DELETION: DialectTexts = {
202
+ postgres: `delete from ${D} where object_key = $1 and recorded_at <= $2::timestamptz returning object_key`,
203
+ sqlite: `delete from ${D} where object_key = ?1 and recorded_at <= ?2 returning object_key`,
191
204
  }
192
205
 
193
206
  const SQL_FORGET: DialectTexts = {
@@ -195,13 +208,22 @@ const SQL_FORGET: DialectTexts = {
195
208
  sqlite: `delete from ${D} where object_key = ?1`,
196
209
  }
197
210
 
211
+ // The keys are one parameter, a JSON array.
212
+ const SQL_CANCEL: DialectTexts = {
213
+ postgres: `delete from ${D} where object_key in (select jsonb_array_elements_text($1::jsonb)) returning object_key`,
214
+ sqlite: `delete from ${D} where object_key in (select value from json_each(?1)) returning object_key`,
215
+ }
216
+
198
217
  const SQL_REMOVE = `with gone as (
199
218
  delete from ${F} where id = $1::uuid and legacy is null and created_at < now() - $2::bigint * interval '1 millisecond' returning object_key
200
219
  )
201
- insert into ${D} (object_key, recorded_at) select object_key, now() from gone returning object_key`
220
+ insert into ${D} (object_key, recorded_at) select object_key, ${RECORDED_NOW} from gone
221
+ on conflict (object_key) do update set recorded_at = excluded.recorded_at returning object_key`
202
222
 
203
223
  const SQLITE_REMOVE = `delete from ${F} where id = ?1 and legacy is null and created_at < ${sqliteNowPlus('-?2')} returning object_key`
204
- const SQLITE_RECORD_REMOVED = `insert into ${D} (object_key, recorded_at) values (?1, ${N}) returning object_key`
224
+ // A key queued again restarts its window: the removal is fresh.
225
+ const SQLITE_RECORD_REMOVED =
226
+ `insert into ${D} (object_key, recorded_at) values (?1, ${N}) on conflict (object_key) do update set recorded_at = excluded.recorded_at returning object_key`
205
227
 
206
228
  /** The lock a reference write takes: a file being deleted cannot gain a reference, and a referenced one is not deleted. */
207
229
  const SQL_LOCK: DialectTexts = {
@@ -452,15 +474,26 @@ export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
452
474
 
453
475
  reject: (id: string) => fenced(SQL_REJECT, [uuid(id)]),
454
476
 
455
- async unfinishedDeletions(limit: number): Promise<readonly string[]> {
456
- const rows = await run(session(), SQL_UNFINISHED, [positive(limit, 'a sweep batch')])
477
+ async dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]> {
478
+ const rows = await run(session(), SQL_DUE, [positive(limit, 'a sweep batch'), storedTimestamp(cutoff, 'a deletion cutoff')])
457
479
  return rows.map((found) => text(record(found), 'object_key'))
458
480
  },
459
481
 
482
+ async claimDeletion(objectKey: string, cutoff: Date): Promise<boolean> {
483
+ return (await run(session(), SQL_CLAIM_DELETION, [objectKey, storedTimestamp(cutoff, 'a deletion cutoff')])).length === 1
484
+ },
485
+
460
486
  async forgetDeletion(objectKey: string): Promise<void> {
461
487
  await run(session(), SQL_FORGET, [objectKey])
462
488
  },
463
489
 
490
+ async cancelDeletions(objectKeys: readonly string[]): Promise<number> {
491
+ if (objectKeys.length === 0) {
492
+ return 0
493
+ }
494
+ return (await run(session(), SQL_CANCEL, [JSON.stringify(objectKeys)])).length
495
+ },
496
+
464
497
  async adoptReferenced(columns: readonly FileColumnRef[]): Promise<number> {
465
498
  if (columns.length === 0) {
466
499
  return 0
@@ -83,6 +83,11 @@ export interface IsolationWorlds {
83
83
  readonly dimension: string
84
84
  readonly own: WorldRow
85
85
  readonly other: WorldRow
86
+ /**
87
+ * Deletes both rows of the table and every row that refers to them, however deep; the containers stay. A case whose
88
+ * rows hold pinned values removes them, so the next case can pin the same values again under a unique index.
89
+ */
90
+ readonly remove: () => Promise<void>
86
91
  }
87
92
 
88
93
  /** What a test kit seeds through, over its migrated schema. */
@@ -90,9 +95,17 @@ export interface TestSeeding {
90
95
  /**
91
96
  * Seeds one row of `table` in each of two fresh chains, with every container row a table owns. `values` (column →
92
97
  * value) are written into both rows of `table`: the state an endpoint's precondition needs. A text column keeps its
93
- * marker, so a seed of one, or of a column that places the row, throws.
98
+ * marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
99
+ * `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
100
+ * counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
101
+ * no text column, throws.
94
102
  */
95
- seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>): Promise<IsolationWorlds>
103
+ seedWorlds<DB, P>(
104
+ tables: Tables<DB, P>,
105
+ table: string,
106
+ values?: Readonly<Record<string, SampleValue>>,
107
+ pins?: Readonly<Record<string, string>>,
108
+ ): Promise<IsolationWorlds>
96
109
  /**
97
110
  * Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
98
111
  * as given, a text column too, every other column sampled. A value for a stamped column or a file column throws.
@@ -525,7 +538,17 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
525
538
  return { key, ...seeded }
526
539
  }
527
540
 
528
- async function seedWorld(models: TableModels, model: TableModel, world: string, seed: Readonly<Record<string, SampleValue>>): Promise<WorldRow> {
541
+ /** The value a pin gives the row of `world`: as written in the own row, distinct in the other. */
542
+ const pinnedValue = (value: string, world: string): string => (world === 'own' ? value : `${value}-${world}`)
543
+
544
+ async function seedWorld(
545
+ models: TableModels,
546
+ model: TableModel,
547
+ world: string,
548
+ seed: Readonly<Record<string, SampleValue>>,
549
+ pins: Readonly<Record<string, string>>,
550
+ inserted: InsertedRow[],
551
+ ): Promise<WorldRow> {
529
552
  const markers: string[] = []
530
553
  const values = new Map<string, string>()
531
554
  const links: readonly Container[] = model.chain
@@ -562,7 +585,20 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
562
585
  }
563
586
  assigned.set(name, value)
564
587
  }
588
+ for (const [name, value] of Object.entries(pins)) {
589
+ const column = columnOf(model.name, name)
590
+ if (assigned.has(name)) {
591
+ throw new Error(`${model.name}.${name} places the row in its scope or is seeded; a pin gives a text column of the row's own state a known value`)
592
+ }
593
+ if (!(await holdsMarker(model, model.name, column))) {
594
+ throw new Error(`${model.name}.${name} holds no text marker; a pin gives a text column a known value, a seed every other column`)
595
+ }
596
+ const pinned = pinnedValue(value, world)
597
+ assigned.set(name, pinned)
598
+ markers.push(pinned)
599
+ }
565
600
  const { row } = await insert(models, model.name, assigned, markers)
601
+ inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
566
602
  const updates: Record<string, SampleValue> = {}
567
603
  for (const name of namesOf(model.update)) {
568
604
  updates[name] = row.get(name) ?? await updateSample(model.name, name)
@@ -586,10 +622,16 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
586
622
  }
587
623
 
588
624
  return {
589
- async seedWorlds(tables, table, values = {}) {
625
+ async seedWorlds(tables, table, values = {}, pins = {}) {
590
626
  const { models, model } = scopedModel(tables, table)
591
627
  const dimension = grantDimension(models, model)
592
- return { dimension, own: await seedWorld(models, model, 'own', values), other: await seedWorld(models, model, 'other', values) }
628
+ const inserted: InsertedRow[] = []
629
+ return {
630
+ dimension,
631
+ own: await seedWorld(models, model, 'own', values, pins, inserted),
632
+ other: await seedWorld(models, model, 'other', values, pins, inserted),
633
+ remove: () => backend.remove(inserted),
634
+ }
593
635
  },
594
636
  async seedRow(tables, table, values = {}) {
595
637
  const { models, model } = scopedModel(tables, table)
@@ -28,6 +28,11 @@ export interface DatabaseEngine {
28
28
  readonly transaction: TransactionRunner;
29
29
  /** The application's schema, the connection's `search_path`; `undefined` where the database has none. */
30
30
  readonly schema?: string;
31
+ /**
32
+ * SQLite's: runs each statement in a transaction of its own (a savepoint inside an open one) and refuses, rolling it
33
+ * back, one that wrote. A `ctx.sql` site that declares `'read'` runs on it in a writable invocation too.
34
+ */
35
+ readonly reads?: Executor;
31
36
  }
32
37
  /**
33
38
  * The compiler turns the guarded tree into SQL, so a patch to it after the guard ran would bypass the guard.
@@ -173,7 +178,8 @@ export declare function runFixedStatement(session: Session, text: string, parame
173
178
  export type SqlParameter = string | number | boolean | bigint | null;
174
179
  /**
175
180
  * One `ctx.sql` statement, whose text `sql.ts` classified and whose values are bound parameters only. It runs through the
176
- * session's one path to the connection, so a statement the database refuses fails the invocation it runs in.
181
+ * session's one path to the connection, so a statement the database refuses fails the invocation it runs in. A `'read'`
182
+ * statement runs on the engine's `reads` where it has one (SQLite), so one that wrote is refused and rolled back.
177
183
  */
178
- export declare function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[]): Promise<readonly unknown[]>;
184
+ export declare function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[], mode: 'read' | 'write'): Promise<readonly unknown[]>;
179
185
  export {};
@@ -44,11 +44,10 @@ export declare const QUERY_REFUSALS: {
44
44
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
45
45
  readonly sql_statement: "ctx.sql runs one statement of an admitted kind, and none inside another";
46
46
  readonly sql_read_only: "sql: 'read' runs queries only; declare sql: 'write' on a mutation, a job or a webhook";
47
- readonly sql_name: "ctx.sql names a framework, catalog or foreign-schema object, or writes a name in U& form";
47
+ readonly sql_name: "ctx.sql names a framework (fabrika_*), catalog (pg_*, sqlite_*) or foreign-schema object, or writes a name in U& form";
48
48
  readonly sql_function: "ctx.sql calls a function that is not a reviewed built-in";
49
49
  readonly sql_outside_transaction: "a job runs ctx.sql only inside ctx.transaction((tx) => …), as tx.sql";
50
- readonly sql_scope: "ctx.sql.scope(…) stands alone, joined by AND, in a WHERE or JOIN … ON clause of its own invocation";
51
- readonly sql_dialect: "ctx.sql runs only on Postgres; an application on SQLite (Cloudflare) reads and writes through ctx.db";
50
+ readonly sql_scope: "ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site";
52
51
  readonly file_scan: "a scan verdict outside the scan job's lease";
53
52
  readonly claim_site: "claim leases rows in a transaction of its own: a job calls it on ctx.db, never inside ctx.transaction or a request";
54
53
  readonly on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action";
@@ -8,7 +8,8 @@ export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, LeaseLo
8
8
  export type { FileBinding } from './file-columns';
9
9
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references';
10
10
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables';
11
- export type { JobLeases, JobLeaseState, JobOutcome, OverdueClaim } from './job-leases';
11
+ export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
12
+ export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
12
13
  export type { DataAccess, DataHandles, DataSite } from './orm';
13
14
  export type { FrameworkTables, Locator, ProvisionalBinding } from './registry';
14
15
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
@@ -26,8 +27,8 @@ export declare function bindScopedDatabase(value: unknown, runtime: DataLayerRun
26
27
  */
27
28
  export declare function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding;
28
29
  /**
29
- * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and the
30
- * admission counters. Each operation needs the layer bound first. Throws for any other value.
30
+ * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
31
+ * the admission counters. Each operation needs the layer bound first. Throws for any other value.
31
32
  */
32
33
  export declare function frameworkTablesOf(value: unknown): FrameworkTables;
33
34
  /**
@@ -1,5 +1,6 @@
1
1
  import type { LeaseFence } from './capability';
2
2
  import { type Session, type SqlDialect } from './database';
3
+ import { type FinishWakes } from './job-wakes';
3
4
  import type { DataLayerRuntime } from './store';
4
5
  export type JobOutcome = 'succeeded' | 'failed';
5
6
  export interface JobLeaseState {
@@ -48,8 +49,11 @@ export interface JobLeases {
48
49
  * now on. `null` when `fence` no longer holds it.
49
50
  */
50
51
  renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null>;
51
- /** Frees the lease and records the run's outcome and duration; `false` when `fence` no longer held it. */
52
- finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean>;
52
+ /**
53
+ * Frees the lease and records the run's outcome and duration, and in the same transaction applies `wakes` to the wakes
54
+ * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
55
+ */
56
+ finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>;
53
57
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
54
58
  markPending(job: string): Promise<void>;
55
59
  /**
@@ -69,6 +73,21 @@ export interface JobLeases {
69
73
  cancelInFlight(fence: LeaseFence): Promise<void>;
70
74
  state(job: string): Promise<JobLeaseState | null>;
71
75
  }
76
+ /**
77
+ * What a lease statement changed: a crashed holder reaped, a lease taken or handed on, or a run finished with what its
78
+ * wakes become (`null` leaves them).
79
+ */
80
+ export type LeaseChange = {
81
+ readonly kind: 'reaped' | 'acquired' | 'renewed';
82
+ } | {
83
+ readonly kind: 'finished';
84
+ readonly wakes: FinishWakes | null;
85
+ };
86
+ /**
87
+ * Runs in the transaction of every lease statement that changed the lease, so a table that follows the lease (the
88
+ * wakes, `job-wakes.ts`) commits with it or not at all. A statement that changed nothing, a lost lease's, runs none.
89
+ */
90
+ export type LeaseProjection = (transaction: Session, job: string, change: LeaseChange) => Promise<void>;
72
91
  /** One framework statement in each dialect's text; a session runs the text of its own. */
73
92
  export type DialectTexts = Readonly<Record<SqlDialect, string>>;
74
93
  /** SQLite's clock, as a stored timestamp: ISO text, so a comparison of two is a text comparison. */
@@ -90,4 +109,4 @@ export declare function databaseNow(session: Session): Promise<Date>;
90
109
  * On SQLite only the two checks run: no other event reaches the Durable Object while the transaction is open.
91
110
  */
92
111
  export declare function fencedTransaction<T>(session: Session, fence: LeaseFence, work: (transaction: Session) => Promise<T>): Promise<T>;
93
- export declare function jobLeases(runtime: () => DataLayerRuntime): JobLeases;
112
+ export declare function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases;
@@ -0,0 +1,101 @@
1
+ import type { LeaseFence } from './capability';
2
+ import { type Session } from './database';
3
+ import type { JobOutcome, LeaseProjection } from './job-leases';
4
+ import type { DataLayerRuntime } from './store';
5
+ export declare const WAKE_REASONS: readonly ["cron", "kick", "claim", "retry"];
6
+ export type WakeReason = (typeof WAKE_REASONS)[number];
7
+ export interface NewWake {
8
+ readonly job: string;
9
+ readonly reason: WakeReason;
10
+ readonly dueAt: Date;
11
+ /** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
12
+ readonly dedupe?: string;
13
+ }
14
+ export interface Wake {
15
+ readonly id: string;
16
+ readonly job: string;
17
+ readonly reason: WakeReason;
18
+ readonly dueAt: Date;
19
+ /** How many failed runs moved this wake (`retry`). */
20
+ readonly attempt: number;
21
+ readonly dedupe: string | null;
22
+ /** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
23
+ readonly owned: boolean;
24
+ }
25
+ /**
26
+ * What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
27
+ * transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
28
+ * leaves the wakes as they are.
29
+ */
30
+ export type FinishWakes =
31
+ /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
32
+ {
33
+ readonly kind: 'completed';
34
+ readonly nextCron?: {
35
+ readonly expression: string;
36
+ readonly dueAt: Date;
37
+ };
38
+ }
39
+ /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
40
+ | {
41
+ readonly kind: 'retry';
42
+ readonly at: Date;
43
+ };
44
+ export interface JobWakes {
45
+ /**
46
+ * Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
47
+ * keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
48
+ * run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
49
+ * a key another job holds is refused.
50
+ */
51
+ schedule(wake: NewWake, using?: Session): Promise<Wake>;
52
+ /** The pending wakes of `job`, earliest first. */
53
+ pending(job: string): Promise<readonly Wake[]>;
54
+ /**
55
+ * When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
56
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
57
+ */
58
+ next(using?: Session): Promise<Date | null>;
59
+ /** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
60
+ untilNext(using?: Session): Promise<number | null>;
61
+ /** The database's clock, read in `using` when given: a wake due now is due by it. */
62
+ now(using?: Session): Promise<Date>;
63
+ /**
64
+ * Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
65
+ * each declared job's cron wake whose key names another expression; answers how many it deleted.
66
+ */
67
+ reconcile(declared: readonly DeclaredJob[]): Promise<number>;
68
+ /**
69
+ * The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
70
+ * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
71
+ */
72
+ hasten(ids: readonly string[]): Promise<number>;
73
+ /**
74
+ * The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
75
+ * alarm through `next` until someone reaps it.
76
+ */
77
+ expiredHolders(): Promise<readonly string[]>;
78
+ }
79
+ /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
80
+ export interface DeclaredJob {
81
+ readonly job: string;
82
+ readonly expression: string;
83
+ }
84
+ /**
85
+ * A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
86
+ * lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
87
+ */
88
+ export declare function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null;
89
+ /**
90
+ * The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
91
+ * fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
92
+ * runs the runtime's projection.
93
+ */
94
+ export declare function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection;
95
+ /**
96
+ * Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
97
+ * transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
98
+ * left; each later claim keeps the earliest re-arm of the attempt.
99
+ */
100
+ export declare function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void>;
101
+ export declare function jobWakes(runtime: () => DataLayerRuntime): JobWakes;
@@ -4,6 +4,7 @@ export declare const WEBHOOK_BINDINGS_TABLE = "fabrika_webhook_bindings";
4
4
  export declare const WEBHOOK_DELIVERIES_TABLE = "fabrika_webhook_deliveries";
5
5
  export declare const JOB_LEASES_TABLE = "fabrika_job_leases";
6
6
  export declare const JOB_KICKS_TABLE = "fabrika_job_kicks";
7
+ export declare const JOB_WAKES_TABLE = "fabrika_wakes";
7
8
  export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
8
9
  export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
9
10
  export declare const FORM_FILES_TABLE = "fabrika_form_files";