@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.21

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 (80) hide show
  1. package/package.json +35 -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 +229 -40
  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 +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -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 +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
@@ -9,9 +9,10 @@ import { freeze } from './builtins'
9
9
  import { type FixedParameter, runFixedStatement, type Session, sessionOf } from './database'
10
10
  import { DatabaseError, QueryRefusedError } from './errors'
11
11
  import { isPlainIdentifier } from './identifier'
12
- import { fencedTransaction } from './job-leases'
12
+ import { type DialectTexts, fencedTransaction, SQLITE_NOW, sqliteNowPlus, sqliteTimestamp } from './job-leases'
13
13
  import { FILE_DELETIONS_TABLE, FILES_TABLE } from './migrations'
14
14
  import type { DataLayerRuntime } from './store'
15
+ import { storedTimestamp } from './temporal'
15
16
 
16
17
  const F = FILES_TABLE
17
18
  const D = FILE_DELETIONS_TABLE
@@ -96,10 +97,14 @@ export interface StoredFiles {
96
97
  promote(id: string, sha256: string, version: string): Promise<boolean>
97
98
  deferScan(id: string, attempts: number, after: Date): Promise<boolean>
98
99
  reject(id: string): Promise<boolean>
99
- // The sweep.
100
- /** Objects whose rows a sweep deleted and whose own deletion it did not finish. */
101
- unfinishedDeletions(limit: number): Promise<readonly string[]>
100
+ // The sweep. A queued object key is a tombstone: its object outlives its row by the retention window.
101
+ /** At most `limit` queued object keys recorded at or before `cutoff` (equality is due), oldest first. */
102
+ dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]>
103
+ /** Takes a due key out of the queue before its object is deleted; `false` when a cancel or a requeue got there first. */
104
+ claimDeletion(objectKey: string, cutoff: Date): Promise<boolean>
102
105
  forgetDeletion(objectKey: string): Promise<void>
106
+ /** Takes `objectKeys` out of the queue, so their objects stay: a restore's rows reference them again. The number taken. */
107
+ cancelDeletions(objectKeys: readonly string[]): Promise<number>
103
108
  /** Clears the legacy marker of every migrated file that one of `columns` references: it is an ordinary file now. */
104
109
  adoptReferenced(columns: readonly FileColumnRef[]): Promise<number>
105
110
  /** At most `limit` files past the grace that no column of `columns` references (pending ones included), oldest first. */
@@ -112,55 +117,153 @@ export interface StoredFiles {
112
117
  }
113
118
 
114
119
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
115
- /** Postgres' code of a foreign key violation: the delete of a file some column still references. */
120
+ /** Postgres' code of a foreign key violation, which the SQLite engine maps its own to: the delete of a referenced file. */
116
121
  const FOREIGN_KEY_VIOLATION = '23503'
117
122
 
118
123
  const SERVED_COLUMNS = `id::text as id, kind, name, content_type, size, status, object_key, object_version`
124
+ const SQLITE_SERVED_COLUMNS = `id, kind, name, content_type, size, status, object_key, object_version`
125
+ const N = SQLITE_NOW
126
+ // A tombstone's instant in whole milliseconds, as SQLite stores it: the sweep's cutoff is a `Date`, and a key recorded
127
+ // in the cutoff's own millisecond is due (equality), not one microsecond past it.
128
+ const RECORDED_NOW = `date_trunc('milliseconds', now())`
129
+
130
+ const SQL_STAGE: DialectTexts = {
131
+ postgres: `insert into ${F} (id, kind, status, object_key, content_type, name, request, created_at)
132
+ values ($1::uuid, $2, 'pending', $3, $4, $5, $6, now())`,
133
+ sqlite: `insert into ${F} (id, kind, status, object_key, content_type, name, request, created_at)
134
+ values (?1, ?2, 'pending', ?3, ?4, ?5, ?6, ${N})`,
135
+ }
119
136
 
120
- const SQL_STAGE = `insert into ${F} (id, kind, status, object_key, content_type, name, request, created_at)
121
- values ($1::uuid, $2, 'pending', $3, $4, $5, $6, now())`
122
-
123
- const SQL_WRITTEN = `update ${F} set size = $2::bigint, sha256 = $3 where id = $1::uuid and status = 'pending' returning id`
137
+ const SQL_WRITTEN: DialectTexts = {
138
+ postgres: `update ${F} set size = $2::bigint, sha256 = $3 where id = $1::uuid and status = 'pending' returning id`,
139
+ sqlite: `update ${F} set size = cast(?2 as integer), sha256 = ?3 where id = ?1 and status = 'pending' returning id`,
140
+ }
124
141
 
125
142
  const SQL_ABANDON = `with gone as (delete from ${F} where id = $1::uuid and status = 'pending' and request = $2 returning object_key)
126
- insert into ${D} (object_key, recorded_at) select object_key, now() from gone on conflict (object_key) do nothing returning object_key`
143
+ insert into ${D} (object_key, recorded_at) select object_key, ${RECORDED_NOW} from gone on conflict (object_key) do nothing returning object_key`
127
144
 
128
- const SQL_FIND = `select ${SERVED_COLUMNS} from ${F} where id = $1::uuid`
145
+ // SQLite has no data-modifying CTE: the delete and the record of its object are two statements in one transaction.
146
+ const SQLITE_ABANDON = `delete from ${F} where id = ?1 and status = 'pending' and request = ?2 returning object_key`
147
+ const SQLITE_RECORD_ABANDONED =
148
+ `insert into ${D} (object_key, recorded_at) values (?1, ${N}) on conflict (object_key) do nothing returning object_key`
129
149
 
130
- const SQL_REQUARANTINE = `update ${F} set status = 'quarantined', object_version = null, scan_attempts = 0, scan_after = now()
131
- where id = $1::uuid and status = 'live' and object_version is not distinct from $2`
150
+ const SQL_FIND: DialectTexts = {
151
+ postgres: `select ${SERVED_COLUMNS} from ${F} where id = $1::uuid`,
152
+ sqlite: `select ${SQLITE_SERVED_COLUMNS} from ${F} where id = ?1`,
153
+ }
132
154
 
133
- const SQL_METADATA = `select id::text as id, kind, name, content_type, size, status from ${F}
134
- where id = any(string_to_array($1, ',')::uuid[])`
155
+ const SQL_REQUARANTINE: DialectTexts = {
156
+ postgres: `update ${F} set status = 'quarantined', object_version = null, scan_attempts = 0, scan_after = now()
157
+ where id = $1::uuid and status = 'live' and object_version is not distinct from $2`,
158
+ sqlite: `update ${F} set status = 'quarantined', object_version = null, scan_attempts = 0, scan_after = ${N}
159
+ where id = ?1 and status = 'live' and object_version is ?2`,
160
+ }
135
161
 
136
- const SQL_QUARANTINED = `select id::text as id, object_key, size, sha256, content_type, scan_attempts, coalesce(scan_after, created_at) as due_since
162
+ // The ids are one parameter: a comma-separated list on Postgres, a JSON array on SQLite.
163
+ const SQL_METADATA: DialectTexts = {
164
+ postgres: `select id::text as id, kind, name, content_type, size, status from ${F}
165
+ where id = any(string_to_array($1, ',')::uuid[])`,
166
+ sqlite: `select id, kind, name, content_type, size, status from ${F}
167
+ where id in (select value from json_each(?1))`,
168
+ }
169
+
170
+ const SQL_QUARANTINED: DialectTexts = {
171
+ postgres: `select id::text as id, object_key, size, sha256, content_type, scan_attempts, coalesce(scan_after, created_at) as due_since
137
172
  from ${F} where status = 'quarantined' and kind = any(string_to_array($1, ',')) and (scan_after is null or scan_after < $2::timestamptz)
138
- order by scan_after nulls first, created_at limit $3::int`
173
+ order by scan_after nulls first, created_at limit $3::int`,
174
+ sqlite: `select id, object_key, size, sha256, content_type, scan_attempts, coalesce(scan_after, created_at) as due_since
175
+ from ${F} where status = 'quarantined' and kind in (select value from json_each(?1)) and (scan_after is null or scan_after < ?2)
176
+ order by scan_after nulls first, created_at limit ?3`,
177
+ }
178
+
179
+ const SQL_PROMOTE: DialectTexts = {
180
+ postgres: `update ${F} set status = 'live', object_version = $3 where id = $1::uuid and status = 'quarantined' and sha256 = $2 returning id`,
181
+ sqlite: `update ${F} set status = 'live', object_version = ?3 where id = ?1 and status = 'quarantined' and sha256 = ?2 returning id`,
182
+ }
139
183
 
140
- const SQL_PROMOTE = `update ${F} set status = 'live', object_version = $3 where id = $1::uuid and status = 'quarantined' and sha256 = $2 returning id`
184
+ const SQL_DEFER: DialectTexts = {
185
+ postgres: `update ${F} set scan_attempts = $2::int, scan_after = $3::timestamptz
186
+ where id = $1::uuid and status = 'quarantined' and scan_attempts = $2::int - 1 returning id`,
187
+ sqlite: `update ${F} set scan_attempts = ?2, scan_after = ?3
188
+ where id = ?1 and status = 'quarantined' and scan_attempts = ?2 - 1 returning id`,
189
+ }
141
190
 
142
- const SQL_DEFER = `update ${F} set scan_attempts = $2::int, scan_after = $3::timestamptz
143
- where id = $1::uuid and status = 'quarantined' and scan_attempts = $2::int - 1 returning id`
191
+ const SQL_REJECT: DialectTexts = {
192
+ postgres: `update ${F} set status = 'rejected' where id = $1::uuid and status = 'quarantined' returning id`,
193
+ sqlite: `update ${F} set status = 'rejected' where id = ?1 and status = 'quarantined' returning id`,
194
+ }
144
195
 
145
- const SQL_REJECT = `update ${F} set status = 'rejected' where id = $1::uuid and status = 'quarantined' returning id`
196
+ const SQL_DUE: DialectTexts = {
197
+ postgres: `select object_key from ${D} where recorded_at <= $2::timestamptz order by recorded_at limit $1::int`,
198
+ sqlite: `select object_key from ${D} where recorded_at <= ?2 order by recorded_at limit ?1`,
199
+ }
146
200
 
147
- const SQL_UNFINISHED = `select object_key from ${D} order by recorded_at limit $1::int`
201
+ const SQL_CLAIM_DELETION: DialectTexts = {
202
+ postgres: `delete from ${D} where object_key = $1 and recorded_at <= $2::timestamptz returning object_key`,
203
+ sqlite: `delete from ${D} where object_key = ?1 and recorded_at <= ?2 returning object_key`,
204
+ }
148
205
 
149
- const SQL_FORGET = `delete from ${D} where object_key = $1`
206
+ const SQL_FORGET: DialectTexts = {
207
+ postgres: `delete from ${D} where object_key = $1`,
208
+ sqlite: `delete from ${D} where object_key = ?1`,
209
+ }
210
+
211
+ // The keys are one parameter, a JSON array.
212
+ const SQL_CANCEL: DialectTexts = {
213
+ postgres: `delete from ${D} where object_key in (select jsonb_array_elements_text($1::jsonb)) returning object_key`,
214
+ sqlite: `delete from ${D} where object_key in (select value from json_each(?1)) returning object_key`,
215
+ }
150
216
 
151
217
  const SQL_REMOVE = `with gone as (
152
218
  delete from ${F} where id = $1::uuid and legacy is null and created_at < now() - $2::bigint * interval '1 millisecond' returning object_key
153
219
  )
154
- insert into ${D} (object_key, recorded_at) select object_key, now() from gone returning object_key`
220
+ insert into ${D} (object_key, recorded_at) select object_key, ${RECORDED_NOW} from gone
221
+ on conflict (object_key) do update set recorded_at = excluded.recorded_at returning object_key`
222
+
223
+ const SQLITE_REMOVE = `delete from ${F} where id = ?1 and legacy is null and created_at < ${sqliteNowPlus('-?2')} returning object_key`
224
+ // A key queued again restarts its window: the removal is fresh.
225
+ const SQLITE_RECORD_REMOVED =
226
+ `insert into ${D} (object_key, recorded_at) values (?1, ${N}) on conflict (object_key) do update set recorded_at = excluded.recorded_at returning object_key`
155
227
 
156
228
  /** The lock a reference write takes: a file being deleted cannot gain a reference, and a referenced one is not deleted. */
157
- const SQL_LOCK = `select kind, status, request, scope, created_at > now() - $2::bigint * interval '1 millisecond' as fresh
158
- from ${F} where id = $1::uuid for share`
229
+ const SQL_LOCK: DialectTexts = {
230
+ postgres: `select kind, status, request, scope, created_at > now() - $2::bigint * interval '1 millisecond' as fresh
231
+ from ${F} where id = $1::uuid for share`,
232
+ // No lock: while the reference write's transaction is open, the Durable Object runs no sweep.
233
+ sqlite: `select kind, status, request, scope, created_at > ${sqliteNowPlus('-?2')} as fresh
234
+ from ${F} where id = ?1`,
235
+ }
159
236
 
160
- const SQL_CLAIM = `update ${F} set status = $2 where id = $1::uuid and status = 'pending' returning id`
237
+ const SQL_CLAIM: DialectTexts = {
238
+ postgres: `update ${F} set status = $2 where id = $1::uuid and status = 'pending' returning id`,
239
+ sqlite: `update ${F} set status = ?2 where id = ?1 and status = 'pending' returning id`,
240
+ }
161
241
 
162
242
  /** The first dimensional reference stamps the scope; one from another top-level scope matches nothing. */
163
- const SQL_STAMP = `update ${F} set scope = $2 where id = $1::uuid and (scope is null or scope = $2) returning id`
243
+ const SQL_STAMP: DialectTexts = {
244
+ postgres: `update ${F} set scope = $2 where id = $1::uuid and (scope is null or scope = $2) returning id`,
245
+ sqlite: `update ${F} set scope = ?2 where id = ?1 and (scope is null or scope = ?2) returning id`,
246
+ }
247
+
248
+ /** Runs the text of `session`'s dialect. */
249
+ function run(session: Session, texts: DialectTexts, parameters: readonly FixedParameter[]): Promise<readonly unknown[]> {
250
+ return runFixedStatement(session, texts[session.dialect], parameters)
251
+ }
252
+
253
+ /**
254
+ * SQLite's form of a delete that records its object for deletion: the delete, then the record, in one transaction.
255
+ * The record's object key, or `null` when nothing was deleted or recorded.
256
+ */
257
+ function deleteAndRecord(session: Session, deletion: string, parameters: readonly FixedParameter[], recording: string): Promise<string | null> {
258
+ return session.transaction(async (transaction) => {
259
+ const [gone] = await runFixedStatement(transaction, deletion, parameters)
260
+ if (gone === undefined) {
261
+ return null
262
+ }
263
+ const [recorded] = await runFixedStatement(transaction, recording, [text(record(gone), 'object_key')])
264
+ return recorded === undefined ? null : text(record(recorded), 'object_key')
265
+ })
266
+ }
164
267
 
165
268
  /** `exists (select 1 from <table> where <column> = f.id)`, one per column, over the policies' validated identifiers. */
166
269
  function referencedBy(columns: readonly FileColumnRef[]): string {
@@ -227,8 +330,9 @@ function status(row: Readonly<Record<string, unknown>>): StoredFileStatus {
227
330
  return found
228
331
  }
229
332
 
230
- function date(row: Readonly<Record<string, unknown>>, column: string): Date {
231
- const value = row[column]
333
+ /** A timestamp column: a `Date` from Postgres, a stored ISO text from SQLite. */
334
+ function date(session: Session, row: Readonly<Record<string, unknown>>, column: string): Date {
335
+ const value = session.dialect === 'sqlite' ? sqliteTimestamp(row[column], `${F}.${column}`) : row[column]
232
336
  if (!(value instanceof Date)) {
233
337
  throw new QueryRefusedError('unexpected_row', `${F}.${column} came back as ${typeof value}`)
234
338
  }
@@ -248,7 +352,7 @@ function metaOf(row: Readonly<Record<string, unknown>>): StoredFileMeta {
248
352
 
249
353
  /** Locks file `id` `for share` in `session`, the transaction that writes a reference to it; `null` when it is gone. */
250
354
  export async function lockStoredFile(session: Session, id: string, graceMs: number): Promise<LockedFile | null> {
251
- const [found] = await runFixedStatement(session, SQL_LOCK, [uuid(id), positive(graceMs, 'a pending grace')])
355
+ const [found] = await run(session, SQL_LOCK, [uuid(id), positive(graceMs, 'a pending grace')])
252
356
  if (found === undefined) {
253
357
  return null
254
358
  }
@@ -258,13 +362,14 @@ export async function lockStoredFile(session: Session, id: string, graceMs: numb
258
362
  status: status(row),
259
363
  request: nullableText(row, 'request'),
260
364
  scope: nullableText(row, 'scope'),
261
- fresh: row['fresh'] === true,
365
+ // SQLite answers a comparison as 1 or 0.
366
+ fresh: row['fresh'] === (session.dialect === 'sqlite' ? 1 : true),
262
367
  })
263
368
  }
264
369
 
265
370
  /** Ends the pending state of a file the reference write locked: `quarantined` for a scanning kind, else `live`. */
266
371
  export async function claimStoredFile(session: Session, id: string, ended: 'quarantined' | 'live'): Promise<void> {
267
- const rows = await runFixedStatement(session, SQL_CLAIM, [uuid(id), ended])
372
+ const rows = await run(session, SQL_CLAIM, [uuid(id), ended])
268
373
  if (rows.length !== 1) {
269
374
  throw new QueryRefusedError('unexpected_row', 'a pending file changed under its lock')
270
375
  }
@@ -272,7 +377,7 @@ export async function claimStoredFile(session: Session, id: string, ended: 'quar
272
377
 
273
378
  /** Sets the scope of a file's first dimensional reference; `false` when it already holds another. */
274
379
  export async function stampStoredFile(session: Session, id: string, scope: string): Promise<boolean> {
275
- return (await runFixedStatement(session, SQL_STAMP, [uuid(id), scope])).length === 1
380
+ return (await run(session, SQL_STAMP, [uuid(id), scope])).length === 1
276
381
  }
277
382
 
278
383
  /** Each file's metadata, by id, in `using`: one statement for every file column of a read. */
@@ -281,7 +386,8 @@ export async function storedFilesMetadata(using: Session, ids: readonly string[]
281
386
  if (unique.length === 0) {
282
387
  return new Map()
283
388
  }
284
- const rows = await runFixedStatement(using, SQL_METADATA, [unique.map(uuid).join(',')])
389
+ const checked = unique.map(uuid)
390
+ const rows = await run(using, SQL_METADATA, [using.dialect === 'sqlite' ? JSON.stringify(checked) : checked.join(',')])
285
391
  return new Map(rows.map((found) => {
286
392
  const meta = metaOf(record(found))
287
393
  return [meta.id, meta] as const
@@ -290,32 +396,36 @@ export async function storedFilesMetadata(using: Session, ids: readonly string[]
290
396
 
291
397
  export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
292
398
  const session = () => sessionOf(runtime())
293
- async function fenced(statement: string, parameters: readonly FixedParameter[]): Promise<boolean> {
399
+ async function fenced(statement: DialectTexts, parameters: readonly FixedParameter[]): Promise<boolean> {
294
400
  const current = runtime()
295
401
  const fence = current.capabilities.fence()
296
402
  if (fence === null) {
297
403
  throw new QueryRefusedError('file_scan', "a scan verdict is written only inside the scan job's lease")
298
404
  }
299
- const rows = await fencedTransaction(sessionOf(current), fence, (transaction) => runFixedStatement(transaction, statement, parameters))
405
+ const rows = await fencedTransaction(sessionOf(current), fence, (transaction) => run(transaction, statement, parameters))
300
406
  return rows.length > 0
301
407
  }
302
408
  return freeze({
303
409
  async stage(file: StagedFile): Promise<void> {
304
- await runFixedStatement(session(), SQL_STAGE, [uuid(file.id), file.kind, file.objectKey, file.contentType, file.name, file.request])
410
+ await run(session(), SQL_STAGE, [uuid(file.id), file.kind, file.objectKey, file.contentType, file.name, file.request])
305
411
  },
306
412
 
307
413
  async written(id: string, written: { readonly size: number; readonly sha256: string }): Promise<void> {
308
414
  if (!/^[0-9a-f]{64}$/.test(written.sha256) || !Number.isSafeInteger(written.size) || written.size < 0) {
309
415
  throw new QueryRefusedError('invalid_argument', 'a written file records its size and the hex SHA-256 of its bytes')
310
416
  }
311
- const rows = await runFixedStatement(session(), SQL_WRITTEN, [uuid(id), String(written.size), written.sha256])
417
+ const rows = await run(session(), SQL_WRITTEN, [uuid(id), String(written.size), written.sha256])
312
418
  if (rows.length !== 1) {
313
419
  throw new QueryRefusedError('unexpected_row', 'a staged file is no longer pending')
314
420
  }
315
421
  },
316
422
 
317
423
  async abandon(id: string, request: string): Promise<string | null> {
318
- const [found] = await runFixedStatement(session(), SQL_ABANDON, [uuid(id), request])
424
+ const current = session()
425
+ if (current.dialect === 'sqlite') {
426
+ return deleteAndRecord(current, SQLITE_ABANDON, [uuid(id), request], SQLITE_RECORD_ABANDONED)
427
+ }
428
+ const [found] = await runFixedStatement(current, SQL_ABANDON, [uuid(id), request])
319
429
  return found === undefined ? null : text(record(found), 'object_key')
320
430
  },
321
431
 
@@ -323,7 +433,7 @@ export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
323
433
  if (!UUID.test(id)) {
324
434
  return null
325
435
  }
326
- const [found] = await runFixedStatement(using ?? session(), SQL_FIND, [id])
436
+ const [found] = await run(using ?? session(), SQL_FIND, [id])
327
437
  if (found === undefined) {
328
438
  return null
329
439
  }
@@ -332,7 +442,7 @@ export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
332
442
  },
333
443
 
334
444
  async requarantine(id: string, version: string | null): Promise<void> {
335
- await runFixedStatement(session(), SQL_REQUARANTINE, [uuid(id), version])
445
+ await run(session(), SQL_REQUARANTINE, [uuid(id), version])
336
446
  },
337
447
 
338
448
  metadata: storedFilesMetadata,
@@ -341,7 +451,9 @@ export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
341
451
  if (kinds.length === 0) {
342
452
  return []
343
453
  }
344
- const rows = await runFixedStatement(session(), SQL_QUARANTINED, [kinds.join(','), now.toISOString(), positive(limit, 'a scan batch')])
454
+ const current = session()
455
+ const listed = current.dialect === 'sqlite' ? JSON.stringify(kinds) : kinds.join(',')
456
+ const rows = await run(current, SQL_QUARANTINED, [listed, now.toISOString(), positive(limit, 'a scan batch')])
345
457
  return rows.map((found) => {
346
458
  const row = record(found)
347
459
  return freeze({
@@ -351,7 +463,7 @@ export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
351
463
  sha256: text(row, 'sha256'),
352
464
  contentType: text(row, 'content_type'),
353
465
  scanAttempts: count(row, 'scan_attempts'),
354
- dueSince: date(row, 'due_since'),
466
+ dueSince: date(current, row, 'due_since'),
355
467
  })
356
468
  })
357
469
  },
@@ -362,34 +474,58 @@ export function storedFiles(runtime: () => DataLayerRuntime): StoredFiles {
362
474
 
363
475
  reject: (id: string) => fenced(SQL_REJECT, [uuid(id)]),
364
476
 
365
- async unfinishedDeletions(limit: number): Promise<readonly string[]> {
366
- const rows = await runFixedStatement(session(), SQL_UNFINISHED, [positive(limit, 'a sweep batch')])
477
+ async dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]> {
478
+ const rows = await run(session(), SQL_DUE, [positive(limit, 'a sweep batch'), storedTimestamp(cutoff, 'a deletion cutoff')])
367
479
  return rows.map((found) => text(record(found), 'object_key'))
368
480
  },
369
481
 
482
+ async claimDeletion(objectKey: string, cutoff: Date): Promise<boolean> {
483
+ return (await run(session(), SQL_CLAIM_DELETION, [objectKey, storedTimestamp(cutoff, 'a deletion cutoff')])).length === 1
484
+ },
485
+
370
486
  async forgetDeletion(objectKey: string): Promise<void> {
371
- await runFixedStatement(session(), SQL_FORGET, [objectKey])
487
+ await run(session(), SQL_FORGET, [objectKey])
488
+ },
489
+
490
+ async cancelDeletions(objectKeys: readonly string[]): Promise<number> {
491
+ if (objectKeys.length === 0) {
492
+ return 0
493
+ }
494
+ return (await run(session(), SQL_CANCEL, [JSON.stringify(objectKeys)])).length
372
495
  },
373
496
 
374
497
  async adoptReferenced(columns: readonly FileColumnRef[]): Promise<number> {
375
498
  if (columns.length === 0) {
376
499
  return 0
377
500
  }
378
- const statement = `update ${F} f set legacy = null where f.legacy is not null and (${referencedBy(columns)}) returning id`
379
- return (await runFixedStatement(session(), statement, [])).length
501
+ const current = session()
502
+ const statement = current.dialect === 'sqlite'
503
+ ? `update ${F} as f set legacy = null where f.legacy is not null and (${referencedBy(columns)}) returning id`
504
+ : `update ${F} f set legacy = null where f.legacy is not null and (${referencedBy(columns)}) returning id`
505
+ return (await runFixedStatement(current, statement, [])).length
380
506
  },
381
507
 
382
508
  async unreferenced(columns: readonly FileColumnRef[], limit: number, graceMs: number): Promise<readonly string[]> {
383
- const statement = `select f.id::text as id from ${F} f
509
+ const current = session()
510
+ const statement = current.dialect === 'sqlite'
511
+ ? `select f.id as id from ${F} f
512
+ where f.legacy is null and f.created_at < ${sqliteNowPlus('-?1')} and not (${referencedBy(columns)})
513
+ order by f.created_at limit ?2`
514
+ : `select f.id::text as id from ${F} f
384
515
  where f.legacy is null and f.created_at < now() - $1::bigint * interval '1 millisecond' and not (${referencedBy(columns)})
385
516
  order by f.created_at limit $2::int`
386
- const rows = await runFixedStatement(session(), statement, [positive(graceMs, 'a pending grace'), positive(limit, 'a sweep batch')])
517
+ const rows = await runFixedStatement(current, statement, [positive(graceMs, 'a pending grace'), positive(limit, 'a sweep batch')])
387
518
  return rows.map((found) => text(record(found), 'id'))
388
519
  },
389
520
 
390
521
  async remove(id: string, graceMs: number): Promise<string | null> {
391
522
  try {
392
- const [found] = await runFixedStatement(session(), SQL_REMOVE, [uuid(id), positive(graceMs, 'a pending grace')])
523
+ const current = session()
524
+ const parameters = [uuid(id), positive(graceMs, 'a pending grace')]
525
+ if (current.dialect === 'sqlite') {
526
+ return await deleteAndRecord(current, SQLITE_REMOVE, parameters, SQLITE_RECORD_REMOVED)
527
+ }
528
+ const [found] = await runFixedStatement(current, SQL_REMOVE, parameters)
393
529
  return found === undefined ? null : text(record(found), 'object_key')
394
530
  } catch (error) {
395
531
  if (error instanceof DatabaseError && error.sqlState === FOREIGN_KEY_VIOLATION) {
package/src/tables.ts CHANGED
@@ -1,11 +1,37 @@
1
1
  // @fabrika/db/tables — the table policies of `src/db/tables.ts` as data. Browser- and Worker-safe: no Bun API and no
2
2
  // driver, so `@fabrika/app/contract` and the static contract reader in `@fabrika/check` import it.
3
3
 
4
- import type { ColumnPolicyArtifact, TableActionArtifact, TablePolicyArtifact, TableScope } from '@fabrika/auth-core'
4
+ import type {
5
+ AccessArtifact,
6
+ ColumnPolicyArtifact,
7
+ ConditionArtifact,
8
+ ConfersArtifact,
9
+ MemberRevealsArtifact,
10
+ RevealsArtifact,
11
+ TableActionArtifact,
12
+ TablePolicyArtifact,
13
+ TableScope,
14
+ } from '@fabrika/auth-core'
15
+ import { type ApplicationRowsPlan, planApplicationRows } from './application-rows'
5
16
  import { freeze, namesOf, ownEntry, ownKeys, setOwn } from './builtins'
17
+ import { conditionArtifact, type ConditionModel } from './conditions'
6
18
  import { PolicyError } from './errors'
7
- import { modelOf, type ScopeModel, type TableModel, tableModels, type Tables } from './policy'
19
+ import {
20
+ type AccessModel,
21
+ accessTablesOf,
22
+ type MemberRevealModel,
23
+ modelOf,
24
+ READ_ANY,
25
+ type RelationSource,
26
+ type RevealModel,
27
+ type ScopeModel,
28
+ type TableModel,
29
+ tableModels,
30
+ type Tables,
31
+ } from './policy'
8
32
 
33
+ export { applicationRowRefusalText } from './application-rows'
34
+ export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-rows'
9
35
  export { PolicyError } from './errors'
10
36
  export type { FileReference } from './file-references'
11
37
  export type {
@@ -82,6 +108,7 @@ export {
82
108
  } from './policy'
83
109
  export type {
84
110
  ColumnTypes,
111
+ ColumnViews,
85
112
  DefineVocabularyPolicies,
86
113
  NormalizedPolicies,
87
114
  TableVocabulary,
@@ -94,8 +121,31 @@ export type {
94
121
  VocabularyDimensionScope,
95
122
  VocabularyPolicyMap,
96
123
  VocabularyTablePolicy,
124
+ VocabularyViewPolicy,
97
125
  } from './vocabulary-tables'
98
126
 
127
+ /**
128
+ * The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
129
+ * case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
130
+ * `@fabrika/check` reports the refusals from source; `@fabrika/db/testing` throws the first, both in the words of
131
+ * `applicationRowRefusalText`.
132
+ */
133
+ export function applicationRowsPlan<DB, P>(
134
+ tables: Tables<DB, P>,
135
+ rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>,
136
+ ): ApplicationRowsPlan {
137
+ return planApplicationRows(tableModels(tables), rows)
138
+ }
139
+
140
+ /**
141
+ * The tables whose rows hand out access, lowercased: a relation source or a path reveal, a member-revealing table, and
142
+ * the tables a principal path or a relation's condition reads. Only the data layer writes them; the migration classifier
143
+ * refuses database code that does.
144
+ */
145
+ export function accessTables<DB, P>(tables: Tables<DB, P>): readonly string[] {
146
+ return accessTablesOf(tableModels(tables))
147
+ }
148
+
99
149
  /** Every table's policy in the form the contract artifact carries, by table name. */
100
150
  export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>
101
151
 
@@ -125,7 +175,7 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
125
175
  return {
126
176
  scope: scopeOf(model.scope),
127
177
  actions: {
128
- read: actionArtifact(model.actions.read) ?? noReadAction(model.name),
178
+ read: model.actions.readAny ? READ_ANY : actionArtifact(model.actions.read) ?? noReadAction(model.name),
129
179
  insert: actionArtifact(model.actions.insert),
130
180
  update: actionArtifact(model.actions.update),
131
181
  delete: actionArtifact(model.actions.delete),
@@ -138,7 +188,118 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
138
188
  createdBy: model.createdBy ?? null,
139
189
  columns,
140
190
  ...(ownKeys(model.files).length === 0 ? {} : { files: { ...model.files } }),
191
+ ...(model.view ? { view: true } : {}),
192
+ ...(model.confers.length === 0 ? {} : { confers: confersArtifact(model.confers) }),
193
+ ...(ownKeys(model.when).length === 0 ? {} : { when: whenArtifact(model.when) }),
194
+ ...(ownKeys(model.relationWhen).length === 0 ? {} : { relationWhen: relationWhenArtifact(model.relationWhen) }),
195
+ ...(model.reveals.length === 0 ? {} : { reveals: revealsArtifact(model.reveals) }),
196
+ ...(model.readThrough.length === 0 ? {} : { readThrough: readThroughArtifact(model) }),
197
+ ...writeThroughArtifact(model),
198
+ ...(model.memberReveals.length === 0 ? {} : { memberReveals: memberRevealsArtifact(model.memberReveals) }),
199
+ ...(model.access.length === 0 ? {} : { access: accessArtifact(model.access) }),
200
+ }
201
+ }
202
+
203
+ function accessArtifact(access: readonly AccessModel[]): Record<string, AccessArtifact> {
204
+ const artifact: Record<string, AccessArtifact> = {}
205
+ for (let index = 0; index < access.length; index++) {
206
+ const entry = access[index]
207
+ if (entry !== undefined) {
208
+ setOwn(artifact, entry.relation, { view: entry.view, row: entry.row, principal: entry.principal ?? null, member: entry.member ?? null })
209
+ }
210
+ }
211
+ return artifact
212
+ }
213
+
214
+ function memberRevealsArtifact(reveals: readonly MemberRevealModel[]): Record<string, MemberRevealsArtifact> {
215
+ const artifact: Record<string, MemberRevealsArtifact> = {}
216
+ for (let index = 0; index < reveals.length; index++) {
217
+ const reveal = reveals[index]
218
+ if (reveal === undefined) continue
219
+ setOwn(artifact, reveal.source, {
220
+ to: reveal.dimension,
221
+ actions: [...reveal.actions],
222
+ ...(reveal.when === undefined ? {} : { when: conditionArtifact(reveal.when) }),
223
+ ...(reveal.assign === undefined ? {} : { assign: { self: reveal.assign.self } }),
224
+ })
225
+ }
226
+ return artifact
227
+ }
228
+
229
+ function readThroughArtifact(model: TableModel): Record<string, string> {
230
+ const artifact: Record<string, string> = {}
231
+ for (let index = 0; index < model.readThrough.length; index++) {
232
+ const path = model.readThrough[index]
233
+ if (path !== undefined) setOwn(artifact, path.dimension, path.via === undefined ? path.column : `${path.via.column}.${path.column}`)
234
+ }
235
+ return artifact
236
+ }
237
+
238
+ function writeThroughArtifact(model: TableModel): { readonly writeThrough: Record<string, string[]> } | undefined {
239
+ const artifact: Record<string, string[]> = {}
240
+ let declared = false
241
+ for (let index = 0; index < model.readThrough.length; index++) {
242
+ const path = model.readThrough[index]
243
+ if (path === undefined || path.writes.length === 0) continue
244
+ setOwn(artifact, path.dimension, [...path.writes])
245
+ declared = true
246
+ }
247
+ return declared ? { writeThrough: artifact } : undefined
248
+ }
249
+
250
+ function revealsArtifact(reveals: readonly RevealModel[]): Record<string, RevealsArtifact> {
251
+ const artifact: Record<string, RevealsArtifact> = {}
252
+ for (let index = 0; index < reveals.length; index++) {
253
+ const reveal = reveals[index]
254
+ if (reveal === undefined) continue
255
+ setOwn(artifact, reveal.relation, {
256
+ to: reveal.dimension,
257
+ actions: [...reveal.actions],
258
+ ...(reveal.when === undefined ? {} : { when: conditionArtifact(reveal.when) }),
259
+ ...(reveal.assign === undefined ? {} : { assign: { self: reveal.assign.self } }),
260
+ })
261
+ }
262
+ return artifact
263
+ }
264
+
265
+ function confersArtifact(sources: readonly RelationSource[]): Record<string, ConfersArtifact> {
266
+ const confers: Record<string, ConfersArtifact> = {}
267
+ for (let index = 0; index < sources.length; index++) {
268
+ const source = sources[index]
269
+ if (source === undefined) continue
270
+ setOwn(confers, source.relation, {
271
+ principal: source.principalPath === undefined ? source.principal : `${source.principal}.${source.principalPath.column}`,
272
+ node: source.node,
273
+ expires: source.expires ?? null,
274
+ ...(source.when === undefined ? {} : { when: conditionArtifact(source.when) }),
275
+ assign: source.assign === undefined ? null : { maxDays: source.assign.maxDays ?? null, self: source.assign.self },
276
+ })
277
+ }
278
+ return confers
279
+ }
280
+
281
+ function whenArtifact(when: Readonly<Record<string, ConditionModel>>): Record<string, ConditionArtifact> {
282
+ const artifact: Record<string, ConditionArtifact> = {}
283
+ const actions = ownKeys(when)
284
+ for (let index = 0; index < actions.length; index++) {
285
+ const action = actions[index] ?? ''
286
+ const condition = ownEntry(when, action)
287
+ if (condition !== undefined) setOwn(artifact, action, conditionArtifact(condition))
288
+ }
289
+ return artifact
290
+ }
291
+
292
+ function relationWhenArtifact(
293
+ relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>,
294
+ ): Record<string, Record<string, ConditionArtifact>> {
295
+ const artifact: Record<string, Record<string, ConditionArtifact>> = {}
296
+ const relations = ownKeys(relationWhen)
297
+ for (let index = 0; index < relations.length; index++) {
298
+ const relation = relations[index] ?? ''
299
+ const conditions = ownEntry(relationWhen, relation)
300
+ if (conditions !== undefined) setOwn(artifact, relation, whenArtifact(conditions))
141
301
  }
302
+ return artifact
142
303
  }
143
304
 
144
305
  /** One action as its text, so a single-action policy keeps the artifact and digest it had; several as a list; none as `null`. */