@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.41
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-wakes.ts
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
// The framework's side of `fabrika_wakes` (`@fabrika/db/migrations`): a job's durable pending work, one row per due
|
|
2
|
+
// unit (its next scheduled run, a kick, a claim's re-arm, a durable retry), and the scheduler's next wake over it and the
|
|
3
|
+
// leases. Only `@fabrika/app` reaches it, through `frameworkTablesOf`. A run owns the wakes due when it took its lease,
|
|
4
|
+
// marked in that transaction (`owned`); a wake written or merged into afterwards is not its. Only the transaction of that
|
|
5
|
+
// run's fenced finish consumes or retries what it owns (`leaseProjection`), so a crash at any point leaves either the wake
|
|
6
|
+
// or a held lease whose expiry is due. Every change runs the runtime's `projectWakes` in its own transaction. Where no
|
|
7
|
+
// crontab runs, `fabrika_job_schedule` keeps the generation of the deploy whose serving processes keep the cron wakes
|
|
8
|
+
// (ADR-0080).
|
|
9
|
+
|
|
10
|
+
import { uuidv7 } from '@fabrika/platform'
|
|
11
|
+
import { freeze } from './builtins'
|
|
12
|
+
import type { LeaseFence } from './capability'
|
|
13
|
+
import { type FixedParameter, runFixedStatement, type Session, sessionOf } from './database'
|
|
14
|
+
import { QueryRefusedError } from './errors'
|
|
15
|
+
import type { DialectTexts, JobOutcome, LeaseChange, LeaseProjection } from './job-leases'
|
|
16
|
+
import { JOB_LEASES_TABLE, JOB_SCHEDULE_TABLE, JOB_WAKES_TABLE } from './migrations'
|
|
17
|
+
import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
|
|
18
|
+
import { refuseInProduction } from './production'
|
|
19
|
+
import type { DataLayerRuntime } from './store'
|
|
20
|
+
|
|
21
|
+
export const WAKE_REASONS = ['cron', 'kick', 'claim', 'retry'] as const
|
|
22
|
+
|
|
23
|
+
export type WakeReason = (typeof WAKE_REASONS)[number]
|
|
24
|
+
|
|
25
|
+
export interface NewWake {
|
|
26
|
+
readonly job: string
|
|
27
|
+
readonly reason: WakeReason
|
|
28
|
+
readonly dueAt: Date
|
|
29
|
+
/** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
|
|
30
|
+
readonly dedupe?: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface Wake {
|
|
34
|
+
readonly id: string
|
|
35
|
+
readonly job: string
|
|
36
|
+
readonly reason: WakeReason
|
|
37
|
+
readonly dueAt: Date
|
|
38
|
+
/** How many failed runs moved this wake (`retry`). */
|
|
39
|
+
readonly attempt: number
|
|
40
|
+
readonly dedupe: string | null
|
|
41
|
+
/** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
|
|
42
|
+
readonly owned: boolean
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
|
|
47
|
+
* transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
|
|
48
|
+
* leaves the wakes as they are.
|
|
49
|
+
*/
|
|
50
|
+
export type FinishWakes =
|
|
51
|
+
/** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
|
|
52
|
+
| {
|
|
53
|
+
readonly kind: 'completed'
|
|
54
|
+
/**
|
|
55
|
+
* With `scheduled`, the next fire is written only when the stored schedule (`keepSchedule`) declares its key, read
|
|
56
|
+
* in the finish's transaction: under a process schedule, a run of an older deploy writes no removed job's or
|
|
57
|
+
* changed expression's fire (ADR-0080).
|
|
58
|
+
*/
|
|
59
|
+
readonly nextCron?: { readonly expression: string; readonly dueAt: Date; readonly scheduled?: boolean }
|
|
60
|
+
}
|
|
61
|
+
/** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
|
|
62
|
+
| { readonly kind: 'retry'; readonly at: Date }
|
|
63
|
+
|
|
64
|
+
export interface JobWakes {
|
|
65
|
+
/**
|
|
66
|
+
* Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
|
|
67
|
+
* keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
|
|
68
|
+
* run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
|
|
69
|
+
* a key another job holds is refused.
|
|
70
|
+
*/
|
|
71
|
+
schedule(wake: NewWake, using?: Session): Promise<Wake>
|
|
72
|
+
/** The pending wakes of `job`, earliest first. */
|
|
73
|
+
pending(job: string): Promise<readonly Wake[]>
|
|
74
|
+
/**
|
|
75
|
+
* When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
|
|
76
|
+
* held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given;
|
|
77
|
+
* with `jobs`, of those jobs only, so a wake of a job this process does not run never holds its timer.
|
|
78
|
+
*/
|
|
79
|
+
next(using?: Session, jobs?: readonly string[]): Promise<Date | null>
|
|
80
|
+
/** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
|
|
81
|
+
untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null>
|
|
82
|
+
/**
|
|
83
|
+
* Where no crontab runs (ADR-0080), in one transaction: raises the stored schedule generation to `generation` when that
|
|
84
|
+
* one is higher in byte order, with the cron keys `fires` declare, and when `generation` is then the stored one,
|
|
85
|
+
* reconciles the wakes against `fires` (as `reconcile`) and adds each fire's wake under its job's cron key where none
|
|
86
|
+
* is pending (an existing one, overdue or not, is left as it is and not locked, so a lease taken meanwhile still owns
|
|
87
|
+
* it). Answers whether `generation` is the stored one; a process of an older one writes nothing. The generation's row stays
|
|
88
|
+
* locked until the transaction commits, so on Postgres a newer generation waits for an older one's seed and reconciles
|
|
89
|
+
* after it, and an older one queued behind a newer one reads the newer and writes nothing. A UUIDv7, lowercase: a
|
|
90
|
+
* later deploy's sorts later.
|
|
91
|
+
*/
|
|
92
|
+
keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean>
|
|
93
|
+
/** The database's clock, read in `using` when given: a wake due now is due by it. */
|
|
94
|
+
now(using?: Session): Promise<Date>
|
|
95
|
+
/**
|
|
96
|
+
* Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
|
|
97
|
+
* each declared job's cron wake whose key names another expression; answers how many it deleted. In `using` when
|
|
98
|
+
* given.
|
|
99
|
+
*/
|
|
100
|
+
reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number>
|
|
101
|
+
/**
|
|
102
|
+
* The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
|
|
103
|
+
* now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
|
|
104
|
+
*/
|
|
105
|
+
hasten(ids: readonly string[]): Promise<number>
|
|
106
|
+
/**
|
|
107
|
+
* The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
|
|
108
|
+
* alarm through `next` until someone reaps it.
|
|
109
|
+
*/
|
|
110
|
+
expiredHolders(): Promise<readonly string[]>
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A declared job and its next fire, which `keepSchedule` seeds; `null` when its expression has none in the window. */
|
|
114
|
+
export interface ScheduledFire extends DeclaredJob {
|
|
115
|
+
readonly dueAt: Date | null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
|
|
119
|
+
export interface DeclaredJob {
|
|
120
|
+
readonly job: string
|
|
121
|
+
readonly expression: string
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const W = JOB_WAKES_TABLE
|
|
125
|
+
const L = JOB_LEASES_TABLE
|
|
126
|
+
const S = JOB_SCHEDULE_TABLE
|
|
127
|
+
const COLUMNS = 'job, due_at, reason, attempt, dedupe'
|
|
128
|
+
const SELECTED = `${COLUMNS}, owned`
|
|
129
|
+
const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
|
|
130
|
+
|
|
131
|
+
/** A stored timestamp as epoch milliseconds, in each dialect. */
|
|
132
|
+
const PG_EPOCH_MS = (column: string): string => `floor(extract(epoch from ${column}) * 1000)::bigint`
|
|
133
|
+
const SQLITE_EPOCH_MS = (column: string): string => `cast(round((julianday(${column}) - 2440587.5) * 86400000) as integer)`
|
|
134
|
+
|
|
135
|
+
/** The start of the job's current run, in epoch milliseconds: the wakes due by then are the ones it takes. */
|
|
136
|
+
const PG_RUN_START = `(select ${PG_EPOCH_MS('last_started_at')} from ${L} where job = $1)`
|
|
137
|
+
const SQLITE_RUN_START = `(select ${SQLITE_EPOCH_MS('last_started_at')} from ${L} where job = ?1)`
|
|
138
|
+
|
|
139
|
+
const SQL_SCHEDULE: DialectTexts = {
|
|
140
|
+
// The update applies only to the same job's row, so a key another job holds answers no row.
|
|
141
|
+
postgres: `insert into ${W} (id, ${COLUMNS}) values ($1::uuid, $2, $3::bigint, $4, 0, $5)
|
|
142
|
+
on conflict (dedupe) where dedupe is not null do update set due_at = least(${W}.due_at, excluded.due_at),
|
|
143
|
+
owned = ${W}.owned and excluded.reason = 'cron' where ${W}.job = excluded.job
|
|
144
|
+
returning id::text as id, ${SELECTED}`,
|
|
145
|
+
sqlite: `insert into ${W} (id, ${COLUMNS}) values (?1, ?2, cast(?3 as integer), ?4, 0, ?5)
|
|
146
|
+
on conflict (dedupe) where dedupe is not null do update set due_at = min(${W}.due_at, excluded.due_at),
|
|
147
|
+
owned = ${W}.owned and excluded.reason = 'cron' where ${W}.job = excluded.job
|
|
148
|
+
returning id, ${SELECTED}`,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const SQL_PENDING: DialectTexts = {
|
|
152
|
+
postgres: `select id::text as id, ${SELECTED} from ${W} where job = $1 order by due_at, id`,
|
|
153
|
+
sqlite: `select id, ${SELECTED} from ${W} where job = ?1 order by due_at, id`,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// A taking run marks every wake of its job, due by its start or not. A row a write still holds (`skip locked`) is being
|
|
157
|
+
// written, and that write leaves it unowned: the lease is taken without waiting for it.
|
|
158
|
+
const SQL_OWN: DialectTexts = {
|
|
159
|
+
postgres: `update ${W} set owned = coalesce(${W}.due_at <= ${PG_RUN_START}, false)
|
|
160
|
+
where id in (select id from ${W} where job = $1 for update skip locked)`,
|
|
161
|
+
sqlite: `update ${W} set owned = coalesce(due_at <= ${SQLITE_RUN_START}, 0) where job = ?1`,
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const SQL_DISOWN: DialectTexts = {
|
|
165
|
+
postgres: `update ${W} set owned = false where id in (select id from ${W} where job = $1 and owned for update skip locked)`,
|
|
166
|
+
sqlite: `update ${W} set owned = 0 where job = ?1 and owned = 1`,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Two candidates, each one index-ordered or per-job lookup: the earliest wake of a free or expired job walks the due index
|
|
170
|
+
// and stops at the first, and the earliest held expiry reads the lease rows, one per job. Postgres compares by the
|
|
171
|
+
// statement's clock, not the transaction's: `using` may be a transaction that began before a lease expired. The one
|
|
172
|
+
// parameter is the JSON list of jobs to look at, or null for every job.
|
|
173
|
+
const SQL_NEXT: DialectTexts = {
|
|
174
|
+
postgres: `select
|
|
175
|
+
(select w.due_at from ${W} w left join ${L} l on l.job = w.job
|
|
176
|
+
where (l.holder is null or l.expires_at <= clock_timestamp())
|
|
177
|
+
and ($1::jsonb is null or w.job in (select jsonb_array_elements_text($1::jsonb))) order by w.due_at limit 1) as wake,
|
|
178
|
+
(select ${PG_EPOCH_MS('min(expires_at)')} from ${L}
|
|
179
|
+
where holder is not null and ($1::jsonb is null or job in (select jsonb_array_elements_text($1::jsonb)))) as held,
|
|
180
|
+
${PG_EPOCH_MS('clock_timestamp()')} as now`,
|
|
181
|
+
sqlite: `select
|
|
182
|
+
(select w.due_at from ${W} w left join ${L} l on l.job = w.job
|
|
183
|
+
where (l.holder is null or l.expires_at <= ${SQLITE_NOW})
|
|
184
|
+
and (?1 is null or w.job in (select value from json_each(?1))) order by w.due_at limit 1) as wake,
|
|
185
|
+
(select ${SQLITE_EPOCH_MS('min(expires_at)')} from ${L}
|
|
186
|
+
where holder is not null and (?1 is null or job in (select value from json_each(?1)))) as held,
|
|
187
|
+
${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// One row; a lower generation leaves it as it is, keys included, and the row answers what is stored after the write.
|
|
191
|
+
const SQL_HOLD_SCHEDULE: DialectTexts = {
|
|
192
|
+
postgres: `insert into ${S} (id, generation, declared) values (1, $1, $2)
|
|
193
|
+
on conflict (id) do update set generation = greatest(${S}.generation, excluded.generation),
|
|
194
|
+
declared = case when excluded.generation >= ${S}.generation then excluded.declared else ${S}.declared end
|
|
195
|
+
returning generation`,
|
|
196
|
+
sqlite: `insert into ${S} (id, generation, declared) values (1, ?1, ?2)
|
|
197
|
+
on conflict (id) do update set generation = max(${S}.generation, excluded.generation),
|
|
198
|
+
declared = case when excluded.generation >= ${S}.generation then excluded.declared else ${S}.declared end
|
|
199
|
+
returning generation`,
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// A seed only adds a missing wake. `do nothing` takes no lock on a row that exists, so a replica's lease, taken while
|
|
203
|
+
// a seed is open, still marks that row owned (`SQL_OWN` skips a locked row).
|
|
204
|
+
const SQL_SEED: DialectTexts = {
|
|
205
|
+
postgres: `insert into ${W} (id, ${COLUMNS}) values ($1::uuid, $2, $3::bigint, $4, 0, $5) on conflict (dedupe) where dedupe is not null do nothing`,
|
|
206
|
+
sqlite: `insert into ${W} (id, ${COLUMNS}) values (?1, ?2, cast(?3 as integer), ?4, 0, ?5) on conflict (dedupe) where dedupe is not null do nothing`,
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// The keys the stored generation declares, read by a finish in its transaction; `for share` waits for a seed under way.
|
|
210
|
+
const SQL_SCHEDULE_DECLARED: DialectTexts = {
|
|
211
|
+
postgres: `select declared from ${S} where id = 1 for share`,
|
|
212
|
+
sqlite: `select declared from ${S} where id = 1`,
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Whether the stored schedule declares `key`: its row's keys, read in `transaction`. No row declares nothing. */
|
|
216
|
+
async function scheduleDeclares(transaction: Session, key: string): Promise<boolean> {
|
|
217
|
+
const [row] = await rows(transaction, SQL_SCHEDULE_DECLARED, [])
|
|
218
|
+
if (row === undefined) {
|
|
219
|
+
return false
|
|
220
|
+
}
|
|
221
|
+
const declared: unknown = typeof row['declared'] === 'string' ? JSON.parse(row['declared']) : undefined
|
|
222
|
+
if (!Array.isArray(declared)) {
|
|
223
|
+
throw new QueryRefusedError('unexpected_row', `${S}.declared is not a list of keys`)
|
|
224
|
+
}
|
|
225
|
+
return declared.includes(key)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* A schedule generation: a lowercase UUIDv7 (version 7, the RFC variant), whose text order is its time order. Any other
|
|
230
|
+
* UUID would order deploys at random, and a later deploy that sorted lower would never take the schedule.
|
|
231
|
+
*/
|
|
232
|
+
const SCHEDULE_GENERATION = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
|
|
233
|
+
|
|
234
|
+
/** The declared jobs `reconcile` keeps, checked: a list of jobs with their expressions. */
|
|
235
|
+
function declaredJobs(declared: readonly DeclaredJob[]): DeclaredJob[] {
|
|
236
|
+
if (!Array.isArray(declared)) {
|
|
237
|
+
throw new QueryRefusedError('invalid_argument', 'the declared jobs are a list of jobs with their expressions')
|
|
238
|
+
}
|
|
239
|
+
return declared.map((entry: unknown) => {
|
|
240
|
+
const job: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'job') : undefined
|
|
241
|
+
const expression: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'expression') : undefined
|
|
242
|
+
return { job: nonEmpty(job, 'a declared job'), expression: nonEmpty(expression, "a declared job's expression") }
|
|
243
|
+
})
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Each fire `keepSchedule` seeds, checked before its transaction: the declared job and the cron wake of its next fire. */
|
|
247
|
+
function scheduledFires(fires: readonly ScheduledFire[]): {
|
|
248
|
+
readonly declared: DeclaredJob[]
|
|
249
|
+
readonly wakes: { readonly job: string; readonly parameters: readonly FixedParameter[] }[]
|
|
250
|
+
} {
|
|
251
|
+
const declared = declaredJobs(fires)
|
|
252
|
+
const wakes = fires.flatMap((fire, index) => {
|
|
253
|
+
const dueAt: unknown = Reflect.get(fire, 'dueAt')
|
|
254
|
+
const job = declared[index]
|
|
255
|
+
if (dueAt === null || job === undefined) {
|
|
256
|
+
return []
|
|
257
|
+
}
|
|
258
|
+
if (!(dueAt instanceof Date)) {
|
|
259
|
+
throw new QueryRefusedError('invalid_argument', "a fire's due time is a valid time or null")
|
|
260
|
+
}
|
|
261
|
+
return [{ job: job.job, parameters: newWake({ job: job.job, reason: 'cron', dueAt, dedupe: `cron:${job.job}:${job.expression}` }) }]
|
|
262
|
+
})
|
|
263
|
+
return { declared, wakes }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const SQL_CLOCK: DialectTexts = {
|
|
267
|
+
postgres: `select ${PG_EPOCH_MS('clock_timestamp()')} as now`,
|
|
268
|
+
sqlite: `select ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const SQL_EXPIRED_HOLDERS: DialectTexts = {
|
|
272
|
+
postgres: `select job from ${L} where holder is not null and expires_at <= clock_timestamp() order by job`,
|
|
273
|
+
sqlite: `select job from ${L} where holder is not null and expires_at <= ${SQLITE_NOW} order by job`,
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const SQL_CONSUME: DialectTexts = {
|
|
277
|
+
postgres: `delete from ${W} where job = $1 and owned`,
|
|
278
|
+
sqlite: `delete from ${W} where job = ?1 and owned = 1`,
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const SQL_RETRY: DialectTexts = {
|
|
282
|
+
postgres: `update ${W} set due_at = $2::bigint, attempt = attempt + 1, owned = false where job = $1 and owned`,
|
|
283
|
+
sqlite: `update ${W} set due_at = cast(?2 as integer), attempt = attempt + 1, owned = 0 where job = ?1 and owned = 1`,
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const SQL_DROP_CLAIM: DialectTexts = {
|
|
287
|
+
postgres: `delete from ${W} where job = $1 and dedupe = $2`,
|
|
288
|
+
sqlite: `delete from ${W} where job = ?1 and dedupe = ?2`,
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// A wake is kept when its job is declared and it is no cron wake, or is the cron wake of the declared expression.
|
|
292
|
+
const SQL_RECONCILE: DialectTexts = {
|
|
293
|
+
postgres: `delete from ${W} where not exists (select 1 from jsonb_to_recordset($1::jsonb) as d(job text, expression text)
|
|
294
|
+
where d.job = ${W}.job and (${W}.reason <> 'cron' or ${W}.dedupe = 'cron:' || d.job || ':' || d.expression)) returning id`,
|
|
295
|
+
sqlite: `delete from ${W} where not exists (select 1 from json_each(?1) d
|
|
296
|
+
where json_extract(d.value, '$.job') = ${W}.job
|
|
297
|
+
and (${W}.reason <> 'cron' or ${W}.dedupe = 'cron:' || json_extract(d.value, '$.job') || ':' || json_extract(d.value, '$.expression'))) returning id`,
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Only a wake still ahead moves: moving an overdue one to now would postpone it.
|
|
301
|
+
const SQL_HASTEN: DialectTexts = {
|
|
302
|
+
postgres: `update ${W} set due_at = ${PG_EPOCH_MS('now()')}
|
|
303
|
+
where id::text in (select jsonb_array_elements_text($1::jsonb)) and due_at > ${PG_EPOCH_MS('now()')} returning id::text as id`,
|
|
304
|
+
sqlite: `update ${W} set due_at = ${SQLITE_EPOCH_MS(SQLITE_NOW)}
|
|
305
|
+
where id in (select value from json_each(?1)) and due_at > ${SQLITE_EPOCH_MS(SQLITE_NOW)} returning id`,
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function record(row: unknown): Readonly<Record<string, unknown>> {
|
|
309
|
+
if (typeof row !== 'object' || row === null) {
|
|
310
|
+
throw new QueryRefusedError('unexpected_row', `${W} answered a row that is not an object`)
|
|
311
|
+
}
|
|
312
|
+
return Object.fromEntries(Object.entries(row))
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function rows(session: Session, texts: DialectTexts, parameters: readonly FixedParameter[]): Promise<Readonly<Record<string, unknown>>[]> {
|
|
316
|
+
return (await runFixedStatement(session, texts[session.dialect], parameters)).map(record)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** BIGINT comes back from Postgres as a string, INTEGER from SQLite as a number. */
|
|
320
|
+
function wholeNumber(value: unknown, what: string): number {
|
|
321
|
+
const parsed = typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value
|
|
322
|
+
if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed)) {
|
|
323
|
+
throw new QueryRefusedError('unexpected_row', `${what} is not a whole number`)
|
|
324
|
+
}
|
|
325
|
+
return parsed
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** BOOLEAN comes back from Postgres as a boolean, an INTEGER flag from SQLite as 0 or 1. */
|
|
329
|
+
function flag(value: unknown, what: string): boolean {
|
|
330
|
+
if (value === true || value === 1) {
|
|
331
|
+
return true
|
|
332
|
+
}
|
|
333
|
+
if (value === false || value === 0) {
|
|
334
|
+
return false
|
|
335
|
+
}
|
|
336
|
+
throw new QueryRefusedError('unexpected_row', `${what} is not a flag`)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function wakeOf(row: Readonly<Record<string, unknown>>): Wake {
|
|
340
|
+
const { id, job, reason, due_at: dueAt, attempt, dedupe, owned } = row
|
|
341
|
+
if (typeof id !== 'string' || typeof job !== 'string' || (dedupe !== null && typeof dedupe !== 'string')) {
|
|
342
|
+
throw new QueryRefusedError('unexpected_row', `${W} came back in another shape than its migration declares`)
|
|
343
|
+
}
|
|
344
|
+
const known = WAKE_REASONS.find((candidate) => candidate === reason)
|
|
345
|
+
if (known === undefined) {
|
|
346
|
+
throw new QueryRefusedError('unexpected_row', `${W}.reason is not a wake reason`)
|
|
347
|
+
}
|
|
348
|
+
return freeze({
|
|
349
|
+
id,
|
|
350
|
+
job,
|
|
351
|
+
reason: known,
|
|
352
|
+
dueAt: new Date(wholeNumber(dueAt, `${W}.due_at`)),
|
|
353
|
+
attempt: wholeNumber(attempt, `${W}.attempt`),
|
|
354
|
+
dedupe,
|
|
355
|
+
owned: flag(owned, `${W}.owned`),
|
|
356
|
+
})
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function epochOf(value: unknown, what: string): number {
|
|
360
|
+
const time = value instanceof Date ? value.getTime() : Number.NaN
|
|
361
|
+
if (!Number.isSafeInteger(time)) {
|
|
362
|
+
throw new QueryRefusedError('invalid_argument', `${what} is a valid time`)
|
|
363
|
+
}
|
|
364
|
+
return time
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function nonEmpty(value: unknown, what: string): string {
|
|
368
|
+
if (typeof value !== 'string' || value === '') {
|
|
369
|
+
throw new QueryRefusedError('invalid_argument', `${what} is a non-empty string`)
|
|
370
|
+
}
|
|
371
|
+
return value
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function newWake(wake: NewWake): readonly FixedParameter[] {
|
|
375
|
+
const job = nonEmpty(wake.job, "a wake's job")
|
|
376
|
+
if (!WAKE_REASONS.some((reason) => reason === wake.reason)) {
|
|
377
|
+
throw new QueryRefusedError('invalid_argument', `a wake's reason is one of ${WAKE_REASONS.join(', ')}`)
|
|
378
|
+
}
|
|
379
|
+
const due = epochOf(wake.dueAt, "a wake's due time")
|
|
380
|
+
const dedupe = wake.dedupe === undefined ? null : nonEmpty(wake.dedupe, "a wake's dedupe key")
|
|
381
|
+
return [uuidv7(), job, String(due), wake.reason, dedupe]
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Inserts the wake `newWake` checked, in `transaction`; refuses a key another job holds, which rolls it back. */
|
|
385
|
+
async function insert(transaction: Session, parameters: readonly FixedParameter[], job: string): Promise<Wake> {
|
|
386
|
+
const [row] = await rows(transaction, SQL_SCHEDULE, parameters)
|
|
387
|
+
if (row === undefined) {
|
|
388
|
+
throw new QueryRefusedError('invalid_argument', `the dedupe key of this wake of '${job}' is held by another job's wake`)
|
|
389
|
+
}
|
|
390
|
+
return wakeOf(row)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
|
|
395
|
+
* lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
|
|
396
|
+
*/
|
|
397
|
+
export function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null {
|
|
398
|
+
if (wakes === undefined) {
|
|
399
|
+
return outcome === 'succeeded' ? freeze({ kind: 'completed' }) : null
|
|
400
|
+
}
|
|
401
|
+
if (wakes.kind === 'retry') {
|
|
402
|
+
if (outcome !== 'failed') {
|
|
403
|
+
throw new QueryRefusedError('invalid_argument', 'only a failed run retries its wakes')
|
|
404
|
+
}
|
|
405
|
+
epochOf(wakes.at, 'a retry')
|
|
406
|
+
return freeze({ kind: 'retry', at: wakes.at })
|
|
407
|
+
}
|
|
408
|
+
if (wakes.kind !== 'completed') {
|
|
409
|
+
throw new QueryRefusedError('invalid_argument', "a finish's wakes are completed or retried")
|
|
410
|
+
}
|
|
411
|
+
if (wakes.nextCron === undefined) {
|
|
412
|
+
return freeze({ kind: 'completed' })
|
|
413
|
+
}
|
|
414
|
+
nonEmpty(wakes.nextCron.expression, "a cron wake's expression")
|
|
415
|
+
epochOf(wakes.nextCron.dueAt, "a cron wake's due time")
|
|
416
|
+
const { expression, dueAt, scheduled } = wakes.nextCron
|
|
417
|
+
if (scheduled !== undefined && typeof scheduled !== 'boolean') {
|
|
418
|
+
throw new QueryRefusedError('invalid_argument', "a cron wake's schedule guard is a boolean")
|
|
419
|
+
}
|
|
420
|
+
return freeze({ kind: 'completed', nextCron: freeze(scheduled === true ? { expression, dueAt, scheduled } : { expression, dueAt }) })
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** The runtime's projection of a change, in its transaction; nothing without one. */
|
|
424
|
+
function projectionOf(runtime: () => DataLayerRuntime): (transaction: Session) => Promise<void> {
|
|
425
|
+
return async (transaction) => {
|
|
426
|
+
await runtime().projectWakes?.(transaction)
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
|
|
432
|
+
* fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
|
|
433
|
+
* runs the runtime's projection.
|
|
434
|
+
*/
|
|
435
|
+
export function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection {
|
|
436
|
+
const project = projectionOf(runtime)
|
|
437
|
+
return async (transaction: Session, job: string, change: LeaseChange): Promise<void> => {
|
|
438
|
+
if (change.kind === 'acquired') {
|
|
439
|
+
await rows(transaction, SQL_OWN, [job])
|
|
440
|
+
}
|
|
441
|
+
if (change.kind === 'finished' && change.wakes !== null) {
|
|
442
|
+
if (change.wakes.kind === 'retry') {
|
|
443
|
+
await rows(transaction, SQL_RETRY, [job, String(change.wakes.at.getTime())])
|
|
444
|
+
} else {
|
|
445
|
+
const next = change.wakes.nextCron
|
|
446
|
+
const key = next === undefined ? null : `cron:${job}:${next.expression}`
|
|
447
|
+
// The schedule row before the wakes, the order `keepSchedule` takes them in: a seed that holds the row waits
|
|
448
|
+
// for no delete of this finish, so the two never wait on each other.
|
|
449
|
+
const declared = next?.scheduled === true && key !== null ? await scheduleDeclares(transaction, key) : true
|
|
450
|
+
await rows(transaction, SQL_CONSUME, [job])
|
|
451
|
+
if (next !== undefined && key !== null && declared) {
|
|
452
|
+
await insert(transaction, newWake({ job, reason: 'cron', dueAt: next.dueAt, dedupe: key }), job)
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (change.kind === 'finished' || change.kind === 'reaped') {
|
|
457
|
+
await rows(transaction, SQL_DISOWN, [job])
|
|
458
|
+
}
|
|
459
|
+
await project(transaction)
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** A job's one claim wake: each attempt's first claim replaces it. */
|
|
464
|
+
const claimKey = (job: string): string => `claim:${job}`
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Each attempt's earliest claim re-arm so far (`null`: none), by its fence: a later claim of the attempt, over another
|
|
468
|
+
* queue or `where`, never postpones it. A claim whose transaction rolled back may leave it early, which costs one run.
|
|
469
|
+
*/
|
|
470
|
+
const attemptRearms = new WeakMap<LeaseFence, number | null>()
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
|
|
474
|
+
* transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
|
|
475
|
+
* left; each later claim keeps the earliest re-arm of the attempt.
|
|
476
|
+
*/
|
|
477
|
+
export async function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void> {
|
|
478
|
+
const candidate = dueAt === null ? null : epochOf(dueAt, 'a claim re-arm')
|
|
479
|
+
const earlier = attemptRearms.get(fence) ?? null
|
|
480
|
+
const due = earlier === null ? candidate : candidate === null ? earlier : Math.min(earlier, candidate)
|
|
481
|
+
attemptRearms.set(fence, due)
|
|
482
|
+
await rows(transaction, SQL_DROP_CLAIM, [fence.job, claimKey(fence.job)])
|
|
483
|
+
if (due !== null) {
|
|
484
|
+
await insert(transaction, newWake({ job: fence.job, reason: 'claim', dueAt: new Date(due), dedupe: claimKey(fence.job) }), fence.job)
|
|
485
|
+
}
|
|
486
|
+
await runtime.projectWakes?.(transaction)
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** The jobs `next` looks at, as its JSON parameter: `null` for every job. */
|
|
490
|
+
function jobsFilter(jobs: readonly string[] | undefined): FixedParameter {
|
|
491
|
+
if (jobs === undefined) {
|
|
492
|
+
return null
|
|
493
|
+
}
|
|
494
|
+
if (!Array.isArray(jobs)) {
|
|
495
|
+
throw new QueryRefusedError('invalid_argument', 'the jobs the next wake is read for are a list of job names')
|
|
496
|
+
}
|
|
497
|
+
return JSON.stringify(jobs.map((job: unknown) => nonEmpty(job, 'a job the next wake is read for')))
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** The next wake, in epoch milliseconds, and the database's now as the same statement read it. */
|
|
501
|
+
async function nextAndNow(
|
|
502
|
+
session: Session,
|
|
503
|
+
jobs: readonly string[] | undefined,
|
|
504
|
+
): Promise<{ readonly next: number | null; readonly now: () => number }> {
|
|
505
|
+
const [{ wake = null, held = null, now = null } = {}] = await rows(session, SQL_NEXT, [jobsFilter(jobs)])
|
|
506
|
+
const candidates = [wake, held].filter((value) => value !== null).map((value) => wholeNumber(value, 'the next wake'))
|
|
507
|
+
return { next: candidates.length === 0 ? null : Math.min(...candidates), now: () => wholeNumber(now, "the database's now") }
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
|
|
511
|
+
const session = () => sessionOf(runtime())
|
|
512
|
+
const project = projectionOf(runtime)
|
|
513
|
+
return freeze({
|
|
514
|
+
async schedule(wake: NewWake, using?: Session): Promise<Wake> {
|
|
515
|
+
const parameters = newWake(wake)
|
|
516
|
+
return await (using ?? session()).transaction(async (transaction) => {
|
|
517
|
+
const scheduled = await insert(transaction, parameters, wake.job)
|
|
518
|
+
await project(transaction)
|
|
519
|
+
return scheduled
|
|
520
|
+
})
|
|
521
|
+
},
|
|
522
|
+
|
|
523
|
+
async pending(job: string): Promise<readonly Wake[]> {
|
|
524
|
+
return freeze((await rows(session(), SQL_PENDING, [job])).map(wakeOf))
|
|
525
|
+
},
|
|
526
|
+
|
|
527
|
+
async next(using?: Session, jobs?: readonly string[]): Promise<Date | null> {
|
|
528
|
+
const { next } = await nextAndNow(using ?? session(), jobs)
|
|
529
|
+
return next === null ? null : new Date(next)
|
|
530
|
+
},
|
|
531
|
+
|
|
532
|
+
async untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null> {
|
|
533
|
+
const { next, now } = await nextAndNow(using ?? session(), jobs)
|
|
534
|
+
return next === null ? null : next - now()
|
|
535
|
+
},
|
|
536
|
+
|
|
537
|
+
async keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean> {
|
|
538
|
+
if (typeof generation !== 'string' || !SCHEDULE_GENERATION.test(generation)) {
|
|
539
|
+
throw new QueryRefusedError('invalid_argument', 'a schedule generation is a lowercase UUIDv7')
|
|
540
|
+
}
|
|
541
|
+
const { declared, wakes } = scheduledFires(fires)
|
|
542
|
+
const keys = JSON.stringify(declared.map(({ job, expression }) => `cron:${job}:${expression}`))
|
|
543
|
+
return await session().transaction(async (transaction) => {
|
|
544
|
+
// The upsert locks the row until this transaction commits: the reconcile and the seed below happen under it,
|
|
545
|
+
// and a finish that reads the declared keys waits for them.
|
|
546
|
+
const [{ generation: stored } = {}] = await rows(transaction, SQL_HOLD_SCHEDULE, [generation, keys])
|
|
547
|
+
if (typeof stored !== 'string') {
|
|
548
|
+
throw new QueryRefusedError('unexpected_row', `${S} came back in another shape than its migration declares`)
|
|
549
|
+
}
|
|
550
|
+
if (stored !== generation) {
|
|
551
|
+
return false
|
|
552
|
+
}
|
|
553
|
+
await rows(transaction, SQL_RECONCILE, [JSON.stringify(declared)])
|
|
554
|
+
for (const wake of wakes) {
|
|
555
|
+
await rows(transaction, SQL_SEED, wake.parameters)
|
|
556
|
+
}
|
|
557
|
+
await project(transaction)
|
|
558
|
+
return true
|
|
559
|
+
})
|
|
560
|
+
},
|
|
561
|
+
|
|
562
|
+
async now(using?: Session): Promise<Date> {
|
|
563
|
+
const [{ now = null } = {}] = await rows(using ?? session(), SQL_CLOCK, [])
|
|
564
|
+
return new Date(wholeNumber(now, "the database's now"))
|
|
565
|
+
},
|
|
566
|
+
|
|
567
|
+
async expiredHolders(): Promise<readonly string[]> {
|
|
568
|
+
return freeze(
|
|
569
|
+
(await rows(session(), SQL_EXPIRED_HOLDERS, [])).map(({ job }) => {
|
|
570
|
+
if (typeof job !== 'string') {
|
|
571
|
+
throw new QueryRefusedError('unexpected_row', `${L} came back in another shape than its migration declares`)
|
|
572
|
+
}
|
|
573
|
+
return job
|
|
574
|
+
}),
|
|
575
|
+
)
|
|
576
|
+
},
|
|
577
|
+
|
|
578
|
+
async reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number> {
|
|
579
|
+
const jobs = declaredJobs(declared)
|
|
580
|
+
return await (using ?? session()).transaction(async (transaction) => {
|
|
581
|
+
const removed = await rows(transaction, SQL_RECONCILE, [JSON.stringify(jobs)])
|
|
582
|
+
await project(transaction)
|
|
583
|
+
return removed.length
|
|
584
|
+
})
|
|
585
|
+
},
|
|
586
|
+
|
|
587
|
+
async hasten(ids: readonly string[]): Promise<number> {
|
|
588
|
+
refuseInProduction("the wakes store's hasten")
|
|
589
|
+
if (!Array.isArray(ids)) {
|
|
590
|
+
throw new QueryRefusedError('invalid_argument', 'the wakes to hasten are a list of wake ids')
|
|
591
|
+
}
|
|
592
|
+
const named = ids.map((id: unknown) => nonEmpty(id, 'a wake id'))
|
|
593
|
+
return await session().transaction(async (transaction) => {
|
|
594
|
+
const moved = await rows(transaction, SQL_HASTEN, [JSON.stringify(named)])
|
|
595
|
+
await project(transaction)
|
|
596
|
+
return moved.length
|
|
597
|
+
})
|
|
598
|
+
},
|
|
599
|
+
})
|
|
600
|
+
}
|