@fabrika/db 0.9.0-dev.33 → 0.9.0-dev.34
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 +4 -4
- package/src/framework.ts +1 -1
- package/src/job-leases.ts +16 -0
- package/src/job-wakes.ts +183 -33
- package/src/migrations-sqlite.ts +17 -0
- package/src/migrations.ts +18 -0
- package/src/orm-types.ts +8 -4
- package/src/policy.ts +60 -33
- package/src/tables.ts +3 -3
- package/src/testing-shared.ts +5 -2
- package/types/src/framework.d.ts +1 -1
- package/types/src/job-leases.d.ts +6 -0
- package/types/src/job-wakes.d.ts +28 -5
- package/types/src/migrations.d.ts +1 -0
- package/types/src/orm-types.d.ts +8 -8
- package/types/src/policy.d.ts +8 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/db",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.34",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": [
|
|
6
6
|
"./src/testing.ts",
|
|
@@ -96,9 +96,9 @@
|
|
|
96
96
|
"test": "bun test"
|
|
97
97
|
},
|
|
98
98
|
"dependencies": {
|
|
99
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
100
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
101
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
99
|
+
"@fabrika/auth-core": "0.9.0-dev.34",
|
|
100
|
+
"@fabrika/platform": "0.9.0-dev.34",
|
|
101
|
+
"@fabrika/platform-node": "0.9.0-dev.34",
|
|
102
102
|
"kysely": "0.29.6",
|
|
103
103
|
"kysely-postgres-js": "5.0.1",
|
|
104
104
|
"zod": "^3.25.76"
|
package/src/framework.ts
CHANGED
|
@@ -22,7 +22,7 @@ export type { FileBinding } from './file-columns'
|
|
|
22
22
|
export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
|
|
23
23
|
export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
|
|
24
24
|
export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
|
|
25
|
-
export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
|
|
25
|
+
export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes'
|
|
26
26
|
export type { DataAccess, DataHandles, DataSite } from './orm'
|
|
27
27
|
export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
|
|
28
28
|
export type { RequestReceipt, RequestReceipts } from './request-receipts'
|
package/src/job-leases.ts
CHANGED
|
@@ -68,6 +68,12 @@ export interface JobLeases {
|
|
|
68
68
|
* the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
|
|
69
69
|
*/
|
|
70
70
|
finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>
|
|
71
|
+
/**
|
|
72
|
+
* Gives back a lease under which no run started: frees it and leaves every wake as it is, owned ones disowned, and
|
|
73
|
+
* records no run (no status, end or duration). A process schedule's timer releases a lease whose take owned no due
|
|
74
|
+
* wake (ADR-0080). `false` when `fence` no longer held it.
|
|
75
|
+
*/
|
|
76
|
+
release(fence: LeaseFence): Promise<boolean>
|
|
71
77
|
/** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
|
|
72
78
|
markPending(job: string): Promise<void>
|
|
73
79
|
/**
|
|
@@ -177,6 +183,11 @@ const SQL_FINISH: DialectTexts = {
|
|
|
177
183
|
where job = ?1 and generation = ?2 and holder = ?3 returning job`,
|
|
178
184
|
}
|
|
179
185
|
|
|
186
|
+
const SQL_RELEASE: DialectTexts = {
|
|
187
|
+
postgres: `update ${T} set holder = null where job = $1 and generation = $2 and holder = $3 returning job`,
|
|
188
|
+
sqlite: `update ${T} set holder = null where job = ?1 and generation = ?2 and holder = ?3 returning job`,
|
|
189
|
+
}
|
|
190
|
+
|
|
180
191
|
const SQL_TRY_ACQUIRE: DialectTexts = {
|
|
181
192
|
// A free lease whose row no transaction holds (`skip locked`): an attempt's fence holds it `for share` while it writes.
|
|
182
193
|
postgres: `with free as (select job from ${T} where job = $1 and holder is null for update skip locked)
|
|
@@ -497,6 +508,11 @@ export function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProject
|
|
|
497
508
|
return (await changing(SQL_FINISH, [...params(fence), outcome], fence.job, change)).length > 0
|
|
498
509
|
},
|
|
499
510
|
|
|
511
|
+
async release(fence: LeaseFence): Promise<boolean> {
|
|
512
|
+
// A finish that applies nothing to the wakes: the projection only disowns what the take marked owned.
|
|
513
|
+
return (await changing(SQL_RELEASE, params(fence), fence.job, { kind: 'finished', wakes: null })).length > 0
|
|
514
|
+
},
|
|
515
|
+
|
|
500
516
|
async tryAcquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
|
|
501
517
|
const [row] = await changing(
|
|
502
518
|
SQL_TRY_ACQUIRE,
|
package/src/job-wakes.ts
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
// leases. Only `@fabrika/app` reaches it, through `frameworkTablesOf`. A run owns the wakes due when it took its lease,
|
|
4
4
|
// marked in that transaction (`owned`); a wake written or merged into afterwards is not its. Only the transaction of that
|
|
5
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.
|
|
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).
|
|
7
9
|
|
|
8
10
|
import { uuidv7 } from '@fabrika/platform'
|
|
9
11
|
import { freeze } from './builtins'
|
|
@@ -11,7 +13,7 @@ import type { LeaseFence } from './capability'
|
|
|
11
13
|
import { type FixedParameter, runFixedStatement, type Session, sessionOf } from './database'
|
|
12
14
|
import { QueryRefusedError } from './errors'
|
|
13
15
|
import type { DialectTexts, JobOutcome, LeaseChange, LeaseProjection } from './job-leases'
|
|
14
|
-
import { JOB_LEASES_TABLE, JOB_WAKES_TABLE } from './migrations'
|
|
16
|
+
import { JOB_LEASES_TABLE, JOB_SCHEDULE_TABLE, JOB_WAKES_TABLE } from './migrations'
|
|
15
17
|
import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
|
|
16
18
|
import { refuseInProduction } from './production'
|
|
17
19
|
import type { DataLayerRuntime } from './store'
|
|
@@ -47,7 +49,15 @@ export interface Wake {
|
|
|
47
49
|
*/
|
|
48
50
|
export type FinishWakes =
|
|
49
51
|
/** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
|
|
50
|
-
| {
|
|
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
|
+
}
|
|
51
61
|
/** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
|
|
52
62
|
| { readonly kind: 'retry'; readonly at: Date }
|
|
53
63
|
|
|
@@ -63,18 +73,31 @@ export interface JobWakes {
|
|
|
63
73
|
pending(job: string): Promise<readonly Wake[]>
|
|
64
74
|
/**
|
|
65
75
|
* 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
|
|
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.
|
|
67
78
|
*/
|
|
68
|
-
next(using?: Session): Promise<Date | null>
|
|
79
|
+
next(using?: Session, jobs?: readonly string[]): Promise<Date | null>
|
|
69
80
|
/** 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>
|
|
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>
|
|
71
93
|
/** The database's clock, read in `using` when given: a wake due now is due by it. */
|
|
72
94
|
now(using?: Session): Promise<Date>
|
|
73
95
|
/**
|
|
74
96
|
* 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.
|
|
97
|
+
* each declared job's cron wake whose key names another expression; answers how many it deleted. In `using` when
|
|
98
|
+
* given.
|
|
76
99
|
*/
|
|
77
|
-
reconcile(declared: readonly DeclaredJob[]): Promise<number>
|
|
100
|
+
reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number>
|
|
78
101
|
/**
|
|
79
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
|
|
80
103
|
* now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
|
|
@@ -87,6 +110,11 @@ export interface JobWakes {
|
|
|
87
110
|
expiredHolders(): Promise<readonly string[]>
|
|
88
111
|
}
|
|
89
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
|
+
|
|
90
118
|
/** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
|
|
91
119
|
export interface DeclaredJob {
|
|
92
120
|
readonly job: string
|
|
@@ -95,6 +123,7 @@ export interface DeclaredJob {
|
|
|
95
123
|
|
|
96
124
|
const W = JOB_WAKES_TABLE
|
|
97
125
|
const L = JOB_LEASES_TABLE
|
|
126
|
+
const S = JOB_SCHEDULE_TABLE
|
|
98
127
|
const COLUMNS = 'job, due_at, reason, attempt, dedupe'
|
|
99
128
|
const SELECTED = `${COLUMNS}, owned`
|
|
100
129
|
const SQLITE_NOW = `strftime('${SQLITE_NOW_FORMAT}', 'now')`
|
|
@@ -139,20 +168,101 @@ const SQL_DISOWN: DialectTexts = {
|
|
|
139
168
|
|
|
140
169
|
// Two candidates, each one index-ordered or per-job lookup: the earliest wake of a free or expired job walks the due index
|
|
141
170
|
// 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.
|
|
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.
|
|
143
173
|
const SQL_NEXT: DialectTexts = {
|
|
144
174
|
postgres: `select
|
|
145
175
|
(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()
|
|
147
|
-
|
|
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,
|
|
148
180
|
${PG_EPOCH_MS('clock_timestamp()')} as now`,
|
|
149
181
|
sqlite: `select
|
|
150
182
|
(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}
|
|
152
|
-
|
|
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,
|
|
153
187
|
${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
|
|
154
188
|
}
|
|
155
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
|
+
|
|
156
266
|
const SQL_CLOCK: DialectTexts = {
|
|
157
267
|
postgres: `select ${PG_EPOCH_MS('clock_timestamp()')} as now`,
|
|
158
268
|
sqlite: `select ${SQLITE_EPOCH_MS(SQLITE_NOW)} as now`,
|
|
@@ -303,7 +413,11 @@ export function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined)
|
|
|
303
413
|
}
|
|
304
414
|
nonEmpty(wakes.nextCron.expression, "a cron wake's expression")
|
|
305
415
|
epochOf(wakes.nextCron.dueAt, "a cron wake's due time")
|
|
306
|
-
|
|
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 }) })
|
|
307
421
|
}
|
|
308
422
|
|
|
309
423
|
/** The runtime's projection of a change, in its transaction; nothing without one. */
|
|
@@ -328,10 +442,14 @@ export function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjectio
|
|
|
328
442
|
if (change.wakes.kind === 'retry') {
|
|
329
443
|
await rows(transaction, SQL_RETRY, [job, String(change.wakes.at.getTime())])
|
|
330
444
|
} else {
|
|
331
|
-
await rows(transaction, SQL_CONSUME, [job])
|
|
332
445
|
const next = change.wakes.nextCron
|
|
333
|
-
|
|
334
|
-
|
|
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)
|
|
335
453
|
}
|
|
336
454
|
}
|
|
337
455
|
}
|
|
@@ -368,9 +486,23 @@ export async function rearmClaim(runtime: DataLayerRuntime, transaction: Session
|
|
|
368
486
|
await runtime.projectWakes?.(transaction)
|
|
369
487
|
}
|
|
370
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
|
+
|
|
371
500
|
/** The next wake, in epoch milliseconds, and the database's now as the same statement read it. */
|
|
372
|
-
async function nextAndNow(
|
|
373
|
-
|
|
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)])
|
|
374
506
|
const candidates = [wake, held].filter((value) => value !== null).map((value) => wholeNumber(value, 'the next wake'))
|
|
375
507
|
return { next: candidates.length === 0 ? null : Math.min(...candidates), now: () => wholeNumber(now, "the database's now") }
|
|
376
508
|
}
|
|
@@ -392,16 +524,41 @@ export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
|
|
|
392
524
|
return freeze((await rows(session(), SQL_PENDING, [job])).map(wakeOf))
|
|
393
525
|
},
|
|
394
526
|
|
|
395
|
-
async next(using?: Session): Promise<Date | null> {
|
|
396
|
-
const { next } = await nextAndNow(using ?? session())
|
|
527
|
+
async next(using?: Session, jobs?: readonly string[]): Promise<Date | null> {
|
|
528
|
+
const { next } = await nextAndNow(using ?? session(), jobs)
|
|
397
529
|
return next === null ? null : new Date(next)
|
|
398
530
|
},
|
|
399
531
|
|
|
400
|
-
async untilNext(using?: Session): Promise<number | null> {
|
|
401
|
-
const { next, now } = await nextAndNow(using ?? session())
|
|
532
|
+
async untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null> {
|
|
533
|
+
const { next, now } = await nextAndNow(using ?? session(), jobs)
|
|
402
534
|
return next === null ? null : next - now()
|
|
403
535
|
},
|
|
404
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
|
+
|
|
405
562
|
async now(using?: Session): Promise<Date> {
|
|
406
563
|
const [{ now = null } = {}] = await rows(using ?? session(), SQL_CLOCK, [])
|
|
407
564
|
return new Date(wholeNumber(now, "the database's now"))
|
|
@@ -418,16 +575,9 @@ export function jobWakes(runtime: () => DataLayerRuntime): JobWakes {
|
|
|
418
575
|
)
|
|
419
576
|
},
|
|
420
577
|
|
|
421
|
-
async reconcile(declared: readonly DeclaredJob[]): Promise<number> {
|
|
422
|
-
|
|
423
|
-
|
|
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) => {
|
|
578
|
+
async reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number> {
|
|
579
|
+
const jobs = declaredJobs(declared)
|
|
580
|
+
return await (using ?? session()).transaction(async (transaction) => {
|
|
431
581
|
const removed = await rows(transaction, SQL_RECONCILE, [JSON.stringify(jobs)])
|
|
432
582
|
await project(transaction)
|
|
433
583
|
return removed.length
|
package/src/migrations-sqlite.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
type FrameworkMigration,
|
|
18
18
|
JOB_KICKS_TABLE,
|
|
19
19
|
JOB_LEASES_TABLE,
|
|
20
|
+
JOB_SCHEDULE_TABLE,
|
|
20
21
|
JOB_WAKES_TABLE,
|
|
21
22
|
LIST_CURSOR_KEY_TABLE,
|
|
22
23
|
REQUEST_RECEIPTS_TABLE,
|
|
@@ -188,6 +189,22 @@ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
|
|
|
188
189
|
secret TEXT NOT NULL
|
|
189
190
|
) STRICT;
|
|
190
191
|
INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, hex(randomblob(32)));
|
|
192
|
+
`,
|
|
193
|
+
}),
|
|
194
|
+
Object.freeze({
|
|
195
|
+
name: '0007_job_schedule.sql',
|
|
196
|
+
sql: `-- Which deploy keeps the cron wakes where no crontab runs (ADR-0080): one row, the highest generation a serving process
|
|
197
|
+
-- has seen. The Durable Object keeps its schedule itself and never writes it; the table keeps both bundles alike.
|
|
198
|
+
CREATE TABLE ${JOB_SCHEDULE_TABLE} (
|
|
199
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
200
|
+
generation TEXT NOT NULL
|
|
201
|
+
) STRICT;
|
|
202
|
+
`,
|
|
203
|
+
}),
|
|
204
|
+
Object.freeze({
|
|
205
|
+
name: '0008_job_schedule_declared.sql',
|
|
206
|
+
sql: `-- The cron keys the stored generation's deploy declares, as a JSON array (see the Postgres bundle's 0014).
|
|
207
|
+
ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
|
|
191
208
|
`,
|
|
192
209
|
}),
|
|
193
210
|
])
|
package/src/migrations.ts
CHANGED
|
@@ -10,6 +10,7 @@ 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
12
|
export const JOB_WAKES_TABLE = 'fabrika_wakes'
|
|
13
|
+
export const JOB_SCHEDULE_TABLE = 'fabrika_job_schedule'
|
|
13
14
|
export const FORM_ADMISSIONS_TABLE = 'fabrika_form_admissions'
|
|
14
15
|
export const FORM_CHALLENGES_TABLE = 'fabrika_form_challenges'
|
|
15
16
|
export const FORM_FILES_TABLE = 'fabrika_form_files'
|
|
@@ -309,6 +310,23 @@ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
|
|
|
309
310
|
secret TEXT NOT NULL
|
|
310
311
|
);
|
|
311
312
|
INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, gen_random_uuid()::text || gen_random_uuid()::text);
|
|
313
|
+
`,
|
|
314
|
+
}),
|
|
315
|
+
Object.freeze({
|
|
316
|
+
name: '0013_job_schedule.sql',
|
|
317
|
+
sql: `-- Which deploy keeps the cron wakes where no crontab runs (ADR-0080): one row, the highest generation a serving process
|
|
318
|
+
-- has seen. A process of that generation reconciles and seeds the wakes; an older one does neither. Compared as bytes.
|
|
319
|
+
CREATE TABLE ${JOB_SCHEDULE_TABLE} (
|
|
320
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
321
|
+
generation TEXT COLLATE "C" NOT NULL
|
|
322
|
+
);
|
|
323
|
+
`,
|
|
324
|
+
}),
|
|
325
|
+
Object.freeze({
|
|
326
|
+
name: '0014_job_schedule_declared.sql',
|
|
327
|
+
sql: `-- The cron keys (cron:<job>:<expression>) the stored generation's deploy declares, as a JSON array: a run of any
|
|
328
|
+
-- deploy schedules its job's next fire only under a key in it, so an old revision restores no removed job or expression.
|
|
329
|
+
ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
|
|
312
330
|
`,
|
|
313
331
|
}),
|
|
314
332
|
])
|
package/src/orm-types.ts
CHANGED
|
@@ -61,12 +61,16 @@ type ConditionedOf<P, T> = PolicyOf<P, T> extends { readonly when?: infer W } ?
|
|
|
61
61
|
|
|
62
62
|
type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends { readonly columns: infer C } ? C : never
|
|
63
63
|
|
|
64
|
-
/** The
|
|
65
|
-
type
|
|
64
|
+
/** The actions a column's own `write` names: one action, or each of a list. */
|
|
65
|
+
type WriteActionsOf<P> = P extends { readonly write: infer W } ? W extends readonly (infer L extends string)[] ? L : W extends string ? W : never
|
|
66
|
+
: never
|
|
67
|
+
|
|
68
|
+
/** The columns that list `A` among their own write actions. */
|
|
69
|
+
type ColumnsWrittenBy<C, A> = { [K in keyof C]: [A] extends [WriteActionsOf<C[K]>] ? K : never }[keyof C]
|
|
66
70
|
|
|
67
71
|
/**
|
|
68
72
|
* Each action that updates the table, with the values a capability of it updates: the update action its update list,
|
|
69
|
-
* a column's own write action the columns that
|
|
73
|
+
* a column's own write action the columns that list it (an update action both), and no other.
|
|
70
74
|
*/
|
|
71
75
|
type UpdatesOf<DB, P, T extends keyof DB> =
|
|
72
76
|
& { readonly [A in ActionOf<P, T, 'update'>]: UpdateValues<DB, P, T> }
|
|
@@ -76,7 +80,7 @@ type UpdatesOf<DB, P, T extends keyof DB> =
|
|
|
76
80
|
>
|
|
77
81
|
}
|
|
78
82
|
|
|
79
|
-
type ColumnWriteAction<C> = { [K in keyof C]: C[K]
|
|
83
|
+
type ColumnWriteAction<C> = { [K in keyof C]: WriteActionsOf<C[K]> }[keyof C]
|
|
80
84
|
|
|
81
85
|
/** One table, as every handle reads it. */
|
|
82
86
|
export interface IndexedTable {
|
package/src/policy.ts
CHANGED
|
@@ -206,15 +206,15 @@ export type FilePolicies<Col extends string> = { readonly [C in Col]?: string }
|
|
|
206
206
|
|
|
207
207
|
/**
|
|
208
208
|
* A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
|
|
209
|
-
* without one it falls back to the table's read action. `write`: only a capability of
|
|
210
|
-
*
|
|
209
|
+
* without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
|
|
210
|
+
* column, so the column is not in `update`; a listed table update action writes it beside its update list.
|
|
211
211
|
*/
|
|
212
212
|
export type ColumnPolicies<Col extends string, A extends string> = { readonly [C in Col]?: ColumnPolicy<A> }
|
|
213
213
|
|
|
214
|
-
/** A column's own read actions (one, or a list as a table
|
|
214
|
+
/** A column's own read actions and its own write actions (each one, or a list as a table operation takes), or both. */
|
|
215
215
|
export interface ColumnPolicy<A extends string> {
|
|
216
216
|
readonly read?: TableAction<A>
|
|
217
|
-
readonly write?: A
|
|
217
|
+
readonly write?: TableAction<A>
|
|
218
218
|
}
|
|
219
219
|
|
|
220
220
|
/** A table no handler writes (a reference table) declares column read actions only. */
|
|
@@ -344,8 +344,8 @@ export interface TableModel {
|
|
|
344
344
|
readonly files: Readonly<Record<string, string>>
|
|
345
345
|
/** The columns that declare their own read actions, as declared (also those equal to the table's). */
|
|
346
346
|
readonly columnReads: Readonly<Record<string, readonly string[]>>
|
|
347
|
-
/** The columns that declare their own write
|
|
348
|
-
readonly columnWrites: Readonly<Record<string, string>>
|
|
347
|
+
/** The columns that declare their own write actions, as declared: only a capability of one of them updates them. */
|
|
348
|
+
readonly columnWrites: Readonly<Record<string, readonly string[]>>
|
|
349
349
|
/** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
|
|
350
350
|
readonly dates: NameSet
|
|
351
351
|
/** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
|
|
@@ -819,7 +819,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
|
|
|
819
819
|
const byConvention = nameSet(unnamed)
|
|
820
820
|
const restricted: string[] = []
|
|
821
821
|
const columnReads: Record<string, readonly string[]> = {}
|
|
822
|
-
const columnWrites: Record<string, string> = {}
|
|
822
|
+
const columnWrites: Record<string, readonly string[]> = {}
|
|
823
823
|
const columnsInput = ownEntry(policy, 'columns')
|
|
824
824
|
const columnPolicies = columnsInput === undefined ? freeze({}) : plainRecord(columnsInput, `${table}: columns`)
|
|
825
825
|
const declared = ownKeys(columnPolicies)
|
|
@@ -846,7 +846,10 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
|
|
|
846
846
|
throw new PolicyError(viewWrite(table))
|
|
847
847
|
}
|
|
848
848
|
if (writeInput !== undefined) {
|
|
849
|
-
|
|
849
|
+
const writes = isArray(writeInput)
|
|
850
|
+
? distinctActions(table, writeInput, `columns.${name}.write`, action)
|
|
851
|
+
: freeze([action(writeInput, `columns.${name}.write`)])
|
|
852
|
+
setOwn(columnWrites, name, columnWrite(table, name, writes, actions, update))
|
|
850
853
|
}
|
|
851
854
|
}
|
|
852
855
|
const hidden = nameSet(restricted)
|
|
@@ -973,19 +976,23 @@ function parseFileColumns(
|
|
|
973
976
|
}
|
|
974
977
|
|
|
975
978
|
/**
|
|
976
|
-
* A column's own write
|
|
977
|
-
*
|
|
979
|
+
* A column's own write actions. A table update action may be one of them: it then writes the column beside its update
|
|
980
|
+
* list. Naming exactly the table's update actions says what `update` says, so that form is refused.
|
|
978
981
|
*/
|
|
979
|
-
function columnWrite(table: string, name: string,
|
|
982
|
+
function columnWrite(table: string, name: string, writes: readonly string[], actions: ActionModel, update: NameSet): readonly string[] {
|
|
980
983
|
if (inSet(update, name)) {
|
|
981
984
|
throw new PolicyError(
|
|
982
|
-
`${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${
|
|
985
|
+
`${table}: ${name} is in update, which the table's update action writes, and declares its own write action ${
|
|
986
|
+
writes.join(', ')
|
|
987
|
+
}; remove it from update`,
|
|
983
988
|
)
|
|
984
989
|
}
|
|
985
|
-
if (
|
|
986
|
-
throw new PolicyError(
|
|
990
|
+
if (everyIncluded(writes, actions.update) && everyIncluded(actions.update, writes)) {
|
|
991
|
+
throw new PolicyError(
|
|
992
|
+
`${table}: columns.${name}.write names ${writes.join(', ')}, the table's update action; list ${name} in update instead`,
|
|
993
|
+
)
|
|
987
994
|
}
|
|
988
|
-
return
|
|
995
|
+
return writes
|
|
989
996
|
}
|
|
990
997
|
|
|
991
998
|
/**
|
|
@@ -1002,7 +1009,7 @@ function parseQueue(
|
|
|
1002
1009
|
readonly version: string | undefined
|
|
1003
1010
|
readonly actions: ActionModel
|
|
1004
1011
|
readonly update: NameSet
|
|
1005
|
-
readonly columnWrites: Readonly<Record<string, string>>
|
|
1012
|
+
readonly columnWrites: Readonly<Record<string, readonly string[]>>
|
|
1006
1013
|
},
|
|
1007
1014
|
): QueueModel {
|
|
1008
1015
|
const queue = plainRecord(input, `${table}: queue`)
|
|
@@ -1055,22 +1062,39 @@ function parseColumnSet(table: string, input: unknown, column: (name: unknown, f
|
|
|
1055
1062
|
}
|
|
1056
1063
|
|
|
1057
1064
|
/**
|
|
1058
|
-
* The columns a capability of `action` updates in `model`: the update list for
|
|
1059
|
-
*
|
|
1065
|
+
* The columns a capability of `action` updates in `model`: the update list for a table update action, and every
|
|
1066
|
+
* column that lists it among its own write actions; none for an action that writes nothing here.
|
|
1060
1067
|
*/
|
|
1061
1068
|
export function updatableBy(model: TableModel, action: string): NameSet {
|
|
1062
|
-
|
|
1069
|
+
const owned = columnsWrittenBy(model, action)
|
|
1070
|
+
if (!includes(model.actions.update, action)) {
|
|
1071
|
+
return nameSet(owned)
|
|
1072
|
+
}
|
|
1073
|
+
if (owned.length === 0) {
|
|
1063
1074
|
return model.update
|
|
1064
1075
|
}
|
|
1076
|
+
const listed = namesOf(model.update)
|
|
1077
|
+
const columns: string[] = []
|
|
1078
|
+
for (let index = 0; index < listed.length; index++) {
|
|
1079
|
+
columns[columns.length] = listed[index] ?? ''
|
|
1080
|
+
}
|
|
1081
|
+
for (let index = 0; index < owned.length; index++) {
|
|
1082
|
+
columns[columns.length] = owned[index] ?? ''
|
|
1083
|
+
}
|
|
1084
|
+
return nameSet(columns)
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** The columns that list `action` among their own write actions. */
|
|
1088
|
+
function columnsWrittenBy(model: TableModel, action: string): readonly string[] {
|
|
1065
1089
|
const names = ownKeys(model.columnWrites)
|
|
1066
1090
|
const columns: string[] = []
|
|
1067
1091
|
for (let index = 0; index < names.length; index++) {
|
|
1068
1092
|
const name = names[index] ?? ''
|
|
1069
|
-
if (model.columnWrites[
|
|
1093
|
+
if (includes(ownEntry(model.columnWrites, name) ?? [], action)) {
|
|
1070
1094
|
columns[columns.length] = name
|
|
1071
1095
|
}
|
|
1072
1096
|
}
|
|
1073
|
-
return
|
|
1097
|
+
return columns
|
|
1074
1098
|
}
|
|
1075
1099
|
|
|
1076
1100
|
/**
|
|
@@ -1097,13 +1121,7 @@ export function namesAction(model: TableModel, action: string): boolean {
|
|
|
1097
1121
|
if (includes(read, action) || includes(insert, action) || includes(update, action) || includes(remove, action)) {
|
|
1098
1122
|
return true
|
|
1099
1123
|
}
|
|
1100
|
-
|
|
1101
|
-
for (let index = 0; index < columns.length; index++) {
|
|
1102
|
-
if (model.columnWrites[columns[index] ?? ''] === action) {
|
|
1103
|
-
return true
|
|
1104
|
-
}
|
|
1105
|
-
}
|
|
1106
|
-
return false
|
|
1124
|
+
return columnsWrittenBy(model, action).length > 0
|
|
1107
1125
|
}
|
|
1108
1126
|
|
|
1109
1127
|
/**
|
|
@@ -1186,9 +1204,12 @@ export function updateActions(model: TableModel): readonly string[] {
|
|
|
1186
1204
|
}
|
|
1187
1205
|
const names = ownKeys(model.columnWrites)
|
|
1188
1206
|
for (let index = 0; index < names.length; index++) {
|
|
1189
|
-
const
|
|
1190
|
-
|
|
1191
|
-
|
|
1207
|
+
const writes = ownEntry(model.columnWrites, names[index] ?? '') ?? []
|
|
1208
|
+
for (let position = 0; position < writes.length; position++) {
|
|
1209
|
+
const write = writes[position] ?? ''
|
|
1210
|
+
if (!includes(actions, write)) {
|
|
1211
|
+
actions[actions.length] = write
|
|
1212
|
+
}
|
|
1192
1213
|
}
|
|
1193
1214
|
}
|
|
1194
1215
|
return actions
|
|
@@ -1755,7 +1776,10 @@ function tableActionNames(table: LinkedTable): NameSet {
|
|
|
1755
1776
|
}
|
|
1756
1777
|
const writes = ownKeys(table.columnWrites)
|
|
1757
1778
|
for (let index = 0; index < writes.length; index++) {
|
|
1758
|
-
|
|
1779
|
+
const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
|
|
1780
|
+
for (let position = 0; position < actions.length; position++) {
|
|
1781
|
+
names[names.length] = actions[position] ?? ''
|
|
1782
|
+
}
|
|
1759
1783
|
}
|
|
1760
1784
|
return nameSet(names)
|
|
1761
1785
|
}
|
|
@@ -1772,7 +1796,10 @@ function writeActionNames(table: LinkedTable): NameSet {
|
|
|
1772
1796
|
}
|
|
1773
1797
|
const writes = ownKeys(table.columnWrites)
|
|
1774
1798
|
for (let index = 0; index < writes.length; index++) {
|
|
1775
|
-
|
|
1799
|
+
const actions = ownEntry(table.columnWrites, writes[index] ?? '') ?? []
|
|
1800
|
+
for (let position = 0; position < actions.length; position++) {
|
|
1801
|
+
names[names.length] = actions[position] ?? ''
|
|
1802
|
+
}
|
|
1776
1803
|
}
|
|
1777
1804
|
return nameSet(names)
|
|
1778
1805
|
}
|
package/src/tables.ts
CHANGED
|
@@ -172,10 +172,10 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
|
|
|
172
172
|
const declared = [...ownKeys(model.columnReads), ...ownKeys(model.columnWrites)]
|
|
173
173
|
for (let index = 0; index < declared.length; index++) {
|
|
174
174
|
const name = declared[index] ?? ''
|
|
175
|
-
// A single
|
|
175
|
+
// A single action stays its text, so a policy that names one keeps its digest.
|
|
176
176
|
const read = actionArtifact(ownEntry(model.columnReads, name) ?? [])
|
|
177
|
-
const write = ownEntry(model.columnWrites, name)
|
|
178
|
-
setOwn(columns, name, { ...(read === null ? {} : { read }), ...(write ===
|
|
177
|
+
const write = actionArtifact(ownEntry(model.columnWrites, name) ?? [])
|
|
178
|
+
setOwn(columns, name, { ...(read === null ? {} : { read }), ...(write === null ? {} : { write }) })
|
|
179
179
|
}
|
|
180
180
|
return {
|
|
181
181
|
scope: scopeOf(model.scope),
|
package/src/testing-shared.ts
CHANGED
|
@@ -789,11 +789,14 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
789
789
|
return stored
|
|
790
790
|
}
|
|
791
791
|
|
|
792
|
-
/**
|
|
792
|
+
/**
|
|
793
|
+
* A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. Either
|
|
794
|
+
* holds a random v4 uuid's 122 bits, so a large seed never collides on a key.
|
|
795
|
+
*/
|
|
793
796
|
function scopeValue(table: string, name: string, dimension: string, world: string): string {
|
|
794
797
|
const column = columnOf(table, name)
|
|
795
798
|
if (column.uuid) return crypto.randomUUID()
|
|
796
|
-
if (column.text) return `${dimension}-${world}-${
|
|
799
|
+
if (column.text) return `${dimension}-${world}-${crypto.randomUUID()}`
|
|
797
800
|
throw new Error(`${table}.${name} holds a ${dimension} as ${column.type}; a key or containment column holds its scope value as text or uuid`)
|
|
798
801
|
}
|
|
799
802
|
|
package/types/src/framework.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export type { FileBinding } from './file-columns';
|
|
|
9
9
|
export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references';
|
|
10
10
|
export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables';
|
|
11
11
|
export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
|
|
12
|
-
export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
|
|
12
|
+
export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes';
|
|
13
13
|
export type { DataAccess, DataHandles, DataSite } from './orm';
|
|
14
14
|
export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
|
|
15
15
|
export type { RequestReceipt, RequestReceipts } from './request-receipts';
|
|
@@ -54,6 +54,12 @@ export interface JobLeases {
|
|
|
54
54
|
* the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
|
|
55
55
|
*/
|
|
56
56
|
finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>;
|
|
57
|
+
/**
|
|
58
|
+
* Gives back a lease under which no run started: frees it and leaves every wake as it is, owned ones disowned, and
|
|
59
|
+
* records no run (no status, end or duration). A process schedule's timer releases a lease whose take owned no due
|
|
60
|
+
* wake (ADR-0080). `false` when `fence` no longer held it.
|
|
61
|
+
*/
|
|
62
|
+
release(fence: LeaseFence): Promise<boolean>;
|
|
57
63
|
/** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
|
|
58
64
|
markPending(job: string): Promise<void>;
|
|
59
65
|
/**
|
package/types/src/job-wakes.d.ts
CHANGED
|
@@ -31,9 +31,15 @@ export type FinishWakes =
|
|
|
31
31
|
/** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
|
|
32
32
|
{
|
|
33
33
|
readonly kind: 'completed';
|
|
34
|
+
/**
|
|
35
|
+
* With `scheduled`, the next fire is written only when the stored schedule (`keepSchedule`) declares its key, read
|
|
36
|
+
* in the finish's transaction: under a process schedule, a run of an older deploy writes no removed job's or
|
|
37
|
+
* changed expression's fire (ADR-0080).
|
|
38
|
+
*/
|
|
34
39
|
readonly nextCron?: {
|
|
35
40
|
readonly expression: string;
|
|
36
41
|
readonly dueAt: Date;
|
|
42
|
+
readonly scheduled?: boolean;
|
|
37
43
|
};
|
|
38
44
|
}
|
|
39
45
|
/** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
|
|
@@ -53,18 +59,31 @@ export interface JobWakes {
|
|
|
53
59
|
pending(job: string): Promise<readonly Wake[]>;
|
|
54
60
|
/**
|
|
55
61
|
* When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
|
|
56
|
-
* held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given
|
|
62
|
+
* held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given;
|
|
63
|
+
* with `jobs`, of those jobs only, so a wake of a job this process does not run never holds its timer.
|
|
57
64
|
*/
|
|
58
|
-
next(using?: Session): Promise<Date | null>;
|
|
65
|
+
next(using?: Session, jobs?: readonly string[]): Promise<Date | null>;
|
|
59
66
|
/** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
|
|
60
|
-
untilNext(using?: Session): Promise<number | null>;
|
|
67
|
+
untilNext(using?: Session, jobs?: readonly string[]): Promise<number | null>;
|
|
68
|
+
/**
|
|
69
|
+
* Where no crontab runs (ADR-0080), in one transaction: raises the stored schedule generation to `generation` when that
|
|
70
|
+
* one is higher in byte order, with the cron keys `fires` declare, and when `generation` is then the stored one,
|
|
71
|
+
* reconciles the wakes against `fires` (as `reconcile`) and adds each fire's wake under its job's cron key where none
|
|
72
|
+
* is pending (an existing one, overdue or not, is left as it is and not locked, so a lease taken meanwhile still owns
|
|
73
|
+
* it). Answers whether `generation` is the stored one; a process of an older one writes nothing. The generation's row stays
|
|
74
|
+
* locked until the transaction commits, so on Postgres a newer generation waits for an older one's seed and reconciles
|
|
75
|
+
* after it, and an older one queued behind a newer one reads the newer and writes nothing. A UUIDv7, lowercase: a
|
|
76
|
+
* later deploy's sorts later.
|
|
77
|
+
*/
|
|
78
|
+
keepSchedule(generation: string, fires: readonly ScheduledFire[]): Promise<boolean>;
|
|
61
79
|
/** The database's clock, read in `using` when given: a wake due now is due by it. */
|
|
62
80
|
now(using?: Session): Promise<Date>;
|
|
63
81
|
/**
|
|
64
82
|
* Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
|
|
65
|
-
* each declared job's cron wake whose key names another expression; answers how many it deleted.
|
|
83
|
+
* each declared job's cron wake whose key names another expression; answers how many it deleted. In `using` when
|
|
84
|
+
* given.
|
|
66
85
|
*/
|
|
67
|
-
reconcile(declared: readonly DeclaredJob[]): Promise<number>;
|
|
86
|
+
reconcile(declared: readonly DeclaredJob[], using?: Session): Promise<number>;
|
|
68
87
|
/**
|
|
69
88
|
* The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
|
|
70
89
|
* now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
|
|
@@ -76,6 +95,10 @@ export interface JobWakes {
|
|
|
76
95
|
*/
|
|
77
96
|
expiredHolders(): Promise<readonly string[]>;
|
|
78
97
|
}
|
|
98
|
+
/** A declared job and its next fire, which `keepSchedule` seeds; `null` when its expression has none in the window. */
|
|
99
|
+
export interface ScheduledFire extends DeclaredJob {
|
|
100
|
+
readonly dueAt: Date | null;
|
|
101
|
+
}
|
|
79
102
|
/** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
|
|
80
103
|
export interface DeclaredJob {
|
|
81
104
|
readonly job: string;
|
|
@@ -5,6 +5,7 @@ export declare const WEBHOOK_DELIVERIES_TABLE = "fabrika_webhook_deliveries";
|
|
|
5
5
|
export declare const JOB_LEASES_TABLE = "fabrika_job_leases";
|
|
6
6
|
export declare const JOB_KICKS_TABLE = "fabrika_job_kicks";
|
|
7
7
|
export declare const JOB_WAKES_TABLE = "fabrika_wakes";
|
|
8
|
+
export declare const JOB_SCHEDULE_TABLE = "fabrika_job_schedule";
|
|
8
9
|
export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
|
|
9
10
|
export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
|
|
10
11
|
export declare const FORM_FILES_TABLE = "fabrika_form_files";
|
package/types/src/orm-types.d.ts
CHANGED
|
@@ -49,15 +49,17 @@ type ConditionedOf<P, T> = PolicyOf<P, T> extends {
|
|
|
49
49
|
type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends {
|
|
50
50
|
readonly columns: infer C;
|
|
51
51
|
} ? C : never;
|
|
52
|
-
/** The
|
|
52
|
+
/** The actions a column's own `write` names: one action, or each of a list. */
|
|
53
|
+
type WriteActionsOf<P> = P extends {
|
|
54
|
+
readonly write: infer W;
|
|
55
|
+
} ? W extends readonly (infer L extends string)[] ? L : W extends string ? W : never : never;
|
|
56
|
+
/** The columns that list `A` among their own write actions. */
|
|
53
57
|
type ColumnsWrittenBy<C, A> = {
|
|
54
|
-
[K in keyof C]: C[K]
|
|
55
|
-
readonly write: A;
|
|
56
|
-
} ? K : never;
|
|
58
|
+
[K in keyof C]: [A] extends [WriteActionsOf<C[K]>] ? K : never;
|
|
57
59
|
}[keyof C];
|
|
58
60
|
/**
|
|
59
61
|
* Each action that updates the table, with the values a capability of it updates: the update action its update list,
|
|
60
|
-
* a column's own write action the columns that
|
|
62
|
+
* a column's own write action the columns that list it (an update action both), and no other.
|
|
61
63
|
*/
|
|
62
64
|
type UpdatesOf<DB, P, T extends keyof DB> = {
|
|
63
65
|
readonly [A in ActionOf<P, T, 'update'>]: UpdateValues<DB, P, T>;
|
|
@@ -65,9 +67,7 @@ type UpdatesOf<DB, P, T extends keyof DB> = {
|
|
|
65
67
|
readonly [A in ColumnWriteAction<ColumnPoliciesOf<P, T>>]: Flat<Pick<Updateable<DB[T]>, ColumnsWrittenBy<ColumnPoliciesOf<P, T>, A> & keyof Updateable<DB[T]>>>;
|
|
66
68
|
};
|
|
67
69
|
type ColumnWriteAction<C> = {
|
|
68
|
-
[K in keyof C]: C[K]
|
|
69
|
-
readonly write: infer A extends string;
|
|
70
|
-
} ? A : never;
|
|
70
|
+
[K in keyof C]: WriteActionsOf<C[K]>;
|
|
71
71
|
}[keyof C];
|
|
72
72
|
/** One table, as every handle reads it. */
|
|
73
73
|
export interface IndexedTable {
|
package/types/src/policy.d.ts
CHANGED
|
@@ -192,16 +192,16 @@ export type FilePolicies<Col extends string> = {
|
|
|
192
192
|
};
|
|
193
193
|
/**
|
|
194
194
|
* A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
|
|
195
|
-
* without one it falls back to the table's read action. `write`: only a capability of
|
|
196
|
-
*
|
|
195
|
+
* without one it falls back to the table's read action. `write`: only a capability of one of those actions updates the
|
|
196
|
+
* column, so the column is not in `update`; a listed table update action writes it beside its update list.
|
|
197
197
|
*/
|
|
198
198
|
export type ColumnPolicies<Col extends string, A extends string> = {
|
|
199
199
|
readonly [C in Col]?: ColumnPolicy<A>;
|
|
200
200
|
};
|
|
201
|
-
/** A column's own read actions (one, or a list as a table
|
|
201
|
+
/** A column's own read actions and its own write actions (each one, or a list as a table operation takes), or both. */
|
|
202
202
|
export interface ColumnPolicy<A extends string> {
|
|
203
203
|
readonly read?: TableAction<A>;
|
|
204
|
-
readonly write?: A
|
|
204
|
+
readonly write?: TableAction<A>;
|
|
205
205
|
}
|
|
206
206
|
/** A table no handler writes (a reference table) declares column read actions only. */
|
|
207
207
|
export type ColumnReadPolicies<Col extends string, A extends string> = {
|
|
@@ -335,8 +335,8 @@ export interface TableModel {
|
|
|
335
335
|
readonly files: Readonly<Record<string, string>>;
|
|
336
336
|
/** The columns that declare their own read actions, as declared (also those equal to the table's). */
|
|
337
337
|
readonly columnReads: Readonly<Record<string, readonly string[]>>;
|
|
338
|
-
/** The columns that declare their own write
|
|
339
|
-
readonly columnWrites: Readonly<Record<string, string>>;
|
|
338
|
+
/** The columns that declare their own write actions, as declared: only a capability of one of them updates them. */
|
|
339
|
+
readonly columnWrites: Readonly<Record<string, readonly string[]>>;
|
|
340
340
|
/** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
|
|
341
341
|
readonly dates: NameSet;
|
|
342
342
|
/** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
|
|
@@ -500,8 +500,8 @@ export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never] ? Unavaila
|
|
|
500
500
|
*/
|
|
501
501
|
export declare function readTables(columns: unknown, policies: unknown, vocabulary: unknown): Tables<unknown, unknown>;
|
|
502
502
|
/**
|
|
503
|
-
* The columns a capability of `action` updates in `model`: the update list for
|
|
504
|
-
*
|
|
503
|
+
* The columns a capability of `action` updates in `model`: the update list for a table update action, and every
|
|
504
|
+
* column that lists it among its own write actions; none for an action that writes nothing here.
|
|
505
505
|
*/
|
|
506
506
|
export declare function updatableBy(model: TableModel, action: string): NameSet;
|
|
507
507
|
/**
|