@fabrika/db 0.9.0-cloudflare.1 → 0.9.0-cloudflare.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-cloudflare.1",
3
+ "version": "0.9.0-cloudflare.3",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -92,9 +92,9 @@
92
92
  "test": "bun test"
93
93
  },
94
94
  "dependencies": {
95
- "@fabrika/auth-core": "0.9.0-cloudflare.1",
96
- "@fabrika/platform": "0.9.0-cloudflare.1",
97
- "@fabrika/platform-node": "0.9.0-cloudflare.1",
95
+ "@fabrika/auth-core": "0.9.0-cloudflare.3",
96
+ "@fabrika/platform": "0.9.0-cloudflare.3",
97
+ "@fabrika/platform-node": "0.9.0-cloudflare.3",
98
98
  "kysely": "0.29.6",
99
99
  "kysely-postgres-js": "5.0.1",
100
100
  "zod": "^3.25.76"
@@ -5,6 +5,7 @@
5
5
  import { Database } from 'bun:sqlite'
6
6
  import { z } from 'zod/v4'
7
7
  import { CodegenError, type DescribedColumn, type ForeignKeyColumns, type NamedColumn, renderTables, type ScalarType } from './codegen'
8
+ import { execStatements } from './sqlite-bun'
8
9
  import { migrateSqlite, type SqliteMigrationBundle, type SqliteMigrationTarget } from './sqlite-migrate'
9
10
 
10
11
  const STRING: ScalarType = { select: 'string' }
@@ -55,17 +56,8 @@ const foreignKeySchema = z.object({ id: z.number(), seq: z.number(), table: z.st
55
56
  function bunTarget(db: Database): SqliteMigrationTarget {
56
57
  return {
57
58
  exec(query, ...bindings) {
58
- const statement = db.prepare<Record<string, unknown>, (string | number | null)[]>(query)
59
- try {
60
- if (bindings.length > 0 || statement.columnNames.length > 0) {
61
- const rows = statement.all(...bindings)
62
- return { toArray: () => rows }
63
- }
64
- } finally {
65
- statement.finalize()
66
- }
67
- db.run(query)
68
- return { toArray: () => [] }
59
+ const rows = execStatements(db, query, bindings)
60
+ return { toArray: () => rows }
69
61
  },
70
62
  transactionSync: (fn) => db.transaction(fn)(),
71
63
  }
package/src/database.ts CHANGED
@@ -35,6 +35,11 @@ export interface DatabaseEngine {
35
35
  readonly transaction: TransactionRunner
36
36
  /** The application's schema, the connection's `search_path`; `undefined` where the database has none. */
37
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
38
43
  }
39
44
 
40
45
  /**
@@ -180,6 +185,7 @@ export function sessionOf(source: SessionSource): Session {
180
185
  }
181
186
 
182
187
  let executeFixed: (session: Session, compiled: CompiledQuery) => Promise<readonly unknown[]>
188
+ let executeRead: (session: Session, compiled: CompiledQuery) => Promise<readonly unknown[]>
183
189
 
184
190
  /** What a session reports to, and asks, the transaction it runs in. */
185
191
  interface SessionHooks {
@@ -226,6 +232,7 @@ export class Session {
226
232
 
227
233
  static {
228
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
229
236
  }
230
237
 
231
238
  get readOnly(): boolean {
@@ -242,12 +249,12 @@ export class Session {
242
249
  this.#hooks.failed?.()
243
250
  }
244
251
 
245
- async #execute<O>(compiled: CompiledQuery<O>): Promise<{ readonly rows: O[] }> {
252
+ async #execute<O>(compiled: CompiledQuery<O>, executor: Executor = this.#executor): Promise<{ readonly rows: O[] }> {
246
253
  if (this.#hooks.open?.() === false) {
247
254
  throw new QueryRefusedError('ended', 'the transaction of this session has ended; it runs nothing more')
248
255
  }
249
256
  try {
250
- return await this.#executor.executeQuery(compiled)
257
+ return await executor.executeQuery(compiled)
251
258
  } catch (error) {
252
259
  this.#hooks.failed?.()
253
260
  throw databaseError(error)
@@ -571,8 +578,15 @@ export type SqlParameter = string | number | boolean | bigint | null
571
578
 
572
579
  /**
573
580
  * One `ctx.sql` statement, whose text `sql.ts` classified and whose values are bound parameters only. It runs through the
574
- * 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.
575
583
  */
576
- export function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[]): Promise<readonly unknown[]> {
577
- return executeFixed(session, CompiledQuery.raw(text, [...parameters]))
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)
578
592
  }
package/src/errors.ts CHANGED
@@ -51,11 +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(…) stands alone, joined by AND, in a WHERE or JOIN … ON clause of its own invocation',
58
- sql_dialect: 'ctx.sql runs only on Postgres; an application on SQLite (Cloudflare) reads and writes through ctx.db',
57
+ sql_scope: 'ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site',
59
58
  file_scan: "a scan verdict outside the scan job's lease",
60
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',
61
60
  on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action",
package/src/framework.ts CHANGED
@@ -21,7 +21,8 @@ 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
27
  export type { FrameworkTables, Locator, ProvisionalBinding } from './registry'
27
28
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
@@ -53,8 +54,8 @@ export function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLay
53
54
  }
54
55
 
55
56
  /**
56
- * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and the
57
- * 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.
58
59
  */
59
60
  export function frameworkTablesOf(value: unknown): FrameworkTables {
60
61
  const side = frameworkSideOf(value)
package/src/job-leases.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  // The framework's side of `fabrika_job_leases` (`@fabrika/db/migrations`): the lease a job run takes, the generation
2
2
  // and deadline that fence every write of the attempt holding it, and the state of the job's last run; and
3
- // `fabrika_job_kicks`, a kick's pending run. Only
4
- // `@fabrika/app`'s job runner reaches it, through `frameworkTablesOf`. Every time is the database's own clock: two
5
- // containers whose clocks disagree still agree on who holds a lease and when it expires.
3
+ // `fabrika_job_kicks`, a kick's pending run. Each statement that changes a lease runs its projection (the wakes,
4
+ // `job-wakes.ts`) in its own transaction. Only `@fabrika/app`'s job runner reaches it, through `frameworkTablesOf`.
5
+ // Every time is the database's own clock: two containers whose clocks disagree still agree on who holds a lease and
6
+ // when it expires.
6
7
 
7
8
  import type { LeaseFence } from './capability'
8
9
  import { runFixedStatement, type Session, sessionOf, type SqlDialect } from './database'
9
10
  import { DatabaseError, LeaseLostError, QueryRefusedError } from './errors'
11
+ import { type FinishWakes, finishWakes } from './job-wakes'
10
12
  import { JOB_KICKS_TABLE, JOB_LEASES_TABLE } from './migrations'
11
13
  import { SQLITE_NOW_FORMAT } from './migrations-sqlite'
12
14
  import type { DataLayerRuntime } from './store'
@@ -61,8 +63,11 @@ export interface JobLeases {
61
63
  * now on. `null` when `fence` no longer holds it.
62
64
  */
63
65
  renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null>
64
- /** Frees the lease and records the run's outcome and duration; `false` when `fence` no longer held it. */
65
- finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean>
66
+ /**
67
+ * Frees the lease and records the run's outcome and duration, and in the same transaction applies `wakes` to the wakes
68
+ * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
69
+ */
70
+ finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>
66
71
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
67
72
  markPending(job: string): Promise<void>
68
73
  /**
@@ -83,6 +88,20 @@ export interface JobLeases {
83
88
  state(job: string): Promise<JobLeaseState | null>
84
89
  }
85
90
 
91
+ /**
92
+ * What a lease statement changed: a crashed holder reaped, a lease taken or handed on, or a run finished with what its
93
+ * wakes become (`null` leaves them).
94
+ */
95
+ export type LeaseChange =
96
+ | { readonly kind: 'reaped' | 'acquired' | 'renewed' }
97
+ | { readonly kind: 'finished'; readonly wakes: FinishWakes | null }
98
+
99
+ /**
100
+ * Runs in the transaction of every lease statement that changed the lease, so a table that follows the lease (the
101
+ * wakes, `job-wakes.ts`) commits with it or not at all. A statement that changed nothing, a lost lease's, runs none.
102
+ */
103
+ export type LeaseProjection = (transaction: Session, job: string, change: LeaseChange) => Promise<void>
104
+
86
105
  /** One framework statement in each dialect's text; a session runs the text of its own. */
87
106
  export type DialectTexts = Readonly<Record<SqlDialect, string>>
88
107
 
@@ -430,8 +449,17 @@ export async function fencedTransaction<T>(session: Session, fence: LeaseFence,
430
449
  }
431
450
  }
432
451
 
433
- export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
452
+ export function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases {
434
453
  const session = () => sessionOf(runtime())
454
+ /** A lease statement and, when it changed the lease, its projection, in one transaction. */
455
+ const changing = (texts: DialectTexts, parameters: readonly (string | number)[], job: string, change: LeaseChange) =>
456
+ session().transaction(async (transaction) => {
457
+ const found = await rows(transaction, texts, parameters)
458
+ if (found.length > 0) {
459
+ await project(transaction, job, change)
460
+ }
461
+ return found
462
+ })
435
463
  return Object.freeze({
436
464
  async now(): Promise<Date> {
437
465
  const [row] = await rows(session(), SQL_NOW, [])
@@ -443,30 +471,38 @@ export function jobLeases(runtime: () => DataLayerRuntime): JobLeases {
443
471
  },
444
472
 
445
473
  async reapCrashed(job: string): Promise<boolean> {
446
- return (await rows(session(), SQL_REAP, [job])).length > 0
474
+ return (await changing(SQL_REAP, [job], job, { kind: 'reaped' })).length > 0
447
475
  },
448
476
 
449
477
  async acquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
450
- const [row] = await rows(session(), SQL_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')])
478
+ const [row] = await changing(SQL_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')], job, {
479
+ kind: 'acquired',
480
+ })
451
481
  return fenceOf(job, holder, row)
452
482
  },
453
483
 
454
484
  async renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
455
- const [row] = await rows(session(), SQL_RENEW, [
456
- ...params(fence),
457
- holder,
458
- milliseconds(leaseMs, 'a lease'),
459
- milliseconds(attemptMs, 'an attempt'),
460
- ])
485
+ const [row] = await changing(
486
+ SQL_RENEW,
487
+ [...params(fence), holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
488
+ fence.job,
489
+ { kind: 'renewed' },
490
+ )
461
491
  return fenceOf(fence.job, holder, row)
462
492
  },
463
493
 
464
- async finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean> {
465
- return (await rows(session(), SQL_FINISH, [...params(fence), outcome])).length > 0
494
+ async finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean> {
495
+ const change: LeaseChange = { kind: 'finished', wakes: finishWakes(outcome, wakes) }
496
+ return (await changing(SQL_FINISH, [...params(fence), outcome], fence.job, change)).length > 0
466
497
  },
467
498
 
468
499
  async tryAcquire(job: string, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null> {
469
- const [row] = await rows(session(), SQL_TRY_ACQUIRE, [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')])
500
+ const [row] = await changing(
501
+ SQL_TRY_ACQUIRE,
502
+ [job, holder, milliseconds(leaseMs, 'a lease'), milliseconds(attemptMs, 'an attempt')],
503
+ job,
504
+ { kind: 'acquired' },
505
+ )
470
506
  return fenceOf(job, holder, row)
471
507
  },
472
508