durable-db 0.13.2 → 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.
- package/README.md +29 -5
- package/dist/cli/index.d.ts +2 -2
- package/dist/context/index.d.ts +33 -0
- package/dist/context/index.js +53 -26
- package/dist/db/index.d.ts +4 -4
- package/dist/db/index.js +279 -26
- package/dist/{defineDatabase-DlgYfwhP.d.ts → defineDatabase-Dj5DOPUM.d.ts} +45 -9
- package/dist/{defineDatabase-B1pKzO-V.js → defineDatabase-_AusJf3r.js} +2 -1
- package/dist/{index-B5W4m0Dq.d.ts → index-B1J4Kjum.d.ts} +108 -10
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/kysely-C675L1b9.js +488 -0
- package/dist/outbox-DpyNU99x.d.ts +104 -0
- package/dist/registry.d.ts +11 -1
- package/dist/testing/index.d.ts +15 -2
- package/dist/testing/index.js +12 -8
- package/dist/vite/durableDb.d.ts +17 -3
- package/dist/vite/durableDb.js +45 -8
- package/package.json +1 -1
- package/dist/kysely-D07wMKZZ.js +0 -279
- package/dist/outbox-D3Q9n7Rt.d.ts +0 -41
package/dist/testing/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-
|
|
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 {
|
|
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
|
|
91
|
+
instanceKey,
|
|
90
92
|
outbox
|
|
91
93
|
});
|
|
92
94
|
const envelopes = outbox.take().map((message) => ({
|
|
93
95
|
message: JSON.parse(message),
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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
|
}
|
package/dist/vite/durableDb.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
|
|
2
|
-
import "../index-
|
|
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
|
-
/**
|
|
84
|
-
|
|
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
|
}
|
package/dist/vite/durableDb.js
CHANGED
|
@@ -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
|
|
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,
|
|
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
|
-
] : [
|
|
904
|
-
|
|
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(".") ? {
|
|
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
|
|
1659
|
+
outbox: checkOutbox(options.outbox)
|
|
1623
1660
|
});
|
|
1624
1661
|
return {
|
|
1625
1662
|
name: "durable-db",
|
package/package.json
CHANGED
package/dist/kysely-D07wMKZZ.js
DELETED
|
@@ -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 };
|
|
@@ -1,41 +0,0 @@
|
|
|
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
|
-
/** The instance key of the Durable Object that recorded it. */
|
|
19
|
-
instanceKey: string;
|
|
20
|
-
/** The tenant of a per-tenant database's instance (its key without the dev epoch); null for a global database. */
|
|
21
|
-
tenantId: string | null;
|
|
22
|
-
/** When the action recorded it (ms since the epoch). */
|
|
23
|
-
recordedAt: number;
|
|
24
|
-
}
|
|
25
|
-
interface OutboxSinkContext<Env = unknown> {
|
|
26
|
-
/** The Durable Object's env: the worker's bindings. */
|
|
27
|
-
env: Env;
|
|
28
|
-
}
|
|
29
|
-
/** Where the outbox delivers. A delivery that throws is retried, every envelope of it. */
|
|
30
|
-
interface OutboxSink<Env = unknown> {
|
|
31
|
-
deliver(envelopes: OutboxEnvelope[], context: OutboxSinkContext<Env>): Promise<void> | void;
|
|
32
|
-
}
|
|
33
|
-
type OutboxSinkModule<Env = unknown> = OutboxSink<Env> | OutboxSink<Env>['deliver'];
|
|
34
|
-
/** A sink module's default export as a sink: a deliver function, or an object with one. */
|
|
35
|
-
declare function outboxSink<Env = unknown>(module: OutboxSinkModule<Env>): OutboxSink<Env>;
|
|
36
|
-
/** Each message to the Queue binding `binding`, as it was pushed. */
|
|
37
|
-
declare function queueOutboxSink(binding: string): OutboxSink;
|
|
38
|
-
/** The tenant an instance key belongs to (its dev epoch suffix dropped); null for a global database. */
|
|
39
|
-
declare function tenantOfInstanceKey(instanceKey: string): string | null;
|
|
40
|
-
//#endregion
|
|
41
|
-
export { OutboxSinkContext as a, queueOutboxSink as c, OutboxSink as i, tenantOfInstanceKey as l, OutboxEnvelope as n, OutboxSinkModule as o, OutboxMessage as r, outboxSink as s, Outbox as t };
|