@fabrika/db 0.9.0-dev.7 → 0.9.0-dev.70

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 (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +69 -13
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +67 -9
  10. package/src/errors.ts +9 -5
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +187 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +40 -9
  47. package/types/src/errors.d.ts +8 -5
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +35 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +176 -22
@@ -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
  ])
package/src/migrations.ts CHANGED
@@ -10,12 +10,17 @@ 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'
16
17
  export const FORM_BYTES_TABLE = 'fabrika_form_bytes'
17
18
  export const FILES_TABLE = 'fabrika_files'
18
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'
22
+ export const PUSH_SUBSCRIPTIONS_TABLE = 'fabrika_push_subscriptions'
23
+ export const NOTIFICATIONS_TABLE = 'fabrika_notifications'
19
24
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
20
25
  export const FILES_RELEASE_FUNCTION = 'fabrika_files_release'
21
26
  /**
@@ -279,6 +284,100 @@ CREATE UNIQUE INDEX ${JOB_WAKES_TABLE}_dedupe ON ${JOB_WAKES_TABLE} (dedupe) WHE
279
284
  sql: `-- The wakes the run holding the job's lease took when it took the lease: its finish consumes or retries exactly these.
280
285
  -- A wake written or merged into afterwards is not taken, though due before the run started: the run may not have read its work.
281
286
  ALTER TABLE ${JOB_WAKES_TABLE} ADD COLUMN owned BOOLEAN NOT NULL DEFAULT false;
287
+ `,
288
+ }),
289
+ Object.freeze({
290
+ name: '0011_request_receipts.sql',
291
+ sql: `-- The answer of a mutation whose request carried a key (ADR-0078), for a repeat of that request: the principal's key,
292
+ -- the operation and the SHA-256 of its input, and the output's JSON. created_at is epoch milliseconds; each write prunes
293
+ -- a batch of receipts past the retention.
294
+ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
295
+ principal TEXT NOT NULL,
296
+ request_key TEXT NOT NULL,
297
+ operation TEXT NOT NULL,
298
+ identity TEXT NOT NULL,
299
+ output TEXT NOT NULL,
300
+ created_at BIGINT NOT NULL,
301
+ PRIMARY KEY (principal, request_key)
302
+ );
303
+ CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
304
+ `,
305
+ }),
306
+ Object.freeze({
307
+ name: '0012_list_cursor_key.sql',
308
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
309
+ -- here once and only read afterwards. Two random UUIDs give it 244 random bits.
310
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
311
+ id INTEGER PRIMARY KEY CHECK (id = 1),
312
+ secret TEXT NOT NULL
313
+ );
314
+ INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, gen_random_uuid()::text || gen_random_uuid()::text);
315
+ `,
316
+ }),
317
+ Object.freeze({
318
+ name: '0013_job_schedule.sql',
319
+ sql: `-- Which deploy keeps the cron wakes where no crontab runs (ADR-0080): one row, the highest generation a serving process
320
+ -- has seen. A process of that generation reconciles and seeds the wakes; an older one does neither. Compared as bytes.
321
+ CREATE TABLE ${JOB_SCHEDULE_TABLE} (
322
+ id INTEGER PRIMARY KEY CHECK (id = 1),
323
+ generation TEXT COLLATE "C" NOT NULL
324
+ );
325
+ `,
326
+ }),
327
+ Object.freeze({
328
+ name: '0014_job_schedule_declared.sql',
329
+ sql: `-- The cron keys (cron:<job>:<expression>) the stored generation's deploy declares, as a JSON array: a run of any
330
+ -- deploy schedules its job's next fire only under a key in it, so an old revision restores no removed job or expression.
331
+ ALTER TABLE ${JOB_SCHEDULE_TABLE} ADD COLUMN declared TEXT NOT NULL DEFAULT '[]';
332
+ `,
333
+ }),
334
+ Object.freeze({
335
+ name: '0015_push_subscriptions.sql',
336
+ sql: `-- A browser's Web Push subscription (ADR-0088), bound to the principal who recorded it: its endpoint at the push service,
337
+ -- its keys, the VAPID public key it was made with, the newest notification the inbox answered for it (cursor), and when
338
+ -- the sender may try it again. A row whose gone_at is set is a tombstone: the push service called the endpoint gone,
339
+ -- and only the principal and the endpoint stay, so a replacement the page posts later still finds whose it was. Times
340
+ -- are epoch milliseconds.
341
+ CREATE TABLE ${PUSH_SUBSCRIPTIONS_TABLE} (
342
+ id UUID PRIMARY KEY,
343
+ principal TEXT NOT NULL,
344
+ endpoint TEXT NOT NULL UNIQUE,
345
+ p256dh TEXT,
346
+ auth TEXT,
347
+ vapid_key TEXT,
348
+ cursor TEXT,
349
+ next_attempt_at BIGINT,
350
+ recorded_at BIGINT NOT NULL,
351
+ gone_at BIGINT,
352
+ CONSTRAINT ${PUSH_SUBSCRIPTIONS_TABLE}_tombstone CHECK (
353
+ (gone_at IS NULL AND p256dh IS NOT NULL AND auth IS NOT NULL AND vapid_key IS NOT NULL)
354
+ 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)
355
+ )
356
+ );
357
+ CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_principal ON ${PUSH_SUBSCRIPTIONS_TABLE} (principal, recorded_at) WHERE gone_at IS NULL;
358
+ CREATE INDEX ${PUSH_SUBSCRIPTIONS_TABLE}_gone_at ON ${PUSH_SUBSCRIPTIONS_TABLE} (gone_at) WHERE gone_at IS NOT NULL;
359
+ `,
360
+ }),
361
+ Object.freeze({
362
+ name: '0016_notifications.sql',
363
+ sql: `-- A notification for one principal (ADR-0088 §6): its text and the path a click opens, and what the recipient must
364
+ -- hold to read it, checked when the inbox answers: an action on an object (its dimension and key), or the action as a
365
+ -- global grant (dimension and scope_value null). The id is a UUIDv7, so its order is the order written, which a
366
+ -- subscription's cursor counts in. created_at is epoch milliseconds; a row lives seven days.
367
+ CREATE TABLE ${NOTIFICATIONS_TABLE} (
368
+ id UUID PRIMARY KEY,
369
+ principal TEXT NOT NULL,
370
+ title TEXT NOT NULL,
371
+ body TEXT NOT NULL,
372
+ path TEXT NOT NULL,
373
+ action TEXT NOT NULL,
374
+ dimension TEXT,
375
+ scope_value TEXT,
376
+ created_at BIGINT NOT NULL,
377
+ CONSTRAINT ${NOTIFICATIONS_TABLE}_about CHECK ((dimension IS NULL) = (scope_value IS NULL))
378
+ );
379
+ CREATE INDEX ${NOTIFICATIONS_TABLE}_principal ON ${NOTIFICATIONS_TABLE} (principal, id);
380
+ CREATE INDEX ${NOTIFICATIONS_TABLE}_created_at ON ${NOTIFICATIONS_TABLE} (created_at);
282
381
  `,
283
382
  }),
284
383
  ])
package/src/nodes.ts CHANGED
@@ -81,11 +81,12 @@ export function anyOf(nodes: readonly OperationNode[]): OperationNode {
81
81
  }
82
82
 
83
83
  export function inList(table: string, name: string, values: readonly string[]): OperationNode {
84
- return BinaryOperationNode.create(
85
- column(table, name),
86
- OperatorNode.create('in'),
87
- ValueListNode.create(valueNodes(values)),
88
- )
84
+ return BinaryOperationNode.create(column(table, name), OperatorNode.create('in'), valueList(values))
85
+ }
86
+
87
+ /** `($1, $2, …)`: bound values, as the right operand of an `in`. */
88
+ export function valueList(values: readonly string[]): OperationNode {
89
+ return ValueListNode.create(valueNodes(values))
89
90
  }
90
91
 
91
92
  function valueNodes(values: readonly string[]): ValueNode[] {
@@ -166,7 +167,7 @@ function rowSelection(table: string, name: string, days: NameSet): SelectionNode
166
167
  return SelectionNode.create(AliasNode.create(CastNode.create(column(table, name), DataTypeNode.create('text')), IdentifierNode.create(name)))
167
168
  }
168
169
 
169
- const NO_DAYS: NameSet = nameSet([])
170
+ const NO_NAMES: NameSet = nameSet([])
170
171
 
171
172
  /** `returning key as id[, version as version]`: a mutation's acknowledgement, never row data. */
172
173
  export function acknowledgement(table: string, key: string, version: string | undefined): ReturningNode {
@@ -181,7 +182,9 @@ function joinNode(parent: string, join: JoinState): JoinNode {
181
182
  BinaryOperationNode.create(column(child, pair.childColumn), OperatorNode.create('='), column(parent, pair.parentColumn))
182
183
  ),
183
184
  )
184
- const conditions = conditionsNode(child, join.select.conditions)
185
+ const requested = conditionsNode(child, join.select.conditions)
186
+ const held = join.condition
187
+ const conditions = held === undefined ? requested : requested === undefined ? held : AndNode.create(requested, ParensNode.create(held))
185
188
  const on = conditions === undefined ? foreignKey : AndNode.create(foreignKey, ParensNode.create(conditions))
186
189
  return JoinNode.createWithOn('InnerJoin', TableNode.create(child), on)
187
190
  }
@@ -194,11 +197,14 @@ function joinedSelections(join: JoinState): SelectionNode[] {
194
197
 
195
198
  /**
196
199
  * One order term. Postgres sorts nulls last ascending and first descending; SQLite the other way, so on SQLite the term
197
- * states Postgres's order and a keyset page (`orm.ts`) reads the same rows after its cursor on both.
200
+ * states Postgres's order and a keyset page (`orm.ts`) reads the same rows after its cursor on both. A NOT NULL column
201
+ * states none: SQLite reads an order from an index only in its own null order, and such a column holds no null.
198
202
  */
199
- function orderItem(table: string, order: SelectState['orderBy'][number], dialect: SqlDialect): OrderByItemNode {
203
+ function orderItem(table: string, order: SelectState['orderBy'][number], dialect: SqlDialect, notNull: NameSet): OrderByItemNode {
200
204
  const item = OrderByItemNode.create(column(table, order.column), RawNode.createWithSql(order.direction))
201
- return dialect === 'postgres' ? item : Object.freeze({ ...item, nulls: order.direction === 'asc' ? 'last' : 'first' })
205
+ return dialect === 'postgres' || inSet(notNull, order.column)
206
+ ? item
207
+ : Object.freeze({ ...item, nulls: order.direction === 'asc' ? 'last' : 'first' })
202
208
  }
203
209
 
204
210
  /** `after` is a keyset page's position, ANDed to the caller's conditions inside their parenthesis. */
@@ -207,14 +213,15 @@ export function selectNode(
207
213
  visible: readonly string[],
208
214
  scope: OperationNode,
209
215
  after?: OperationNode,
210
- days: NameSet = NO_DAYS,
216
+ days: NameSet = NO_NAMES,
211
217
  dialect: SqlDialect = 'postgres',
218
+ notNull: NameSet = NO_NAMES,
212
219
  ): SelectQueryNode {
213
220
  const table = state.table
214
221
  const columns = state.columns ?? visible
215
222
  const conditions = conditionsNode(table, state.conditions)
216
223
  const filter = after === undefined ? conditions : conditions === undefined ? after : AndNode.create(conditions, ParensNode.create(after))
217
- const orderBy = state.orderBy.map((order) => orderItem(table, order, dialect))
224
+ const orderBy = state.orderBy.map((order) => orderItem(table, order, dialect, notNull))
218
225
  const node: SelectQueryNode = {
219
226
  kind: 'SelectQueryNode',
220
227
  from: FromNode.create([TableNode.create(table)]),
@@ -245,7 +252,7 @@ export function aggregateNode(
245
252
  columns: AggregateColumns,
246
253
  conditions: readonly Condition[],
247
254
  scope: OperationNode,
248
- days: NameSet = NO_DAYS,
255
+ days: NameSet = NO_NAMES,
249
256
  ): SelectQueryNode {
250
257
  const selections = [
251
258
  ...columns.groupBy.map((name) => rowSelection(table, name, days)),
@@ -351,6 +358,18 @@ export function locateNode(table: string, columns: readonly string[], scope: Ope
351
358
  return Object.freeze(node)
352
359
  }
353
360
 
361
+ /** `select T.<name> from T where <scope> group by T.<name>`: each value of `name` the scoped rows hold, once. */
362
+ export function valuesNode(table: string, name: string, scope: OperationNode): SelectQueryNode {
363
+ const node: SelectQueryNode = {
364
+ kind: 'SelectQueryNode',
365
+ from: FromNode.create([TableNode.create(table)]),
366
+ selections: [selection(table, name)],
367
+ where: scopedWhere(undefined, scope),
368
+ groupBy: GroupByNode.create([GroupByItemNode.create(column(table, name))]),
369
+ }
370
+ return Object.freeze(node)
371
+ }
372
+
354
373
  /**
355
374
  * The same check, locked: `for share` keeps the row from moving until the transaction that checked it ends, `for
356
375
  * update` also keeps every other writer and locker of it waiting.
@@ -419,7 +438,7 @@ export function nextClaimNode(
419
438
  }
420
439
 
421
440
  /** `select <columns> from table where scope for update`: a mutation's precondition read of its own target. */
422
- export function lockedSelectNode(table: string, columns: readonly string[], scope: OperationNode, days: NameSet = NO_DAYS): SelectQueryNode {
441
+ export function lockedSelectNode(table: string, columns: readonly string[], scope: OperationNode, days: NameSet = NO_NAMES): SelectQueryNode {
423
442
  const node: SelectQueryNode = {
424
443
  kind: 'SelectQueryNode',
425
444
  from: FromNode.create([TableNode.create(table)]),
@@ -0,0 +1,152 @@
1
+ // The framework's side of `fabrika_notifications` (`@fabrika/db/migrations`, ADR-0088 §6): a notification written for
2
+ // one principal, with what the recipient must hold to read it. Only `@fabrika/app` reaches it, through
3
+ // `frameworkTablesOf`, in the invocation's own transaction. The inbox reads a principal's rows after a subscription's
4
+ // cursor, oldest first; whether the caller may read each one is the framework's check, not this module's. A row lives
5
+ // `retentionMs`: a read never answers an older one, and every write prunes a batch of them.
6
+
7
+ import { runFixedStatement, type Session } from './database'
8
+ import { QueryRefusedError } from './errors'
9
+ import type { DialectTexts } from './job-leases'
10
+ import { NOTIFICATIONS_TABLE } from './migrations'
11
+
12
+ export const NOTIFICATION_LIMITS = Object.freeze({
13
+ /** How long a notification is kept and answered: seven days. */
14
+ retentionMs: 7 * 24 * 60 * 60 * 1_000,
15
+ })
16
+
17
+ /** What the recipient must hold to read a notification: an action on one object, or the action as a global grant. */
18
+ export type NotificationAbout =
19
+ | { readonly action: string; readonly dimension: string; readonly value: string }
20
+ | { readonly action: string; readonly dimension: null; readonly value: null }
21
+
22
+ export interface StoredNotification {
23
+ /** A UUIDv7: its order is the order written. */
24
+ readonly id: string
25
+ readonly title: string
26
+ readonly body: string
27
+ readonly path: string
28
+ readonly about: NotificationAbout
29
+ }
30
+
31
+ export interface NewNotification extends StoredNotification {
32
+ readonly principal: string
33
+ /** Epoch milliseconds. */
34
+ readonly createdAt: number
35
+ }
36
+
37
+ export interface Notifications {
38
+ /** Writes `notification`, after pruning a batch of rows past the retention. */
39
+ record(session: Session, notification: NewNotification): Promise<void>
40
+ /** `principal`'s rows written after the notification `after` (all of them for `null`), within the retention at `now`, oldest first, at most `limit`. */
41
+ unseen(session: Session, principal: string, after: string | null, now: number, limit: number): Promise<readonly StoredNotification[]>
42
+ /** How many of `principal`'s rows within the retention at `now` were written after `after`. */
43
+ countAfter(session: Session, principal: string, after: string | null, now: number): Promise<number>
44
+ }
45
+
46
+ const N = NOTIFICATIONS_TABLE
47
+
48
+ /** Rows one write prunes at most. */
49
+ const PRUNE_BATCH = 32
50
+
51
+ const SQL_PRUNE: DialectTexts = {
52
+ postgres: `delete from ${N} where id in (select id from ${N} where created_at < $1::bigint limit ${PRUNE_BATCH} for update skip locked)`,
53
+ sqlite: `delete from ${N} where id in (select id from ${N} where created_at < ?1 limit ${PRUNE_BATCH})`,
54
+ }
55
+
56
+ const SQL_INSERT: DialectTexts = {
57
+ postgres: `insert into ${N} (id, principal, title, body, path, action, dimension, scope_value, created_at)
58
+ values ($1, $2, $3, $4, $5, $6, $7, $8, $9::bigint)`,
59
+ sqlite: `insert into ${N} (id, principal, title, body, path, action, dimension, scope_value, created_at)
60
+ values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
61
+ }
62
+
63
+ const SQL_UNSEEN: DialectTexts = {
64
+ postgres: `select id::text as id, title, body, path, action, dimension, scope_value from ${N}
65
+ where principal = $1 and ($2::uuid is null or id > $2::uuid) and created_at >= $3::bigint order by id limit $4::int`,
66
+ sqlite: `select id, title, body, path, action, dimension, scope_value from ${N}
67
+ where principal = ?1 and (?2 is null or id > ?2) and created_at >= ?3 order by id limit ?4`,
68
+ }
69
+
70
+ const SQL_COUNT: DialectTexts = {
71
+ postgres: `select count(*)::int as unseen from ${N} where principal = $1 and ($2::uuid is null or id > $2::uuid) and created_at >= $3::bigint`,
72
+ sqlite: `select count(*) as unseen from ${N} where principal = ?1 and (?2 is null or id > ?2) and created_at >= ?3`,
73
+ }
74
+
75
+ function isRow(value: unknown): value is Readonly<Record<string, unknown>> {
76
+ return typeof value === 'object' && value !== null
77
+ }
78
+
79
+ function text(row: Readonly<Record<string, unknown>>, column: string): string {
80
+ const value = row[column]
81
+ if (typeof value !== 'string') {
82
+ throw new QueryRefusedError('unexpected_row', `${N}.${column} came back as ${typeof value}`)
83
+ }
84
+ return value
85
+ }
86
+
87
+ function storedOf(row: unknown): StoredNotification {
88
+ if (!isRow(row)) {
89
+ throw new QueryRefusedError('unexpected_row', `${N} answered a row that is not an object`)
90
+ }
91
+ const dimension = row['dimension']
92
+ const value = row['scope_value']
93
+ const action = text(row, 'action')
94
+ const about: NotificationAbout | null = dimension === null && value === null
95
+ ? { action, dimension: null, value: null }
96
+ : typeof dimension === 'string' && typeof value === 'string'
97
+ ? { action, dimension, value }
98
+ : null
99
+ if (about === null) {
100
+ throw new QueryRefusedError('unexpected_row', `${N} answered a row whose object is half named`)
101
+ }
102
+ return { id: text(row, 'id'), title: text(row, 'title'), body: text(row, 'body'), path: text(row, 'path'), about }
103
+ }
104
+
105
+ function epochMs(value: number, what: string): number {
106
+ if (!Number.isSafeInteger(value) || value < 0) {
107
+ throw new QueryRefusedError('invalid_argument', `${what} must be epoch milliseconds`)
108
+ }
109
+ return value
110
+ }
111
+
112
+ export function notifications(): Notifications {
113
+ return Object.freeze({
114
+ record(session: Session, notification: NewNotification): Promise<void> {
115
+ const createdAt = epochMs(notification.createdAt, 'createdAt')
116
+ return session.transaction(async (transaction) => {
117
+ await runFixedStatement(transaction, SQL_PRUNE[transaction.dialect], [createdAt - NOTIFICATION_LIMITS.retentionMs])
118
+ const { about } = notification
119
+ await runFixedStatement(transaction, SQL_INSERT[transaction.dialect], [
120
+ notification.id,
121
+ notification.principal,
122
+ notification.title,
123
+ notification.body,
124
+ notification.path,
125
+ about.action,
126
+ about.dimension,
127
+ about.value,
128
+ createdAt,
129
+ ])
130
+ })
131
+ },
132
+
133
+ async unseen(session: Session, principal: string, after: string | null, now: number, limit: number): Promise<readonly StoredNotification[]> {
134
+ if (!Number.isSafeInteger(limit) || limit < 1) {
135
+ throw new QueryRefusedError('invalid_argument', 'a limit must be a whole number of at least 1')
136
+ }
137
+ const since = epochMs(now, 'now') - NOTIFICATION_LIMITS.retentionMs
138
+ const rows = await runFixedStatement(session, SQL_UNSEEN[session.dialect], [principal, after, since, limit])
139
+ return rows.map(storedOf)
140
+ },
141
+
142
+ async countAfter(session: Session, principal: string, after: string | null, now: number): Promise<number> {
143
+ const since = epochMs(now, 'now') - NOTIFICATION_LIMITS.retentionMs
144
+ const [row] = await runFixedStatement(session, SQL_COUNT[session.dialect], [principal, after, since])
145
+ const counted = isRow(row) ? row['unseen'] : undefined
146
+ if (typeof counted !== 'number') {
147
+ throw new QueryRefusedError('unexpected_row', `${N} answered a count that is no number`)
148
+ }
149
+ return counted
150
+ },
151
+ })
152
+ }