@fabrika/db 0.9.0-dev.3 → 0.9.0-dev.30

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 (82) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +8 -5
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +181 -0
  24. package/src/migrations.ts +43 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +198 -67
  27. package/src/orm.ts +383 -133
  28. package/src/policy.ts +1933 -122
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +55 -3
  31. package/src/request-receipts.ts +107 -0
  32. package/src/sql.ts +247 -476
  33. package/src/sqlite-bun.ts +149 -0
  34. package/src/sqlite-migrate.ts +242 -0
  35. package/src/sqlite.ts +269 -0
  36. package/src/store.ts +2292 -239
  37. package/src/stored-files.ts +188 -52
  38. package/src/tables.ts +171 -5
  39. package/src/temporal.ts +122 -9
  40. package/src/testing-shared.ts +1348 -0
  41. package/src/testing-sqlite.ts +685 -0
  42. package/src/testing.ts +310 -494
  43. package/src/vocabulary-tables.ts +159 -27
  44. package/types/src/application-rows.d.ts +58 -0
  45. package/types/src/authority.d.ts +147 -0
  46. package/types/src/builtins.d.ts +2 -0
  47. package/types/src/capability.d.ts +55 -2
  48. package/types/src/codegen-sqlite.d.ts +13 -0
  49. package/types/src/codegen.d.ts +79 -5
  50. package/types/src/condition-nodes.d.ts +9 -0
  51. package/types/src/conditions.d.ts +151 -0
  52. package/types/src/database.d.ts +81 -20
  53. package/types/src/description.d.ts +26 -8
  54. package/types/src/errors.d.ts +7 -5
  55. package/types/src/file-columns.d.ts +6 -4
  56. package/types/src/framework.d.ts +12 -5
  57. package/types/src/guard.d.ts +24 -0
  58. package/types/src/index.d.ts +5 -4
  59. package/types/src/job-leases.d.ts +34 -5
  60. package/types/src/job-wakes.d.ts +101 -0
  61. package/types/src/json.d.ts +18 -0
  62. package/types/src/migrations-sqlite.d.ts +4 -0
  63. package/types/src/migrations.d.ts +2 -0
  64. package/types/src/nodes.d.ts +17 -2
  65. package/types/src/orm-types.d.ts +155 -63
  66. package/types/src/orm.d.ts +21 -0
  67. package/types/src/policy.d.ts +344 -16
  68. package/types/src/postgres.d.ts +12 -0
  69. package/types/src/registry.d.ts +40 -3
  70. package/types/src/request-receipts.d.ts +22 -0
  71. package/types/src/sql.d.ts +29 -21
  72. package/types/src/sqlite-bun.d.ts +21 -0
  73. package/types/src/sqlite-migrate.d.ts +28 -0
  74. package/types/src/sqlite.d.ts +24 -0
  75. package/types/src/store.d.ts +143 -34
  76. package/types/src/stored-files.d.ts +6 -2
  77. package/types/src/tables.d.ts +18 -2
  78. package/types/src/temporal.d.ts +24 -0
  79. package/types/src/testing-shared.d.ts +290 -0
  80. package/types/src/testing-sqlite.d.ts +37 -0
  81. package/types/src/testing.d.ts +2 -93
  82. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -0,0 +1,450 @@
1
+ // The framework's side of `fabrika_wakes` (`@fabrika/db/migrations`): a job's durable pending work, one row per due
2
+ // unit (its next scheduled run, a kick, a claim's re-arm, a durable retry), and the scheduler's next wake over it and the
3
+ // leases. Only `@fabrika/app` reaches it, through `frameworkTablesOf`. A run owns the wakes due when it took its lease,
4
+ // marked in that transaction (`owned`); a wake written or merged into afterwards is not its. Only the transaction of that
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.
7
+
8
+ import { uuidv7 } from '@fabrika/platform'
9
+ import { freeze } from './builtins'
10
+ import type { LeaseFence } from './capability'
11
+ import { type FixedParameter, runFixedStatement, type Session, sessionOf } from './database'
12
+ import { QueryRefusedError } from './errors'
13
+ import type { DialectTexts, JobOutcome, LeaseChange, LeaseProjection } from './job-leases'
14
+ import { JOB_LEASES_TABLE, JOB_WAKES_TABLE } from './migrations'
15
+ import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
16
+ import { refuseInProduction } from './production'
17
+ import type { DataLayerRuntime } from './store'
18
+
19
+ export const WAKE_REASONS = ['cron', 'kick', 'claim', 'retry'] as const
20
+
21
+ export type WakeReason = (typeof WAKE_REASONS)[number]
22
+
23
+ export interface NewWake {
24
+ readonly job: string
25
+ readonly reason: WakeReason
26
+ readonly dueAt: Date
27
+ /** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
28
+ readonly dedupe?: string
29
+ }
30
+
31
+ export interface Wake {
32
+ readonly id: string
33
+ readonly job: string
34
+ readonly reason: WakeReason
35
+ readonly dueAt: Date
36
+ /** How many failed runs moved this wake (`retry`). */
37
+ readonly attempt: number
38
+ readonly dedupe: string | null
39
+ /** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
40
+ readonly owned: boolean
41
+ }
42
+
43
+ /**
44
+ * What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
45
+ * transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
46
+ * leaves the wakes as they are.
47
+ */
48
+ export type FinishWakes =
49
+ /** 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 } }
51
+ /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
52
+ | { readonly kind: 'retry'; readonly at: Date }
53
+
54
+ export interface JobWakes {
55
+ /**
56
+ * Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
57
+ * keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
58
+ * run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
59
+ * a key another job holds is refused.
60
+ */
61
+ schedule(wake: NewWake, using?: Session): Promise<Wake>
62
+ /** The pending wakes of `job`, earliest first. */
63
+ pending(job: string): Promise<readonly Wake[]>
64
+ /**
65
+ * 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.
67
+ */
68
+ next(using?: Session): Promise<Date | null>
69
+ /** 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>
71
+ /** The database's clock, read in `using` when given: a wake due now is due by it. */
72
+ now(using?: Session): Promise<Date>
73
+ /**
74
+ * 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.
76
+ */
77
+ reconcile(declared: readonly DeclaredJob[]): Promise<number>
78
+ /**
79
+ * 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
+ * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
81
+ */
82
+ hasten(ids: readonly string[]): Promise<number>
83
+ /**
84
+ * The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
85
+ * alarm through `next` until someone reaps it.
86
+ */
87
+ expiredHolders(): Promise<readonly string[]>
88
+ }
89
+
90
+ /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
91
+ export interface DeclaredJob {
92
+ readonly job: string
93
+ readonly expression: string
94
+ }
95
+
96
+ const W = JOB_WAKES_TABLE
97
+ const L = JOB_LEASES_TABLE
98
+ const COLUMNS = 'job, due_at, reason, attempt, dedupe'
99
+ const SELECTED = `${COLUMNS}, owned`
100
+ const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
101
+
102
+ /** A stored timestamp as epoch milliseconds, in each dialect. */
103
+ const PG_EPOCH_MS = (column: string): string => `floor(extract(epoch from ${column}) * 1000)::bigint`
104
+ const SQLITE_EPOCH_MS = (column: string): string => `cast(round((julianday(${column}) - 2440587.5) * 86400000) as integer)`
105
+
106
+ /** The start of the job's current run, in epoch milliseconds: the wakes due by then are the ones it takes. */
107
+ const PG_RUN_START = `(select ${PG_EPOCH_MS('last_started_at')} from ${L} where job = $1)`
108
+ const SQLITE_RUN_START = `(select ${SQLITE_EPOCH_MS('last_started_at')} from ${L} where job = ?1)`
109
+
110
+ const SQL_SCHEDULE: DialectTexts = {
111
+ // The update applies only to the same job's row, so a key another job holds answers no row.
112
+ postgres: `insert into ${W} (id, ${COLUMNS}) values ($1::uuid, $2, $3::bigint, $4, 0, $5)
113
+ on conflict (dedupe) where dedupe is not null do update set due_at = least(${W}.due_at, excluded.due_at),
114
+ owned = ${W}.owned and excluded.reason = 'cron' where ${W}.job = excluded.job
115
+ returning id::text as id, ${SELECTED}`,
116
+ sqlite: `insert into ${W} (id, ${COLUMNS}) values (?1, ?2, cast(?3 as integer), ?4, 0, ?5)
117
+ on conflict (dedupe) where dedupe is not null do update set due_at = min(${W}.due_at, excluded.due_at),
118
+ owned = ${W}.owned and excluded.reason = 'cron' where ${W}.job = excluded.job
119
+ returning id, ${SELECTED}`,
120
+ }
121
+
122
+ const SQL_PENDING: DialectTexts = {
123
+ postgres: `select id::text as id, ${SELECTED} from ${W} where job = $1 order by due_at, id`,
124
+ sqlite: `select id, ${SELECTED} from ${W} where job = ?1 order by due_at, id`,
125
+ }
126
+
127
+ // A taking run marks every wake of its job, due by its start or not. A row a write still holds (`skip locked`) is being
128
+ // written, and that write leaves it unowned: the lease is taken without waiting for it.
129
+ const SQL_OWN: DialectTexts = {
130
+ postgres: `update ${W} set owned = coalesce(${W}.due_at <= ${PG_RUN_START}, false)
131
+ where id in (select id from ${W} where job = $1 for update skip locked)`,
132
+ sqlite: `update ${W} set owned = coalesce(due_at <= ${SQLITE_RUN_START}, 0) where job = ?1`,
133
+ }
134
+
135
+ const SQL_DISOWN: DialectTexts = {
136
+ postgres: `update ${W} set owned = false where id in (select id from ${W} where job = $1 and owned for update skip locked)`,
137
+ sqlite: `update ${W} set owned = 0 where job = ?1 and owned = 1`,
138
+ }
139
+
140
+ // Two candidates, each one index-ordered or per-job lookup: the earliest wake of a free or expired job walks the due index
141
+ // 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.
143
+ const SQL_NEXT: DialectTexts = {
144
+ postgres: `select
145
+ (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,
148
+ ${PG_EPOCH_MS('clock_timestamp()')} as now`,
149
+ sqlite: `select
150
+ (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,
153
+ ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
154
+ }
155
+
156
+ const SQL_CLOCK: DialectTexts = {
157
+ postgres: `select ${PG_EPOCH_MS('clock_timestamp()')} as now`,
158
+ sqlite: `select ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
159
+ }
160
+
161
+ const SQL_EXPIRED_HOLDERS: DialectTexts = {
162
+ postgres: `select job from ${L} where holder is not null and expires_at <= clock_timestamp() order by job`,
163
+ sqlite: `select job from ${L} where holder is not null and expires_at <= ${SQLITE_NOW} order by job`,
164
+ }
165
+
166
+ const SQL_CONSUME: DialectTexts = {
167
+ postgres: `delete from ${W} where job = $1 and owned`,
168
+ sqlite: `delete from ${W} where job = ?1 and owned = 1`,
169
+ }
170
+
171
+ const SQL_RETRY: DialectTexts = {
172
+ postgres: `update ${W} set due_at = $2::bigint, attempt = attempt + 1, owned = false where job = $1 and owned`,
173
+ sqlite: `update ${W} set due_at = cast(?2 as integer), attempt = attempt + 1, owned = 0 where job = ?1 and owned = 1`,
174
+ }
175
+
176
+ const SQL_DROP_CLAIM: DialectTexts = {
177
+ postgres: `delete from ${W} where job = $1 and dedupe = $2`,
178
+ sqlite: `delete from ${W} where job = ?1 and dedupe = ?2`,
179
+ }
180
+
181
+ // A wake is kept when its job is declared and it is no cron wake, or is the cron wake of the declared expression.
182
+ const SQL_RECONCILE: DialectTexts = {
183
+ postgres: `delete from ${W} where not exists (select 1 from jsonb_to_recordset($1::jsonb) as d(job text, expression text)
184
+ where d.job = ${W}.job and (${W}.reason <> 'cron' or ${W}.dedupe = 'cron:' || d.job || ':' || d.expression)) returning id`,
185
+ sqlite: `delete from ${W} where not exists (select 1 from json_each(?1) d
186
+ where json_extract(d.value, '$.job') = ${W}.job
187
+ and (${W}.reason <> 'cron' or ${W}.dedupe = 'cron:' || json_extract(d.value, '$.job') || ':' || json_extract(d.value, '$.expression'))) returning id`,
188
+ }
189
+
190
+ // Only a wake still ahead moves: moving an overdue one to now would postpone it.
191
+ const SQL_HASTEN: DialectTexts = {
192
+ postgres: `update ${W} set due_at = ${PG_EPOCH_MS('now()')}
193
+ where id::text in (select jsonb_array_elements_text($1::jsonb)) and due_at > ${PG_EPOCH_MS('now()')} returning id::text as id`,
194
+ sqlite: `update ${W} set due_at = ${SQLITE_EPOCH_MS(SQLITE_NOW)}
195
+ where id in (select value from json_each(?1)) and due_at > ${SQLITE_EPOCH_MS(SQLITE_NOW)} returning id`,
196
+ }
197
+
198
+ function record(row: unknown): Readonly<Record<string, unknown>> {
199
+ if (typeof row !== 'object' || row === null) {
200
+ throw new QueryRefusedError('unexpected_row', `${W} answered a row that is not an object`)
201
+ }
202
+ return Object.fromEntries(Object.entries(row))
203
+ }
204
+
205
+ async function rows(session: Session, texts: DialectTexts, parameters: readonly FixedParameter[]): Promise<Readonly<Record<string, unknown>>[]> {
206
+ return (await runFixedStatement(session, texts[session.dialect], parameters)).map(record)
207
+ }
208
+
209
+ /** BIGINT comes back from Postgres as a string, INTEGER from SQLite as a number. */
210
+ function wholeNumber(value: unknown, what: string): number {
211
+ const parsed = typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value
212
+ if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed)) {
213
+ throw new QueryRefusedError('unexpected_row', `${what} is not a whole number`)
214
+ }
215
+ return parsed
216
+ }
217
+
218
+ /** BOOLEAN comes back from Postgres as a boolean, an INTEGER flag from SQLite as 0 or 1. */
219
+ function flag(value: unknown, what: string): boolean {
220
+ if (value === true || value === 1) {
221
+ return true
222
+ }
223
+ if (value === false || value === 0) {
224
+ return false
225
+ }
226
+ throw new QueryRefusedError('unexpected_row', `${what} is not a flag`)
227
+ }
228
+
229
+ function wakeOf(row: Readonly<Record<string, unknown>>): Wake {
230
+ const { id, job, reason, due_at: dueAt, attempt, dedupe, owned } = row
231
+ if (typeof id !== 'string' || typeof job !== 'string' || (dedupe !== null && typeof dedupe !== 'string')) {
232
+ throw new QueryRefusedError('unexpected_row', `${W} came back in another shape than its migration declares`)
233
+ }
234
+ const known = WAKE_REASONS.find((candidate) => candidate === reason)
235
+ if (known === undefined) {
236
+ throw new QueryRefusedError('unexpected_row', `${W}.reason is not a wake reason`)
237
+ }
238
+ return freeze({
239
+ id,
240
+ job,
241
+ reason: known,
242
+ dueAt: new Date(wholeNumber(dueAt, `${W}.due_at`)),
243
+ attempt: wholeNumber(attempt, `${W}.attempt`),
244
+ dedupe,
245
+ owned: flag(owned, `${W}.owned`),
246
+ })
247
+ }
248
+
249
+ function epochOf(value: unknown, what: string): number {
250
+ const time = value instanceof Date ? value.getTime() : Number.NaN
251
+ if (!Number.isSafeInteger(time)) {
252
+ throw new QueryRefusedError('invalid_argument', `${what} is a valid time`)
253
+ }
254
+ return time
255
+ }
256
+
257
+ function nonEmpty(value: unknown, what: string): string {
258
+ if (typeof value !== 'string' || value === '') {
259
+ throw new QueryRefusedError('invalid_argument', `${what} is a non-empty string`)
260
+ }
261
+ return value
262
+ }
263
+
264
+ function newWake(wake: NewWake): readonly FixedParameter[] {
265
+ const job = nonEmpty(wake.job, "a wake's job")
266
+ if (!WAKE_REASONS.some((reason) => reason === wake.reason)) {
267
+ throw new QueryRefusedError('invalid_argument', `a wake's reason is one of ${WAKE_REASONS.join(', ')}`)
268
+ }
269
+ const due = epochOf(wake.dueAt, "a wake's due time")
270
+ const dedupe = wake.dedupe === undefined ? null : nonEmpty(wake.dedupe, "a wake's dedupe key")
271
+ return [uuidv7(), job, String(due), wake.reason, dedupe]
272
+ }
273
+
274
+ /** Inserts the wake `newWake` checked, in `transaction`; refuses a key another job holds, which rolls it back. */
275
+ async function insert(transaction: Session, parameters: readonly FixedParameter[], job: string): Promise<Wake> {
276
+ const [row] = await rows(transaction, SQL_SCHEDULE, parameters)
277
+ if (row === undefined) {
278
+ throw new QueryRefusedError('invalid_argument', `the dedupe key of this wake of '${job}' is held by another job's wake`)
279
+ }
280
+ return wakeOf(row)
281
+ }
282
+
283
+ /**
284
+ * A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
285
+ * lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
286
+ */
287
+ export function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null {
288
+ if (wakes === undefined) {
289
+ return outcome === 'succeeded' ? freeze({ kind: 'completed' }) : null
290
+ }
291
+ if (wakes.kind === 'retry') {
292
+ if (outcome !== 'failed') {
293
+ throw new QueryRefusedError('invalid_argument', 'only a failed run retries its wakes')
294
+ }
295
+ epochOf(wakes.at, 'a retry')
296
+ return freeze({ kind: 'retry', at: wakes.at })
297
+ }
298
+ if (wakes.kind !== 'completed') {
299
+ throw new QueryRefusedError('invalid_argument', "a finish's wakes are completed or retried")
300
+ }
301
+ if (wakes.nextCron === undefined) {
302
+ return freeze({ kind: 'completed' })
303
+ }
304
+ nonEmpty(wakes.nextCron.expression, "a cron wake's expression")
305
+ 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 }) })
307
+ }
308
+
309
+ /** The runtime's projection of a change, in its transaction; nothing without one. */
310
+ function projectionOf(runtime: () => DataLayerRuntime): (transaction: Session) => Promise<void> {
311
+ return async (transaction) => {
312
+ await runtime().projectWakes?.(transaction)
313
+ }
314
+ }
315
+
316
+ /**
317
+ * The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
318
+ * fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
319
+ * runs the runtime's projection.
320
+ */
321
+ export function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection {
322
+ const project = projectionOf(runtime)
323
+ return async (transaction: Session, job: string, change: LeaseChange): Promise<void> => {
324
+ if (change.kind === 'acquired') {
325
+ await rows(transaction, SQL_OWN, [job])
326
+ }
327
+ if (change.kind === 'finished' && change.wakes !== null) {
328
+ if (change.wakes.kind === 'retry') {
329
+ await rows(transaction, SQL_RETRY, [job, String(change.wakes.at.getTime())])
330
+ } else {
331
+ await rows(transaction, SQL_CONSUME, [job])
332
+ 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)
335
+ }
336
+ }
337
+ }
338
+ if (change.kind === 'finished' || change.kind === 'reaped') {
339
+ await rows(transaction, SQL_DISOWN, [job])
340
+ }
341
+ await project(transaction)
342
+ }
343
+ }
344
+
345
+ /** A job's one claim wake: each attempt's first claim replaces it. */
346
+ const claimKey = (job: string): string => `claim:${job}`
347
+
348
+ /**
349
+ * Each attempt's earliest claim re-arm so far (`null`: none), by its fence: a later claim of the attempt, over another
350
+ * queue or `where`, never postpones it. A claim whose transaction rolled back may leave it early, which costs one run.
351
+ */
352
+ const attemptRearms = new WeakMap<LeaseFence, number | null>()
353
+
354
+ /**
355
+ * Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
356
+ * transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
357
+ * left; each later claim keeps the earliest re-arm of the attempt.
358
+ */
359
+ export async function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void> {
360
+ const candidate = dueAt === null ? null : epochOf(dueAt, 'a claim re-arm')
361
+ const earlier = attemptRearms.get(fence) ?? null
362
+ const due = earlier === null ? candidate : candidate === null ? earlier : Math.min(earlier, candidate)
363
+ attemptRearms.set(fence, due)
364
+ await rows(transaction, SQL_DROP_CLAIM, [fence.job, claimKey(fence.job)])
365
+ if (due !== null) {
366
+ await insert(transaction, newWake({ job: fence.job, reason: 'claim', dueAt: new Date(due), dedupe: claimKey(fence.job) }), fence.job)
367
+ }
368
+ await runtime.projectWakes?.(transaction)
369
+ }
370
+
371
+ /** 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, [])
374
+ const candidates = [wake, held].filter((value) => value !== null).map((value) => wholeNumber(value, 'the next wake'))
375
+ return { next: candidates.length === 0 ? null : Math.min(...candidates), now: () => wholeNumber(now, "the database's now") }
376
+ }
377
+
378
+ export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
379
+ const session = () => sessionOf(runtime())
380
+ const project = projectionOf(runtime)
381
+ return freeze({
382
+ async schedule(wake: NewWake, using?: Session): Promise<Wake> {
383
+ const parameters = newWake(wake)
384
+ return await (using ?? session()).transaction(async (transaction) => {
385
+ const scheduled = await insert(transaction, parameters, wake.job)
386
+ await project(transaction)
387
+ return scheduled
388
+ })
389
+ },
390
+
391
+ async pending(job: string): Promise<readonly Wake[]> {
392
+ return freeze((await rows(session(), SQL_PENDING, [job])).map(wakeOf))
393
+ },
394
+
395
+ async next(using?: Session): Promise<Date | null> {
396
+ const { next } = await nextAndNow(using ?? session())
397
+ return next === null ? null : new Date(next)
398
+ },
399
+
400
+ async untilNext(using?: Session): Promise<number | null> {
401
+ const { next, now } = await nextAndNow(using ?? session())
402
+ return next === null ? null : next - now()
403
+ },
404
+
405
+ async now(using?: Session): Promise<Date> {
406
+ const [{ now = null } = {}] = await rows(using ?? session(), SQL_CLOCK, [])
407
+ return new Date(wholeNumber(now, "the database's now"))
408
+ },
409
+
410
+ async expiredHolders(): Promise<readonly string[]> {
411
+ return freeze(
412
+ (await rows(session(), SQL_EXPIRED_HOLDERS, [])).map(({ job }) => {
413
+ if (typeof job !== 'string') {
414
+ throw new QueryRefusedError('unexpected_row', `${L} came back in another shape than its migration declares`)
415
+ }
416
+ return job
417
+ }),
418
+ )
419
+ },
420
+
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) => {
431
+ const removed = await rows(transaction, SQL_RECONCILE, [JSON.stringify(jobs)])
432
+ await project(transaction)
433
+ return removed.length
434
+ })
435
+ },
436
+
437
+ async hasten(ids: readonly string[]): Promise<number> {
438
+ refuseInProduction("the wakes store's hasten")
439
+ if (!Array.isArray(ids)) {
440
+ throw new QueryRefusedError('invalid_argument', 'the wakes to hasten are a list of wake ids')
441
+ }
442
+ const named = ids.map((id: unknown) => nonEmpty(id, 'a wake id'))
443
+ return await session().transaction(async (transaction) => {
444
+ const moved = await rows(transaction, SQL_HASTEN, [JSON.stringify(named)])
445
+ await project(transaction)
446
+ return moved.length
447
+ })
448
+ },
449
+ })
450
+ }
package/src/json.ts ADDED
@@ -0,0 +1,124 @@
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 (`->>`).
7
+
8
+ import { hasOwn, isArray, OBJECT_PROTOTYPE, ownDescriptor, ownNames, ownSymbols, parseList, prototypeOf } from './builtins'
9
+ import { QueryRefusedError } from './errors'
10
+
11
+ const stringify = JSON.stringify
12
+ const parse = JSON.parse
13
+ const isFinite = Number.isFinite
14
+
15
+ /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
16
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | { readonly [key: string]: JsonValue | undefined }
17
+
18
+ /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
19
+ export type JsonColumnValue = Exclude<JsonValue, null>
20
+
21
+ /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
22
+ export const MAX_JSON_DEPTH = 64
23
+
24
+ function refusal(where: string, detail: string): QueryRefusedError {
25
+ return new QueryRefusedError('invalid_value', `${where} takes a JSON value (${detail})`)
26
+ }
27
+
28
+ /** Half of a surrogate pair, which Postgres refuses in `jsonb` text and SQLite would store. */
29
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
30
+ const NUL = String.fromCharCode(0)
31
+
32
+ function text(value: string, where: string): string {
33
+ if (value.includes(NUL) || LONE_SURROGATE.test(value)) {
34
+ throw refusal(where, 'a string or key holds no NUL character and no lone surrogate')
35
+ }
36
+ return stringify(value)
37
+ }
38
+
39
+ function written(value: unknown, where: string, depth: number): string {
40
+ if (typeof value === 'string') {
41
+ return text(value, where)
42
+ }
43
+ if (value === null || typeof value === 'boolean') {
44
+ return stringify(value)
45
+ }
46
+ if (typeof value === 'number') {
47
+ if (!isFinite(value)) {
48
+ throw refusal(where, 'a number is finite')
49
+ }
50
+ return stringify(value)
51
+ }
52
+ if (typeof value !== 'object') {
53
+ throw refusal(where, `${typeof value} is not JSON`)
54
+ }
55
+ if (depth >= MAX_JSON_DEPTH) {
56
+ throw refusal(where, `nested at most ${MAX_JSON_DEPTH} deep, and never containing itself`)
57
+ }
58
+ if (isArray(value)) {
59
+ const items = parseList(value, (item) => {
60
+ if (item === undefined) {
61
+ throw refusal(where, 'an array holds no undefined')
62
+ }
63
+ return written(item, where, depth + 1)
64
+ })
65
+ if (items === undefined) {
66
+ throw refusal(where, 'an array is a plain array without holes or accessors')
67
+ }
68
+ let serialized = '['
69
+ for (let index = 0; index < items.length; index++) {
70
+ serialized += `${index === 0 ? '' : ','}${items[index] ?? ''}`
71
+ }
72
+ return `${serialized}]`
73
+ }
74
+ const prototype: unknown = prototypeOf(value)
75
+ if (prototype !== OBJECT_PROTOTYPE && prototype !== null) {
76
+ throw refusal(where, 'an object is a plain object, not an instance of a class such as a Date or a Map')
77
+ }
78
+ if (ownSymbols(value).length > 0) {
79
+ throw refusal(where, 'an object has string keys only')
80
+ }
81
+ const keys = ownNames(value)
82
+ let serialized = '{'
83
+ let first = true
84
+ for (let index = 0; index < keys.length; index++) {
85
+ const key = keys[index] ?? ''
86
+ const descriptor = ownDescriptor(value, key)
87
+ if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
88
+ throw refusal(where, `${key} is an accessor`)
89
+ }
90
+ const member: unknown = descriptor.value
91
+ if (member === undefined) {
92
+ continue
93
+ }
94
+ serialized += `${first ? '' : ','}${text(key, where)}:${written(member, where, depth + 1)}`
95
+ first = false
96
+ }
97
+ return `${serialized}}`
98
+ }
99
+
100
+ /**
101
+ * A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
102
+ * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
103
+ */
104
+ export function jsonInput(value: unknown, where: string): string {
105
+ return written(value, where, 0)
106
+ }
107
+
108
+ /**
109
+ * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
110
+ * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
111
+ */
112
+ export function sqliteJson(value: unknown, where: string): unknown {
113
+ if (typeof value === 'number') {
114
+ return value
115
+ }
116
+ if (typeof value === 'string') {
117
+ try {
118
+ return parse(value)
119
+ } catch {
120
+ // Fall through: the text is not JSON, which no write of the layer stores.
121
+ }
122
+ }
123
+ throw new QueryRefusedError('unexpected_row', `${where} came back as something other than JSON text, the form a JSON column is stored in on SQLite`)
124
+ }
package/src/links.ts CHANGED
@@ -57,5 +57,12 @@ export function linkValues(table: string, links: readonly Container[], grant: Re
57
57
  }
58
58
 
59
59
  export function linksPredicate(table: string, values: readonly LinkValue[]): OperationNode {
60
- return allOf(values.map(({ link, value }) => equals(table, link.column, value)))
60
+ const terms: OperationNode[] = []
61
+ for (let index = 0; index < values.length; index++) {
62
+ const entry = values[index]
63
+ if (entry !== undefined) {
64
+ terms[terms.length] = equals(table, entry.link.column, entry.value)
65
+ }
66
+ }
67
+ return allOf(terms)
61
68
  }