@fabrika/db 0.9.0-dev.1 → 0.9.0-dev.10

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 (78) hide show
  1. package/package.json +44 -12
  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 +191 -0
  6. package/src/codegen.ts +170 -28
  7. package/src/database.ts +227 -61
  8. package/src/description.ts +34 -8
  9. package/src/errors.ts +6 -4
  10. package/src/file-columns.ts +36 -9
  11. package/src/framework-tables.ts +28 -8
  12. package/src/framework.ts +14 -5
  13. package/src/guard.ts +8 -0
  14. package/src/index.ts +10 -1
  15. package/src/job-leases.ts +210 -54
  16. package/src/job-wakes.ts +450 -0
  17. package/src/json.ts +124 -0
  18. package/src/links.ts +8 -1
  19. package/src/migrations-sqlite.ts +163 -0
  20. package/src/migrations.ts +25 -0
  21. package/src/nodes.ts +64 -9
  22. package/src/orm-types.ts +5 -5
  23. package/src/orm.ts +94 -37
  24. package/src/policy.ts +17 -2
  25. package/src/postgres.ts +26 -0
  26. package/src/registry.ts +11 -2
  27. package/src/sql.ts +230 -477
  28. package/src/sqlite-bun.ts +149 -0
  29. package/src/sqlite-migrate.ts +242 -0
  30. package/src/sqlite.ts +224 -0
  31. package/src/store.ts +385 -103
  32. package/src/stored-files.ts +188 -52
  33. package/src/tables.ts +16 -0
  34. package/src/temporal.ts +122 -9
  35. package/src/testing-shared.ts +878 -0
  36. package/src/testing-sqlite.ts +570 -0
  37. package/src/testing.ts +255 -482
  38. package/types/src/admissions.d.ts +21 -0
  39. package/types/src/application-rows.d.ts +58 -0
  40. package/types/src/builtins.d.ts +42 -0
  41. package/types/src/capability.d.ts +119 -0
  42. package/types/src/codegen-sqlite.d.ts +13 -0
  43. package/types/src/codegen.d.ts +113 -0
  44. package/types/src/database.d.ts +185 -0
  45. package/types/src/description.d.ts +124 -0
  46. package/types/src/errors.d.ts +98 -0
  47. package/types/src/file-columns.d.ts +39 -0
  48. package/types/src/file-references.d.ts +27 -0
  49. package/types/src/framework-tables.d.ts +59 -0
  50. package/types/src/framework.d.ts +38 -0
  51. package/types/src/guard.d.ts +23 -0
  52. package/types/src/identifier.d.ts +4 -0
  53. package/types/src/index.d.ts +11 -0
  54. package/types/src/job-leases.d.ts +112 -0
  55. package/types/src/job-wakes.d.ts +101 -0
  56. package/types/src/json.d.ts +18 -0
  57. package/types/src/links.d.ts +13 -0
  58. package/types/src/migrations-sqlite.d.ts +4 -0
  59. package/types/src/migrations.d.ts +26 -0
  60. package/types/src/nodes.d.ts +73 -0
  61. package/types/src/orm-types.d.ts +638 -0
  62. package/types/src/orm.d.ts +82 -0
  63. package/types/src/policy.d.ts +358 -0
  64. package/types/src/postgres.d.ts +12 -0
  65. package/types/src/production.d.ts +5 -0
  66. package/types/src/registry.d.ts +43 -0
  67. package/types/src/sql.d.ts +67 -0
  68. package/types/src/sqlite-bun.d.ts +21 -0
  69. package/types/src/sqlite-migrate.d.ts +28 -0
  70. package/types/src/sqlite.d.ts +24 -0
  71. package/types/src/store.d.ts +351 -0
  72. package/types/src/stored-files.d.ts +102 -0
  73. package/types/src/tables.d.ts +21 -0
  74. package/types/src/temporal.d.ts +36 -0
  75. package/types/src/testing-shared.d.ts +250 -0
  76. package/types/src/testing-sqlite.d.ts +22 -0
  77. package/types/src/testing.d.ts +35 -0
  78. package/types/src/vocabulary-tables.d.ts +225 -0
@@ -3,7 +3,7 @@
3
3
  // and claims, locks and stamps the file in the write's own transaction. The file's row is `fabrika_files`
4
4
  // (`stored-files.ts`); the column is a foreign key to it, so a file some row references is never deleted.
5
5
 
6
- import { defineValue, ownDescriptor, ownKeys } from './builtins'
6
+ import { defineValue, hasOwn, inSet, type NameSet, nameSet, ownDescriptor, ownKeys } from './builtins'
7
7
  import { runFixedStatement, type Session } from './database'
8
8
  import type { Primitive } from './description'
9
9
  import { NotFoundError, QueryRefusedError } from './errors'
@@ -24,17 +24,41 @@ export interface FileBinding {
24
24
  scans(kind: string): boolean
25
25
  }
26
26
 
27
- /** Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's read action. */
28
- function readsFile(model: TableModel, column: string, action: string): boolean {
29
- const own = Object.hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
30
- return own === undefined ? model.actions.read.includes(action) : own === action
27
+ /**
28
+ * Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's
29
+ * read action, or a table read action among `held`, the actions a job holds over the whole application. A column with
30
+ * its own read action is answered only under that action (`visibleFor`), so `held` never widens it.
31
+ */
32
+ function readsFile(model: TableModel, column: string, action: string, held: NameSet): boolean {
33
+ const own = hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
34
+ if (own !== undefined) {
35
+ return own === action
36
+ }
37
+ const reads = model.actions.read
38
+ for (let index = 0; index < reads.length; index++) {
39
+ const read = reads[index]
40
+ if (read === action || inSet(held, read)) {
41
+ return true
42
+ }
43
+ }
44
+ return false
31
45
  }
32
46
 
47
+ const NONE_HELD: NameSet = nameSet([])
48
+
33
49
  /**
34
50
  * Puts a file reference in each file column of `rows`, read with `action` in `session`: one statement loads every
35
- * file's metadata. Without a binding (a store's own runner) the columns keep their ids.
51
+ * file's metadata. Without a binding (a store's own runner) the columns keep their ids. `held` (a queue claim's) adds
52
+ * the actions the site holds over the whole application: a reference is readable when one of them reads the table.
36
53
  */
37
- export async function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], action: string): Promise<R[]> {
54
+ export async function answerFiles<R>(
55
+ model: TableModel,
56
+ binding: FileBinding | undefined,
57
+ session: Session,
58
+ rows: R[],
59
+ action: string,
60
+ held: NameSet = NONE_HELD,
61
+ ): Promise<R[]> {
38
62
  const columns = ownKeys(model.files)
39
63
  if (binding === undefined || columns.length === 0 || rows.length === 0) {
40
64
  return rows
@@ -62,7 +86,7 @@ export async function answerFiles<R>(model: TableModel, binding: FileBinding | u
62
86
  if (meta === undefined) {
63
87
  throw new QueryRefusedError('unexpected_row', `${model.name}.${column} references a file that is not stored`)
64
88
  }
65
- defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action)))
89
+ defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action, held)))
66
90
  }
67
91
  }
68
92
  return rows
@@ -125,7 +149,10 @@ export async function storedRowScope(model: TableModel, session: Session, key: s
125
149
  if (!isPlainIdentifier(model.name) || !isPlainIdentifier(column) || !isPlainIdentifier(key)) {
126
150
  throw new QueryRefusedError('invalid_name', "a file column's table is named by plain identifiers")
127
151
  }
128
- const [found] = await runFixedStatement(session, `select ${column}::text as scope from ${model.name} where ${key}::text = $1`, [keyValue])
152
+ const statement = session.dialect === 'sqlite'
153
+ ? `select cast(${column} as text) as scope from ${model.name} where cast(${key} as text) = ?1`
154
+ : `select ${column}::text as scope from ${model.name} where ${key}::text = $1`
155
+ const [found] = await runFixedStatement(session, statement, [keyValue])
129
156
  const value: unknown = typeof found === 'object' && found !== null ? ownDescriptor(found, 'scope')?.value : undefined
130
157
  if (typeof value !== 'string') {
131
158
  throw new NotFoundError(`${model.name} not found`)
@@ -8,6 +8,7 @@ import { BinaryOperationNode, type OperationNode, OperatorNode, ValueNode } from
8
8
  import { runFixedStatement, type Session, sessionOf } from './database'
9
9
  import { QueryRefusedError } from './errors'
10
10
  import type { GuardContext } from './guard'
11
+ import type { DialectTexts } from './job-leases'
11
12
  import { WEBHOOK_BINDINGS_TABLE, WEBHOOK_DELIVERIES_TABLE } from './migrations'
12
13
  import { acknowledgement, allOf, column, deleteNode, equals, insertNode, locateNode, scopedWhere, updateNode } from './nodes'
13
14
  import type { DataLayerRuntime } from './store'
@@ -72,16 +73,35 @@ export interface DeliveryClaim {
72
73
  const D = WEBHOOK_DELIVERIES_TABLE
73
74
 
74
75
  /** A new key, or one whose claim expired without completion; a completed one (no lease) is never taken. */
75
- const SQL_CLAIM = `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values ($1, $2, $3::bigint, $4::bigint)
76
+ const SQL_CLAIM: DialectTexts = {
77
+ postgres: `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values ($1, $2, $3::bigint, $4::bigint)
76
78
  on conflict (binding_id, delivery_id) do update set received_at = excluded.received_at, lease_until = excluded.lease_until
77
79
  where ${D}.lease_until is not null and ${D}.lease_until < excluded.received_at
78
- returning delivery_id`
80
+ returning delivery_id`,
81
+ sqlite: `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values (?1, ?2, ?3, ?4)
82
+ on conflict (binding_id, delivery_id) do update set received_at = excluded.received_at, lease_until = excluded.lease_until
83
+ where ${D}.lease_until is not null and ${D}.lease_until < excluded.received_at
84
+ returning delivery_id`,
85
+ }
79
86
 
80
- const SQL_COMPLETE = `update ${D} set lease_until = null
87
+ const SQL_COMPLETE: DialectTexts = {
88
+ postgres: `update ${D} set lease_until = null
81
89
  where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint
82
- returning delivery_id`
90
+ returning delivery_id`,
91
+ sqlite: `update ${D} set lease_until = null
92
+ where binding_id = ?1 and delivery_id = ?2 and lease_until = ?3
93
+ returning delivery_id`,
94
+ }
83
95
 
84
- const SQL_RELEASE = `delete from ${D} where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint returning delivery_id`
96
+ const SQL_RELEASE: DialectTexts = {
97
+ postgres: `delete from ${D} where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint returning delivery_id`,
98
+ sqlite: `delete from ${D} where binding_id = ?1 and delivery_id = ?2 and lease_until = ?3 returning delivery_id`,
99
+ }
100
+
101
+ /** Runs the text of `session`'s dialect. */
102
+ function run(session: Session, texts: DialectTexts, parameters: readonly (string | number)[]): Promise<readonly unknown[]> {
103
+ return runFixedStatement(session, texts[session.dialect], parameters)
104
+ }
85
105
 
86
106
  const BINDING_COLUMNS = ['id', 'webhook', 'scope_type', 'scope_value', 'account', 'secret']
87
107
 
@@ -186,17 +206,17 @@ export function webhookTables(runtime: () => DataLayerRuntime): WebhookTables {
186
206
  )
187
207
  const leaseUntil = now + leaseMs
188
208
  // The primary key decides between concurrent copies of one delivery: exactly one inserts or takes over.
189
- const claimed = await runFixedStatement(session(), SQL_CLAIM, [bindingId, deliveryKey, now, leaseUntil])
209
+ const claimed = await run(session(), SQL_CLAIM, [bindingId, deliveryKey, now, leaseUntil])
190
210
  return claimed.length === 0 ? null : Object.freeze({ bindingId, key: deliveryKey, leaseUntil })
191
211
  },
192
212
 
193
213
  async completeDelivery(claim: DeliveryClaim, using?: Session): Promise<boolean> {
194
- const completed = await runFixedStatement(using ?? session(), SQL_COMPLETE, [claim.bindingId, claim.key, claim.leaseUntil])
214
+ const completed = await run(using ?? session(), SQL_COMPLETE, [claim.bindingId, claim.key, claim.leaseUntil])
195
215
  return completed.length > 0
196
216
  },
197
217
 
198
218
  async releaseDelivery(claim: DeliveryClaim): Promise<void> {
199
- await runFixedStatement(session(), SQL_RELEASE, [claim.bindingId, claim.key, claim.leaseUntil])
219
+ await run(session(), SQL_RELEASE, [claim.bindingId, claim.key, claim.leaseUntil])
200
220
  },
201
221
  })
202
222
  }
package/src/framework.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // hands the framework the locator its access check uses. Browser- and Worker-safe: the Worker adapter imports `boot`.
4
4
 
5
5
  import type { DataAccess } from './orm'
6
- import { frameworkSideOf, type FrameworkTables, type Locator } from './registry'
6
+ import { frameworkSideOf, type FrameworkTables, type Locator, type ProvisionalBinding } from './registry'
7
7
  import type { DataLayerRuntime } from './store'
8
8
 
9
9
  export type { Admissions } from './admissions'
@@ -21,9 +21,10 @@ export {
21
21
  export type { FileBinding } from './file-columns'
22
22
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
23
23
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
24
- export type { JobLeases, JobLeaseState, JobOutcome, OverdueClaim } from './job-leases'
24
+ export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
25
+ export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
25
26
  export type { DataAccess, DataHandles, DataSite } from './orm'
26
- export type { FrameworkTables, Locator } from './registry'
27
+ export type { FrameworkTables, Locator, ProvisionalBinding } from './registry'
27
28
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
28
29
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files'
29
30
 
@@ -37,6 +38,14 @@ export function isScopedDatabase(value: unknown): boolean {
37
38
  * reach. Throws for any other value and for a layer that is already connected.
38
39
  */
39
40
  export function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): Locator {
41
+ return bindScopedDatabaseProvisionally(value, runtime).locate
42
+ }
43
+
44
+ /**
45
+ * Connects the layer like `bindScopedDatabase`, and answers with its locator the `release` that disconnects it again:
46
+ * a boot that fails releases the layer, so a later boot of the same application binds it. Throws as that does.
47
+ */
48
+ export function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding {
40
49
  const side = frameworkSideOf(value)
41
50
  if (side === undefined) {
42
51
  throw new TypeError('not a data layer scoped(tables) created')
@@ -45,8 +54,8 @@ export function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): L
45
54
  }
46
55
 
47
56
  /**
48
- * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and the
49
- * admission counters. Each operation needs the layer bound first. Throws for any other value.
57
+ * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
58
+ * the admission counters. Each operation needs the layer bound first. Throws for any other value.
50
59
  */
51
60
  export function frameworkTablesOf(value: unknown): FrameworkTables {
52
61
  const side = frameworkSideOf(value)
package/src/guard.ts CHANGED
@@ -262,6 +262,14 @@ function checkNode(node: OperationNode, parent: Visit | undefined, context: Guar
262
262
  return
263
263
  case 'TableNode':
264
264
  return checkTable(node, parent, context)
265
+ case 'OrderByItemNode': {
266
+ // Kysely prints `nulls` as raw text; the layer only ever states the order Postgres has by default.
267
+ const nulls = read(node, 'nulls')
268
+ if (nulls !== undefined && nulls !== 'first' && nulls !== 'last') {
269
+ throw new QueryRefusedError('statement_shape', 'an order term states nulls first or nulls last, nothing else')
270
+ }
271
+ return
272
+ }
265
273
  case 'JoinNode':
266
274
  return checkJoin(node, context)
267
275
  case 'ReferenceNode':
package/src/index.ts CHANGED
@@ -13,7 +13,15 @@ export type {
13
13
  WithinGrant,
14
14
  } from './capability'
15
15
  export { MAX_WITHIN_VALUES } from './capability'
16
- export { applicationSchema, Database, type PostgresOptions } from './database'
16
+ export {
17
+ applicationSchema,
18
+ Database,
19
+ type DatabaseEngine,
20
+ type Executor,
21
+ type SqlDialect,
22
+ type TransactionOptions,
23
+ type TransactionRunner,
24
+ } from './database'
17
25
  export type {
18
26
  AllowedOperator,
19
27
  ComparisonOperator,
@@ -37,6 +45,7 @@ export {
37
45
  type QueryRefusal,
38
46
  QueryRefusedError,
39
47
  } from './errors'
48
+ export type { JsonColumnValue, JsonValue } from './json'
40
49
  export type {
41
50
  AnyDbIndex,
42
51
  ChildRows,
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