@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.20
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 +35 -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 +229 -40
- 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 +6 -4
- package/src/file-columns.ts +56 -11
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +373 -15
- package/src/index.ts +13 -1
- package/src/job-leases.ts +212 -55
- package/src/job-wakes.ts +450 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +163 -0
- package/src/migrations.ts +25 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +124 -45
- package/src/orm.ts +283 -133
- package/src/policy.ts +1851 -119
- package/src/postgres.ts +26 -0
- package/src/registry.ts +52 -3
- 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 +2290 -239
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +164 -3
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1348 -0
- package/src/testing-sqlite.ts +685 -0
- package/src/testing.ts +310 -494
- package/src/vocabulary-tables.ts +124 -18
- 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 +5 -4
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +11 -5
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +4 -3
- package/types/src/job-leases.d.ts +34 -5
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +1 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +91 -42
- package/types/src/orm.d.ts +10 -0
- package/types/src/policy.d.ts +332 -6
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +37 -3
- 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 +17 -1
- 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 +141 -17
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,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
|
-
/**
|
|
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>
|
|
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 =
|
|
126
|
+
const SQL_NOW: DialectTexts = {
|
|
127
|
+
postgres: 'select now() as now',
|
|
128
|
+
sqlite: `select ${N} as now`,
|
|
129
|
+
}
|
|
94
130
|
|
|
95
|
-
const SQL_REGISTER =
|
|
96
|
-
|
|
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 =
|
|
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 =
|
|
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
|
|
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 =
|
|
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
|
-
|
|
118
|
-
|
|
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
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
135
|
-
|
|
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
|
|
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
|
-
|
|
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 =
|
|
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(
|
|
157
|
-
|
|
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,11 +382,15 @@ function refuseEnded(fence: LeaseFence): void {
|
|
|
254
382
|
}
|
|
255
383
|
}
|
|
256
384
|
|
|
257
|
-
const SQL_CLOCK =
|
|
385
|
+
const SQL_CLOCK: DialectTexts = {
|
|
386
|
+
postgres: `select date_trunc('milliseconds', clock_timestamp() + interval '999 microseconds') 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
|
|
261
|
-
* clock decides when a row is due.
|
|
392
|
+
* clock decides when a row is due. On Postgres it is rounded up to the millisecond a `Date` holds, so it is never
|
|
393
|
+
* earlier than a `due` that `now()` wrote with microseconds.
|
|
262
394
|
*/
|
|
263
395
|
export async function databaseNow(session: Session): Promise<Date> {
|
|
264
396
|
const [row] = await rows(session, SQL_CLOCK, [])
|
|
@@ -275,6 +407,7 @@ const params = (fence: LeaseFence): (string | number)[] => [fence.job, fence.gen
|
|
|
275
407
|
* stays locked `for share` until the commit (a takeover or a renewal waits), and every statement is bounded by the
|
|
276
408
|
* attempt's remaining time. After it, just before the commit: the attempt still holds the lease within its deadline.
|
|
277
409
|
* Otherwise the transaction rolls back with `LeaseLostError`; so does a statement the deadline or the runner cancelled.
|
|
410
|
+
* On SQLite only the two checks run: no other event reaches the Durable Object while the transaction is open.
|
|
278
411
|
*/
|
|
279
412
|
export async function fencedTransaction<T>(session: Session, fence: LeaseFence, work: (transaction: Session) => Promise<T>): Promise<T> {
|
|
280
413
|
refuseEnded(fence)
|
|
@@ -285,12 +418,19 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
|
|
|
285
418
|
if (held === undefined) {
|
|
286
419
|
throw lost(fence)
|
|
287
420
|
}
|
|
288
|
-
backend
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
421
|
+
// SQLite has no backend to cancel and no statement timeout: the check before the commit refuses a late attempt,
|
|
422
|
+
// and a Durable Object resets a transaction that runs past its own limit.
|
|
423
|
+
const postgres = transaction.dialect === 'postgres'
|
|
424
|
+
if (postgres) {
|
|
425
|
+
backend = { pid: integer(held, 'pid'), began: text(held, 'began') }
|
|
426
|
+
const running = inFlight.get(fence) ?? new Set<Backend>()
|
|
427
|
+
running.add(backend)
|
|
428
|
+
inFlight.set(fence, running)
|
|
429
|
+
}
|
|
292
430
|
refuseEnded(fence)
|
|
293
|
-
|
|
431
|
+
if (postgres) {
|
|
432
|
+
await runFixedStatement(transaction, SQL_TIMEOUTS, [String(integer(held, 'remaining_ms'))])
|
|
433
|
+
}
|
|
294
434
|
const result = await work(transaction)
|
|
295
435
|
refuseEnded(fence)
|
|
296
436
|
if ((await rows(transaction, SQL_STILL_HELD, params(fence))).length === 0) {
|
|
@@ -310,8 +450,17 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
|
|
|
310
450
|
}
|
|
311
451
|
}
|
|
312
452
|
|
|
313
|
-
export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
|
|
453
|
+
export function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases {
|
|
314
454
|
const session = () => sessionOf(runtime())
|
|
455
|
+
/** A lease statement and, when it changed the lease, its projection, in one transaction. */
|
|
456
|
+
const changing = (texts: DialectTexts, parameters: readonly (string | number)[], job: string, change: LeaseChange) =>
|
|
457
|
+
session().transaction(async (transaction) => {
|
|
458
|
+
const found = await rows(transaction, texts, parameters)
|
|
459
|
+
if (found.length > 0) {
|
|
460
|
+
await project(transaction, job, change)
|
|
461
|
+
}
|
|
462
|
+
return found
|
|
463
|
+
})
|
|
315
464
|
return Object.freeze({
|
|
316
465
|
async now(): Promise<Date> {
|
|
317
466
|
const [row] = await rows(session(), SQL_NOW, [])
|
|
@@ -323,30 +472,38 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
|
|
|
323
472
|
},
|
|
324
473
|
|
|
325
474
|
async reapCrashed(job: string): Promise<boolean> {
|
|
326
|
-
return (await
|
|
475
|
+
return (await changing(SQL_REAP, [job], job, { kind: 'reaped' })).length > 0
|
|
327
476
|
},
|
|
328
477
|
|
|
329
478
|
async acquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
330
|
-
const [row] = await
|
|
479
|
+
const [row] = await changing(SQL_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')], job, {
|
|
480
|
+
kind: 'acquired',
|
|
481
|
+
})
|
|
331
482
|
return fenceOf(job, holder, row)
|
|
332
483
|
},
|
|
333
484
|
|
|
334
485
|
async renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
335
|
-
const [row] = await
|
|
336
|
-
|
|
337
|
-
holder,
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
486
|
+
const [row] = await changing(
|
|
487
|
+
SQL_RENEW,
|
|
488
|
+
[...params(fence), holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
|
|
489
|
+
fence.job,
|
|
490
|
+
{ kind: 'renewed' },
|
|
491
|
+
)
|
|
341
492
|
return fenceOf(fence.job, holder, row)
|
|
342
493
|
},
|
|
343
494
|
|
|
344
|
-
async finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean> {
|
|
345
|
-
|
|
495
|
+
async finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean> {
|
|
496
|
+
const change: LeaseChange = { kind: 'finished', wakes: finishWakes(outcome, wakes) }
|
|
497
|
+
return (await changing(SQL_FINISH, [...params(fence), outcome], fence.job, change)).length > 0
|
|
346
498
|
},
|
|
347
499
|
|
|
348
500
|
async tryAcquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
349
|
-
const [row] = await
|
|
501
|
+
const [row] = await changing(
|
|
502
|
+
SQL_TRY_ACQUIRE,
|
|
503
|
+
[job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
|
|
504
|
+
job,
|
|
505
|
+
{ kind: 'acquired' },
|
|
506
|
+
)
|
|
350
507
|
return fenceOf(job, holder, row)
|
|
351
508
|
},
|
|
352
509
|
|
|
@@ -368,11 +525,11 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
|
|
|
368
525
|
async cancelInFlight(fence: LeaseFence): Promise<void> {
|
|
369
526
|
ended.add(fence)
|
|
370
527
|
// 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.
|
|
528
|
+
// a statement still running is cancelled, so the ROLLBACK queued behind it runs. SQLite records no backend.
|
|
372
529
|
stopOf(fence).abort(lost(fence))
|
|
373
530
|
const running = [...(inFlight.get(fence) ?? [])]
|
|
374
531
|
for (const backend of running) {
|
|
375
|
-
await
|
|
532
|
+
await runFixedStatement(session(), SQL_CANCEL, [backend.pid, backend.began])
|
|
376
533
|
}
|
|
377
534
|
},
|
|
378
535
|
|