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.
@@ -0,0 +1,488 @@
1
+ import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-_AusJf3r.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
+ const QUEUE_MESSAGE_BYTES = 128e3;
11
+ const QUEUE_MESSAGE_OVERHEAD = 100;
12
+ const QUEUE_BATCH_MESSAGES = 100;
13
+ const QUEUE_BATCH_BYTES = 256e3;
14
+ const utf8 = new TextEncoder();
15
+ /** What the queue counts of a message: its JSON's bytes and its own. */
16
+ function queueMessageBytes(message) {
17
+ return utf8.encode(JSON.stringify(message)).byteLength + QUEUE_MESSAGE_OVERHEAD;
18
+ }
19
+ /**
20
+ * Each message to the Queue binding `binding`, as it was pushed (as JSON), in
21
+ * as few sendBatch calls as the queue takes: at most 100 messages and 256 KB
22
+ * each. A message larger than a queue message holds (128 KB) can never be
23
+ * sent: it is not, and is answered in `{ dead }`. A sendBatch that fails
24
+ * answers the envelopes not sent yet in `{ retry }`: the batches before it
25
+ * were delivered.
26
+ */
27
+ function queueOutboxSink(binding) {
28
+ return { async deliver(envelopes, { env }) {
29
+ const queue = env[binding];
30
+ if (!queue?.sendBatch) throw new Error(`[db] The outbox sends to the Queue binding ${binding}, which this worker does not have`);
31
+ const dead = [];
32
+ const deadSizes = [];
33
+ const batches = [];
34
+ let batch = [];
35
+ let bytes = 0;
36
+ for (const envelope of envelopes) {
37
+ const size = queueMessageBytes(envelope.message);
38
+ if (size > QUEUE_MESSAGE_BYTES) {
39
+ dead.push(envelope);
40
+ deadSizes.push(size);
41
+ continue;
42
+ }
43
+ if (batch.length === QUEUE_BATCH_MESSAGES || bytes + size > QUEUE_BATCH_BYTES) {
44
+ batches.push(batch);
45
+ batch = [];
46
+ bytes = 0;
47
+ }
48
+ batch.push(envelope);
49
+ bytes += size;
50
+ }
51
+ if (batch.length > 0) batches.push(batch);
52
+ const tooLarge = dead.length > 0 ? `${dead.length} message(s) of ${deadSizes.join(", ")} bytes, more than a queue message holds (${QUEUE_MESSAGE_BYTES})` : null;
53
+ for (let i = 0; i < batches.length; i++) try {
54
+ await queue.sendBatch(batches[i].map((envelope) => ({
55
+ body: envelope.message,
56
+ contentType: "json"
57
+ })));
58
+ } catch (error) {
59
+ const retry = batches.slice(i).flat();
60
+ if (!tooLarge) return {
61
+ retry,
62
+ error
63
+ };
64
+ return {
65
+ retry,
66
+ dead,
67
+ error: new Error(`[db] A sendBatch to the Queue binding ${binding} failed (${outboxErrorText(error)}); and ${tooLarge}`, { cause: error })
68
+ };
69
+ }
70
+ if (tooLarge) return {
71
+ dead,
72
+ error: /* @__PURE__ */ new Error(`[db] The Queue binding ${binding} cannot take ${tooLarge}`)
73
+ };
74
+ } };
75
+ }
76
+ /** Why an envelope is retried, or given up on, when the sink's answer gave no `error`. */
77
+ const ANSWERED_IN = (field) => `[db] The outbox sink answered it in { ${field} }`;
78
+ /**
79
+ * What a sink call settled. An answer with neither `retry` nor `dead`
80
+ * delivered everything (a sink that returns a value — a fetch's Response —
81
+ * did so before they existed). A `retry` or `dead` that is no list, names an
82
+ * envelope this call was not handed (a copy, say), or names one envelope in
83
+ * both is the sink's mistake and counts as a throw: no envelope of the call
84
+ * was delivered. A message is never counted as delivered, or given up on,
85
+ * that the sink did not say was. A function's fields are read as an object's
86
+ * (a function with a `retry` is still an answer). Each field of the answer is
87
+ * read once, and each list copied once, by index: what is checked is what
88
+ * settles the call, however the answer reads a second time.
89
+ */
90
+ function settleOutboxDelivery(envelopes, answer) {
91
+ if (answer === null || typeof answer !== "object" && typeof answer !== "function") return {
92
+ retry: /* @__PURE__ */ new Set(),
93
+ error: void 0,
94
+ dead: /* @__PURE__ */ new Set(),
95
+ deadError: void 0
96
+ };
97
+ const { retry, dead, error } = answer;
98
+ if (retry === void 0 && dead === void 0) return {
99
+ retry: /* @__PURE__ */ new Set(),
100
+ error: void 0,
101
+ dead: /* @__PURE__ */ new Set(),
102
+ deadError: void 0
103
+ };
104
+ const retried = answeredList(retry);
105
+ const given = answeredList(dead);
106
+ const handed = new Set(envelopes);
107
+ const named = (list) => list !== null && list.every((envelope) => handed.has(envelope));
108
+ if (!named(retried) || !named(given) || retried.some((envelope) => given.includes(envelope))) return {
109
+ retry: handed,
110
+ dead: /* @__PURE__ */ new Set(),
111
+ deadError: void 0,
112
+ error: /* @__PURE__ */ new Error("[db] The outbox sink answered { retry } or { dead } with something other than envelopes of this call, or one in both: answer the envelope objects it was handed (every envelope of the call is retried)")
113
+ };
114
+ return {
115
+ retry: new Set(retried),
116
+ error: error ?? new Error(ANSWERED_IN("retry")),
117
+ dead: new Set(given),
118
+ deadError: error ?? new Error(ANSWERED_IN("dead"))
119
+ };
120
+ }
121
+ /** A list of a sink's answer as a plain array of its own, its length and each index read once: none (left out) is empty, anything but an array null. */
122
+ function answeredList(list) {
123
+ if (list === void 0) return [];
124
+ if (!Array.isArray(list)) return null;
125
+ const length = list.length;
126
+ if (!Number.isSafeInteger(length) || length < 0) return null;
127
+ const copy = new Array(length);
128
+ for (let i = 0; i < length; i++) copy[i] = list[i];
129
+ return copy;
130
+ }
131
+ const OUTBOX_TABLE = "__outbox";
132
+ /**
133
+ * The outbox. `tries`: how often the message failed alone — its own backoff,
134
+ * `next_attempt_at` (ms since the epoch; 0 is due) = now +
135
+ * `outboxRetryDelay(tries)`. `counted`: those of its failures that count
136
+ * toward `maxAttempts` — the envelope's `attempts`. `tried_at`: when a try of
137
+ * the down sink last handed it alone (0: never); with `recorded_at`, the
138
+ * order those tries take the waiting messages in (`max(tried_at,
139
+ * recorded_at)`). `attempts` is durable-db 0.13's count, kept so that 0.13
140
+ * runs on this table after a rollback: never read or written here. No index,
141
+ * on purpose: every index write is a billed row written per message, and the
142
+ * outbox is near-empty but for an outage.
143
+ */
144
+ const OUTBOX_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_TABLE} (
145
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
146
+ instance_key TEXT NOT NULL,
147
+ message TEXT NOT NULL,
148
+ recorded_at INTEGER NOT NULL,
149
+ attempts INTEGER NOT NULL DEFAULT 0,
150
+ last_error TEXT,
151
+ tries INTEGER NOT NULL DEFAULT 0,
152
+ counted INTEGER NOT NULL DEFAULT 0,
153
+ next_attempt_at INTEGER NOT NULL DEFAULT 0,
154
+ tried_at INTEGER NOT NULL DEFAULT 0
155
+ )`;
156
+ /** What the outbox knows of its sink: one row. */
157
+ const OUTBOX_SINK_TABLE = "__outbox_sink";
158
+ /**
159
+ * `down_until`: while later than now the sink is taken for down and nothing
160
+ * is read or called; once past, the next alarm is its next try (0: it is not
161
+ * down). `down_rounds`: how many rounds in a row the sink has been taken for
162
+ * down (1 when an alarm takes it down, one more for each try that finds it
163
+ * down), the backoff of the next try.
164
+ */
165
+ const OUTBOX_SINK_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_SINK_TABLE} (
166
+ id INTEGER PRIMARY KEY CHECK (id = 1),
167
+ down_until INTEGER NOT NULL DEFAULT 0,
168
+ down_rounds INTEGER NOT NULL DEFAULT 0
169
+ )`;
170
+ /**
171
+ * The columns an outbox durable-db 0.13 created lacks (`CREATE TABLE IF NOT
172
+ * EXISTS` leaves a table as it is), each added once; nothing is reset. 0.13's
173
+ * `attempts` stays as it was: this count is `counted`, which starts at 0.
174
+ */
175
+ const OUTBOX_ADDED_COLUMNS = [
176
+ {
177
+ table: OUTBOX_TABLE,
178
+ column: "tries",
179
+ ddl: `ALTER TABLE ${OUTBOX_TABLE} ADD COLUMN tries INTEGER NOT NULL DEFAULT 0`
180
+ },
181
+ {
182
+ table: OUTBOX_TABLE,
183
+ column: "counted",
184
+ ddl: `ALTER TABLE ${OUTBOX_TABLE} ADD COLUMN counted INTEGER NOT NULL DEFAULT 0`
185
+ },
186
+ {
187
+ table: OUTBOX_TABLE,
188
+ column: "next_attempt_at",
189
+ ddl: `ALTER TABLE ${OUTBOX_TABLE} ADD COLUMN next_attempt_at INTEGER NOT NULL DEFAULT 0`
190
+ },
191
+ {
192
+ table: OUTBOX_TABLE,
193
+ column: "tried_at",
194
+ ddl: `ALTER TABLE ${OUTBOX_TABLE} ADD COLUMN tried_at INTEGER NOT NULL DEFAULT 0`
195
+ }
196
+ ];
197
+ /** Where a message goes that the sink gave up on, or that reached `maxAttempts`: kept, never retried by itself. */
198
+ const OUTBOX_DEAD_TABLE = "__outbox_dead";
199
+ /** The row as it was in `__outbox` (its id kept), its last error and when it was moved here (`dead_at`, ms since the epoch). */
200
+ const OUTBOX_DEAD_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_DEAD_TABLE} (
201
+ id INTEGER PRIMARY KEY,
202
+ instance_key TEXT NOT NULL,
203
+ message TEXT NOT NULL,
204
+ recorded_at INTEGER NOT NULL,
205
+ attempts INTEGER NOT NULL,
206
+ last_error TEXT,
207
+ dead_at INTEGER NOT NULL
208
+ )`;
209
+ /**
210
+ * What a row and a log line keep of a sink's error, whatever it is: a sink
211
+ * throws, and answers as `error`, any value, and `String()` throws for some
212
+ * (a null-prototype object, a revoked Proxy).
213
+ */
214
+ function outboxErrorText(error) {
215
+ try {
216
+ return String(error);
217
+ } catch {
218
+ try {
219
+ return Object.prototype.toString.call(error);
220
+ } catch {
221
+ return "[an error that cannot be shown as text]";
222
+ }
223
+ }
224
+ }
225
+ /** The wait before the next try: 5 s, doubling, at most 5 minutes. */
226
+ function outboxRetryDelay(tries) {
227
+ return Math.min(5e3 * 2 ** Math.max(0, tries - 1), 3e5);
228
+ }
229
+ /** A dev epoch suffix: `__dev_` and a base36 epoch (`Date.now().toString(36)`, a counter appended when two collide). */
230
+ const DEV_EPOCH_SUFFIX = /__dev_[0-9a-z]+$/;
231
+ /**
232
+ * The tenant an instance key belongs to: null for a global database's
233
+ * instance, else the key without exactly the dev epoch suffix the build
234
+ * applied, when it ends with it — so a tenant id that contains `__dev_` is
235
+ * kept whole. In production (no suffix) the key is the tenant. In dev every
236
+ * key carries an epoch, so a key that does not end with the current one is
237
+ * an earlier epoch's — an object `db reset` left behind, whose alarm still
238
+ * delivers what waits in its outbox — and its trailing `__dev_<epoch>` is cut.
239
+ */
240
+ function tenantOfInstanceKey(instanceKey, origin) {
241
+ if (origin?.instance !== "per-tenant" && origin?.instance !== "global") throw new TypeError("[db] tenantOfInstanceKey(instanceKey, { instance, devEpochSuffix }): say the database's instance kind — a key alone cannot tell a global database's 'global' from a tenant named so");
242
+ const { instance, devEpochSuffix = "" } = origin;
243
+ if (instance === "global") return null;
244
+ if (!devEpochSuffix) return instanceKey;
245
+ if (instanceKey.endsWith(devEpochSuffix)) return instanceKey.slice(0, -devEpochSuffix.length);
246
+ return instanceKey.replace(DEV_EPOCH_SUFFIX, "");
247
+ }
248
+ /**
249
+ * The outbox of one action run: `push()` collects, and once the handler has
250
+ * resolved `take()` hands the messages over to be written. A message must be
251
+ * a JSON value; it is checked (serialized) when pushed, so a bad one fails
252
+ * the action that pushed it rather than a delivery later.
253
+ */
254
+ function createActionOutbox(sinkConfigured) {
255
+ let messages = [];
256
+ return {
257
+ push(message) {
258
+ 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\" } })");
259
+ const json = JSON.stringify(message);
260
+ if (json === void 0) throw new TypeError("[db] ctx.outbox.push(): a message must be a JSON value");
261
+ messages.push(json);
262
+ },
263
+ take() {
264
+ const taken = messages;
265
+ messages = [];
266
+ return taken;
267
+ }
268
+ };
269
+ }
270
+ //#endregion
271
+ //#region src/db/kysely.ts
272
+ const MAX_BOUND_PARAMETERS = 100;
273
+ /**
274
+ * Kysely's SQLite compiler with identifiers quoted in backticks instead of
275
+ * double quotes. SQLite (workerd's build included) reads a double-quoted
276
+ * identifier that names no column as a string literal, so a column missing
277
+ * from the database — a schema change not yet migrated — silently selects its
278
+ * own name (`"weight_grams"` → 'weight_grams') and a WHERE on it compares two
279
+ * constants. A backtick-quoted identifier is never a literal: the query fails
280
+ * with "no such column". The migrations already quote with backticks.
281
+ */
282
+ var BacktickSqliteQueryCompiler = class extends SqliteQueryCompiler {
283
+ getLeftIdentifierWrapper() {
284
+ return "`";
285
+ }
286
+ getRightIdentifierWrapper() {
287
+ return "`";
288
+ }
289
+ sanitizeIdentifier(identifier) {
290
+ return identifier.replaceAll("`", "``");
291
+ }
292
+ };
293
+ /**
294
+ * workerd has no boolean binding type and silently stringifies JS booleans
295
+ * (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
296
+ * outright. Normalize to SQLite's 1/0 convention before the value reaches
297
+ * either. `undefined` → NULL for the same reason.
298
+ */
299
+ function normalizeParameter(value) {
300
+ if (typeof value === "boolean") return value ? 1 : 0;
301
+ if (value === void 0) return null;
302
+ return value;
303
+ }
304
+ function escapeLiteral(value) {
305
+ if (value === null || value === void 0) return "NULL";
306
+ if (typeof value === "boolean") return value ? "1" : "0";
307
+ if (typeof value === "number") {
308
+ if (!Number.isFinite(value)) throw new Error(`[db] Cannot inline non-finite number parameter (${value})`);
309
+ return String(value);
310
+ }
311
+ if (typeof value === "bigint") return value.toString();
312
+ if (typeof value === "string") {
313
+ if (value.includes("\0")) throw new Error("[db] Cannot inline a string parameter containing a NUL byte");
314
+ return `'${value.replaceAll("'", "''")}'`;
315
+ }
316
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
317
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
318
+ let hex = "";
319
+ for (const b of bytes) hex += b.toString(16).padStart(2, "0");
320
+ return `X'${hex}'`;
321
+ }
322
+ throw new Error(`[db] Cannot inline SQL parameter of type ${typeof value}`);
323
+ }
324
+ /**
325
+ * Replace each `?` placeholder in `sql` with the escaped literal of its
326
+ * parameter. A real scanner, not a regex: '…' string literals ('' escapes),
327
+ * "…" and `…` quoted identifiers, `--` line comments and C-style block
328
+ * comments are skipped, so a `?` inside any of them is never touched.
329
+ *
330
+ * Exported for tests.
331
+ */
332
+ function inlineParameters(sql, parameters) {
333
+ let out = "";
334
+ let p = 0;
335
+ for (let i = 0; i < sql.length; i++) {
336
+ const ch = sql[i];
337
+ if (ch === "'" || ch === "\"" || ch === "`") {
338
+ let j = i + 1;
339
+ while (j < sql.length) {
340
+ if (sql[j] === ch) {
341
+ if (sql[j + 1] === ch) {
342
+ j += 2;
343
+ continue;
344
+ }
345
+ break;
346
+ }
347
+ j++;
348
+ }
349
+ out += sql.slice(i, j + 1);
350
+ i = j;
351
+ continue;
352
+ }
353
+ if (ch === "-" && sql[i + 1] === "-") {
354
+ let j = sql.indexOf("\n", i);
355
+ if (j === -1) j = sql.length;
356
+ out += sql.slice(i, j);
357
+ i = j - 1;
358
+ continue;
359
+ }
360
+ if (ch === "/" && sql[i + 1] === "*") {
361
+ let j = sql.indexOf("*/", i + 2);
362
+ j = j === -1 ? sql.length : j + 2;
363
+ out += sql.slice(i, j);
364
+ i = j - 1;
365
+ continue;
366
+ }
367
+ if (ch === "?") {
368
+ if (p >= parameters.length) throw new Error("[db] Query has more `?` placeholders than parameters while inlining");
369
+ out += escapeLiteral(parameters[p++]);
370
+ continue;
371
+ }
372
+ out += ch;
373
+ }
374
+ if (p !== parameters.length) throw new Error(`[db] Inlined ${p} parameter(s) but the query provided ${parameters.length} — placeholder/parameter mismatch`);
375
+ return out;
376
+ }
377
+ /**
378
+ * A Kysely driver that uses Cloudflare DO SQLite storage
379
+ */
380
+ var CloudflareSqliteDriver = class {
381
+ sql;
382
+ constructor(sql) {
383
+ this.sql = sql;
384
+ }
385
+ async init() {}
386
+ async acquireConnection() {
387
+ return new CloudflareSqliteConnection(this.sql);
388
+ }
389
+ async beginTransaction(connection, settings) {
390
+ if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
391
+ await connection.executeQuery(createCompiledQuery("BEGIN"));
392
+ }
393
+ async commitTransaction(connection) {
394
+ await connection.executeQuery(createCompiledQuery("COMMIT"));
395
+ }
396
+ async rollbackTransaction(connection) {
397
+ await connection.executeQuery(createCompiledQuery("ROLLBACK"));
398
+ }
399
+ async releaseConnection() {}
400
+ async destroy() {}
401
+ };
402
+ /**
403
+ * Helper to create a CompiledQuery object
404
+ */
405
+ function createCompiledQuery(sql, parameters = []) {
406
+ return {
407
+ sql,
408
+ parameters,
409
+ query: {
410
+ kind: "RawNode",
411
+ sqlFragments: [sql],
412
+ parameters: []
413
+ }
414
+ };
415
+ }
416
+ /**
417
+ * A Kysely connection that wraps Cloudflare's SqlStorage
418
+ */
419
+ var CloudflareSqliteConnection = class {
420
+ sql;
421
+ constructor(sql) {
422
+ this.sql = sql;
423
+ }
424
+ async executeQuery(compiledQuery) {
425
+ let queryStr = compiledQuery.sql;
426
+ let parameters = compiledQuery.parameters.map(normalizeParameter);
427
+ if (parameters.length > MAX_BOUND_PARAMETERS) {
428
+ queryStr = inlineParameters(queryStr, parameters);
429
+ parameters = [];
430
+ }
431
+ const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
432
+ try {
433
+ if (isSelect) return {
434
+ rows: this.sql.exec(queryStr, ...parameters).toArray(),
435
+ numAffectedRows: void 0,
436
+ insertId: void 0
437
+ };
438
+ else {
439
+ this.sql.exec(queryStr, ...parameters);
440
+ const [result] = this.sql.exec("SELECT changes() AS changes, last_insert_rowid() AS id").toArray();
441
+ const changes = result?.changes ?? 0;
442
+ const lastId = result?.id;
443
+ return {
444
+ rows: [],
445
+ numAffectedRows: BigInt(changes),
446
+ insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
447
+ };
448
+ }
449
+ } catch (error) {
450
+ throw error;
451
+ }
452
+ }
453
+ streamQuery() {
454
+ throw new Error("Streaming is not supported in Cloudflare SQLite");
455
+ }
456
+ };
457
+ /**
458
+ * Create a Kysely instance from Cloudflare SqlStorage
459
+ *
460
+ * @param sqlStorage - The Cloudflare SqlStorage instance
461
+ * @param options - Configuration options including schema for plugins
462
+ */
463
+ function createKyselyFromSql(sqlStorage, options = {}) {
464
+ const { schema, plugins = [], camelCase = true } = options;
465
+ const sqliteDialect = new SqliteDialect({ database: null });
466
+ const allPlugins = [];
467
+ const naming = schema && camelCase ? new SchemaPlugin(schema) : void 0;
468
+ const related = schema ? createRelatedPlugins(schema, naming ? { resultKey: (name) => naming.resultKey(name) } : {}) : void 0;
469
+ if (related) allPlugins.push(related.capture);
470
+ if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
471
+ else if (camelCase) {
472
+ allPlugins.push(new CamelCasePlugin());
473
+ allPlugins.push(new DateSerializePlugin());
474
+ } else allPlugins.push(new DateSerializePlugin());
475
+ allPlugins.push(...plugins);
476
+ if (related) allPlugins.push(related.results);
477
+ return new Kysely({
478
+ dialect: {
479
+ createAdapter: () => sqliteDialect.createAdapter(),
480
+ createDriver: () => new CloudflareSqliteDriver(sqlStorage),
481
+ createIntrospector: (db) => sqliteDialect.createIntrospector(db),
482
+ createQueryCompiler: () => new BacktickSqliteQueryCompiler()
483
+ },
484
+ plugins: allPlugins
485
+ });
486
+ }
487
+ //#endregion
488
+ export { OUTBOX_DEAD_TABLE as a, OUTBOX_TABLE as c, outboxRetryDelay as d, outboxSink as f, tenantOfInstanceKey as h, OUTBOX_DEAD_DDL as i, createActionOutbox as l, settleOutboxDelivery as m, OUTBOX_ADDED_COLUMNS as n, OUTBOX_SINK_DDL as o, queueOutboxSink as p, OUTBOX_DDL as r, OUTBOX_SINK_TABLE as s, createKyselyFromSql as t, outboxErrorText as u };
@@ -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 `{}`. */