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

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 (63) hide show
  1. package/package.json +34 -3
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/capability.ts +5 -0
  5. package/src/codegen-sqlite.ts +154 -0
  6. package/src/codegen.ts +59 -9
  7. package/src/database.ts +227 -61
  8. package/src/errors.ts +2 -2
  9. package/src/file-columns.ts +4 -1
  10. package/src/framework-tables.ts +28 -8
  11. package/src/framework.ts +14 -5
  12. package/src/guard.ts +8 -0
  13. package/src/index.ts +9 -1
  14. package/src/job-leases.ts +210 -54
  15. package/src/job-wakes.ts +450 -0
  16. package/src/links.ts +8 -1
  17. package/src/migrations-sqlite.ts +163 -0
  18. package/src/migrations.ts +25 -0
  19. package/src/nodes.ts +64 -9
  20. package/src/orm-types.ts +2 -2
  21. package/src/orm.ts +68 -35
  22. package/src/policy.ts +8 -2
  23. package/src/postgres.ts +26 -0
  24. package/src/registry.ts +11 -2
  25. package/src/sql.ts +216 -473
  26. package/src/sqlite-bun.ts +122 -0
  27. package/src/sqlite-migrate.ts +242 -0
  28. package/src/sqlite.ts +224 -0
  29. package/src/store.ts +362 -93
  30. package/src/stored-files.ts +188 -52
  31. package/src/tables.ts +16 -0
  32. package/src/temporal.ts +115 -9
  33. package/src/testing-shared.ts +733 -0
  34. package/src/testing-sqlite.ts +513 -0
  35. package/src/testing.ts +169 -482
  36. package/types/src/application-rows.d.ts +58 -0
  37. package/types/src/capability.d.ts +5 -0
  38. package/types/src/codegen-sqlite.d.ts +6 -0
  39. package/types/src/codegen.d.ts +30 -0
  40. package/types/src/database.d.ts +81 -20
  41. package/types/src/errors.d.ts +2 -2
  42. package/types/src/framework.d.ts +11 -5
  43. package/types/src/index.d.ts +1 -1
  44. package/types/src/job-leases.d.ts +32 -4
  45. package/types/src/job-wakes.d.ts +101 -0
  46. package/types/src/migrations-sqlite.d.ts +4 -0
  47. package/types/src/migrations.d.ts +1 -0
  48. package/types/src/nodes.d.ts +13 -2
  49. package/types/src/orm-types.d.ts +2 -2
  50. package/types/src/policy.d.ts +4 -0
  51. package/types/src/postgres.d.ts +12 -0
  52. package/types/src/registry.d.ts +10 -2
  53. package/types/src/sql.d.ts +29 -21
  54. package/types/src/sqlite-bun.d.ts +13 -0
  55. package/types/src/sqlite-migrate.d.ts +28 -0
  56. package/types/src/sqlite.d.ts +24 -0
  57. package/types/src/store.d.ts +26 -9
  58. package/types/src/stored-files.d.ts +6 -2
  59. package/types/src/tables.d.ts +10 -0
  60. package/types/src/temporal.d.ts +21 -0
  61. package/types/src/testing-shared.d.ts +201 -0
  62. package/types/src/testing-sqlite.d.ts +22 -0
  63. package/types/src/testing.d.ts +2 -93
package/src/job-leases.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  // The framework's side of `fabrika_job_leases` (`@fabrika/db/migrations`): the lease a job run takes, the generation
2
2
  // and deadline that fence every write of the attempt holding it, and the state of the job's last run; and
3
- // `fabrika_job_kicks`, a kick's pending run. Only
4
- // `@fabrika/app`'s job runner reaches it, through `frameworkTablesOf`. Every time is the database's own clock: two
5
- // containers whose clocks disagree still agree on who holds a lease and when it expires.
3
+ // `fabrika_job_kicks`, a kick's pending run. Each statement that changes a lease runs its projection (the wakes,
4
+ // `job-wakes.ts`) in its own transaction. Only `@fabrika/app`'s job runner reaches it, through `frameworkTablesOf`.
5
+ // Every time is the database's own clock: two containers whose clocks disagree still agree on who holds a lease and
6
+ // when it expires.
6
7
 
7
8
  import type { LeaseFence } from './capability'
8
- import { runFixedStatement, type Session, sessionOf } from './database'
9
+ import { runFixedStatement, type Session, sessionOf, type SqlDialect } from './database'
9
10
  import { DatabaseError, LeaseLostError, QueryRefusedError } from './errors'
11
+ import { type FinishWakes, finishWakes } from './job-wakes'
10
12
  import { JOB_KICKS_TABLE, JOB_LEASES_TABLE } from './migrations'
13
+ import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
11
14
  import type { DataLayerRuntime } from './store'
12
15
 
13
16
  export type JobOutcome = 'succeeded' | 'failed'
@@ -60,8 +63,11 @@ export interface JobLeases {
60
63
  * now on. `null` when `fence` no longer holds it.
61
64
  */
62
65
  renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null>
63
- /** Frees the lease and records the run's outcome and duration; `false` when `fence` no longer held it. */
64
- finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean>
66
+ /**
67
+ * Frees the lease and records the run's outcome and duration, and in the same transaction applies `wakes` to the wakes
68
+ * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
69
+ */
70
+ finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>
65
71
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
66
72
  markPending(job: string): Promise<void>
67
73
  /**
@@ -82,69 +88,180 @@ export interface JobLeases {
82
88
  state(job: string): Promise<JobLeaseState | null>
83
89
  }
84
90
 
91
+ /**
92
+ * What a lease statement changed: a crashed holder reaped, a lease taken or handed on, or a run finished with what its
93
+ * wakes become (`null` leaves them).
94
+ */
95
+ export type LeaseChange =
96
+ | { readonly kind: 'reaped' | 'acquired' | 'renewed' }
97
+ | { readonly kind: 'finished'; readonly wakes: FinishWakes | null }
98
+
99
+ /**
100
+ * Runs in the transaction of every lease statement that changed the lease, so a table that follows the lease (the
101
+ * wakes, `job-wakes.ts`) commits with it or not at all. A statement that changed nothing, a lost lease's, runs none.
102
+ */
103
+ export type LeaseProjection = (transaction: Session, job: string, change: LeaseChange) => Promise<void>
104
+
105
+ /** One framework statement in each dialect's text; a session runs the text of its own. */
106
+ export type DialectTexts = Readonly<Record<SqlDialect, string>>
107
+
108
+ /** SQLite's clock, as a stored timestamp: ISO text, so a comparison of two is a text comparison. */
109
+ export const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
110
+
111
+ /** SQLite's clock moved by `ms`, an SQL expression of milliseconds (negative is earlier). */
112
+ export function sqliteNowPlus(ms: string): string {
113
+ return `strftime('${SQLITE_NOW_FORMAT}', 'now', printf('%+.3f seconds', (${ms}) / 1000.0))`
114
+ }
115
+
85
116
  const T = JOB_LEASES_TABLE
86
117
  const MS = `* interval '1 millisecond'`
118
+ const N = SQLITE_NOW
119
+ const SQLITE_RUN_MS = `cast(round((julianday('now') - julianday(last_started_at)) * 86400000) as integer)`
87
120
  const QUERY_CANCELED = '57014'
88
121
  const IDLE_TIMEOUT = '25P03'
89
122
 
90
123
  const STATE_COLUMNS =
91
124
  'generation, holder, expires_at, attempt_deadline, first_seen_at, last_started_at, last_finished_at, last_status, last_succeeded_at, last_duration_ms, last_missed_reported_at'
92
125
 
93
- const SQL_NOW = 'select now() as now'
126
+ const SQL_NOW: DialectTexts = {
127
+ postgres: 'select now() as now',
128
+ sqlite: `select ${N} as now`,
129
+ }
94
130
 
95
- const SQL_REGISTER = `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at)
96
- values ($1, 0, null, now(), now(), now()) on conflict (job) do nothing`
131
+ const SQL_REGISTER: DialectTexts = {
132
+ postgres: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at)
133
+ values ($1, 0, null, now(), now(), now()) on conflict (job) do nothing`,
134
+ sqlite: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at)
135
+ values (?1, 0, null, ${N}, ${N}, ${N}) on conflict (job) do nothing`,
136
+ }
97
137
 
98
- const SQL_REAP = `update ${T} set holder = null, last_status = 'failed', last_finished_at = now(),
138
+ const SQL_REAP: DialectTexts = {
139
+ postgres: `update ${T} set holder = null, last_status = 'failed', last_finished_at = now(),
99
140
  last_duration_ms = (extract(epoch from now() - last_started_at) * 1000)::int
100
- where job = $1 and holder is not null and expires_at <= now() returning job`
141
+ where job = $1 and holder is not null and expires_at <= now() returning job`,
142
+ sqlite: `update ${T} set holder = null, last_status = 'failed', last_finished_at = ${N},
143
+ last_duration_ms = ${SQLITE_RUN_MS}
144
+ where job = ?1 and holder is not null and expires_at <= ${N} returning job`,
145
+ }
101
146
 
102
- const SQL_ACQUIRE = `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at, last_started_at)
147
+ const SQL_ACQUIRE: DialectTexts = {
148
+ postgres: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at, last_started_at)
103
149
  values ($1, 1, $2, now() + $3::bigint ${MS}, now() + $4::bigint ${MS}, now(), now())
104
150
  on conflict (job) do update set generation = ${T}.generation + 1, holder = excluded.holder, expires_at = excluded.expires_at,
105
151
  attempt_deadline = excluded.attempt_deadline, last_started_at = excluded.last_started_at
106
- where ${T}.holder is null returning generation`
152
+ where ${T}.holder is null returning generation`,
153
+ sqlite: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at, last_started_at)
154
+ values (?1, 1, ?2, ${sqliteNowPlus('?3')}, ${sqliteNowPlus('?4')}, ${N}, ${N})
155
+ on conflict (job) do update set generation = ${T}.generation + 1, holder = excluded.holder, expires_at = excluded.expires_at,
156
+ attempt_deadline = excluded.attempt_deadline, last_started_at = excluded.last_started_at
157
+ where ${T}.holder is null returning generation`,
158
+ }
107
159
 
108
- const SQL_RENEW = `update ${T} set generation = generation + 1, holder = $4, expires_at = now() + $5::bigint ${MS},
160
+ const SQL_RENEW: DialectTexts = {
161
+ postgres: `update ${T} set generation = generation + 1, holder = $4, expires_at = now() + $5::bigint ${MS},
109
162
  attempt_deadline = now() + $6::bigint ${MS}
110
- where job = $1 and generation = $2 and holder = $3 and expires_at > now() returning generation`
163
+ where job = $1 and generation = $2 and holder = $3 and expires_at > now() returning generation`,
164
+ sqlite: `update ${T} set generation = generation + 1, holder = ?4, expires_at = ${sqliteNowPlus('?5')},
165
+ attempt_deadline = ${sqliteNowPlus('?6')}
166
+ where job = ?1 and generation = ?2 and holder = ?3 and expires_at > ${N} returning generation`,
167
+ }
111
168
 
112
- const SQL_FINISH = `update ${T} set holder = null, last_finished_at = now(), last_status = $4,
169
+ const SQL_FINISH: DialectTexts = {
170
+ postgres: `update ${T} set holder = null, last_finished_at = now(), last_status = $4,
113
171
  last_duration_ms = (extract(epoch from now() - last_started_at) * 1000)::int,
114
172
  last_succeeded_at = case when $4 = 'succeeded' then now() else last_succeeded_at end
115
- where job = $1 and generation = $2 and holder = $3 returning job`
173
+ where job = $1 and generation = $2 and holder = $3 returning job`,
174
+ sqlite: `update ${T} set holder = null, last_finished_at = ${N}, last_status = ?4,
175
+ last_duration_ms = ${SQLITE_RUN_MS},
176
+ last_succeeded_at = case when ?4 = 'succeeded' then ${N} else last_succeeded_at end
177
+ where job = ?1 and generation = ?2 and holder = ?3 returning job`,
178
+ }
116
179
 
117
- // A free lease whose row no transaction holds (`skip locked`): an attempt's fence holds it `for share` while it writes.
118
- const SQL_TRY_ACQUIRE = `with free as (select job from ${T} where job = $1 and holder is null for update skip locked)
180
+ const SQL_TRY_ACQUIRE: DialectTexts = {
181
+ // A free lease whose row no transaction holds (`skip locked`): an attempt's fence holds it `for share` while it writes.
182
+ postgres: `with free as (select job from ${T} where job = $1 and holder is null for update skip locked)
119
183
  update ${T} set generation = ${T}.generation + 1, holder = $2, expires_at = now() + $3::bigint ${MS},
120
184
  attempt_deadline = now() + $4::bigint ${MS}, last_started_at = now()
121
- from free where ${T}.job = free.job returning ${T}.generation`
185
+ from free where ${T}.job = free.job returning ${T}.generation`,
186
+ // No lock to skip: while an attempt's fenced transaction is open, the Durable Object serves no kick.
187
+ sqlite: `update ${T} set generation = generation + 1, holder = ?2, expires_at = ${sqliteNowPlus('?3')},
188
+ attempt_deadline = ${sqliteNowPlus('?4')}, last_started_at = ${N}
189
+ where job = ?1 and holder is null returning generation`,
190
+ }
122
191
 
123
192
  const K = JOB_KICKS_TABLE
124
193
 
125
- const SQL_MARK_PENDING = `insert into ${K} (job, pending) values ($1, true) on conflict (job) do update set pending = true where ${K}.pending = false`
194
+ const SQL_MARK_PENDING: DialectTexts = {
195
+ postgres: `insert into ${K} (job, pending) values ($1, true) on conflict (job) do update set pending = true where ${K}.pending = false`,
196
+ sqlite: `insert into ${K} (job, pending) values (?1, 1) on conflict (job) do update set pending = 1 where ${K}.pending = 0`,
197
+ }
126
198
 
127
- const SQL_TAKE_PENDING = `update ${K} set pending = false where job = $1 and pending returning job`
199
+ const SQL_TAKE_PENDING: DialectTexts = {
200
+ postgres: `update ${K} set pending = false where job = $1 and pending returning job`,
201
+ sqlite: `update ${K} set pending = 0 where job = ?1 and pending = 1 returning job`,
202
+ }
128
203
 
129
- const SQL_CLAIM_OVERDUE = `update ${T} set last_missed_reported_at = now()
204
+ const SQL_CLAIM_OVERDUE: DialectTexts = {
205
+ postgres: `update ${T} set last_missed_reported_at = now()
130
206
  where job = $1 and coalesce(last_succeeded_at, first_seen_at) < now() - 2 * $2::bigint ${MS}
131
207
  and (last_missed_reported_at is null or last_missed_reported_at <= now() - $2::bigint ${MS})
132
- returning last_succeeded_at, first_seen_at`
208
+ returning last_succeeded_at, first_seen_at`,
209
+ sqlite: `update ${T} set last_missed_reported_at = ${N}
210
+ where job = ?1 and coalesce(last_succeeded_at, first_seen_at) < ${sqliteNowPlus('-2 * ?2')}
211
+ and (last_missed_reported_at is null or last_missed_reported_at <= ${sqliteNowPlus('-?2')})
212
+ returning last_succeeded_at, first_seen_at`,
213
+ }
214
+
215
+ const SQL_STILL_HELD: DialectTexts = {
216
+ postgres: `select job from ${T} where job = $1 and generation = $2 and holder = $3 and attempt_deadline > clock_timestamp()`,
217
+ sqlite: `select job from ${T} where job = ?1 and generation = ?2 and holder = ?3 and attempt_deadline > ${N}`,
218
+ }
133
219
 
134
- // Inside a mutation's transaction, so `clock_timestamp()`: `now()` is when the transaction began.
135
- const SQL_FENCE = `select pg_backend_pid() as pid, transaction_timestamp()::text as began,
220
+ const SQL_FENCE: DialectTexts = {
221
+ // Inside a mutation's transaction, so `clock_timestamp()`: `now()` is when the transaction began.
222
+ postgres: `select pg_backend_pid() as pid, transaction_timestamp()::text as began,
136
223
  greatest(1, ceil(extract(epoch from attempt_deadline - clock_timestamp()) * 1000))::int as remaining_ms
137
- from ${T} where job = $1 and generation = $2 and holder = $3 and attempt_deadline > clock_timestamp() for share`
224
+ from ${T} where job = $1 and generation = $2 and holder = $3 and attempt_deadline > clock_timestamp() for share`,
225
+ // No lock: while the transaction is open the Durable Object serves no other event, so no takeover runs before it ends.
226
+ sqlite: SQL_STILL_HELD.sqlite,
227
+ }
138
228
 
139
- // The attempt's remaining time bounds a statement and an idle wait alike: either past the deadline ends the transaction.
229
+ // Postgres only. The attempt's remaining time bounds a statement and an idle wait alike: either past the deadline ends it.
140
230
  const SQL_TIMEOUTS = `select set_config('statement_timeout', $1, true), set_config('idle_in_transaction_session_timeout', $1, true)`
141
231
 
142
- const SQL_STILL_HELD = `select job from ${T} where job = $1 and generation = $2 and holder = $3 and attempt_deadline > clock_timestamp()`
143
-
144
- // Only the backend still in the transaction the fence opened: a pid the pool reused for other work is left alone.
232
+ // Postgres only. Only the backend still in the transaction the fence opened: a pid the pool reused is left alone.
145
233
  const SQL_CANCEL = `select pg_cancel_backend(pid) from pg_stat_activity where pid = $1 and xact_start = $2::timestamptz`
146
234
 
147
- const SQL_STATE = `select now() as now, ${STATE_COLUMNS} from ${T} where job = $1`
235
+ const SQL_STATE: DialectTexts = {
236
+ postgres: `select now() as now, ${STATE_COLUMNS} from ${T} where job = $1`,
237
+ sqlite: `select ${N} as now, ${STATE_COLUMNS} from ${T} where job = ?1`,
238
+ }
239
+
240
+ /** The columns that hold a time; SQLite answers each as ISO text, which the row's entry reads as a `Date`. */
241
+ const TIMESTAMP_COLUMNS: ReadonlySet<string> = new Set([
242
+ 'now',
243
+ 'expires_at',
244
+ 'attempt_deadline',
245
+ 'first_seen_at',
246
+ 'last_started_at',
247
+ 'last_finished_at',
248
+ 'last_succeeded_at',
249
+ 'last_missed_reported_at',
250
+ ])
251
+
252
+ const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
253
+
254
+ /** A stored SQLite timestamp (`SQLITE_NOW_FORMAT`) as a `Date`, or `null`; anything else is refused. */
255
+ export function sqliteTimestamp(value: unknown, what: string): Date | null {
256
+ if (value === null) {
257
+ return null
258
+ }
259
+ const parsed = typeof value === 'string' && ISO_TIMESTAMP.test(value) ? new Date(value) : undefined
260
+ if (parsed === undefined || Number.isNaN(parsed.getTime())) {
261
+ throw new QueryRefusedError('unexpected_row', `${what} is not a stored timestamp`)
262
+ }
263
+ return parsed
264
+ }
148
265
 
149
266
  function record(row: unknown): Readonly<Record<string, unknown>> {
150
267
  if (typeof row !== 'object' || row === null) {
@@ -153,8 +270,19 @@ function record(row: unknown): Readonly<Record<string, unknown>> {
153
270
  return Object.fromEntries(Object.entries(row))
154
271
  }
155
272
 
156
- async function rows(session: Session, text: string, parameters: readonly (string | number | null)[]): Promise<Readonly<Record<string, unknown>>[]> {
157
- return (await runFixedStatement(session, text, parameters)).map(record)
273
+ async function rows(
274
+ session: Session,
275
+ texts: DialectTexts,
276
+ parameters: readonly (string | number | null)[],
277
+ ): Promise<Readonly<Record<string, unknown>>[]> {
278
+ const found = (await runFixedStatement(session, texts[session.dialect], parameters)).map(record)
279
+ return session.dialect === 'sqlite' ? found.map(sqliteRow) : found
280
+ }
281
+
282
+ function sqliteRow(row: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>> {
283
+ return Object.fromEntries(
284
+ Object.entries(row).map(([name, value]) => [name, TIMESTAMP_COLUMNS.has(name) ? sqliteTimestamp(value, `${T}.${name}`) : value]),
285
+ )
158
286
  }
159
287
 
160
288
  function integer(row: Readonly<Record<string, unknown>>, name: string): number {
@@ -254,7 +382,10 @@ function refuseEnded(fence: LeaseFence): void {
254
382
  }
255
383
  }
256
384
 
257
- const SQL_CLOCK = 'select clock_timestamp() as now'
385
+ const SQL_CLOCK: DialectTexts = {
386
+ postgres: 'select clock_timestamp() as now',
387
+ sqlite: `select ${N} as now`,
388
+ }
258
389
 
259
390
  /**
260
391
  * The database's clock inside `session`'s transaction: a queue claim compares and moves `due` by it, so no process
@@ -275,6 +406,7 @@ const params = (fence: LeaseFence): (string | number)[] => [fence.job, fence.gen
275
406
  * stays locked `for share` until the commit (a takeover or a renewal waits), and every statement is bounded by the
276
407
  * attempt's remaining time. After it, just before the commit: the attempt still holds the lease within its deadline.
277
408
  * Otherwise the transaction rolls back with `LeaseLostError`; so does a statement the deadline or the runner cancelled.
409
+ * On SQLite only the two checks run: no other event reaches the Durable Object while the transaction is open.
278
410
  */
279
411
  export async function fencedTransaction<T>(session: Session, fence: LeaseFence, work: (transaction: Session) => Promise<T>): Promise<T> {
280
412
  refuseEnded(fence)
@@ -285,12 +417,19 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
285
417
  if (held === undefined) {
286
418
  throw lost(fence)
287
419
  }
288
- backend = { pid: integer(held, 'pid'), began: text(held, 'began') }
289
- const running = inFlight.get(fence) ?? new Set<Backend>()
290
- running.add(backend)
291
- inFlight.set(fence, running)
420
+ // SQLite has no backend to cancel and no statement timeout: the check before the commit refuses a late attempt,
421
+ // and a Durable Object resets a transaction that runs past its own limit.
422
+ const postgres = transaction.dialect === 'postgres'
423
+ if (postgres) {
424
+ backend = { pid: integer(held, 'pid'), began: text(held, 'began') }
425
+ const running = inFlight.get(fence) ?? new Set<Backend>()
426
+ running.add(backend)
427
+ inFlight.set(fence, running)
428
+ }
292
429
  refuseEnded(fence)
293
- await rows(transaction, SQL_TIMEOUTS, [String(integer(held, 'remaining_ms'))])
430
+ if (postgres) {
431
+ await runFixedStatement(transaction, SQL_TIMEOUTS, [String(integer(held, 'remaining_ms'))])
432
+ }
294
433
  const result = await work(transaction)
295
434
  refuseEnded(fence)
296
435
  if ((await rows(transaction, SQL_STILL_HELD, params(fence))).length === 0) {
@@ -310,8 +449,17 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
310
449
  }
311
450
  }
312
451
 
313
- export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
452
+ export function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases {
314
453
  const session = () => sessionOf(runtime())
454
+ /** A lease statement and, when it changed the lease, its projection, in one transaction. */
455
+ const changing = (texts: DialectTexts, parameters: readonly (string | number)[], job: string, change: LeaseChange) =>
456
+ session().transaction(async (transaction) => {
457
+ const found = await rows(transaction, texts, parameters)
458
+ if (found.length > 0) {
459
+ await project(transaction, job, change)
460
+ }
461
+ return found
462
+ })
315
463
  return Object.freeze({
316
464
  async now(): Promise<Date> {
317
465
  const [row] = await rows(session(), SQL_NOW, [])
@@ -323,30 +471,38 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
323
471
  },
324
472
 
325
473
  async reapCrashed(job: string): Promise<boolean> {
326
- return (await rows(session(), SQL_REAP, [job])).length > 0
474
+ return (await changing(SQL_REAP, [job], job, { kind: 'reaped' })).length > 0
327
475
  },
328
476
 
329
477
  async acquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
330
- const [row] = await rows(session(), SQL_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')])
478
+ const [row] = await changing(SQL_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')], job, {
479
+ kind: 'acquired',
480
+ })
331
481
  return fenceOf(job, holder, row)
332
482
  },
333
483
 
334
484
  async renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
335
- const [row] = await rows(session(), SQL_RENEW, [
336
- ...params(fence),
337
- holder,
338
- milliseconds(leaseMs, 'a lease'),
339
- milliseconds(attemptMs, 'an attempt'),
340
- ])
485
+ const [row] = await changing(
486
+ SQL_RENEW,
487
+ [...params(fence), holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
488
+ fence.job,
489
+ { kind: 'renewed' },
490
+ )
341
491
  return fenceOf(fence.job, holder, row)
342
492
  },
343
493
 
344
- async finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean> {
345
- return (await rows(session(), SQL_FINISH, [...params(fence), outcome])).length > 0
494
+ async finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean> {
495
+ const change: LeaseChange = { kind: 'finished', wakes: finishWakes(outcome, wakes) }
496
+ return (await changing(SQL_FINISH, [...params(fence), outcome], fence.job, change)).length > 0
346
497
  },
347
498
 
348
499
  async tryAcquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
349
- const [row] = await rows(session(), SQL_TRY_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')])
500
+ const [row] = await changing(
501
+ SQL_TRY_ACQUIRE,
502
+ [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
503
+ job,
504
+ { kind: 'acquired' },
505
+ )
350
506
  return fenceOf(job, holder, row)
351
507
  },
352
508
 
@@ -368,11 +524,11 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
368
524
  async cancelInFlight(fence: LeaseFence): Promise<void> {
369
525
  ended.add(fence)
370
526
  // The transaction rolls back and gives its connection back now, even while its work waits on something else;
371
- // a statement still running is cancelled, so the ROLLBACK queued behind it runs.
527
+ // a statement still running is cancelled, so the ROLLBACK queued behind it runs. SQLite records no backend.
372
528
  stopOf(fence).abort(lost(fence))
373
529
  const running = [...(inFlight.get(fence) ?? [])]
374
530
  for (const backend of running) {
375
- await rows(session(), SQL_CANCEL, [backend.pid, backend.began])
531
+ await runFixedStatement(session(), SQL_CANCEL, [backend.pid, backend.began])
376
532
  }
377
533
  },
378
534