@fabrika/db 0.9.0-dev.3 → 0.9.0-dev.30

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 (82) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +8 -5
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +181 -0
  24. package/src/migrations.ts +43 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +198 -67
  27. package/src/orm.ts +383 -133
  28. package/src/policy.ts +1933 -122
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +55 -3
  31. package/src/request-receipts.ts +107 -0
  32. package/src/sql.ts +247 -476
  33. package/src/sqlite-bun.ts +149 -0
  34. package/src/sqlite-migrate.ts +242 -0
  35. package/src/sqlite.ts +269 -0
  36. package/src/store.ts +2292 -239
  37. package/src/stored-files.ts +188 -52
  38. package/src/tables.ts +171 -5
  39. package/src/temporal.ts +122 -9
  40. package/src/testing-shared.ts +1348 -0
  41. package/src/testing-sqlite.ts +685 -0
  42. package/src/testing.ts +310 -494
  43. package/src/vocabulary-tables.ts +159 -27
  44. package/types/src/application-rows.d.ts +58 -0
  45. package/types/src/authority.d.ts +147 -0
  46. package/types/src/builtins.d.ts +2 -0
  47. package/types/src/capability.d.ts +55 -2
  48. package/types/src/codegen-sqlite.d.ts +13 -0
  49. package/types/src/codegen.d.ts +79 -5
  50. package/types/src/condition-nodes.d.ts +9 -0
  51. package/types/src/conditions.d.ts +151 -0
  52. package/types/src/database.d.ts +81 -20
  53. package/types/src/description.d.ts +26 -8
  54. package/types/src/errors.d.ts +7 -5
  55. package/types/src/file-columns.d.ts +6 -4
  56. package/types/src/framework.d.ts +12 -5
  57. package/types/src/guard.d.ts +24 -0
  58. package/types/src/index.d.ts +5 -4
  59. package/types/src/job-leases.d.ts +34 -5
  60. package/types/src/job-wakes.d.ts +101 -0
  61. package/types/src/json.d.ts +18 -0
  62. package/types/src/migrations-sqlite.d.ts +4 -0
  63. package/types/src/migrations.d.ts +2 -0
  64. package/types/src/nodes.d.ts +17 -2
  65. package/types/src/orm-types.d.ts +155 -63
  66. package/types/src/orm.d.ts +21 -0
  67. package/types/src/policy.d.ts +344 -16
  68. package/types/src/postgres.d.ts +12 -0
  69. package/types/src/registry.d.ts +40 -3
  70. package/types/src/request-receipts.d.ts +22 -0
  71. package/types/src/sql.d.ts +29 -21
  72. package/types/src/sqlite-bun.d.ts +21 -0
  73. package/types/src/sqlite-migrate.d.ts +28 -0
  74. package/types/src/sqlite.d.ts +24 -0
  75. package/types/src/store.d.ts +143 -34
  76. package/types/src/stored-files.d.ts +6 -2
  77. package/types/src/tables.d.ts +18 -2
  78. package/types/src/temporal.d.ts +24 -0
  79. package/types/src/testing-shared.d.ts +290 -0
  80. package/types/src/testing-sqlite.d.ts +37 -0
  81. package/types/src/testing.d.ts +2 -93
  82. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -3,13 +3,13 @@
3
3
  // and claims, locks and stamps the file in the write's own transaction. The file's row is `fabrika_files`
4
4
  // (`stored-files.ts`); the column is a foreign key to it, so a file some row references is never deleted.
5
5
 
6
- import { defineValue, ownDescriptor, ownKeys } from './builtins'
6
+ import { defineValue, hasOwn, inSet, type NameSet, nameSet, ownDescriptor, ownKeys } from './builtins'
7
7
  import { runFixedStatement, type Session } from './database'
8
8
  import type { Primitive } from './description'
9
9
  import { NotFoundError, QueryRefusedError } from './errors'
10
10
  import { fileHoldingOf, fileReference, holdsFile } from './file-references'
11
11
  import { isPlainIdentifier } from './identifier'
12
- import type { TableModel } from './policy'
12
+ import { includes, type ReadReach, readsAsAction, readsAsOneOf, type TableModel } from './policy'
13
13
  import { claimStoredFile, lockStoredFile, stampStoredFile, storedFilesMetadata } from './stored-files'
14
14
 
15
15
  /** Where a site's file references belong, and what claiming a pending one needs. */
@@ -24,17 +24,59 @@ export interface FileBinding {
24
24
  scans(kind: string): boolean
25
25
  }
26
26
 
27
- /** Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's read action. */
28
- function readsFile(model: TableModel, column: string, action: string): boolean {
29
- const own = Object.hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
30
- return own === undefined ? model.actions.read.includes(action) : own === action
27
+ /**
28
+ * Whether a reference read under `reach` (one action, or an `anyOf` endpoint's held actions that read the row) lets its
29
+ * holder serve, open and copy the file: a table read action, or one of the column's own read actions, that reads every answered
30
+ * row alone (`readsAsAction`), or a table read action among `held`, the actions a job holds over the whole application.
31
+ * When every action of the reach is a table read action, each answered row was admitted by one that alone reads it,
32
+ * so a column without its own read action is readable. A column with its own read actions is answered only under one of
33
+ * them (`visibleThrough`), so `held` never widens it. A table read with `'any'` admits whoever read the row: the
34
+ * store refused every other reader.
35
+ */
36
+ function readsFile(model: TableModel, column: string, reach: ReadReach, held: NameSet): boolean {
37
+ const own = hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
38
+ if (own !== undefined) {
39
+ return readsAsOneOf(model, own, reach)
40
+ }
41
+ if (model.actions.readAny || readsThroughEvery(model, reach)) {
42
+ return true
43
+ }
44
+ const reads = model.actions.read
45
+ for (let index = 0; index < reads.length; index++) {
46
+ const read = reads[index]
47
+ if (read !== undefined && (readsAsAction(model, read, reach) || inSet(held, read))) {
48
+ return true
49
+ }
50
+ }
51
+ return false
52
+ }
53
+
54
+ /** Whether the reach holds at least one action and each is one of the table's read actions. */
55
+ function readsThroughEvery(model: TableModel, reach: ReadReach): boolean {
56
+ const actions = reach.actions
57
+ for (let index = 0; index < actions.length; index++) {
58
+ if (!includes(model.actions.read, actions[index])) {
59
+ return false
60
+ }
61
+ }
62
+ return actions.length > 0
31
63
  }
32
64
 
65
+ const NONE_HELD: NameSet = nameSet([])
66
+
33
67
  /**
34
- * Puts a file reference in each file column of `rows`, read with `action` in `session`: one statement loads every
35
- * file's metadata. Without a binding (a store's own runner) the columns keep their ids.
68
+ * Puts a file reference in each file column of `rows`, read under `reach` in `session`: one statement loads every
69
+ * file's metadata. Without a binding (a store's own runner) the columns keep their ids. `held` (a queue claim's) adds
70
+ * the actions the site holds over the whole application: a reference is readable when one of them reads the table.
36
71
  */
37
- export async function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], action: string): Promise<R[]> {
72
+ export async function answerFiles<R>(
73
+ model: TableModel,
74
+ binding: FileBinding | undefined,
75
+ session: Session,
76
+ rows: R[],
77
+ reach: ReadReach,
78
+ held: NameSet = NONE_HELD,
79
+ ): Promise<R[]> {
38
80
  const columns = ownKeys(model.files)
39
81
  if (binding === undefined || columns.length === 0 || rows.length === 0) {
40
82
  return rows
@@ -62,7 +104,7 @@ export async function answerFiles<R>(model: TableModel, binding: FileBinding | u
62
104
  if (meta === undefined) {
63
105
  throw new QueryRefusedError('unexpected_row', `${model.name}.${column} references a file that is not stored`)
64
106
  }
65
- defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action)))
107
+ defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, reach, held)))
66
108
  }
67
109
  }
68
110
  return rows
@@ -125,7 +167,10 @@ export async function storedRowScope(model: TableModel, session: Session, key: s
125
167
  if (!isPlainIdentifier(model.name) || !isPlainIdentifier(column) || !isPlainIdentifier(key)) {
126
168
  throw new QueryRefusedError('invalid_name', "a file column's table is named by plain identifiers")
127
169
  }
128
- const [found] = await runFixedStatement(session, `select ${column}::text as scope from ${model.name} where ${key}::text = $1`, [keyValue])
170
+ const statement = session.dialect === 'sqlite'
171
+ ? `select cast(${column} as text) as scope from ${model.name} where cast(${key} as text) = ?1`
172
+ : `select ${column}::text as scope from ${model.name} where ${key}::text = $1`
173
+ const [found] = await runFixedStatement(session, statement, [keyValue])
129
174
  const value: unknown = typeof found === 'object' && found !== null ? ownDescriptor(found, 'scope')?.value : undefined
130
175
  if (typeof value !== 'string') {
131
176
  throw new NotFoundError(`${model.name} not found`)
@@ -8,6 +8,7 @@ import { BinaryOperationNode, type OperationNode, OperatorNode, ValueNode } from
8
8
  import { runFixedStatement, type Session, sessionOf } from './database'
9
9
  import { QueryRefusedError } from './errors'
10
10
  import type { GuardContext } from './guard'
11
+ import type { DialectTexts } from './job-leases'
11
12
  import { WEBHOOK_BINDINGS_TABLE, WEBHOOK_DELIVERIES_TABLE } from './migrations'
12
13
  import { acknowledgement, allOf, column, deleteNode, equals, insertNode, locateNode, scopedWhere, updateNode } from './nodes'
13
14
  import type { DataLayerRuntime } from './store'
@@ -72,16 +73,35 @@ export interface DeliveryClaim {
72
73
  const D = WEBHOOK_DELIVERIES_TABLE
73
74
 
74
75
  /** A new key, or one whose claim expired without completion; a completed one (no lease) is never taken. */
75
- const SQL_CLAIM = `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values ($1, $2, $3::bigint, $4::bigint)
76
+ const SQL_CLAIM: DialectTexts = {
77
+ postgres: `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values ($1, $2, $3::bigint, $4::bigint)
76
78
  on conflict (binding_id, delivery_id) do update set received_at = excluded.received_at, lease_until = excluded.lease_until
77
79
  where ${D}.lease_until is not null and ${D}.lease_until < excluded.received_at
78
- returning delivery_id`
80
+ returning delivery_id`,
81
+ sqlite: `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values (?1, ?2, ?3, ?4)
82
+ on conflict (binding_id, delivery_id) do update set received_at = excluded.received_at, lease_until = excluded.lease_until
83
+ where ${D}.lease_until is not null and ${D}.lease_until < excluded.received_at
84
+ returning delivery_id`,
85
+ }
79
86
 
80
- const SQL_COMPLETE = `update ${D} set lease_until = null
87
+ const SQL_COMPLETE: DialectTexts = {
88
+ postgres: `update ${D} set lease_until = null
81
89
  where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint
82
- returning delivery_id`
90
+ returning delivery_id`,
91
+ sqlite: `update ${D} set lease_until = null
92
+ where binding_id = ?1 and delivery_id = ?2 and lease_until = ?3
93
+ returning delivery_id`,
94
+ }
83
95
 
84
- const SQL_RELEASE = `delete from ${D} where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint returning delivery_id`
96
+ const SQL_RELEASE: DialectTexts = {
97
+ postgres: `delete from ${D} where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint returning delivery_id`,
98
+ sqlite: `delete from ${D} where binding_id = ?1 and delivery_id = ?2 and lease_until = ?3 returning delivery_id`,
99
+ }
100
+
101
+ /** Runs the text of `session`'s dialect. */
102
+ function run(session: Session, texts: DialectTexts, parameters: readonly (string | number)[]): Promise<readonly unknown[]> {
103
+ return runFixedStatement(session, texts[session.dialect], parameters)
104
+ }
85
105
 
86
106
  const BINDING_COLUMNS = ['id', 'webhook', 'scope_type', 'scope_value', 'account', 'secret']
87
107
 
@@ -186,17 +206,17 @@ export function webhookTables(runtime: () => DataLayerRuntime): WebhookTables {
186
206
  )
187
207
  const leaseUntil = now + leaseMs
188
208
  // The primary key decides between concurrent copies of one delivery: exactly one inserts or takes over.
189
- const claimed = await runFixedStatement(session(), SQL_CLAIM, [bindingId, deliveryKey, now, leaseUntil])
209
+ const claimed = await run(session(), SQL_CLAIM, [bindingId, deliveryKey, now, leaseUntil])
190
210
  return claimed.length === 0 ? null : Object.freeze({ bindingId, key: deliveryKey, leaseUntil })
191
211
  },
192
212
 
193
213
  async completeDelivery(claim: DeliveryClaim, using?: Session): Promise<boolean> {
194
- const completed = await runFixedStatement(using ?? session(), SQL_COMPLETE, [claim.bindingId, claim.key, claim.leaseUntil])
214
+ const completed = await run(using ?? session(), SQL_COMPLETE, [claim.bindingId, claim.key, claim.leaseUntil])
195
215
  return completed.length > 0
196
216
  },
197
217
 
198
218
  async releaseDelivery(claim: DeliveryClaim): Promise<void> {
199
- await runFixedStatement(session(), SQL_RELEASE, [claim.bindingId, claim.key, claim.leaseUntil])
219
+ await run(session(), SQL_RELEASE, [claim.bindingId, claim.key, claim.leaseUntil])
200
220
  },
201
221
  })
202
222
  }
package/src/framework.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // hands the framework the locator its access check uses. Browser- and Worker-safe: the Worker adapter imports `boot`.
4
4
 
5
5
  import type { DataAccess } from './orm'
6
- import { frameworkSideOf, type FrameworkTables, type Locator } from './registry'
6
+ import { frameworkSideOf, type FrameworkTables, type Locator, type ProvisionalBinding } from './registry'
7
7
  import type { DataLayerRuntime } from './store'
8
8
 
9
9
  export type { Admissions } from './admissions'
@@ -21,9 +21,11 @@ export {
21
21
  export type { FileBinding } from './file-columns'
22
22
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
23
23
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
24
- export type { JobLeases, JobLeaseState, JobOutcome, OverdueClaim } from './job-leases'
24
+ export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
25
+ export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
25
26
  export type { DataAccess, DataHandles, DataSite } from './orm'
26
- export type { FrameworkTables, Locator } from './registry'
27
+ export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
28
+ export type { RequestReceipt, RequestReceipts } from './request-receipts'
27
29
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
28
30
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files'
29
31
 
@@ -37,6 +39,14 @@ export function isScopedDatabase(value: unknown): boolean {
37
39
  * reach. Throws for any other value and for a layer that is already connected.
38
40
  */
39
41
  export function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): Locator {
42
+ return bindScopedDatabaseProvisionally(value, runtime).locate
43
+ }
44
+
45
+ /**
46
+ * Connects the layer like `bindScopedDatabase`, and answers with its locator the `release` that disconnects it again:
47
+ * a boot that fails releases the layer, so a later boot of the same application binds it. Throws as that does.
48
+ */
49
+ export function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding {
40
50
  const side = frameworkSideOf(value)
41
51
  if (side === undefined) {
42
52
  throw new TypeError('not a data layer scoped(tables) created')
@@ -45,8 +55,8 @@ export function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): L
45
55
  }
46
56
 
47
57
  /**
48
- * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and the
49
- * admission counters. Each operation needs the layer bound first. Throws for any other value.
58
+ * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
59
+ * the admission counters. Each operation needs the layer bound first. Throws for any other value.
50
60
  */
51
61
  export function frameworkTablesOf(value: unknown): FrameworkTables {
52
62
  const side = frameworkSideOf(value)