@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.40

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.
Files changed (84) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +10 -6
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +228 -55
  20. package/src/job-wakes.ts +600 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/list-cursor.ts +82 -0
  24. package/src/migrations-sqlite.ts +210 -0
  25. package/src/migrations.ts +73 -0
  26. package/src/nodes.ts +84 -14
  27. package/src/orm-types.ts +206 -71
  28. package/src/orm.ts +425 -170
  29. package/src/policy.ts +1979 -141
  30. package/src/postgres.ts +26 -0
  31. package/src/registry.ts +55 -3
  32. package/src/request-receipts.ts +107 -0
  33. package/src/sql.ts +247 -476
  34. package/src/sqlite-bun.ts +149 -0
  35. package/src/sqlite-migrate.ts +242 -0
  36. package/src/sqlite.ts +269 -0
  37. package/src/store.ts +2292 -239
  38. package/src/stored-files.ts +188 -52
  39. package/src/tables.ts +172 -6
  40. package/src/temporal.ts +122 -9
  41. package/src/testing-shared.ts +1351 -0
  42. package/src/testing-sqlite.ts +685 -0
  43. package/src/testing.ts +310 -494
  44. package/src/vocabulary-tables.ts +159 -27
  45. package/types/src/application-rows.d.ts +58 -0
  46. package/types/src/authority.d.ts +147 -0
  47. package/types/src/builtins.d.ts +2 -0
  48. package/types/src/capability.d.ts +55 -2
  49. package/types/src/codegen-sqlite.d.ts +13 -0
  50. package/types/src/codegen.d.ts +79 -5
  51. package/types/src/condition-nodes.d.ts +9 -0
  52. package/types/src/conditions.d.ts +151 -0
  53. package/types/src/database.d.ts +81 -20
  54. package/types/src/description.d.ts +26 -8
  55. package/types/src/errors.d.ts +9 -6
  56. package/types/src/file-columns.d.ts +6 -4
  57. package/types/src/framework.d.ts +12 -5
  58. package/types/src/guard.d.ts +24 -0
  59. package/types/src/index.d.ts +5 -4
  60. package/types/src/job-leases.d.ts +40 -5
  61. package/types/src/job-wakes.d.ts +124 -0
  62. package/types/src/json.d.ts +18 -0
  63. package/types/src/list-cursor.d.ts +13 -0
  64. package/types/src/migrations-sqlite.d.ts +4 -0
  65. package/types/src/migrations.d.ts +4 -0
  66. package/types/src/nodes.d.ts +17 -2
  67. package/types/src/orm-types.d.ts +163 -71
  68. package/types/src/orm.d.ts +21 -0
  69. package/types/src/policy.d.ts +351 -23
  70. package/types/src/postgres.d.ts +12 -0
  71. package/types/src/registry.d.ts +40 -3
  72. package/types/src/request-receipts.d.ts +22 -0
  73. package/types/src/sql.d.ts +29 -21
  74. package/types/src/sqlite-bun.d.ts +21 -0
  75. package/types/src/sqlite-migrate.d.ts +28 -0
  76. package/types/src/sqlite.d.ts +24 -0
  77. package/types/src/store.d.ts +143 -34
  78. package/types/src/stored-files.d.ts +6 -2
  79. package/types/src/tables.d.ts +18 -2
  80. package/types/src/temporal.d.ts +24 -0
  81. package/types/src/testing-shared.d.ts +290 -0
  82. package/types/src/testing-sqlite.d.ts +37 -0
  83. package/types/src/testing.d.ts +2 -93
  84. package/types/src/vocabulary-tables.d.ts +169 -22
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
+ }
package/src/links.ts CHANGED
@@ -57,5 +57,12 @@ export function linkValues(table: string, links: readonly Container[], grant: Re
57
57
  }
58
58
 
59
59
  export function linksPredicate(table: string, values: readonly LinkValue[]): OperationNode {
60
- return allOf(values.map(({ link, value }) => equals(table, link.column, value)))
60
+ const terms: OperationNode[] = []
61
+ for (let index = 0; index < values.length; index++) {
62
+ const entry = values[index]
63
+ if (entry !== undefined) {
64
+ terms[terms.length] = equals(table, entry.link.column, entry.value)
65
+ }
66
+ }
67
+ return allOf(terms)
61
68
  }
@@ -0,0 +1,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
+ }
@@ -0,0 +1,210 @@
1
+ // @fabrika/db/migrations-sqlite — the framework's own tables in an application's SQLite database, a Cloudflare
2
+ // Durable Object's (ADR-0065). The same tables and columns as the Postgres bundle in `migrations.ts`, without the
3
+ // history a Postgres schema carries: no form files and no adoption of collection tables, which no SQLite database
4
+ // ever had. Plain data, applied as the bundle `fabrika` before the application's `app` bundle.
5
+ //
6
+ // The SQLite forms of the column types, which every framework statement and the row reads rely on:
7
+ // - a timestamp is TEXT in UTC, `YYYY-MM-DDTHH:MM:SS.sssZ`: what `strftime(SQLITE_NOW_FORMAT, 'now')` and
8
+ // `Date#toISOString()` both write, so text order is time order;
9
+ // - a boolean is INTEGER 0 or 1; a UUID is TEXT; a BIGINT is INTEGER.
10
+
11
+ import {
12
+ FILE_DELETIONS_TABLE,
13
+ FILES_TABLE,
14
+ FORM_ADMISSIONS_TABLE,
15
+ FORM_BYTES_TABLE,
16
+ FORM_CHALLENGES_TABLE,
17
+ type FrameworkMigration,
18
+ JOB_KICKS_TABLE,
19
+ JOB_LEASES_TABLE,
20
+ JOB_SCHEDULE_TABLE,
21
+ JOB_WAKES_TABLE,
22
+ LIST_CURSOR_KEY_TABLE,
23
+ REQUEST_RECEIPTS_TABLE,
24
+ WEBHOOK_BINDINGS_TABLE,
25
+ WEBHOOK_DELIVERIES_TABLE,
26
+ } from './migrations'
27
+
28
+ /** The `strftime` format of a stored timestamp; `strftime(SQLITE_NOW_FORMAT, 'now')` is the database's clock. */
29
+ export const SQLITE_NOW_FORMAT = '%Y-%m-%dT%H:%M:%fZ'
30
+
31
+ export const SQLITE_FRAMEWORK_MIGRATIONS: readonly FrameworkMigration[] = Object.freeze([
32
+ Object.freeze({
33
+ name: '0001_framework.sql',
34
+ sql: `-- A binding admits deliveries for one scope value from one provider account, signed with its own secret.
35
+ CREATE TABLE ${WEBHOOK_BINDINGS_TABLE} (
36
+ id TEXT PRIMARY KEY,
37
+ webhook TEXT NOT NULL,
38
+ scope_type TEXT NOT NULL,
39
+ scope_value TEXT NOT NULL,
40
+ account TEXT NOT NULL,
41
+ secret TEXT NOT NULL,
42
+ created_by TEXT NOT NULL,
43
+ created_at INTEGER NOT NULL
44
+ ) STRICT;
45
+
46
+ -- GitHub signs no timestamp, so a recorded delivery id is the replay defence. A delivery is claimed with a lease and
47
+ -- completed in its handler's transaction, which clears the lease.
48
+ CREATE TABLE ${WEBHOOK_DELIVERIES_TABLE} (
49
+ binding_id TEXT NOT NULL REFERENCES ${WEBHOOK_BINDINGS_TABLE} (id) ON DELETE CASCADE,
50
+ delivery_id TEXT NOT NULL,
51
+ received_at INTEGER NOT NULL,
52
+ lease_until INTEGER,
53
+ PRIMARY KEY (binding_id, delivery_id)
54
+ ) STRICT;
55
+
56
+ -- One row per job: the lease a run takes, fenced by its generation, and the outcome of the last run.
57
+ CREATE TABLE ${JOB_LEASES_TABLE} (
58
+ job TEXT PRIMARY KEY,
59
+ generation INTEGER NOT NULL,
60
+ holder TEXT,
61
+ expires_at TEXT NOT NULL,
62
+ attempt_deadline TEXT NOT NULL,
63
+ first_seen_at TEXT NOT NULL,
64
+ last_started_at TEXT,
65
+ last_finished_at TEXT,
66
+ last_status TEXT,
67
+ last_succeeded_at TEXT,
68
+ last_duration_ms INTEGER,
69
+ last_missed_reported_at TEXT
70
+ ) STRICT;
71
+
72
+ -- Whether a kick arrived after the job's current run started: that run runs the job once more after it succeeded.
73
+ CREATE TABLE ${JOB_KICKS_TABLE} (
74
+ job TEXT PRIMARY KEY,
75
+ pending INTEGER NOT NULL CHECK (pending IN (0, 1))
76
+ ) STRICT;
77
+
78
+ -- A form's admission counters, one row per form, bucket and minute; a row of a past minute is pruned by the next
79
+ -- admission.
80
+ CREATE TABLE ${FORM_ADMISSIONS_TABLE} (
81
+ form TEXT NOT NULL,
82
+ bucket TEXT NOT NULL,
83
+ window_start TEXT NOT NULL,
84
+ count INTEGER NOT NULL,
85
+ PRIMARY KEY (form, bucket, window_start)
86
+ ) STRICT;
87
+ CREATE INDEX ${FORM_ADMISSIONS_TABLE}_window_start ON ${FORM_ADMISSIONS_TABLE} (window_start);
88
+
89
+ -- The digest of each challenge token a form accepted, until the token could no longer verify: a replay is refused.
90
+ CREATE TABLE ${FORM_CHALLENGES_TABLE} (
91
+ form TEXT NOT NULL,
92
+ token_digest TEXT NOT NULL,
93
+ expires_at TEXT NOT NULL,
94
+ PRIMARY KEY (form, token_digest)
95
+ ) STRICT;
96
+ CREATE INDEX ${FORM_CHALLENGES_TABLE}_expires_at ON ${FORM_CHALLENGES_TABLE} (expires_at);
97
+
98
+ -- The bytes a form's files may write per hour: one row per form and hour, which the next reservation of a later hour
99
+ -- prunes.
100
+ CREATE TABLE ${FORM_BYTES_TABLE} (
101
+ form TEXT NOT NULL,
102
+ window_start TEXT NOT NULL,
103
+ bytes INTEGER NOT NULL,
104
+ PRIMARY KEY (form, window_start)
105
+ ) STRICT;
106
+
107
+ -- Every stored file: a value a table's file column references by id. A row is 'pending' from before its object
108
+ -- (<kind>/<id>) is written until the first reference claims it, then 'quarantined' (a scanning kind) or 'live'.
109
+ CREATE TABLE ${FILES_TABLE} (
110
+ id TEXT PRIMARY KEY,
111
+ kind TEXT NOT NULL,
112
+ status TEXT NOT NULL CONSTRAINT ${FILES_TABLE}_status CHECK (status IN ('pending', 'quarantined', 'live', 'rejected')),
113
+ object_key TEXT NOT NULL UNIQUE,
114
+ size INTEGER,
115
+ sha256 TEXT,
116
+ content_type TEXT NOT NULL,
117
+ name TEXT,
118
+ scope TEXT,
119
+ request TEXT,
120
+ created_at TEXT NOT NULL,
121
+ object_version TEXT,
122
+ scan_attempts INTEGER NOT NULL DEFAULT 0,
123
+ scan_after TEXT,
124
+ legacy TEXT
125
+ ) STRICT;
126
+ CREATE INDEX ${FILES_TABLE}_created_at ON ${FILES_TABLE} (created_at) WHERE legacy IS NULL;
127
+ CREATE INDEX ${FILES_TABLE}_scan ON ${FILES_TABLE} (scan_after) WHERE status = 'quarantined';
128
+
129
+ -- An object whose file row is deleted, until the object is: the sweep finishes a deletion a crash interrupted.
130
+ CREATE TABLE ${FILE_DELETIONS_TABLE} (
131
+ object_key TEXT PRIMARY KEY,
132
+ recorded_at TEXT NOT NULL
133
+ ) STRICT;
134
+ `,
135
+ }),
136
+ Object.freeze({
137
+ name: '0002_job_wakes.sql',
138
+ sql: `-- A job's pending work, one row per due unit: its next scheduled run, a kick, a claim's re-arm, a durable retry. due_at
139
+ -- is epoch milliseconds. Only the fenced finish of a run that started at or after a row changes it: consumed when the run is
140
+ -- done with it, or moved to a retry, which counts in attempt.
141
+ CREATE TABLE ${JOB_WAKES_TABLE} (
142
+ id TEXT PRIMARY KEY,
143
+ job TEXT NOT NULL,
144
+ due_at INTEGER NOT NULL,
145
+ reason TEXT NOT NULL CONSTRAINT ${JOB_WAKES_TABLE}_reason CHECK (reason IN ('cron', 'kick', 'claim', 'retry')),
146
+ attempt INTEGER NOT NULL DEFAULT 0,
147
+ dedupe TEXT
148
+ ) STRICT;
149
+ CREATE INDEX ${JOB_WAKES_TABLE}_due ON ${JOB_WAKES_TABLE} (due_at);
150
+ CREATE UNIQUE INDEX ${JOB_WAKES_TABLE}_dedupe ON ${JOB_WAKES_TABLE} (dedupe) WHERE dedupe IS NOT NULL;
151
+ `,
152
+ }),
153
+ Object.freeze({
154
+ name: '0003_file_deletions_recorded_at.sql',
155
+ sql: `-- A queued key is a tombstone kept for the retention window: the sweep reads the due ones by age, not the whole queue.
156
+ CREATE INDEX ${FILE_DELETIONS_TABLE}_recorded_at ON ${FILE_DELETIONS_TABLE} (recorded_at, object_key);
157
+ `,
158
+ }),
159
+ Object.freeze({
160
+ name: '0004_job_wakes_owned.sql',
161
+ sql: `-- The wakes the run holding the job's lease took when it took the lease: its finish consumes or retries exactly these.
162
+ -- A wake written or merged into afterwards is not taken, though due before the run started: the run may not have read its work.
163
+ ALTER TABLE ${JOB_WAKES_TABLE} ADD COLUMN owned INTEGER NOT NULL DEFAULT 0 CHECK (owned IN (0, 1));
164
+ `,
165
+ }),
166
+ Object.freeze({
167
+ name: '0005_request_receipts.sql',
168
+ sql: `-- The answer of a mutation whose request carried a key (ADR-0078), for a repeat of that request: the principal's key,
169
+ -- the operation and the SHA-256 of its input, and the output's JSON. created_at is epoch milliseconds; each write prunes
170
+ -- a batch of receipts past the retention.
171
+ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
172
+ principal TEXT NOT NULL,
173
+ request_key TEXT NOT NULL,
174
+ operation TEXT NOT NULL,
175
+ identity TEXT NOT NULL,
176
+ output TEXT NOT NULL,
177
+ created_at INTEGER NOT NULL,
178
+ PRIMARY KEY (principal, request_key)
179
+ ) STRICT;
180
+ CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
181
+ `,
182
+ }),
183
+ Object.freeze({
184
+ name: '0006_list_cursor_key.sql',
185
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
186
+ -- here once and only read afterwards. 32 random bytes as hex.
187
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
188
+ id INTEGER PRIMARY KEY CHECK (id = 1),
189
+ secret TEXT NOT NULL
190
+ ) STRICT;
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 '[]';
208
+ `,
209
+ }),
210
+ ])
package/src/migrations.ts CHANGED
@@ -9,12 +9,16 @@ export const WEBHOOK_BINDINGS_TABLE = 'fabrika_webhook_bindings'
9
9
  export const WEBHOOK_DELIVERIES_TABLE = 'fabrika_webhook_deliveries'
10
10
  export const JOB_LEASES_TABLE = 'fabrika_job_leases'
11
11
  export const JOB_KICKS_TABLE = 'fabrika_job_kicks'
12
+ export const JOB_WAKES_TABLE = 'fabrika_wakes'
13
+ export const JOB_SCHEDULE_TABLE = 'fabrika_job_schedule'
12
14
  export const FORM_ADMISSIONS_TABLE = 'fabrika_form_admissions'
13
15
  export const FORM_CHALLENGES_TABLE = 'fabrika_form_challenges'
14
16
  export const FORM_FILES_TABLE = 'fabrika_form_files'
15
17
  export const FORM_BYTES_TABLE = 'fabrika_form_bytes'
16
18
  export const FILES_TABLE = 'fabrika_files'
17
19
  export const FILE_DELETIONS_TABLE = 'fabrika_file_deletions'
20
+ export const REQUEST_RECEIPTS_TABLE = 'fabrika_request_receipts'
21
+ export const LIST_CURSOR_KEY_TABLE = 'fabrika_list_cursor_key'
18
22
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
19
23
  export const FILES_RELEASE_FUNCTION = 'fabrika_files_release'
20
24
  /**
@@ -254,6 +258,75 @@ BEGIN
254
258
  DELETE FROM ${FORM_FILES_TABLE} f WHERE status = 'held' AND EXISTS (SELECT 1 FROM ${FILES_TABLE} c WHERE c.id = f.id);
255
259
  END
256
260
  $$;
261
+ `,
262
+ }),
263
+ Object.freeze({
264
+ name: '0009_job_wakes.sql',
265
+ sql: `-- A job's pending work, one row per due unit: its next scheduled run, a kick, a claim's re-arm, a durable retry. due_at
266
+ -- is epoch milliseconds. Only the fenced finish of a run that started at or after a row changes it: consumed when the run is
267
+ -- done with it, or moved to a retry, which counts in attempt.
268
+ CREATE TABLE ${JOB_WAKES_TABLE} (
269
+ id UUID PRIMARY KEY,
270
+ job TEXT NOT NULL,
271
+ due_at BIGINT NOT NULL,
272
+ reason TEXT NOT NULL CONSTRAINT ${JOB_WAKES_TABLE}_reason CHECK (reason IN ('cron', 'kick', 'claim', 'retry')),
273
+ attempt INTEGER NOT NULL DEFAULT 0,
274
+ dedupe TEXT
275
+ );
276
+ CREATE INDEX ${JOB_WAKES_TABLE}_due ON ${JOB_WAKES_TABLE} (due_at);
277
+ CREATE UNIQUE INDEX ${JOB_WAKES_TABLE}_dedupe ON ${JOB_WAKES_TABLE} (dedupe) WHERE dedupe IS NOT NULL;
278
+ `,
279
+ }),
280
+ Object.freeze({
281
+ name: '0010_job_wakes_owned.sql',
282
+ sql: `-- The wakes the run holding the job's lease took when it took the lease: its finish consumes or retries exactly these.
283
+ -- A wake written or merged into afterwards is not taken, though due before the run started: the run may not have read its work.
284
+ ALTER TABLE ${JOB_WAKES_TABLE} ADD COLUMN owned BOOLEAN NOT NULL DEFAULT false;
285
+ `,
286
+ }),
287
+ Object.freeze({
288
+ name: '0011_request_receipts.sql',
289
+ sql: `-- The answer of a mutation whose request carried a key (ADR-0078), for a repeat of that request: the principal's key,
290
+ -- the operation and the SHA-256 of its input, and the output's JSON. created_at is epoch milliseconds; each write prunes
291
+ -- a batch of receipts past the retention.
292
+ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
293
+ principal TEXT NOT NULL,
294
+ request_key TEXT NOT NULL,
295
+ operation TEXT NOT NULL,
296
+ identity TEXT NOT NULL,
297
+ output TEXT NOT NULL,
298
+ created_at BIGINT NOT NULL,
299
+ PRIMARY KEY (principal, request_key)
300
+ );
301
+ CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
302
+ `,
303
+ }),
304
+ Object.freeze({
305
+ name: '0012_list_cursor_key.sql',
306
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
307
+ -- here once and only read afterwards. Two random UUIDs give it 244 random bits.
308
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
309
+ id INTEGER PRIMARY KEY CHECK (id = 1),
310
+ secret TEXT NOT NULL
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 '[]';
257
330
  `,
258
331
  }),
259
332
  ])