@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +34 -3
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/capability.ts +5 -0
- package/src/codegen-sqlite.ts +154 -0
- package/src/codegen.ts +59 -9
- package/src/database.ts +227 -61
- package/src/errors.ts +2 -2
- package/src/file-columns.ts +4 -1
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +8 -0
- package/src/index.ts +9 -1
- package/src/job-leases.ts +210 -54
- package/src/job-wakes.ts +450 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +163 -0
- package/src/migrations.ts +25 -0
- package/src/nodes.ts +64 -9
- package/src/orm-types.ts +2 -2
- package/src/orm.ts +68 -35
- package/src/policy.ts +8 -2
- package/src/postgres.ts +26 -0
- package/src/registry.ts +11 -2
- package/src/sql.ts +216 -473
- package/src/sqlite-bun.ts +122 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +224 -0
- package/src/store.ts +362 -93
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +16 -0
- package/src/temporal.ts +115 -9
- package/src/testing-shared.ts +733 -0
- package/src/testing-sqlite.ts +513 -0
- package/src/testing.ts +169 -482
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/capability.d.ts +5 -0
- package/types/src/codegen-sqlite.d.ts +6 -0
- package/types/src/codegen.d.ts +30 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/errors.d.ts +2 -2
- package/types/src/framework.d.ts +11 -5
- package/types/src/index.d.ts +1 -1
- package/types/src/job-leases.d.ts +32 -4
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +1 -0
- package/types/src/nodes.d.ts +13 -2
- package/types/src/orm-types.d.ts +2 -2
- package/types/src/policy.d.ts +4 -0
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +10 -2
- package/types/src/sql.d.ts +29 -21
- package/types/src/sqlite-bun.d.ts +13 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +26 -9
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +10 -0
- package/types/src/temporal.d.ts +21 -0
- package/types/src/testing-shared.d.ts +201 -0
- package/types/src/testing-sqlite.d.ts +22 -0
- package/types/src/testing.d.ts +2 -93
package/src/job-wakes.ts
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
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.
|
|
7
|
+
|
|
8
|
+
import { uuidv7 } from '@fabrika/platform'
|
|
9
|
+
import { freeze } from './builtins'
|
|
10
|
+
import type { LeaseFence } from './capability'
|
|
11
|
+
import { type FixedParameter, runFixedStatement, type Session, sessionOf } from './database'
|
|
12
|
+
import { QueryRefusedError } from './errors'
|
|
13
|
+
import type { DialectTexts, JobOutcome, LeaseChange, LeaseProjection } from './job-leases'
|
|
14
|
+
import { JOB_LEASES_TABLE, JOB_WAKES_TABLE } from './migrations'
|
|
15
|
+
import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
|
|
16
|
+
import { refuseInProduction } from './production'
|
|
17
|
+
import type { DataLayerRuntime } from './store'
|
|
18
|
+
|
|
19
|
+
export const WAKE_REASONS = ['cron', 'kick', 'claim', 'retry'] as const
|
|
20
|
+
|
|
21
|
+
export type WakeReason = (typeof WAKE_REASONS)[number]
|
|
22
|
+
|
|
23
|
+
export interface NewWake {
|
|
24
|
+
readonly job: string
|
|
25
|
+
readonly reason: WakeReason
|
|
26
|
+
readonly dueAt: Date
|
|
27
|
+
/** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
|
|
28
|
+
readonly dedupe?: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface Wake {
|
|
32
|
+
readonly id: string
|
|
33
|
+
readonly job: string
|
|
34
|
+
readonly reason: WakeReason
|
|
35
|
+
readonly dueAt: Date
|
|
36
|
+
/** How many failed runs moved this wake (`retry`). */
|
|
37
|
+
readonly attempt: number
|
|
38
|
+
readonly dedupe: string | null
|
|
39
|
+
/** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
|
|
40
|
+
readonly owned: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
|
|
45
|
+
* transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
|
|
46
|
+
* leaves the wakes as they are.
|
|
47
|
+
*/
|
|
48
|
+
export type FinishWakes =
|
|
49
|
+
/** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
|
|
50
|
+
| { readonly kind: 'completed'; readonly nextCron?: { readonly expression: string; readonly dueAt: Date } }
|
|
51
|
+
/** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
|
|
52
|
+
| { readonly kind: 'retry'; readonly at: Date }
|
|
53
|
+
|
|
54
|
+
export interface JobWakes {
|
|
55
|
+
/**
|
|
56
|
+
* Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
|
|
57
|
+
* keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
|
|
58
|
+
* run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
|
|
59
|
+
* a key another job holds is refused.
|
|
60
|
+
*/
|
|
61
|
+
schedule(wake: NewWake, using?: Session): Promise<Wake>
|
|
62
|
+
/** The pending wakes of `job`, earliest first. */
|
|
63
|
+
pending(job: string): Promise<readonly Wake[]>
|
|
64
|
+
/**
|
|
65
|
+
* When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
|
|
66
|
+
* held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
|
|
67
|
+
*/
|
|
68
|
+
next(using?: Session): Promise<Date | null>
|
|
69
|
+
/** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
|
|
70
|
+
untilNext(using?: Session): Promise<number | null>
|
|
71
|
+
/** The database's clock, read in `using` when given: a wake due now is due by it. */
|
|
72
|
+
now(using?: Session): Promise<Date>
|
|
73
|
+
/**
|
|
74
|
+
* Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
|
|
75
|
+
* each declared job's cron wake whose key names another expression; answers how many it deleted.
|
|
76
|
+
*/
|
|
77
|
+
reconcile(declared: readonly DeclaredJob[]): Promise<number>
|
|
78
|
+
/**
|
|
79
|
+
* The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
|
|
80
|
+
* now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
|
|
81
|
+
*/
|
|
82
|
+
hasten(ids: readonly string[]): Promise<number>
|
|
83
|
+
/**
|
|
84
|
+
* The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
|
|
85
|
+
* alarm through `next` until someone reaps it.
|
|
86
|
+
*/
|
|
87
|
+
expiredHolders(): Promise<readonly string[]>
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
|
|
91
|
+
export interface DeclaredJob {
|
|
92
|
+
readonly job: string
|
|
93
|
+
readonly expression: string
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const W = JOB_WAKES_TABLE
|
|
97
|
+
const L = JOB_LEASES_TABLE
|
|
98
|
+
const COLUMNS = 'job, due_at, reason, attempt, dedupe'
|
|
99
|
+
const SELECTED = `${COLUMNS}, owned`
|
|
100
|
+
const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
|
|
101
|
+
|
|
102
|
+
/** A stored timestamp as epoch milliseconds, in each dialect. */
|
|
103
|
+
const PG_EPOCH_MS = (column: string): string => `floor(extract(epoch from ${column}) * 1000)::bigint`
|
|
104
|
+
const SQLITE_EPOCH_MS = (column: string): string => `cast(round((julianday(${column}) - 2440587.5) * 86400000) as integer)`
|
|
105
|
+
|
|
106
|
+
/** The start of the job's current run, in epoch milliseconds: the wakes due by then are the ones it takes. */
|
|
107
|
+
const PG_RUN_START = `(select ${PG_EPOCH_MS('last_started_at')} from ${L} where job = $1)`
|
|
108
|
+
const SQLITE_RUN_START = `(select ${SQLITE_EPOCH_MS('last_started_at')} from ${L} where job = ?1)`
|
|
109
|
+
|
|
110
|
+
const SQL_SCHEDULE: DialectTexts = {
|
|
111
|
+
// The update applies only to the same job's row, so a key another job holds answers no row.
|
|
112
|
+
postgres: `insert into ${W} (id, ${COLUMNS}) values ($1::uuid, $2, $3::bigint, $4, 0, $5)
|
|
113
|
+
on conflict (dedupe) where dedupe is not null do update set due_at = least(${W}.due_at, excluded.due_at),
|
|
114
|
+
owned = ${W}.owned and excluded.reason = 'cron' where ${W}.job = excluded.job
|
|
115
|
+
returning id::text as id, ${SELECTED}`,
|
|
116
|
+
sqlite: `insert into ${W} (id, ${COLUMNS}) values (?1, ?2, cast(?3 as integer), ?4, 0, ?5)
|
|
117
|
+
on conflict (dedupe) where dedupe is not null do update set due_at = min(${W}.due_at, excluded.due_at),
|
|
118
|
+
owned = ${W}.owned and excluded.reason = 'cron' where ${W}.job = excluded.job
|
|
119
|
+
returning id, ${SELECTED}`,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const SQL_PENDING: DialectTexts = {
|
|
123
|
+
postgres: `select id::text as id, ${SELECTED} from ${W} where job = $1 order by due_at, id`,
|
|
124
|
+
sqlite: `select id, ${SELECTED} from ${W} where job = ?1 order by due_at, id`,
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 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
|
|
128
|
+
// written, and that write leaves it unowned: the lease is taken without waiting for it.
|
|
129
|
+
const SQL_OWN: DialectTexts = {
|
|
130
|
+
postgres: `update ${W} set owned = coalesce(${W}.due_at <= ${PG_RUN_START}, false)
|
|
131
|
+
where id in (select id from ${W} where job = $1 for update skip locked)`,
|
|
132
|
+
sqlite: `update ${W} set owned = coalesce(due_at <= ${SQLITE_RUN_START}, 0) where job = ?1`,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const SQL_DISOWN: DialectTexts = {
|
|
136
|
+
postgres: `update ${W} set owned = false where id in (select id from ${W} where job = $1 and owned for update skip locked)`,
|
|
137
|
+
sqlite: `update ${W} set owned = 0 where job = ?1 and owned = 1`,
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Two candidates, each one index-ordered or per-job lookup: the earliest wake of a free or expired job walks the due index
|
|
141
|
+
// and stops at the first, and the earliest held expiry reads the lease rows, one per job. Postgres compares by the
|
|
142
|
+
// statement's clock, not the transaction's: `using` may be a transaction that began before a lease expired.
|
|
143
|
+
const SQL_NEXT: DialectTexts = {
|
|
144
|
+
postgres: `select
|
|
145
|
+
(select w.due_at from ${W} w left join ${L} l on l.job = w.job
|
|
146
|
+
where l.holder is null or l.expires_at <= clock_timestamp() order by w.due_at limit 1) as wake,
|
|
147
|
+
(select ${PG_EPOCH_MS('min(expires_at)')} from ${L} where holder is not null) as held,
|
|
148
|
+
${PG_EPOCH_MS('clock_timestamp()')} as now`,
|
|
149
|
+
sqlite: `select
|
|
150
|
+
(select w.due_at from ${W} w left join ${L} l on l.job = w.job
|
|
151
|
+
where l.holder is null or l.expires_at <= ${SQLITE_NOW} order by w.due_at limit 1) as wake,
|
|
152
|
+
(select ${SQLITE_EPOCH_MS('min(expires_at)')} from ${L} where holder is not null) as held,
|
|
153
|
+
${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const SQL_CLOCK: DialectTexts = {
|
|
157
|
+
postgres: `select ${PG_EPOCH_MS('clock_timestamp()')} as now`,
|
|
158
|
+
sqlite: `select ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const SQL_EXPIRED_HOLDERS: DialectTexts = {
|
|
162
|
+
postgres: `select job from ${L} where holder is not null and expires_at <= clock_timestamp() order by job`,
|
|
163
|
+
sqlite: `select job from ${L} where holder is not null and expires_at <= ${SQLITE_NOW} order by job`,
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const SQL_CONSUME: DialectTexts = {
|
|
167
|
+
postgres: `delete from ${W} where job = $1 and owned`,
|
|
168
|
+
sqlite: `delete from ${W} where job = ?1 and owned = 1`,
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const SQL_RETRY: DialectTexts = {
|
|
172
|
+
postgres: `update ${W} set due_at = $2::bigint, attempt = attempt + 1, owned = false where job = $1 and owned`,
|
|
173
|
+
sqlite: `update ${W} set due_at = cast(?2 as integer), attempt = attempt + 1, owned = 0 where job = ?1 and owned = 1`,
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const SQL_DROP_CLAIM: DialectTexts = {
|
|
177
|
+
postgres: `delete from ${W} where job = $1 and dedupe = $2`,
|
|
178
|
+
sqlite: `delete from ${W} where job = ?1 and dedupe = ?2`,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// A wake is kept when its job is declared and it is no cron wake, or is the cron wake of the declared expression.
|
|
182
|
+
const SQL_RECONCILE: DialectTexts = {
|
|
183
|
+
postgres: `delete from ${W} where not exists (select 1 from jsonb_to_recordset($1::jsonb) as d(job text, expression text)
|
|
184
|
+
where d.job = ${W}.job and (${W}.reason <> 'cron' or ${W}.dedupe = 'cron:' || d.job || ':' || d.expression)) returning id`,
|
|
185
|
+
sqlite: `delete from ${W} where not exists (select 1 from json_each(?1) d
|
|
186
|
+
where json_extract(d.value, '$.job') = ${W}.job
|
|
187
|
+
and (${W}.reason <> 'cron' or ${W}.dedupe = 'cron:' || json_extract(d.value, '$.job') || ':' || json_extract(d.value, '$.expression'))) returning id`,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Only a wake still ahead moves: moving an overdue one to now would postpone it.
|
|
191
|
+
const SQL_HASTEN: DialectTexts = {
|
|
192
|
+
postgres: `update ${W} set due_at = ${PG_EPOCH_MS('now()')}
|
|
193
|
+
where id::text in (select jsonb_array_elements_text($1::jsonb)) and due_at > ${PG_EPOCH_MS('now()')} returning id::text as id`,
|
|
194
|
+
sqlite: `update ${W} set due_at = ${SQLITE_EPOCH_MS(SQLITE_NOW)}
|
|
195
|
+
where id in (select value from json_each(?1)) and due_at > ${SQLITE_EPOCH_MS(SQLITE_NOW)} returning id`,
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function record(row: unknown): Readonly<Record<string, unknown>> {
|
|
199
|
+
if (typeof row !== 'object' || row === null) {
|
|
200
|
+
throw new QueryRefusedError('unexpected_row', `${W} answered a row that is not an object`)
|
|
201
|
+
}
|
|
202
|
+
return Object.fromEntries(Object.entries(row))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function rows(session: Session, texts: DialectTexts, parameters: readonly FixedParameter[]): Promise<Readonly<Record<string, unknown>>[]> {
|
|
206
|
+
return (await runFixedStatement(session, texts[session.dialect], parameters)).map(record)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** BIGINT comes back from Postgres as a string, INTEGER from SQLite as a number. */
|
|
210
|
+
function wholeNumber(value: unknown, what: string): number {
|
|
211
|
+
const parsed = typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value
|
|
212
|
+
if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed)) {
|
|
213
|
+
throw new QueryRefusedError('unexpected_row', `${what} is not a whole number`)
|
|
214
|
+
}
|
|
215
|
+
return parsed
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** BOOLEAN comes back from Postgres as a boolean, an INTEGER flag from SQLite as 0 or 1. */
|
|
219
|
+
function flag(value: unknown, what: string): boolean {
|
|
220
|
+
if (value === true || value === 1) {
|
|
221
|
+
return true
|
|
222
|
+
}
|
|
223
|
+
if (value === false || value === 0) {
|
|
224
|
+
return false
|
|
225
|
+
}
|
|
226
|
+
throw new QueryRefusedError('unexpected_row', `${what} is not a flag`)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function wakeOf(row: Readonly<Record<string, unknown>>): Wake {
|
|
230
|
+
const { id, job, reason, due_at: dueAt, attempt, dedupe, owned } = row
|
|
231
|
+
if (typeof id !== 'string' || typeof job !== 'string' || (dedupe !== null && typeof dedupe !== 'string')) {
|
|
232
|
+
throw new QueryRefusedError('unexpected_row', `${W} came back in another shape than its migration declares`)
|
|
233
|
+
}
|
|
234
|
+
const known = WAKE_REASONS.find((candidate) => candidate === reason)
|
|
235
|
+
if (known === undefined) {
|
|
236
|
+
throw new QueryRefusedError('unexpected_row', `${W}.reason is not a wake reason`)
|
|
237
|
+
}
|
|
238
|
+
return freeze({
|
|
239
|
+
id,
|
|
240
|
+
job,
|
|
241
|
+
reason: known,
|
|
242
|
+
dueAt: new Date(wholeNumber(dueAt, `${W}.due_at`)),
|
|
243
|
+
attempt: wholeNumber(attempt, `${W}.attempt`),
|
|
244
|
+
dedupe,
|
|
245
|
+
owned: flag(owned, `${W}.owned`),
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function epochOf(value: unknown, what: string): number {
|
|
250
|
+
const time = value instanceof Date ? value.getTime() : Number.NaN
|
|
251
|
+
if (!Number.isSafeInteger(time)) {
|
|
252
|
+
throw new QueryRefusedError('invalid_argument', `${what} is a valid time`)
|
|
253
|
+
}
|
|
254
|
+
return time
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function nonEmpty(value: unknown, what: string): string {
|
|
258
|
+
if (typeof value !== 'string' || value === '') {
|
|
259
|
+
throw new QueryRefusedError('invalid_argument', `${what} is a non-empty string`)
|
|
260
|
+
}
|
|
261
|
+
return value
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function newWake(wake: NewWake): readonly FixedParameter[] {
|
|
265
|
+
const job = nonEmpty(wake.job, "a wake's job")
|
|
266
|
+
if (!WAKE_REASONS.some((reason) => reason === wake.reason)) {
|
|
267
|
+
throw new QueryRefusedError('invalid_argument', `a wake's reason is one of ${WAKE_REASONS.join(', ')}`)
|
|
268
|
+
}
|
|
269
|
+
const due = epochOf(wake.dueAt, "a wake's due time")
|
|
270
|
+
const dedupe = wake.dedupe === undefined ? null : nonEmpty(wake.dedupe, "a wake's dedupe key")
|
|
271
|
+
return [uuidv7(), job, String(due), wake.reason, dedupe]
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Inserts the wake `newWake` checked, in `transaction`; refuses a key another job holds, which rolls it back. */
|
|
275
|
+
async function insert(transaction: Session, parameters: readonly FixedParameter[], job: string): Promise<Wake> {
|
|
276
|
+
const [row] = await rows(transaction, SQL_SCHEDULE, parameters)
|
|
277
|
+
if (row === undefined) {
|
|
278
|
+
throw new QueryRefusedError('invalid_argument', `the dedupe key of this wake of '${job}' is held by another job's wake`)
|
|
279
|
+
}
|
|
280
|
+
return wakeOf(row)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
|
|
285
|
+
* lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
|
|
286
|
+
*/
|
|
287
|
+
export function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null {
|
|
288
|
+
if (wakes === undefined) {
|
|
289
|
+
return outcome === 'succeeded' ? freeze({ kind: 'completed' }) : null
|
|
290
|
+
}
|
|
291
|
+
if (wakes.kind === 'retry') {
|
|
292
|
+
if (outcome !== 'failed') {
|
|
293
|
+
throw new QueryRefusedError('invalid_argument', 'only a failed run retries its wakes')
|
|
294
|
+
}
|
|
295
|
+
epochOf(wakes.at, 'a retry')
|
|
296
|
+
return freeze({ kind: 'retry', at: wakes.at })
|
|
297
|
+
}
|
|
298
|
+
if (wakes.kind !== 'completed') {
|
|
299
|
+
throw new QueryRefusedError('invalid_argument', "a finish's wakes are completed or retried")
|
|
300
|
+
}
|
|
301
|
+
if (wakes.nextCron === undefined) {
|
|
302
|
+
return freeze({ kind: 'completed' })
|
|
303
|
+
}
|
|
304
|
+
nonEmpty(wakes.nextCron.expression, "a cron wake's expression")
|
|
305
|
+
epochOf(wakes.nextCron.dueAt, "a cron wake's due time")
|
|
306
|
+
return freeze({ kind: 'completed', nextCron: freeze({ expression: wakes.nextCron.expression, dueAt: wakes.nextCron.dueAt }) })
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The runtime's projection of a change, in its transaction; nothing without one. */
|
|
310
|
+
function projectionOf(runtime: () => DataLayerRuntime): (transaction: Session) => Promise<void> {
|
|
311
|
+
return async (transaction) => {
|
|
312
|
+
await runtime().projectWakes?.(transaction)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
|
|
318
|
+
* fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
|
|
319
|
+
* runs the runtime's projection.
|
|
320
|
+
*/
|
|
321
|
+
export function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection {
|
|
322
|
+
const project = projectionOf(runtime)
|
|
323
|
+
return async (transaction: Session, job: string, change: LeaseChange): Promise<void> => {
|
|
324
|
+
if (change.kind === 'acquired') {
|
|
325
|
+
await rows(transaction, SQL_OWN, [job])
|
|
326
|
+
}
|
|
327
|
+
if (change.kind === 'finished' && change.wakes !== null) {
|
|
328
|
+
if (change.wakes.kind === 'retry') {
|
|
329
|
+
await rows(transaction, SQL_RETRY, [job, String(change.wakes.at.getTime())])
|
|
330
|
+
} else {
|
|
331
|
+
await rows(transaction, SQL_CONSUME, [job])
|
|
332
|
+
const next = change.wakes.nextCron
|
|
333
|
+
if (next !== undefined) {
|
|
334
|
+
await insert(transaction, newWake({ job, reason: 'cron', dueAt: next.dueAt, dedupe: `cron:${job}:${next.expression}` }), job)
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (change.kind === 'finished' || change.kind === 'reaped') {
|
|
339
|
+
await rows(transaction, SQL_DISOWN, [job])
|
|
340
|
+
}
|
|
341
|
+
await project(transaction)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** A job's one claim wake: each attempt's first claim replaces it. */
|
|
346
|
+
const claimKey = (job: string): string => `claim:${job}`
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Each attempt's earliest claim re-arm so far (`null`: none), by its fence: a later claim of the attempt, over another
|
|
350
|
+
* queue or `where`, never postpones it. A claim whose transaction rolled back may leave it early, which costs one run.
|
|
351
|
+
*/
|
|
352
|
+
const attemptRearms = new WeakMap<LeaseFence, number | null>()
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
|
|
356
|
+
* transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
|
|
357
|
+
* left; each later claim keeps the earliest re-arm of the attempt.
|
|
358
|
+
*/
|
|
359
|
+
export async function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void> {
|
|
360
|
+
const candidate = dueAt === null ? null : epochOf(dueAt, 'a claim re-arm')
|
|
361
|
+
const earlier = attemptRearms.get(fence) ?? null
|
|
362
|
+
const due = earlier === null ? candidate : candidate === null ? earlier : Math.min(earlier, candidate)
|
|
363
|
+
attemptRearms.set(fence, due)
|
|
364
|
+
await rows(transaction, SQL_DROP_CLAIM, [fence.job, claimKey(fence.job)])
|
|
365
|
+
if (due !== null) {
|
|
366
|
+
await insert(transaction, newWake({ job: fence.job, reason: 'claim', dueAt: new Date(due), dedupe: claimKey(fence.job) }), fence.job)
|
|
367
|
+
}
|
|
368
|
+
await runtime.projectWakes?.(transaction)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** The next wake, in epoch milliseconds, and the database's now as the same statement read it. */
|
|
372
|
+
async function nextAndNow(session: Session): Promise<{ readonly next: number | null; readonly now: () => number }> {
|
|
373
|
+
const [{ wake = null, held = null, now = null } = {}] = await rows(session, SQL_NEXT, [])
|
|
374
|
+
const candidates = [wake, held].filter((value) => value !== null).map((value) => wholeNumber(value, 'the next wake'))
|
|
375
|
+
return { next: candidates.length === 0 ? null : Math.min(...candidates), now: () => wholeNumber(now, "the database's now") }
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
|
|
379
|
+
const session = () => sessionOf(runtime())
|
|
380
|
+
const project = projectionOf(runtime)
|
|
381
|
+
return freeze({
|
|
382
|
+
async schedule(wake: NewWake, using?: Session): Promise<Wake> {
|
|
383
|
+
const parameters = newWake(wake)
|
|
384
|
+
return await (using ?? session()).transaction(async (transaction) => {
|
|
385
|
+
const scheduled = await insert(transaction, parameters, wake.job)
|
|
386
|
+
await project(transaction)
|
|
387
|
+
return scheduled
|
|
388
|
+
})
|
|
389
|
+
},
|
|
390
|
+
|
|
391
|
+
async pending(job: string): Promise<readonly Wake[]> {
|
|
392
|
+
return freeze((await rows(session(), SQL_PENDING, [job])).map(wakeOf))
|
|
393
|
+
},
|
|
394
|
+
|
|
395
|
+
async next(using?: Session): Promise<Date | null> {
|
|
396
|
+
const { next } = await nextAndNow(using ?? session())
|
|
397
|
+
return next === null ? null : new Date(next)
|
|
398
|
+
},
|
|
399
|
+
|
|
400
|
+
async untilNext(using?: Session): Promise<number | null> {
|
|
401
|
+
const { next, now } = await nextAndNow(using ?? session())
|
|
402
|
+
return next === null ? null : next - now()
|
|
403
|
+
},
|
|
404
|
+
|
|
405
|
+
async now(using?: Session): Promise<Date> {
|
|
406
|
+
const [{ now = null } = {}] = await rows(using ?? session(), SQL_CLOCK, [])
|
|
407
|
+
return new Date(wholeNumber(now, "the database's now"))
|
|
408
|
+
},
|
|
409
|
+
|
|
410
|
+
async expiredHolders(): Promise<readonly string[]> {
|
|
411
|
+
return freeze(
|
|
412
|
+
(await rows(session(), SQL_EXPIRED_HOLDERS, [])).map(({ job }) => {
|
|
413
|
+
if (typeof job !== 'string') {
|
|
414
|
+
throw new QueryRefusedError('unexpected_row', `${L} came back in another shape than its migration declares`)
|
|
415
|
+
}
|
|
416
|
+
return job
|
|
417
|
+
}),
|
|
418
|
+
)
|
|
419
|
+
},
|
|
420
|
+
|
|
421
|
+
async reconcile(declared: readonly DeclaredJob[]): Promise<number> {
|
|
422
|
+
if (!Array.isArray(declared)) {
|
|
423
|
+
throw new QueryRefusedError('invalid_argument', 'the declared jobs are a list of jobs with their expressions')
|
|
424
|
+
}
|
|
425
|
+
const jobs = declared.map((entry: unknown) => {
|
|
426
|
+
const job: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'job') : undefined
|
|
427
|
+
const expression: unknown = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'expression') : undefined
|
|
428
|
+
return { job: nonEmpty(job, 'a declared job'), expression: nonEmpty(expression, "a declared job's expression") }
|
|
429
|
+
})
|
|
430
|
+
return await session().transaction(async (transaction) => {
|
|
431
|
+
const removed = await rows(transaction, SQL_RECONCILE, [JSON.stringify(jobs)])
|
|
432
|
+
await project(transaction)
|
|
433
|
+
return removed.length
|
|
434
|
+
})
|
|
435
|
+
},
|
|
436
|
+
|
|
437
|
+
async hasten(ids: readonly string[]): Promise<number> {
|
|
438
|
+
refuseInProduction("the wakes store's hasten")
|
|
439
|
+
if (!Array.isArray(ids)) {
|
|
440
|
+
throw new QueryRefusedError('invalid_argument', 'the wakes to hasten are a list of wake ids')
|
|
441
|
+
}
|
|
442
|
+
const named = ids.map((id: unknown) => nonEmpty(id, 'a wake id'))
|
|
443
|
+
return await session().transaction(async (transaction) => {
|
|
444
|
+
const moved = await rows(transaction, SQL_HASTEN, [JSON.stringify(named)])
|
|
445
|
+
await project(transaction)
|
|
446
|
+
return moved.length
|
|
447
|
+
})
|
|
448
|
+
},
|
|
449
|
+
})
|
|
450
|
+
}
|
package/src/links.ts
CHANGED
|
@@ -57,5 +57,12 @@ export function linkValues(table: string, links: readonly Container[], grant: Re
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
export function linksPredicate(table: string, values: readonly LinkValue[]): OperationNode {
|
|
60
|
-
|
|
60
|
+
const terms: OperationNode[] = []
|
|
61
|
+
for (let index = 0; index < values.length; index++) {
|
|
62
|
+
const entry = values[index]
|
|
63
|
+
if (entry !== undefined) {
|
|
64
|
+
terms[terms.length] = equals(table, entry.link.column, entry.value)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return allOf(terms)
|
|
61
68
|
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// @fabrika/db/migrations-sqlite — the framework's own tables in an application's SQLite database, a Cloudflare
|
|
2
|
+
// Durable Object's (ADR-0065). The same tables and columns as the Postgres bundle in `migrations.ts`, without the
|
|
3
|
+
// history a Postgres schema carries: no form files and no adoption of collection tables, which no SQLite database
|
|
4
|
+
// ever had. Plain data, applied as the bundle `fabrika` before the application's `app` bundle.
|
|
5
|
+
//
|
|
6
|
+
// The SQLite forms of the column types, which every framework statement and the row reads rely on:
|
|
7
|
+
// - a timestamp is TEXT in UTC, `YYYY-MM-DDTHH:MM:SS.sssZ`: what `strftime(SQLITE_NOW_FORMAT, 'now')` and
|
|
8
|
+
// `Date#toISOString()` both write, so text order is time order;
|
|
9
|
+
// - a boolean is INTEGER 0 or 1; a UUID is TEXT; a BIGINT is INTEGER.
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
FILE_DELETIONS_TABLE,
|
|
13
|
+
FILES_TABLE,
|
|
14
|
+
FORM_ADMISSIONS_TABLE,
|
|
15
|
+
FORM_BYTES_TABLE,
|
|
16
|
+
FORM_CHALLENGES_TABLE,
|
|
17
|
+
type FrameworkMigration,
|
|
18
|
+
JOB_KICKS_TABLE,
|
|
19
|
+
JOB_LEASES_TABLE,
|
|
20
|
+
JOB_WAKES_TABLE,
|
|
21
|
+
WEBHOOK_BINDINGS_TABLE,
|
|
22
|
+
WEBHOOK_DELIVERIES_TABLE,
|
|
23
|
+
} from './migrations'
|
|
24
|
+
|
|
25
|
+
/** The `strftime` format of a stored timestamp; `strftime(SQLITE_NOW_FORMAT, 'now')` is the database's clock. */
|
|
26
|
+
export const SQLITE_NOW_FORMAT = '%Y-%m-%dT%H:%M:%fZ'
|
|
27
|
+
|
|
28
|
+
export const SQLITE_FRAMEWORK_MIGRATIONS: readonly FrameworkMigration[] = Object.freeze([
|
|
29
|
+
Object.freeze({
|
|
30
|
+
name: '0001_framework.sql',
|
|
31
|
+
sql: `-- A binding admits deliveries for one scope value from one provider account, signed with its own secret.
|
|
32
|
+
CREATE TABLE ${WEBHOOK_BINDINGS_TABLE} (
|
|
33
|
+
id TEXT PRIMARY KEY,
|
|
34
|
+
webhook TEXT NOT NULL,
|
|
35
|
+
scope_type TEXT NOT NULL,
|
|
36
|
+
scope_value TEXT NOT NULL,
|
|
37
|
+
account TEXT NOT NULL,
|
|
38
|
+
secret TEXT NOT NULL,
|
|
39
|
+
created_by TEXT NOT NULL,
|
|
40
|
+
created_at INTEGER NOT NULL
|
|
41
|
+
) STRICT;
|
|
42
|
+
|
|
43
|
+
-- GitHub signs no timestamp, so a recorded delivery id is the replay defence. A delivery is claimed with a lease and
|
|
44
|
+
-- completed in its handler's transaction, which clears the lease.
|
|
45
|
+
CREATE TABLE ${WEBHOOK_DELIVERIES_TABLE} (
|
|
46
|
+
binding_id TEXT NOT NULL REFERENCES ${WEBHOOK_BINDINGS_TABLE} (id) ON DELETE CASCADE,
|
|
47
|
+
delivery_id TEXT NOT NULL,
|
|
48
|
+
received_at INTEGER NOT NULL,
|
|
49
|
+
lease_until INTEGER,
|
|
50
|
+
PRIMARY KEY (binding_id, delivery_id)
|
|
51
|
+
) STRICT;
|
|
52
|
+
|
|
53
|
+
-- One row per job: the lease a run takes, fenced by its generation, and the outcome of the last run.
|
|
54
|
+
CREATE TABLE ${JOB_LEASES_TABLE} (
|
|
55
|
+
job TEXT PRIMARY KEY,
|
|
56
|
+
generation INTEGER NOT NULL,
|
|
57
|
+
holder TEXT,
|
|
58
|
+
expires_at TEXT NOT NULL,
|
|
59
|
+
attempt_deadline TEXT NOT NULL,
|
|
60
|
+
first_seen_at TEXT NOT NULL,
|
|
61
|
+
last_started_at TEXT,
|
|
62
|
+
last_finished_at TEXT,
|
|
63
|
+
last_status TEXT,
|
|
64
|
+
last_succeeded_at TEXT,
|
|
65
|
+
last_duration_ms INTEGER,
|
|
66
|
+
last_missed_reported_at TEXT
|
|
67
|
+
) STRICT;
|
|
68
|
+
|
|
69
|
+
-- Whether a kick arrived after the job's current run started: that run runs the job once more after it succeeded.
|
|
70
|
+
CREATE TABLE ${JOB_KICKS_TABLE} (
|
|
71
|
+
job TEXT PRIMARY KEY,
|
|
72
|
+
pending INTEGER NOT NULL CHECK (pending IN (0, 1))
|
|
73
|
+
) STRICT;
|
|
74
|
+
|
|
75
|
+
-- A form's admission counters, one row per form, bucket and minute; a row of a past minute is pruned by the next
|
|
76
|
+
-- admission.
|
|
77
|
+
CREATE TABLE ${FORM_ADMISSIONS_TABLE} (
|
|
78
|
+
form TEXT NOT NULL,
|
|
79
|
+
bucket TEXT NOT NULL,
|
|
80
|
+
window_start TEXT NOT NULL,
|
|
81
|
+
count INTEGER NOT NULL,
|
|
82
|
+
PRIMARY KEY (form, bucket, window_start)
|
|
83
|
+
) STRICT;
|
|
84
|
+
CREATE INDEX ${FORM_ADMISSIONS_TABLE}_window_start ON ${FORM_ADMISSIONS_TABLE} (window_start);
|
|
85
|
+
|
|
86
|
+
-- The digest of each challenge token a form accepted, until the token could no longer verify: a replay is refused.
|
|
87
|
+
CREATE TABLE ${FORM_CHALLENGES_TABLE} (
|
|
88
|
+
form TEXT NOT NULL,
|
|
89
|
+
token_digest TEXT NOT NULL,
|
|
90
|
+
expires_at TEXT NOT NULL,
|
|
91
|
+
PRIMARY KEY (form, token_digest)
|
|
92
|
+
) STRICT;
|
|
93
|
+
CREATE INDEX ${FORM_CHALLENGES_TABLE}_expires_at ON ${FORM_CHALLENGES_TABLE} (expires_at);
|
|
94
|
+
|
|
95
|
+
-- The bytes a form's files may write per hour: one row per form and hour, which the next reservation of a later hour
|
|
96
|
+
-- prunes.
|
|
97
|
+
CREATE TABLE ${FORM_BYTES_TABLE} (
|
|
98
|
+
form TEXT NOT NULL,
|
|
99
|
+
window_start TEXT NOT NULL,
|
|
100
|
+
bytes INTEGER NOT NULL,
|
|
101
|
+
PRIMARY KEY (form, window_start)
|
|
102
|
+
) STRICT;
|
|
103
|
+
|
|
104
|
+
-- Every stored file: a value a table's file column references by id. A row is 'pending' from before its object
|
|
105
|
+
-- (<kind>/<id>) is written until the first reference claims it, then 'quarantined' (a scanning kind) or 'live'.
|
|
106
|
+
CREATE TABLE ${FILES_TABLE} (
|
|
107
|
+
id TEXT PRIMARY KEY,
|
|
108
|
+
kind TEXT NOT NULL,
|
|
109
|
+
status TEXT NOT NULL CONSTRAINT ${FILES_TABLE}_status CHECK (status IN ('pending', 'quarantined', 'live', 'rejected')),
|
|
110
|
+
object_key TEXT NOT NULL UNIQUE,
|
|
111
|
+
size INTEGER,
|
|
112
|
+
sha256 TEXT,
|
|
113
|
+
content_type TEXT NOT NULL,
|
|
114
|
+
name TEXT,
|
|
115
|
+
scope TEXT,
|
|
116
|
+
request TEXT,
|
|
117
|
+
created_at TEXT NOT NULL,
|
|
118
|
+
object_version TEXT,
|
|
119
|
+
scan_attempts INTEGER NOT NULL DEFAULT 0,
|
|
120
|
+
scan_after TEXT,
|
|
121
|
+
legacy TEXT
|
|
122
|
+
) STRICT;
|
|
123
|
+
CREATE INDEX ${FILES_TABLE}_created_at ON ${FILES_TABLE} (created_at) WHERE legacy IS NULL;
|
|
124
|
+
CREATE INDEX ${FILES_TABLE}_scan ON ${FILES_TABLE} (scan_after) WHERE status = 'quarantined';
|
|
125
|
+
|
|
126
|
+
-- An object whose file row is deleted, until the object is: the sweep finishes a deletion a crash interrupted.
|
|
127
|
+
CREATE TABLE ${FILE_DELETIONS_TABLE} (
|
|
128
|
+
object_key TEXT PRIMARY KEY,
|
|
129
|
+
recorded_at TEXT NOT NULL
|
|
130
|
+
) STRICT;
|
|
131
|
+
`,
|
|
132
|
+
}),
|
|
133
|
+
Object.freeze({
|
|
134
|
+
name: '0002_job_wakes.sql',
|
|
135
|
+
sql: `-- A job's pending work, one row per due unit: its next scheduled run, a kick, a claim's re-arm, a durable retry. due_at
|
|
136
|
+
-- is epoch milliseconds. Only the fenced finish of a run that started at or after a row changes it: consumed when the run is
|
|
137
|
+
-- done with it, or moved to a retry, which counts in attempt.
|
|
138
|
+
CREATE TABLE ${JOB_WAKES_TABLE} (
|
|
139
|
+
id TEXT PRIMARY KEY,
|
|
140
|
+
job TEXT NOT NULL,
|
|
141
|
+
due_at INTEGER NOT NULL,
|
|
142
|
+
reason TEXT NOT NULL CONSTRAINT ${JOB_WAKES_TABLE}_reason CHECK (reason IN ('cron', 'kick', 'claim', 'retry')),
|
|
143
|
+
attempt INTEGER NOT NULL DEFAULT 0,
|
|
144
|
+
dedupe TEXT
|
|
145
|
+
) STRICT;
|
|
146
|
+
CREATE INDEX ${JOB_WAKES_TABLE}_due ON ${JOB_WAKES_TABLE} (due_at);
|
|
147
|
+
CREATE UNIQUE INDEX ${JOB_WAKES_TABLE}_dedupe ON ${JOB_WAKES_TABLE} (dedupe) WHERE dedupe IS NOT NULL;
|
|
148
|
+
`,
|
|
149
|
+
}),
|
|
150
|
+
Object.freeze({
|
|
151
|
+
name: '0003_file_deletions_recorded_at.sql',
|
|
152
|
+
sql: `-- A queued key is a tombstone kept for the retention window: the sweep reads the due ones by age, not the whole queue.
|
|
153
|
+
CREATE INDEX ${FILE_DELETIONS_TABLE}_recorded_at ON ${FILE_DELETIONS_TABLE} (recorded_at, object_key);
|
|
154
|
+
`,
|
|
155
|
+
}),
|
|
156
|
+
Object.freeze({
|
|
157
|
+
name: '0004_job_wakes_owned.sql',
|
|
158
|
+
sql: `-- The wakes the run holding the job's lease took when it took the lease: its finish consumes or retries exactly these.
|
|
159
|
+
-- A wake written or merged into afterwards is not taken, though due before the run started: the run may not have read its work.
|
|
160
|
+
ALTER TABLE ${JOB_WAKES_TABLE} ADD COLUMN owned INTEGER NOT NULL DEFAULT 0 CHECK (owned IN (0, 1));
|
|
161
|
+
`,
|
|
162
|
+
}),
|
|
163
|
+
])
|
package/src/migrations.ts
CHANGED
|
@@ -9,6 +9,7 @@ export const WEBHOOK_BINDINGS_TABLE = 'fabrika_webhook_bindings'
|
|
|
9
9
|
export const WEBHOOK_DELIVERIES_TABLE = 'fabrika_webhook_deliveries'
|
|
10
10
|
export const JOB_LEASES_TABLE = 'fabrika_job_leases'
|
|
11
11
|
export const JOB_KICKS_TABLE = 'fabrika_job_kicks'
|
|
12
|
+
export const JOB_WAKES_TABLE = 'fabrika_wakes'
|
|
12
13
|
export const FORM_ADMISSIONS_TABLE = 'fabrika_form_admissions'
|
|
13
14
|
export const FORM_CHALLENGES_TABLE = 'fabrika_form_challenges'
|
|
14
15
|
export const FORM_FILES_TABLE = 'fabrika_form_files'
|
|
@@ -254,6 +255,30 @@ BEGIN
|
|
|
254
255
|
DELETE FROM ${FORM_FILES_TABLE} f WHERE status = 'held' AND EXISTS (SELECT 1 FROM ${FILES_TABLE} c WHERE c.id = f.id);
|
|
255
256
|
END
|
|
256
257
|
$$;
|
|
258
|
+
`,
|
|
259
|
+
}),
|
|
260
|
+
Object.freeze({
|
|
261
|
+
name: '0009_job_wakes.sql',
|
|
262
|
+
sql: `-- A job's pending work, one row per due unit: its next scheduled run, a kick, a claim's re-arm, a durable retry. due_at
|
|
263
|
+
-- is epoch milliseconds. Only the fenced finish of a run that started at or after a row changes it: consumed when the run is
|
|
264
|
+
-- done with it, or moved to a retry, which counts in attempt.
|
|
265
|
+
CREATE TABLE ${JOB_WAKES_TABLE} (
|
|
266
|
+
id UUID PRIMARY KEY,
|
|
267
|
+
job TEXT NOT NULL,
|
|
268
|
+
due_at BIGINT NOT NULL,
|
|
269
|
+
reason TEXT NOT NULL CONSTRAINT ${JOB_WAKES_TABLE}_reason CHECK (reason IN ('cron', 'kick', 'claim', 'retry')),
|
|
270
|
+
attempt INTEGER NOT NULL DEFAULT 0,
|
|
271
|
+
dedupe TEXT
|
|
272
|
+
);
|
|
273
|
+
CREATE INDEX ${JOB_WAKES_TABLE}_due ON ${JOB_WAKES_TABLE} (due_at);
|
|
274
|
+
CREATE UNIQUE INDEX ${JOB_WAKES_TABLE}_dedupe ON ${JOB_WAKES_TABLE} (dedupe) WHERE dedupe IS NOT NULL;
|
|
275
|
+
`,
|
|
276
|
+
}),
|
|
277
|
+
Object.freeze({
|
|
278
|
+
name: '0010_job_wakes_owned.sql',
|
|
279
|
+
sql: `-- The wakes the run holding the job's lease took when it took the lease: its finish consumes or retries exactly these.
|
|
280
|
+
-- A wake written or merged into afterwards is not taken, though due before the run started: the run may not have read its work.
|
|
281
|
+
ALTER TABLE ${JOB_WAKES_TABLE} ADD COLUMN owned BOOLEAN NOT NULL DEFAULT false;
|
|
257
282
|
`,
|
|
258
283
|
}),
|
|
259
284
|
])
|