@fabrika/db 0.9.0-dev.32 → 0.9.0-dev.34

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.32",
3
+ "version": "0.9.0-dev.34",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/testing.ts",
@@ -96,9 +96,9 @@
96
96
  "test": "bun test"
97
97
  },
98
98
  "dependencies": {
99
- "@fabrika/auth-core": "0.9.0-dev.32",
100
- "@fabrika/platform": "0.9.0-dev.32",
101
- "@fabrika/platform-node": "0.9.0-dev.32",
99
+ "@fabrika/auth-core": "0.9.0-dev.34",
100
+ "@fabrika/platform": "0.9.0-dev.34",
101
+ "@fabrika/platform-node": "0.9.0-dev.34",
102
102
  "kysely": "0.29.6",
103
103
  "kysely-postgres-js": "5.0.1",
104
104
  "zod": "^3.25.76"
package/src/errors.ts CHANGED
@@ -48,7 +48,8 @@ export const QUERY_REFUSALS = {
48
48
  unexpected_row: 'the database answered a row in another shape than its migration declares',
49
49
  statement_shape: 'the compiled statement has a form the guard does not admit',
50
50
  scope_predicate: 'the scope predicate is missing or is not a top-level conjunct',
51
- list_page: 'a list limit, cursor or order outside what a page admits',
51
+ list_page: 'a list limit or order outside what a page admits',
52
+ list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order",
52
53
  too_many_rows: 'all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate',
53
54
  undeclared_reach: 'the site reaches data it did not declare (sql or unscoped, or their mode)',
54
55
  sql_template: 'ctx.sql was not called as one tagged template whose values are interpolated whole',
package/src/framework.ts CHANGED
@@ -22,7 +22,7 @@ export type { FileBinding } from './file-columns'
22
22
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
23
23
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
24
24
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
25
- export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
25
+ export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes'
26
26
  export type { DataAccess, DataHandles, DataSite } from './orm'
27
27
  export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
28
28
  export type { RequestReceipt, RequestReceipts } from './request-receipts'
package/src/job-leases.ts CHANGED
@@ -68,6 +68,12 @@ export interface JobLeases {
68
68
  * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
69
69
  */
70
70
  finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>
71
+ /**
72
+ * Gives back a lease under which no run started: frees it and leaves every wake as it is, owned ones disowned, and
73
+ * records no run (no status, end or duration). A process schedule's timer releases a lease whose take owned no due
74
+ * wake (ADR-0080). `false` when `fence` no longer held it.
75
+ */
76
+ release(fence: LeaseFence): Promise<boolean>
71
77
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
72
78
  markPending(job: string): Promise<void>
73
79
  /**
@@ -177,6 +183,11 @@ const SQL_FINISH: DialectTexts = {
177
183
  where job = ?1 and generation = ?2 and holder = ?3 returning job`,
178
184
  }
179
185
 
186
+ const SQL_RELEASE: DialectTexts = {
187
+ postgres: `update ${T} set holder = null where job = $1 and generation = $2 and holder = $3 returning job`,
188
+ sqlite: `update ${T} set holder = null where job = ?1 and generation = ?2 and holder = ?3 returning job`,
189
+ }
190
+
180
191
  const SQL_TRY_ACQUIRE: DialectTexts = {
181
192
  // A free lease whose row no transaction holds (`skip locked`): an attempt's fence holds it `for share` while it writes.
182
193
  postgres: `with free as (select job from ${T} where job = $1 and holder is null for update skip locked)
@@ -497,6 +508,11 @@ export function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProject
497
508
  return (await changing(SQL_FINISH, [...params(fence), outcome], fence.job, change)).length > 0
498
509
  },
499
510
 
511
+ async release(fence: LeaseFence): Promise<boolean> {
512
+ // A finish that applies nothing to the wakes: the projection only disowns what the take marked owned.
513
+ return (await changing(SQL_RELEASE, params(fence), fence.job, { kind: 'finished', wakes: null })).length > 0
514
+ },
515
+
500
516
  async tryAcquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
501
517
  const [row] = await changing(
502
518
  SQL_TRY_ACQUIRE,
package/src/job-wakes.ts CHANGED
@@ -3,7 +3,9 @@
3
3
  // leases. Only `@fabrika/app` reaches it, through `frameworkTablesOf`. A run owns the wakes due when it took its lease,
4
4
  // marked in that transaction (`owned`); a wake written or merged into afterwards is not its. Only the transaction of that
5
5
  // run's fenced finish consumes or retries what it owns (`leaseProjection`), so a crash at any point leaves either the wake
6
- // or a held lease whose expiry is due. Every change runs the runtime's `projectWakes` in its own transaction.
6
+ // or a held lease whose expiry is due. Every change runs the runtime's `projectWakes` in its own transaction. Where no
7
+ // crontab runs, `fabrika_job_schedule` keeps the generation of the deploy whose serving processes keep the cron wakes
8
+ // (ADR-0080).
7
9
 
8
10
  import { uuidv7 } from '@fabrika/platform'
9
11
  import { freeze } from './builtins'
@@ -11,7 +13,7 @@ import type { LeaseFence } from './capability'
11
13
  import { type FixedParameter, runFixedStatement, type Session, sessionOf } from './database'
12
14
  import { QueryRefusedError } from './errors'
13
15
  import type { DialectTexts, JobOutcome, LeaseChange, LeaseProjection } from './job-leases'
14
- import { JOB_LEASES_TABLE, JOB_WAKES_TABLE } from './migrations'
16
+ import { JOB_LEASES_TABLE, JOB_SCHEDULE_TABLE, JOB_WAKES_TABLE } from './migrations'
15
17
  import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
16
18
  import { refuseInProduction } from './production'
17
19
  import type { DataLayerRuntime } from './store'
@@ -47,7 +49,15 @@ export interface Wake {
47
49
  */
48
50
  export type FinishWakes =
49
51
  /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
50
- | { readonly kind: 'completed'; readonly nextCron?: { readonly expression: string; readonly dueAt: Date } }
52
+ | {
53
+ readonly kind: 'completed'
54
+ /**
55
+ * With `scheduled`, the next fire is written only when the stored schedule (`keepSchedule`) declares its key, read
56
+ * in the finish's transaction: under a process schedule, a run of an older deploy writes no removed job's or
57
+ * changed expression's fire (ADR-0080).
58
+ */
59
+ readonly nextCron?: { readonly expression: string; readonly dueAt: Date; readonly scheduled?: boolean }
60
+ }
51
61
  /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
52
62
  | { readonly kind: 'retry'; readonly at: Date }
53
63
 
@@ -63,18 +73,31 @@ export interface JobWakes {
63
73
  pending(job: string): Promise<readonly Wake[]>
64
74
  /**
65
75
  * When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
66
- * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
76
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given;
77
+ * with `jobs`, of those jobs only, so a wake of a job this process does not run never holds its timer.
67
78
  */
68
- next(using?: Session): Promise<Date | null>
79
+ next(using?: Session, jobs?: readonly string[]): Promise<Date | null>
69
80
  /** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
70
- untilNext(using?: Session): Promise<number | null>
81
+ untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null>
82
+ /**
83
+ * Where no crontab runs (ADR-0080), in one transaction: raises the stored schedule generation to `generation` when that
84
+ * one is higher in byte order, with the cron keys `fires` declare, and when `generation` is then the stored one,
85
+ * reconciles the wakes against `fires` (as `reconcile`) and adds each fire's wake under its job's cron key where none
86
+ * is pending (an existing one, overdue or not, is left as it is and not locked, so a lease taken meanwhile still owns
87
+ * it). Answers whether `generation` is the stored one; a process of an older one writes nothing. The generation's row stays
88
+ * locked until the transaction commits, so on Postgres a newer generation waits for an older one's seed and reconciles
89
+ * after it, and an older one queued behind a newer one reads the newer and writes nothing. A UUIDv7, lowercase: a
90
+ * later deploy's sorts later.
91
+ */
92
+ keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean>
71
93
  /** The database's clock, read in `using` when given: a wake due now is due by it. */
72
94
  now(using?: Session): Promise<Date>
73
95
  /**
74
96
  * Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
75
- * each declared job's cron wake whose key names another expression; answers how many it deleted.
97
+ * each declared job's cron wake whose key names another expression; answers how many it deleted. In `using` when
98
+ * given.
76
99
  */
77
- reconcile(declared: readonly DeclaredJob[]): Promise<number>
100
+ reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number>
78
101
  /**
79
102
  * The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
80
103
  * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
@@ -87,6 +110,11 @@ export interface JobWakes {
87
110
  expiredHolders(): Promise<readonly string[]>
88
111
  }
89
112
 
113
+ /** A declared job and its next fire, which `keepSchedule` seeds; `null` when its expression has none in the window. */
114
+ export interface ScheduledFire extends DeclaredJob {
115
+ readonly dueAt: Date | null
116
+ }
117
+
90
118
  /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
91
119
  export interface DeclaredJob {
92
120
  readonly job: string
@@ -95,6 +123,7 @@ export interface DeclaredJob {
95
123
 
96
124
  const W = JOB_WAKES_TABLE
97
125
  const L = JOB_LEASES_TABLE
126
+ const S = JOB_SCHEDULE_TABLE
98
127
  const COLUMNS = 'job, due_at, reason, attempt, dedupe'
99
128
  const SELECTED = `${COLUMNS}, owned`
100
129
  const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
@@ -139,20 +168,101 @@ const SQL_DISOWN: DialectTexts = {
139
168
 
140
169
  // Two candidates, each one index-ordered or per-job lookup: the earliest wake of a free or expired job walks the due index
141
170
  // and stops at the first, and the earliest held expiry reads the lease rows, one per job. Postgres compares by the
142
- // statement's clock, not the transaction's: `using` may be a transaction that began before a lease expired.
171
+ // statement's clock, not the transaction's: `using` may be a transaction that began before a lease expired. The one
172
+ // parameter is the JSON list of jobs to look at, or null for every job.
143
173
  const SQL_NEXT: DialectTexts = {
144
174
  postgres: `select
145
175
  (select w.due_at from ${W} w left join ${L} l on l.job = w.job
146
- where l.holder is null or l.expires_at <= clock_timestamp() order by w.due_at limit 1) as wake,
147
- (select ${PG_EPOCH_MS('min(expires_at)')} from ${L} where holder is not null) as held,
176
+ where (l.holder is null or l.expires_at <= clock_timestamp())
177
+ and ($1::jsonb is null or w.job in (select jsonb_array_elements_text($1::jsonb))) order by w.due_at limit 1) as wake,
178
+ (select ${PG_EPOCH_MS('min(expires_at)')} from ${L}
179
+ where holder is not null and ($1::jsonb is null or job in (select jsonb_array_elements_text($1::jsonb)))) as held,
148
180
  ${PG_EPOCH_MS('clock_timestamp()')} as now`,
149
181
  sqlite: `select
150
182
  (select w.due_at from ${W} w left join ${L} l on l.job = w.job
151
- where l.holder is null or l.expires_at <= ${SQLITE_NOW} order by w.due_at limit 1) as wake,
152
- (select ${SQLITE_EPOCH_MS('min(expires_at)')} from ${L} where holder is not null) as held,
183
+ where (l.holder is null or l.expires_at <= ${SQLITE_NOW})
184
+ and (?1 is null or w.job in (select value from json_each(?1))) order by w.due_at limit 1) as wake,
185
+ (select ${SQLITE_EPOCH_MS('min(expires_at)')} from ${L}
186
+ where holder is not null and (?1 is null or job in (select value from json_each(?1)))) as held,
153
187
  ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
154
188
  }
155
189
 
190
+ // One row; a lower generation leaves it as it is, keys included, and the row answers what is stored after the write.
191
+ const SQL_HOLD_SCHEDULE: DialectTexts = {
192
+ postgres: `insert into ${S} (id, generation, declared) values (1, $1, $2)
193
+ on conflict (id) do update set generation = greatest(${S}.generation, excluded.generation),
194
+ declared = case when excluded.generation >= ${S}.generation then excluded.declared else ${S}.declared end
195
+ returning generation`,
196
+ sqlite: `insert into ${S} (id, generation, declared) values (1, ?1, ?2)
197
+ on conflict (id) do update set generation = max(${S}.generation, excluded.generation),
198
+ declared = case when excluded.generation >= ${S}.generation then excluded.declared else ${S}.declared end
199
+ returning generation`,
200
+ }
201
+
202
+ // A seed only adds a missing wake. `do nothing` takes no lock on a row that exists, so a replica's lease, taken while
203
+ // a seed is open, still marks that row owned (`SQL_OWN` skips a locked row).
204
+ const SQL_SEED: DialectTexts = {
205
+ postgres: `insert into ${W} (id, ${COLUMNS}) values ($1::uuid, $2, $3::bigint, $4, 0, $5) on conflict (dedupe) where dedupe is not null do nothing`,
206
+ sqlite: `insert into ${W} (id, ${COLUMNS}) values (?1, ?2, cast(?3 as integer), ?4, 0, ?5) on conflict (dedupe) where dedupe is not null do nothing`,
207
+ }
208
+
209
+ // The keys the stored generation declares, read by a finish in its transaction; `for share` waits for a seed under way.
210
+ const SQL_SCHEDULE_DECLARED: DialectTexts = {
211
+ postgres: `select declared from ${S} where id = 1 for share`,
212
+ sqlite: `select declared from ${S} where id = 1`,
213
+ }
214
+
215
+ /** Whether the stored schedule declares `key`: its row's keys, read in `transaction`. No row declares nothing. */
216
+ async function scheduleDeclares(transaction: Session, key: string): Promise<boolean> {
217
+ const [row] = await rows(transaction, SQL_SCHEDULE_DECLARED, [])
218
+ if (row === undefined) {
219
+ return false
220
+ }
221
+ const declared: unknown = typeof row['declared'] === 'string' ? JSON.parse(row['declared']) : undefined
222
+ if (!Array.isArray(declared)) {
223
+ throw new QueryRefusedError('unexpected_row', `${S}.declared is not a list of keys`)
224
+ }
225
+ return declared.includes(key)
226
+ }
227
+
228
+ /**
229
+ * A schedule generation: a lowercase UUIDv7 (version 7, the RFC variant), whose text order is its time order. Any other
230
+ * UUID would order deploys at random, and a later deploy that sorted lower would never take the schedule.
231
+ */
232
+ const SCHEDULE_GENERATION = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
233
+
234
+ /** The declared jobs `reconcile` keeps, checked: a list of jobs with their expressions. */
235
+ function declaredJobs(declared: readonly DeclaredJob[]): DeclaredJob[] {
236
+ if (!Array.isArray(declared)) {
237
+ throw new QueryRefusedError('invalid_argument', 'the declared jobs are a list of jobs with their expressions')
238
+ }
239
+ return declared.map((entry: unknown) => {
240
+ const job: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'job') : undefined
241
+ const expression: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'expression') : undefined
242
+ return { job: nonEmpty(job, 'a declared job'), expression: nonEmpty(expression, "a declared job's expression") }
243
+ })
244
+ }
245
+
246
+ /** Each fire `keepSchedule` seeds, checked before its transaction: the declared job and the cron wake of its next fire. */
247
+ function scheduledFires(fires: readonly ScheduledFire[]): {
248
+ readonly declared: DeclaredJob[]
249
+ readonly wakes: { readonly job: string; readonly parameters: readonly FixedParameter[] }[]
250
+ } {
251
+ const declared = declaredJobs(fires)
252
+ const wakes = fires.flatMap((fire, index) => {
253
+ const dueAt: unknown = Reflect.get(fire, 'dueAt')
254
+ const job = declared[index]
255
+ if (dueAt === null || job === undefined) {
256
+ return []
257
+ }
258
+ if (!(dueAt instanceof Date)) {
259
+ throw new QueryRefusedError('invalid_argument', "a fire's due time is a valid time or null")
260
+ }
261
+ return [{ job: job.job, parameters: newWake({ job: job.job, reason: 'cron', dueAt, dedupe: `cron:${job.job}:${job.expression}` }) }]
262
+ })
263
+ return { declared, wakes }
264
+ }
265
+
156
266
  const SQL_CLOCK: DialectTexts = {
157
267
  postgres: `select ${PG_EPOCH_MS('clock_timestamp()')} as now`,
158
268
  sqlite: `select ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
@@ -303,7 +413,11 @@ export function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined)
303
413
  }
304
414
  nonEmpty(wakes.nextCron.expression, "a cron wake's expression")
305
415
  epochOf(wakes.nextCron.dueAt, "a cron wake's due time")
306
- return freeze({ kind: 'completed', nextCron: freeze({ expression: wakes.nextCron.expression, dueAt: wakes.nextCron.dueAt }) })
416
+ const { expression, dueAt, scheduled } = wakes.nextCron
417
+ if (scheduled !== undefined && typeof scheduled !== 'boolean') {
418
+ throw new QueryRefusedError('invalid_argument', "a cron wake's schedule guard is a boolean")
419
+ }
420
+ return freeze({ kind: 'completed', nextCron: freeze(scheduled === true ? { expression, dueAt, scheduled } : { expression, dueAt }) })
307
421
  }
308
422
 
309
423
  /** The runtime's projection of a change, in its transaction; nothing without one. */
@@ -328,10 +442,14 @@ export function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjectio
328
442
  if (change.wakes.kind === 'retry') {
329
443
  await rows(transaction, SQL_RETRY, [job, String(change.wakes.at.getTime())])
330
444
  } else {
331
- await rows(transaction, SQL_CONSUME, [job])
332
445
  const next = change.wakes.nextCron
333
- if (next !== undefined) {
334
- await insert(transaction, newWake({ job, reason: 'cron', dueAt: next.dueAt, dedupe: `cron:${job}:${next.expression}` }), job)
446
+ const key = next === undefined ? null : `cron:${job}:${next.expression}`
447
+ // The schedule row before the wakes, the order `keepSchedule` takes them in: a seed that holds the row waits
448
+ // for no delete of this finish, so the two never wait on each other.
449
+ const declared = next?.scheduled === true && key !== null ? await scheduleDeclares(transaction, key) : true
450
+ await rows(transaction, SQL_CONSUME, [job])
451
+ if (next !== undefined && key !== null && declared) {
452
+ await insert(transaction, newWake({ job, reason: 'cron', dueAt: next.dueAt, dedupe: key }), job)
335
453
  }
336
454
  }
337
455
  }
@@ -368,9 +486,23 @@ export async function rearmClaim(runtime: DataLayerRuntime, transaction: Session
368
486
  await runtime.projectWakes?.(transaction)
369
487
  }
370
488
 
489
+ /** The jobs `next` looks at, as its JSON parameter: `null` for every job. */
490
+ function jobsFilter(jobs: readonly string[] | undefined): FixedParameter {
491
+ if (jobs === undefined) {
492
+ return null
493
+ }
494
+ if (!Array.isArray(jobs)) {
495
+ throw new QueryRefusedError('invalid_argument', 'the jobs the next wake is read for are a list of job names')
496
+ }
497
+ return JSON.stringify(jobs.map((job: unknown) => nonEmpty(job, 'a job the next wake is read for')))
498
+ }
499
+
371
500
  /** The next wake, in epoch milliseconds, and the database's now as the same statement read it. */
372
- async function nextAndNow(session: Session): Promise<{ readonly next: number | null; readonly now: () => number }> {
373
- const [{ wake = null, held = null, now = null } = {}] = await rows(session, SQL_NEXT, [])
501
+ async function nextAndNow(
502
+ session: Session,
503
+ jobs: readonly string[] | undefined,
504
+ ): Promise<{ readonly next: number | null; readonly now: () => number }> {
505
+ const [{ wake = null, held = null, now = null } = {}] = await rows(session, SQL_NEXT, [jobsFilter(jobs)])
374
506
  const candidates = [wake, held].filter((value) => value !== null).map((value) => wholeNumber(value, 'the next wake'))
375
507
  return { next: candidates.length === 0 ? null : Math.min(...candidates), now: () => wholeNumber(now, "the database's now") }
376
508
  }
@@ -392,16 +524,41 @@ export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
392
524
  return freeze((await rows(session(), SQL_PENDING, [job])).map(wakeOf))
393
525
  },
394
526
 
395
- async next(using?: Session): Promise<Date | null> {
396
- const { next } = await nextAndNow(using ?? session())
527
+ async next(using?: Session, jobs?: readonly string[]): Promise<Date | null> {
528
+ const { next } = await nextAndNow(using ?? session(), jobs)
397
529
  return next === null ? null : new Date(next)
398
530
  },
399
531
 
400
- async untilNext(using?: Session): Promise<number | null> {
401
- const { next, now } = await nextAndNow(using ?? session())
532
+ async untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null> {
533
+ const { next, now } = await nextAndNow(using ?? session(), jobs)
402
534
  return next === null ? null : next - now()
403
535
  },
404
536
 
537
+ async keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean> {
538
+ if (typeof generation !== 'string' || !SCHEDULE_GENERATION.test(generation)) {
539
+ throw new QueryRefusedError('invalid_argument', 'a schedule generation is a lowercase UUIDv7')
540
+ }
541
+ const { declared, wakes } = scheduledFires(fires)
542
+ const keys = JSON.stringify(declared.map(({ job, expression }) => `cron:${job}:${expression}`))
543
+ return await session().transaction(async (transaction) => {
544
+ // The upsert locks the row until this transaction commits: the reconcile and the seed below happen under it,
545
+ // and a finish that reads the declared keys waits for them.
546
+ const [{ generation: stored } = {}] = await rows(transaction, SQL_HOLD_SCHEDULE, [generation, keys])
547
+ if (typeof stored !== 'string') {
548
+ throw new QueryRefusedError('unexpected_row', `${S} came back in another shape than its migration declares`)
549
+ }
550
+ if (stored !== generation) {
551
+ return false
552
+ }
553
+ await rows(transaction, SQL_RECONCILE, [JSON.stringify(declared)])
554
+ for (const wake of wakes) {
555
+ await rows(transaction, SQL_SEED, wake.parameters)
556
+ }
557
+ await project(transaction)
558
+ return true
559
+ })
560
+ },
561
+
405
562
  async now(using?: Session): Promise<Date> {
406
563
  const [{ now = null } = {}] = await rows(using ?? session(), SQL_CLOCK, [])
407
564
  return new Date(wholeNumber(now, "the database's now"))
@@ -418,16 +575,9 @@ export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
418
575
  )
419
576
  },
420
577
 
421
- async reconcile(declared: readonly DeclaredJob[]): Promise<number> {
422
- if (!Array.isArray(declared)) {
423
- throw new QueryRefusedError('invalid_argument', 'the declared jobs are a list of jobs with their expressions')
424
- }
425
- const jobs = declared.map((entry: unknown) => {
426
- const job: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'job') : undefined
427
- const expression: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'expression') : undefined
428
- return { job: nonEmpty(job, 'a declared job'), expression: nonEmpty(expression, "a declared job's expression") }
429
- })
430
- return await session().transaction(async (transaction) => {
578
+ async reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number> {
579
+ const jobs = declaredJobs(declared)
580
+ return await (using ?? session()).transaction(async (transaction) => {
431
581
  const removed = await rows(transaction, SQL_RECONCILE, [JSON.stringify(jobs)])
432
582
  await project(transaction)
433
583
  return removed.length
@@ -0,0 +1,82 @@
1
+ // A list's cursor, signed with the database's own key (`fabrika_list_cursor_key`, which the framework migration writes
2
+ // once), so a cursor a client edited is the caller's `list_cursor`, never a statement the database refuses (a 500) or a
3
+ // page from a position no page ended at. A cursor is `<payload>.<signature>`: the payload is the base64url JSON of the
4
+ // last row's order values, and the signature an HMAC-SHA256 over the list it belongs to (its table and whole order) and
5
+ // the payload. The list is signed, not carried, so the cursor names no table or column.
6
+
7
+ import { parseList } from './builtins'
8
+ import { runFixedStatement, type Session } from './database'
9
+ import { QueryRefusedError } from './errors'
10
+ import type { DialectTexts } from './job-leases'
11
+ import { LIST_CURSOR_KEY_TABLE } from './migrations'
12
+
13
+ /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
14
+ export type CursorValue = string | null
15
+
16
+ const SQL_KEY: DialectTexts = {
17
+ postgres: `select secret from ${LIST_CURSOR_KEY_TABLE} where id = 1`,
18
+ sqlite: `select secret from ${LIST_CURSOR_KEY_TABLE} where id = 1`,
19
+ }
20
+
21
+ const BASE64URL = /^[A-Za-z0-9_-]+$/
22
+
23
+ /** The database's cursor key, read in `session`; the framework migration wrote it, so its absence is no caller's fault. */
24
+ export async function cursorKey(session: Session): Promise<CryptoKey> {
25
+ const [row] = await runFixedStatement(session, SQL_KEY[session.dialect], [])
26
+ const secret: unknown = typeof row === 'object' && row !== null ? Reflect.get(row, 'secret') : undefined
27
+ if (typeof secret !== 'string' || secret.length === 0) {
28
+ throw new QueryRefusedError('unexpected_row', `${LIST_CURSOR_KEY_TABLE} holds no key; the framework migrations did not run`)
29
+ }
30
+ return await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify'])
31
+ }
32
+
33
+ function signed(list: string, payload: string): Uint8Array<ArrayBuffer> {
34
+ return new TextEncoder().encode(`fabrika-list-cursor\n${list}\n${payload}`)
35
+ }
36
+
37
+ /** The cursor of the page after the row whose order values are `values`, in the list `list` names. */
38
+ export async function signCursor(key: () => Promise<CryptoKey>, list: string, values: readonly CursorValue[]): Promise<string> {
39
+ const payload = Buffer.from(JSON.stringify(values)).toString('base64url')
40
+ const signature = await crypto.subtle.sign('HMAC', await key(), signed(list, payload))
41
+ return `${payload}.${Buffer.from(signature).toString('base64url')}`
42
+ }
43
+
44
+ /**
45
+ * The order values of `after` when it is a cursor this database signed for the list `list` names, with one plain value
46
+ * per order column (`count`). Anything else is the caller's `list_cursor`: undecodable, unsigned, edited, of another
47
+ * list or order, or of another shape.
48
+ */
49
+ export async function openCursor(key: () => Promise<CryptoKey>, list: string, after: unknown, count: number): Promise<readonly CursorValue[]> {
50
+ const refused = () => new QueryRefusedError('list_cursor', 'after takes the next cursor of a page of this same list')
51
+ if (typeof after !== 'string') {
52
+ throw refused()
53
+ }
54
+ const [payload = '', given = '', ...rest] = after.split('.')
55
+ if (rest.length > 0 || !BASE64URL.test(payload) || !BASE64URL.test(given)) {
56
+ throw refused()
57
+ }
58
+ const signature = Buffer.from(given, 'base64url')
59
+ // One spelling per signature: the last character's padding bits decode to nothing, and a cursor has exactly one.
60
+ if (signature.toString('base64url') !== given) {
61
+ throw refused()
62
+ }
63
+ if (!(await crypto.subtle.verify('HMAC', await key(), new Uint8Array(signature), signed(list, payload)))) {
64
+ throw refused()
65
+ }
66
+ let parsed: unknown
67
+ try {
68
+ parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
69
+ } catch {
70
+ throw refused()
71
+ }
72
+ const values = parseList(parsed, (value): CursorValue => {
73
+ if (typeof value === 'string' || value === null) {
74
+ return value
75
+ }
76
+ throw refused()
77
+ })
78
+ if (values === undefined || values.length !== count) {
79
+ throw refused()
80
+ }
81
+ return values
82
+ }
@@ -17,7 +17,9 @@ import {
17
17
  type FrameworkMigration,
18
18
  JOB_KICKS_TABLE,
19
19
  JOB_LEASES_TABLE,
20
+ JOB_SCHEDULE_TABLE,
20
21
  JOB_WAKES_TABLE,
22
+ LIST_CURSOR_KEY_TABLE,
21
23
  REQUEST_RECEIPTS_TABLE,
22
24
  WEBHOOK_BINDINGS_TABLE,
23
25
  WEBHOOK_DELIVERIES_TABLE,
@@ -176,6 +178,33 @@ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
176
178
  PRIMARY KEY (principal, request_key)
177
179
  ) STRICT;
178
180
  CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
181
+ `,
182
+ }),
183
+ Object.freeze({
184
+ name: '0006_list_cursor_key.sql',
185
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
186
+ -- here once and only read afterwards. 32 random bytes as hex.
187
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
188
+ id INTEGER PRIMARY KEY CHECK (id = 1),
189
+ secret TEXT NOT NULL
190
+ ) STRICT;
191
+ INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, hex(randomblob(32)));
192
+ `,
193
+ }),
194
+ Object.freeze({
195
+ name: '0007_job_schedule.sql',
196
+ sql: `-- Which deploy keeps the cron wakes where no crontab runs (ADR-0080): one row, the highest generation a serving process
197
+ -- has seen. The Durable Object keeps its schedule itself and never writes it; the table keeps both bundles alike.
198
+ CREATE TABLE ${JOB_SCHEDULE_TABLE} (
199
+ id INTEGER PRIMARY KEY CHECK (id = 1),
200
+ generation TEXT NOT NULL
201
+ ) STRICT;
202
+ `,
203
+ }),
204
+ Object.freeze({
205
+ name: '0008_job_schedule_declared.sql',
206
+ sql: `-- The cron keys the stored generation's deploy declares, as a JSON array (see the Postgres bundle's 0014).
207
+ ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
179
208
  `,
180
209
  }),
181
210
  ])
package/src/migrations.ts CHANGED
@@ -10,6 +10,7 @@ export const WEBHOOK_DELIVERIES_TABLE = 'fabrika_webhook_deliveries'
10
10
  export const JOB_LEASES_TABLE = 'fabrika_job_leases'
11
11
  export const JOB_KICKS_TABLE = 'fabrika_job_kicks'
12
12
  export const JOB_WAKES_TABLE = 'fabrika_wakes'
13
+ export const JOB_SCHEDULE_TABLE = 'fabrika_job_schedule'
13
14
  export const FORM_ADMISSIONS_TABLE = 'fabrika_form_admissions'
14
15
  export const FORM_CHALLENGES_TABLE = 'fabrika_form_challenges'
15
16
  export const FORM_FILES_TABLE = 'fabrika_form_files'
@@ -17,6 +18,7 @@ export const FORM_BYTES_TABLE = 'fabrika_form_bytes'
17
18
  export const FILES_TABLE = 'fabrika_files'
18
19
  export const FILE_DELETIONS_TABLE = 'fabrika_file_deletions'
19
20
  export const REQUEST_RECEIPTS_TABLE = 'fabrika_request_receipts'
21
+ export const LIST_CURSOR_KEY_TABLE = 'fabrika_list_cursor_key'
20
22
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
21
23
  export const FILES_RELEASE_FUNCTION = 'fabrika_files_release'
22
24
  /**
@@ -297,6 +299,34 @@ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
297
299
  PRIMARY KEY (principal, request_key)
298
300
  );
299
301
  CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
302
+ `,
303
+ }),
304
+ Object.freeze({
305
+ name: '0012_list_cursor_key.sql',
306
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
307
+ -- here once and only read afterwards. Two random UUIDs give it 244 random bits.
308
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
309
+ id INTEGER PRIMARY KEY CHECK (id = 1),
310
+ secret TEXT NOT NULL
311
+ );
312
+ INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, gen_random_uuid()::text || gen_random_uuid()::text);
313
+ `,
314
+ }),
315
+ Object.freeze({
316
+ name: '0013_job_schedule.sql',
317
+ sql: `-- Which deploy keeps the cron wakes where no crontab runs (ADR-0080): one row, the highest generation a serving process
318
+ -- has seen. A process of that generation reconciles and seeds the wakes; an older one does neither. Compared as bytes.
319
+ CREATE TABLE ${JOB_SCHEDULE_TABLE} (
320
+ id INTEGER PRIMARY KEY CHECK (id = 1),
321
+ generation TEXT COLLATE "C" NOT NULL
322
+ );
323
+ `,
324
+ }),
325
+ Object.freeze({
326
+ name: '0014_job_schedule_declared.sql',
327
+ sql: `-- The cron keys (cron:<job>:<expression>) the stored generation's deploy declares, as a JSON array: a run of any
328
+ -- deploy schedules its job's next fire only under a key in it, so an old revision restores no removed job or expression.
329
+ ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
300
330
  `,
301
331
  }),
302
332
  ])
package/src/orm-types.ts CHANGED
@@ -61,12 +61,16 @@ type ConditionedOf<P, T> = PolicyOf<P, T> extends { readonly when?: infer W } ?
61
61
 
62
62
  type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends { readonly columns: infer C } ? C : never
63
63
 
64
- /** The columns that declare `A` as their own write action. */
65
- type ColumnsWrittenBy<C, A> = { [K in keyof C]: C[K] extends { readonly write: A } ? K : never }[keyof C]
64
+ /** The actions a column's own `write` names: one action, or each of a list. */
65
+ type WriteActionsOf<P> = P extends { readonly write: infer W } ? W extends readonly (infer L extends string)[] ? L : W extends string ? W : never
66
+ : never
67
+
68
+ /** The columns that list `A` among their own write actions. */
69
+ type ColumnsWrittenBy<C, A> = { [K in keyof C]: [A] extends [WriteActionsOf<C[K]>] ? K : never }[keyof C]
66
70
 
67
71
  /**
68
72
  * Each action that updates the table, with the values a capability of it updates: the update action its update list,
69
- * a column's own write action the columns that declare it, and no other.
73
+ * a column's own write action the columns that list it (an update action both), and no other.
70
74
  */
71
75
  type UpdatesOf<DB, P, T extends keyof DB> =
72
76
  & { readonly [A in ActionOf<P, T, 'update'>]: UpdateValues<DB, P, T> }
@@ -76,7 +80,7 @@ type UpdatesOf<DB, P, T extends keyof DB> =
76
80
  >
77
81
  }
78
82
 
79
- type ColumnWriteAction<C> = { [K in keyof C]: C[K] extends { readonly write: infer A extends string } ? A : never }[keyof C]
83
+ type ColumnWriteAction<C> = { [K in keyof C]: WriteActionsOf<C[K]> }[keyof C]
80
84
 
81
85
  /** One table, as every handle reads it. */
82
86
  export interface IndexedTable {
package/src/orm.ts CHANGED
@@ -24,6 +24,7 @@ import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError }
24
24
  import { answerFiles, type FileBinding } from './file-columns'
25
25
  import { databaseNow } from './job-leases'
26
26
  import { rearmClaim } from './job-wakes'
27
+ import { cursorKey, type CursorValue, openCursor, signCursor } from './list-cursor'
27
28
  import {
28
29
  aggregateNode,
29
30
  allOf,
@@ -1301,11 +1302,18 @@ function rowState(table: string, conditions: readonly (Compare | Contains)[], or
1301
1302
  return { origin: freeze({}), table, columns: undefined, conditions, orderBy: order, limit, offset: undefined, joins: [] }
1302
1303
  }
1303
1304
 
1304
- /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
1305
- type CursorValue = string | null
1305
+ /** The list a cursor belongs to, as its signature covers it: its table and its whole order, the tiebreak included. */
1306
+ function cursorList(table: string, order: readonly OrderColumn[]): string {
1307
+ return JSON.stringify([table, order.map((term) => [term.column, term.direction])])
1308
+ }
1306
1309
 
1307
- /** A page's position: the text of its last row's order columns (`keyset.c<n>`), as opaque text. */
1308
- function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly OrderColumn[]): string {
1310
+ /** A page's position: the text of its last row's order columns (`keyset.c<n>`), signed for its list. */
1311
+ async function encodeCursor(
1312
+ key: () => Promise<CryptoKey>,
1313
+ table: string,
1314
+ row: Readonly<Record<string, unknown>>,
1315
+ order: readonly OrderColumn[],
1316
+ ): Promise<string> {
1309
1317
  const values: CursorValue[] = order.map(({ column: name }, index) => {
1310
1318
  const value = hasOwn(row, cursorAlias(index)) ? row[cursorAlias(index)] : null
1311
1319
  if (typeof value === 'string' || value === null) {
@@ -1313,7 +1321,7 @@ function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly Or
1313
1321
  }
1314
1322
  throw new QueryRefusedError('list_page', `${name} came back as ${typeof value} text, which a list cannot page by`)
1315
1323
  })
1316
- return Buffer.from(JSON.stringify(values)).toString('base64url')
1324
+ return await signCursor(key, cursorList(table, order), values)
1317
1325
  }
1318
1326
 
1319
1327
  /** A row as the caller sees it: the position columns stay the layer's. */
@@ -1330,30 +1338,6 @@ function withoutCursor(row: Readonly<Record<string, unknown>>, order: readonly O
1330
1338
  return item
1331
1339
  }
1332
1340
 
1333
- /** The cursor `after` names, parsed at the boundary: one plain value per order column. */
1334
- function decodeCursor(after: unknown, order: readonly OrderColumn[]): readonly CursorValue[] {
1335
- const refused = () => new QueryRefusedError('list_page', 'after takes the next cursor of a page of this same list')
1336
- if (typeof after !== 'string' || after.length === 0) {
1337
- throw refused()
1338
- }
1339
- let parsed: unknown
1340
- try {
1341
- parsed = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'))
1342
- } catch {
1343
- throw refused()
1344
- }
1345
- const values = parseList(parsed, (value): CursorValue => {
1346
- if (typeof value === 'string' || value === null) {
1347
- return value
1348
- }
1349
- throw refused()
1350
- })
1351
- if (values === undefined || values.length !== order.length) {
1352
- throw refused()
1353
- }
1354
- return values
1355
- }
1356
-
1357
1341
  function compare(table: string, name: string, operator: '>' | '<' | '=', value: Primitive): OperationNode {
1358
1342
  return BinaryOperationNode.create(column(table, name), OperatorNode.create(operator), ValueNode.create(value))
1359
1343
  }
@@ -1406,7 +1390,13 @@ async function listRows(
1406
1390
  const conditions = conditionsOf(context, shape, options['where'])
1407
1391
  const order = orderOf(shape, options['orderBy'], tiebreak)
1408
1392
  const limit = limitOf(options['limit'])
1409
- const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1393
+ const session = await run.read()
1394
+ // Read once per page, whether the page verifies `after`, signs `next` or both.
1395
+ let read: Promise<CryptoKey> | undefined
1396
+ const key = (): Promise<CryptoKey> => (read ??= cursorKey(session))
1397
+ const position = options['after'] === undefined
1398
+ ? undefined
1399
+ : keysetAfter(table, order, await openCursor(key, cursorList(table, order), options['after'], order.length))
1410
1400
  if (scope === undefined) {
1411
1401
  return { items: [], next: null }
1412
1402
  }
@@ -1416,7 +1406,6 @@ async function listRows(
1416
1406
  table,
1417
1407
  order.map((term) => term.column),
1418
1408
  )
1419
- const session = await run.read()
1420
1409
  const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
1421
1410
  root: 'SelectQueryNode',
1422
1411
  table,
@@ -1430,7 +1419,7 @@ async function listRows(
1430
1419
  const items = page.map((row) => withoutCursor(row, order))
1431
1420
  return {
1432
1421
  items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
1433
- next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
1422
+ next: rows.length > limit && last !== undefined ? await encodeCursor(key, table, last, order) : null,
1434
1423
  }
1435
1424
  }
1436
1425
 
package/src/policy.ts CHANGED
@@ -206,15 +206,15 @@ export type FilePolicies<Col extends string> = { readonly [C in Col]?: string }
206
206
 
207
207
  /**
208
208
  * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
209
- * without one it falls back to the table's read action. `write`: only a capability of that action updates the column,
210
- * and the table's update action does not, so the column is not in `update`.
209
+ * without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
210
+ * column, so the column is not in `update`; a listed table update action writes it beside its update list.
211
211
  */
212
212
  export type ColumnPolicies<Col extends string, A extends string> = { readonly [C in Col]?: ColumnPolicy<A> }
213
213
 
214
- /** A column's own read actions (one, or a list as a table's read takes), its own write action, or both. */
214
+ /** A column's own read actions and its own write actions (each one, or a list as a table operation takes), or both. */
215
215
  export interface ColumnPolicy<A extends string> {
216
216
  readonly read?: TableAction<A>
217
- readonly write?: A
217
+ readonly write?: TableAction<A>
218
218
  }
219
219
 
220
220
  /** A table no handler writes (a reference table) declares column read actions only. */
@@ -344,8 +344,8 @@ export interface TableModel {
344
344
  readonly files: Readonly<Record<string, string>>
345
345
  /** The columns that declare their own read actions, as declared (also those equal to the table's). */
346
346
  readonly columnReads: Readonly<Record<string, readonly string[]>>
347
- /** The columns that declare their own write action: only a capability of it updates them. */
348
- readonly columnWrites: Readonly<Record<string, string>>
347
+ /** The columns that declare their own write actions, as declared: only a capability of one of them updates them. */
348
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>
349
349
  /** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
350
350
  readonly dates: NameSet
351
351
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
@@ -819,7 +819,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
819
819
  const byConvention = nameSet(unnamed)
820
820
  const restricted: string[] = []
821
821
  const columnReads: Record<string, readonly string[]> = {}
822
- const columnWrites: Record<string, string> = {}
822
+ const columnWrites: Record<string, readonly string[]> = {}
823
823
  const columnsInput = ownEntry(policy, 'columns')
824
824
  const columnPolicies = columnsInput === undefined ? freeze({}) : plainRecord(columnsInput, `${table}: columns`)
825
825
  const declared = ownKeys(columnPolicies)
@@ -846,7 +846,10 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
846
846
  throw new PolicyError(viewWrite(table))
847
847
  }
848
848
  if (writeInput !== undefined) {
849
- setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
849
+ const writes = isArray(writeInput)
850
+ ? distinctActions(table, writeInput, `columns.${name}.write`, action)
851
+ : freeze([action(writeInput, `columns.${name}.write`)])
852
+ setOwn(columnWrites, name, columnWrite(table, name, writes, actions, update))
850
853
  }
851
854
  }
852
855
  const hidden = nameSet(restricted)
@@ -973,19 +976,23 @@ function parseFileColumns(
973
976
  }
974
977
 
975
978
  /**
976
- * A column's own write action takes the column away from the table's update action: one action writes a column, so
977
- * the column is not in `update`, and the action is not the update action (that one lists the column in `update`).
979
+ * A column's own write actions. A table update action may be one of them: it then writes the column beside its update
980
+ * list. Naming exactly the table's update actions says what `update` says, so that form is refused.
978
981
  */
979
- function columnWrite(table: string, name: string, write: string, actions: ActionModel, update: NameSet): string {
982
+ function columnWrite(table: string, name: string, writes: readonly string[], actions: ActionModel, update: NameSet): readonly string[] {
980
983
  if (inSet(update, name)) {
981
984
  throw new PolicyError(
982
- `${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${write}; remove it from update`,
985
+ `${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${
986
+ writes.join(', ')
987
+ }; remove it from update`,
983
988
  )
984
989
  }
985
- if (includes(actions.update, write)) {
986
- throw new PolicyError(`${table}: columns.${name}.write names ${write}, the table's update action; list ${name} in update instead`)
990
+ if (everyIncluded(writes, actions.update) && everyIncluded(actions.update, writes)) {
991
+ throw new PolicyError(
992
+ `${table}: columns.${name}.write names ${writes.join(', ')}, the table's update action; list ${name} in update instead`,
993
+ )
987
994
  }
988
- return write
995
+ return writes
989
996
  }
990
997
 
991
998
  /**
@@ -1002,7 +1009,7 @@ function parseQueue(
1002
1009
  readonly version: string | undefined
1003
1010
  readonly actions: ActionModel
1004
1011
  readonly update: NameSet
1005
- readonly columnWrites: Readonly<Record<string, string>>
1012
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>
1006
1013
  },
1007
1014
  ): QueueModel {
1008
1015
  const queue = plainRecord(input, `${table}: queue`)
@@ -1055,22 +1062,39 @@ function parseColumnSet(table: string, input: unknown, column: (name: unknown, f
1055
1062
  }
1056
1063
 
1057
1064
  /**
1058
- * The columns a capability of `action` updates in `model`: the update list for the table's update action, the
1059
- * columns that declare it as their own write action for any other; none for an action that writes nothing here.
1065
+ * The columns a capability of `action` updates in `model`: the update list for a table update action, and every
1066
+ * column that lists it among its own write actions; none for an action that writes nothing here.
1060
1067
  */
1061
1068
  export function updatableBy(model: TableModel, action: string): NameSet {
1062
- if (includes(model.actions.update, action)) {
1069
+ const owned = columnsWrittenBy(model, action)
1070
+ if (!includes(model.actions.update, action)) {
1071
+ return nameSet(owned)
1072
+ }
1073
+ if (owned.length === 0) {
1063
1074
  return model.update
1064
1075
  }
1076
+ const listed = namesOf(model.update)
1077
+ const columns: string[] = []
1078
+ for (let index = 0; index < listed.length; index++) {
1079
+ columns[columns.length] = listed[index] ?? ''
1080
+ }
1081
+ for (let index = 0; index < owned.length; index++) {
1082
+ columns[columns.length] = owned[index] ?? ''
1083
+ }
1084
+ return nameSet(columns)
1085
+ }
1086
+
1087
+ /** The columns that list `action` among their own write actions. */
1088
+ function columnsWrittenBy(model: TableModel, action: string): readonly string[] {
1065
1089
  const names = ownKeys(model.columnWrites)
1066
1090
  const columns: string[] = []
1067
1091
  for (let index = 0; index < names.length; index++) {
1068
1092
  const name = names[index] ?? ''
1069
- if (model.columnWrites[name] === action) {
1093
+ if (includes(ownEntry(model.columnWrites, name) ?? [], action)) {
1070
1094
  columns[columns.length] = name
1071
1095
  }
1072
1096
  }
1073
- return nameSet(columns)
1097
+ return columns
1074
1098
  }
1075
1099
 
1076
1100
  /**
@@ -1097,13 +1121,7 @@ export function namesAction(model: TableModel, action: string): boolean {
1097
1121
  if (includes(read, action) || includes(insert, action) || includes(update, action) || includes(remove, action)) {
1098
1122
  return true
1099
1123
  }
1100
- const columns = ownKeys(model.columnWrites)
1101
- for (let index = 0; index < columns.length; index++) {
1102
- if (model.columnWrites[columns[index] ?? ''] === action) {
1103
- return true
1104
- }
1105
- }
1106
- return false
1124
+ return columnsWrittenBy(model, action).length > 0
1107
1125
  }
1108
1126
 
1109
1127
  /**
@@ -1186,9 +1204,12 @@ export function updateActions(model: TableModel): readonly string[] {
1186
1204
  }
1187
1205
  const names = ownKeys(model.columnWrites)
1188
1206
  for (let index = 0; index < names.length; index++) {
1189
- const write = model.columnWrites[names[index] ?? '']
1190
- if (write !== undefined && !includes(actions, write)) {
1191
- actions[actions.length] = write
1207
+ const writes = ownEntry(model.columnWrites, names[index] ?? '') ?? []
1208
+ for (let position = 0; position < writes.length; position++) {
1209
+ const write = writes[position] ?? ''
1210
+ if (!includes(actions, write)) {
1211
+ actions[actions.length] = write
1212
+ }
1192
1213
  }
1193
1214
  }
1194
1215
  return actions
@@ -1755,7 +1776,10 @@ function tableActionNames(table: LinkedTable): NameSet {
1755
1776
  }
1756
1777
  const writes = ownKeys(table.columnWrites)
1757
1778
  for (let index = 0; index < writes.length; index++) {
1758
- names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1779
+ const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
1780
+ for (let position = 0; position < actions.length; position++) {
1781
+ names[names.length] = actions[position] ?? ''
1782
+ }
1759
1783
  }
1760
1784
  return nameSet(names)
1761
1785
  }
@@ -1772,7 +1796,10 @@ function writeActionNames(table: LinkedTable): NameSet {
1772
1796
  }
1773
1797
  const writes = ownKeys(table.columnWrites)
1774
1798
  for (let index = 0; index < writes.length; index++) {
1775
- names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1799
+ const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
1800
+ for (let position = 0; position < actions.length; position++) {
1801
+ names[names.length] = actions[position] ?? ''
1802
+ }
1776
1803
  }
1777
1804
  return nameSet(names)
1778
1805
  }
package/src/tables.ts CHANGED
@@ -172,10 +172,10 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
172
172
  const declared = [...ownKeys(model.columnReads), ...ownKeys(model.columnWrites)]
173
173
  for (let index = 0; index < declared.length; index++) {
174
174
  const name = declared[index] ?? ''
175
- // A single read action stays its text, so a policy that names one keeps its digest.
175
+ // A single action stays its text, so a policy that names one keeps its digest.
176
176
  const read = actionArtifact(ownEntry(model.columnReads, name) ?? [])
177
- const write = ownEntry(model.columnWrites, name)
178
- setOwn(columns, name, { ...(read === null ? {} : { read }), ...(write === undefined ? {} : { write }) })
177
+ const write = actionArtifact(ownEntry(model.columnWrites, name) ?? [])
178
+ setOwn(columns, name, { ...(read === null ? {} : { read }), ...(write === null ? {} : { write }) })
179
179
  }
180
180
  return {
181
181
  scope: scopeOf(model.scope),
@@ -789,11 +789,14 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
789
789
  return stored
790
790
  }
791
791
 
792
- /** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
792
+ /**
793
+ * A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. Either
794
+ * holds a random v4 uuid's 122 bits, so a large seed never collides on a key.
795
+ */
793
796
  function scopeValue(table: string, name: string, dimension: string, world: string): string {
794
797
  const column = columnOf(table, name)
795
798
  if (column.uuid) return crypto.randomUUID()
796
- if (column.text) return `${dimension}-${world}-${randomHex()}`
799
+ if (column.text) return `${dimension}-${world}-${crypto.randomUUID()}`
797
800
  throw new Error(`${table}.${name} holds a ${dimension} as ${column.type}; a key or containment column holds its scope value as text or uuid`)
798
801
  }
799
802
 
@@ -40,7 +40,8 @@ export declare const QUERY_REFUSALS: {
40
40
  readonly unexpected_row: "the database answered a row in another shape than its migration declares";
41
41
  readonly statement_shape: "the compiled statement has a form the guard does not admit";
42
42
  readonly scope_predicate: "the scope predicate is missing or is not a top-level conjunct";
43
- readonly list_page: "a list limit, cursor or order outside what a page admits";
43
+ readonly list_page: "a list limit or order outside what a page admits";
44
+ readonly list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order";
44
45
  readonly too_many_rows: "all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate";
45
46
  readonly undeclared_reach: "the site reaches data it did not declare (sql or unscoped, or their mode)";
46
47
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
@@ -9,7 +9,7 @@ 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
11
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
12
- export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
12
+ export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes';
13
13
  export type { DataAccess, DataHandles, DataSite } from './orm';
14
14
  export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
15
15
  export type { RequestReceipt, RequestReceipts } from './request-receipts';
@@ -54,6 +54,12 @@ export interface JobLeases {
54
54
  * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
55
55
  */
56
56
  finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>;
57
+ /**
58
+ * Gives back a lease under which no run started: frees it and leaves every wake as it is, owned ones disowned, and
59
+ * records no run (no status, end or duration). A process schedule's timer releases a lease whose take owned no due
60
+ * wake (ADR-0080). `false` when `fence` no longer held it.
61
+ */
62
+ release(fence: LeaseFence): Promise<boolean>;
57
63
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
58
64
  markPending(job: string): Promise<void>;
59
65
  /**
@@ -31,9 +31,15 @@ export type FinishWakes =
31
31
  /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
32
32
  {
33
33
  readonly kind: 'completed';
34
+ /**
35
+ * With `scheduled`, the next fire is written only when the stored schedule (`keepSchedule`) declares its key, read
36
+ * in the finish's transaction: under a process schedule, a run of an older deploy writes no removed job's or
37
+ * changed expression's fire (ADR-0080).
38
+ */
34
39
  readonly nextCron?: {
35
40
  readonly expression: string;
36
41
  readonly dueAt: Date;
42
+ readonly scheduled?: boolean;
37
43
  };
38
44
  }
39
45
  /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
@@ -53,18 +59,31 @@ export interface JobWakes {
53
59
  pending(job: string): Promise<readonly Wake[]>;
54
60
  /**
55
61
  * 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.
62
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given;
63
+ * with `jobs`, of those jobs only, so a wake of a job this process does not run never holds its timer.
57
64
  */
58
- next(using?: Session): Promise<Date | null>;
65
+ next(using?: Session, jobs?: readonly string[]): Promise<Date | null>;
59
66
  /** 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>;
67
+ untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null>;
68
+ /**
69
+ * Where no crontab runs (ADR-0080), in one transaction: raises the stored schedule generation to `generation` when that
70
+ * one is higher in byte order, with the cron keys `fires` declare, and when `generation` is then the stored one,
71
+ * reconciles the wakes against `fires` (as `reconcile`) and adds each fire's wake under its job's cron key where none
72
+ * is pending (an existing one, overdue or not, is left as it is and not locked, so a lease taken meanwhile still owns
73
+ * it). Answers whether `generation` is the stored one; a process of an older one writes nothing. The generation's row stays
74
+ * locked until the transaction commits, so on Postgres a newer generation waits for an older one's seed and reconciles
75
+ * after it, and an older one queued behind a newer one reads the newer and writes nothing. A UUIDv7, lowercase: a
76
+ * later deploy's sorts later.
77
+ */
78
+ keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean>;
61
79
  /** The database's clock, read in `using` when given: a wake due now is due by it. */
62
80
  now(using?: Session): Promise<Date>;
63
81
  /**
64
82
  * 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.
83
+ * each declared job's cron wake whose key names another expression; answers how many it deleted. In `using` when
84
+ * given.
66
85
  */
67
- reconcile(declared: readonly DeclaredJob[]): Promise<number>;
86
+ reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number>;
68
87
  /**
69
88
  * 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
89
  * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
@@ -76,6 +95,10 @@ export interface JobWakes {
76
95
  */
77
96
  expiredHolders(): Promise<readonly string[]>;
78
97
  }
98
+ /** A declared job and its next fire, which `keepSchedule` seeds; `null` when its expression has none in the window. */
99
+ export interface ScheduledFire extends DeclaredJob {
100
+ readonly dueAt: Date | null;
101
+ }
79
102
  /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
80
103
  export interface DeclaredJob {
81
104
  readonly job: string;
@@ -0,0 +1,13 @@
1
+ import { type Session } from './database';
2
+ /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
3
+ export type CursorValue = string | null;
4
+ /** The database's cursor key, read in `session`; the framework migration wrote it, so its absence is no caller's fault. */
5
+ export declare function cursorKey(session: Session): Promise<CryptoKey>;
6
+ /** The cursor of the page after the row whose order values are `values`, in the list `list` names. */
7
+ export declare function signCursor(key: () => Promise<CryptoKey>, list: string, values: readonly CursorValue[]): Promise<string>;
8
+ /**
9
+ * The order values of `after` when it is a cursor this database signed for the list `list` names, with one plain value
10
+ * per order column (`count`). Anything else is the caller's `list_cursor`: undecodable, unsigned, edited, of another
11
+ * list or order, or of another shape.
12
+ */
13
+ export declare function openCursor(key: () => Promise<CryptoKey>, list: string, after: unknown, count: number): Promise<readonly CursorValue[]>;
@@ -5,6 +5,7 @@ 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
7
  export declare const JOB_WAKES_TABLE = "fabrika_wakes";
8
+ export declare const JOB_SCHEDULE_TABLE = "fabrika_job_schedule";
8
9
  export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
9
10
  export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
10
11
  export declare const FORM_FILES_TABLE = "fabrika_form_files";
@@ -12,6 +13,7 @@ export declare const FORM_BYTES_TABLE = "fabrika_form_bytes";
12
13
  export declare const FILES_TABLE = "fabrika_files";
13
14
  export declare const FILE_DELETIONS_TABLE = "fabrika_file_deletions";
14
15
  export declare const REQUEST_RECEIPTS_TABLE = "fabrika_request_receipts";
16
+ export declare const LIST_CURSOR_KEY_TABLE = "fabrika_list_cursor_key";
15
17
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
16
18
  export declare const FILES_RELEASE_FUNCTION = "fabrika_files_release";
17
19
  /**
@@ -49,15 +49,17 @@ type ConditionedOf<P, T> = PolicyOf<P, T> extends {
49
49
  type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends {
50
50
  readonly columns: infer C;
51
51
  } ? C : never;
52
- /** The columns that declare `A` as their own write action. */
52
+ /** The actions a column's own `write` names: one action, or each of a list. */
53
+ type WriteActionsOf<P> = P extends {
54
+ readonly write: infer W;
55
+ } ? W extends readonly (infer L extends string)[] ? L : W extends string ? W : never : never;
56
+ /** The columns that list `A` among their own write actions. */
53
57
  type ColumnsWrittenBy<C, A> = {
54
- [K in keyof C]: C[K] extends {
55
- readonly write: A;
56
- } ? K : never;
58
+ [K in keyof C]: [A] extends [WriteActionsOf<C[K]>] ? K : never;
57
59
  }[keyof C];
58
60
  /**
59
61
  * Each action that updates the table, with the values a capability of it updates: the update action its update list,
60
- * a column's own write action the columns that declare it, and no other.
62
+ * a column's own write action the columns that list it (an update action both), and no other.
61
63
  */
62
64
  type UpdatesOf<DB, P, T extends keyof DB> = {
63
65
  readonly [A in ActionOf<P, T, 'update'>]: UpdateValues<DB, P, T>;
@@ -65,9 +67,7 @@ type UpdatesOf<DB, P, T extends keyof DB> = {
65
67
  readonly [A in ColumnWriteAction<ColumnPoliciesOf<P, T>>]: Flat<Pick<Updateable<DB[T]>, ColumnsWrittenBy<ColumnPoliciesOf<P, T>, A> & keyof Updateable<DB[T]>>>;
66
68
  };
67
69
  type ColumnWriteAction<C> = {
68
- [K in keyof C]: C[K] extends {
69
- readonly write: infer A extends string;
70
- } ? A : never;
70
+ [K in keyof C]: WriteActionsOf<C[K]>;
71
71
  }[keyof C];
72
72
  /** One table, as every handle reads it. */
73
73
  export interface IndexedTable {
@@ -192,16 +192,16 @@ export type FilePolicies<Col extends string> = {
192
192
  };
193
193
  /**
194
194
  * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
195
- * without one it falls back to the table's read action. `write`: only a capability of that action updates the column,
196
- * and the table's update action does not, so the column is not in `update`.
195
+ * without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
196
+ * column, so the column is not in `update`; a listed table update action writes it beside its update list.
197
197
  */
198
198
  export type ColumnPolicies<Col extends string, A extends string> = {
199
199
  readonly [C in Col]?: ColumnPolicy<A>;
200
200
  };
201
- /** A column's own read actions (one, or a list as a table's read takes), its own write action, or both. */
201
+ /** A column's own read actions and its own write actions (each one, or a list as a table operation takes), or both. */
202
202
  export interface ColumnPolicy<A extends string> {
203
203
  readonly read?: TableAction<A>;
204
- readonly write?: A;
204
+ readonly write?: TableAction<A>;
205
205
  }
206
206
  /** A table no handler writes (a reference table) declares column read actions only. */
207
207
  export type ColumnReadPolicies<Col extends string, A extends string> = {
@@ -335,8 +335,8 @@ export interface TableModel {
335
335
  readonly files: Readonly<Record<string, string>>;
336
336
  /** The columns that declare their own read actions, as declared (also those equal to the table's). */
337
337
  readonly columnReads: Readonly<Record<string, readonly string[]>>;
338
- /** The columns that declare their own write action: only a capability of it updates them. */
339
- readonly columnWrites: Readonly<Record<string, string>>;
338
+ /** The columns that declare their own write actions, as declared: only a capability of one of them updates them. */
339
+ readonly columnWrites: Readonly<Record<string, readonly string[]>>;
340
340
  /** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
341
341
  readonly dates: NameSet;
342
342
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
@@ -500,8 +500,8 @@ export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never] ? Unavaila
500
500
  */
501
501
  export declare function readTables(columns: unknown, policies: unknown, vocabulary: unknown): Tables<unknown, unknown>;
502
502
  /**
503
- * The columns a capability of `action` updates in `model`: the update list for the table's update action, the
504
- * columns that declare it as their own write action for any other; none for an action that writes nothing here.
503
+ * The columns a capability of `action` updates in `model`: the update list for a table update action, and every
504
+ * column that lists it among its own write actions; none for an action that writes nothing here.
505
505
  */
506
506
  export declare function updatableBy(model: TableModel, action: string): NameSet;
507
507
  /**