@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.41
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 +39 -4
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +56 -2
- package/src/codegen-sqlite.ts +194 -0
- package/src/codegen.ts +230 -41
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/database.ts +227 -61
- package/src/description.ts +37 -8
- package/src/errors.ts +10 -6
- package/src/file-columns.ts +56 -11
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +15 -5
- package/src/guard.ts +373 -15
- package/src/index.ts +17 -1
- package/src/job-leases.ts +228 -55
- package/src/job-wakes.ts +600 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +210 -0
- package/src/migrations.ts +73 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +206 -71
- package/src/orm.ts +425 -170
- package/src/policy.ts +1979 -141
- package/src/postgres.ts +26 -0
- package/src/registry.ts +55 -3
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +247 -476
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +269 -0
- package/src/store.ts +2292 -239
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +172 -6
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1351 -0
- package/src/testing-sqlite.ts +685 -0
- package/src/testing.ts +310 -494
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +55 -2
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +79 -5
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/description.d.ts +26 -8
- package/types/src/errors.d.ts +9 -6
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +12 -5
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +5 -4
- package/types/src/job-leases.d.ts +40 -5
- package/types/src/job-wakes.d.ts +124 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +4 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +163 -71
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +351 -23
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +40 -3
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +29 -21
- 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 +143 -34
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +18 -2
- package/types/src/temporal.d.ts +24 -0
- package/types/src/testing-shared.d.ts +290 -0
- package/types/src/testing-sqlite.d.ts +37 -0
- package/types/src/testing.d.ts +2 -93
- package/types/src/vocabulary-tables.d.ts +169 -22
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
|
@@ -1,14 +1,42 @@
|
|
|
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 {
|
|
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 {
|
|
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 {
|
|
38
|
+
AllOptions,
|
|
39
|
+
AllQuery,
|
|
12
40
|
AnyDbIndex,
|
|
13
41
|
ApplicationRows,
|
|
14
42
|
ApplicationTables,
|
|
@@ -19,6 +47,7 @@ export type {
|
|
|
19
47
|
ClaimOptions,
|
|
20
48
|
ContainedRows,
|
|
21
49
|
CountOptions,
|
|
50
|
+
CountQuery,
|
|
22
51
|
DataKind,
|
|
23
52
|
DbIndex,
|
|
24
53
|
FragmentTable,
|
|
@@ -27,6 +56,7 @@ export type {
|
|
|
27
56
|
InsertMethod,
|
|
28
57
|
ListOptions,
|
|
29
58
|
ListPage,
|
|
59
|
+
ListQuery,
|
|
30
60
|
NoUnscoped,
|
|
31
61
|
OrderTerm,
|
|
32
62
|
OwnerRow,
|
|
@@ -82,6 +112,7 @@ export {
|
|
|
82
112
|
} from './policy'
|
|
83
113
|
export type {
|
|
84
114
|
ColumnTypes,
|
|
115
|
+
ColumnViews,
|
|
85
116
|
DefineVocabularyPolicies,
|
|
86
117
|
NormalizedPolicies,
|
|
87
118
|
TableVocabulary,
|
|
@@ -94,8 +125,31 @@ export type {
|
|
|
94
125
|
VocabularyDimensionScope,
|
|
95
126
|
VocabularyPolicyMap,
|
|
96
127
|
VocabularyTablePolicy,
|
|
128
|
+
VocabularyViewPolicy,
|
|
97
129
|
} from './vocabulary-tables'
|
|
98
130
|
|
|
131
|
+
/**
|
|
132
|
+
* The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
|
|
133
|
+
* case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
|
|
134
|
+
* `@fabrika/check` reports the refusals from source; `@fabrika/db/testing` throws the first, both in the words of
|
|
135
|
+
* `applicationRowRefusalText`.
|
|
136
|
+
*/
|
|
137
|
+
export function applicationRowsPlan<DB, P>(
|
|
138
|
+
tables: Tables<DB, P>,
|
|
139
|
+
rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>,
|
|
140
|
+
): ApplicationRowsPlan {
|
|
141
|
+
return planApplicationRows(tableModels(tables), rows)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The tables whose rows hand out access, lowercased: a relation source or a path reveal, a member-revealing table, and
|
|
146
|
+
* the tables a principal path or a relation's condition reads. Only the data layer writes them; the migration classifier
|
|
147
|
+
* refuses database code that does.
|
|
148
|
+
*/
|
|
149
|
+
export function accessTables<DB, P>(tables: Tables<DB, P>): readonly string[] {
|
|
150
|
+
return accessTablesOf(tableModels(tables))
|
|
151
|
+
}
|
|
152
|
+
|
|
99
153
|
/** Every table's policy in the form the contract artifact carries, by table name. */
|
|
100
154
|
export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>
|
|
101
155
|
|
|
@@ -118,14 +172,15 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
|
|
|
118
172
|
const declared = [...ownKeys(model.columnReads), ...ownKeys(model.columnWrites)]
|
|
119
173
|
for (let index = 0; index < declared.length; index++) {
|
|
120
174
|
const name = declared[index] ?? ''
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
175
|
+
// A single action stays its text, so a policy that names one keeps its digest.
|
|
176
|
+
const read = actionArtifact(ownEntry(model.columnReads, name) ?? [])
|
|
177
|
+
const write = actionArtifact(ownEntry(model.columnWrites, name) ?? [])
|
|
178
|
+
setOwn(columns, name, { ...(read === null ? {} : { read }), ...(write === null ? {} : { write }) })
|
|
124
179
|
}
|
|
125
180
|
return {
|
|
126
181
|
scope: scopeOf(model.scope),
|
|
127
182
|
actions: {
|
|
128
|
-
read: actionArtifact(model.actions.read) ?? noReadAction(model.name),
|
|
183
|
+
read: model.actions.readAny ? READ_ANY : actionArtifact(model.actions.read) ?? noReadAction(model.name),
|
|
129
184
|
insert: actionArtifact(model.actions.insert),
|
|
130
185
|
update: actionArtifact(model.actions.update),
|
|
131
186
|
delete: actionArtifact(model.actions.delete),
|
|
@@ -138,7 +193,118 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
|
|
|
138
193
|
createdBy: model.createdBy ?? null,
|
|
139
194
|
columns,
|
|
140
195
|
...(ownKeys(model.files).length === 0 ? {} : { files: { ...model.files } }),
|
|
196
|
+
...(model.view ? { view: true } : {}),
|
|
197
|
+
...(model.confers.length === 0 ? {} : { confers: confersArtifact(model.confers) }),
|
|
198
|
+
...(ownKeys(model.when).length === 0 ? {} : { when: whenArtifact(model.when) }),
|
|
199
|
+
...(ownKeys(model.relationWhen).length === 0 ? {} : { relationWhen: relationWhenArtifact(model.relationWhen) }),
|
|
200
|
+
...(model.reveals.length === 0 ? {} : { reveals: revealsArtifact(model.reveals) }),
|
|
201
|
+
...(model.readThrough.length === 0 ? {} : { readThrough: readThroughArtifact(model) }),
|
|
202
|
+
...writeThroughArtifact(model),
|
|
203
|
+
...(model.memberReveals.length === 0 ? {} : { memberReveals: memberRevealsArtifact(model.memberReveals) }),
|
|
204
|
+
...(model.access.length === 0 ? {} : { access: accessArtifact(model.access) }),
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function accessArtifact(access: readonly AccessModel[]): Record<string, AccessArtifact> {
|
|
209
|
+
const artifact: Record<string, AccessArtifact> = {}
|
|
210
|
+
for (let index = 0; index < access.length; index++) {
|
|
211
|
+
const entry = access[index]
|
|
212
|
+
if (entry !== undefined) {
|
|
213
|
+
setOwn(artifact, entry.relation, { view: entry.view, row: entry.row, principal: entry.principal ?? null, member: entry.member ?? null })
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return artifact
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function memberRevealsArtifact(reveals: readonly MemberRevealModel[]): Record<string, MemberRevealsArtifact> {
|
|
220
|
+
const artifact: Record<string, MemberRevealsArtifact> = {}
|
|
221
|
+
for (let index = 0; index < reveals.length; index++) {
|
|
222
|
+
const reveal = reveals[index]
|
|
223
|
+
if (reveal === undefined) continue
|
|
224
|
+
setOwn(artifact, reveal.source, {
|
|
225
|
+
to: reveal.dimension,
|
|
226
|
+
actions: [...reveal.actions],
|
|
227
|
+
...(reveal.when === undefined ? {} : { when: conditionArtifact(reveal.when) }),
|
|
228
|
+
...(reveal.assign === undefined ? {} : { assign: { self: reveal.assign.self } }),
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
return artifact
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function readThroughArtifact(model: TableModel): Record<string, string> {
|
|
235
|
+
const artifact: Record<string, string> = {}
|
|
236
|
+
for (let index = 0; index < model.readThrough.length; index++) {
|
|
237
|
+
const path = model.readThrough[index]
|
|
238
|
+
if (path !== undefined) setOwn(artifact, path.dimension, path.via === undefined ? path.column : `${path.via.column}.${path.column}`)
|
|
239
|
+
}
|
|
240
|
+
return artifact
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function writeThroughArtifact(model: TableModel): { readonly writeThrough: Record<string, string[]> } | undefined {
|
|
244
|
+
const artifact: Record<string, string[]> = {}
|
|
245
|
+
let declared = false
|
|
246
|
+
for (let index = 0; index < model.readThrough.length; index++) {
|
|
247
|
+
const path = model.readThrough[index]
|
|
248
|
+
if (path === undefined || path.writes.length === 0) continue
|
|
249
|
+
setOwn(artifact, path.dimension, [...path.writes])
|
|
250
|
+
declared = true
|
|
251
|
+
}
|
|
252
|
+
return declared ? { writeThrough: artifact } : undefined
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function revealsArtifact(reveals: readonly RevealModel[]): Record<string, RevealsArtifact> {
|
|
256
|
+
const artifact: Record<string, RevealsArtifact> = {}
|
|
257
|
+
for (let index = 0; index < reveals.length; index++) {
|
|
258
|
+
const reveal = reveals[index]
|
|
259
|
+
if (reveal === undefined) continue
|
|
260
|
+
setOwn(artifact, reveal.relation, {
|
|
261
|
+
to: reveal.dimension,
|
|
262
|
+
actions: [...reveal.actions],
|
|
263
|
+
...(reveal.when === undefined ? {} : { when: conditionArtifact(reveal.when) }),
|
|
264
|
+
...(reveal.assign === undefined ? {} : { assign: { self: reveal.assign.self } }),
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
return artifact
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function confersArtifact(sources: readonly RelationSource[]): Record<string, ConfersArtifact> {
|
|
271
|
+
const confers: Record<string, ConfersArtifact> = {}
|
|
272
|
+
for (let index = 0; index < sources.length; index++) {
|
|
273
|
+
const source = sources[index]
|
|
274
|
+
if (source === undefined) continue
|
|
275
|
+
setOwn(confers, source.relation, {
|
|
276
|
+
principal: source.principalPath === undefined ? source.principal : `${source.principal}.${source.principalPath.column}`,
|
|
277
|
+
node: source.node,
|
|
278
|
+
expires: source.expires ?? null,
|
|
279
|
+
...(source.when === undefined ? {} : { when: conditionArtifact(source.when) }),
|
|
280
|
+
assign: source.assign === undefined ? null : { maxDays: source.assign.maxDays ?? null, self: source.assign.self },
|
|
281
|
+
})
|
|
282
|
+
}
|
|
283
|
+
return confers
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function whenArtifact(when: Readonly<Record<string, ConditionModel>>): Record<string, ConditionArtifact> {
|
|
287
|
+
const artifact: Record<string, ConditionArtifact> = {}
|
|
288
|
+
const actions = ownKeys(when)
|
|
289
|
+
for (let index = 0; index < actions.length; index++) {
|
|
290
|
+
const action = actions[index] ?? ''
|
|
291
|
+
const condition = ownEntry(when, action)
|
|
292
|
+
if (condition !== undefined) setOwn(artifact, action, conditionArtifact(condition))
|
|
293
|
+
}
|
|
294
|
+
return artifact
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function relationWhenArtifact(
|
|
298
|
+
relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>,
|
|
299
|
+
): Record<string, Record<string, ConditionArtifact>> {
|
|
300
|
+
const artifact: Record<string, Record<string, ConditionArtifact>> = {}
|
|
301
|
+
const relations = ownKeys(relationWhen)
|
|
302
|
+
for (let index = 0; index < relations.length; index++) {
|
|
303
|
+
const relation = relations[index] ?? ''
|
|
304
|
+
const conditions = ownEntry(relationWhen, relation)
|
|
305
|
+
if (conditions !== undefined) setOwn(artifact, relation, whenArtifact(conditions))
|
|
141
306
|
}
|
|
307
|
+
return artifact
|
|
142
308
|
}
|
|
143
309
|
|
|
144
310
|
/** One action as its text, so a single-action policy keeps the artifact and digest it had; several as a list; none as `null`. */
|