@fabrika/db 0.9.0-dev.1 → 0.9.0-dev.11
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/package.json +44 -12
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/capability.ts +5 -0
- package/src/codegen-sqlite.ts +191 -0
- package/src/codegen.ts +170 -28
- package/src/database.ts +227 -61
- package/src/description.ts +34 -8
- package/src/errors.ts +6 -4
- package/src/file-columns.ts +36 -9
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +8 -0
- package/src/index.ts +10 -1
- package/src/job-leases.ts +210 -54
- package/src/job-wakes.ts +450 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +163 -0
- package/src/migrations.ts +25 -0
- package/src/nodes.ts +64 -9
- package/src/orm-types.ts +5 -5
- package/src/orm.ts +94 -37
- package/src/policy.ts +17 -2
- package/src/postgres.ts +26 -0
- package/src/registry.ts +11 -2
- package/src/sql.ts +230 -477
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +224 -0
- package/src/store.ts +385 -103
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +16 -0
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +999 -0
- package/src/testing-sqlite.ts +576 -0
- package/src/testing.ts +261 -482
- package/types/src/admissions.d.ts +21 -0
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/builtins.d.ts +42 -0
- package/types/src/capability.d.ts +119 -0
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +113 -0
- package/types/src/database.d.ts +185 -0
- package/types/src/description.d.ts +124 -0
- package/types/src/errors.d.ts +98 -0
- package/types/src/file-columns.d.ts +39 -0
- package/types/src/file-references.d.ts +27 -0
- package/types/src/framework-tables.d.ts +59 -0
- package/types/src/framework.d.ts +38 -0
- package/types/src/guard.d.ts +23 -0
- package/types/src/identifier.d.ts +4 -0
- package/types/src/index.d.ts +11 -0
- package/types/src/job-leases.d.ts +112 -0
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/links.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +26 -0
- package/types/src/nodes.d.ts +73 -0
- package/types/src/orm-types.d.ts +638 -0
- package/types/src/orm.d.ts +82 -0
- package/types/src/policy.d.ts +358 -0
- package/types/src/postgres.d.ts +12 -0
- package/types/src/production.d.ts +5 -0
- package/types/src/registry.d.ts +43 -0
- package/types/src/sql.d.ts +67 -0
- package/types/src/sqlite-bun.d.ts +21 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +351 -0
- package/types/src/stored-files.d.ts +102 -0
- package/types/src/tables.d.ts +21 -0
- package/types/src/temporal.d.ts +36 -0
- package/types/src/testing-shared.d.ts +269 -0
- package/types/src/testing-sqlite.d.ts +22 -0
- package/types/src/testing.d.ts +35 -0
- package/types/src/vocabulary-tables.d.ts +225 -0
package/src/stored-files.ts
CHANGED
|
@@ -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
|
-
/**
|
|
101
|
-
|
|
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
|
|
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
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
|
131
|
-
where id = $1::uuid
|
|
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
|
|
134
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
143
|
-
where id = $1::uuid and status = 'quarantined'
|
|
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
|
|
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
|
|
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 =
|
|
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,
|
|
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 =
|
|
158
|
-
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
231
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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:
|
|
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) =>
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
366
|
-
const rows = await
|
|
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
|
|
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
|
|
379
|
-
|
|
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
|
|
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(
|
|
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
|
|
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
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
// driver, so `@fabrika/app/contract` and the static contract reader in `@fabrika/check` import it.
|
|
3
3
|
|
|
4
4
|
import type { ColumnPolicyArtifact, TableActionArtifact, TablePolicyArtifact, TableScope } from '@fabrika/auth-core'
|
|
5
|
+
import { type ApplicationRowsPlan, planApplicationRows } from './application-rows'
|
|
5
6
|
import { freeze, namesOf, ownEntry, ownKeys, setOwn } from './builtins'
|
|
6
7
|
import { PolicyError } from './errors'
|
|
7
8
|
import { modelOf, type ScopeModel, type TableModel, tableModels, type Tables } from './policy'
|
|
8
9
|
|
|
10
|
+
export { applicationRowRefusalText } from './application-rows'
|
|
11
|
+
export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-rows'
|
|
9
12
|
export { PolicyError } from './errors'
|
|
10
13
|
export type { FileReference } from './file-references'
|
|
11
14
|
export type {
|
|
@@ -96,6 +99,19 @@ export type {
|
|
|
96
99
|
VocabularyTablePolicy,
|
|
97
100
|
} from './vocabulary-tables'
|
|
98
101
|
|
|
102
|
+
/**
|
|
103
|
+
* The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
|
|
104
|
+
* case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
|
|
105
|
+
* `@fabrika/check` reports the refusals from source; `@fabrika/db/testing` throws the first, both in the words of
|
|
106
|
+
* `applicationRowRefusalText`.
|
|
107
|
+
*/
|
|
108
|
+
export function applicationRowsPlan<DB, P>(
|
|
109
|
+
tables: Tables<DB, P>,
|
|
110
|
+
rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>,
|
|
111
|
+
): ApplicationRowsPlan {
|
|
112
|
+
return planApplicationRows(tableModels(tables), rows)
|
|
113
|
+
}
|
|
114
|
+
|
|
99
115
|
/** Every table's policy in the form the contract artifact carries, by table name. */
|
|
100
116
|
export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>
|
|
101
117
|
|
package/src/temporal.ts
CHANGED
|
@@ -3,12 +3,16 @@
|
|
|
3
3
|
// the database's own text (`cast(<column> as text)`, `nodes.ts`), never through the `Date` `Bun.SQL` decodes: outside
|
|
4
4
|
// 0001–9999 that one drifts by the process's offset and can land on a neighbouring valid day. Only an aggregate's
|
|
5
5
|
// `min`/`max` and a store's joined child column still arrive as a `Date`. The generated column list names the `date`
|
|
6
|
-
// columns (`TableColumns.dates`); every read of a table's rows passes through `answerDays
|
|
6
|
+
// columns (`TableColumns.dates`); every read of a table's rows passes through `answerRows` (`answerDays` on Postgres). A write's text for a day or a
|
|
7
7
|
// timestamp is checked here before anything is sent: Postgres would also take `now`, `today` or `10/12/2026`, and read
|
|
8
|
-
// a timestamp without an offset in the session's time zone.
|
|
8
|
+
// a timestamp without an offset in the session's time zone. On SQLite (ADR-0065) a timestamp is stored as UTC ISO text
|
|
9
|
+
// and a boolean as 0 or 1: `storedTimestamp` is what a write binds and `answerRows` turns both back into what Postgres's
|
|
10
|
+
// driver answers.
|
|
9
11
|
|
|
10
12
|
import { defineValue, inSet, type NameSet, ownDescriptor, ownKeys } from './builtins'
|
|
13
|
+
import type { SqlDialect } from './database'
|
|
11
14
|
import { QueryRefusedError } from './errors'
|
|
15
|
+
import { sqliteJson } from './json'
|
|
12
16
|
|
|
13
17
|
/** The text Postgres prints for a day in 0001–9999 under its default `DateStyle` (ISO). */
|
|
14
18
|
const DAY_TEXT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/
|
|
@@ -61,7 +65,7 @@ export function answerDays<R>(table: string, days: NameSet, rows: R[]): R[] {
|
|
|
61
65
|
}
|
|
62
66
|
|
|
63
67
|
/** An instant in strict ISO 8601: a day, `T`, the time to the minute or finer, and `Z` or an offset. */
|
|
64
|
-
const TIMESTAMP_TEXT = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.[0-9]{1,6})?)?(?:Z|[+-]([0-9]{2}):([0-9]{2}))$/
|
|
68
|
+
const TIMESTAMP_TEXT = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.([0-9]{1,6}))?)?(?:Z|([+-])([0-9]{2}):([0-9]{2}))$/
|
|
65
69
|
|
|
66
70
|
/** Whether `year-month-day` is a day of the calendar: no 30 February, no month 13. */
|
|
67
71
|
function isCalendarDay(year: number, month: number, day: number): boolean {
|
|
@@ -78,14 +82,123 @@ export function dayInput(value: string, where: string): string {
|
|
|
78
82
|
return value
|
|
79
83
|
}
|
|
80
84
|
|
|
81
|
-
/**
|
|
82
|
-
|
|
85
|
+
/** The instant of strict ISO 8601 text, in milliseconds since the epoch (digits past the millisecond dropped), or `undefined`. */
|
|
86
|
+
function instantOf(value: string): number | undefined {
|
|
83
87
|
const match = TIMESTAMP_TEXT.exec(value)
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
88
|
+
if (match === null) {
|
|
89
|
+
return undefined
|
|
90
|
+
}
|
|
91
|
+
const [, year, month, day, hour, minute, second = '0', fraction = '', sign = '+', offsetHour = '0', offsetMinute = '0'] = match
|
|
92
|
+
const valid = isCalendarDay(Number(year), Number(month), Number(day)) && Number(hour) < 24 && Number(minute) < 60 && Number(second) < 60
|
|
93
|
+
&& Number(offsetHour) < 16 && Number(offsetMinute) < 60
|
|
87
94
|
if (!valid) {
|
|
88
|
-
|
|
95
|
+
return undefined
|
|
96
|
+
}
|
|
97
|
+
// setUTCFullYear, unlike Date.UTC, keeps the years 0001–0099.
|
|
98
|
+
const date = new Date(0)
|
|
99
|
+
date.setUTCFullYear(Number(year), Number(month) - 1, Number(day))
|
|
100
|
+
date.setUTCHours(Number(hour), Number(minute), Number(second), Number(fraction.padEnd(3, '0').slice(0, 3)))
|
|
101
|
+
const offset = (Number(offsetHour) * 60 + Number(offsetMinute)) * 60_000
|
|
102
|
+
return date.getTime() - (sign === '-' ? -offset : offset)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function timestampRefused(where: string): QueryRefusedError {
|
|
106
|
+
return new QueryRefusedError('invalid_value', `${where} takes a Date or ISO 8601 text with Z or an offset, such as 2026-10-12T08:30:00.000Z`)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A timestamp a write binds as text: strict ISO 8601 with `Z` or an offset, every field in range. */
|
|
110
|
+
export function timestampInput(value: string, where: string): string {
|
|
111
|
+
if (instantOf(value) === undefined) {
|
|
112
|
+
throw timestampRefused(where)
|
|
89
113
|
}
|
|
90
114
|
return value
|
|
91
115
|
}
|
|
116
|
+
|
|
117
|
+
/** A timestamp as SQLite stores it: UTC `Date#toISOString()` text, whose text order is time order. */
|
|
118
|
+
const STORED_TIMESTAMP = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* What a write or a comparison binds for a timestamp on SQLite: the instant of a `Date`, or of the text `timestampInput`
|
|
122
|
+
* admits, as stored text. Digits past the millisecond are dropped; an instant outside the years 0000–9999 UTC is
|
|
123
|
+
* refused, since its text would not sort.
|
|
124
|
+
*/
|
|
125
|
+
export function storedTimestamp(value: string | Date, where: string): string {
|
|
126
|
+
const time = typeof value === 'string' ? instantOf(value) : value.getTime()
|
|
127
|
+
if (time === undefined) {
|
|
128
|
+
throw timestampRefused(where)
|
|
129
|
+
}
|
|
130
|
+
const text = Number.isNaN(time) ? '' : new Date(time).toISOString()
|
|
131
|
+
if (!STORED_TIMESTAMP.test(text)) {
|
|
132
|
+
throw new QueryRefusedError(
|
|
133
|
+
'invalid_value',
|
|
134
|
+
`${where} holds an instant outside the years 0000-9999 UTC, which SQLite cannot store as sortable text`,
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
return text
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The columns of a read's rows the layer answers in a form of its own, by the name each arrives under. */
|
|
141
|
+
export interface RowColumns {
|
|
142
|
+
/** `date` columns: `YYYY-MM-DD` text. */
|
|
143
|
+
readonly days: NameSet
|
|
144
|
+
/** Timestamps: a `Date` (SQLite answers its stored text). */
|
|
145
|
+
readonly timestamps: NameSet
|
|
146
|
+
/** Booleans: `true` or `false` (SQLite answers 1 or 0). */
|
|
147
|
+
readonly booleans: NameSet
|
|
148
|
+
/** JSON columns: the parsed value (SQLite answers its text). */
|
|
149
|
+
readonly json: NameSet
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function unexpected(where: string, expected: string): QueryRefusedError {
|
|
153
|
+
return new QueryRefusedError('unexpected_row', `${where} came back as something other than ${expected}`)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** One SQLite value of `key` as Postgres's driver answers it; a value the migrations' types never store is refused. */
|
|
157
|
+
function sqliteValue(columns: RowColumns, where: string, key: string, value: unknown): unknown {
|
|
158
|
+
if (value === null) {
|
|
159
|
+
return value
|
|
160
|
+
}
|
|
161
|
+
if (inSet(columns.timestamps, key)) {
|
|
162
|
+
if (typeof value !== 'string' || !STORED_TIMESTAMP.test(value)) {
|
|
163
|
+
throw unexpected(where, 'UTC ISO text (YYYY-MM-DDTHH:MM:SS.sssZ), the form a timestamp is stored in on SQLite')
|
|
164
|
+
}
|
|
165
|
+
return new Date(value)
|
|
166
|
+
}
|
|
167
|
+
if (inSet(columns.booleans, key)) {
|
|
168
|
+
if (value !== 0 && value !== 1) {
|
|
169
|
+
throw unexpected(where, '0 or 1, the form a boolean is stored in on SQLite')
|
|
170
|
+
}
|
|
171
|
+
return value === 1
|
|
172
|
+
}
|
|
173
|
+
if (inSet(columns.json, key)) {
|
|
174
|
+
return sqliteJson(value, where)
|
|
175
|
+
}
|
|
176
|
+
return typeof value === 'string' && inSet(columns.days, key) ? dayText(value, where) : value
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Every row of a read as the layer answers it, in place: each day as `YYYY-MM-DD` text, and on SQLite each timestamp as
|
|
181
|
+
* a `Date`, each boolean as `true` or `false` and each JSON column as its parsed value, so a handler reads the same
|
|
182
|
+
* values on both dialects.
|
|
183
|
+
*/
|
|
184
|
+
export function answerRows<R>(dialect: SqlDialect, table: string, columns: RowColumns, rows: R[]): R[] {
|
|
185
|
+
if (dialect === 'postgres') {
|
|
186
|
+
return answerDays(table, columns.days, rows)
|
|
187
|
+
}
|
|
188
|
+
for (let index = 0; index < rows.length; index++) {
|
|
189
|
+
const row = rows[index]
|
|
190
|
+
if (typeof row !== 'object' || row === null) {
|
|
191
|
+
continue
|
|
192
|
+
}
|
|
193
|
+
const keys = ownKeys(row)
|
|
194
|
+
for (let position = 0; position < keys.length; position++) {
|
|
195
|
+
const key = keys[position] ?? ''
|
|
196
|
+
const value: unknown = ownDescriptor(row, key)?.value
|
|
197
|
+
const answered = sqliteValue(columns, `${table}.${key}`, key, value)
|
|
198
|
+
if (answered !== value) {
|
|
199
|
+
defineValue(row, key, answered)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return rows
|
|
204
|
+
}
|