@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.61
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 +9 -5
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +51 -2
- package/src/codegen-sqlite.ts +59 -11
- package/src/codegen.ts +181 -42
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/description.ts +55 -9
- package/src/errors.ts +8 -4
- package/src/file-columns.ts +52 -10
- package/src/framework.ts +5 -2
- package/src/guard.ts +365 -15
- package/src/index.ts +8 -0
- package/src/job-leases.ts +19 -2
- package/src/job-wakes.ts +183 -33
- package/src/json.ts +124 -0
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +93 -0
- package/src/migrations.ts +99 -0
- package/src/nodes.ts +33 -14
- package/src/notifications.ts +152 -0
- package/src/orm-types.ts +208 -74
- package/src/orm.ts +417 -158
- package/src/policy.ts +1973 -141
- package/src/push-subscriptions.ts +287 -0
- package/src/registry.ts +50 -1
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +39 -11
- package/src/sqlite-migrate.ts +102 -1
- package/src/sqlite.ts +46 -1
- package/src/store.ts +1933 -168
- package/src/tables.ts +156 -6
- package/src/temporal.ts +8 -1
- package/src/testing-shared.ts +758 -140
- package/src/testing-sqlite.ts +212 -40
- package/src/testing.ts +151 -22
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +50 -2
- package/types/src/codegen-sqlite.d.ts +8 -1
- package/types/src/codegen.d.ts +54 -10
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/description.d.ts +31 -9
- package/types/src/errors.d.ts +7 -4
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +5 -2
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +4 -3
- package/types/src/job-leases.d.ts +8 -1
- package/types/src/job-wakes.d.ts +28 -5
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations.d.ts +5 -0
- package/types/src/nodes.d.ts +5 -1
- package/types/src/notifications.d.ts +37 -0
- package/types/src/orm-types.d.ts +165 -73
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +347 -23
- package/types/src/push-subscriptions.d.ts +49 -0
- package/types/src/registry.d.ts +36 -1
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/sqlite-migrate.d.ts +32 -0
- package/types/src/store.d.ts +118 -31
- package/types/src/tables.d.ts +8 -2
- package/types/src/temporal.d.ts +4 -1
- package/types/src/testing-shared.d.ts +112 -23
- package/types/src/testing-sqlite.d.ts +17 -2
- package/types/src/testing.d.ts +1 -1
- package/types/src/vocabulary-tables.d.ts +169 -22
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/json.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// JSON columns at the layer's boundary: `jsonb` on Postgres, a column declared `JSONB` on SQLite (the column list's
|
|
2
|
+
// `json`). A write takes a JSON value, checked and serialized here, and binds its text as one parameter: Postgres reads
|
|
3
|
+
// an untyped text parameter into `jsonb`, SQLite stores the text. A read answers the parsed value: `Bun.SQL` decodes
|
|
4
|
+
// `jsonb` itself, and `sqliteJson` parses SQLite's text. JS `null` is SQL NULL in both directions, so a top-level JSON
|
|
5
|
+
// `null` written by `ctx.sql` reads as `null` too. A JSON column is never compared, ordered, grouped or aggregated by
|
|
6
|
+
// the layer; a path condition is `ctx.sql`'s (`->>`).
|
|
7
|
+
|
|
8
|
+
import { hasOwn, isArray, OBJECT_PROTOTYPE, ownDescriptor, ownNames, ownSymbols, parseList, prototypeOf } from './builtins'
|
|
9
|
+
import { QueryRefusedError } from './errors'
|
|
10
|
+
|
|
11
|
+
const stringify = JSON.stringify
|
|
12
|
+
const parse = JSON.parse
|
|
13
|
+
const isFinite = Number.isFinite
|
|
14
|
+
|
|
15
|
+
/** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
|
|
16
|
+
export type JsonValue = string | number | boolean | null | readonly JsonValue[] | { readonly [key: string]: JsonValue | undefined }
|
|
17
|
+
|
|
18
|
+
/** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
|
|
19
|
+
export type JsonColumnValue = Exclude<JsonValue, null>
|
|
20
|
+
|
|
21
|
+
/** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
|
|
22
|
+
export const MAX_JSON_DEPTH = 64
|
|
23
|
+
|
|
24
|
+
function refusal(where: string, detail: string): QueryRefusedError {
|
|
25
|
+
return new QueryRefusedError('invalid_value', `${where} takes a JSON value (${detail})`)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Half of a surrogate pair, which Postgres refuses in `jsonb` text and SQLite would store. */
|
|
29
|
+
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
|
|
30
|
+
const NUL = String.fromCharCode(0)
|
|
31
|
+
|
|
32
|
+
function text(value: string, where: string): string {
|
|
33
|
+
if (value.includes(NUL) || LONE_SURROGATE.test(value)) {
|
|
34
|
+
throw refusal(where, 'a string or key holds no NUL character and no lone surrogate')
|
|
35
|
+
}
|
|
36
|
+
return stringify(value)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function written(value: unknown, where: string, depth: number): string {
|
|
40
|
+
if (typeof value === 'string') {
|
|
41
|
+
return text(value, where)
|
|
42
|
+
}
|
|
43
|
+
if (value === null || typeof value === 'boolean') {
|
|
44
|
+
return stringify(value)
|
|
45
|
+
}
|
|
46
|
+
if (typeof value === 'number') {
|
|
47
|
+
if (!isFinite(value)) {
|
|
48
|
+
throw refusal(where, 'a number is finite')
|
|
49
|
+
}
|
|
50
|
+
return stringify(value)
|
|
51
|
+
}
|
|
52
|
+
if (typeof value !== 'object') {
|
|
53
|
+
throw refusal(where, `${typeof value} is not JSON`)
|
|
54
|
+
}
|
|
55
|
+
if (depth >= MAX_JSON_DEPTH) {
|
|
56
|
+
throw refusal(where, `nested at most ${MAX_JSON_DEPTH} deep, and never containing itself`)
|
|
57
|
+
}
|
|
58
|
+
if (isArray(value)) {
|
|
59
|
+
const items = parseList(value, (item) => {
|
|
60
|
+
if (item === undefined) {
|
|
61
|
+
throw refusal(where, 'an array holds no undefined')
|
|
62
|
+
}
|
|
63
|
+
return written(item, where, depth + 1)
|
|
64
|
+
})
|
|
65
|
+
if (items === undefined) {
|
|
66
|
+
throw refusal(where, 'an array is a plain array without holes or accessors')
|
|
67
|
+
}
|
|
68
|
+
let serialized = '['
|
|
69
|
+
for (let index = 0; index < items.length; index++) {
|
|
70
|
+
serialized += `${index === 0 ? '' : ','}${items[index] ?? ''}`
|
|
71
|
+
}
|
|
72
|
+
return `${serialized}]`
|
|
73
|
+
}
|
|
74
|
+
const prototype: unknown = prototypeOf(value)
|
|
75
|
+
if (prototype !== OBJECT_PROTOTYPE && prototype !== null) {
|
|
76
|
+
throw refusal(where, 'an object is a plain object, not an instance of a class such as a Date or a Map')
|
|
77
|
+
}
|
|
78
|
+
if (ownSymbols(value).length > 0) {
|
|
79
|
+
throw refusal(where, 'an object has string keys only')
|
|
80
|
+
}
|
|
81
|
+
const keys = ownNames(value)
|
|
82
|
+
let serialized = '{'
|
|
83
|
+
let first = true
|
|
84
|
+
for (let index = 0; index < keys.length; index++) {
|
|
85
|
+
const key = keys[index] ?? ''
|
|
86
|
+
const descriptor = ownDescriptor(value, key)
|
|
87
|
+
if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
|
|
88
|
+
throw refusal(where, `${key} is an accessor`)
|
|
89
|
+
}
|
|
90
|
+
const member: unknown = descriptor.value
|
|
91
|
+
if (member === undefined) {
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
serialized += `${first ? '' : ','}${text(key, where)}:${written(member, where, depth + 1)}`
|
|
95
|
+
first = false
|
|
96
|
+
}
|
|
97
|
+
return `${serialized}}`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
|
|
102
|
+
* and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
|
|
103
|
+
*/
|
|
104
|
+
export function jsonInput(value: unknown, where: string): string {
|
|
105
|
+
return written(value, where, 0)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
|
|
110
|
+
* NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
|
|
111
|
+
*/
|
|
112
|
+
export function sqliteJson(value: unknown, where: string): unknown {
|
|
113
|
+
if (typeof value === 'number') {
|
|
114
|
+
return value
|
|
115
|
+
}
|
|
116
|
+
if (typeof value === 'string') {
|
|
117
|
+
try {
|
|
118
|
+
return parse(value)
|
|
119
|
+
} catch {
|
|
120
|
+
// Fall through: the text is not JSON, which no write of the layer stores.
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
throw new QueryRefusedError('unexpected_row', `${where} came back as something other than JSON text, the form a JSON column is stored in on SQLite`)
|
|
124
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// A list's cursor, signed with the database's own key (`fabrika_list_cursor_key`, which the framework migration writes
|
|
2
|
+
// once), so a cursor a client edited is the caller's `list_cursor`, never a statement the database refuses (a 500) or a
|
|
3
|
+
// page from a position no page ended at. A cursor is `<payload>.<signature>`: the payload is the base64url JSON of the
|
|
4
|
+
// last row's order values, and the signature an HMAC-SHA256 over the list it belongs to (its table and whole order) and
|
|
5
|
+
// the payload. The list is signed, not carried, so the cursor names no table or column.
|
|
6
|
+
|
|
7
|
+
import { parseList } from './builtins'
|
|
8
|
+
import { runFixedStatement, type Session } from './database'
|
|
9
|
+
import { QueryRefusedError } from './errors'
|
|
10
|
+
import type { DialectTexts } from './job-leases'
|
|
11
|
+
import { LIST_CURSOR_KEY_TABLE } from './migrations'
|
|
12
|
+
|
|
13
|
+
/** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
|
|
14
|
+
export type CursorValue = string | null
|
|
15
|
+
|
|
16
|
+
const SQL_KEY: DialectTexts = {
|
|
17
|
+
postgres: `select secret from ${LIST_CURSOR_KEY_TABLE} where id = 1`,
|
|
18
|
+
sqlite: `select secret from ${LIST_CURSOR_KEY_TABLE} where id = 1`,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const BASE64URL = /^[A-Za-z0-9_-]+$/
|
|
22
|
+
|
|
23
|
+
/** The database's cursor key, read in `session`; the framework migration wrote it, so its absence is no caller's fault. */
|
|
24
|
+
export async function cursorKey(session: Session): Promise<CryptoKey> {
|
|
25
|
+
const [row] = await runFixedStatement(session, SQL_KEY[session.dialect], [])
|
|
26
|
+
const secret: unknown = typeof row === 'object' && row !== null ? Reflect.get(row, 'secret') : undefined
|
|
27
|
+
if (typeof secret !== 'string' || secret.length === 0) {
|
|
28
|
+
throw new QueryRefusedError('unexpected_row', `${LIST_CURSOR_KEY_TABLE} holds no key; the framework migrations did not run`)
|
|
29
|
+
}
|
|
30
|
+
return await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify'])
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function signed(list: string, payload: string): Uint8Array<ArrayBuffer> {
|
|
34
|
+
return new TextEncoder().encode(`fabrika-list-cursor\n${list}\n${payload}`)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The cursor of the page after the row whose order values are `values`, in the list `list` names. */
|
|
38
|
+
export async function signCursor(key: () => Promise<CryptoKey>, list: string, values: readonly CursorValue[]): Promise<string> {
|
|
39
|
+
const payload = Buffer.from(JSON.stringify(values)).toString('base64url')
|
|
40
|
+
const signature = await crypto.subtle.sign('HMAC', await key(), signed(list, payload))
|
|
41
|
+
return `${payload}.${Buffer.from(signature).toString('base64url')}`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The order values of `after` when it is a cursor this database signed for the list `list` names, with one plain value
|
|
46
|
+
* per order column (`count`). Anything else is the caller's `list_cursor`: undecodable, unsigned, edited, of another
|
|
47
|
+
* list or order, or of another shape.
|
|
48
|
+
*/
|
|
49
|
+
export async function openCursor(key: () => Promise<CryptoKey>, list: string, after: unknown, count: number): Promise<readonly CursorValue[]> {
|
|
50
|
+
const refused = () => new QueryRefusedError('list_cursor', 'after takes the next cursor of a page of this same list')
|
|
51
|
+
if (typeof after !== 'string') {
|
|
52
|
+
throw refused()
|
|
53
|
+
}
|
|
54
|
+
const [payload = '', given = '', ...rest] = after.split('.')
|
|
55
|
+
if (rest.length > 0 || !BASE64URL.test(payload) || !BASE64URL.test(given)) {
|
|
56
|
+
throw refused()
|
|
57
|
+
}
|
|
58
|
+
const signature = Buffer.from(given, 'base64url')
|
|
59
|
+
// One spelling per signature: the last character's padding bits decode to nothing, and a cursor has exactly one.
|
|
60
|
+
if (signature.toString('base64url') !== given) {
|
|
61
|
+
throw refused()
|
|
62
|
+
}
|
|
63
|
+
if (!(await crypto.subtle.verify('HMAC', await key(), new Uint8Array(signature), signed(list, payload)))) {
|
|
64
|
+
throw refused()
|
|
65
|
+
}
|
|
66
|
+
let parsed: unknown
|
|
67
|
+
try {
|
|
68
|
+
parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
|
|
69
|
+
} catch {
|
|
70
|
+
throw refused()
|
|
71
|
+
}
|
|
72
|
+
const values = parseList(parsed, (value): CursorValue => {
|
|
73
|
+
if (typeof value === 'string' || value === null) {
|
|
74
|
+
return value
|
|
75
|
+
}
|
|
76
|
+
throw refused()
|
|
77
|
+
})
|
|
78
|
+
if (values === undefined || values.length !== count) {
|
|
79
|
+
throw refused()
|
|
80
|
+
}
|
|
81
|
+
return values
|
|
82
|
+
}
|
package/src/migrations-sqlite.ts
CHANGED
|
@@ -17,7 +17,12 @@ import {
|
|
|
17
17
|
type FrameworkMigration,
|
|
18
18
|
JOB_KICKS_TABLE,
|
|
19
19
|
JOB_LEASES_TABLE,
|
|
20
|
+
JOB_SCHEDULE_TABLE,
|
|
20
21
|
JOB_WAKES_TABLE,
|
|
22
|
+
LIST_CURSOR_KEY_TABLE,
|
|
23
|
+
NOTIFICATIONS_TABLE,
|
|
24
|
+
PUSH_SUBSCRIPTIONS_TABLE,
|
|
25
|
+
REQUEST_RECEIPTS_TABLE,
|
|
21
26
|
WEBHOOK_BINDINGS_TABLE,
|
|
22
27
|
WEBHOOK_DELIVERIES_TABLE,
|
|
23
28
|
} from './migrations'
|
|
@@ -158,6 +163,94 @@ CREATE INDEX ${FILE_DELETIONS_TABLE}_recorded_at ON ${FILE_DELETIONS_TABLE} (rec
|
|
|
158
163
|
sql: `-- The wakes the run holding the job's lease took when it took the lease: its finish consumes or retries exactly these.
|
|
159
164
|
-- 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
165
|
ALTER TABLE ${JOB_WAKES_TABLE} ADD COLUMN owned INTEGER NOT NULL DEFAULT 0 CHECK (owned IN (0, 1));
|
|
166
|
+
`,
|
|
167
|
+
}),
|
|
168
|
+
Object.freeze({
|
|
169
|
+
name: '0005_request_receipts.sql',
|
|
170
|
+
sql: `-- The answer of a mutation whose request carried a key (ADR-0078), for a repeat of that request: the principal's key,
|
|
171
|
+
-- the operation and the SHA-256 of its input, and the output's JSON. created_at is epoch milliseconds; each write prunes
|
|
172
|
+
-- a batch of receipts past the retention.
|
|
173
|
+
CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
|
|
174
|
+
principal TEXT NOT NULL,
|
|
175
|
+
request_key TEXT NOT NULL,
|
|
176
|
+
operation TEXT NOT NULL,
|
|
177
|
+
identity TEXT NOT NULL,
|
|
178
|
+
output TEXT NOT NULL,
|
|
179
|
+
created_at INTEGER NOT NULL,
|
|
180
|
+
PRIMARY KEY (principal, request_key)
|
|
181
|
+
) STRICT;
|
|
182
|
+
CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
|
|
183
|
+
`,
|
|
184
|
+
}),
|
|
185
|
+
Object.freeze({
|
|
186
|
+
name: '0006_list_cursor_key.sql',
|
|
187
|
+
sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
|
|
188
|
+
-- here once and only read afterwards. 32 random bytes as hex.
|
|
189
|
+
CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
|
|
190
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
191
|
+
secret TEXT NOT NULL
|
|
192
|
+
) STRICT;
|
|
193
|
+
INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, hex(randomblob(32)));
|
|
194
|
+
`,
|
|
195
|
+
}),
|
|
196
|
+
Object.freeze({
|
|
197
|
+
name: '0007_job_schedule.sql',
|
|
198
|
+
sql: `-- Which deploy keeps the cron wakes where no crontab runs (ADR-0080): one row, the highest generation a serving process
|
|
199
|
+
-- has seen. The Durable Object keeps its schedule itself and never writes it; the table keeps both bundles alike.
|
|
200
|
+
CREATE TABLE ${JOB_SCHEDULE_TABLE} (
|
|
201
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
202
|
+
generation TEXT NOT NULL
|
|
203
|
+
) STRICT;
|
|
204
|
+
`,
|
|
205
|
+
}),
|
|
206
|
+
Object.freeze({
|
|
207
|
+
name: '0008_job_schedule_declared.sql',
|
|
208
|
+
sql: `-- The cron keys the stored generation's deploy declares, as a JSON array (see the Postgres bundle's 0014).
|
|
209
|
+
ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
|
|
210
|
+
`,
|
|
211
|
+
}),
|
|
212
|
+
Object.freeze({
|
|
213
|
+
name: '0009_push_subscriptions.sql',
|
|
214
|
+
sql: `-- A browser's Web Push subscription (ADR-0088), bound to the principal who recorded it; a row whose gone_at is set is a
|
|
215
|
+
-- tombstone (see the Postgres bundle's 0015). Times are epoch milliseconds.
|
|
216
|
+
CREATE TABLE ${PUSH_SUBSCRIPTIONS_TABLE} (
|
|
217
|
+
id TEXT PRIMARY KEY,
|
|
218
|
+
principal TEXT NOT NULL,
|
|
219
|
+
endpoint TEXT NOT NULL UNIQUE,
|
|
220
|
+
p256dh TEXT,
|
|
221
|
+
auth TEXT,
|
|
222
|
+
vapid_key TEXT,
|
|
223
|
+
cursor TEXT,
|
|
224
|
+
next_attempt_at INTEGER,
|
|
225
|
+
recorded_at INTEGER NOT NULL,
|
|
226
|
+
gone_at INTEGER,
|
|
227
|
+
CONSTRAINT ${PUSH_SUBSCRIPTIONS_TABLE}_tombstone CHECK (
|
|
228
|
+
(gone_at IS NULL AND p256dh IS NOT NULL AND auth IS NOT NULL AND vapid_key IS NOT NULL)
|
|
229
|
+
OR (gone_at IS NOT NULL AND p256dh IS NULL AND auth IS NULL AND vapid_key IS NULL AND next_attempt_at IS NULL)
|
|
230
|
+
)
|
|
231
|
+
) STRICT;
|
|
232
|
+
CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_principal ON ${PUSH_SUBSCRIPTIONS_TABLE} (principal, recorded_at) WHERE gone_at IS NULL;
|
|
233
|
+
CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_gone_at ON ${PUSH_SUBSCRIPTIONS_TABLE} (gone_at) WHERE gone_at IS NOT NULL;
|
|
234
|
+
`,
|
|
235
|
+
}),
|
|
236
|
+
Object.freeze({
|
|
237
|
+
name: '0010_notifications.sql',
|
|
238
|
+
sql: `-- A notification for one principal (ADR-0088 §6); see the Postgres bundle's 0016. The id is a UUIDv7 as lowercase
|
|
239
|
+
-- text, so text order is the order written.
|
|
240
|
+
CREATE TABLE ${NOTIFICATIONS_TABLE} (
|
|
241
|
+
id TEXT PRIMARY KEY,
|
|
242
|
+
principal TEXT NOT NULL,
|
|
243
|
+
title TEXT NOT NULL,
|
|
244
|
+
body TEXT NOT NULL,
|
|
245
|
+
path TEXT NOT NULL,
|
|
246
|
+
action TEXT NOT NULL,
|
|
247
|
+
dimension TEXT,
|
|
248
|
+
scope_value TEXT,
|
|
249
|
+
created_at INTEGER NOT NULL,
|
|
250
|
+
CONSTRAINT ${NOTIFICATIONS_TABLE}_about CHECK ((dimension IS NULL) = (scope_value IS NULL))
|
|
251
|
+
) STRICT;
|
|
252
|
+
CREATE INDEX ${NOTIFICATIONS_TABLE}_principal ON ${NOTIFICATIONS_TABLE} (principal, id);
|
|
253
|
+
CREATE INDEX ${NOTIFICATIONS_TABLE}_created_at ON ${NOTIFICATIONS_TABLE} (created_at);
|
|
161
254
|
`,
|
|
162
255
|
}),
|
|
163
256
|
])
|