@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.
@@ -59,5 +59,15 @@ export declare function claimNode(state: SelectState, columns: readonly string[]
59
59
  readonly now: Date;
60
60
  readonly maxAttempts: number;
61
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;
62
72
  /** `select <columns> from table where scope for update`: a mutation's precondition read of its own target. */
63
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`. */
@@ -2,6 +2,7 @@ import type { Admissions } from './admissions';
2
2
  import type { Session } from './database';
3
3
  import type { WebhookTables } from './framework-tables';
4
4
  import type { JobLeases } from './job-leases';
5
+ import type { JobWakes } from './job-wakes';
5
6
  import type { DataAccess } from './orm';
6
7
  import type { DataLayerRuntime, TableContext, TableProbe } from './store';
7
8
  import type { StoredFiles } from './stored-files';
@@ -14,6 +15,8 @@ export type Locator = (dimension: string, id: string, using?: Session) => Promis
14
15
  export interface FrameworkTables {
15
16
  readonly webhooks: WebhookTables;
16
17
  readonly jobs: JobLeases;
18
+ /** A job's durable pending work (`fabrika_wakes`), which follows its lease, and the scheduler's next wake over both. */
19
+ readonly wakes: JobWakes;
17
20
  /** A procedure's admission buckets, the challenge tokens it accepted and its byte budget. */
18
21
  readonly admissions: Admissions;
19
22
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */
@@ -2,8 +2,15 @@ import { z } from 'zod/v4';
2
2
  import { type Session } from './database';
3
3
  /** What a site declares: `'read'` runs queries only, `'write'` also `INSERT`, `UPDATE` and `DELETE`. */
4
4
  export type SqlMode = 'read' | 'write';
5
- /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers (an array). */
5
+ /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers. */
6
6
  export type SqlValue = string | number | boolean | bigint | Date | null | readonly (string | number)[];
7
+ /** The database a statement is classified for: Postgres in the application's schema, or a Durable Object's SQLite. */
8
+ export type SqlDatabase = {
9
+ readonly dialect: 'postgres';
10
+ readonly schema: string;
11
+ } | {
12
+ readonly dialect: 'sqlite';
13
+ };
7
14
  /** One test of a capability's scope on a table: the column holds the value, or one of the list. */
8
15
  export interface ScopeTest {
9
16
  readonly column: string;
@@ -11,21 +18,20 @@ export interface ScopeTest {
11
18
  }
12
19
  /** A capability's predicate on one table: every row (`'all'`), or an OR of AND groups; no group matches nothing. */
13
20
  export type ScopeTerms = 'all' | readonly (readonly ScopeTest[])[];
14
- /** What a fragment's table is to its statement: read, or the target of its UPDATE or DELETE. */
21
+ /** What a fragment's table is to its statement, as its author states it: read, or the target of an UPDATE or DELETE. */
15
22
  export type ScopeUse = 'read' | 'update' | 'delete';
23
+ /** The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not reach it. */
24
+ export type ScopeOf = (capability: unknown, table: string, use: ScopeUse) => ScopeTerms;
25
+ /** The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. */
26
+ export interface SqlScopeOptions {
27
+ /** The table's name in the statement; the table's own name by default. */
28
+ readonly alias?: string;
29
+ /** `'update'` or `'delete'` where the statement writes the table, which needs that operation's action; `'read'` by default. */
30
+ readonly use?: ScopeUse;
31
+ }
16
32
  /**
17
- * The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not
18
- * reach it for that use. `assigned` is the columns an UPDATE's SET names (none when the SET cannot be read with
19
- * certainty), and `undefined` before a statement is known.
20
- */
21
- export type ScopeOf = (capability: unknown, table: string, use: ScopeUse, assigned?: readonly string[]) => ScopeTerms;
22
- /** The operation a write statement performs on one of its targets. */
23
- export type WriteOperation = 'insert' | 'update' | 'delete';
24
- /** Throws for a table no statement may write with `operation`: a reference table. */
25
- export type WriteTarget = (table: string, operation: WriteOperation) => void;
26
- /**
27
- * `ctx.sql.scope(capability, table, alias?)`: the capability's whole predicate on one table, as SQL with bound values.
28
- * A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
33
+ * `ctx.sql.scope(capability, table, { alias, use })`: the capability's whole predicate on one table, as SQL with bound
34
+ * values. A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
29
35
  * methods captured at load, so no object an application builds or changes is ever taken for one.
30
36
  */
31
37
  export interface SqlScope {
@@ -34,7 +40,7 @@ export interface SqlScope {
34
40
  /** `ctx.sql(Row)`: the tag for rows of `Row`, and `scope` for the capability's predicate inside its text. */
35
41
  export interface SqlTag {
36
42
  <S extends z.core.$ZodType>(row: S): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<z.output<S>[]>;
37
- scope(capability: unknown, table: string, alias?: string): SqlScope;
43
+ scope(capability: unknown, table: string, options?: SqlScopeOptions): SqlScope;
38
44
  }
39
45
  /** The site a tag is made for: its mode, its binding to the invocation, and the session its statements run in. */
40
46
  export interface SqlSite {
@@ -46,14 +52,16 @@ export interface SqlSite {
46
52
  fail(): void;
47
53
  }
48
54
  /**
49
- * The SQL `parts` make, with `$1…$n` for the values, or a `QueryRefusedError` that names what is refused: more than
50
- * one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for `'write'`), a nested statement of
51
- * another kind, a qualified name outside `schema`, a `fabrika_*` or `pg_*` name, a function call outside the reviewed
52
- * built-ins, and a value placed where it would not be bound.
55
+ * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
56
+ * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
57
+ * `'write'`), a `'read'` statement that writes or locks, a value placed where it would not be bound, and a `fabrika_*`
58
+ * name. On Postgres also a nested statement of another kind, `SELECT … INTO`, a `U&` name, a `pg_*` name, a qualified
59
+ * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
60
+ * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
53
61
  */
54
- export declare function classifySql(parts: readonly string[], mode: SqlMode, schema: string): string;
62
+ export declare function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string;
55
63
  /**
56
64
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
57
65
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
58
66
  */
59
- export declare function sqlTag(site: SqlSite, schema: string | undefined, termsOf: ScopeOf, writeTarget: WriteTarget): SqlTag;
67
+ export declare function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag;
@@ -1,13 +1,21 @@
1
- import { Database } from 'bun:sqlite';
1
+ import { Database, type SQLQueryBindings } from 'bun:sqlite';
2
2
  import type { SqliteStorage } from './sqlite';
3
3
  export interface BunSqliteStorage extends SqliteStorage {
4
4
  /** Runs `fn` in one transaction of its own, as a Durable Object's `storage.transactionSync` does. */
5
5
  transactionSync<T>(fn: () => T): T;
6
6
  }
7
+ /**
8
+ * Runs each statement of `query` in turn and answers the rows of the last one, as a Durable Object's `sql.exec` does.
9
+ * bun:sqlite's `prepare` compiles only the first statement of a text, and its column count cannot tell a migration from a
10
+ * read (`ALTER TABLE … ADD COLUMN … CHECK (…)` reports one column), so the text is split at the end of each compiled
11
+ * statement. `bindings` belong to a text of one statement. Refuses what workerd's SQLite refuses: more than 100 result
12
+ * columns or parameters in one statement.
13
+ */
14
+ export declare function execStatements(database: Database, query: string, bindings?: readonly SQLQueryBindings[]): Record<string, unknown>[];
7
15
  /**
8
16
  * `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
9
17
  * `transaction` runs at a time; one started inside a callback nests in a savepoint, as workerd nests it, and its
10
- * siblings wait for each other. A statement outside one runs at once. A text of several statements runs whole when its
11
- * first statement answers no rows, as a migration's does; otherwise only its first statement runs.
18
+ * siblings wait for each other. A statement outside one runs at once. A text of several statements runs each of them and
19
+ * answers the rows of the last (`execStatements`).
12
20
  */
13
21
  export declare function bunSqliteStorage(database?: Database): BunSqliteStorage;
@@ -14,6 +14,11 @@ export interface DataLayerRuntime {
14
14
  readonly capabilities: CapabilityAuthority;
15
15
  /** Whether the request running now may only read (an export's); its every statement then runs `READ ONLY`. */
16
16
  readonly readOnly?: () => boolean;
17
+ /**
18
+ * Runs inside the transaction of every change of a job's wakes or lease, after the change: the Cloudflare driver arms
19
+ * the alarm from `wakes.next(transaction)` there, so the alarm commits with the change. A throw rolls the change back.
20
+ */
21
+ readonly projectWakes?: (transaction: Session) => Promise<void>;
17
22
  }
18
23
  /** Empty until the framework connects the layer at boot; every table handle of one `scoped` call shares it. */
19
24
  export interface Connection {
@@ -79,12 +84,13 @@ export declare function reachPredicate(context: TableContext, capability: unknow
79
84
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
80
85
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
81
86
  * its read action for a `Within`, an action `ctx.db.app` lists it for with an `app` capability, and its read action
82
- * for a scoped site's read of an application table. A fragment on the statement's UPDATE or DELETE target needs that
83
- * operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's column
84
- * and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container grant on
85
- * its own column, or every row for `all`); an `app` capability, and a scoped read of an application table, every row.
87
+ * for a scoped site's read of an application table. A fragment its author marks `use: 'update'` or `'delete'` needs
88
+ * that operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's
89
+ * column and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container
90
+ * grant on its own column, or every row for `all`); an `app` capability, and a scoped read of an application table,
91
+ * every row.
86
92
  */
87
- export declare function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse, assigned?: readonly string[]): ScopeTerms;
93
+ export declare function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse): ScopeTerms;
88
94
  /**
89
95
  * A `Ref` of `dimension` whose action updates columns of the table: its update action, or a column's own write action.
90
96
  * Which columns it updates follows from the action (`updatableBy`).
@@ -74,9 +74,13 @@ export interface StoredFiles {
74
74
  promote(id: string, sha256: string, version: string): Promise<boolean>;
75
75
  deferScan(id: string, attempts: number, after: Date): Promise<boolean>;
76
76
  reject(id: string): Promise<boolean>;
77
- /** Objects whose rows a sweep deleted and whose own deletion it did not finish. */
78
- unfinishedDeletions(limit: number): Promise<readonly string[]>;
77
+ /** At most `limit` queued object keys recorded at or before `cutoff` (equality is due), oldest first. */
78
+ dueDeletions(limit: number, cutoff: Date): Promise<readonly string[]>;
79
+ /** Takes a due key out of the queue before its object is deleted; `false` when a cancel or a requeue got there first. */
80
+ claimDeletion(objectKey: string, cutoff: Date): Promise<boolean>;
79
81
  forgetDeletion(objectKey: string): Promise<void>;
82
+ /** Takes `objectKeys` out of the queue, so their objects stay: a restore's rows reference them again. The number taken. */
83
+ cancelDeletions(objectKeys: readonly string[]): Promise<number>;
80
84
  /** Clears the legacy marker of every migrated file that one of `columns` references: it is an ordinary file now. */
81
85
  adoptReferenced(columns: readonly FileColumnRef[]): Promise<number>;
82
86
  /** At most `limit` files past the grace that no column of `columns` references (pending ones included), oldest first. */
@@ -69,15 +69,23 @@ export interface IsolationWorlds {
69
69
  readonly dimension: string;
70
70
  readonly own: WorldRow;
71
71
  readonly other: WorldRow;
72
+ /**
73
+ * Deletes both rows of the table and every row that refers to them, however deep; the containers stay. A case whose
74
+ * rows hold pinned values removes them, so the next case can pin the same values again under a unique index.
75
+ */
76
+ readonly remove: () => Promise<void>;
72
77
  }
73
78
  /** What a test kit seeds through, over its migrated schema. */
74
79
  export interface TestSeeding {
75
80
  /**
76
81
  * Seeds one row of `table` in each of two fresh chains, with every container row a table owns. `values` (column →
77
82
  * value) are written into both rows of `table`: the state an endpoint's precondition needs. A text column keeps its
78
- * marker, so a seed of one, or of a column that places the row, throws.
83
+ * marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
84
+ * `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
85
+ * counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
86
+ * no text column, throws.
79
87
  */
80
- seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>): Promise<IsolationWorlds>;
88
+ seedWorlds<DB, P>(tables: Tables<DB, P>, table: string, values?: Readonly<Record<string, SampleValue>>, pins?: Readonly<Record<string, string>>): Promise<IsolationWorlds>;
81
89
  /**
82
90
  * Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
83
91
  * as given, a text column too, every other column sampled. A value for a stamped column or a file column throws.