@fabrika/db 0.9.0-dev.7 → 0.9.0-dev.70

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.
Files changed (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +69 -13
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +67 -9
  10. package/src/errors.ts +9 -5
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +187 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +40 -9
  47. package/types/src/errors.d.ts +8 -5
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +35 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +176 -22
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
package/src/json.ts ADDED
@@ -0,0 +1,187 @@
1
+ // JSON columns at the layer's boundary: `jsonb` on Postgres, a column declared `JSONB` on SQLite (the column list's
2
+ // `json`). A write takes a JSON value, checked and serialized here, and binds its text as one parameter: Postgres reads
3
+ // an untyped text parameter into `jsonb`, SQLite stores the text. A read answers the parsed value: `Bun.SQL` decodes
4
+ // `jsonb` itself, and `sqliteJson` parses SQLite's text. JS `null` is SQL NULL in both directions, so a top-level JSON
5
+ // `null` written by `ctx.sql` reads as `null` too. A JSON column is never compared, ordered, grouped or aggregated by
6
+ // the layer; a path condition is `ctx.sql`'s (`->>`). A column the policy declares a zod schema for (`json`) is checked
7
+ // against it: a write's value is parsed before it is serialized, and every value a read answers is parsed again.
8
+
9
+ import { z } from 'zod/v4'
10
+ import { hasOwn, isArray, OBJECT_PROTOTYPE, ownDescriptor, ownNames, ownSymbols, parseList, prototypeOf } from './builtins'
11
+ import { QueryRefusedError } from './errors'
12
+
13
+ const stringify = JSON.stringify
14
+ const parse = JSON.parse
15
+ const isFinite = Number.isFinite
16
+
17
+ /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
18
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | { readonly [key: string]: JsonValue | undefined }
19
+
20
+ /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
21
+ export type JsonColumnValue = Exclude<JsonValue, null>
22
+
23
+ /** The zod schema a table policy declares for a JSON column (`json: { <column>: schema }`); its output is JSON. */
24
+ export type JsonSchema = z.core.$ZodType
25
+
26
+ /**
27
+ * What a failed parse says of the value: the first issue's code, and the type it expected. No path, message or key: a
28
+ * key or a message can quote the value, as a row error of `ctx.sql` never does.
29
+ */
30
+ function issueText(error: z.core.$ZodError): string {
31
+ const [issue] = error.issues
32
+ if (issue === undefined) {
33
+ return 'refused'
34
+ }
35
+ return issue.code === 'invalid_type' ? `${issue.code}, expected ${issue.expected}` : issue.code
36
+ }
37
+
38
+ /**
39
+ * The text a column with a declared schema binds for a written value, or `null` (SQL NULL) where the schema answers
40
+ * `null`. The value is first read as `jsonInput` reads any JSON column's (plain data only, so no getter, `toJSON` or
41
+ * class instance reaches the schema), then parsed, and the schema's output is what is stored. A value the schema
42
+ * refuses, and an output the schema would refuse on read, are `invalid_value` before anything is sent.
43
+ */
44
+ export function schemaInput(schema: JsonSchema, value: unknown, where: string): string | null {
45
+ const parsed = z.safeParse(schema, parse(jsonInput(value, where)))
46
+ if (!parsed.success) {
47
+ throw new QueryRefusedError('invalid_value', `${where} does not match its JSON schema (${issueText(parsed.error)})`)
48
+ }
49
+ if (parsed.data === null) {
50
+ return null
51
+ }
52
+ const text = jsonInput(parsed.data, where)
53
+ if (!z.safeParse(schema, parse(text)).success) {
54
+ throw new QueryRefusedError('invalid_value', `${where}: its JSON schema refuses its own output, which every read parses again`)
55
+ }
56
+ return text
57
+ }
58
+
59
+ /**
60
+ * A read value of a column with a declared schema, parsed by it: a stored value the schema refuses (written by
61
+ * `ctx.sql`, a migration, or before the schema tightened) is `unexpected_row`, so no handler sees it.
62
+ */
63
+ export function schemaOutput(schema: JsonSchema, value: unknown, where: string): unknown {
64
+ const parsed = z.safeParse(schema, value)
65
+ if (!parsed.success) {
66
+ throw new QueryRefusedError('unexpected_row', `${where} came back in a shape its JSON schema refuses (${issueText(parsed.error)})`)
67
+ }
68
+ return parsed.data
69
+ }
70
+
71
+ /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
72
+ export const MAX_JSON_DEPTH = 64
73
+
74
+ function refusal(where: string, detail: string): QueryRefusedError {
75
+ return new QueryRefusedError('invalid_value', `${where} takes a JSON value (${detail})`)
76
+ }
77
+
78
+ /** Half of a surrogate pair, which Postgres refuses in `jsonb` text and SQLite would store. */
79
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
80
+ const NUL = String.fromCharCode(0)
81
+
82
+ function text(value: string, where: string): string {
83
+ if (value.includes(NUL) || LONE_SURROGATE.test(value)) {
84
+ throw refusal(where, 'a string or key holds no NUL character and no lone surrogate')
85
+ }
86
+ return stringify(value)
87
+ }
88
+
89
+ function written(value: unknown, where: string, depth: number): string {
90
+ if (typeof value === 'string') {
91
+ return text(value, where)
92
+ }
93
+ if (value === null || typeof value === 'boolean') {
94
+ return stringify(value)
95
+ }
96
+ if (typeof value === 'number') {
97
+ if (!isFinite(value)) {
98
+ throw refusal(where, 'a number is finite')
99
+ }
100
+ return stringify(value)
101
+ }
102
+ if (typeof value !== 'object') {
103
+ throw refusal(where, `${typeof value} is not JSON`)
104
+ }
105
+ if (depth >= MAX_JSON_DEPTH) {
106
+ throw refusal(where, `nested at most ${MAX_JSON_DEPTH} deep, and never containing itself`)
107
+ }
108
+ if (isArray(value)) {
109
+ const items = parseList(value, (item) => {
110
+ if (item === undefined) {
111
+ throw refusal(where, 'an array holds no undefined')
112
+ }
113
+ return written(item, where, depth + 1)
114
+ })
115
+ if (items === undefined) {
116
+ throw refusal(where, 'an array is a plain array without holes or accessors')
117
+ }
118
+ let serialized = '['
119
+ for (let index = 0; index < items.length; index++) {
120
+ serialized += `${index === 0 ? '' : ','}${items[index] ?? ''}`
121
+ }
122
+ return `${serialized}]`
123
+ }
124
+ const prototype: unknown = prototypeOf(value)
125
+ if (prototype !== OBJECT_PROTOTYPE && prototype !== null) {
126
+ throw refusal(where, 'an object is a plain object, not an instance of a class such as a Date or a Map')
127
+ }
128
+ if (ownSymbols(value).length > 0) {
129
+ throw refusal(where, 'an object has string keys only')
130
+ }
131
+ const keys = ownNames(value)
132
+ let serialized = '{'
133
+ let first = true
134
+ for (let index = 0; index < keys.length; index++) {
135
+ const key = keys[index] ?? ''
136
+ const descriptor = ownDescriptor(value, key)
137
+ if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
138
+ throw refusal(where, `${key} is an accessor`)
139
+ }
140
+ const member: unknown = descriptor.value
141
+ if (member === undefined) {
142
+ continue
143
+ }
144
+ serialized += `${first ? '' : ','}${text(key, where)}:${written(member, where, depth + 1)}`
145
+ first = false
146
+ }
147
+ return `${serialized}}`
148
+ }
149
+
150
+ /**
151
+ * A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
152
+ * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
153
+ */
154
+ export function jsonInput(value: unknown, where: string): string {
155
+ return written(value, where, 0)
156
+ }
157
+
158
+ /** Whether `value` is one a JSON column takes: a JSON value `jsonInput` serializes, other than `null`. */
159
+ export function isJsonColumnValue(value: unknown): value is JsonColumnValue {
160
+ if (value === null) {
161
+ return false
162
+ }
163
+ try {
164
+ written(value, '', 0)
165
+ return true
166
+ } catch {
167
+ return false
168
+ }
169
+ }
170
+
171
+ /**
172
+ * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
173
+ * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
174
+ */
175
+ export function sqliteJson(value: unknown, where: string): unknown {
176
+ if (typeof value === 'number') {
177
+ return value
178
+ }
179
+ if (typeof value === 'string') {
180
+ try {
181
+ return parse(value)
182
+ } catch {
183
+ // Fall through: the text is not JSON, which no write of the layer stores.
184
+ }
185
+ }
186
+ throw new QueryRefusedError('unexpected_row', `${where} came back as something other than JSON text, the form a JSON column is stored in on SQLite`)
187
+ }
@@ -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
+ }