@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.60

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 +59 -11
  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 +55 -9
  10. package/src/errors.ts +8 -4
  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 +124 -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 +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +369 -147
  25. package/src/policy.ts +1973 -141
  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 +1933 -168
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +8 -1
  35. package/src/testing-shared.ts +758 -140
  36. package/src/testing-sqlite.ts +212 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +159 -27
  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 +31 -9
  47. package/types/src/errors.d.ts +7 -4
  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 +18 -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 +4 -0
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +165 -73
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +347 -23
  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 +4 -1
  70. package/types/src/testing-shared.d.ts +112 -23
  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 +169 -22
@@ -0,0 +1,287 @@
1
+ // The framework's side of `fabrika_push_subscriptions` (`@fabrika/db/migrations`, ADR-0088): a browser's Web Push
2
+ // subscription, bound to the principal who recorded it. Only `@fabrika/app`'s dispatcher reaches it, through
3
+ // `frameworkTablesOf`, in the invocation's own transaction. The principal always comes from the verified token, never
4
+ // from a request body; the caller hands it in.
5
+ //
6
+ // - A subscription is recorded only under its own principal: an endpoint whose row (or unexpired tombstone) names
7
+ // another principal is `taken`, never rebound.
8
+ // - A replacement (a key rotation, a `pushsubscriptionchange`) names the old endpoint, and is accepted only when the
9
+ // old endpoint's row or tombstone names the caller; the old row goes, its cursor moves to the new one.
10
+ // - A push service's 404 or 410 turns the row into a tombstone (`retire`): the principal and the endpoint only, kept
11
+ // `tombstoneRetentionMs`, which answers nothing but a replacement's question.
12
+ // - A principal holds at most `perPrincipal` live subscriptions: a record past it drops the oldest.
13
+ //
14
+ // On Postgres every write first takes the principal's transaction lock, so two records of one person never both see
15
+ // room under the bound; the endpoint's uniqueness decides between two people. Times are epoch milliseconds the caller
16
+ // passes, as the receipts take theirs.
17
+
18
+ import { runFixedStatement, type Session } from './database'
19
+ import { QueryRefusedError } from './errors'
20
+ import type { DialectTexts } from './job-leases'
21
+ import { PUSH_SUBSCRIPTIONS_TABLE } from './migrations'
22
+
23
+ export const PUSH_SUBSCRIPTION_LIMITS = Object.freeze({
24
+ /** Live subscriptions one principal holds; the next record drops the oldest. */
25
+ perPrincipal: 10,
26
+ /** How long a tombstone answers a replacement: 30 days. */
27
+ tombstoneRetentionMs: 30 * 24 * 60 * 60 * 1_000,
28
+ })
29
+
30
+ /** A subscription as the page hands it over, with the VAPID public key it was made with. */
31
+ export interface PushSubscriptionKeys {
32
+ readonly endpoint: string
33
+ /** The browser's P-256 key, base64url. */
34
+ readonly p256dh: string
35
+ /** The browser's authentication secret, base64url. */
36
+ readonly auth: string
37
+ /** The VAPID public key the browser subscribed with, base64url. */
38
+ readonly vapidKey: string
39
+ }
40
+
41
+ /** Whose a browser's endpoint is, as the caller may learn it: its own live row, another principal's, or none (a tombstone included). */
42
+ export type PushBinding = 'mine' | 'other' | 'unknown'
43
+
44
+ /** The caller's live subscription and the newest notification the inbox answered for it, or `null` when it is not theirs. */
45
+ export type PushInboxSubscription = { readonly cursor: string | null } | null
46
+
47
+ /** `recorded`, or why not: the endpoint is bound to another principal, or the replaced endpoint is not the caller's. */
48
+ export type PushRecordOutcome = 'recorded' | 'taken' | 'not_replaceable'
49
+
50
+ export interface PushSubscriptions {
51
+ /** Whose `endpoint` is, for `principal`. */
52
+ binding(session: Session, principal: string, endpoint: string): Promise<PushBinding>
53
+ /**
54
+ * Records `subscription` for `principal` under `id` (a new row's key, a UUIDv7 made now, which is also a new row's
55
+ * cursor, so it reads only notifications written after it; an existing row of the caller keeps its key and cursor),
56
+ * replacing the endpoint `replace` when it names one, at `now`. Prunes a batch of expired tombstones first, and
57
+ * drops the principal's oldest live rows past the bound after. An outcome but `recorded` changes no subscription: the
58
+ * old row is removed only after the new one was written.
59
+ */
60
+ record(
61
+ session: Session,
62
+ principal: string,
63
+ id: string,
64
+ subscription: PushSubscriptionKeys,
65
+ replace: string | null,
66
+ now: number,
67
+ ): Promise<PushRecordOutcome>
68
+ /**
69
+ * What the inbox reads `endpoint` as for `principal`: the caller's live subscription and its cursor, or none. A live row
70
+ * of another principal is deleted here (§7): the browser it wakes is someone else's now, and stops waking for them.
71
+ */
72
+ inbox(session: Session, principal: string, endpoint: string): Promise<PushInboxSubscription>
73
+ /** Moves the cursor of `principal`'s live `endpoint` forward to `cursor`, never back. */
74
+ advance(session: Session, principal: string, endpoint: string, cursor: string): Promise<void>
75
+ /** Removes `principal`'s own row (or tombstone) of `endpoint`; `false` when it has none. */
76
+ remove(session: Session, principal: string, endpoint: string): Promise<boolean>
77
+ /** The push service called `endpoint` gone: its live row becomes a tombstone at `now`. `false` when it had none. */
78
+ retire(session: Session, endpoint: string, now: number): Promise<boolean>
79
+ }
80
+
81
+ const T = PUSH_SUBSCRIPTIONS_TABLE
82
+
83
+ /** Tombstones one write prunes at most; every record prunes, so expired ones never outgrow the live ones. */
84
+ const PRUNE_BATCH = 32
85
+
86
+ // Held until the transaction ends; two principals whose hashes collide only wait for each other.
87
+ const SQL_LOCK = `select 1 as locked from pg_advisory_xact_lock(hashtextextended('fabrika_push' || chr(10) || $1, 0))`
88
+
89
+ const SQL_PRUNE: DialectTexts = {
90
+ postgres: `delete from ${T} where id in (
91
+ select id from ${T} where gone_at < $1::bigint limit ${PRUNE_BATCH} for update skip locked
92
+ )`,
93
+ sqlite: `delete from ${T} where id in (select id from ${T} where gone_at < ?1 limit ${PRUNE_BATCH})`,
94
+ }
95
+
96
+ // The old row is replaceable only when it, or its tombstone within the retention, is the caller's; its cursor moves on.
97
+ // Locked until the transaction ends, so the sender cannot retire it between this read and its delete.
98
+ const SQL_REPLACED: DialectTexts = {
99
+ postgres: `select cursor from ${T} where endpoint = $1 and principal = $2 and (gone_at is null or gone_at >= $3::bigint) for update`,
100
+ sqlite: `select cursor from ${T} where endpoint = ?1 and principal = ?2 and (gone_at is null or gone_at >= ?3)`,
101
+ }
102
+
103
+ // After the new row is written: the old one, read and locked above, goes.
104
+ const SQL_DROP_REPLACED: DialectTexts = {
105
+ postgres: `delete from ${T} where endpoint = $1 and principal = $2`,
106
+ sqlite: `delete from ${T} where endpoint = ?1 and principal = ?2`,
107
+ }
108
+
109
+ // One statement decides between two principals: a row of another principal is overwritten only when it is a tombstone
110
+ // past the retention. A row of the caller keeps its id and its cursor, and is live again with the new keys.
111
+ const SQL_UPSERT: DialectTexts = {
112
+ postgres: `insert into ${T} (id, principal, endpoint, p256dh, auth, vapid_key, cursor, recorded_at)
113
+ values ($1, $2, $3, $4, $5, $6, $7, $8::bigint)
114
+ on conflict (endpoint) do update set
115
+ principal = excluded.principal,
116
+ p256dh = excluded.p256dh,
117
+ auth = excluded.auth,
118
+ vapid_key = excluded.vapid_key,
119
+ cursor = case when ${T}.principal = excluded.principal then coalesce(${T}.cursor, excluded.cursor) else excluded.cursor end,
120
+ next_attempt_at = null,
121
+ recorded_at = excluded.recorded_at,
122
+ gone_at = null
123
+ where ${T}.principal = excluded.principal or ${T}.gone_at < $9::bigint
124
+ returning endpoint`,
125
+ sqlite: `insert into ${T} (id, principal, endpoint, p256dh, auth, vapid_key, cursor, recorded_at)
126
+ values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
127
+ on conflict (endpoint) do update set
128
+ principal = excluded.principal,
129
+ p256dh = excluded.p256dh,
130
+ auth = excluded.auth,
131
+ vapid_key = excluded.vapid_key,
132
+ cursor = case when ${T}.principal = excluded.principal then coalesce(${T}.cursor, excluded.cursor) else excluded.cursor end,
133
+ next_attempt_at = null,
134
+ recorded_at = excluded.recorded_at,
135
+ gone_at = null
136
+ where ${T}.principal = excluded.principal or ${T}.gone_at < ?9
137
+ returning endpoint`,
138
+ }
139
+
140
+ const SQL_TRIM: DialectTexts = {
141
+ postgres: `delete from ${T} where id in (
142
+ select id from ${T} where principal = $1 and gone_at is null order by recorded_at desc, id desc offset ${PUSH_SUBSCRIPTION_LIMITS.perPrincipal}
143
+ )`,
144
+ sqlite: `delete from ${T} where id in (
145
+ select id from ${T} where principal = ?1 and gone_at is null order by recorded_at desc, id desc limit -1 offset ${PUSH_SUBSCRIPTION_LIMITS.perPrincipal}
146
+ )`,
147
+ }
148
+
149
+ const SQL_BINDING: DialectTexts = {
150
+ postgres: `select principal from ${T} where endpoint = $1 and gone_at is null`,
151
+ sqlite: `select principal from ${T} where endpoint = ?1 and gone_at is null`,
152
+ }
153
+
154
+ const SQL_INBOX: DialectTexts = {
155
+ postgres: `select principal, cursor from ${T} where endpoint = $1 and gone_at is null for update`,
156
+ sqlite: `select principal, cursor from ${T} where endpoint = ?1 and gone_at is null`,
157
+ }
158
+
159
+ const SQL_DROP_OTHER: DialectTexts = {
160
+ postgres: `delete from ${T} where endpoint = $1 and principal <> $2 and gone_at is null`,
161
+ sqlite: `delete from ${T} where endpoint = ?1 and principal <> ?2 and gone_at is null`,
162
+ }
163
+
164
+ const SQL_ADVANCE: DialectTexts = {
165
+ postgres: `update ${T} set cursor = $3 where endpoint = $1 and principal = $2 and gone_at is null and (cursor is null or cursor::uuid < $3::uuid)`,
166
+ sqlite: `update ${T} set cursor = ?3 where endpoint = ?1 and principal = ?2 and gone_at is null and (cursor is null or cursor < ?3)`,
167
+ }
168
+
169
+ const SQL_REMOVE: DialectTexts = {
170
+ postgres: `delete from ${T} where endpoint = $1 and principal = $2 returning endpoint`,
171
+ sqlite: `delete from ${T} where endpoint = ?1 and principal = ?2 returning endpoint`,
172
+ }
173
+
174
+ const SQL_RETIRE: DialectTexts = {
175
+ postgres: `update ${T} set gone_at = $2::bigint, p256dh = null, auth = null, vapid_key = null, next_attempt_at = null
176
+ where endpoint = $1 and gone_at is null returning endpoint`,
177
+ sqlite: `update ${T} set gone_at = ?2, p256dh = null, auth = null, vapid_key = null, next_attempt_at = null
178
+ where endpoint = ?1 and gone_at is null returning endpoint`,
179
+ }
180
+
181
+ function isRow(value: unknown): value is Readonly<Record<string, unknown>> {
182
+ return typeof value === 'object' && value !== null
183
+ }
184
+
185
+ /** The text in `column` of the row, or `null`; any other value is a row this module did not write. */
186
+ function nullableText(row: unknown, column: string): string | null {
187
+ if (!isRow(row)) {
188
+ throw new QueryRefusedError('unexpected_row', `${T} answered a row that is not an object`)
189
+ }
190
+ const value = row[column]
191
+ if (value === null || typeof value === 'string') {
192
+ return value
193
+ }
194
+ throw new QueryRefusedError('unexpected_row', `${T}.${column} came back as ${typeof value}`)
195
+ }
196
+
197
+ function epochMs(value: number, what: string): number {
198
+ if (!Number.isSafeInteger(value) || value < 0) {
199
+ throw new QueryRefusedError('invalid_argument', `${what} must be epoch milliseconds`)
200
+ }
201
+ return value
202
+ }
203
+
204
+ export function pushSubscriptions(): PushSubscriptions {
205
+ return Object.freeze({
206
+ async binding(session: Session, principal: string, endpoint: string): Promise<PushBinding> {
207
+ const [row] = await runFixedStatement(session, SQL_BINDING[session.dialect], [endpoint])
208
+ if (row === undefined) {
209
+ return 'unknown'
210
+ }
211
+ return nullableText(row, 'principal') === principal ? 'mine' : 'other'
212
+ },
213
+
214
+ record(
215
+ session: Session,
216
+ principal: string,
217
+ id: string,
218
+ subscription: PushSubscriptionKeys,
219
+ replace: string | null,
220
+ now: number,
221
+ ): Promise<PushRecordOutcome> {
222
+ const cutoff = epochMs(now, 'now') - PUSH_SUBSCRIPTION_LIMITS.tombstoneRetentionMs
223
+ return session.transaction(async (transaction) => {
224
+ const dialect = transaction.dialect
225
+ if (dialect === 'postgres') {
226
+ await runFixedStatement(transaction, SQL_LOCK, [principal])
227
+ }
228
+ await runFixedStatement(transaction, SQL_PRUNE[dialect], [cutoff])
229
+ // Nothing but the prune is written before both checks pass, so no outcome but `recorded` changes a row.
230
+ let cursor: string | null = null
231
+ const replacing = replace !== null && replace !== subscription.endpoint ? replace : null
232
+ if (replacing !== null) {
233
+ const [replaced] = await runFixedStatement(transaction, SQL_REPLACED[dialect], [replacing, principal, cutoff])
234
+ if (replaced === undefined) {
235
+ return 'not_replaceable'
236
+ }
237
+ cursor = nullableText(replaced, 'cursor')
238
+ }
239
+ const written = await runFixedStatement(transaction, SQL_UPSERT[dialect], [
240
+ id,
241
+ principal,
242
+ subscription.endpoint,
243
+ subscription.p256dh,
244
+ subscription.auth,
245
+ subscription.vapidKey,
246
+ // A new subscription reads only what is written after it: its id is a UUIDv7 made now. A replacement
247
+ // carries the old cursor, so a key rotation or a changed subscription neither replays nor skips.
248
+ cursor ?? id,
249
+ now,
250
+ cutoff,
251
+ ])
252
+ if (written.length === 0) {
253
+ return 'taken'
254
+ }
255
+ if (replacing !== null) {
256
+ await runFixedStatement(transaction, SQL_DROP_REPLACED[dialect], [replacing, principal])
257
+ }
258
+ await runFixedStatement(transaction, SQL_TRIM[dialect], [principal])
259
+ return 'recorded'
260
+ })
261
+ },
262
+
263
+ async inbox(session: Session, principal: string, endpoint: string): Promise<PushInboxSubscription> {
264
+ const [row] = await runFixedStatement(session, SQL_INBOX[session.dialect], [endpoint])
265
+ if (row === undefined) {
266
+ return null
267
+ }
268
+ if (nullableText(row, 'principal') !== principal) {
269
+ await runFixedStatement(session, SQL_DROP_OTHER[session.dialect], [endpoint, principal])
270
+ return null
271
+ }
272
+ return { cursor: nullableText(row, 'cursor') }
273
+ },
274
+
275
+ async advance(session: Session, principal: string, endpoint: string, cursor: string): Promise<void> {
276
+ await runFixedStatement(session, SQL_ADVANCE[session.dialect], [endpoint, principal, cursor])
277
+ },
278
+
279
+ async remove(session: Session, principal: string, endpoint: string): Promise<boolean> {
280
+ return (await runFixedStatement(session, SQL_REMOVE[session.dialect], [endpoint, principal])).length > 0
281
+ },
282
+
283
+ async retire(session: Session, endpoint: string, now: number): Promise<boolean> {
284
+ return (await runFixedStatement(session, SQL_RETIRE[session.dialect], [endpoint, epochMs(now, 'now')])).length > 0
285
+ },
286
+ })
287
+ }
package/src/registry.ts CHANGED
@@ -3,11 +3,15 @@
3
3
  // files may import.
4
4
 
5
5
  import type { Admissions } from './admissions'
6
+ import type { ContainerGrant, RelationHold } from './capability'
6
7
  import type { Session } from './database'
7
8
  import type { WebhookTables } from './framework-tables'
8
9
  import type { JobLeases } from './job-leases'
9
10
  import type { JobWakes } from './job-wakes'
11
+ import type { Notifications } from './notifications'
10
12
  import type { DataAccess } from './orm'
13
+ import type { PushSubscriptions } from './push-subscriptions'
14
+ import type { RequestReceipts } from './request-receipts'
11
15
  import type { DataLayerRuntime, TableContext, TableProbe } from './store'
12
16
  import type { StoredFiles } from './stored-files'
13
17
 
@@ -17,6 +21,41 @@ import type { StoredFiles } from './stored-files'
17
21
  */
18
22
  export type Locator = (dimension: string, id: string, using?: Session) => Promise<ReadonlyMap<string, string> | null>
19
23
 
24
+ /** Whether an active row of `relation`'s source names `principal` at `node`: what a Ref held through it is minted on. */
25
+ export type RelationCheck = (relation: string, node: string, principal: string) => Promise<boolean>
26
+
27
+ /**
28
+ * Whether a row `relation` reaches for `principal` reveals `node` of `dimension` now: what a Ref held through a reveal
29
+ * is minted on.
30
+ */
31
+ export type RevealCheck = (relation: string, dimension: string, node: string, principal: string, action: string) => Promise<boolean>
32
+
33
+ /**
34
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
35
+ * through a secondary path that holds the action for a Ref (`writeThrough`), or through a relation row or reveal: what a
36
+ * Ref held through a path is minted on, and carries.
37
+ */
38
+ export type PathCheck = (
39
+ dimension: string,
40
+ id: string,
41
+ action: string,
42
+ principal: string,
43
+ relations: readonly RelationHold[],
44
+ paths: readonly ContainerGrant[],
45
+ ) => Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }>
46
+
47
+ /**
48
+ * Of `values`, the caller's grants of `action` at nodes of `revealing`, those whose row reveals `node` of `dimension` to
49
+ * its members now: what a Ref held through member reveals is minted on, and carries.
50
+ */
51
+ export type MemberRevealCheck = (
52
+ revealing: string,
53
+ values: readonly string[],
54
+ dimension: string,
55
+ node: string,
56
+ action: string,
57
+ ) => Promise<readonly string[]>
58
+
20
59
  /** What the framework writes itself: its own `fabrika_*` tables. Usable once bound. */
21
60
  export interface FrameworkTables {
22
61
  readonly webhooks: WebhookTables
@@ -27,11 +66,21 @@ export interface FrameworkTables {
27
66
  readonly admissions: Admissions
28
67
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */
29
68
  readonly files: StoredFiles
69
+ /** The answers of keyed mutations, read and written in the invocation's transaction (ADR-0078). */
70
+ readonly receipts: RequestReceipts
71
+ /** The browsers' Web Push subscriptions (ADR-0088), read and written in the invocation's transaction. */
72
+ readonly push: PushSubscriptions
73
+ /** The notifications written for people (ADR-0088 §6), which the inbox answers. */
74
+ readonly notifications: Notifications
30
75
  }
31
76
 
32
77
  /** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
33
78
  export interface ProvisionalBinding {
34
79
  readonly locate: Locator
80
+ readonly relates: RelationCheck
81
+ readonly reveals: RevealCheck
82
+ readonly holdsThrough: PathCheck
83
+ readonly revealsToMembers: MemberRevealCheck
35
84
  release(): void
36
85
  }
37
86
 
@@ -39,7 +88,7 @@ export interface FrameworkSide {
39
88
  /** Connects the layer once and answers its binding; a call while one is connected throws. */
40
89
  bind(runtime: DataLayerRuntime): ProvisionalBinding
41
90
  readonly framework: FrameworkTables
42
- /** The untyped handle over one table that `@fabrika/db/testing` hands the isolation tests. */
91
+ /** The untyped handle over one table that `@fabrika/db/testing` hands the policy isolation kit. */
43
92
  probe(table: string): TableProbe
44
93
  /** One table's context, for the framework's own store builders (`defineStore`, `@fabrika/db/testing`). */
45
94
  tableContext(table: string, mode: 'dimension' | 'child'): TableContext
@@ -0,0 +1,107 @@
1
+ // The framework's side of `fabrika_request_receipts` (`@fabrika/db/migrations`, ADR-0078): the answer of a mutation
2
+ // whose request carried a key, kept so a repeat of that request is answered without running it again. Keyed by the
3
+ // principal and the key; only `@fabrika/app`'s dispatcher reaches it, through `frameworkTablesOf`, and always in the
4
+ // invocation's own transaction, so a receipt commits with the write it answers. Each write prunes a bounded batch of
5
+ // receipts past the retention, so the table holds about one retention of keyed writes.
6
+
7
+ import { runFixedStatement, type Session } from './database'
8
+ import { QueryRefusedError } from './errors'
9
+ import type { DialectTexts } from './job-leases'
10
+ import { REQUEST_RECEIPTS_TABLE } from './migrations'
11
+
12
+ /** What a receipt records of the request it answers: its operation, the digest of its input, and the output's JSON. */
13
+ export interface RequestReceipt {
14
+ readonly operation: string
15
+ readonly identity: string
16
+ readonly output: string
17
+ }
18
+
19
+ export interface RequestReceipts {
20
+ /**
21
+ * The receipt of `principal`'s `key`, read in `session`; `null` when there is none. On Postgres it first takes the
22
+ * key's transaction lock, so a concurrent copy of the request waits for this transaction and then reads its receipt
23
+ * instead of running too; SQLite's one writer already serializes them.
24
+ */
25
+ find(session: Session, principal: string, key: string): Promise<RequestReceipt | null>
26
+ /**
27
+ * Records `receipt` under `principal`'s `key` in `session`, created at `now` (epoch ms), after pruning a batch of
28
+ * receipts created before `retainedSince`. `false` when the key already has a receipt: another copy of the request
29
+ * recorded it meanwhile, and this one's transaction must not commit.
30
+ */
31
+ record(session: Session, principal: string, key: string, receipt: RequestReceipt, now: number, retainedSince: number): Promise<boolean>
32
+ }
33
+
34
+ const R = REQUEST_RECEIPTS_TABLE
35
+
36
+ /** Receipts one write prunes at most; every write prunes, so expired receipts never outgrow the live ones. */
37
+ const PRUNE_BATCH = 32
38
+
39
+ // Held until the transaction ends; two keys whose hashes collide only wait for each other.
40
+ const SQL_LOCK = `select 1 as locked from pg_advisory_xact_lock(hashtextextended($1 || chr(10) || $2, 0))`
41
+
42
+ const SQL_FIND: DialectTexts = {
43
+ postgres: `select operation, identity, output from ${R} where principal = $1 and request_key = $2`,
44
+ sqlite: `select operation, identity, output from ${R} where principal = ?1 and request_key = ?2`,
45
+ }
46
+
47
+ // `skip locked`: a prune never waits on a receipt another transaction holds. It never touches the key it writes.
48
+ const SQL_RECORD_POSTGRES = `with pruned as (
49
+ delete from ${R} where (principal, request_key) in (
50
+ select principal, request_key from ${R}
51
+ where created_at < $7::bigint and not (principal = $1 and request_key = $2)
52
+ limit ${PRUNE_BATCH} for update skip locked
53
+ )
54
+ )
55
+ insert into ${R} (principal, request_key, operation, identity, output, created_at) values ($1, $2, $3, $4, $5, $6::bigint)
56
+ on conflict (principal, request_key) do nothing
57
+ returning request_key`
58
+
59
+ // SQLite has no data-modifying CTE, so the prune is a statement of its own before the insert, in the same transaction.
60
+ const SQLITE_PRUNE = `delete from ${R} where (principal, request_key) in (
61
+ select principal, request_key from ${R}
62
+ where created_at < ?3 and not (principal = ?1 and request_key = ?2)
63
+ limit ${PRUNE_BATCH}
64
+ )`
65
+
66
+ const SQLITE_RECORD = `insert into ${R} (principal, request_key, operation, identity, output, created_at) values (?1, ?2, ?3, ?4, ?5, ?6)
67
+ on conflict (principal, request_key) do nothing
68
+ returning request_key`
69
+
70
+ function text(row: Readonly<Record<string, unknown>>, column: string): string {
71
+ const value = row[column]
72
+ if (typeof value !== 'string') {
73
+ throw new QueryRefusedError('unexpected_row', `${R}.${column} came back as ${typeof value}`)
74
+ }
75
+ return value
76
+ }
77
+
78
+ function isRow(value: unknown): value is Readonly<Record<string, unknown>> {
79
+ return typeof value === 'object' && value !== null
80
+ }
81
+
82
+ export function requestReceipts(): RequestReceipts {
83
+ return Object.freeze({
84
+ async find(session: Session, principal: string, key: string): Promise<RequestReceipt | null> {
85
+ if (session.dialect === 'postgres') {
86
+ await runFixedStatement(session, SQL_LOCK, [principal, key])
87
+ }
88
+ const rows = await runFixedStatement(session, SQL_FIND[session.dialect], [principal, key])
89
+ const row = rows[0]
90
+ if (row === undefined) {
91
+ return null
92
+ }
93
+ if (!isRow(row)) {
94
+ throw new QueryRefusedError('unexpected_row', `${R} answered a row that is not an object`)
95
+ }
96
+ return { operation: text(row, 'operation'), identity: text(row, 'identity'), output: text(row, 'output') }
97
+ },
98
+ async record(session: Session, principal: string, key: string, receipt: RequestReceipt, now: number, retainedSince: number): Promise<boolean> {
99
+ const values = [principal, key, receipt.operation, receipt.identity, receipt.output, now]
100
+ if (session.dialect === 'sqlite') {
101
+ await runFixedStatement(session, SQLITE_PRUNE, [principal, key, retainedSince])
102
+ return (await runFixedStatement(session, SQLITE_RECORD, values)).length === 1
103
+ }
104
+ return (await runFixedStatement(session, SQL_RECORD_POSTGRES, [...values, retainedSince])).length === 1
105
+ },
106
+ })
107
+ }
package/src/sql.ts CHANGED
@@ -6,14 +6,17 @@
6
6
  // approver's to review, since the `sql:` declaration marks the site for a closer look (ADR-0012, ADR-0050).
7
7
 
8
8
  import {
9
- dmlForeignSchema,
9
+ CTE_FORM,
10
10
  frameworkReference,
11
11
  lexSql,
12
12
  lexSqlite,
13
13
  nameReferences,
14
14
  nestedStatement,
15
15
  parenthesizedTarget,
16
- refusedFunctionCall,
16
+ ReadSql,
17
+ referencedForeignSchema,
18
+ refusedCall,
19
+ SQLITE_PARAMETER_STARTS,
17
20
  type SqlToken,
18
21
  statementKind,
19
22
  statementsOf,
@@ -117,8 +120,6 @@ const WRITE_WORDS: ReadonlySet<string> = new Set(['INSERT', 'UPDATE', 'DELETE',
117
120
  const LOCK_WORDS: ReadonlySet<string> = new Set(['UPDATE', 'NO', 'SHARE', 'KEY'])
118
121
  /** ctx.sql calls reviewed built-ins only: the functions the migrations declare are not known at runtime. */
119
122
  const NO_DECLARED_FUNCTIONS: ReadonlySet<string> = new Set()
120
- /** What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`): only the tag writes one. */
121
- const SQLITE_PARAMETER_STARTS: ReadonlySet<string> = new Set(['?', ':', '@', '$', '#'])
122
123
 
123
124
  function refuse(reason: QueryRefusal, message: string): never {
124
125
  throw new QueryRefusedError(reason, `ctx.sql: ${message}`)
@@ -236,6 +237,18 @@ function sqliteNameRefusal(tokens: readonly SqlToken[]): { readonly name: string
236
237
  return undefined
237
238
  }
238
239
 
240
+ /**
241
+ * The name of a table whose rows hand out access anywhere in a statement of a writing site, in any spelling: only the
242
+ * data layer's insert bounds the delegation, or generates the key a grant names. No statement kind is trusted to be a read (SQLite's `WITH … REPLACE`).
243
+ */
244
+ function sourceReference(tokens: readonly SqlToken[], sources: readonly string[]): { readonly name: string; readonly line: number } | undefined {
245
+ for (const token of tokens) {
246
+ const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
247
+ if (text !== undefined && sources.includes(text.toLowerCase())) return { name: text, line: token.line }
248
+ }
249
+ return undefined
250
+ }
251
+
239
252
  /**
240
253
  * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
241
254
  * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
@@ -244,7 +257,7 @@ function sqliteNameRefusal(tokens: readonly SqlToken[]): { readonly name: string
244
257
  * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
245
258
  * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
246
259
  */
247
- export function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string {
260
+ export function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase, sources: readonly string[] = []): string {
248
261
  const all = placedTokens(parts, database)
249
262
  const statements = statementsOf(all)
250
263
  const [statement] = statements
@@ -269,6 +282,13 @@ export function classifySql(parts: readonly string[], mode: SqlMode, database: S
269
282
  if (writes !== undefined) {
270
283
  refuse('sql_read_only', `sql: 'read' runs queries only, and the statement holds ${writes}; declare sql: 'write' on a mutation, a job or a webhook`)
271
284
  }
285
+ const source = mode === 'write' ? sourceReference(tokens, sources) : undefined
286
+ if (source !== undefined) {
287
+ refuse(
288
+ 'sql_name',
289
+ `'${source.name}' at line ${source.line} hands out access, so a statement that writes never names it: write its rows through ctx.db`,
290
+ )
291
+ }
272
292
  const framework = frameworkReference(tokens)
273
293
  if (framework !== undefined) {
274
294
  refuse('sql_name', `'${framework.name}' at line ${framework.line} is the framework's; ctx.sql reaches only the application's own tables`)
@@ -285,7 +305,14 @@ export function classifySql(parts: readonly string[], mode: SqlMode, database: S
285
305
  }
286
306
  return statementText(parts, markerOf(database))
287
307
  }
288
- const nested = nestedStatement(tokens) ?? parenthesizedTarget(tokens)
308
+ const read = ReadSql.query(tokens)
309
+ if (read.ctes.unread !== undefined) {
310
+ refuse(
311
+ 'sql_statement',
312
+ `the WITH at line ${read.ctes.unread} begins a CTE list that cannot be read; write each CTE as ${CTE_FORM}, a CYCLE mark a constant and never an interpolated value`,
313
+ )
314
+ }
315
+ const nested = nestedStatement(read) ?? parenthesizedTarget(tokens)
289
316
  if (nested !== undefined) {
290
317
  refuse('sql_statement', `${nested.statement} at line ${nested.line} is refused inside another statement`)
291
318
  }
@@ -296,16 +323,17 @@ export function classifySql(parts: readonly string[], mode: SqlMode, database: S
296
323
  if (unicodeIdentifier(tokens) !== undefined) {
297
324
  refuse('sql_name', 'a U&"…" name is refused: write the name plainly')
298
325
  }
299
- for (const reference of nameReferences(tokens)) {
326
+ const references = nameReferences(read)
327
+ for (const reference of references) {
300
328
  if (reference.role !== 'call' && reference.name.startsWith('pg_')) {
301
329
  refuse('sql_name', `'${reference.name}' at line ${reference.line} is a catalog name; ctx.sql reaches only the application's own tables`)
302
330
  }
303
331
  }
304
- const foreign = dmlForeignSchema(tokens, database.schema)
332
+ const foreign = referencedForeignSchema(references, database.schema)
305
333
  if (foreign !== undefined) {
306
334
  refuse('sql_name', `the schema '${foreign}' is outside the application's; write its tables' names unqualified`)
307
335
  }
308
- const call = refusedFunctionCall(tokens, database.schema, NO_DECLARED_FUNCTIONS)
336
+ const call = refusedCall(references, database.schema, NO_DECLARED_FUNCTIONS)
309
337
  if (call !== undefined) {
310
338
  refuse(
311
339
  'sql_function',
@@ -556,7 +584,7 @@ function scopeOptions(options: unknown): { readonly alias: string | undefined; r
556
584
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
557
585
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
558
586
  */
559
- export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag {
587
+ export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf, sources: readonly string[]): SqlTag {
560
588
  const tag = <S extends z.core.$ZodType>(row: S) => {
561
589
  site.check()
562
590
  if (!(row instanceof z.core.$ZodType)) {
@@ -567,7 +595,7 @@ export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf):
567
595
  site.check()
568
596
  return failing(site, async () => {
569
597
  const expanded = expandScopes(site, templateParts(text), values, database)
570
- const statement = classifySql(expanded.parts, site.mode, database)
598
+ const statement = classifySql(expanded.parts, site.mode, database, sources)
571
599
  const parameters = expanded.values.map((value, index) => parameterOf(value, index + 1, database))
572
600
  const session = await site.session()
573
601
  if (session.readOnly && site.mode === 'write') {