durable-db 0.13.3 → 0.14.0

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.
@@ -0,0 +1,104 @@
1
+ //#region src/db/outbox.d.ts
2
+ /** What a message may be: declare it once with `declare global { interface DurableDbOutbox { message: MyMessage } }`. */
3
+ declare global {
4
+ interface DurableDbOutbox {}
5
+ }
6
+ /** The message `ctx.outbox.push()` takes: `DurableDbOutbox['message']` when declared, else any JSON value. */
7
+ type OutboxMessage = DurableDbOutbox extends {
8
+ message: infer M;
9
+ } ? M : unknown;
10
+ /** What an action records messages with. */
11
+ interface Outbox {
12
+ /** Records `message` (a JSON value) for delivery after the action succeeds. */
13
+ push(message: OutboxMessage): void;
14
+ }
15
+ /** A recorded message, as the sink gets it. */
16
+ interface OutboxEnvelope<M = OutboxMessage> {
17
+ message: M;
18
+ /**
19
+ * The database that recorded it: the name `db` commands know it by (the
20
+ * generated class's `databaseName`; a hand-written subclass without one, a
21
+ * name derived from its class name).
22
+ */
23
+ database: string;
24
+ /** The instance key of the Durable Object that recorded it, as the build applied it (in dev with the database's epoch). */
25
+ instanceKey: string;
26
+ /**
27
+ * The tenant of a per-tenant database's instance: its key without the dev
28
+ * epoch the build applied. Null for a global database's instance — by the
29
+ * database's instance kind, so a per-tenant database's tenant named
30
+ * `global` is that tenant.
31
+ */
32
+ tenantId: string | null;
33
+ /** When the action recorded it (ms since the epoch). */
34
+ recordedAt: number;
35
+ /**
36
+ * How many of its failures counted toward `maxAttempts` before this call:
37
+ * 0 on its first. Only a failure alone counts — the one message of a call
38
+ * the sink did not deliver — and only when the sink delivered another
39
+ * message in that alarm, in that call or earlier.
40
+ */
41
+ attempts: number;
42
+ }
43
+ interface OutboxSinkContext<Env = unknown> {
44
+ /** The Durable Object's env: the worker's bindings. */
45
+ env: Env;
46
+ }
47
+ /**
48
+ * What a sink call answers. Nothing: every envelope of it was delivered.
49
+ * `{ retry, dead }` — each a list of the very envelope objects the call was
50
+ * handed, either may be left out: those in `retry` were not delivered and are
51
+ * tried again, those in `dead` can never be and are moved to `__outbox_dead`
52
+ * at once, and every other envelope counts as delivered; `error`, when given,
53
+ * is kept with both as their last error. A throw is a `retry` of every
54
+ * envelope, and so is an answer that names an envelope the call was not
55
+ * handed, or one in both lists.
56
+ */
57
+ type OutboxDelivery = void | {
58
+ retry?: readonly OutboxEnvelope[];
59
+ dead?: readonly OutboxEnvelope[];
60
+ error?: unknown;
61
+ };
62
+ /**
63
+ * Where the outbox delivers. `envelopes` is the call's own list, frozen: copy
64
+ * it (`[...envelopes]`) to chunk or sort it — what settles the call is the
65
+ * envelope objects, never their places in the list.
66
+ */
67
+ interface OutboxSink<Env = unknown> {
68
+ deliver(envelopes: readonly OutboxEnvelope[], context: OutboxSinkContext<Env>): OutboxDelivery | Promise<OutboxDelivery>;
69
+ }
70
+ type OutboxSinkModule<Env = unknown> = OutboxSink<Env> | OutboxSink<Env>['deliver'];
71
+ /** A sink module's default export as a sink: a deliver function, or an object with one. */
72
+ declare function outboxSink<Env = unknown>(module: OutboxSinkModule<Env>): OutboxSink<Env>;
73
+ /**
74
+ * Each message to the Queue binding `binding`, as it was pushed (as JSON), in
75
+ * as few sendBatch calls as the queue takes: at most 100 messages and 256 KB
76
+ * each. A message larger than a queue message holds (128 KB) can never be
77
+ * sent: it is not, and is answered in `{ dead }`. A sendBatch that fails
78
+ * answers the envelopes not sent yet in `{ retry }`: the batches before it
79
+ * were delivered.
80
+ */
81
+ declare function queueOutboxSink(binding: string): OutboxSink;
82
+ /** What tells an instance key's tenant: the database's instance kind and the dev epoch the build applied to its keys. */
83
+ interface InstanceKeyOrigin {
84
+ /** The database's `instance`: a global database's instance has no tenant, whatever its key. */
85
+ instance: 'per-tenant' | 'global';
86
+ /**
87
+ * What the build appends to the database's instance keys —
88
+ * `applyDevEpoch('', name)` of `virtual:durable-db/__devEpoch`: `__dev_<epoch>`
89
+ * in dev, `''` (the default) in production, where a key is the tenant whole.
90
+ */
91
+ devEpochSuffix?: string;
92
+ }
93
+ /**
94
+ * The tenant an instance key belongs to: null for a global database's
95
+ * instance, else the key without exactly the dev epoch suffix the build
96
+ * applied, when it ends with it — so a tenant id that contains `__dev_` is
97
+ * kept whole. In production (no suffix) the key is the tenant. In dev every
98
+ * key carries an epoch, so a key that does not end with the current one is
99
+ * an earlier epoch's — an object `db reset` left behind, whose alarm still
100
+ * delivers what waits in its outbox — and its trailing `__dev_<epoch>` is cut.
101
+ */
102
+ declare function tenantOfInstanceKey(instanceKey: string, origin: InstanceKeyOrigin): string | null;
103
+ //#endregion
104
+ export { OutboxMessage as a, OutboxSinkModule as c, tenantOfInstanceKey as d, OutboxEnvelope as i, outboxSink as l, Outbox as n, OutboxSink as o, OutboxDelivery as r, OutboxSinkContext as s, InstanceKeyOrigin as t, queueOutboxSink as u };
@@ -1,5 +1,5 @@
1
1
  import { o as TypeParser } from "./index-bUUlOWfP.js";
2
- import { t as Outbox } from "./outbox-D3Q9n7Rt.js";
2
+ import { n as Outbox } from "./outbox-DpyNU99x.js";
3
3
  //#region src/db/actionArgs.d.ts
4
4
  /**
5
5
  * `type` (durable-db/type: ArkType's definitions and types), for an
@@ -40,6 +40,16 @@ export interface DoContext {
40
40
  ctx: RpcContext;
41
41
  dbName: string;
42
42
  instanceKey: string;
43
+ /**
44
+ * The tenant the object worked out from `instanceKey` (`tenantOf()`: null
45
+ * for a global database, else the key without exactly the dev epoch the
46
+ * build applied) — what `getTenantId()` answers inside the action, before
47
+ * any resolver (`setTenantIdResolver()`): the resolver is asked only where
48
+ * this is null (a global database's object) or left out. The generated
49
+ * Durable Objects set it; a store without it (one built by hand) is read
50
+ * as its key, `'global'` as no tenant, when no resolver is set.
51
+ */
52
+ tenantId?: string | null;
43
53
  }
44
54
  export interface RpcContext {
45
55
  env: Record<string, unknown>;
@@ -1,4 +1,4 @@
1
- import { i as OutboxSink, n as OutboxEnvelope } from "../outbox-D3Q9n7Rt.js";
1
+ import { i as OutboxEnvelope, o as OutboxSink } from "../outbox-DpyNU99x.js";
2
2
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
3
3
  import { Kysely } from "kysely";
4
4
  import { DatabaseSync } from "node:sqlite";
@@ -23,10 +23,23 @@ export interface CreateTestDatabaseOptions {
23
23
  * that reads the tenant id.
24
24
  */
25
25
  tenantId?: string;
26
+ /**
27
+ * The database name the outbox envelopes carry (`envelope.database`, the
28
+ * name `db` commands know the database by). Defaults to `'test'`.
29
+ */
30
+ database?: string;
31
+ /**
32
+ * The database's instance kind: a global database's actions run on the
33
+ * instance key `'global'` and its envelopes have no tenant. Defaults to
34
+ * the action's own database's (`defineDatabase({ instance })`), per-tenant
35
+ * unless it says.
36
+ */
37
+ instance?: 'per-tenant' | 'global';
26
38
  /**
27
39
  * Delivers what an action pushed to `ctx.outbox`, after the action
28
40
  * succeeds, as the Durable Object's sink would (awaited before `run()`
29
- * returns). Every envelope is also kept in {@link TestDatabase.outbox}.
41
+ * returns), handed a frozen list of its own as the sink is. Every envelope
42
+ * is also kept in {@link TestDatabase.outbox}.
30
43
  */
31
44
  outbox?: OutboxSink['deliver'];
32
45
  /** The `ctx.env` handlers see. Defaults to `{}`. */
@@ -1,8 +1,8 @@
1
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-B1pKzO-V.js";
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-_AusJf3r.js";
2
2
  import { r as type } from "../type-pAQ37iEL.js";
3
3
  import "../actionArgs-oUWwX6Xn.js";
4
4
  import { setTenantIdResolver } from "../context/index.js";
5
- import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-D07wMKZZ.js";
5
+ import { h as tenantOfInstanceKey, l as createActionOutbox, t as createKyselyFromSql } from "../kysely-C675L1b9.js";
6
6
  import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-CY4FLqAo.js";
7
7
  import { createRequire } from "node:module";
8
8
  //#region src/testing/index.ts
@@ -70,7 +70,7 @@ async function deriveStatements(schema) {
70
70
  * ```
71
71
  */
72
72
  async function createTestDatabase(options) {
73
- const { schema, statements, tenantId = "test", env = {} } = options;
73
+ const { schema, statements, tenantId = "test", database = "test", env = {} } = options;
74
74
  const recorded = [];
75
75
  const { DatabaseSync } = loadSqlite();
76
76
  const sqlite = new DatabaseSync(":memory:");
@@ -83,21 +83,25 @@ async function createTestDatabase(options) {
83
83
  if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
84
84
  const validated = meta.validator(args);
85
85
  if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
86
+ const instance = options.instance ?? meta.instance ?? "per-tenant";
87
+ const instanceKey = instance === "global" ? "global" : tenantId;
86
88
  const outbox = createActionOutbox(true);
87
89
  const result = await meta.handler(db, validated, {
88
90
  env,
89
- instanceKey: tenantId,
91
+ instanceKey,
90
92
  outbox
91
93
  });
92
94
  const envelopes = outbox.take().map((message) => ({
93
95
  message: JSON.parse(message),
94
- instanceKey: tenantId,
95
- tenantId: tenantOfInstanceKey(tenantId),
96
- recordedAt: Date.now()
96
+ database,
97
+ instanceKey,
98
+ tenantId: tenantOfInstanceKey(instanceKey, { instance }),
99
+ recordedAt: Date.now(),
100
+ attempts: 0
97
101
  }));
98
102
  if (envelopes.length > 0) {
99
103
  recorded.push(...envelopes);
100
- await options.outbox?.(envelopes, { env });
104
+ await options.outbox?.(Object.freeze(envelopes.slice()), { env });
101
105
  }
102
106
  return result;
103
107
  }
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-Di-UGgpS.js";
2
+ import "../index-B1J4Kjum.js";
3
3
  import { Plugin } from "vite";
4
4
  import "@babel/types";
5
5
  //#region src/vite/modules/wrangler.d.ts
@@ -80,11 +80,17 @@ interface PatchResult {
80
80
  }
81
81
  //#endregion
82
82
  //#region src/vite/modules/generator.d.ts
83
- /** Where the outbox delivers: a Queue binding, or a module whose default export is the sink. */
84
- type OutboxOption = {
83
+ /**
84
+ * Where the outbox delivers: a Queue binding, or a module whose default export
85
+ * is the sink; `maxAttempts` (default 100) is how many counted failures move
86
+ * a message to `__outbox_dead` (see `alarm()`).
87
+ */
88
+ type OutboxOption = ({
85
89
  queue: string;
86
90
  } | {
87
91
  module: string;
92
+ }) & {
93
+ maxAttempts?: number;
88
94
  };
89
95
  //#endregion
90
96
  //#region src/vite/modules/syncWrangler.d.ts
@@ -163,6 +169,14 @@ export interface DurableDbOptions {
163
169
  * root, or a package specifier) whose default export delivers them — a
164
170
  * function `(envelopes, { env }) => …`, or an object with `deliver`. Without
165
171
  * it, `ctx.outbox.push()` throws naming this option.
172
+ *
173
+ * `maxAttempts` (default 100, at least 2) is how many counted failures
174
+ * move a message to the Durable Object's `__outbox_dead` table, where it is
175
+ * kept and logged but never retried by itself. A failure counts when the
176
+ * message failed alone (the one of its call not delivered) in an alarm in
177
+ * which the sink delivered another message, in that call or earlier, so an
178
+ * outage counts at most one failure a message: it buries only a message
179
+ * that already had `maxAttempts - 1`.
166
180
  */
167
181
  outbox?: OutboxOption;
168
182
  }
@@ -816,6 +816,7 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
816
816
  ...tombstones.length > 0 ? ["RemovedDatabaseDurableObject"] : []
817
817
  ], "durable-db/db"),
818
818
  createNamedImport(["getAction", "runWithDoContext"], registryImport),
819
+ createNamedImport(["applyDevEpoch"], DEV_EPOCH_IMPORT),
819
820
  ...actionFiles.map((file) => t.importDeclaration([], t.stringLiteral(file))),
820
821
  ...databases.filter(hasSchema).map(buildSchemaImport)
821
822
  ];
@@ -833,7 +834,7 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
833
834
  }
834
835
  }
835
836
  const statements = [...imports, ...outboxStatements];
836
- for (const db of databases) statements.push(...buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev, outbox !== null));
837
+ for (const db of databases) statements.push(...buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev, outbox));
837
838
  for (const tombstone of tombstones) statements.push(buildTombstoneStatement(tombstone));
838
839
  const program = t.program(statements);
839
840
  return generateCode(t.file(program));
@@ -888,20 +889,31 @@ function buildMigrationGuardMethod(name, params) {
888
889
  * export class ClassName extends SqliteDurableObject {
889
890
  * migrations = {...};
890
891
  * databaseName = "name";
892
+ * databaseInstance = "per-tenant";
893
+ * devEpochSuffix = applyDevEpoch("", "name");
891
894
  * async rpc(...) { ... }
892
895
  * }
893
896
  */
894
- function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev, hasOutbox = false) {
897
+ function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev, outbox = null) {
895
898
  const isBrowsable = db.browsable === true || db.browsable === "development" && isDev;
896
899
  const rpcMethod = buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr);
897
900
  const migrationsProperty = t.classProperty(t.identifier("migrations"), buildMigrationsObject(db.migrations));
898
901
  const databaseNameProperty = t.classProperty(t.identifier("databaseName"), t.stringLiteral(db.name));
902
+ const instanceProperties = [t.classProperty(t.identifier("databaseInstance"), t.stringLiteral(db.instance)), t.classProperty(t.identifier("devEpochSuffix"), t.callExpression(t.identifier("applyDevEpoch"), [t.stringLiteral(""), t.stringLiteral(db.name)]))];
899
903
  const dataProperties = hasSchema(db) ? [
900
904
  migrationsProperty,
901
905
  databaseNameProperty,
906
+ ...instanceProperties,
902
907
  buildSchemaProperty(db)
903
- ] : [migrationsProperty, databaseNameProperty];
904
- if (hasOutbox) dataProperties.push(t.classProperty(t.identifier("outboxSink"), t.identifier(OUTBOX_LOCAL)));
908
+ ] : [
909
+ migrationsProperty,
910
+ databaseNameProperty,
911
+ ...instanceProperties
912
+ ];
913
+ if (outbox) {
914
+ dataProperties.push(t.classProperty(t.identifier("outboxSink"), t.identifier(OUTBOX_LOCAL)));
915
+ if (outbox.maxAttempts !== void 0) dataProperties.push(t.classProperty(t.identifier("outboxMaxAttempts"), t.numericLiteral(outbox.maxAttempts)));
916
+ }
905
917
  const classMethods = [rpcMethod, buildSysMethod()];
906
918
  if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
907
919
  if (!isBrowsable) {
@@ -959,6 +971,14 @@ function buildSysMethod() {
959
971
  return t.classMethod("method", t.identifier("sys"), [t.identifier("command")], body, false, false, false, true);
960
972
  }
961
973
  /**
974
+ * `tenantId: this.tenantOf(ctx.instanceKey)` in the DoContext store: the
975
+ * tenant the object works out from its instance kind and epoch suffix, which
976
+ * `getTenantId()` answers inside the action.
977
+ */
978
+ function buildDoContextTenantProperty() {
979
+ return t.objectProperty(t.identifier("tenantId"), t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("tenantOf")), [t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey"))]));
980
+ }
981
+ /**
962
982
  * `this.runWithOutbox(ctx, async () => entry.handler(this.db, validated, ctx))`:
963
983
  * the handler with `ctx.outbox`, its messages written when it resolves.
964
984
  */
@@ -1001,7 +1021,8 @@ function buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr) {
1001
1021
  t.objectProperty(t.identifier("db"), t.memberExpression(t.thisExpression(), t.identifier("db"))),
1002
1022
  t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
1003
1023
  t.objectProperty(t.identifier("dbName"), dbNameLiteral),
1004
- t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey")))
1024
+ t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey"))),
1025
+ buildDoContextTenantProperty()
1005
1026
  ]), t.arrowFunctionExpression([], buildOutboxHandlerCall(), true)]))
1006
1027
  ]);
1007
1028
  return t.classMethod("method", t.identifier("rpc"), [
@@ -1068,7 +1089,8 @@ function buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr) {
1068
1089
  t.objectProperty(t.identifier("db"), t.memberExpression(t.thisExpression(), t.identifier("db"))),
1069
1090
  t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
1070
1091
  t.objectProperty(t.identifier("dbName"), dbNameLiteral),
1071
- t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey")))
1092
+ t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey"))),
1093
+ buildDoContextTenantProperty()
1072
1094
  ]), t.arrowFunctionExpression([], buildOutboxHandlerCall(), true)])))]),
1073
1095
  wsSendResponse([
1074
1096
  t.objectProperty(t.identifier("id"), t.identifier("id"), false, true),
@@ -1610,7 +1632,22 @@ async function findImportedDatabase(resolve, state, imports, importer) {
1610
1632
  /** A relative sink module resolves from the project root; a package specifier or an absolute path stays as it is. */
1611
1633
  function resolveOutbox(outbox, projectRoot) {
1612
1634
  if (!outbox || "queue" in outbox) return outbox;
1613
- return outbox.module.startsWith(".") ? { module: path$1.resolve(projectRoot, outbox.module).split(path$1.sep).join("/") } : outbox;
1635
+ return outbox.module.startsWith(".") ? {
1636
+ ...outbox,
1637
+ module: path$1.resolve(projectRoot, outbox.module).split(path$1.sep).join("/")
1638
+ } : outbox;
1639
+ }
1640
+ /**
1641
+ * `outbox.maxAttempts` is a whole number of at least 2, said where the plugin
1642
+ * is configured: an outage can count one failure of a message — in the alarm
1643
+ * it began in, after a delivery — so with 1 an outage would bury what it
1644
+ * found waiting.
1645
+ */
1646
+ function checkOutbox(outbox) {
1647
+ if (!outbox) return null;
1648
+ const { maxAttempts } = outbox;
1649
+ if (maxAttempts !== void 0 && !(Number.isInteger(maxAttempts) && maxAttempts >= 2)) throw new Error(`[durable-db] durableDb({ outbox: { maxAttempts } }) is how many counted failures move a message to __outbox_dead: a whole number of at least 2, not ${String(maxAttempts)}. An outage can count one failure of a message, in the alarm it began in after a delivery, so with 1 an outage would bury it.`);
1650
+ return outbox;
1614
1651
  }
1615
1652
  function durableDb(options = {}) {
1616
1653
  const state = new PluginState({
@@ -1619,7 +1656,7 @@ function durableDb(options = {}) {
1619
1656
  databasesDir: options.databasesDir ?? "src/databases",
1620
1657
  migrationsDir: options.migrationsDir ?? "migrations",
1621
1658
  patchWranglerConfig: options.patchWranglerConfig ?? false,
1622
- outbox: options.outbox ?? null
1659
+ outbox: checkOutbox(options.outbox)
1623
1660
  });
1624
1661
  return {
1625
1662
  name: "durable-db",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.13.3",
3
+ "version": "0.14.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"
@@ -1,279 +0,0 @@
1
- import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-B1pKzO-V.js";
2
- import { CamelCasePlugin, Kysely, SqliteDialect, SqliteQueryCompiler } from "kysely";
3
- //#region src/db/outbox.ts
4
- /** A sink module's default export as a sink: a deliver function, or an object with one. */
5
- function outboxSink(module) {
6
- if (typeof module === "function") return { deliver: module };
7
- if (module && typeof module.deliver === "function") return module;
8
- throw new TypeError("[db] An outbox module must default-export a deliver function, or an object with one");
9
- }
10
- /** Cloudflare Queues takes at most 100 messages per sendBatch. */
11
- const QUEUE_BATCH = 100;
12
- /** Each message to the Queue binding `binding`, as it was pushed. */
13
- function queueOutboxSink(binding) {
14
- return { async deliver(envelopes, { env }) {
15
- const queue = env[binding];
16
- if (!queue?.sendBatch) throw new Error(`[db] The outbox sends to the Queue binding ${binding}, which this worker does not have`);
17
- for (let i = 0; i < envelopes.length; i += QUEUE_BATCH) await queue.sendBatch(envelopes.slice(i, i + QUEUE_BATCH).map((envelope) => ({ body: envelope.message })));
18
- } };
19
- }
20
- const OUTBOX_TABLE = "__outbox";
21
- const OUTBOX_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_TABLE} (
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
23
- instance_key TEXT NOT NULL,
24
- message TEXT NOT NULL,
25
- recorded_at INTEGER NOT NULL,
26
- attempts INTEGER NOT NULL DEFAULT 0,
27
- last_error TEXT
28
- )`;
29
- /** The wait before retrying a failed delivery: 5 s, doubling, at most 5 minutes. */
30
- function outboxRetryDelay(attempts) {
31
- return Math.min(5e3 * 2 ** Math.max(0, attempts - 1), 3e5);
32
- }
33
- /** The tenant an instance key belongs to (its dev epoch suffix dropped); null for a global database. */
34
- function tenantOfInstanceKey(instanceKey) {
35
- const suffixAt = instanceKey.lastIndexOf("__dev_");
36
- const tenant = suffixAt === -1 ? instanceKey : instanceKey.slice(0, suffixAt);
37
- return tenant === "global" ? null : tenant;
38
- }
39
- /**
40
- * The outbox of one action run: `push()` collects, and once the handler has
41
- * resolved `take()` hands the messages over to be written. A message must be
42
- * a JSON value; it is checked (serialized) when pushed, so a bad one fails
43
- * the action that pushed it rather than a delivery later.
44
- */
45
- function createActionOutbox(sinkConfigured) {
46
- let messages = [];
47
- return {
48
- push(message) {
49
- if (!sinkConfigured) throw new Error("[db] ctx.outbox.push(): no outbox sink is configured — durableDb({ outbox: { queue: \"<QUEUE_BINDING>\" } }) or durableDb({ outbox: { module: \"./src/outbox.ts\" } })");
50
- const json = JSON.stringify(message);
51
- if (json === void 0) throw new TypeError("[db] ctx.outbox.push(): a message must be a JSON value");
52
- messages.push(json);
53
- },
54
- take() {
55
- const taken = messages;
56
- messages = [];
57
- return taken;
58
- }
59
- };
60
- }
61
- //#endregion
62
- //#region src/db/kysely.ts
63
- const MAX_BOUND_PARAMETERS = 100;
64
- /**
65
- * Kysely's SQLite compiler with identifiers quoted in backticks instead of
66
- * double quotes. SQLite (workerd's build included) reads a double-quoted
67
- * identifier that names no column as a string literal, so a column missing
68
- * from the database — a schema change not yet migrated — silently selects its
69
- * own name (`"weight_grams"` → 'weight_grams') and a WHERE on it compares two
70
- * constants. A backtick-quoted identifier is never a literal: the query fails
71
- * with "no such column". The migrations already quote with backticks.
72
- */
73
- var BacktickSqliteQueryCompiler = class extends SqliteQueryCompiler {
74
- getLeftIdentifierWrapper() {
75
- return "`";
76
- }
77
- getRightIdentifierWrapper() {
78
- return "`";
79
- }
80
- sanitizeIdentifier(identifier) {
81
- return identifier.replaceAll("`", "``");
82
- }
83
- };
84
- /**
85
- * workerd has no boolean binding type and silently stringifies JS booleans
86
- * (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
87
- * outright. Normalize to SQLite's 1/0 convention before the value reaches
88
- * either. `undefined` → NULL for the same reason.
89
- */
90
- function normalizeParameter(value) {
91
- if (typeof value === "boolean") return value ? 1 : 0;
92
- if (value === void 0) return null;
93
- return value;
94
- }
95
- function escapeLiteral(value) {
96
- if (value === null || value === void 0) return "NULL";
97
- if (typeof value === "boolean") return value ? "1" : "0";
98
- if (typeof value === "number") {
99
- if (!Number.isFinite(value)) throw new Error(`[db] Cannot inline non-finite number parameter (${value})`);
100
- return String(value);
101
- }
102
- if (typeof value === "bigint") return value.toString();
103
- if (typeof value === "string") {
104
- if (value.includes("\0")) throw new Error("[db] Cannot inline a string parameter containing a NUL byte");
105
- return `'${value.replaceAll("'", "''")}'`;
106
- }
107
- if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
108
- const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
109
- let hex = "";
110
- for (const b of bytes) hex += b.toString(16).padStart(2, "0");
111
- return `X'${hex}'`;
112
- }
113
- throw new Error(`[db] Cannot inline SQL parameter of type ${typeof value}`);
114
- }
115
- /**
116
- * Replace each `?` placeholder in `sql` with the escaped literal of its
117
- * parameter. A real scanner, not a regex: '…' string literals ('' escapes),
118
- * "…" and `…` quoted identifiers, `--` line comments and C-style block
119
- * comments are skipped, so a `?` inside any of them is never touched.
120
- *
121
- * Exported for tests.
122
- */
123
- function inlineParameters(sql, parameters) {
124
- let out = "";
125
- let p = 0;
126
- for (let i = 0; i < sql.length; i++) {
127
- const ch = sql[i];
128
- if (ch === "'" || ch === "\"" || ch === "`") {
129
- let j = i + 1;
130
- while (j < sql.length) {
131
- if (sql[j] === ch) {
132
- if (sql[j + 1] === ch) {
133
- j += 2;
134
- continue;
135
- }
136
- break;
137
- }
138
- j++;
139
- }
140
- out += sql.slice(i, j + 1);
141
- i = j;
142
- continue;
143
- }
144
- if (ch === "-" && sql[i + 1] === "-") {
145
- let j = sql.indexOf("\n", i);
146
- if (j === -1) j = sql.length;
147
- out += sql.slice(i, j);
148
- i = j - 1;
149
- continue;
150
- }
151
- if (ch === "/" && sql[i + 1] === "*") {
152
- let j = sql.indexOf("*/", i + 2);
153
- j = j === -1 ? sql.length : j + 2;
154
- out += sql.slice(i, j);
155
- i = j - 1;
156
- continue;
157
- }
158
- if (ch === "?") {
159
- if (p >= parameters.length) throw new Error("[db] Query has more `?` placeholders than parameters while inlining");
160
- out += escapeLiteral(parameters[p++]);
161
- continue;
162
- }
163
- out += ch;
164
- }
165
- if (p !== parameters.length) throw new Error(`[db] Inlined ${p} parameter(s) but the query provided ${parameters.length} — placeholder/parameter mismatch`);
166
- return out;
167
- }
168
- /**
169
- * A Kysely driver that uses Cloudflare DO SQLite storage
170
- */
171
- var CloudflareSqliteDriver = class {
172
- sql;
173
- constructor(sql) {
174
- this.sql = sql;
175
- }
176
- async init() {}
177
- async acquireConnection() {
178
- return new CloudflareSqliteConnection(this.sql);
179
- }
180
- async beginTransaction(connection, settings) {
181
- if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
182
- await connection.executeQuery(createCompiledQuery("BEGIN"));
183
- }
184
- async commitTransaction(connection) {
185
- await connection.executeQuery(createCompiledQuery("COMMIT"));
186
- }
187
- async rollbackTransaction(connection) {
188
- await connection.executeQuery(createCompiledQuery("ROLLBACK"));
189
- }
190
- async releaseConnection() {}
191
- async destroy() {}
192
- };
193
- /**
194
- * Helper to create a CompiledQuery object
195
- */
196
- function createCompiledQuery(sql, parameters = []) {
197
- return {
198
- sql,
199
- parameters,
200
- query: {
201
- kind: "RawNode",
202
- sqlFragments: [sql],
203
- parameters: []
204
- }
205
- };
206
- }
207
- /**
208
- * A Kysely connection that wraps Cloudflare's SqlStorage
209
- */
210
- var CloudflareSqliteConnection = class {
211
- sql;
212
- constructor(sql) {
213
- this.sql = sql;
214
- }
215
- async executeQuery(compiledQuery) {
216
- let queryStr = compiledQuery.sql;
217
- let parameters = compiledQuery.parameters.map(normalizeParameter);
218
- if (parameters.length > MAX_BOUND_PARAMETERS) {
219
- queryStr = inlineParameters(queryStr, parameters);
220
- parameters = [];
221
- }
222
- const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
223
- try {
224
- if (isSelect) return {
225
- rows: this.sql.exec(queryStr, ...parameters).toArray(),
226
- numAffectedRows: void 0,
227
- insertId: void 0
228
- };
229
- else {
230
- this.sql.exec(queryStr, ...parameters);
231
- const [result] = this.sql.exec("SELECT changes() AS changes, last_insert_rowid() AS id").toArray();
232
- const changes = result?.changes ?? 0;
233
- const lastId = result?.id;
234
- return {
235
- rows: [],
236
- numAffectedRows: BigInt(changes),
237
- insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
238
- };
239
- }
240
- } catch (error) {
241
- throw error;
242
- }
243
- }
244
- streamQuery() {
245
- throw new Error("Streaming is not supported in Cloudflare SQLite");
246
- }
247
- };
248
- /**
249
- * Create a Kysely instance from Cloudflare SqlStorage
250
- *
251
- * @param sqlStorage - The Cloudflare SqlStorage instance
252
- * @param options - Configuration options including schema for plugins
253
- */
254
- function createKyselyFromSql(sqlStorage, options = {}) {
255
- const { schema, plugins = [], camelCase = true } = options;
256
- const sqliteDialect = new SqliteDialect({ database: null });
257
- const allPlugins = [];
258
- const naming = schema && camelCase ? new SchemaPlugin(schema) : void 0;
259
- const related = schema ? createRelatedPlugins(schema, naming ? { resultKey: (name) => naming.resultKey(name) } : {}) : void 0;
260
- if (related) allPlugins.push(related.capture);
261
- if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
262
- else if (camelCase) {
263
- allPlugins.push(new CamelCasePlugin());
264
- allPlugins.push(new DateSerializePlugin());
265
- } else allPlugins.push(new DateSerializePlugin());
266
- allPlugins.push(...plugins);
267
- if (related) allPlugins.push(related.results);
268
- return new Kysely({
269
- dialect: {
270
- createAdapter: () => sqliteDialect.createAdapter(),
271
- createDriver: () => new CloudflareSqliteDriver(sqlStorage),
272
- createIntrospector: (db) => sqliteDialect.createIntrospector(db),
273
- createQueryCompiler: () => new BacktickSqliteQueryCompiler()
274
- },
275
- plugins: allPlugins
276
- });
277
- }
278
- //#endregion
279
- export { outboxRetryDelay as a, tenantOfInstanceKey as c, createActionOutbox as i, OUTBOX_DDL as n, outboxSink as o, OUTBOX_TABLE as r, queueOutboxSink as s, createKyselyFromSql as t };