@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.
Files changed (63) hide show
  1. package/package.json +34 -3
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/capability.ts +5 -0
  5. package/src/codegen-sqlite.ts +146 -0
  6. package/src/codegen.ts +59 -9
  7. package/src/database.ts +227 -61
  8. package/src/errors.ts +2 -2
  9. package/src/file-columns.ts +4 -1
  10. package/src/framework-tables.ts +28 -8
  11. package/src/framework.ts +14 -5
  12. package/src/guard.ts +8 -0
  13. package/src/index.ts +9 -1
  14. package/src/job-leases.ts +210 -54
  15. package/src/job-wakes.ts +450 -0
  16. package/src/links.ts +8 -1
  17. package/src/migrations-sqlite.ts +163 -0
  18. package/src/migrations.ts +25 -0
  19. package/src/nodes.ts +64 -9
  20. package/src/orm-types.ts +2 -2
  21. package/src/orm.ts +68 -35
  22. package/src/policy.ts +8 -2
  23. package/src/postgres.ts +26 -0
  24. package/src/registry.ts +11 -2
  25. package/src/sql.ts +216 -473
  26. package/src/sqlite-bun.ts +149 -0
  27. package/src/sqlite-migrate.ts +242 -0
  28. package/src/sqlite.ts +224 -0
  29. package/src/store.ts +362 -93
  30. package/src/stored-files.ts +188 -52
  31. package/src/tables.ts +16 -0
  32. package/src/temporal.ts +115 -9
  33. package/src/testing-shared.ts +733 -0
  34. package/src/testing-sqlite.ts +513 -0
  35. package/src/testing.ts +169 -482
  36. package/types/src/application-rows.d.ts +58 -0
  37. package/types/src/capability.d.ts +5 -0
  38. package/types/src/codegen-sqlite.d.ts +6 -0
  39. package/types/src/codegen.d.ts +30 -0
  40. package/types/src/database.d.ts +81 -20
  41. package/types/src/errors.d.ts +2 -2
  42. package/types/src/framework.d.ts +11 -5
  43. package/types/src/index.d.ts +1 -1
  44. package/types/src/job-leases.d.ts +32 -4
  45. package/types/src/job-wakes.d.ts +101 -0
  46. package/types/src/migrations-sqlite.d.ts +4 -0
  47. package/types/src/migrations.d.ts +1 -0
  48. package/types/src/nodes.d.ts +13 -2
  49. package/types/src/orm-types.d.ts +2 -2
  50. package/types/src/policy.d.ts +4 -0
  51. package/types/src/postgres.d.ts +12 -0
  52. package/types/src/registry.d.ts +10 -2
  53. package/types/src/sql.d.ts +29 -21
  54. package/types/src/sqlite-bun.d.ts +21 -0
  55. package/types/src/sqlite-migrate.d.ts +28 -0
  56. package/types/src/sqlite.d.ts +24 -0
  57. package/types/src/store.d.ts +26 -9
  58. package/types/src/stored-files.d.ts +6 -2
  59. package/types/src/tables.d.ts +10 -0
  60. package/types/src/temporal.d.ts +21 -0
  61. package/types/src/testing-shared.d.ts +201 -0
  62. package/types/src/testing-sqlite.d.ts +22 -0
  63. package/types/src/testing.d.ts +2 -93
@@ -0,0 +1,58 @@
1
+ import { type ForeignKey, type TableModels } from './policy';
2
+ /** Why the values of a set of application rows cannot be seeded as given. */
3
+ export type ApplicationRowRefusal =
4
+ /** `table` is no application table: `mode` is its scope mode, or `null` when no policy names it. */
5
+ {
6
+ readonly kind: 'table';
7
+ readonly table: string;
8
+ readonly mode: string | null;
9
+ }
10
+ /** `column` is no column of `table`'s column list. */
11
+ | {
12
+ readonly kind: 'column';
13
+ readonly table: string;
14
+ readonly column: string;
15
+ }
16
+ /** `column` is the row's key, version or creator, which the seeding stamps. */
17
+ | {
18
+ readonly kind: 'stamped';
19
+ readonly table: string;
20
+ readonly column: string;
21
+ }
22
+ /** `column` is a file column, which the seeding fills with a live, scanned file. */
23
+ | {
24
+ readonly kind: 'file';
25
+ readonly table: string;
26
+ readonly column: string;
27
+ }
28
+ /** `column` is given an array or an object, where a column takes one value. */
29
+ | {
30
+ readonly kind: 'value';
31
+ readonly table: string;
32
+ readonly column: string;
33
+ readonly given: 'array' | 'object';
34
+ }
35
+ /** The values give `columns`, some but not all columns of the foreign key `key`. */
36
+ | {
37
+ readonly kind: 'partial-key';
38
+ readonly table: string;
39
+ readonly columns: readonly string[];
40
+ readonly key: ForeignKey;
41
+ }
42
+ /** The foreign keys that link `tables` form a cycle, so no order seeds each after the rows it links to. */
43
+ | {
44
+ readonly kind: 'cycle';
45
+ readonly tables: readonly string[];
46
+ };
47
+ export interface ApplicationRowsPlan {
48
+ /** The application tables, each after every given table it links to. */
49
+ readonly order: readonly string[];
50
+ /** Each application table's foreign keys to another given table that the values leave to the link. */
51
+ readonly links: Readonly<Record<string, readonly ForeignKey[]>>;
52
+ /** Every refusal, by table then column; a cycle last. Empty when the rows can be seeded. */
53
+ readonly refusals: readonly ApplicationRowRefusal[];
54
+ }
55
+ /** The plan of seeding one row of each table `rows` names (table → column → value). */
56
+ export declare function planApplicationRows(models: TableModels, rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>): ApplicationRowsPlan;
57
+ /** A refusal in the words both the checker and the test kit use, so the two never describe one rule differently. */
58
+ export declare function applicationRowRefusalText(refusal: ApplicationRowRefusal): string;
@@ -70,6 +70,11 @@ export interface WithinGrant {
70
70
  * every statement judges a row by the chain columns it carries now: a scope moved out of a container is out.
71
71
  */
72
72
  readonly containers: readonly ContainerGrant[];
73
+ /**
74
+ * The dimensions inside `dimension` (the listed object's own and the containers between) in which the caller holds
75
+ * the action: a row that lies in one of their values is listed, as a single-object read of it is allowed.
76
+ */
77
+ readonly contained: readonly ContainerGrant[];
73
78
  }
74
79
  /** An `app` endpoint's grant: the action everywhere in the application, which the proxy checked was held globally. */
75
80
  export interface AppGrant {
@@ -0,0 +1,6 @@
1
+ import { type SqliteMigrationBundle } from './sqlite-migrate';
2
+ /**
3
+ * Applies `bundles` (the framework's `fabrika`, then the application's `app`) to a fresh in-memory database and renders
4
+ * the module for `SCHEMA_FILE` from its application tables. Deterministic for given migrations.
5
+ */
6
+ export declare function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<string>;
@@ -2,6 +2,11 @@ import { type DatabaseObject } from '@fabrika/platform-node';
2
2
  import { z } from 'zod/v4';
3
3
  /** Where an application keeps the generated types and column list; committed, never hand-edited. */
4
4
  export declare const SCHEMA_FILE = "src/db/schema.generated.ts";
5
+ /** A column's TypeScript types: what a read returns, and what an insert or update may bind when that differs. */
6
+ export interface ScalarType {
7
+ readonly select: string;
8
+ readonly write?: string;
9
+ }
5
10
  export declare class CodegenError extends Error {
6
11
  name: string;
7
12
  }
@@ -41,12 +46,37 @@ export interface Catalog {
41
46
  export declare function introspectSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<readonly CatalogColumn[]>;
42
47
  /** `introspectSchema`, with the foreign keys between the schema's tables. */
43
48
  export declare function introspectCatalog(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<Catalog>;
49
+ /** What the renderer needs of a column beyond its name, whichever database it was read from. */
50
+ export interface DescribedColumn {
51
+ readonly scalar: ScalarType;
52
+ readonly nullable: boolean;
53
+ readonly generated: 'no' | 'default' | 'always';
54
+ /** The column list field that names the column: a day, a timestamp, or (on SQLite) a boolean. */
55
+ readonly list: 'dates' | 'timestamps' | 'booleans' | undefined;
56
+ }
57
+ /** A foreign key as the renderer reads it: the columns of `table_name` that reference `referenced_table`. */
58
+ export interface ForeignKeyColumns {
59
+ readonly table_name: string;
60
+ readonly columns: readonly string[];
61
+ readonly referenced_table: string;
62
+ readonly referenced_columns: readonly string[];
63
+ }
64
+ /** A column as the renderer groups it, before its type is described. */
65
+ export interface NamedColumn {
66
+ readonly table_name: string;
67
+ readonly column_name: string;
68
+ }
44
69
  /**
45
70
  * The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take, and the
46
71
  * runtime column list with each table's foreign keys to application tables. Deterministic for a given catalog, so
47
72
  * `fabrika db codegen --verify` can compare text.
48
73
  */
49
74
  export declare function renderSchema(catalog: readonly CatalogColumn[], foreignKeys?: readonly CatalogForeignKey[]): string;
75
+ /**
76
+ * `renderSchema` over columns of any database: `describe` gives each column's types and list field, and refuses a
77
+ * type the data layer does not read. A foreign key's `constraint_name` is not rendered; keys keep the given order.
78
+ */
79
+ export declare function renderTables<C extends NamedColumn>(catalog: readonly C[], foreignKeys: readonly ForeignKeyColumns[], describe: (column: C) => DescribedColumn): string;
50
80
  /** Introspects the migrated schema, checked against the migrations' manifest, and renders the module for `SCHEMA_FILE`. */
51
81
  export declare function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<string>;
52
82
  export {};
@@ -1,30 +1,64 @@
1
- import { type Dialect, Kysely, type RootOperationNode } from 'kysely';
1
+ import { type Dialect, Kysely, type QueryCompiler, type RootOperationNode } from 'kysely';
2
2
  import { type GuardContext } from './guard';
3
- type LooseDB = Record<string, Record<string, unknown>>;
4
- type Executor = Pick<Kysely<LooseDB>, 'executeQuery'>;
3
+ export type LooseDB = Record<string, Record<string, unknown>>;
4
+ /** What a statement runs on: the database's own executor, or the one of the transaction it runs in. */
5
+ export type Executor = Pick<Kysely<LooseDB>, 'executeQuery'>;
6
+ /** The SQL a database speaks: Postgres on Bun, SQLite in a Cloudflare Durable Object (ADR-0065). */
7
+ export type SqlDialect = 'postgres' | 'sqlite';
8
+ export interface TransactionOptions {
9
+ /**
10
+ * A `READ ONLY` transaction on Postgres. SQLite opens none: each statement runs in a transaction of its own, which
11
+ * rolls back a statement that wrote. A read-only session refuses writes either way.
12
+ */
13
+ readonly readOnly: boolean;
14
+ /** How long the transaction may sit idle before the database ends it; a database without the setting ignores it. */
15
+ readonly idleTimeoutMs?: number;
16
+ }
17
+ /**
18
+ * Runs `body` in one transaction, on the executor it hands it: commits when `body` resolves, rolls back when it
19
+ * rejects, and rejects with `body`'s error. Its BEGIN, COMMIT and ROLLBACK failures reject with the driver's error.
20
+ */
21
+ export type TransactionRunner = <T>(options: TransactionOptions, body: (executor: Executor) => Promise<T>) => Promise<T>;
22
+ /** What a `Database` runs on: the driver, the compiler of its dialect, and how it opens a transaction. */
23
+ export interface DatabaseEngine {
24
+ readonly dialect: SqlDialect;
25
+ readonly kysely: Kysely<LooseDB>;
26
+ /** Compiles every guarded tree; frozen, since a patch to it after the guard ran would bypass the guard. */
27
+ readonly compiler: QueryCompiler;
28
+ readonly transaction: TransactionRunner;
29
+ /** The application's schema, the connection's `search_path`; `undefined` where the database has none. */
30
+ readonly schema?: string;
31
+ /**
32
+ * SQLite's: runs each statement in a transaction of its own (a savepoint inside an open one) and refuses, rolling it
33
+ * back, one that wrote. A `ctx.sql` site that declares `'read'` runs on it in a writable invocation too.
34
+ */
35
+ readonly reads?: Executor;
36
+ }
37
+ /**
38
+ * The compiler turns the guarded tree into SQL, so a patch to it after the guard ran would bypass the guard.
39
+ * Freezing it when this module loads, before application modules, makes such a patch throw instead.
40
+ */
41
+ export declare function freezePrototypeChain(object: object): void;
5
42
  /**
6
43
  * `app_<id>`, the schema an application's migrations create (ADR-0017). `@fabrika/platform-node`'s
7
44
  * `applicationDatabaseSchema` derives the same name for the migration runner; the two must agree.
8
45
  */
9
46
  export declare function applicationSchema(appId: string): string;
10
- export interface PostgresOptions {
11
- readonly url: string;
12
- /** The application's schema (`app_<id>`), set as the connection's `search_path`. */
13
- readonly schema: string;
14
- readonly max?: number;
15
- }
16
47
  /** The connection the data layer runs on. It has no public query method: everything goes through a store. */
17
48
  export declare class Database {
18
49
  #private;
19
50
  private constructor();
20
51
  /**
21
- * Over `Bun.SQL` with `prepare: false`: Bun otherwise keeps one prepared statement per distinct SQL text per
22
- * connection, and `in` lists of different lengths make that grow without bound.
52
+ * Any Kysely Postgres dialect: `@fabrika/db/postgres` opens Bun.SQL through it, tests use one that records statements
53
+ * instead of sending them.
23
54
  */
24
- static postgres(options: PostgresOptions): Database;
25
- /** Any Kysely Postgres dialect; tests use one that records statements instead of sending them. */
26
- static fromDialect(dialect: Dialect): Database;
27
- /** The application's schema, the connection's `search_path`; `undefined` over a bare dialect. */
55
+ static fromDialect(dialect: Dialect, options?: {
56
+ readonly schema?: string;
57
+ }): Database;
58
+ /** A database of another dialect (`@fabrika/db/sqlite`), with its own frozen compiler and transaction runner. */
59
+ static fromEngine(engine: DatabaseEngine): Database;
60
+ get dialect(): SqlDialect;
61
+ /** The application's schema, the connection's `search_path`; `undefined` over a bare dialect and on SQLite. */
28
62
  get schema(): string | undefined;
29
63
  close(): Promise<void>;
30
64
  }
@@ -58,8 +92,10 @@ interface SessionHooks {
58
92
  */
59
93
  export declare class Session {
60
94
  #private;
61
- constructor(executor: Executor, kysely: Kysely<LooseDB> | undefined, readOnly: boolean, hooks?: SessionHooks);
95
+ constructor(executor: Executor, engine: DatabaseEngine, inTransaction: boolean, readOnly: boolean, hooks?: SessionHooks);
62
96
  get readOnly(): boolean;
97
+ /** The dialect of the database this session runs on: a framework statement picks its text by it. */
98
+ get dialect(): SqlDialect;
63
99
  /** Fails the transaction this session runs in, so it commits nothing: a statement refused before it was sent. */
64
100
  fail(): void;
65
101
  run<O>(node: RootOperationNode, context: GuardContext): Promise<O[]>;
@@ -72,6 +108,17 @@ export declare class Session {
72
108
  }
73
109
  /** How long an invocation's transaction may sit idle before Postgres ends it, and its connection with it. */
74
110
  export declare const INVOCATION_IDLE_TIMEOUT_MS = 30000;
111
+ /** A writing invocation that holds its object's storage transaction longer than this logs one line. */
112
+ export declare const TRANSACTION_HELD_LOG_MS = 1000;
113
+ /** A writing invocation that holds its object's storage transaction longer than this is also reported. */
114
+ export declare const TRANSACTION_HELD_REPORT_MS = 5000;
115
+ /** Where an enclosure tells how long it held its object: every other event of the object waited that long. */
116
+ export interface HoldWatch {
117
+ /** The site the invocation serves, which the log line names. */
118
+ readonly site: string;
119
+ /** Hears a hold longer than `TRANSACTION_HELD_REPORT_MS`, in whole ms. */
120
+ readonly held: (heldMs: number) => void;
121
+ }
75
122
  /**
76
123
  * The one transaction of an invocation (a request, a webhook delivery): opened by its first statement, then ended
77
124
  * once by the framework — committed after the handler returned and its output passed validation, rolled back
@@ -81,7 +128,8 @@ export declare const INVOCATION_IDLE_TIMEOUT_MS = 30000;
81
128
  */
82
129
  export declare class InvocationTransaction {
83
130
  #private;
84
- constructor(database: Database, readOnly: boolean);
131
+ /** `now` is the clock an enclosure's hold is measured by. */
132
+ constructor(database: Database, readOnly: boolean, now?: () => number);
85
133
  /** A `READ ONLY` transaction: a query's or an export's. */
86
134
  get readOnly(): boolean;
87
135
  /** Whether the transaction was opened: an invocation that reached no data commits nothing. */
@@ -92,6 +140,18 @@ export declare class InvocationTransaction {
92
140
  get ended(): boolean;
93
141
  /** Its connection is back in the pool (or it never took one). */
94
142
  get released(): boolean;
143
+ /**
144
+ * Runs `work`: the invocation from its handler to its `commit()`. On SQLite a writing invocation's transaction
145
+ * encloses `work`, opened before it: a Durable Object's transaction holds back every other event, the answers to the
146
+ * object's own I/O included, until its callback ends, so the handler runs inside it. There `commit()` and `rollback()`
147
+ * decide, the COMMIT runs once `work` returned, and a failed COMMIT rejects with a `DatabaseError`. A read-only
148
+ * invocation, and every invocation elsewhere, runs `work` as is: a read-only one on SQLite holds no storage
149
+ * transaction, so the object serves other events while it awaits.
150
+ *
151
+ * Only the SQLite enclosure is measured for `watch`, from entering the transaction until it settled: it holds the
152
+ * whole object, where a Postgres transaction holds one pooled connection and other requests go on.
153
+ */
154
+ enclose<T>(work: () => Promise<T>, watch: HoldWatch): Promise<T>;
95
155
  /** The session the invocation's statements run in; the first call opens the transaction. */
96
156
  session(): Promise<Session>;
97
157
  /**
@@ -100,7 +160,7 @@ export declare class InvocationTransaction {
100
160
  * `DatabaseError`, after the connection is back in the pool.
101
161
  */
102
162
  commit(): Promise<void>;
103
- /** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back. */
163
+ /** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back (inside `enclose`, it only decides). */
104
164
  rollback(): Promise<void>;
105
165
  }
106
166
  /**
@@ -118,7 +178,8 @@ export declare function runFixedStatement(session: Session, text: string, parame
118
178
  export type SqlParameter = string | number | boolean | bigint | null;
119
179
  /**
120
180
  * One `ctx.sql` statement, whose text `sql.ts` classified and whose values are bound parameters only. It runs through the
121
- * session's one path to the connection, so a statement the database refuses fails the invocation it runs in.
181
+ * session's one path to the connection, so a statement the database refuses fails the invocation it runs in. A `'read'`
182
+ * statement runs on the engine's `reads` where it has one (SQLite), so one that wrote is refused and rolled back.
122
183
  */
123
- export declare function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[]): Promise<readonly unknown[]>;
184
+ export declare function runApplicationStatement(session: Session, text: string, parameters: readonly SqlParameter[], mode: 'read' | 'write'): Promise<readonly unknown[]>;
124
185
  export {};
@@ -44,10 +44,10 @@ export declare const QUERY_REFUSALS: {
44
44
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
45
45
  readonly sql_statement: "ctx.sql runs one statement of an admitted kind, and none inside another";
46
46
  readonly sql_read_only: "sql: 'read' runs queries only; declare sql: 'write' on a mutation, a job or a webhook";
47
- readonly sql_name: "ctx.sql names a framework, catalog or foreign-schema object, or writes a name in U& form";
47
+ readonly sql_name: "ctx.sql names a framework (fabrika_*), catalog (pg_*, sqlite_*) or foreign-schema object, or writes a name in U& form";
48
48
  readonly sql_function: "ctx.sql calls a function that is not a reviewed built-in";
49
49
  readonly sql_outside_transaction: "a job runs ctx.sql only inside ctx.transaction((tx) => …), as tx.sql";
50
- readonly sql_scope: "ctx.sql.scope(…) stands alone, joined by AND, in a WHERE or JOIN … ON clause of its own invocation";
50
+ readonly sql_scope: "ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site";
51
51
  readonly file_scan: "a scan verdict outside the scan job's lease";
52
52
  readonly 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";
53
53
  readonly on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action";
@@ -1,5 +1,5 @@
1
1
  import type { DataAccess } from './orm';
2
- import { type FrameworkTables, type Locator } from './registry';
2
+ import { type FrameworkTables, type Locator, type ProvisionalBinding } from './registry';
3
3
  import type { DataLayerRuntime } from './store';
4
4
  export type { Admissions } from './admissions';
5
5
  export type { LeaseFence } from './capability';
@@ -8,9 +8,10 @@ export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, LeaseLo
8
8
  export type { FileBinding } from './file-columns';
9
9
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references';
10
10
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables';
11
- export type { JobLeases, JobLeaseState, JobOutcome, OverdueClaim } from './job-leases';
11
+ export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
12
+ export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
12
13
  export type { DataAccess, DataHandles, DataSite } from './orm';
13
- export type { FrameworkTables, Locator } from './registry';
14
+ export type { FrameworkTables, Locator, ProvisionalBinding } from './registry';
14
15
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
15
16
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files';
16
17
  /** Whether `value` is an object `scoped(tables)` created, rather than a look-alike with the same fields. */
@@ -21,8 +22,13 @@ export declare function isScopedDatabase(value: unknown): boolean;
21
22
  */
22
23
  export declare function bindScopedDatabase(value: unknown, runtime: DataLayerRuntime): Locator;
23
24
  /**
24
- * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and the
25
- * admission counters. Each operation needs the layer bound first. Throws for any other value.
25
+ * Connects the layer like `bindScopedDatabase`, and answers with its locator the `release` that disconnects it again:
26
+ * a boot that fails releases the layer, so a later boot of the same application binds it. Throws as that does.
27
+ */
28
+ export declare function bindScopedDatabaseProvisionally(value: unknown, runtime: DataLayerRuntime): ProvisionalBinding;
29
+ /**
30
+ * The framework's own writes over the layer `scoped(tables)` created: the webhook tables, the job leases and wakes, and
31
+ * the admission counters. Each operation needs the layer bound first. Throws for any other value.
26
32
  */
27
33
  export declare function frameworkTablesOf(value: unknown): FrameworkTables;
28
34
  /**
@@ -1,6 +1,6 @@
1
1
  export type { AppCapability, AppGrant, CapabilityAuthority, CapabilityGrant, ContainerGrant, LeaseFence, Ref, RefGrant, RowGrant, RowRef, Within, WithinGrant, } from './capability';
2
2
  export { MAX_WITHIN_VALUES } from './capability';
3
- export { applicationSchema, Database, type PostgresOptions } from './database';
3
+ export { applicationSchema, Database, type DatabaseEngine, type Executor, type SqlDialect, type TransactionOptions, type TransactionRunner, } from './database';
4
4
  export type { AllowedOperator, ComparisonOperator, ConditionTuple, ListOperator, NoColumns, NullOperator, PatternOperator, Primitive, ScopedSelect, } from './description';
5
5
  export { CAPABILITY_ERRORS, CapabilityError, type CapabilityErrorReason, DatabaseError, LeaseLostError, PolicyError, QUERY_REFUSALS, type QueryRefusal, QueryRefusedError, } from './errors';
6
6
  export type { AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIndex, IndexedTable, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, Saved, ScopeTarget, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
@@ -1,5 +1,6 @@
1
1
  import type { LeaseFence } from './capability';
2
- import { type Session } from './database';
2
+ import { type Session, type SqlDialect } from './database';
3
+ import { type FinishWakes } from './job-wakes';
3
4
  import type { DataLayerRuntime } from './store';
4
5
  export type JobOutcome = 'succeeded' | 'failed';
5
6
  export interface JobLeaseState {
@@ -48,8 +49,11 @@ export interface JobLeases {
48
49
  * now on. `null` when `fence` no longer holds it.
49
50
  */
50
51
  renew(fence: LeaseFence, holder: string, attemptMs: number, leaseMs: number): Promise<LeaseFence | null>;
51
- /** Frees the lease and records the run's outcome and duration; `false` when `fence` no longer held it. */
52
- finish(fence: LeaseFence, outcome: JobOutcome): Promise<boolean>;
52
+ /**
53
+ * Frees the lease and records the run's outcome and duration, and in the same transaction applies `wakes` to the wakes
54
+ * the run owned (`job-wakes.ts`). `false` when `fence` no longer held it: then nothing is applied.
55
+ */
56
+ finish(fence: LeaseFence, outcome: JobOutcome, wakes?: FinishWakes): Promise<boolean>;
53
57
  /** Records that a kick arrived: the run that started before it runs the job once more. Never waits on the lease. */
54
58
  markPending(job: string): Promise<void>;
55
59
  /**
@@ -69,6 +73,29 @@ export interface JobLeases {
69
73
  cancelInFlight(fence: LeaseFence): Promise<void>;
70
74
  state(job: string): Promise<JobLeaseState | null>;
71
75
  }
76
+ /**
77
+ * What a lease statement changed: a crashed holder reaped, a lease taken or handed on, or a run finished with what its
78
+ * wakes become (`null` leaves them).
79
+ */
80
+ export type LeaseChange = {
81
+ readonly kind: 'reaped' | 'acquired' | 'renewed';
82
+ } | {
83
+ readonly kind: 'finished';
84
+ readonly wakes: FinishWakes | null;
85
+ };
86
+ /**
87
+ * Runs in the transaction of every lease statement that changed the lease, so a table that follows the lease (the
88
+ * wakes, `job-wakes.ts`) commits with it or not at all. A statement that changed nothing, a lost lease's, runs none.
89
+ */
90
+ export type LeaseProjection = (transaction: Session, job: string, change: LeaseChange) => Promise<void>;
91
+ /** One framework statement in each dialect's text; a session runs the text of its own. */
92
+ export type DialectTexts = Readonly<Record<SqlDialect, string>>;
93
+ /** SQLite's clock, as a stored timestamp: ISO text, so a comparison of two is a text comparison. */
94
+ export declare const SQLITE_NOW = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
95
+ /** SQLite's clock moved by `ms`, an SQL expression of milliseconds (negative is earlier). */
96
+ export declare function sqliteNowPlus(ms: string): string;
97
+ /** A stored SQLite timestamp (`SQLITE_NOW_FORMAT`) as a `Date`, or `null`; anything else is refused. */
98
+ export declare function sqliteTimestamp(value: unknown, what: string): Date | null;
72
99
  /**
73
100
  * The database's clock inside `session`'s transaction: a queue claim compares and moves `due` by it, so no process
74
101
  * clock decides when a row is due.
@@ -79,6 +106,7 @@ export declare function databaseNow(session: Session): Promise<Date>;
79
106
  * stays locked `for share` until the commit (a takeover or a renewal waits), and every statement is bounded by the
80
107
  * attempt's remaining time. After it, just before the commit: the attempt still holds the lease within its deadline.
81
108
  * Otherwise the transaction rolls back with `LeaseLostError`; so does a statement the deadline or the runner cancelled.
109
+ * On SQLite only the two checks run: no other event reaches the Durable Object while the transaction is open.
82
110
  */
83
111
  export declare function fencedTransaction<T>(session: Session, fence: LeaseFence, work: (transaction: Session) => Promise<T>): Promise<T>;
84
- export declare function jobLeases(runtime: () => DataLayerRuntime): JobLeases;
112
+ export declare function jobLeases(runtime: () => DataLayerRuntime, project: LeaseProjection): JobLeases;
@@ -0,0 +1,101 @@
1
+ import type { LeaseFence } from './capability';
2
+ import { type Session } from './database';
3
+ import type { JobOutcome, LeaseProjection } from './job-leases';
4
+ import type { DataLayerRuntime } from './store';
5
+ export declare const WAKE_REASONS: readonly ["cron", "kick", "claim", "retry"];
6
+ export type WakeReason = (typeof WAKE_REASONS)[number];
7
+ export interface NewWake {
8
+ readonly job: string;
9
+ readonly reason: WakeReason;
10
+ readonly dueAt: Date;
11
+ /** Wakes under one key are one row: `cron:<job>:<expr>`, `claim:<job>`, `kick:<job>:<due second>`. */
12
+ readonly dedupe?: string;
13
+ }
14
+ export interface Wake {
15
+ readonly id: string;
16
+ readonly job: string;
17
+ readonly reason: WakeReason;
18
+ readonly dueAt: Date;
19
+ /** How many failed runs moved this wake (`retry`). */
20
+ readonly attempt: number;
21
+ readonly dedupe: string | null;
22
+ /** Taken by the run that holds its job's lease, when that run took it: that run's finish consumes or retries it. */
23
+ readonly owned: boolean;
24
+ }
25
+ /**
26
+ * What a run's finish does with the wakes it owned (those due when it took the lease), applied in the finish's
27
+ * transaction and only when the finish still held the lease. Without one, a success is `completed` and a failure
28
+ * leaves the wakes as they are.
29
+ */
30
+ export type FinishWakes =
31
+ /** The run is done with them: they are consumed, then the job's next cron run is scheduled (`cron:<job>:<expression>`). */
32
+ {
33
+ readonly kind: 'completed';
34
+ readonly nextCron?: {
35
+ readonly expression: string;
36
+ readonly dueAt: Date;
37
+ };
38
+ }
39
+ /** The run failed and runs again: they move to `at`, and their attempt counts up. Only with a failed outcome. */
40
+ | {
41
+ readonly kind: 'retry';
42
+ readonly at: Date;
43
+ };
44
+ export interface JobWakes {
45
+ /**
46
+ * Records a pending wake, in `using` when given (the transaction of the write it belongs to). A key already pending
47
+ * keeps one row at the earlier due time: a later wake never postpones an earlier one. A merge takes the row from the
48
+ * run that owns it, except a cron wake's, whose next fire that run's finish schedules. Answers the row that holds it;
49
+ * a key another job holds is refused.
50
+ */
51
+ schedule(wake: NewWake, using?: Session): Promise<Wake>;
52
+ /** The pending wakes of `job`, earliest first. */
53
+ pending(job: string): Promise<readonly Wake[]>;
54
+ /**
55
+ * When the scheduler wakes next: the earliest due wake of a job whose lease is free or expired, or the expiry of a
56
+ * held lease (its deadman), whichever is earlier; `null` when neither exists. It may be past. Read in `using` when given.
57
+ */
58
+ next(using?: Session): Promise<Date | null>;
59
+ /** How many milliseconds from the database's now `next` is (0 or less when due), read in `using` when given. */
60
+ untilNext(using?: Session): Promise<number | null>;
61
+ /** The database's clock, read in `using` when given: a wake due now is due by it. */
62
+ now(using?: Session): Promise<Date>;
63
+ /**
64
+ * Deletes the wakes of every job not in `declared`, the jobs the contract declares with their cron expressions, and
65
+ * each declared job's cron wake whose key names another expression; answers how many it deleted.
66
+ */
67
+ reconcile(declared: readonly DeclaredJob[]): Promise<number>;
68
+ /**
69
+ * The test kit's: moves each wake `ids` names that is not yet due to the database's now, so the scheduler takes it
70
+ * now; an overdue one stays. Answers how many it moved. Refused in a process that serves an application.
71
+ */
72
+ hasten(ids: readonly string[]): Promise<number>;
73
+ /**
74
+ * The jobs whose lease a run holds past its expiry, declared or not: a removed job's crashed holder still arms the
75
+ * alarm through `next` until someone reaps it.
76
+ */
77
+ expiredHolders(): Promise<readonly string[]>;
78
+ }
79
+ /** A job the contract declares, and the cron expression its schedule is: its cron wake's key is `cron:<job>:<expression>`. */
80
+ export interface DeclaredJob {
81
+ readonly job: string;
82
+ readonly expression: string;
83
+ }
84
+ /**
85
+ * A finish's instruction checked before its statement runs, with the default filled in: `null` leaves the wakes. The
86
+ * lease store calls it, so a malformed instruction refuses the finish and leaves the lease held.
87
+ */
88
+ export declare function finishWakes(outcome: JobOutcome, wakes: FinishWakes | undefined): FinishWakes | null;
89
+ /**
90
+ * The lease store's projection, all in the lease statement's transaction: a taken lease marks the wakes its run owns, a
91
+ * fenced finish applies its wake instruction to them, a finish or a reap leaves none owned, and every lease change then
92
+ * runs the runtime's projection.
93
+ */
94
+ export declare function leaseProjection(runtime: () => DataLayerRuntime): LeaseProjection;
95
+ /**
96
+ * Sets the claim wake of `fence`'s job to `dueAt`, or removes it for `null`, in `transaction`: the claim's fenced
97
+ * transaction, so the re-arm commits with the rows it leased. The attempt's first claim replaces what an earlier run
98
+ * left; each later claim keeps the earliest re-arm of the attempt.
99
+ */
100
+ export declare function rearmClaim(runtime: DataLayerRuntime, transaction: Session, fence: LeaseFence, dueAt: Date | null): Promise<void>;
101
+ export declare function jobWakes(runtime: () => DataLayerRuntime): JobWakes;
@@ -0,0 +1,4 @@
1
+ import { type FrameworkMigration } from './migrations';
2
+ /** The `strftime` format of a stored timestamp; `strftime(SQLITE_NOW_FORMAT, 'now')` is the database's clock. */
3
+ export declare const SQLITE_NOW_FORMAT = "%Y-%m-%dT%H:%M:%fZ";
4
+ export declare const SQLITE_FRAMEWORK_MIGRATIONS: readonly FrameworkMigration[];
@@ -4,6 +4,7 @@ export declare const WEBHOOK_BINDINGS_TABLE = "fabrika_webhook_bindings";
4
4
  export declare const WEBHOOK_DELIVERIES_TABLE = "fabrika_webhook_deliveries";
5
5
  export declare const JOB_LEASES_TABLE = "fabrika_job_leases";
6
6
  export declare const JOB_KICKS_TABLE = "fabrika_job_kicks";
7
+ export declare const JOB_WAKES_TABLE = "fabrika_wakes";
7
8
  export declare const FORM_ADMISSIONS_TABLE = "fabrika_form_admissions";
8
9
  export declare const FORM_CHALLENGES_TABLE = "fabrika_form_challenges";
9
10
  export declare const FORM_FILES_TABLE = "fabrika_form_files";
@@ -1,5 +1,6 @@
1
1
  import { type DeleteQueryNode, type InsertQueryNode, type OperationNode, ReferenceNode, ReturningNode, type SelectQueryNode, type UpdateQueryNode, WhereNode } from 'kysely';
2
2
  import { type NameSet } from './builtins';
3
+ import type { SqlDialect } from './database';
3
4
  import type { Condition, Primitive, SelectState } from './description';
4
5
  export declare function column(table: string, name: string): ReferenceNode;
5
6
  export declare function equals(table: string, name: string, value: Primitive): OperationNode;
@@ -19,7 +20,7 @@ export declare function scopedWhere(conditions: OperationNode | undefined, scope
19
20
  /** `returning key as id[, version as version]`: a mutation's acknowledgement, never row data. */
20
21
  export declare function acknowledgement(table: string, key: string, version: string | undefined): ReturningNode;
21
22
  /** `after` is a keyset page's position, ANDed to the caller's conditions inside their parenthesis. */
22
- export declare function selectNode(state: SelectState, visible: readonly string[], scope: OperationNode, after?: OperationNode, days?: NameSet): SelectQueryNode;
23
+ export declare function selectNode(state: SelectState, visible: readonly string[], scope: OperationNode, after?: OperationNode, days?: NameSet, dialect?: SqlDialect): SelectQueryNode;
23
24
  export interface AggregateColumns {
24
25
  readonly groupBy: readonly string[];
25
26
  readonly count: boolean;
@@ -57,6 +58,16 @@ export declare function claimNode(state: SelectState, columns: readonly string[]
57
58
  readonly attempts: string;
58
59
  readonly now: Date;
59
60
  readonly maxAttempts: number;
60
- }, scope: OperationNode, days: NameSet): SelectQueryNode;
61
+ }, scope: OperationNode, days: NameSet, dialect?: SqlDialect): SelectQueryNode;
62
+ /**
63
+ * When the same claim next finds a row: `select <due> from table where (<conditions> and (<due> > $now and <attempts> <
64
+ * $max)) and scope order by <due> limit 1`, with `state` the claim's conditions ordered by `<due>`, limited to one.
65
+ */
66
+ export declare function nextClaimNode(state: SelectState, due: {
67
+ readonly due: string;
68
+ readonly attempts: string;
69
+ readonly now: Date;
70
+ readonly maxAttempts: number;
71
+ }, scope: OperationNode, days: NameSet, dialect?: SqlDialect): SelectQueryNode;
61
72
  /** `select <columns> from table where scope for update`: a mutation's precondition read of its own target. */
62
73
  export declare function lockedSelectNode(table: string, columns: readonly string[], scope: OperationNode, days?: NameSet): SelectQueryNode;
@@ -604,8 +604,8 @@ type RefFragment<Ix extends AnyDbIndex, D extends string, A extends string> = {
604
604
  [T in TableName<Ix>]: Ix['tables'][T]['mode'] extends 'app' ? (A extends Ix['tables'][T]['actions']['read'] ? T : never) : D extends Ix['tables'][T]['refs'] ? (A extends NamedActions<Ix['tables'][T]> ? T : never) : never;
605
605
  }[TableName<Ix>];
606
606
  /**
607
- * What a `Within` writes on a `'write'` site: the target of an UPDATE or DELETE whose action it holds, a column's own
608
- * write action included (the statement's SET is checked against its columns at run time).
607
+ * What a `Within` writes on a `'write'` site: the table of a fragment of `use: 'update'` or `'delete'` whose action it
608
+ * holds, a column's own write action included (the statement's columns are the approver's to review, not checked).
609
609
  */
610
610
  type WithinWrites<E extends IndexedTable, M extends 'read' | 'write'> = M extends 'write' ? E['actions']['update'] | E['actions']['delete'] | (keyof E['writes'] & string) : never;
611
611
  /** The tables a fragment of a `Within` of `D` and `A` reaches: those it lists by their read action, or writes on `M`. */
@@ -132,6 +132,8 @@ export interface TableColumns<Col extends string = string, Table extends string
132
132
  readonly dates?: readonly Col[];
133
133
  /** The `timestamp` and `timestamptz` columns, which a write takes as a `Date` or strict ISO 8601 text; absent when none. */
134
134
  readonly timestamps?: readonly Col[];
135
+ /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
136
+ readonly booleans?: readonly Col[];
135
137
  }
136
138
  /** The columns and foreign keys of every table, generated next to the schema types. */
137
139
  export type ColumnList<DB> = {
@@ -202,6 +204,8 @@ export interface TableModel {
202
204
  readonly dates: NameSet;
203
205
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
204
206
  readonly timestamps: NameSet;
207
+ /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
208
+ readonly booleans: NameSet;
205
209
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
206
210
  readonly foreignKeys: readonly ForeignKey[];
207
211
  /**
@@ -0,0 +1,12 @@
1
+ import { Database } from './database';
2
+ export interface PostgresOptions {
3
+ readonly url: string;
4
+ /** The application's schema (`app_<id>`), set as the connection's `search_path`. */
5
+ readonly schema: string;
6
+ readonly max?: number;
7
+ }
8
+ /**
9
+ * Over `Bun.SQL` with `prepare: false`: Bun otherwise keeps one prepared statement per distinct SQL text per
10
+ * connection, and `in` lists of different lengths make that grow without bound.
11
+ */
12
+ export declare function openPostgres(options: PostgresOptions): Database;