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.
@@ -1172,7 +1172,8 @@ function defineDatabase(config) {
1172
1172
  args: actionConfig.args,
1173
1173
  handler: actionConfig.handler,
1174
1174
  validator,
1175
- schema
1175
+ schema,
1176
+ instance: config?.instance ?? "per-tenant"
1176
1177
  },
1177
1178
  enumerable: false,
1178
1179
  configurable: true
@@ -1,5 +1,5 @@
1
- import "./defineDatabase-BmjnvgJ8.js";
2
- import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
1
+ import "./defineDatabase-Dj5DOPUM.js";
2
+ import { n as Outbox, o as OutboxSink } from "./outbox-DpyNU99x.js";
3
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
4
4
  import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
5
5
  import { DurableObject } from "cloudflare:workers";
@@ -158,6 +158,20 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
158
158
  * best-effort name derived from its class name (`<PascalCase(name)>DatabaseDO`).
159
159
  */
160
160
  protected databaseName?: string;
161
+ /**
162
+ * The database's `instance` (`defineDatabase({ instance })`): the generated
163
+ * Durable Object sets it. A global database's instance has no tenant,
164
+ * whatever its key; a hand-written subclass that sets none is per-tenant,
165
+ * `defineDatabase()`'s default.
166
+ */
167
+ protected databaseInstance?: 'per-tenant' | 'global';
168
+ /**
169
+ * What the build appends to this database's instance keys —
170
+ * `applyDevEpoch('', name)`: `__dev_<epoch>` in dev, `''` in production. The
171
+ * generated Durable Object sets it; a key's tenant is the key without
172
+ * exactly this.
173
+ */
174
+ protected devEpochSuffix: string;
161
175
  /**
162
176
  * Whether migrations have been run for this instance
163
177
  */
@@ -181,33 +195,117 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
181
195
  */
182
196
  private pitrUnavailableReason;
183
197
  constructor(ctx: DurableObjectState, env: Env);
198
+ /**
199
+ * The name an outbox envelope gives this database: `databaseName`, else
200
+ * one derived from the class name, else the class name.
201
+ */
202
+ private knownDatabaseName;
203
+ /**
204
+ * The tenant of an instance key of this database: null for a global
205
+ * database, else the key without exactly the dev epoch the build applied
206
+ * (`devEpochSuffix`) — never cut anywhere else, so a tenant id containing
207
+ * `__dev_` is kept whole. What `getTenantId()` answers in an action
208
+ * (the generated `rpc` hands it to the action's context) and an outbox
209
+ * envelope's `tenantId`.
210
+ */
211
+ protected tenantOf(instanceKey: string): string | null;
184
212
  /**
185
213
  * Where the outbox delivers (`./outbox`): the generated class sets it from
186
214
  * `durableDb({ outbox })`. Null: `ctx.outbox.push()` refuses, naming the option.
187
215
  */
188
216
  protected outboxSink: OutboxSink | null;
217
+ /**
218
+ * How many counted failures move a message to `__outbox_dead`
219
+ * (`durableDb({ outbox: { maxAttempts } })`, which the generated class sets).
220
+ */
221
+ protected outboxMaxAttempts: number;
189
222
  private outboxReady;
223
+ /**
224
+ * Which storage this instance is on: `resetMigrationState()` (after
225
+ * `deleteAll()`) counts it up, so an alarm whose sink was still running
226
+ * when the storage was wiped settles nothing on the storage that replaced it.
227
+ */
228
+ private storageGeneration;
190
229
  private ensureOutboxTable;
230
+ /** What the outbox knows of its sink (one row by its key; both 0 before it was written). */
231
+ private outboxSinkState;
232
+ /** Writes the sink's row when it changed. */
233
+ private writeOutboxSinkState;
191
234
  /**
192
235
  * Runs an action with `ctx.outbox`. The messages it pushed are written when
193
236
  * it resolves — in the same synchronous block as its last writes, which the
194
237
  * Durable Object commits together — and the alarm that delivers them is set
195
- * with them. A handler that throws records nothing. An action called from
196
- * another action of this database runs on the caller's context, and so on
197
- * its outbox.
238
+ * with them: now, or, while the sink is taken for down, its next try, so a
239
+ * message recorded during an outage adds no alarm (the try still makes at
240
+ * most two sink calls). A handler that throws records nothing. An action
241
+ * called from another action of this database runs on the caller's context,
242
+ * and so on its outbox.
198
243
  */
199
244
  protected runWithOutbox<T>(ctx: {
200
245
  instanceKey: string;
201
246
  outbox?: Outbox;
202
247
  }, run: () => Promise<T>): Promise<T>;
203
248
  /**
204
- * Delivers the outbox: up to OUTBOX_DELIVERY_SIZE messages, oldest first, to
205
- * the sink; what was delivered is deleted, and the alarm comes back while
206
- * more are waiting. A delivery that throws stays in the table and is retried
207
- * with backoff (5 s, doubling, at most 5 minutes), so a message arrives at
208
- * least once. A subclass with an alarm of its own calls `super.alarm()`.
249
+ * Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
250
+ * A failure is judged only by what the sink did in the same alarm.
251
+ *
252
+ * While the sink is taken for down (`down_until` later than now) nothing is
253
+ * read or called, and the alarm is set to that time. Its next try hands it
254
+ * the newest message alone and, if the sink does not take it, the one tried
255
+ * or recorded longest ago alone (`max(tried_at, recorded_at)`), their own
256
+ * clocks ignored. A message a try handed that the sink neither delivered nor
257
+ * answered in `{ dead }` gets `tried_at` and its `last_error`, nothing else:
258
+ * no count, no clock. One it answered in `{ dead }` is moved to
259
+ * `__outbox_dead`, and is no delivery. When the sink takes one, it is up and
260
+ * the alarm goes on; else the next try backs off (5 s, doubling, at most 5
261
+ * minutes).
262
+ *
263
+ * Then it reads the oldest due messages, by id, at most 100, and hands them
264
+ * to the sink in one call. What a call did not deliver — all of it when the
265
+ * sink threw or answered malformed — is halved, and both halves are tried
266
+ * next, the first first. The one message of a call not delivered fails
267
+ * alone: it waits on its own backoff (`tries`), and the failure counts
268
+ * toward `outboxMaxAttempts` (`counted`) only when the sink delivered
269
+ * another message in this alarm, in that call or earlier; at the cap it is
270
+ * moved to `__outbox_dead`. A failure alone before anything was delivered in
271
+ * the alarm cannot be told from an outage: it counts nothing, and the sink is
272
+ * taken for down until its next try, in 5 s. A message the sink answers in
273
+ * `{ dead }` is moved to `__outbox_dead` at once, and is no delivery. The
274
+ * alarm is then set to the earliest message waiting — now, when one is due.
275
+ *
276
+ * After every awaited sink call the alarm checks that the storage is still
277
+ * the one it read, and writes nothing more when `destroyDatabase()` wiped it
278
+ * meanwhile. A message arrives at least once. A subclass with an alarm of its
279
+ * own calls `super.alarm()`.
209
280
  */
210
281
  alarm(): Promise<void>;
282
+ /**
283
+ * Takes the sink for down until its next try, for its `rounds`-th round in a
284
+ * row (1 when an alarm takes it down, one more for each try that finds it
285
+ * down): nothing is read or called before then (5 s, doubling, at most 5
286
+ * minutes), and the alarm is set to that time.
287
+ */
288
+ private takeOutboxSinkForDown;
289
+ /**
290
+ * One sink call: `rows` handed to the sink as envelopes, in a frozen list of
291
+ * its own. What it delivered is deleted and what it gave up on (`{ dead }`)
292
+ * buried, in the synchronous block after the call. Null when the storage was
293
+ * wiped while the sink ran (`storageGeneration` moved on from `generation`):
294
+ * nothing is written then — the rows are gone, and an id now names another
295
+ * row.
296
+ */
297
+ private callOutboxSink;
298
+ /**
299
+ * A message that failed alone: `tries` moves on, and with it its backoff
300
+ * (`next_attempt_at`). When it `counts` — the sink delivered another message
301
+ * in this alarm, in its call or earlier — `counted` moves on too, and at
302
+ * `outboxMaxAttempts` the message is moved to `__outbox_dead`.
303
+ */
304
+ private failOutboxRowAlone;
305
+ /** What the alarm logs of its failures: one line for those retried (or for the sink taken for down), one for those buried. */
306
+ private logOutboxFailures;
307
+ /** A row to `__outbox_dead`, as it was in `__outbox` (its id kept), with its counted failures and last error. */
308
+ private buryOutboxRow;
211
309
  /**
212
310
  * Check if PITR is available on this DO's storage.
213
311
  * Result is cached after the first call.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as Type, l as type } from "./index-bUUlOWfP.js";
2
- import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-BmjnvgJ8.js";
3
- import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-Dj5DOPUM.js";
3
+ import { a as OutboxMessage, c as OutboxSinkModule, i as OutboxEnvelope, n as Outbox, o as OutboxSink, r as OutboxDelivery, s as OutboxSinkContext, t as InstanceKeyOrigin } from "./outbox-DpyNU99x.js";
4
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
5
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
6
6
  import { Kysely } from "kysely";
@@ -20,4 +20,4 @@ interface ActionDescription {
20
20
  /** The description of an action, or undefined for anything that is not one. */
21
21
  export declare function describeAction(action: unknown): ActionDescription | undefined;
22
22
  //#endregion
23
- export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
23
+ export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type InstanceKeyOrigin, type Kysely, type Outbox, type OutboxDelivery, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-B1pKzO-V.js";
1
+ import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-_AusJf3r.js";
2
2
  import { r as type } from "./type-pAQ37iEL.js";
3
3
  import "./actionArgs-oUWwX6Xn.js";
4
4
  import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
@@ -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 };