@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
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.3",
3
+ "version": "0.9.0-dev.30",
4
4
  "type": "module",
5
+ "sideEffects": [
6
+ "./src/testing.ts",
7
+ "./src/testing-sqlite.ts"
8
+ ],
5
9
  "repository": {
6
10
  "type": "git",
7
11
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -41,11 +45,41 @@
41
45
  "types": "./types/src/migrations.d.ts",
42
46
  "default": "./src/migrations.ts"
43
47
  },
48
+ "./migrations-sqlite": {
49
+ "bun": "./src/migrations-sqlite.ts",
50
+ "types": "./types/src/migrations-sqlite.d.ts",
51
+ "default": "./src/migrations-sqlite.ts"
52
+ },
44
53
  "./production": {
45
54
  "bun": "./src/production.ts",
46
55
  "types": "./types/src/production.d.ts",
47
56
  "default": "./src/production.ts"
48
57
  },
58
+ "./postgres": {
59
+ "bun": "./src/postgres.ts",
60
+ "types": "./types/src/postgres.d.ts",
61
+ "default": "./src/postgres.ts"
62
+ },
63
+ "./sqlite": {
64
+ "bun": "./src/sqlite.ts",
65
+ "types": "./types/src/sqlite.d.ts",
66
+ "default": "./src/sqlite.ts"
67
+ },
68
+ "./sqlite-migrate": {
69
+ "bun": "./src/sqlite-migrate.ts",
70
+ "types": "./types/src/sqlite-migrate.d.ts",
71
+ "default": "./src/sqlite-migrate.ts"
72
+ },
73
+ "./codegen-sqlite": {
74
+ "bun": "./src/codegen-sqlite.ts",
75
+ "types": "./types/src/codegen-sqlite.d.ts",
76
+ "default": "./src/codegen-sqlite.ts"
77
+ },
78
+ "./testing-sqlite": {
79
+ "bun": "./src/testing-sqlite.ts",
80
+ "types": "./types/src/testing-sqlite.d.ts",
81
+ "default": "./src/testing-sqlite.ts"
82
+ },
49
83
  "./codegen": {
50
84
  "bun": "./src/codegen.ts",
51
85
  "types": "./types/src/codegen.d.ts",
@@ -58,12 +92,13 @@
58
92
  }
59
93
  },
60
94
  "scripts": {
61
- "typecheck": "tsc --noEmit",
95
+ "typecheck": "tsrs --build tsconfig.test.json",
62
96
  "test": "bun test"
63
97
  },
64
98
  "dependencies": {
65
- "@fabrika/auth-core": "0.9.0-dev.3",
66
- "@fabrika/platform-node": "0.9.0-dev.3",
99
+ "@fabrika/auth-core": "0.9.0-dev.30",
100
+ "@fabrika/platform": "0.9.0-dev.30",
101
+ "@fabrika/platform-node": "0.9.0-dev.30",
67
102
  "kysely": "0.29.6",
68
103
  "kysely-postgres-js": "5.0.1",
69
104
  "zod": "^3.25.76"
package/src/admissions.ts CHANGED
@@ -2,12 +2,13 @@
2
2
  // (`@fabrika/db/migrations`): the per-minute buckets a procedure's admission takes from, shared by every instance of the
3
3
  // application, the digests of the challenge tokens it accepted, and its hourly byte budget (`bytesPerHour`). Each is
4
4
  // keyed by the endpoint id; the tables keep the names and the `form` column they were created with. Only `@fabrika/app`'s
5
- // dispatcher reaches them, through `frameworkTablesOf`. Each operation is one statement, so two instances never read a
6
- // counter and then write it, and each prunes a bounded batch of expired rows of its own table, so no table grows past
7
- // what the last minutes or hours hold.
5
+ // dispatcher reaches them, through `frameworkTablesOf`. Each operation is one statement (on SQLite, a prune and the
6
+ // write in one transaction), so two instances never read a counter and then write it, and each prunes a bounded batch
7
+ // of expired rows of its own table, so no table grows past what the last minutes or hours hold.
8
8
 
9
- import { runFixedStatement, sessionOf } from './database'
9
+ import { runFixedStatement, type Session, sessionOf } from './database'
10
10
  import { QueryRefusedError } from './errors'
11
+ import { SQLITE_NOW, sqliteNowPlus } from './job-leases'
11
12
  import { FORM_ADMISSIONS_TABLE, FORM_BYTES_TABLE, FORM_CHALLENGES_TABLE } from './migrations'
12
13
  import type { DataLayerRuntime } from './store'
13
14
 
@@ -49,6 +50,18 @@ insert into ${A} (form, bucket, window_start, count) values ($1, $2, date_trunc(
49
50
  on conflict (form, bucket, window_start) do update set count = ${A}.count + 1 where ${A}.count < $3::int
50
51
  returning count`
51
52
 
53
+ // SQLite has no data-modifying CTE, so the prune is a statement of its own before the take, in one transaction; no row
54
+ // is locked, as no other event reaches the Durable Object while it is open.
55
+ const SQLITE_MINUTE = `strftime('%Y-%m-%dT%H:%M:00.000Z', 'now')`
56
+
57
+ const SQLITE_PRUNE_ADMISSIONS = `delete from ${A} where (form, bucket, window_start) in (
58
+ select form, bucket, window_start from ${A} where window_start < ${SQLITE_MINUTE} limit ${PRUNE_BATCH}
59
+ )`
60
+
61
+ const SQLITE_TAKE = `insert into ${A} (form, bucket, window_start, count) values (?1, ?2, ${SQLITE_MINUTE}, 1)
62
+ on conflict (form, bucket, window_start) do update set count = ${A}.count + 1 where ${A}.count < ?3
63
+ returning count`
64
+
52
65
  const B = FORM_BYTES_TABLE
53
66
 
54
67
  const SQL_RESERVE_BYTES = `with pruned as (
@@ -61,9 +74,22 @@ insert into ${B} (form, window_start, bytes) select $1, date_trunc('hour', now()
61
74
  on conflict (form, window_start) do update set bytes = ${B}.bytes + excluded.bytes where ${B}.bytes + excluded.bytes <= $3::bigint
62
75
  returning bytes`
63
76
 
77
+ const SQLITE_HOUR = `strftime('%Y-%m-%dT%H:00:00.000Z', 'now')`
78
+
79
+ const SQLITE_PRUNE_BYTES = `delete from ${B} where (form, window_start) in (
80
+ select form, window_start from ${B} where window_start < ${SQLITE_HOUR} limit ${PRUNE_BATCH}
81
+ )`
82
+
83
+ const SQLITE_RESERVE_BYTES = `insert into ${B} (form, window_start, bytes) select ?1, ${SQLITE_HOUR}, ?2 where ?2 <= ?3
84
+ on conflict (form, window_start) do update set bytes = ${B}.bytes + excluded.bytes where ${B}.bytes + excluded.bytes <= ?3
85
+ returning bytes`
86
+
64
87
  const SQL_RELEASE_BYTES = `update ${B} set bytes = greatest(bytes - $2::bigint, 0)
65
88
  where form = $1 and window_start = date_trunc('hour', now()) returning bytes`
66
89
 
90
+ const SQLITE_RELEASE_BYTES = `update ${B} set bytes = max(bytes - ?2, 0)
91
+ where form = ?1 and window_start = ${SQLITE_HOUR} returning bytes`
92
+
67
93
  const SQL_RECORD_CHALLENGE = `with pruned as (
68
94
  delete from ${C} where (form, token_digest) in (
69
95
  select form, token_digest from ${C} where expires_at <= now() and (form, token_digest) <> ($1, $2)
@@ -74,6 +100,33 @@ insert into ${C} (form, token_digest, expires_at) values ($1, $2, now() + $3::bi
74
100
  on conflict (form, token_digest) do update set expires_at = excluded.expires_at where ${C}.expires_at <= now()
75
101
  returning form`
76
102
 
103
+ const SQLITE_PRUNE_CHALLENGES = `delete from ${C} where (form, token_digest) in (
104
+ select form, token_digest from ${C} where expires_at <= ${SQLITE_NOW} and (form, token_digest) <> (?1, ?2) limit ${PRUNE_BATCH}
105
+ )`
106
+
107
+ const SQLITE_RECORD_CHALLENGE = `insert into ${C} (form, token_digest, expires_at) values (?1, ?2, ${sqliteNowPlus('?3')})
108
+ on conflict (form, token_digest) do update set expires_at = excluded.expires_at where ${C}.expires_at <= ${SQLITE_NOW}
109
+ returning form`
110
+
111
+ /**
112
+ * The rows `statement` answers. On Postgres it is one statement, its prune a CTE; on SQLite the prune (with
113
+ * `pruneParameters`) runs first, in the same transaction.
114
+ */
115
+ async function pruneAndWrite(
116
+ session: Session,
117
+ statement: { readonly postgres: string; readonly sqlite: string; readonly prune: string },
118
+ parameters: readonly (string | number)[],
119
+ pruneParameters: readonly (string | number)[],
120
+ ): Promise<readonly unknown[]> {
121
+ if (session.dialect === 'postgres') {
122
+ return runFixedStatement(session, statement.postgres, parameters)
123
+ }
124
+ return session.transaction(async (transaction) => {
125
+ await runFixedStatement(transaction, statement.prune, pruneParameters)
126
+ return runFixedStatement(transaction, statement.sqlite, parameters)
127
+ })
128
+ }
129
+
77
130
  function positiveInteger(value: number, what: string): number {
78
131
  if (!Number.isSafeInteger(value) || value < 1) {
79
132
  throw new QueryRefusedError('invalid_argument', `${what} must be a whole number of at least 1`)
@@ -85,27 +138,40 @@ export function admissions(runtime: () => DataLayerRuntime): Admissions {
85
138
  const session = () => sessionOf(runtime())
86
139
  return Object.freeze({
87
140
  async take(endpoint: string, bucket: string, limit: number): Promise<boolean> {
88
- const rows = await runFixedStatement(session(), SQL_TAKE, [endpoint, bucket, positiveInteger(limit, 'a bucket limit')])
141
+ const rows = await pruneAndWrite(
142
+ session(),
143
+ { postgres: SQL_TAKE, sqlite: SQLITE_TAKE, prune: SQLITE_PRUNE_ADMISSIONS },
144
+ [endpoint, bucket, positiveInteger(limit, 'a bucket limit')],
145
+ [],
146
+ )
89
147
  return rows.length > 0
90
148
  },
91
149
 
92
150
  async recordChallenge(endpoint: string, tokenDigest: string, retainMs: number): Promise<boolean> {
93
- const rows = await runFixedStatement(session(), SQL_RECORD_CHALLENGE, [endpoint, tokenDigest, positiveInteger(retainMs, 'a retention')])
151
+ const rows = await pruneAndWrite(
152
+ session(),
153
+ { postgres: SQL_RECORD_CHALLENGE, sqlite: SQLITE_RECORD_CHALLENGE, prune: SQLITE_PRUNE_CHALLENGES },
154
+ [endpoint, tokenDigest, positiveInteger(retainMs, 'a retention')],
155
+ [endpoint, tokenDigest],
156
+ )
94
157
  return rows.length > 0
95
158
  },
96
159
 
97
160
  async reserveBytes(endpoint: string, bytes: number, limit: number): Promise<boolean> {
98
- const rows = await runFixedStatement(session(), SQL_RESERVE_BYTES, [
99
- endpoint,
100
- positiveInteger(bytes, 'a reservation'),
101
- positiveInteger(limit, 'a byte budget'),
102
- ])
161
+ const rows = await pruneAndWrite(
162
+ session(),
163
+ { postgres: SQL_RESERVE_BYTES, sqlite: SQLITE_RESERVE_BYTES, prune: SQLITE_PRUNE_BYTES },
164
+ [endpoint, positiveInteger(bytes, 'a reservation'), positiveInteger(limit, 'a byte budget')],
165
+ [],
166
+ )
103
167
  return rows.length > 0
104
168
  },
105
169
 
106
170
  async releaseBytes(endpoint: string, bytes: number): Promise<void> {
107
171
  if (bytes > 0) {
108
- await runFixedStatement(session(), SQL_RELEASE_BYTES, [endpoint, positiveInteger(bytes, 'a release')])
172
+ const current = session()
173
+ const statement = current.dialect === 'sqlite' ? SQLITE_RELEASE_BYTES : SQL_RELEASE_BYTES
174
+ await runFixedStatement(current, statement, [endpoint, positiveInteger(bytes, 'a release')])
109
175
  }
110
176
  },
111
177
  })
@@ -0,0 +1,108 @@
1
+ // The rule of the application rows an endpoint access case seeds (`appRows`): which tables, columns and values they
2
+ // may name, which foreign keys link one given row to another, and the order they are seeded in. `@fabrika/check`
3
+ // reports each refusal from source, and `@fabrika/db/testing` throws it before it seeds anything, both in the words of
4
+ // `applicationRowRefusalText`. Browser-safe.
5
+
6
+ import { inSet } from './builtins'
7
+ import { type ForeignKey, modelOf, type TableModels } from './policy'
8
+
9
+ /** Why the values of a set of application rows cannot be seeded as given. */
10
+ export type ApplicationRowRefusal =
11
+ /** `table` is no application table: `mode` is its scope mode, or `null` when no policy names it. */
12
+ | { readonly kind: 'table'; readonly table: string; readonly mode: string | null }
13
+ /** `column` is no column of `table`'s column list. */
14
+ | { readonly kind: 'column'; readonly table: string; readonly column: string }
15
+ /** `column` is the row's key, version or creator, which the seeding stamps. */
16
+ | { readonly kind: 'stamped'; readonly table: string; readonly column: string }
17
+ /** `column` is a file column, which the seeding fills with a live, scanned file. */
18
+ | { readonly kind: 'file'; readonly table: string; readonly column: string }
19
+ /** `column` is given an array or an object, where a column takes one value. */
20
+ | { readonly kind: 'value'; readonly table: string; readonly column: string; readonly given: 'array' | 'object' }
21
+ /** The values give `columns`, some but not all columns of the foreign key `key`. */
22
+ | { readonly kind: 'partial-key'; readonly table: string; readonly columns: readonly string[]; readonly key: ForeignKey }
23
+ /** The foreign keys that link `tables` form a cycle, so no order seeds each after the rows it links to. */
24
+ | { readonly kind: 'cycle'; readonly tables: readonly string[] }
25
+
26
+ export interface ApplicationRowsPlan {
27
+ /** The application tables, each after every given table it links to. */
28
+ readonly order: readonly string[]
29
+ /** Each application table's foreign keys to another given table that the values leave to the link. */
30
+ readonly links: Readonly<Record<string, readonly ForeignKey[]>>
31
+ /** Every refusal, by table then column; a cycle last. Empty when the rows can be seeded. */
32
+ readonly refusals: readonly ApplicationRowRefusal[]
33
+ }
34
+
35
+ /** The plan of seeding one row of each table `rows` names (table → column → value). */
36
+ export function planApplicationRows(models: TableModels, rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>): ApplicationRowsPlan {
37
+ const given = Object.keys(rows).sort()
38
+ const refusals: ApplicationRowRefusal[] = []
39
+ const links: Record<string, readonly ForeignKey[]> = {}
40
+ for (const table of given) {
41
+ const model = modelOf(models, table)
42
+ const scope = model?.scope
43
+ if (model === undefined || scope?.mode !== 'app') {
44
+ refusals.push({ kind: 'table', table, mode: scope?.mode ?? null })
45
+ continue
46
+ }
47
+ const values: Readonly<Record<string, unknown>> = (Object.hasOwn(rows, table) ? rows[table] : undefined) ?? {}
48
+ const named = Object.keys(values).sort()
49
+ const stamped = [scope.key, model.version, model.createdBy]
50
+ for (const column of named) {
51
+ const value = values[column]
52
+ if (!inSet(model.columns, column)) {
53
+ refusals.push({ kind: 'column', table, column })
54
+ } else if (stamped.includes(column)) {
55
+ refusals.push({ kind: 'stamped', table, column })
56
+ } else if (Object.hasOwn(model.files, column)) {
57
+ refusals.push({ kind: 'file', table, column })
58
+ } else if (value !== null && typeof value === 'object') {
59
+ refusals.push({ kind: 'value', table, column, given: Array.isArray(value) ? 'array' : 'object' })
60
+ }
61
+ }
62
+ // A foreign key is given whole or not at all: the seeding fills one it is not given (the seeded row of a given
63
+ // table, else null or a referenced row), never the rest of one.
64
+ for (const key of model.foreignKeys) {
65
+ const set = key.columns.filter((column) => named.includes(column))
66
+ if (set.length > 0 && set.length < key.columns.length) refusals.push({ kind: 'partial-key', table, columns: set, key })
67
+ }
68
+ links[table] = model.foreignKeys.filter((key) =>
69
+ key.table !== table && given.includes(key.table) && key.columns.every((column) => !named.includes(column))
70
+ )
71
+ }
72
+ // A table comes after every given table it links to; a cycle among them has no such order.
73
+ const order: string[] = []
74
+ const pending = given.filter((table) => Object.hasOwn(links, table))
75
+ while (pending.length > 0) {
76
+ const next = pending.findIndex((table) => (links[table] ?? []).every((key) => !pending.includes(key.table)))
77
+ if (next === -1) {
78
+ refusals.push({ kind: 'cycle', tables: [...pending] })
79
+ break
80
+ }
81
+ order.push(...pending.splice(next, 1))
82
+ }
83
+ return { order, links, refusals }
84
+ }
85
+
86
+ /** A refusal in the words both the checker and the test kit use, so the two never describe one rule differently. */
87
+ export function applicationRowRefusalText(refusal: ApplicationRowRefusal): string {
88
+ switch (refusal.kind) {
89
+ case 'table':
90
+ return `${refusal.table} is ${
91
+ refusal.mode === null ? 'no table of src/db/tables.ts' : `a ${refusal.mode} table`
92
+ }, and an application row is seeded only in an application table (scope: { app })`
93
+ case 'column':
94
+ return `${refusal.table}.${refusal.column} is no column of ${refusal.table}`
95
+ case 'stamped':
96
+ return `${refusal.table}.${refusal.column} is the row's key, version or creator, which the seeding stamps`
97
+ case 'file':
98
+ return `${refusal.table}.${refusal.column} is a file column, which the seeding fills with a live, scanned file`
99
+ case 'value':
100
+ return `${refusal.table}.${refusal.column} is given ${refusal.given === 'array' ? 'an array' : 'an object'}, and a seeded column takes one value`
101
+ case 'partial-key':
102
+ return `${refusal.table}.${refusal.columns.join(', ')} is part of the foreign key to ${refusal.key.table} (${
103
+ refusal.key.columns.join(', ')
104
+ }), which is given whole or not at all`
105
+ case 'cycle':
106
+ return `the foreign keys of ${refusal.tables.join(', ')} form a cycle, so the seeding cannot seed each row after the row it refers to`
107
+ }
108
+ }