@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +39 -4
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +56 -2
- package/src/codegen-sqlite.ts +194 -0
- package/src/codegen.ts +230 -41
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/database.ts +227 -61
- package/src/description.ts +37 -8
- package/src/errors.ts +10 -6
- package/src/file-columns.ts +56 -11
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +15 -5
- package/src/guard.ts +373 -15
- package/src/index.ts +17 -1
- package/src/job-leases.ts +228 -55
- package/src/job-wakes.ts +600 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +210 -0
- package/src/migrations.ts +73 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +206 -71
- package/src/orm.ts +425 -170
- package/src/policy.ts +1979 -141
- package/src/postgres.ts +26 -0
- package/src/registry.ts +55 -3
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +247 -476
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +269 -0
- package/src/store.ts +2292 -239
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +172 -6
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1351 -0
- package/src/testing-sqlite.ts +685 -0
- package/src/testing.ts +310 -494
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +55 -2
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +79 -5
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/description.d.ts +26 -8
- package/types/src/errors.d.ts +9 -6
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +12 -5
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +5 -4
- package/types/src/job-leases.d.ts +40 -5
- package/types/src/job-wakes.d.ts +124 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +4 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +163 -71
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +351 -23
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +40 -3
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +29 -21
- package/types/src/sqlite-bun.d.ts +21 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +143 -34
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +18 -2
- package/types/src/temporal.d.ts +24 -0
- package/types/src/testing-shared.d.ts +290 -0
- package/types/src/testing-sqlite.d.ts +37 -0
- package/types/src/testing.d.ts +2 -93
- package/types/src/vocabulary-tables.d.ts +169 -22
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.
|
|
4
|
-
// `@fabrika/app`'s job runner reaches it, through `frameworkTablesOf`.
|
|
5
|
-
// containers whose clocks disagree still agree on who holds a lease and
|
|
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,17 @@ 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
|
-
/**
|
|
64
|
-
|
|
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>
|
|
71
|
+
/**
|
|
72
|
+
* Gives back a lease under which no run started: frees it and leaves every wake as it is, owned ones disowned, and
|
|
73
|
+
* records no run (no status, end or duration). A process schedule's timer releases a lease whose take owned no due
|
|
74
|
+
* wake (ADR-0080). `false` when `fence` no longer held it.
|
|
75
|
+
*/
|
|
76
|
+
release(fence: LeaseFence): Promise<boolean>
|
|
65
77
|
/** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
|
|
66
78
|
markPending(job: string): Promise<void>
|
|
67
79
|
/**
|
|
@@ -82,69 +94,185 @@ export interface JobLeases {
|
|
|
82
94
|
state(job: string): Promise<JobLeaseState | null>
|
|
83
95
|
}
|
|
84
96
|
|
|
97
|
+
/**
|
|
98
|
+
* What a lease statement changed: a crashed holder reaped, a lease taken or handed on, or a run finished with what its
|
|
99
|
+
* wakes become (`null` leaves them).
|
|
100
|
+
*/
|
|
101
|
+
export type LeaseChange =
|
|
102
|
+
| { readonly kind: 'reaped' | 'acquired' | 'renewed' }
|
|
103
|
+
| { readonly kind: 'finished'; readonly wakes: FinishWakes | null }
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Runs in the transaction of every lease statement that changed the lease, so a table that follows the lease (the
|
|
107
|
+
* wakes, `job-wakes.ts`) commits with it or not at all. A statement that changed nothing, a lost lease's, runs none.
|
|
108
|
+
*/
|
|
109
|
+
export type LeaseProjection = (transaction: Session, job: string, change: LeaseChange) => Promise<void>
|
|
110
|
+
|
|
111
|
+
/** One framework statement in each dialect's text; a session runs the text of its own. */
|
|
112
|
+
export type DialectTexts = Readonly<Record<SqlDialect, string>>
|
|
113
|
+
|
|
114
|
+
/** SQLite's clock, as a stored timestamp: ISO text, so a comparison of two is a text comparison. */
|
|
115
|
+
export const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
|
|
116
|
+
|
|
117
|
+
/** SQLite's clock moved by `ms`, an SQL expression of milliseconds (negative is earlier). */
|
|
118
|
+
export function sqliteNowPlus(ms: string): string {
|
|
119
|
+
return `strftime('${SQLITE_NOW_FORMAT}', 'now', printf('%+.3f seconds', (${ms}) / 1000.0))`
|
|
120
|
+
}
|
|
121
|
+
|
|
85
122
|
const T = JOB_LEASES_TABLE
|
|
86
123
|
const MS = `* interval '1 millisecond'`
|
|
124
|
+
const N = SQLITE_NOW
|
|
125
|
+
const SQLITE_RUN_MS = `cast(round((julianday('now') - julianday(last_started_at)) * 86400000) as integer)`
|
|
87
126
|
const QUERY_CANCELED = '57014'
|
|
88
127
|
const IDLE_TIMEOUT = '25P03'
|
|
89
128
|
|
|
90
129
|
const STATE_COLUMNS =
|
|
91
130
|
'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
131
|
|
|
93
|
-
const SQL_NOW =
|
|
132
|
+
const SQL_NOW: DialectTexts = {
|
|
133
|
+
postgres: 'select now() as now',
|
|
134
|
+
sqlite: `select ${N} as now`,
|
|
135
|
+
}
|
|
94
136
|
|
|
95
|
-
const SQL_REGISTER =
|
|
96
|
-
|
|
137
|
+
const SQL_REGISTER: DialectTexts = {
|
|
138
|
+
postgres: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at)
|
|
139
|
+
values ($1, 0, null, now(), now(), now()) on conflict (job) do nothing`,
|
|
140
|
+
sqlite: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at)
|
|
141
|
+
values (?1, 0, null, ${N}, ${N}, ${N}) on conflict (job) do nothing`,
|
|
142
|
+
}
|
|
97
143
|
|
|
98
|
-
const SQL_REAP =
|
|
144
|
+
const SQL_REAP: DialectTexts = {
|
|
145
|
+
postgres: `update ${T} set holder = null, last_status = 'failed', last_finished_at = now(),
|
|
99
146
|
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
|
|
147
|
+
where job = $1 and holder is not null and expires_at <= now() returning job`,
|
|
148
|
+
sqlite: `update ${T} set holder = null, last_status = 'failed', last_finished_at = ${N},
|
|
149
|
+
last_duration_ms = ${SQLITE_RUN_MS}
|
|
150
|
+
where job = ?1 and holder is not null and expires_at <= ${N} returning job`,
|
|
151
|
+
}
|
|
101
152
|
|
|
102
|
-
const SQL_ACQUIRE =
|
|
153
|
+
const SQL_ACQUIRE: DialectTexts = {
|
|
154
|
+
postgres: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at, last_started_at)
|
|
103
155
|
values ($1, 1, $2, now() + $3::bigint ${MS}, now() + $4::bigint ${MS}, now(), now())
|
|
104
156
|
on conflict (job) do update set generation = ${T}.generation + 1, holder = excluded.holder, expires_at = excluded.expires_at,
|
|
105
157
|
attempt_deadline = excluded.attempt_deadline, last_started_at = excluded.last_started_at
|
|
106
|
-
where ${T}.holder is null returning generation
|
|
158
|
+
where ${T}.holder is null returning generation`,
|
|
159
|
+
sqlite: `insert into ${T} (job, generation, holder, expires_at, attempt_deadline, first_seen_at, last_started_at)
|
|
160
|
+
values (?1, 1, ?2, ${sqliteNowPlus('?3')}, ${sqliteNowPlus('?4')}, ${N}, ${N})
|
|
161
|
+
on conflict (job) do update set generation = ${T}.generation + 1, holder = excluded.holder, expires_at = excluded.expires_at,
|
|
162
|
+
attempt_deadline = excluded.attempt_deadline, last_started_at = excluded.last_started_at
|
|
163
|
+
where ${T}.holder is null returning generation`,
|
|
164
|
+
}
|
|
107
165
|
|
|
108
|
-
const SQL_RENEW
|
|
166
|
+
const SQL_RENEW: DialectTexts = {
|
|
167
|
+
postgres: `update ${T} set generation = generation + 1, holder = $4, expires_at = now() + $5::bigint ${MS},
|
|
109
168
|
attempt_deadline = now() + $6::bigint ${MS}
|
|
110
|
-
where job = $1 and generation = $2 and holder = $3 and expires_at > now() returning generation
|
|
169
|
+
where job = $1 and generation = $2 and holder = $3 and expires_at > now() returning generation`,
|
|
170
|
+
sqlite: `update ${T} set generation = generation + 1, holder = ?4, expires_at = ${sqliteNowPlus('?5')},
|
|
171
|
+
attempt_deadline = ${sqliteNowPlus('?6')}
|
|
172
|
+
where job = ?1 and generation = ?2 and holder = ?3 and expires_at > ${N} returning generation`,
|
|
173
|
+
}
|
|
111
174
|
|
|
112
|
-
const SQL_FINISH =
|
|
175
|
+
const SQL_FINISH: DialectTexts = {
|
|
176
|
+
postgres: `update ${T} set holder = null, last_finished_at = now(), last_status = $4,
|
|
113
177
|
last_duration_ms = (extract(epoch from now() - last_started_at) * 1000)::int,
|
|
114
178
|
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
|
|
179
|
+
where job = $1 and generation = $2 and holder = $3 returning job`,
|
|
180
|
+
sqlite: `update ${T} set holder = null, last_finished_at = ${N}, last_status = ?4,
|
|
181
|
+
last_duration_ms = ${SQLITE_RUN_MS},
|
|
182
|
+
last_succeeded_at = case when ?4 = 'succeeded' then ${N} else last_succeeded_at end
|
|
183
|
+
where job = ?1 and generation = ?2 and holder = ?3 returning job`,
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const SQL_RELEASE: DialectTexts = {
|
|
187
|
+
postgres: `update ${T} set holder = null where job = $1 and generation = $2 and holder = $3 returning job`,
|
|
188
|
+
sqlite: `update ${T} set holder = null where job = ?1 and generation = ?2 and holder = ?3 returning job`,
|
|
189
|
+
}
|
|
116
190
|
|
|
117
|
-
|
|
118
|
-
|
|
191
|
+
const SQL_TRY_ACQUIRE: DialectTexts = {
|
|
192
|
+
// A free lease whose row no transaction holds (`skip locked`): an attempt's fence holds it `for share` while it writes.
|
|
193
|
+
postgres: `with free as (select job from ${T} where job = $1 and holder is null for update skip locked)
|
|
119
194
|
update ${T} set generation = ${T}.generation + 1, holder = $2, expires_at = now() + $3::bigint ${MS},
|
|
120
195
|
attempt_deadline = now() + $4::bigint ${MS}, last_started_at = now()
|
|
121
|
-
from free where ${T}.job = free.job returning ${T}.generation
|
|
196
|
+
from free where ${T}.job = free.job returning ${T}.generation`,
|
|
197
|
+
// No lock to skip: while an attempt's fenced transaction is open, the Durable Object serves no kick.
|
|
198
|
+
sqlite: `update ${T} set generation = generation + 1, holder = ?2, expires_at = ${sqliteNowPlus('?3')},
|
|
199
|
+
attempt_deadline = ${sqliteNowPlus('?4')}, last_started_at = ${N}
|
|
200
|
+
where job = ?1 and holder is null returning generation`,
|
|
201
|
+
}
|
|
122
202
|
|
|
123
203
|
const K = JOB_KICKS_TABLE
|
|
124
204
|
|
|
125
|
-
const SQL_MARK_PENDING
|
|
205
|
+
const SQL_MARK_PENDING: DialectTexts = {
|
|
206
|
+
postgres: `insert into ${K} (job, pending) values ($1, true) on conflict (job) do update set pending = true where ${K}.pending = false`,
|
|
207
|
+
sqlite: `insert into ${K} (job, pending) values (?1, 1) on conflict (job) do update set pending = 1 where ${K}.pending = 0`,
|
|
208
|
+
}
|
|
126
209
|
|
|
127
|
-
const SQL_TAKE_PENDING =
|
|
210
|
+
const SQL_TAKE_PENDING: DialectTexts = {
|
|
211
|
+
postgres: `update ${K} set pending = false where job = $1 and pending returning job`,
|
|
212
|
+
sqlite: `update ${K} set pending = 0 where job = ?1 and pending = 1 returning job`,
|
|
213
|
+
}
|
|
128
214
|
|
|
129
|
-
const SQL_CLAIM_OVERDUE =
|
|
215
|
+
const SQL_CLAIM_OVERDUE: DialectTexts = {
|
|
216
|
+
postgres: `update ${T} set last_missed_reported_at = now()
|
|
130
217
|
where job = $1 and coalesce(last_succeeded_at, first_seen_at) < now() - 2 * $2::bigint ${MS}
|
|
131
218
|
and (last_missed_reported_at is null or last_missed_reported_at <= now() - $2::bigint ${MS})
|
|
132
|
-
returning last_succeeded_at, first_seen_at
|
|
219
|
+
returning last_succeeded_at, first_seen_at`,
|
|
220
|
+
sqlite: `update ${T} set last_missed_reported_at = ${N}
|
|
221
|
+
where job = ?1 and coalesce(last_succeeded_at, first_seen_at) < ${sqliteNowPlus('-2 * ?2')}
|
|
222
|
+
and (last_missed_reported_at is null or last_missed_reported_at <= ${sqliteNowPlus('-?2')})
|
|
223
|
+
returning last_succeeded_at, first_seen_at`,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const SQL_STILL_HELD: DialectTexts = {
|
|
227
|
+
postgres: `select job from ${T} where job = $1 and generation = $2 and holder = $3 and attempt_deadline > clock_timestamp()`,
|
|
228
|
+
sqlite: `select job from ${T} where job = ?1 and generation = ?2 and holder = ?3 and attempt_deadline > ${N}`,
|
|
229
|
+
}
|
|
133
230
|
|
|
134
|
-
|
|
135
|
-
|
|
231
|
+
const SQL_FENCE: DialectTexts = {
|
|
232
|
+
// Inside a mutation's transaction, so `clock_timestamp()`: `now()` is when the transaction began.
|
|
233
|
+
postgres: `select pg_backend_pid() as pid, transaction_timestamp()::text as began,
|
|
136
234
|
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
|
|
235
|
+
from ${T} where job = $1 and generation = $2 and holder = $3 and attempt_deadline > clock_timestamp() for share`,
|
|
236
|
+
// No lock: while the transaction is open the Durable Object serves no other event, so no takeover runs before it ends.
|
|
237
|
+
sqlite: SQL_STILL_HELD.sqlite,
|
|
238
|
+
}
|
|
138
239
|
|
|
139
|
-
// The attempt's remaining time bounds a statement and an idle wait alike: either past the deadline ends
|
|
240
|
+
// Postgres only. The attempt's remaining time bounds a statement and an idle wait alike: either past the deadline ends it.
|
|
140
241
|
const SQL_TIMEOUTS = `select set_config('statement_timeout', $1, true), set_config('idle_in_transaction_session_timeout', $1, true)`
|
|
141
242
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
// Only the backend still in the transaction the fence opened: a pid the pool reused for other work is left alone.
|
|
243
|
+
// Postgres only. Only the backend still in the transaction the fence opened: a pid the pool reused is left alone.
|
|
145
244
|
const SQL_CANCEL = `select pg_cancel_backend(pid) from pg_stat_activity where pid = $1 and xact_start = $2::timestamptz`
|
|
146
245
|
|
|
147
|
-
const SQL_STATE =
|
|
246
|
+
const SQL_STATE: DialectTexts = {
|
|
247
|
+
postgres: `select now() as now, ${STATE_COLUMNS} from ${T} where job = $1`,
|
|
248
|
+
sqlite: `select ${N} as now, ${STATE_COLUMNS} from ${T} where job = ?1`,
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The columns that hold a time; SQLite answers each as ISO text, which the row's entry reads as a `Date`. */
|
|
252
|
+
const TIMESTAMP_COLUMNS: ReadonlySet<string> = new Set([
|
|
253
|
+
'now',
|
|
254
|
+
'expires_at',
|
|
255
|
+
'attempt_deadline',
|
|
256
|
+
'first_seen_at',
|
|
257
|
+
'last_started_at',
|
|
258
|
+
'last_finished_at',
|
|
259
|
+
'last_succeeded_at',
|
|
260
|
+
'last_missed_reported_at',
|
|
261
|
+
])
|
|
262
|
+
|
|
263
|
+
const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
|
|
264
|
+
|
|
265
|
+
/** A stored SQLite timestamp (`SQLITE_NOW_FORMAT`) as a `Date`, or `null`; anything else is refused. */
|
|
266
|
+
export function sqliteTimestamp(value: unknown, what: string): Date | null {
|
|
267
|
+
if (value === null) {
|
|
268
|
+
return null
|
|
269
|
+
}
|
|
270
|
+
const parsed = typeof value === 'string' && ISO_TIMESTAMP.test(value) ? new Date(value) : undefined
|
|
271
|
+
if (parsed === undefined || Number.isNaN(parsed.getTime())) {
|
|
272
|
+
throw new QueryRefusedError('unexpected_row', `${what} is not a stored timestamp`)
|
|
273
|
+
}
|
|
274
|
+
return parsed
|
|
275
|
+
}
|
|
148
276
|
|
|
149
277
|
function record(row: unknown): Readonly<Record<string, unknown>> {
|
|
150
278
|
if (typeof row !== 'object' || row === null) {
|
|
@@ -153,8 +281,19 @@ function record(row: unknown): Readonly<Record<string, unknown>> {
|
|
|
153
281
|
return Object.fromEntries(Object.entries(row))
|
|
154
282
|
}
|
|
155
283
|
|
|
156
|
-
async function rows(
|
|
157
|
-
|
|
284
|
+
async function rows(
|
|
285
|
+
session: Session,
|
|
286
|
+
texts: DialectTexts,
|
|
287
|
+
parameters: readonly (string | number | null)[],
|
|
288
|
+
): Promise<Readonly<Record<string, unknown>>[]> {
|
|
289
|
+
const found = (await runFixedStatement(session, texts[session.dialect], parameters)).map(record)
|
|
290
|
+
return session.dialect === 'sqlite' ? found.map(sqliteRow) : found
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function sqliteRow(row: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>> {
|
|
294
|
+
return Object.fromEntries(
|
|
295
|
+
Object.entries(row).map(([name, value]) => [name, TIMESTAMP_COLUMNS.has(name) ? sqliteTimestamp(value, `${T}.${name}`) : value]),
|
|
296
|
+
)
|
|
158
297
|
}
|
|
159
298
|
|
|
160
299
|
function integer(row: Readonly<Record<string, unknown>>, name: string): number {
|
|
@@ -254,11 +393,15 @@ function refuseEnded(fence: LeaseFence): void {
|
|
|
254
393
|
}
|
|
255
394
|
}
|
|
256
395
|
|
|
257
|
-
const SQL_CLOCK =
|
|
396
|
+
const SQL_CLOCK: DialectTexts = {
|
|
397
|
+
postgres: `select date_trunc('milliseconds', clock_timestamp() + interval '999 microseconds') as now`,
|
|
398
|
+
sqlite: `select ${N} as now`,
|
|
399
|
+
}
|
|
258
400
|
|
|
259
401
|
/**
|
|
260
402
|
* The database's clock inside `session`'s transaction: a queue claim compares and moves `due` by it, so no process
|
|
261
|
-
* clock decides when a row is due.
|
|
403
|
+
* clock decides when a row is due. On Postgres it is rounded up to the millisecond a `Date` holds, so it is never
|
|
404
|
+
* earlier than a `due` that `now()` wrote with microseconds.
|
|
262
405
|
*/
|
|
263
406
|
export async function databaseNow(session: Session): Promise<Date> {
|
|
264
407
|
const [row] = await rows(session, SQL_CLOCK, [])
|
|
@@ -275,6 +418,7 @@ const params = (fence: LeaseFence): (string | number)[] => [fence.job, fence.gen
|
|
|
275
418
|
* stays locked `for share` until the commit (a takeover or a renewal waits), and every statement is bounded by the
|
|
276
419
|
* attempt's remaining time. After it, just before the commit: the attempt still holds the lease within its deadline.
|
|
277
420
|
* Otherwise the transaction rolls back with `LeaseLostError`; so does a statement the deadline or the runner cancelled.
|
|
421
|
+
* On SQLite only the two checks run: no other event reaches the Durable Object while the transaction is open.
|
|
278
422
|
*/
|
|
279
423
|
export async function fencedTransaction<T>(session: Session, fence: LeaseFence, work: (transaction: Session) => Promise<T>): Promise<T> {
|
|
280
424
|
refuseEnded(fence)
|
|
@@ -285,12 +429,19 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
|
|
|
285
429
|
if (held === undefined) {
|
|
286
430
|
throw lost(fence)
|
|
287
431
|
}
|
|
288
|
-
backend
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
432
|
+
// SQLite has no backend to cancel and no statement timeout: the check before the commit refuses a late attempt,
|
|
433
|
+
// and a Durable Object resets a transaction that runs past its own limit.
|
|
434
|
+
const postgres = transaction.dialect === 'postgres'
|
|
435
|
+
if (postgres) {
|
|
436
|
+
backend = { pid: integer(held, 'pid'), began: text(held, 'began') }
|
|
437
|
+
const running = inFlight.get(fence) ?? new Set<Backend>()
|
|
438
|
+
running.add(backend)
|
|
439
|
+
inFlight.set(fence, running)
|
|
440
|
+
}
|
|
292
441
|
refuseEnded(fence)
|
|
293
|
-
|
|
442
|
+
if (postgres) {
|
|
443
|
+
await runFixedStatement(transaction, SQL_TIMEOUTS, [String(integer(held, 'remaining_ms'))])
|
|
444
|
+
}
|
|
294
445
|
const result = await work(transaction)
|
|
295
446
|
refuseEnded(fence)
|
|
296
447
|
if ((await rows(transaction, SQL_STILL_HELD, params(fence))).length === 0) {
|
|
@@ -310,8 +461,17 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
|
|
|
310
461
|
}
|
|
311
462
|
}
|
|
312
463
|
|
|
313
|
-
export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
|
|
464
|
+
export function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases {
|
|
314
465
|
const session = () => sessionOf(runtime())
|
|
466
|
+
/** A lease statement and, when it changed the lease, its projection, in one transaction. */
|
|
467
|
+
const changing = (texts: DialectTexts, parameters: readonly (string | number)[], job: string, change: LeaseChange) =>
|
|
468
|
+
session().transaction(async (transaction) => {
|
|
469
|
+
const found = await rows(transaction, texts, parameters)
|
|
470
|
+
if (found.length > 0) {
|
|
471
|
+
await project(transaction, job, change)
|
|
472
|
+
}
|
|
473
|
+
return found
|
|
474
|
+
})
|
|
315
475
|
return Object.freeze({
|
|
316
476
|
async now(): Promise<Date> {
|
|
317
477
|
const [row] = await rows(session(), SQL_NOW, [])
|
|
@@ -323,30 +483,43 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
|
|
|
323
483
|
},
|
|
324
484
|
|
|
325
485
|
async reapCrashed(job: string): Promise<boolean> {
|
|
326
|
-
return (await
|
|
486
|
+
return (await changing(SQL_REAP, [job], job, { kind: 'reaped' })).length > 0
|
|
327
487
|
},
|
|
328
488
|
|
|
329
489
|
async acquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
330
|
-
const [row] = await
|
|
490
|
+
const [row] = await changing(SQL_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')], job, {
|
|
491
|
+
kind: 'acquired',
|
|
492
|
+
})
|
|
331
493
|
return fenceOf(job, holder, row)
|
|
332
494
|
},
|
|
333
495
|
|
|
334
496
|
async renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
335
|
-
const [row] = await
|
|
336
|
-
|
|
337
|
-
holder,
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
497
|
+
const [row] = await changing(
|
|
498
|
+
SQL_RENEW,
|
|
499
|
+
[...params(fence), holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
|
|
500
|
+
fence.job,
|
|
501
|
+
{ kind: 'renewed' },
|
|
502
|
+
)
|
|
341
503
|
return fenceOf(fence.job, holder, row)
|
|
342
504
|
},
|
|
343
505
|
|
|
344
|
-
async finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean> {
|
|
345
|
-
|
|
506
|
+
async finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean> {
|
|
507
|
+
const change: LeaseChange = { kind: 'finished', wakes: finishWakes(outcome, wakes) }
|
|
508
|
+
return (await changing(SQL_FINISH, [...params(fence), outcome], fence.job, change)).length > 0
|
|
509
|
+
},
|
|
510
|
+
|
|
511
|
+
async release(fence: LeaseFence): Promise<boolean> {
|
|
512
|
+
// A finish that applies nothing to the wakes: the projection only disowns what the take marked owned.
|
|
513
|
+
return (await changing(SQL_RELEASE, params(fence), fence.job, { kind: 'finished', wakes: null })).length > 0
|
|
346
514
|
},
|
|
347
515
|
|
|
348
516
|
async tryAcquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
349
|
-
const [row] = await
|
|
517
|
+
const [row] = await changing(
|
|
518
|
+
SQL_TRY_ACQUIRE,
|
|
519
|
+
[job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
|
|
520
|
+
job,
|
|
521
|
+
{ kind: 'acquired' },
|
|
522
|
+
)
|
|
350
523
|
return fenceOf(job, holder, row)
|
|
351
524
|
},
|
|
352
525
|
|
|
@@ -368,11 +541,11 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
|
|
|
368
541
|
async cancelInFlight(fence: LeaseFence): Promise<void> {
|
|
369
542
|
ended.add(fence)
|
|
370
543
|
// 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.
|
|
544
|
+
// a statement still running is cancelled, so the ROLLBACK queued behind it runs. SQLite records no backend.
|
|
372
545
|
stopOf(fence).abort(lost(fence))
|
|
373
546
|
const running = [...(inFlight.get(fence) ?? [])]
|
|
374
547
|
for (const backend of running) {
|
|
375
|
-
await
|
|
548
|
+
await runFixedStatement(session(), SQL_CANCEL, [backend.pid, backend.began])
|
|
376
549
|
}
|
|
377
550
|
},
|
|
378
551
|
|