@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.6
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 +34 -3
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/capability.ts +5 -0
- package/src/codegen-sqlite.ts +146 -0
- package/src/codegen.ts +59 -9
- package/src/database.ts +227 -61
- package/src/errors.ts +2 -2
- package/src/file-columns.ts +4 -1
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +8 -0
- package/src/index.ts +9 -1
- package/src/job-leases.ts +210 -54
- package/src/job-wakes.ts +450 -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 +2 -2
- package/src/orm.ts +68 -35
- package/src/policy.ts +8 -2
- package/src/postgres.ts +26 -0
- package/src/registry.ts +11 -2
- package/src/sql.ts +216 -473
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +224 -0
- package/src/store.ts +362 -93
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +16 -0
- package/src/temporal.ts +115 -9
- package/src/testing-shared.ts +733 -0
- package/src/testing-sqlite.ts +513 -0
- package/src/testing.ts +169 -482
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/capability.d.ts +5 -0
- package/types/src/codegen-sqlite.d.ts +6 -0
- package/types/src/codegen.d.ts +30 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/errors.d.ts +2 -2
- package/types/src/framework.d.ts +11 -5
- package/types/src/index.d.ts +1 -1
- package/types/src/job-leases.d.ts +32 -4
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +1 -0
- package/types/src/nodes.d.ts +13 -2
- package/types/src/orm-types.d.ts +2 -2
- package/types/src/policy.d.ts +4 -0
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +10 -2
- 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 +26 -9
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +10 -0
- package/types/src/temporal.d.ts +21 -0
- package/types/src/testing-shared.d.ts +201 -0
- package/types/src/testing-sqlite.d.ts +22 -0
- package/types/src/testing.d.ts +2 -93
package/src/database.ts
CHANGED
|
@@ -1,12 +1,46 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { CompiledQuery, createQueryId, type Dialect, Kysely, PostgresQueryCompiler, type RootOperationNode, type TransactionBuilder } from 'kysely'
|
|
3
|
-
import { PostgresJSDialect } from 'kysely-postgres-js'
|
|
1
|
+
import { CompiledQuery, createQueryId, type Dialect, Kysely, PostgresQueryCompiler, type QueryCompiler, type RootOperationNode } from 'kysely'
|
|
4
2
|
import { databaseError, QueryRefusedError } from './errors'
|
|
5
3
|
import { assertAllowedTree, type GuardContext } from './guard'
|
|
6
4
|
import { isPlainIdentifier } from './identifier'
|
|
7
5
|
|
|
8
|
-
type LooseDB = Record<string, Record<string, unknown>>
|
|
9
|
-
|
|
6
|
+
export type LooseDB = Record<string, Record<string, unknown>>
|
|
7
|
+
/** What a statement runs on: the database's own executor, or the one of the transaction it runs in. */
|
|
8
|
+
export type Executor = Pick<Kysely<LooseDB>, 'executeQuery'>
|
|
9
|
+
|
|
10
|
+
/** The SQL a database speaks: Postgres on Bun, SQLite in a Cloudflare Durable Object (ADR-0065). */
|
|
11
|
+
export type SqlDialect = 'postgres' | 'sqlite'
|
|
12
|
+
|
|
13
|
+
export interface TransactionOptions {
|
|
14
|
+
/**
|
|
15
|
+
* A `READ ONLY` transaction on Postgres. SQLite opens none: each statement runs in a transaction of its own, which
|
|
16
|
+
* rolls back a statement that wrote. A read-only session refuses writes either way.
|
|
17
|
+
*/
|
|
18
|
+
readonly readOnly: boolean
|
|
19
|
+
/** How long the transaction may sit idle before the database ends it; a database without the setting ignores it. */
|
|
20
|
+
readonly idleTimeoutMs?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Runs `body` in one transaction, on the executor it hands it: commits when `body` resolves, rolls back when it
|
|
25
|
+
* rejects, and rejects with `body`'s error. Its BEGIN, COMMIT and ROLLBACK failures reject with the driver's error.
|
|
26
|
+
*/
|
|
27
|
+
export type TransactionRunner = <T>(options: TransactionOptions, body: (executor: Executor) => Promise<T>) => Promise<T>
|
|
28
|
+
|
|
29
|
+
/** What a `Database` runs on: the driver, the compiler of its dialect, and how it opens a transaction. */
|
|
30
|
+
export interface DatabaseEngine {
|
|
31
|
+
readonly dialect: SqlDialect
|
|
32
|
+
readonly kysely: Kysely<LooseDB>
|
|
33
|
+
/** Compiles every guarded tree; frozen, since a patch to it after the guard ran would bypass the guard. */
|
|
34
|
+
readonly compiler: QueryCompiler
|
|
35
|
+
readonly transaction: TransactionRunner
|
|
36
|
+
/** The application's schema, the connection's `search_path`; `undefined` where the database has none. */
|
|
37
|
+
readonly schema?: string
|
|
38
|
+
/**
|
|
39
|
+
* SQLite's: runs each statement in a transaction of its own (a savepoint inside an open one) and refuses, rolling it
|
|
40
|
+
* back, one that wrote. A `ctx.sql` site that declares `'read'` runs on it in a writable invocation too.
|
|
41
|
+
*/
|
|
42
|
+
readonly reads?: Executor
|
|
43
|
+
}
|
|
10
44
|
|
|
11
45
|
/**
|
|
12
46
|
* With `prepare: false`, Bun.SQL sends every parameter as text and a Date as `Date#toString()`, which Postgres
|
|
@@ -25,14 +59,14 @@ function timestampText(date: Date): string {
|
|
|
25
59
|
return date.toISOString()
|
|
26
60
|
}
|
|
27
61
|
|
|
28
|
-
const
|
|
29
|
-
freezePrototypeChain(
|
|
62
|
+
const postgresCompiler = new ParameterCompiler()
|
|
63
|
+
freezePrototypeChain(postgresCompiler)
|
|
30
64
|
|
|
31
65
|
/**
|
|
32
66
|
* The compiler turns the guarded tree into SQL, so a patch to it after the guard ran would bypass the guard.
|
|
33
67
|
* Freezing it when this module loads, before application modules, makes such a patch throw instead.
|
|
34
68
|
*/
|
|
35
|
-
function freezePrototypeChain(object: object): void {
|
|
69
|
+
export function freezePrototypeChain(object: object): void {
|
|
36
70
|
let current: object | null = object
|
|
37
71
|
while (current !== null && current !== Object.prototype) {
|
|
38
72
|
Object.freeze(current)
|
|
@@ -56,63 +90,73 @@ export function applicationSchema(appId: string): string {
|
|
|
56
90
|
return `app_${appId.replaceAll('-', '_')}`
|
|
57
91
|
}
|
|
58
92
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
93
|
+
const SQL_IDLE_TIMEOUT = "select set_config('idle_in_transaction_session_timeout', $1, true)"
|
|
94
|
+
|
|
95
|
+
/** Postgres over Kysely's own transaction builder. */
|
|
96
|
+
function postgresTransaction(kysely: Kysely<LooseDB>): TransactionRunner {
|
|
97
|
+
return (options, body) => {
|
|
98
|
+
const builder = kysely.transaction()
|
|
99
|
+
return (options.readOnly ? builder.setAccessMode('read only') : builder).execute(async (transaction) => {
|
|
100
|
+
if (options.idleTimeoutMs !== undefined) {
|
|
101
|
+
await transaction.executeQuery(CompiledQuery.raw(SQL_IDLE_TIMEOUT, [String(options.idleTimeoutMs)]))
|
|
102
|
+
}
|
|
103
|
+
return body(transaction)
|
|
104
|
+
})
|
|
105
|
+
}
|
|
64
106
|
}
|
|
65
107
|
|
|
66
108
|
let openSession: (database: Database, readOnly: boolean) => Session
|
|
67
|
-
let
|
|
109
|
+
let engineOf: (database: Database) => DatabaseEngine
|
|
68
110
|
let firstConnection: (database: Database) => Promise<void>
|
|
69
111
|
|
|
70
112
|
/** The connection the data layer runs on. It has no public query method: everything goes through a store. */
|
|
71
113
|
export class Database {
|
|
72
|
-
readonly #
|
|
73
|
-
readonly #schema: string | undefined
|
|
114
|
+
readonly #engine: DatabaseEngine
|
|
74
115
|
|
|
75
|
-
private constructor(
|
|
76
|
-
|
|
77
|
-
|
|
116
|
+
private constructor(engine: DatabaseEngine) {
|
|
117
|
+
if (engine.schema !== undefined && !isPlainIdentifier(engine.schema)) {
|
|
118
|
+
throw new QueryRefusedError('invalid_name', 'the schema must match ^[a-z_][a-z0-9_]*$')
|
|
119
|
+
}
|
|
120
|
+
this.#engine = Object.freeze({ ...engine })
|
|
78
121
|
Object.freeze(this)
|
|
79
122
|
}
|
|
80
123
|
|
|
81
124
|
static {
|
|
82
|
-
openSession = (database, readOnly) => new Session(database.#kysely, database.#
|
|
83
|
-
|
|
125
|
+
openSession = (database, readOnly) => new Session(database.#engine.kysely, database.#engine, false, readOnly)
|
|
126
|
+
engineOf = (database) => database.#engine
|
|
84
127
|
firstConnection = async (database) => {
|
|
85
|
-
await database.#kysely.executeQuery(CompiledQuery.raw('SELECT 1'))
|
|
128
|
+
await database.#engine.kysely.executeQuery(CompiledQuery.raw('SELECT 1'))
|
|
86
129
|
}
|
|
87
130
|
}
|
|
88
131
|
|
|
89
132
|
/**
|
|
90
|
-
*
|
|
91
|
-
*
|
|
133
|
+
* Any Kysely Postgres dialect: `@fabrika/db/postgres` opens Bun.SQL through it, tests use one that records statements
|
|
134
|
+
* instead of sending them.
|
|
92
135
|
*/
|
|
93
|
-
static
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
const pool = new SQL({ url: options.url, adapter: 'postgres', prepare: false, max: options.max ?? 10, connection: { search_path: options.schema } })
|
|
98
|
-
return new Database(new Kysely<LooseDB>({ dialect: new PostgresJSDialect({ postgres: pool }) }), options.schema)
|
|
136
|
+
static fromDialect(dialect: Dialect, options: { readonly schema?: string } = {}): Database {
|
|
137
|
+
const kysely = new Kysely<LooseDB>({ dialect })
|
|
138
|
+
return new Database({ dialect: 'postgres', kysely, compiler: postgresCompiler, transaction: postgresTransaction(kysely), schema: options.schema })
|
|
99
139
|
}
|
|
100
140
|
|
|
101
|
-
/**
|
|
102
|
-
static
|
|
103
|
-
return new Database(
|
|
141
|
+
/** A database of another dialect (`@fabrika/db/sqlite`), with its own frozen compiler and transaction runner. */
|
|
142
|
+
static fromEngine(engine: DatabaseEngine): Database {
|
|
143
|
+
return new Database(engine)
|
|
104
144
|
}
|
|
105
145
|
|
|
106
|
-
|
|
146
|
+
get dialect(): SqlDialect {
|
|
147
|
+
return this.#engine.dialect
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The application's schema, the connection's `search_path`; `undefined` over a bare dialect and on SQLite. */
|
|
107
151
|
get schema(): string | undefined {
|
|
108
|
-
return this.#schema
|
|
152
|
+
return this.#engine.schema
|
|
109
153
|
}
|
|
110
154
|
|
|
111
155
|
async close(): Promise<void> {
|
|
112
|
-
await this.#kysely.destroy()
|
|
156
|
+
await this.#engine.kysely.destroy()
|
|
113
157
|
}
|
|
114
158
|
}
|
|
115
|
-
// Application modules load after this one: a replaced
|
|
159
|
+
// Application modules load after this one: a replaced opener would receive the database's connection.
|
|
116
160
|
Object.freeze(Database)
|
|
117
161
|
Object.freeze(Database.prototype)
|
|
118
162
|
|
|
@@ -141,6 +185,7 @@ export function sessionOf(source: SessionSource): Session {
|
|
|
141
185
|
}
|
|
142
186
|
|
|
143
187
|
let executeFixed: (session: Session, compiled: CompiledQuery) => Promise<readonly unknown[]>
|
|
188
|
+
let executeRead: (session: Session, compiled: CompiledQuery) => Promise<readonly unknown[]>
|
|
144
189
|
|
|
145
190
|
/** What a session reports to, and asks, the transaction it runs in. */
|
|
146
191
|
interface SessionHooks {
|
|
@@ -171,13 +216,15 @@ function untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Pro
|
|
|
171
216
|
*/
|
|
172
217
|
export class Session {
|
|
173
218
|
readonly #executor: Executor
|
|
174
|
-
readonly #
|
|
219
|
+
readonly #engine: DatabaseEngine
|
|
220
|
+
readonly #inTransaction: boolean
|
|
175
221
|
readonly #readOnly: boolean
|
|
176
222
|
readonly #hooks: SessionHooks
|
|
177
223
|
|
|
178
|
-
constructor(executor: Executor,
|
|
224
|
+
constructor(executor: Executor, engine: DatabaseEngine, inTransaction: boolean, readOnly: boolean, hooks: SessionHooks = {}) {
|
|
179
225
|
this.#executor = executor
|
|
180
|
-
this.#
|
|
226
|
+
this.#engine = engine
|
|
227
|
+
this.#inTransaction = inTransaction
|
|
181
228
|
this.#readOnly = readOnly
|
|
182
229
|
this.#hooks = hooks
|
|
183
230
|
Object.freeze(this)
|
|
@@ -185,23 +232,29 @@ export class Session {
|
|
|
185
232
|
|
|
186
233
|
static {
|
|
187
234
|
executeFixed = async (session, compiled) => (await session.#execute(compiled)).rows
|
|
235
|
+
executeRead = async (session, compiled) => (await session.#execute(compiled, session.#engine.reads ?? session.#executor)).rows
|
|
188
236
|
}
|
|
189
237
|
|
|
190
238
|
get readOnly(): boolean {
|
|
191
239
|
return this.#readOnly
|
|
192
240
|
}
|
|
193
241
|
|
|
242
|
+
/** The dialect of the database this session runs on: a framework statement picks its text by it. */
|
|
243
|
+
get dialect(): SqlDialect {
|
|
244
|
+
return this.#engine.dialect
|
|
245
|
+
}
|
|
246
|
+
|
|
194
247
|
/** Fails the transaction this session runs in, so it commits nothing: a statement refused before it was sent. */
|
|
195
248
|
fail(): void {
|
|
196
249
|
this.#hooks.failed?.()
|
|
197
250
|
}
|
|
198
251
|
|
|
199
|
-
async #execute<O>(compiled: CompiledQuery<O
|
|
252
|
+
async #execute<O>(compiled: CompiledQuery<O>, executor: Executor = this.#executor): Promise<{ readonly rows: O[] }> {
|
|
200
253
|
if (this.#hooks.open?.() === false) {
|
|
201
254
|
throw new QueryRefusedError('ended', 'the transaction of this session has ended; it runs nothing more')
|
|
202
255
|
}
|
|
203
256
|
try {
|
|
204
|
-
return await
|
|
257
|
+
return await executor.executeQuery(compiled)
|
|
205
258
|
} catch (error) {
|
|
206
259
|
this.#hooks.failed?.()
|
|
207
260
|
throw databaseError(error)
|
|
@@ -214,11 +267,10 @@ export class Session {
|
|
|
214
267
|
throw new QueryRefusedError('read_only', 'this request is read-only: it reads, and no operation may write or lock a row')
|
|
215
268
|
}
|
|
216
269
|
// CompiledQuery's row type is a phantom: this is the one place where generated row types meet the wire.
|
|
217
|
-
const compiled: CompiledQuery<O> = compiler.compileQuery(node, createQueryId())
|
|
218
|
-
|
|
219
|
-
if (this.#readOnly && kysely !== undefined) {
|
|
270
|
+
const compiled: CompiledQuery<O> = this.#engine.compiler.compileQuery(node, createQueryId())
|
|
271
|
+
if (this.#readOnly && !this.#inTransaction) {
|
|
220
272
|
try {
|
|
221
|
-
const result = await
|
|
273
|
+
const result = await this.#engine.transaction({ readOnly: true }, (executor) => executor.executeQuery(compiled))
|
|
222
274
|
return result.rows
|
|
223
275
|
} catch (error) {
|
|
224
276
|
throw databaseError(error)
|
|
@@ -234,15 +286,14 @@ export class Session {
|
|
|
234
286
|
* `work` returned or not; its session then runs nothing more.
|
|
235
287
|
*/
|
|
236
288
|
async transaction<T>(work: (session: Session) => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
237
|
-
if (this.#
|
|
289
|
+
if (this.#inTransaction) {
|
|
238
290
|
return work(this)
|
|
239
291
|
}
|
|
240
|
-
const builder = this.#kysely.transaction()
|
|
241
292
|
let open = true
|
|
242
293
|
let failed = false
|
|
243
294
|
let failure: { readonly error: unknown } | undefined
|
|
244
295
|
try {
|
|
245
|
-
return await
|
|
296
|
+
return await this.#engine.transaction({ readOnly: this.#readOnly }, async (executor) => {
|
|
246
297
|
try {
|
|
247
298
|
const hooks: SessionHooks = {
|
|
248
299
|
open: () => open,
|
|
@@ -250,7 +301,7 @@ export class Session {
|
|
|
250
301
|
failed = true
|
|
251
302
|
},
|
|
252
303
|
}
|
|
253
|
-
const result = await untilAborted(work(new Session(
|
|
304
|
+
const result = await untilAborted(work(new Session(executor, this.#engine, true, this.#readOnly, hooks)), signal)
|
|
254
305
|
// A failure the work caught: Postgres would answer the COMMIT of an aborted transaction with a silent ROLLBACK.
|
|
255
306
|
if (failed) {
|
|
256
307
|
throw new QueryRefusedError('statement_failed', 'a statement of this transaction failed, so nothing it wrote commits')
|
|
@@ -274,11 +325,43 @@ Object.freeze(Session.prototype)
|
|
|
274
325
|
/** How long an invocation's transaction may sit idle before Postgres ends it, and its connection with it. */
|
|
275
326
|
export const INVOCATION_IDLE_TIMEOUT_MS = 30_000
|
|
276
327
|
|
|
277
|
-
const SQL_IDLE_TIMEOUT = "select set_config('idle_in_transaction_session_timeout', $1, true)"
|
|
278
|
-
|
|
279
328
|
/** What the invocation's transaction body throws to roll back; never seen outside this module. */
|
|
280
329
|
class RolledBack extends Error {}
|
|
281
330
|
|
|
331
|
+
/** A writing invocation that holds its object's storage transaction longer than this logs one line. */
|
|
332
|
+
export const TRANSACTION_HELD_LOG_MS = 1_000
|
|
333
|
+
/** A writing invocation that holds its object's storage transaction longer than this is also reported. */
|
|
334
|
+
export const TRANSACTION_HELD_REPORT_MS = 5_000
|
|
335
|
+
|
|
336
|
+
/** Where an enclosure tells how long it held its object: every other event of the object waited that long. */
|
|
337
|
+
export interface HoldWatch {
|
|
338
|
+
/** The site the invocation serves, which the log line names. */
|
|
339
|
+
readonly site: string
|
|
340
|
+
/** Hears a hold longer than `TRANSACTION_HELD_REPORT_MS`, in whole ms. */
|
|
341
|
+
readonly held: (heldMs: number) => void
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Runs once the transaction settled, so it never throws: a failed log or report must not turn a committed invocation
|
|
346
|
+
* into a failed one. Each has its own guard; the line names the site and the ms only, never a value or a statement.
|
|
347
|
+
*/
|
|
348
|
+
function reportHold(watch: HoldWatch, heldMs: number): void {
|
|
349
|
+
try {
|
|
350
|
+
if (heldMs > TRANSACTION_HELD_LOG_MS) {
|
|
351
|
+
console.warn(`fabrika: ${watch.site}: held its object's transaction for ${heldMs} ms`)
|
|
352
|
+
}
|
|
353
|
+
} catch {
|
|
354
|
+
// The report below still goes out.
|
|
355
|
+
}
|
|
356
|
+
try {
|
|
357
|
+
if (heldMs > TRANSACTION_HELD_REPORT_MS) {
|
|
358
|
+
watch.held(heldMs)
|
|
359
|
+
}
|
|
360
|
+
} catch {
|
|
361
|
+
// The hold was logged; the invocation's own outcome stands.
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
282
365
|
/**
|
|
283
366
|
* The one transaction of an invocation (a request, a webhook delivery): opened by its first statement, then ended
|
|
284
367
|
* once by the framework — committed after the handler returned and its output passed validation, rolled back
|
|
@@ -289,6 +372,7 @@ class RolledBack extends Error {}
|
|
|
289
372
|
export class InvocationTransaction {
|
|
290
373
|
readonly #database: Database
|
|
291
374
|
readonly #readOnly: boolean
|
|
375
|
+
readonly #now: () => number
|
|
292
376
|
readonly #decision = Promise.withResolvers<'commit' | 'rollback'>()
|
|
293
377
|
#opened: Promise<Session> | undefined
|
|
294
378
|
#run: Promise<void> | undefined
|
|
@@ -296,10 +380,15 @@ export class InvocationTransaction {
|
|
|
296
380
|
#isReleased = true
|
|
297
381
|
#ended = false
|
|
298
382
|
#failed = false
|
|
383
|
+
/** Inside `enclose` on SQLite: `commit()` and `rollback()` only decide, and the enclosure ends the transaction. */
|
|
384
|
+
#enclosed = false
|
|
385
|
+
#decided: 'commit' | 'rollback' | undefined
|
|
299
386
|
|
|
300
|
-
|
|
387
|
+
/** `now` is the clock an enclosure's hold is measured by. */
|
|
388
|
+
constructor(database: Database, readOnly: boolean, now: () => number = Date.now) {
|
|
301
389
|
this.#database = database
|
|
302
390
|
this.#readOnly = readOnly
|
|
391
|
+
this.#now = now
|
|
303
392
|
}
|
|
304
393
|
|
|
305
394
|
/** A `READ ONLY` transaction: a query's or an export's. */
|
|
@@ -327,6 +416,65 @@ export class InvocationTransaction {
|
|
|
327
416
|
return this.#isReleased
|
|
328
417
|
}
|
|
329
418
|
|
|
419
|
+
/**
|
|
420
|
+
* Runs `work`: the invocation from its handler to its `commit()`. On SQLite a writing invocation's transaction
|
|
421
|
+
* encloses `work`, opened before it: a Durable Object's transaction holds back every other event, the answers to the
|
|
422
|
+
* object's own I/O included, until its callback ends, so the handler runs inside it. There `commit()` and `rollback()`
|
|
423
|
+
* decide, the COMMIT runs once `work` returned, and a failed COMMIT rejects with a `DatabaseError`. A read-only
|
|
424
|
+
* invocation, and every invocation elsewhere, runs `work` as is: a read-only one on SQLite holds no storage
|
|
425
|
+
* transaction, so the object serves other events while it awaits.
|
|
426
|
+
*
|
|
427
|
+
* Only the SQLite enclosure is measured for `watch`, from entering the transaction until it settled: it holds the
|
|
428
|
+
* whole object, where a Postgres transaction holds one pooled connection and other requests go on.
|
|
429
|
+
*/
|
|
430
|
+
async enclose<T>(work: () => Promise<T>, watch: HoldWatch): Promise<T> {
|
|
431
|
+
const engine = engineOf(this.#database)
|
|
432
|
+
if (engine.dialect !== 'sqlite' || this.#readOnly) {
|
|
433
|
+
return work()
|
|
434
|
+
}
|
|
435
|
+
if (this.#opened !== undefined || this.#ended) {
|
|
436
|
+
throw new QueryRefusedError('ended', 'an invocation encloses its work before its first statement')
|
|
437
|
+
}
|
|
438
|
+
this.#enclosed = true
|
|
439
|
+
this.#isReleased = false
|
|
440
|
+
let result: { readonly value: T } | undefined
|
|
441
|
+
let entered: number | undefined
|
|
442
|
+
try {
|
|
443
|
+
await engine.transaction({ readOnly: this.#readOnly }, async (executor) => {
|
|
444
|
+
entered = this.#now()
|
|
445
|
+
const session = new Session(executor, engine, true, this.#readOnly, {
|
|
446
|
+
failed: () => {
|
|
447
|
+
this.#failed = true
|
|
448
|
+
},
|
|
449
|
+
open: () => !this.#ended,
|
|
450
|
+
})
|
|
451
|
+
this.#opened = Promise.resolve(session)
|
|
452
|
+
result = { value: await work() }
|
|
453
|
+
this.#ended = true
|
|
454
|
+
if (this.#decided !== 'commit') {
|
|
455
|
+
throw new RolledBack()
|
|
456
|
+
}
|
|
457
|
+
})
|
|
458
|
+
} catch (error) {
|
|
459
|
+
if (result === undefined) {
|
|
460
|
+
throw error
|
|
461
|
+
}
|
|
462
|
+
if (!(error instanceof RolledBack)) {
|
|
463
|
+
throw databaseError(error)
|
|
464
|
+
}
|
|
465
|
+
} finally {
|
|
466
|
+
this.#ended = true
|
|
467
|
+
this.#isReleased = true
|
|
468
|
+
if (entered !== undefined) {
|
|
469
|
+
reportHold(watch, Math.round(this.#now() - entered))
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (result === undefined) {
|
|
473
|
+
throw new QueryRefusedError('ended', 'the transaction ended before the invocation answered')
|
|
474
|
+
}
|
|
475
|
+
return result.value
|
|
476
|
+
}
|
|
477
|
+
|
|
330
478
|
/** The session the invocation's statements run in; the first call opens the transaction. */
|
|
331
479
|
session(): Promise<Session> {
|
|
332
480
|
if (this.#ended) {
|
|
@@ -339,15 +487,15 @@ export class InvocationTransaction {
|
|
|
339
487
|
#open(): Promise<Session> {
|
|
340
488
|
const ready = Promise.withResolvers<Session>()
|
|
341
489
|
this.#isReleased = false
|
|
342
|
-
const
|
|
343
|
-
const
|
|
344
|
-
|
|
490
|
+
const engine = engineOf(this.#database)
|
|
491
|
+
const options: TransactionOptions = { readOnly: this.#readOnly, idleTimeoutMs: INVOCATION_IDLE_TIMEOUT_MS }
|
|
492
|
+
const run = engine.transaction(options, async (executor) => {
|
|
493
|
+
const session = new Session(executor, engine, true, this.#readOnly, {
|
|
345
494
|
failed: () => {
|
|
346
495
|
this.#failed = true
|
|
347
496
|
},
|
|
348
497
|
open: () => !this.#ended,
|
|
349
498
|
})
|
|
350
|
-
await executeFixed(session, CompiledQuery.raw(SQL_IDLE_TIMEOUT, [String(INVOCATION_IDLE_TIMEOUT_MS)]))
|
|
351
499
|
ready.resolve(session)
|
|
352
500
|
if ((await this.#decision.promise) === 'rollback') {
|
|
353
501
|
throw new RolledBack()
|
|
@@ -371,6 +519,13 @@ export class InvocationTransaction {
|
|
|
371
519
|
throw new QueryRefusedError('ended', 'this invocation has already ended')
|
|
372
520
|
}
|
|
373
521
|
this.#ended = true
|
|
522
|
+
if (this.#enclosed) {
|
|
523
|
+
this.#decided = this.#failed ? 'rollback' : 'commit'
|
|
524
|
+
if (this.#failed) {
|
|
525
|
+
throw new QueryRefusedError('statement_failed', 'a statement of this invocation failed, so nothing it wrote commits')
|
|
526
|
+
}
|
|
527
|
+
return
|
|
528
|
+
}
|
|
374
529
|
const run = this.#run
|
|
375
530
|
if (this.#failed) {
|
|
376
531
|
this.#decision.resolve('rollback')
|
|
@@ -390,9 +545,13 @@ export class InvocationTransaction {
|
|
|
390
545
|
}
|
|
391
546
|
}
|
|
392
547
|
|
|
393
|
-
/** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back. */
|
|
548
|
+
/** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back (inside `enclose`, it only decides). */
|
|
394
549
|
async rollback(): Promise<void> {
|
|
395
550
|
this.#ended = true
|
|
551
|
+
if (this.#enclosed) {
|
|
552
|
+
this.#decided ??= 'rollback'
|
|
553
|
+
return
|
|
554
|
+
}
|
|
396
555
|
this.#decision.resolve('rollback')
|
|
397
556
|
await this.#released
|
|
398
557
|
}
|
|
@@ -419,8 +578,15 @@ export type SqlParameter = string | number | boolean | bigint | null
|
|
|
419
578
|
|
|
420
579
|
/**
|
|
421
580
|
* One `ctx.sql` statement, whose text `sql.ts` classified and whose values are bound parameters only. It runs through the
|
|
422
|
-
* session's one path to the connection, so a statement the database refuses fails the invocation it runs in.
|
|
581
|
+
* session's one path to the connection, so a statement the database refuses fails the invocation it runs in. A `'read'`
|
|
582
|
+
* statement runs on the engine's `reads` where it has one (SQLite), so one that wrote is refused and rolled back.
|
|
423
583
|
*/
|
|
424
|
-
export function runApplicationStatement(
|
|
425
|
-
|
|
584
|
+
export function runApplicationStatement(
|
|
585
|
+
session: Session,
|
|
586
|
+
text: string,
|
|
587
|
+
parameters: readonly SqlParameter[],
|
|
588
|
+
mode: 'read' | 'write',
|
|
589
|
+
): Promise<readonly unknown[]> {
|
|
590
|
+
const compiled = CompiledQuery.raw(text, [...parameters])
|
|
591
|
+
return mode === 'read' ? executeRead(session, compiled) : executeFixed(session, compiled)
|
|
426
592
|
}
|
package/src/errors.ts
CHANGED
|
@@ -51,10 +51,10 @@ export const QUERY_REFUSALS = {
|
|
|
51
51
|
sql_template: 'ctx.sql was not called as one tagged template whose values are interpolated whole',
|
|
52
52
|
sql_statement: 'ctx.sql runs one statement of an admitted kind, and none inside another',
|
|
53
53
|
sql_read_only: "sql: 'read' runs queries only; declare sql: 'write' on a mutation, a job or a webhook",
|
|
54
|
-
sql_name: 'ctx.sql names a framework, catalog or foreign-schema object, or writes a name in U& form',
|
|
54
|
+
sql_name: 'ctx.sql names a framework (fabrika_*), catalog (pg_*, sqlite_*) or foreign-schema object, or writes a name in U& form',
|
|
55
55
|
sql_function: 'ctx.sql calls a function that is not a reviewed built-in',
|
|
56
56
|
sql_outside_transaction: 'a job runs ctx.sql only inside ctx.transaction((tx) => …), as tx.sql',
|
|
57
|
-
sql_scope: 'ctx.sql.scope(…)
|
|
57
|
+
sql_scope: 'ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site',
|
|
58
58
|
file_scan: "a scan verdict outside the scan job's lease",
|
|
59
59
|
claim_site: 'claim leases rows in a transaction of its own: a job calls it on ctx.db, never inside ctx.transaction or a request',
|
|
60
60
|
on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action",
|
package/src/file-columns.ts
CHANGED
|
@@ -125,7 +125,10 @@ export async function storedRowScope(model: TableModel, session: Session, key: s
|
|
|
125
125
|
if (!isPlainIdentifier(model.name) || !isPlainIdentifier(column) || !isPlainIdentifier(key)) {
|
|
126
126
|
throw new QueryRefusedError('invalid_name', "a file column's table is named by plain identifiers")
|
|
127
127
|
}
|
|
128
|
-
const
|
|
128
|
+
const statement = session.dialect === 'sqlite'
|
|
129
|
+
? `select cast(${column} as text) as scope from ${model.name} where cast(${key} as text) = ?1`
|
|
130
|
+
: `select ${column}::text as scope from ${model.name} where ${key}::text = $1`
|
|
131
|
+
const [found] = await runFixedStatement(session, statement, [keyValue])
|
|
129
132
|
const value: unknown = typeof found === 'object' && found !== null ? ownDescriptor(found, 'scope')?.value : undefined
|
|
130
133
|
if (typeof value !== 'string') {
|
|
131
134
|
throw new NotFoundError(`${model.name} not found`)
|
package/src/framework-tables.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { BinaryOperationNode, type OperationNode, OperatorNode, ValueNode } from
|
|
|
8
8
|
import { runFixedStatement, type Session, sessionOf } from './database'
|
|
9
9
|
import { QueryRefusedError } from './errors'
|
|
10
10
|
import type { GuardContext } from './guard'
|
|
11
|
+
import type { DialectTexts } from './job-leases'
|
|
11
12
|
import { WEBHOOK_BINDINGS_TABLE, WEBHOOK_DELIVERIES_TABLE } from './migrations'
|
|
12
13
|
import { acknowledgement, allOf, column, deleteNode, equals, insertNode, locateNode, scopedWhere, updateNode } from './nodes'
|
|
13
14
|
import type { DataLayerRuntime } from './store'
|
|
@@ -72,16 +73,35 @@ export interface DeliveryClaim {
|
|
|
72
73
|
const D = WEBHOOK_DELIVERIES_TABLE
|
|
73
74
|
|
|
74
75
|
/** A new key, or one whose claim expired without completion; a completed one (no lease) is never taken. */
|
|
75
|
-
const SQL_CLAIM =
|
|
76
|
+
const SQL_CLAIM: DialectTexts = {
|
|
77
|
+
postgres: `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values ($1, $2, $3::bigint, $4::bigint)
|
|
76
78
|
on conflict (binding_id, delivery_id) do update set received_at = excluded.received_at, lease_until = excluded.lease_until
|
|
77
79
|
where ${D}.lease_until is not null and ${D}.lease_until < excluded.received_at
|
|
78
|
-
returning delivery_id
|
|
80
|
+
returning delivery_id`,
|
|
81
|
+
sqlite: `insert into ${D} (binding_id, delivery_id, received_at, lease_until) values (?1, ?2, ?3, ?4)
|
|
82
|
+
on conflict (binding_id, delivery_id) do update set received_at = excluded.received_at, lease_until = excluded.lease_until
|
|
83
|
+
where ${D}.lease_until is not null and ${D}.lease_until < excluded.received_at
|
|
84
|
+
returning delivery_id`,
|
|
85
|
+
}
|
|
79
86
|
|
|
80
|
-
const SQL_COMPLETE =
|
|
87
|
+
const SQL_COMPLETE: DialectTexts = {
|
|
88
|
+
postgres: `update ${D} set lease_until = null
|
|
81
89
|
where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint
|
|
82
|
-
returning delivery_id
|
|
90
|
+
returning delivery_id`,
|
|
91
|
+
sqlite: `update ${D} set lease_until = null
|
|
92
|
+
where binding_id = ?1 and delivery_id = ?2 and lease_until = ?3
|
|
93
|
+
returning delivery_id`,
|
|
94
|
+
}
|
|
83
95
|
|
|
84
|
-
const SQL_RELEASE =
|
|
96
|
+
const SQL_RELEASE: DialectTexts = {
|
|
97
|
+
postgres: `delete from ${D} where binding_id = $1 and delivery_id = $2 and lease_until = $3::bigint returning delivery_id`,
|
|
98
|
+
sqlite: `delete from ${D} where binding_id = ?1 and delivery_id = ?2 and lease_until = ?3 returning delivery_id`,
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Runs the text of `session`'s dialect. */
|
|
102
|
+
function run(session: Session, texts: DialectTexts, parameters: readonly (string | number)[]): Promise<readonly unknown[]> {
|
|
103
|
+
return runFixedStatement(session, texts[session.dialect], parameters)
|
|
104
|
+
}
|
|
85
105
|
|
|
86
106
|
const BINDING_COLUMNS = ['id', 'webhook', 'scope_type', 'scope_value', 'account', 'secret']
|
|
87
107
|
|
|
@@ -186,17 +206,17 @@ export function webhookTables(runtime: () => DataLayerRuntime): WebhookTables {
|
|
|
186
206
|
)
|
|
187
207
|
const leaseUntil = now + leaseMs
|
|
188
208
|
// The primary key decides between concurrent copies of one delivery: exactly one inserts or takes over.
|
|
189
|
-
const claimed = await
|
|
209
|
+
const claimed = await run(session(), SQL_CLAIM, [bindingId, deliveryKey, now, leaseUntil])
|
|
190
210
|
return claimed.length === 0 ? null : Object.freeze({ bindingId, key: deliveryKey, leaseUntil })
|
|
191
211
|
},
|
|
192
212
|
|
|
193
213
|
async completeDelivery(claim: DeliveryClaim, using?: Session): Promise<boolean> {
|
|
194
|
-
const completed = await
|
|
214
|
+
const completed = await run(using ?? session(), SQL_COMPLETE, [claim.bindingId, claim.key, claim.leaseUntil])
|
|
195
215
|
return completed.length > 0
|
|
196
216
|
},
|
|
197
217
|
|
|
198
218
|
async releaseDelivery(claim: DeliveryClaim): Promise<void> {
|
|
199
|
-
await
|
|
219
|
+
await run(session(), SQL_RELEASE, [claim.bindingId, claim.key, claim.leaseUntil])
|
|
200
220
|
},
|
|
201
221
|
})
|
|
202
222
|
}
|
package/src/framework.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// hands the framework the locator its access check uses. Browser- and Worker-safe: the Worker adapter imports `boot`.
|
|
4
4
|
|
|
5
5
|
import type { DataAccess } from './orm'
|
|
6
|
-
import { frameworkSideOf, type FrameworkTables, type Locator } from './registry'
|
|
6
|
+
import { frameworkSideOf, type FrameworkTables, type Locator, type ProvisionalBinding } from './registry'
|
|
7
7
|
import type { DataLayerRuntime } from './store'
|
|
8
8
|
|
|
9
9
|
export type { Admissions } from './admissions'
|
|
@@ -21,9 +21,10 @@ export {
|
|
|
21
21
|
export type { FileBinding } from './file-columns'
|
|
22
22
|
export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
|
|
23
23
|
export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
|
|
24
|
-
export type { JobLeases, JobLeaseState, JobOutcome, OverdueClaim } from './job-leases'
|
|
24
|
+
export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
|
|
25
|
+
export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
|
|
25
26
|
export type { DataAccess, DataHandles, DataSite } from './orm'
|
|
26
|
-
export type { FrameworkTables, Locator } from './registry'
|
|
27
|
+
export type { FrameworkTables, Locator, ProvisionalBinding } from './registry'
|
|
27
28
|
export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
|
|
28
29
|
export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files'
|
|
29
30
|
|
|
@@ -37,6 +38,14 @@ export function isScopedDatabase(value: unknown): boolean {
|
|
|
37
38
|
* reach. Throws for any other value and for a layer that is already connected.
|
|
38
39
|
*/
|
|
39
40
|
export function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): Locator {
|
|
41
|
+
return bindScopedDatabaseProvisionally(value, runtime).locate
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Connects the layer like `bindScopedDatabase`, and answers with its locator the `release` that disconnects it again:
|
|
46
|
+
* a boot that fails releases the layer, so a later boot of the same application binds it. Throws as that does.
|
|
47
|
+
*/
|
|
48
|
+
export function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding {
|
|
40
49
|
const side = frameworkSideOf(value)
|
|
41
50
|
if (side === undefined) {
|
|
42
51
|
throw new TypeError('not a data layer scoped(tables) created')
|
|
@@ -45,8 +54,8 @@ export function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): L
|
|
|
45
54
|
}
|
|
46
55
|
|
|
47
56
|
/**
|
|
48
|
-
* The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and
|
|
49
|
-
* admission counters. Each operation needs the layer bound first. Throws for any other value.
|
|
57
|
+
* The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
|
|
58
|
+
* the admission counters. Each operation needs the layer bound first. Throws for any other value.
|
|
50
59
|
*/
|
|
51
60
|
export function frameworkTablesOf(value: unknown): FrameworkTables {
|
|
52
61
|
const side = frameworkSideOf(value)
|
package/src/guard.ts
CHANGED
|
@@ -262,6 +262,14 @@ function checkNode(node: OperationNode, parent: Visit | undefined, context: Guar
|
|
|
262
262
|
return
|
|
263
263
|
case 'TableNode':
|
|
264
264
|
return checkTable(node, parent, context)
|
|
265
|
+
case 'OrderByItemNode': {
|
|
266
|
+
// Kysely prints `nulls` as raw text; the layer only ever states the order Postgres has by default.
|
|
267
|
+
const nulls = read(node, 'nulls')
|
|
268
|
+
if (nulls !== undefined && nulls !== 'first' && nulls !== 'last') {
|
|
269
|
+
throw new QueryRefusedError('statement_shape', 'an order term states nulls first or nulls last, nothing else')
|
|
270
|
+
}
|
|
271
|
+
return
|
|
272
|
+
}
|
|
265
273
|
case 'JoinNode':
|
|
266
274
|
return checkJoin(node, context)
|
|
267
275
|
case 'ReferenceNode':
|
package/src/index.ts
CHANGED
|
@@ -13,7 +13,15 @@ export type {
|
|
|
13
13
|
WithinGrant,
|
|
14
14
|
} from './capability'
|
|
15
15
|
export { MAX_WITHIN_VALUES } from './capability'
|
|
16
|
-
export {
|
|
16
|
+
export {
|
|
17
|
+
applicationSchema,
|
|
18
|
+
Database,
|
|
19
|
+
type DatabaseEngine,
|
|
20
|
+
type Executor,
|
|
21
|
+
type SqlDialect,
|
|
22
|
+
type TransactionOptions,
|
|
23
|
+
type TransactionRunner,
|
|
24
|
+
} from './database'
|
|
17
25
|
export type {
|
|
18
26
|
AllowedOperator,
|
|
19
27
|
ComparisonOperator,
|