@fabrika/db 0.9.0-dev.23 → 0.9.0-dev.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/policy.ts CHANGED
@@ -205,20 +205,20 @@ export interface ConfersPolicy<Col extends string> {
205
205
  export type FilePolicies<Col extends string> = { readonly [C in Col]?: string }
206
206
 
207
207
  /**
208
- * A column's own actions. `read`: only a capability of exactly that action reads, filters or sorts by the column;
208
+ * A column's own actions. `read`: only a capability of one of those actions reads, filters or sorts by the column;
209
209
  * without one it falls back to the table's read action. `write`: only a capability of that action updates the column,
210
210
  * and the table's update action does not, so the column is not in `update`.
211
211
  */
212
212
  export type ColumnPolicies<Col extends string, A extends string> = { readonly [C in Col]?: ColumnPolicy<A> }
213
213
 
214
- /** A column's own read action, its own write action, or both. */
214
+ /** A column's own read actions (one, or a list as a table's read takes), its own write action, or both. */
215
215
  export interface ColumnPolicy<A extends string> {
216
- readonly read?: A
216
+ readonly read?: TableAction<A>
217
217
  readonly write?: A
218
218
  }
219
219
 
220
220
  /** A table no handler writes (a reference table) declares column read actions only. */
221
- export type ColumnReadPolicies<Col extends string, A extends string> = { readonly [C in Col]?: { readonly read: A } }
221
+ export type ColumnReadPolicies<Col extends string, A extends string> = { readonly [C in Col]?: { readonly read: TableAction<A> } }
222
222
 
223
223
  export interface DimensionPolicy<Col extends string, A extends string, V extends Col = Col> extends WritablePolicy<Col, A, V, RecordActions<A>> {
224
224
  readonly scope: DimensionScope<Col>
@@ -342,8 +342,8 @@ export interface TableModel {
342
342
  readonly queue: QueueModel | undefined
343
343
  /** The file columns, each with its file kind: a reference to `fabrika_files`, written only with a file reference. */
344
344
  readonly files: Readonly<Record<string, string>>
345
- /** The columns that declare their own read action, as declared (also those equal to the table's). */
346
- readonly columnReads: Readonly<Record<string, string>>
345
+ /** The columns that declare their own read actions, as declared (also those equal to the table's). */
346
+ readonly columnReads: Readonly<Record<string, readonly string[]>>
347
347
  /** The columns that declare their own write action: only a capability of it updates them. */
348
348
  readonly columnWrites: Readonly<Record<string, string>>
349
349
  /** The columns of Postgres type `date`, read as `YYYY-MM-DD` text. */
@@ -506,6 +506,8 @@ type ParsedTable =
506
506
  readonly writeThroughInput: unknown
507
507
  readonly memberRevealsInput: unknown
508
508
  readonly accessInput: unknown
509
+ /** The stamped columns the policy did not name: a written table's `version` and `created_by` (`conventional`). */
510
+ readonly byConvention: NameSet
509
511
  }
510
512
 
511
513
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
@@ -722,6 +724,11 @@ function isViewEntry(table: string, entry: unknown): boolean {
722
724
  return view === true
723
725
  }
724
726
 
727
+ /** The version column of a written table whose policy names none, when the table has it. */
728
+ const VERSION_COLUMN = 'version'
729
+ /** The `createdBy` column of a written table whose policy names none, when the table has it. */
730
+ const CREATED_BY_COLUMN = 'created_by'
731
+
725
732
  /** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
726
733
  interface ColumnReader {
727
734
  readonly column: (name: unknown, field: string) => string
@@ -795,12 +802,23 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
795
802
  const actions = parseActions(table, scopeInput, ownEntry(policy, 'actions'), action)
796
803
  const insert = nameSet(columnsOf(ownEntry(policy, 'insert'), 'insert'))
797
804
  const update = nameSet(columnsOf(ownEntry(policy, 'update'), 'update'))
805
+ const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
806
+ // A written table's column named by the convention is stamped unless the policy names another (`NormalizedPolicies`).
807
+ const conventional = (name: string): string | undefined => (writable && inSet(columns, name) ? name : undefined)
798
808
  const versionInput = ownEntry(policy, 'version')
799
809
  const createdByInput = ownEntry(policy, 'createdBy')
800
- const version = versionInput === undefined ? undefined : column(versionInput, 'version')
801
- const createdBy = createdByInput === undefined ? undefined : column(createdByInput, 'createdBy')
810
+ const version = versionInput === undefined ? conventional(VERSION_COLUMN) : column(versionInput, 'version')
811
+ const createdBy = createdByInput === undefined ? conventional(CREATED_BY_COLUMN) : column(createdByInput, 'createdBy')
812
+ const unnamed: string[] = []
813
+ if (versionInput === undefined && version !== undefined) {
814
+ unnamed[unnamed.length] = version
815
+ }
816
+ if (createdByInput === undefined && createdBy !== undefined) {
817
+ unnamed[unnamed.length] = createdBy
818
+ }
819
+ const byConvention = nameSet(unnamed)
802
820
  const restricted: string[] = []
803
- const columnReads: Record<string, string> = {}
821
+ const columnReads: Record<string, readonly string[]> = {}
804
822
  const columnWrites: Record<string, string> = {}
805
823
  const columnsInput = ownEntry(policy, 'columns')
806
824
  const columnPolicies = columnsInput === undefined ? freeze({}) : plainRecord(columnsInput, `${table}: columns`)
@@ -815,10 +833,12 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
815
833
  throw new PolicyError(`${table}: columns.${name} declares no action; it takes read, write or both`)
816
834
  }
817
835
  if (readInput !== undefined) {
818
- const read = action(readInput, `columns.${name}.read`)
819
- setOwn(columnReads, name, read)
820
- // With several read actions, a column of one of them is hidden from the others.
821
- if (actions.read.length > 1 || !includes(actions.read, read)) {
836
+ const reads = isArray(readInput)
837
+ ? distinctActions(table, readInput, `columns.${name}.read`, action)
838
+ : freeze([action(readInput, `columns.${name}.read`)])
839
+ setOwn(columnReads, name, reads)
840
+ // Hidden from a table read action its list leaves out; `'any'` names none, so it hides it from every one.
841
+ if (actions.read.length === 0 || !everyIncluded(actions.read, reads)) {
822
842
  restricted[restricted.length] = name
823
843
  }
824
844
  }
@@ -836,9 +856,8 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
836
856
  throw new PolicyError(`${table}: the key ${scope.key} takes no action of its own`)
837
857
  }
838
858
  if (version !== undefined && hasOwn(columnPolicies, version)) {
839
- throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
859
+ throw new PolicyError(`${table}: the version ${version} takes no action of its own${conventionOf(byConvention, version, 'version') ?? ''}`)
840
860
  }
841
- const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
842
861
  const queueInput = ownEntry(policy, 'queue')
843
862
  const filesInput = ownEntry(policy, 'files')
844
863
  // On a view, an empty insert or update list is refused too: it states a write the view never takes.
@@ -898,6 +917,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
898
917
  writeThroughInput: ownEntry(policy, 'writeThrough'),
899
918
  memberRevealsInput: ownEntry(policy, 'memberReveals'),
900
919
  accessInput: ownEntry(policy, 'access'),
920
+ byConvention,
901
921
  }
902
922
  }
903
923
 
@@ -1087,8 +1107,8 @@ export function namesAction(model: TableModel, action: string): boolean {
1087
1107
  }
1088
1108
 
1089
1109
  /**
1090
- * The columns a capability of `action` reads: every one that declares no read action of its own, or exactly this
1091
- * one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
1110
+ * The columns a capability of `action` reads: every one that declares no read action of its own, or one whose own
1111
+ * read actions include this one. A capability reads its own row, so a write `Ref` sees the columns of its action and none of another's.
1092
1112
  */
1093
1113
  export function visibleFor(model: TableModel, action: string): readonly string[] {
1094
1114
  return visibleThrough(model, soleReach(action))
@@ -1131,13 +1151,33 @@ export function visibleThrough(model: TableModel, reach: ReadReach): readonly st
1131
1151
  for (let index = 0; index < columns.length; index++) {
1132
1152
  const name = columns[index] ?? ''
1133
1153
  const declared = hasOwn(model.columnReads, name) ? model.columnReads[name] : undefined
1134
- if (declared === undefined || readsAsAction(model, declared, reach)) {
1154
+ if (declared === undefined || readsAsOneOf(model, declared, reach)) {
1135
1155
  visible[visible.length] = name
1136
1156
  }
1137
1157
  }
1138
1158
  return freeze(visible)
1139
1159
  }
1140
1160
 
1161
+ /** Whether one of a column's own read actions reads every row a read of `reach` answers (`readsAsAction`). */
1162
+ export function readsAsOneOf(model: TableModel, actions: readonly string[], reach: ReadReach): boolean {
1163
+ for (let index = 0; index < actions.length; index++) {
1164
+ if (readsAsAction(model, actions[index] ?? '', reach)) {
1165
+ return true
1166
+ }
1167
+ }
1168
+ return false
1169
+ }
1170
+
1171
+ /** Whether every one of `actions` is in `list`. */
1172
+ function everyIncluded(actions: readonly string[], list: readonly string[]): boolean {
1173
+ for (let index = 0; index < actions.length; index++) {
1174
+ if (!includes(list, actions[index] ?? '')) {
1175
+ return false
1176
+ }
1177
+ }
1178
+ return true
1179
+ }
1180
+
1141
1181
  /** Every action that updates a column of `model`: its update action and each column's own write action. */
1142
1182
  export function updateActions(model: TableModel): readonly string[] {
1143
1183
  const actions: string[] = []
@@ -1346,6 +1386,8 @@ interface Stamp {
1346
1386
  readonly role: string
1347
1387
  /** An insert may set it: a queue row's first due time. */
1348
1388
  readonly insertable?: true
1389
+ /** Why a column the policy may not have named is stamped: its name is the convention's. */
1390
+ readonly convention?: string
1349
1391
  }
1350
1392
 
1351
1393
  /** The columns the layer writes itself: the key, every containment link, the version and the creator. */
@@ -1361,10 +1403,10 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
1361
1403
  }
1362
1404
  }
1363
1405
  if (table.version !== undefined) {
1364
- stamps[stamps.length] = { column: table.version, role: 'the version' }
1406
+ stamps[stamps.length] = { column: table.version, role: 'the version', convention: conventionOf(table.byConvention, table.version, 'version') }
1365
1407
  }
1366
1408
  if (table.createdBy !== undefined) {
1367
- stamps[stamps.length] = { column: table.createdBy, role: 'createdBy' }
1409
+ stamps[stamps.length] = { column: table.createdBy, role: 'createdBy', convention: conventionOf(table.byConvention, table.createdBy, 'createdBy') }
1368
1410
  }
1369
1411
  if (table.queue !== undefined) {
1370
1412
  stamps[stamps.length] = { column: table.queue.attempts, role: 'queue.attempts' }
@@ -1373,6 +1415,11 @@ function stampsOf(table: ParsedTable, chain: readonly Container[]): readonly Sta
1373
1415
  return stamps
1374
1416
  }
1375
1417
 
1418
+ /** Why a column the policy did not name is stamped, or nothing when the policy named it. */
1419
+ function conventionOf(byConvention: NameSet, column: string, field: string): string | undefined {
1420
+ return inSet(byConvention, column) ? ` (a written table's column named ${column} is its ${field} unless the policy names another)` : undefined
1421
+ }
1422
+
1376
1423
  /**
1377
1424
  * Each stamped column holds one role and is never written by a handler. A shared column would let one stamp
1378
1425
  * overwrite another: `createdBy` on the key inserts the principal as the id, `version` on a container column
@@ -1401,10 +1448,10 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
1401
1448
  }
1402
1449
  }
1403
1450
  if ((stamp.insertable !== true && inSet(table.insert, stamp.column)) || inSet(table.update, stamp.column)) {
1404
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update`)
1451
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; remove it from insert and update${stamp.convention ?? ''}`)
1405
1452
  }
1406
1453
  if (hasOwn(table.columnWrites, stamp.column)) {
1407
- throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
1454
+ throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own${stamp.convention ?? ''}`)
1408
1455
  }
1409
1456
  if (inSet(table.json, stamp.column)) {
1410
1457
  throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
@@ -1489,7 +1536,8 @@ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel,
1489
1536
  const linkedTable = (name: string): LinkedTable | undefined => {
1490
1537
  const target = ownEntry(byName, name)
1491
1538
  if (target === undefined) return undefined
1492
- const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, ...rest } = target
1539
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, byConvention, ...rest } =
1540
+ target
1493
1541
  return { ...rest, ...resolve(target, []) }
1494
1542
  }
1495
1543
  const hopRule: HopRule = (from, column, to, key, backward) => {
@@ -1532,8 +1580,18 @@ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel,
1532
1580
  const table = parsed[index]
1533
1581
  if (table !== undefined) {
1534
1582
  const { scope, chain } = resolve(table, [])
1535
- const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, accessInput, ...rest } =
1536
- table
1583
+ const {
1584
+ confersInput,
1585
+ whenInput,
1586
+ relationWhenInput,
1587
+ revealsInput,
1588
+ readThroughInput,
1589
+ writeThroughInput,
1590
+ memberRevealsInput,
1591
+ accessInput,
1592
+ byConvention,
1593
+ ...rest
1594
+ } = table
1537
1595
  const linked = { ...rest, scope, chain }
1538
1596
  const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1539
1597
  const owner = ownEntry(owners, dimension)
@@ -1685,7 +1743,10 @@ function tableActionNames(table: LinkedTable): NameSet {
1685
1743
  }
1686
1744
  const reads = ownKeys(table.columnReads)
1687
1745
  for (let index = 0; index < reads.length; index++) {
1688
- names[names.length] = ownEntry(table.columnReads, reads[index] ?? '') ?? ''
1746
+ const actions = ownEntry(table.columnReads, reads[index] ?? '') ?? []
1747
+ for (let position = 0; position < actions.length; position++) {
1748
+ names[names.length] = actions[position] ?? ''
1749
+ }
1689
1750
  }
1690
1751
  const writes = ownKeys(table.columnWrites)
1691
1752
  for (let index = 0; index < writes.length; index++) {
@@ -3033,11 +3094,11 @@ type Flat<T> = { [K in keyof T]: T[K] }
3033
3094
 
3034
3095
  type ColumnPoliciesOf<P, T> = PolicyOf<P, T> extends { readonly columns: infer C } ? C : never
3035
3096
  type TableReadAction<P, T> = PolicyOf<P, T> extends { readonly scope: { readonly read: infer A } } ? A : ActionOf<P, T, 'read'>
3036
- /** Columns whose own read action is not the table's: no read by the table's read action returns them. */
3097
+ /** Columns whose own read actions leave out one of the table's: no read by the table's read action returns them. */
3037
3098
  type RestrictedColumns<P, T> = [ColumnPoliciesOf<P, T>] extends [never] ? never
3038
3099
  : {
3039
3100
  [K in keyof ColumnPoliciesOf<P, T>]: ColumnPoliciesOf<P, T>[K] extends { readonly read: infer R }
3040
- ? ([TableReadAction<P, T>] extends [R] ? never : K)
3101
+ ? ([TableReadAction<P, T>] extends [R extends readonly (infer L extends string)[] ? L : R] ? never : K)
3041
3102
  : never
3042
3103
  }[keyof ColumnPoliciesOf<P, T>]
3043
3104
 
package/src/registry.ts CHANGED
@@ -9,6 +9,7 @@ import type { WebhookTables } from './framework-tables'
9
9
  import type { JobLeases } from './job-leases'
10
10
  import type { JobWakes } from './job-wakes'
11
11
  import type { DataAccess } from './orm'
12
+ import type { RequestReceipts } from './request-receipts'
12
13
  import type { DataLayerRuntime, TableContext, TableProbe } from './store'
13
14
  import type { StoredFiles } from './stored-files'
14
15
 
@@ -63,6 +64,8 @@ export interface FrameworkTables {
63
64
  readonly admissions: Admissions
64
65
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */
65
66
  readonly files: StoredFiles
67
+ /** The answers of keyed mutations, read and written in the invocation's transaction (ADR-0078). */
68
+ readonly receipts: RequestReceipts
66
69
  }
67
70
 
68
71
  /** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
@@ -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/store.ts CHANGED
@@ -155,6 +155,7 @@ import {
155
155
  visibleThrough,
156
156
  } from './policy'
157
157
  import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
158
+ import { requestReceipts } from './request-receipts'
158
159
  import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
159
160
  import { storedFiles, storedFilesMetadata } from './stored-files'
160
161
  import { type TablePolicies, tablePolicies } from './tables'
@@ -3504,6 +3505,7 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
3504
3505
  wakes: jobWakes(() => runtimeOf(connection)),
3505
3506
  admissions: admissions(() => runtimeOf(connection)),
3506
3507
  files: storedFiles(() => runtimeOf(connection)),
3508
+ receipts: requestReceipts(),
3507
3509
  }),
3508
3510
  data: dataAccess({
3509
3511
  models,
package/src/tables.ts CHANGED
@@ -35,6 +35,7 @@ export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-r
35
35
  export { PolicyError } from './errors'
36
36
  export type { FileReference } from './file-references'
37
37
  export type {
38
+ AllOptions,
38
39
  AnyDbIndex,
39
40
  ApplicationRows,
40
41
  ApplicationTables,
@@ -168,9 +169,10 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
168
169
  const declared = [...ownKeys(model.columnReads), ...ownKeys(model.columnWrites)]
169
170
  for (let index = 0; index < declared.length; index++) {
170
171
  const name = declared[index] ?? ''
171
- const read = ownEntry(model.columnReads, name)
172
+ // A single read action stays its text, so a policy that names one keeps its digest.
173
+ const read = actionArtifact(ownEntry(model.columnReads, name) ?? [])
172
174
  const write = ownEntry(model.columnWrites, name)
173
- setOwn(columns, name, { ...(read === undefined ? {} : { read }), ...(write === undefined ? {} : { write }) })
175
+ setOwn(columns, name, { ...(read === null ? {} : { read }), ...(write === undefined ? {} : { write }) })
174
176
  }
175
177
  return {
176
178
  scope: scopeOf(model.scope),
@@ -94,11 +94,20 @@ export type VocabularyChildScope<Table extends string, Col extends string> =
94
94
  & { readonly child: Table; readonly column?: Col; readonly inherit?: readonly Col[] }
95
95
  & KeyField<Col>
96
96
 
97
- interface WritableFields<Col extends string, A extends string, Ver extends Col, Acts = TableActions<A>> {
97
+ /** A written table whose `version` column is not an INTEGER names its version column: `version` would be it otherwise. */
98
+ interface NamesItsVersionColumn<Ver extends string> {
99
+ readonly version: Ver
100
+ }
101
+
102
+ /** `version` defaults to the `version` column, so it is required only where that column holds no number. */
103
+ type VersionField<Col extends string, Ver extends Col> = 'version' extends Col
104
+ ? 'version' extends Ver ? { readonly version?: Ver } : NamesItsVersionColumn<Ver>
105
+ : { readonly version?: Ver }
106
+
107
+ interface WritableFields<Col extends string, A extends string, Acts = TableActions<A>> {
98
108
  readonly actions: Acts
99
109
  readonly insert?: readonly Col[]
100
110
  readonly update?: readonly Col[]
101
- readonly version?: Ver
102
111
  readonly createdBy?: Col
103
112
  readonly columns?: ColumnPolicies<Col, A>
104
113
  /** The file columns, each with the file kind it holds (`c.files`): a `uuid` foreign key to `fabrika_files`. */
@@ -167,11 +176,15 @@ type ChildScopes<Table extends string, Col extends string, S, P> = unknown exten
167
176
  : ChildTableScope<Parent, StatedDimensionOf<P, Parent>, Col>
168
177
  : VocabularyChildScope<Table, Col>
169
178
 
170
- type AuthoredDimensionPolicy<Col extends string, A extends string, V, Ver extends Col, S> = WritableFields<Col, A, Ver, RecordActions<A>> & {
171
- readonly scope: DimensionScopes<V, Col, S>
172
- }
179
+ type AuthoredDimensionPolicy<Col extends string, A extends string, V, Ver extends Col, S> =
180
+ & WritableFields<Col, A, RecordActions<A>>
181
+ & VersionField<Col, Ver>
182
+ & {
183
+ readonly scope: DimensionScopes<V, Col, S>
184
+ }
173
185
  type AuthoredChildPolicy<Table extends string, Col extends string, A extends string, Ver extends Col, S, P> =
174
- & WritableFields<Col, A, Ver, RecordActions<A>>
186
+ & WritableFields<Col, A, RecordActions<A>>
187
+ & VersionField<Col, Ver>
175
188
  & {
176
189
  readonly scope: ChildScopes<Table, Col, S, P>
177
190
  }
@@ -193,7 +206,7 @@ interface ReadOnlyFields<Col extends string, A extends string> {
193
206
  readonly createdBy?: never
194
207
  readonly queue?: never
195
208
  readonly files?: never
196
- readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
209
+ readonly columns?: { readonly [C in Col]?: { readonly read: TableAction<A>; readonly write?: never } }
197
210
  }
198
211
 
199
212
  /**
@@ -215,13 +228,16 @@ export type VocabularyViewPolicy<Table extends string, Col extends string, A ext
215
228
 
216
229
  type ReferenceViewPolicy<Col extends string, A extends string> = ReferencePolicy<Col, A> & {
217
230
  readonly actions: NoWriteActions
218
- readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
231
+ readonly columns?: { readonly [C in Col]?: { readonly read: TableAction<A>; readonly write?: never } }
219
232
  }
220
233
 
221
234
  /** An application table's scope: why its rows belong to no dimension; `key` defaults to `id`. */
222
- type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> = WritableFields<Col, A, Ver, ApplicationActions<A>> & {
223
- readonly scope: { readonly app: string } & KeyField<Col>
224
- }
235
+ type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> =
236
+ & WritableFields<Col, A, ApplicationActions<A>>
237
+ & VersionField<Col, Ver>
238
+ & {
239
+ readonly scope: { readonly app: string } & KeyField<Col>
240
+ }
225
241
 
226
242
  /**
227
243
  * One table's policy as an application writes it under a vocabulary. `S` is its scope as written: its mode picks the
@@ -296,17 +312,27 @@ type NormalScope<S, V, P> = S extends { readonly dimension: infer D extends stri
296
312
  /** A view's normalized policy says so, which the handle types read: no site writes it. */
297
313
  type ViewMark<T, Views> = T extends Views ? { readonly view: true } : unknown
298
314
 
315
+ /** A written table's `version` and `created_by` columns are its version and creator unless its policy names others. */
316
+ type Conventions<Row, Pol> =
317
+ & (Pol extends { readonly version: string } ? unknown : 'version' extends keyof Row ? { readonly version: 'version' } : unknown)
318
+ & (Pol extends { readonly createdBy: string } ? unknown : 'created_by' extends keyof Row ? { readonly createdBy: 'created_by' } : unknown)
319
+
320
+ /** Only a dimension, child or application table is written; a view and a reference table get no convention. */
321
+ type WrittenConventions<DB, T, Pol, S, Views> = T extends Views ? unknown
322
+ : S extends { readonly reference: unknown } ? unknown
323
+ : Conventions<T extends keyof DB ? DB[T] : never, Pol>
324
+
299
325
  /**
300
- * The policies as the layer models them: every dimension table's key and container, and every child's key and
301
- * column, stated as the vocabulary and the conventions derive them; each view marked.
326
+ * The policies as the layer models them: every dimension table's key and container, every child's key and column,
327
+ * and a written table's version and creator, stated as the vocabulary and the conventions derive them; each view marked.
302
328
  */
303
- export type NormalizedPolicies<P, V, Views = never> = {
329
+ export type NormalizedPolicies<DB, P, V, Views = never> = {
304
330
  readonly [T in keyof P]: P[T] extends { readonly scope: infer S }
305
- ? Flat<Omit<P[T], 'scope' | 'view'> & { readonly scope: NormalScope<S, V, P> } & ViewMark<T, Views>>
331
+ ? Flat<Omit<P[T], 'scope' | 'view'> & { readonly scope: NormalScope<S, V, P> } & ViewMark<T, Views> & WrittenConventions<DB, T, P[T], S, Views>>
306
332
  : P[T]
307
333
  }
308
334
 
309
335
  /** Takes the policies of exactly the tables of the schema, and of any of its views, written in the vocabulary form. */
310
336
  export type DefineVocabularyPolicies<DB, V, Views extends string = never> = <const P extends VocabularyPolicyMap<DB, V, P, Views>>(
311
337
  policies: P & { readonly [K in Exclude<keyof P, keyof DB>]: never },
312
- ) => Tables<DB, NormalizedPolicies<P, V, Views>>
338
+ ) => Tables<DB, NormalizedPolicies<DB, P, V, Views>>
@@ -41,6 +41,7 @@ export declare const QUERY_REFUSALS: {
41
41
  readonly statement_shape: "the compiled statement has a form the guard does not admit";
42
42
  readonly scope_predicate: "the scope predicate is missing or is not a top-level conjunct";
43
43
  readonly list_page: "a list limit, cursor or order outside what a page admits";
44
+ readonly too_many_rows: "all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate";
44
45
  readonly undeclared_reach: "the site reaches data it did not declare (sql or unscoped, or their mode)";
45
46
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
46
47
  readonly sql_statement: "ctx.sql runs one statement of an admitted kind, and none inside another";
@@ -52,7 +53,7 @@ export declare const QUERY_REFUSALS: {
52
53
  readonly file_scan: "a scan verdict outside the scan job's lease";
53
54
  readonly claim_site: "claim leases rows in a transaction of its own: a job calls it on ctx.db, never inside ctx.transaction or a request";
54
55
  readonly on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action";
55
- readonly public_reach: "a public procedure updates, removes, locks or claims no row, and an insert's conflict writes nothing";
56
+ readonly public_reach: "a public procedure updates, removes, locks or claims no row, reads none with all(), and an insert's conflict writes nothing";
56
57
  readonly file_value: "a file column takes a file reference this request holds and may read (an incoming file, a put, or a read under the table's read action) of the column's kind, or null";
57
58
  readonly file_scope: "a file is referenced from another top-level scope than the one its first reference set";
58
59
  };
@@ -12,6 +12,7 @@ export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection
12
12
  export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
13
13
  export type { DataAccess, DataHandles, DataSite } from './orm';
14
14
  export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
15
+ export type { RequestReceipt, RequestReceipts } from './request-receipts';
15
16
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
16
17
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files';
17
18
  /** Whether `value` is an object `scoped(tables)` created, rather than a look-alike with the same fields. */
@@ -4,7 +4,7 @@ export { applicationSchema, Database, type DatabaseEngine, type Executor, type S
4
4
  export type { AllowedOperator, ComparisonOperator, ConditionTuple, ListOperator, NoColumns, NullOperator, PatternOperator, Primitive, ScopedSelect, } from './description';
5
5
  export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, DatabaseError, LeaseLostError, PolicyError, QUERY_REFUSALS, type QueryRefusal, QueryRefusedError, } from './errors';
6
6
  export type { JsonColumnValue, JsonValue } from './json';
7
- export type { AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIndex, IndexedTable, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, Saved, ScopeTarget, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
7
+ export type { AllOptions, AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIndex, IndexedTable, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, Saved, ScopeTarget, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
8
8
  export { type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type InsertValues, isTables, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type RowOf, type TableActions, type TableInsert, Tables, type TableUpdate, type UpdateValues, type VersionColumn, type VocabularyTables, } from './policy';
9
9
  export { type AggregateRow, type AggregateSpec, type ChildListScope, type DataLayer, type DataLayerRuntime, scoped, type ScopedDatabase, } from './store';
10
10
  export { type TablePolicies, tablePolicies } from './tables';
@@ -11,6 +11,7 @@ export declare const FORM_FILES_TABLE = "fabrika_form_files";
11
11
  export declare const FORM_BYTES_TABLE = "fabrika_form_bytes";
12
12
  export declare const FILES_TABLE = "fabrika_files";
13
13
  export declare const FILE_DELETIONS_TABLE = "fabrika_file_deletions";
14
+ export declare const REQUEST_RECEIPTS_TABLE = "fabrika_request_receipts";
14
15
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
15
16
  export declare const FILES_RELEASE_FUNCTION = "fabrika_files_release";
16
17
  /**