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.
- 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-BmjnvgJ8.d.ts → defineDatabase-Dj5DOPUM.d.ts} +1 -1
- package/dist/{defineDatabase-B1pKzO-V.js → defineDatabase-_AusJf3r.js} +2 -1
- package/dist/{index-Di-UGgpS.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/README.md
CHANGED
|
@@ -333,7 +333,7 @@ import { getRequestInfo } from 'rwsdk/worker';
|
|
|
333
333
|
setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
|
|
334
334
|
```
|
|
335
335
|
|
|
336
|
-
The resolver is called at the moment a database operation needs the tenant ID — by which point request middleware (auth, session, etc.) has already completed.
|
|
336
|
+
The resolver is called at the moment a database operation needs the tenant ID — by which point request middleware (auth, session, etc.) has already completed. Inside a per-tenant database's Durable Object it is not called: code running there gets the object's own tenant (see [the tenant inside the object](#epoch-system)).
|
|
337
337
|
|
|
338
338
|
### How it works
|
|
339
339
|
|
|
@@ -807,6 +807,8 @@ Epochs are base36-encoded timestamps stored in `node_modules/.cache/durable-db/s
|
|
|
807
807
|
|
|
808
808
|
**How the epoch reaches the worker**: the Vite plugin serves a virtual module (`virtual:durable-db/__devEpoch`) exporting `applyDevEpoch(key, dbName)`, and every generated stub routes its instance key through it with its database's name. In dev the plugin embeds the epochs from `state.json`; in production builds the epoch is `null` and `applyDevEpoch` is the identity function, so production keys are never suffixed. The dev server watches durable-db's dev cache directory and reloads on change, so both `db reset` (new epoch → fresh instances) and `db push` (new dev migration → re-embedded into the DO module) take effect on the next request without restarting.
|
|
809
809
|
|
|
810
|
+
**The tenant inside the object** is worked out from what the build applied, never by cutting the key at a guess: each generated class knows its database's `instance` and its own suffix (`applyDevEpoch('', name)`: `__dev_<epoch>` in dev, nothing in production). A global database's instance has no tenant, whatever its key; a per-tenant one's tenant is its key without exactly that suffix — so a tenant named `global` is a tenant, and a tenant id that contains `__dev_` is kept whole. In dev every key carries an epoch, so a key that does not end with the current one is an earlier epoch's — an object `db reset` left behind, whose alarm still delivers what waits in its outbox — and its trailing `__dev_<epoch>` is cut; in production the key is the tenant, whole. That is what an outbox envelope's `tenantId` says, and what `getTenantId()` answers for code running in a per-tenant database's object — an action, and what it calls (another database's action included) — *before* any resolver: the resolver you install with `setTenantIdResolver()` at the worker module's top level is installed in every object's isolate too (in dev the worker and the objects share one), but the object's own tenant cannot be wrong for code running in it, and a resolver that reads a request would throw there. The one thing this rules out: a resolver cannot answer another tenant for an action of a per-tenant object. A global database's object has no tenant of its own, so there — as everywhere outside an object — the resolver answers. So it does in an object's alarm, which runs no action: the outbox sink has no request and no action's context there, and reads the tenant from `envelope.tenantId` — when it calls `getTenantId()`, or another per-tenant database's action whose stub does, the resolver is asked (and throws, without one). `tenantOfInstanceKey(key, { instance, devEpochSuffix })` (`durable-db/db`) works out the tenant of a key you hold the same way.
|
|
811
|
+
|
|
810
812
|
### Dev State Structure
|
|
811
813
|
|
|
812
814
|
```
|
|
@@ -1145,18 +1147,40 @@ durableDb({ outbox: { module: './src/outbox.ts' } }) // a module whose default
|
|
|
1145
1147
|
// src/outbox.ts — a function, or an object with `deliver`
|
|
1146
1148
|
import type { OutboxEnvelope } from 'durable-db/db';
|
|
1147
1149
|
|
|
1148
|
-
export default async function deliver(envelopes: OutboxEnvelope[], { env }: { env: Env }) {
|
|
1150
|
+
export default async function deliver(envelopes: readonly OutboxEnvelope[], { env }: { env: Env }) {
|
|
1149
1151
|
for (const { message, tenantId } of envelopes) await env.WEBHOOKS.send({ ...message, tenant: tenantId });
|
|
1150
1152
|
}
|
|
1151
1153
|
```
|
|
1152
1154
|
|
|
1155
|
+
The list is the call's own and frozen: to chunk or sort it, copy it first (`const queue = [...envelopes]`). A sink may also settle a call one envelope at a time: answer `{ retry }` with the envelopes it could not deliver now and `{ dead }` with those it never can — the very objects it was handed, in any order, either list may be left out — and every other one counts as delivered. A throw is a `{ retry }` of every envelope, and so is an answer that names anything else. Only a delivery is a delivery: a message in `{ dead }` is not.
|
|
1156
|
+
|
|
1157
|
+
```ts
|
|
1158
|
+
export default async function deliver(envelopes: readonly OutboxEnvelope[], { env }: { env: Env }) {
|
|
1159
|
+
const retry: OutboxEnvelope[] = [];
|
|
1160
|
+
const dead: OutboxEnvelope[] = [];
|
|
1161
|
+
for (const envelope of envelopes) {
|
|
1162
|
+
const response = await fetch(env.WEBHOOK_URL, { method: 'POST', body: JSON.stringify(envelope.message) });
|
|
1163
|
+
if (response.status >= 500) retry.push(envelope);
|
|
1164
|
+
else if (!response.ok) dead.push(envelope); // a 4xx: sending it again changes nothing
|
|
1165
|
+
}
|
|
1166
|
+
return { retry, dead, error: retry.length + dead.length > 0 ? new Error('the webhook refused some') : undefined };
|
|
1167
|
+
}
|
|
1168
|
+
```
|
|
1169
|
+
|
|
1153
1170
|
- **With the action's writes.** The messages are written to the object's `__outbox` table when the handler resolves, in the same synchronous block as its last writes — the Durable Object commits them together — and the alarm that delivers them is set with them. A handler that throws records none. An action called from another action of the same database shares its outbox.
|
|
1154
|
-
- **At least once.** The alarm hands the oldest messages
|
|
1155
|
-
- **
|
|
1171
|
+
- **At least once, oldest first.** The alarm hands the sink the oldest messages that are due, by id, up to 100 in a call, and deletes what it delivered. A message may arrive twice — make what consumes it idempotent. No order is kept across a failure: a message that failed waits on its own backoff while the ones behind it go on.
|
|
1172
|
+
- **A failure counts only in an alarm that delivered another message.** What a call did not deliver is halved, and both halves are tried next in the same alarm, so a message the sink cannot take ends up the one of its call not delivered, and the rest are delivered: of 100 messages with one bad, the other 99 go in that alarm — unless the bad one is the oldest of the read and the sink fails every call that holds it: then it fails alone before anything was delivered and takes the sink for down, and the 99 go at the next try, 5 s later (see below). A group that fails moves no clock and counts nothing. A message that fails alone — the one of its call not delivered — waits on its own backoff (5 s, doubling, at most 5 minutes), and the failure counts toward `maxAttempts` only when the sink delivered another message in the same alarm, in that call or earlier. So an alarm in which the sink delivers nothing counts nothing, and an outage counts at most one failure a message.
|
|
1173
|
+
- **When the sink is down.** A failure alone before anything was delivered in its alarm cannot be told from an outage: it counts nothing, and the sink is taken for down. Until its next try nothing is read or called, and a message recorded meanwhile sets no alarm of its own. The try (5 s, doubling, at most 5 minutes) hands the sink the newest message alone and, if the sink does not take it, the one tried or recorded longest ago alone; one it neither takes nor answers in `{ dead }` goes behind every message recorded or tried before it, its count and backoff as they were, and one it answers in `{ dead }` is moved to `__outbox_dead`. The first try at which the sink takes one ends it, and the alarm goes on. So, over tries at which the sink takes nothing, every waiting message is handed alone by the try after as many tries as there are messages ahead of it; a message recorded meanwhile goes behind it (and is handed first, as the newest).
|
|
1174
|
+
- **Not forever.** A message is moved to the object's `__outbox_dead` table — its message, instance key, `recorded_at`, attempts, last error and `dead_at` — and logged with `console.error` when the sink answers it in `{ dead }`, or when its counted failures reach `maxAttempts` (default 100, at least 2; `durableDb({ outbox: { queue: 'EVENTS', maxAttempts: 20 } })`). It is never retried by itself and never dropped: deliver it from there, then delete it. An outage buries only a message that already had `maxAttempts` − 1 counted failures.
|
|
1175
|
+
- **What it costs.** An alarm makes at most 16 sink calls. An outage costs the rest of the alarm it began in (at most 16 calls in all) and at most 8 in the next; then each try makes at most two calls and writes at most two outbox rows and the outbox's own row, however much waits, and moves to `__outbox_dead` what the sink answers in `{ dead }`. An alarm while the sink is down reads no outbox row, and a message recorded meanwhile adds no alarm and leaves each try within those two calls and two outbox rows — though while only one message waited, its tries made one call. With 2 000 waiting, an hour of outage is 17 alarms and 40 calls; with a message recorded every 10 s, 17 alarms and 32 calls. The outbox has no index: each would be a billed row written per message.
|
|
1176
|
+
- **What it cannot tell.** A message the sink never takes while it takes nothing else — a poison on a quiet object, or every message refused — looks like an outage: it is never counted, and the sink stays taken for down, tried at its rounds (to 5 minutes). A message recorded meanwhile waits for the next try, at most 5 minutes, and is handed first as the newest; each such delivery can count the poison once. A message that fails alone before anything was delivered in its alarm (a refused message at the head of the read) takes the sink for down: the rest wait for the next try, 5 s; another 5 s for each later alarm whose read begins with a refused message the alarm before it had no call left to hand alone — that alarm takes the sink for down again, as when the try's alarm spends its 16 calls before it hands a second refused message alone; and a round more, doubled, for each try at which the sink refuses both messages it hands. While refused messages fill the head of the read — a sink relaying to two places, one of them down, refuses that one's messages and takes the rest — that is every alarm after a try: each try delivers only its newest message, and the rest wait, with no bound in tries, until those refused messages leave the read by their own backoff, the cap, or the sink taking them. With a message recorded every 2 s, one waited up to 22 minutes behind 300 refused messages; behind 1 000, most were still waiting after two hours. A sink that stops taking messages part-way through an alarm (a spent quota, a flap) has that alarm's failures alone counted: at most one a message an alarm. A sink that throws on a message it can never take, instead of answering it in `{ dead }`, has it found by halving, a few an alarm; an alarm that finds only such messages takes the sink for down for a round. And a sink that answers success for what it did not deliver loses it: the outbox takes its word.
|
|
1177
|
+
- **Envelopes.** The sink gets `{ message, database, instanceKey, tenantId, recordedAt, attempts }`: `database` is the name the database is known by (`db` commands use it), `tenantId` a per-tenant instance's tenant — null for a global database, by its instance kind, so a per-tenant database's tenant named `global` is that tenant (see [the tenant inside the object](#epoch-system)) — and `attempts` how many of its failures counted so far.
|
|
1178
|
+
- **The Queue sink** sends each message as it is, as JSON, in as few `sendBatch` calls as Cloudflare Queues takes: at most 100 messages and 256 KB a call. When one fails, the batches before it count as delivered and the rest are answered in `{ retry }`. A message larger than a queue message holds (128 KB, about 100 bytes of it the queue's own) is never sent: it is answered in `{ dead }`, so it goes to `__outbox_dead` at once instead of failing the batch it would be in.
|
|
1179
|
+
- **Upgrading.** An outbox 0.13 left gets the new columns once, and nothing is reset. Its own `attempts` column stays as it is, so 0.13 still runs on the table after a rollback, and is never read: 0.13 counted each failure on every message of its batch, and what it counted counts nothing toward `maxAttempts`.
|
|
1156
1180
|
- **JSON.** A message is a JSON value, checked when it is pushed.
|
|
1157
1181
|
- **Typed.** `push()` takes any JSON value until you declare the message: `declare global { interface DurableDbOutbox { message: { type: 'welcome-email'; userId: string } } }`.
|
|
1158
1182
|
- **Without a sink** `ctx.outbox.push()` throws, naming the option. The generated classes use the alarm for the outbox; a hand-written subclass with an alarm of its own calls `super.alarm()`.
|
|
1159
|
-
- **Tests.** `createTestDatabase()` keeps what successful actions pushed in `t.outbox`, and its `outbox` option delivers them as the sink would.
|
|
1183
|
+
- **Tests.** `createTestDatabase()` keeps what successful actions pushed in `t.outbox`, and its `outbox` option delivers them as the sink would (a frozen list of its own). Its envelopes carry the database and instance its options name: `database` (default `'test'`) and `instance` (default: the action's database's, per-tenant unless `defineDatabase()` says `global`, which runs the action on the key `'global'`).
|
|
1160
1184
|
|
|
1161
1185
|
## Action-to-Action Calls
|
|
1162
1186
|
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
|
|
2
2
|
import { C as parseRenameSpec, g as SchemaRenameRequiredError, h as SchemaAmbiguity, m as RenameAnswer, n as Snapshot, t as MigrationResolution, u as MigrationRisk } from "../snapshot-D3_SNABU.js";
|
|
3
|
-
import { l as DatabaseInfo } from "../defineDatabase-
|
|
4
|
-
import "../index-
|
|
3
|
+
import { l as DatabaseInfo } from "../defineDatabase-Dj5DOPUM.js";
|
|
4
|
+
import "../index-B1J4Kjum.js";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import "vite";
|
|
7
7
|
import "@babel/types";
|
package/dist/context/index.d.ts
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
*
|
|
5
5
|
* The resolver is called at the moment a database operation needs the tenant ID —
|
|
6
6
|
* by which point request middleware (auth, session, etc.) has already completed.
|
|
7
|
+
* In an action of a per-tenant database — and what the action calls — it is
|
|
8
|
+
* not asked: the object's own tenant is the answer there (see
|
|
9
|
+
* {@link getTenantId}). Elsewhere in the object it still is: the alarm, and so
|
|
10
|
+
* the outbox sink it runs, has no action's context (a sink reads the tenant
|
|
11
|
+
* from `envelope.tenantId`).
|
|
7
12
|
*
|
|
8
13
|
* @example
|
|
9
14
|
* ```ts
|
|
@@ -14,6 +19,34 @@
|
|
|
14
19
|
* ```
|
|
15
20
|
*/
|
|
16
21
|
export declare function setTenantIdResolver(resolver: (() => string) | null): void;
|
|
22
|
+
/**
|
|
23
|
+
* The current tenant ID.
|
|
24
|
+
*
|
|
25
|
+
* In an action of a per-tenant database's Durable Object, and in what it
|
|
26
|
+
* calls, the object's own tenant (its DoContext's `tenantId`) is the answer,
|
|
27
|
+
* before any resolver: it cannot be wrong for code running in that object,
|
|
28
|
+
* and a resolver that reads a request would throw there (the worker module's
|
|
29
|
+
* top level, where a resolver is installed, runs in every object's isolate
|
|
30
|
+
* too). So a resolver cannot answer another tenant for an action of a
|
|
31
|
+
* per-tenant object. Everywhere else the resolver answers: the worker, a
|
|
32
|
+
* global database's object (no tenant of its own), and an object's alarm —
|
|
33
|
+
* the outbox sink included, which has no action's context (it reads the
|
|
34
|
+
* tenant from `envelope.tenantId`). A store built by hand without a
|
|
35
|
+
* `tenantId` is read as its key, `'global'` as none, only when no resolver
|
|
36
|
+
* is set.
|
|
37
|
+
*
|
|
38
|
+
* @throws Error if no resolver is configured and no Durable Object supplies the tenant
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { getTenantId } from 'durable-db/context';
|
|
43
|
+
*
|
|
44
|
+
* async function myHandler() {
|
|
45
|
+
* const tenantId = getTenantId();
|
|
46
|
+
* // ...
|
|
47
|
+
* }
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
17
50
|
export declare function getTenantId(): string;
|
|
18
51
|
/**
|
|
19
52
|
* Check if a tenant ID resolver is configured (or a Durable Object context
|
package/dist/context/index.js
CHANGED
|
@@ -10,6 +10,11 @@ let tenantIdResolver = null;
|
|
|
10
10
|
*
|
|
11
11
|
* The resolver is called at the moment a database operation needs the tenant ID —
|
|
12
12
|
* by which point request middleware (auth, session, etc.) has already completed.
|
|
13
|
+
* In an action of a per-tenant database — and what the action calls — it is
|
|
14
|
+
* not asked: the object's own tenant is the answer there (see
|
|
15
|
+
* {@link getTenantId}). Elsewhere in the object it still is: the alarm, and so
|
|
16
|
+
* the outbox sink it runs, has no action's context (a sink reads the tenant
|
|
17
|
+
* from `envelope.tenantId`).
|
|
13
18
|
*
|
|
14
19
|
* @example
|
|
15
20
|
* ```ts
|
|
@@ -22,10 +27,51 @@ let tenantIdResolver = null;
|
|
|
22
27
|
function setTenantIdResolver(resolver) {
|
|
23
28
|
tenantIdResolver = resolver;
|
|
24
29
|
}
|
|
30
|
+
/** The DoContext store of the action running, when code runs inside a Durable Object's action. */
|
|
31
|
+
function doContextStore() {
|
|
32
|
+
const getStore = globalThis[Symbol.for("durable-db.doContext")];
|
|
33
|
+
return getStore?.();
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Inside a Durable Object the tenant is the object's own: the generated
|
|
37
|
+
* classes work it out from the instance key with what the build applied —
|
|
38
|
+
* null for a global database (its instance kind, not its key), else the key
|
|
39
|
+
* without exactly its dev epoch suffix (`__dev_<epoch>` in dev, nothing in
|
|
40
|
+
* production, so a tenant id containing `__dev_` is kept whole) — and hand it
|
|
41
|
+
* to the action's DoContext store (`tenantId`). The registry publishes its
|
|
42
|
+
* store getter on globalThis — see the note there for why this is not a
|
|
43
|
+
* module import.
|
|
44
|
+
*/
|
|
45
|
+
function objectTenant() {
|
|
46
|
+
const tenantId = doContextStore()?.tenantId;
|
|
47
|
+
return typeof tenantId === "string" && tenantId !== "" ? tenantId : null;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A store that does not say its tenant (one built by hand, not by a generated
|
|
51
|
+
* class): its key as it is, the key 'global' as no tenant.
|
|
52
|
+
*/
|
|
53
|
+
function tenantFromStoreKey() {
|
|
54
|
+
const store = doContextStore();
|
|
55
|
+
if (!store?.instanceKey || store.tenantId !== void 0) return null;
|
|
56
|
+
return store.instanceKey === "global" ? null : store.instanceKey;
|
|
57
|
+
}
|
|
25
58
|
/**
|
|
26
|
-
*
|
|
59
|
+
* The current tenant ID.
|
|
60
|
+
*
|
|
61
|
+
* In an action of a per-tenant database's Durable Object, and in what it
|
|
62
|
+
* calls, the object's own tenant (its DoContext's `tenantId`) is the answer,
|
|
63
|
+
* before any resolver: it cannot be wrong for code running in that object,
|
|
64
|
+
* and a resolver that reads a request would throw there (the worker module's
|
|
65
|
+
* top level, where a resolver is installed, runs in every object's isolate
|
|
66
|
+
* too). So a resolver cannot answer another tenant for an action of a
|
|
67
|
+
* per-tenant object. Everywhere else the resolver answers: the worker, a
|
|
68
|
+
* global database's object (no tenant of its own), and an object's alarm —
|
|
69
|
+
* the outbox sink included, which has no action's context (it reads the
|
|
70
|
+
* tenant from `envelope.tenantId`). A store built by hand without a
|
|
71
|
+
* `tenantId` is read as its key, `'global'` as none, only when no resolver
|
|
72
|
+
* is set.
|
|
27
73
|
*
|
|
28
|
-
* @throws Error if no resolver is configured
|
|
74
|
+
* @throws Error if no resolver is configured and no Durable Object supplies the tenant
|
|
29
75
|
*
|
|
30
76
|
* @example
|
|
31
77
|
* ```ts
|
|
@@ -37,31 +83,12 @@ function setTenantIdResolver(resolver) {
|
|
|
37
83
|
* }
|
|
38
84
|
* ```
|
|
39
85
|
*/
|
|
40
|
-
/**
|
|
41
|
-
* Inside a Durable Object the instance key IS the tenant (per-tenant DBs key
|
|
42
|
-
* their instances by tenant id, plus an optional `__dev_<epoch>` suffix in
|
|
43
|
-
* dev — the database's own epoch after `db reset --database`, else the
|
|
44
|
-
* project's). The registry publishes its DoContext store getter on globalThis
|
|
45
|
-
* — see the note there for why this is not a module import — so getTenantId()
|
|
46
|
-
* works in action handlers without the worker-side resolver, which the DO
|
|
47
|
-
* execution context never registers.
|
|
48
|
-
*/
|
|
49
|
-
function tenantIdFromDoContext() {
|
|
50
|
-
const getStore = globalThis[Symbol.for("durable-db.doContext")];
|
|
51
|
-
const key = getStore?.()?.instanceKey;
|
|
52
|
-
if (!key) return null;
|
|
53
|
-
const tenant = stripDevEpoch(key);
|
|
54
|
-
return tenant === "global" ? null : tenant;
|
|
55
|
-
}
|
|
56
|
-
/** An instance key without its dev-epoch suffix (`<key>__dev_<epoch>` → `<key>`). */
|
|
57
|
-
function stripDevEpoch(instanceKey) {
|
|
58
|
-
const suffixAt = instanceKey.lastIndexOf("__dev_");
|
|
59
|
-
return suffixAt === -1 ? instanceKey : instanceKey.slice(0, suffixAt);
|
|
60
|
-
}
|
|
61
86
|
function getTenantId() {
|
|
87
|
+
const own = objectTenant();
|
|
88
|
+
if (own) return own;
|
|
62
89
|
if (tenantIdResolver) return tenantIdResolver();
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
90
|
+
const fromKey = tenantFromStoreKey();
|
|
91
|
+
if (fromKey) return fromKey;
|
|
65
92
|
throw new Error("getTenantId() called without a resolver. Call setTenantIdResolver() first.");
|
|
66
93
|
}
|
|
67
94
|
/**
|
|
@@ -69,7 +96,7 @@ function getTenantId() {
|
|
|
69
96
|
* can supply the tenant).
|
|
70
97
|
*/
|
|
71
98
|
function hasTenantId() {
|
|
72
|
-
return tenantIdResolver !== null ||
|
|
99
|
+
return objectTenant() !== null || tenantIdResolver !== null || tenantFromStoreKey() !== null;
|
|
73
100
|
}
|
|
74
101
|
/**
|
|
75
102
|
* One-time warning guard: we only log an unexpected dev-epoch load failure
|
package/dist/db/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { l as type } from "../index-bUUlOWfP.js";
|
|
2
|
-
import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, 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-
|
|
3
|
-
import { a as
|
|
4
|
-
import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-
|
|
5
|
-
export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type AnyRelated, type AnySchema, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type JsonPluginOptions, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
|
|
2
|
+
import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, 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, d as tenantOfInstanceKey, i as OutboxEnvelope, l as outboxSink, n as Outbox, o as OutboxSink, r as OutboxDelivery, s as OutboxSinkContext, t as InstanceKeyOrigin, u as queueOutboxSink } from "../outbox-DpyNU99x.js";
|
|
4
|
+
import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-B1J4Kjum.js";
|
|
5
|
+
export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type AnyRelated, type AnySchema, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type InstanceKeyOrigin, type JsonPluginOptions, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxDelivery, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
|
package/dist/db/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
|
|
2
|
-
import { a as createRelated, c as DrizzleDefaultsPlugin, d as createJsonPlugins, f as dateSerializers, h as relationsOf, i as RelatedExpression, l as SchemaPlugin, m as relationOf, n as defineDatabase, p as parseJsonValue, s as DateSerializePlugin, u as createDrizzlePlugins } from "../defineDatabase-
|
|
2
|
+
import { a as createRelated, c as DrizzleDefaultsPlugin, d as createJsonPlugins, f as dateSerializers, h as relationsOf, i as RelatedExpression, l as SchemaPlugin, m as relationOf, n as defineDatabase, p as parseJsonValue, s as DateSerializePlugin, u as createDrizzlePlugins } from "../defineDatabase-_AusJf3r.js";
|
|
3
3
|
import { r as type } from "../type-pAQ37iEL.js";
|
|
4
4
|
import "../actionArgs-oUWwX6Xn.js";
|
|
5
|
-
import { a as
|
|
5
|
+
import { a as OUTBOX_DEAD_TABLE, c as OUTBOX_TABLE, d as outboxRetryDelay, f as outboxSink, h as tenantOfInstanceKey, i as OUTBOX_DEAD_DDL, l as createActionOutbox, m as settleOutboxDelivery, n as OUTBOX_ADDED_COLUMNS, o as OUTBOX_SINK_DDL, p as queueOutboxSink, r as OUTBOX_DDL, s as OUTBOX_SINK_TABLE, t as createKyselyFromSql, u as outboxErrorText } from "../kysely-C675L1b9.js";
|
|
6
6
|
import { t as guardReferencingRows } from "../referencingRows-B6rU7TDW.js";
|
|
7
7
|
import { CamelCasePlugin } from "kysely";
|
|
8
8
|
import { DurableObject } from "cloudflare:workers";
|
|
@@ -51,6 +51,16 @@ function databaseNameFromClass(className) {
|
|
|
51
51
|
if (!match) return null;
|
|
52
52
|
return match[1].replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
53
53
|
}
|
|
54
|
+
/** The columns of {@link OutboxRow}. */
|
|
55
|
+
const OUTBOX_ROW = "id, instance_key, message, recorded_at, tries, counted";
|
|
56
|
+
/**
|
|
57
|
+
* The messages a try of the down sink hands it, one a call, their own clocks
|
|
58
|
+
* ignored: the newest, then — if the sink did not take it — the one tried or
|
|
59
|
+
* recorded longest ago.
|
|
60
|
+
*/
|
|
61
|
+
const OUTBOX_TRY_ORDER = ["id DESC", "max(tried_at, recorded_at), id"];
|
|
62
|
+
/** What the logs say of `__outbox_dead`. */
|
|
63
|
+
const OUTBOX_ASIDE = `to the table ${OUTBOX_DEAD_TABLE} of its Durable Object: they are not retried — deliver them from there, then delete them.`;
|
|
54
64
|
/**
|
|
55
65
|
* Raised when a pending migration fails with "already exists" or "duplicate
|
|
56
66
|
* column name": the storage holds schema objects the `__migrations` journal
|
|
@@ -140,6 +150,20 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
140
150
|
*/
|
|
141
151
|
databaseName;
|
|
142
152
|
/**
|
|
153
|
+
* The database's `instance` (`defineDatabase({ instance })`): the generated
|
|
154
|
+
* Durable Object sets it. A global database's instance has no tenant,
|
|
155
|
+
* whatever its key; a hand-written subclass that sets none is per-tenant,
|
|
156
|
+
* `defineDatabase()`'s default.
|
|
157
|
+
*/
|
|
158
|
+
databaseInstance;
|
|
159
|
+
/**
|
|
160
|
+
* What the build appends to this database's instance keys —
|
|
161
|
+
* `applyDevEpoch('', name)`: `__dev_<epoch>` in dev, `''` in production. The
|
|
162
|
+
* generated Durable Object sets it; a key's tenant is the key without
|
|
163
|
+
* exactly this.
|
|
164
|
+
*/
|
|
165
|
+
devEpochSuffix = "";
|
|
166
|
+
/**
|
|
143
167
|
* Whether migrations have been run for this instance
|
|
144
168
|
*/
|
|
145
169
|
migrationsApplied = false;
|
|
@@ -166,23 +190,80 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
166
190
|
this.sql = ctx.storage.sql;
|
|
167
191
|
}
|
|
168
192
|
/**
|
|
193
|
+
* The name an outbox envelope gives this database: `databaseName`, else
|
|
194
|
+
* one derived from the class name, else the class name.
|
|
195
|
+
*/
|
|
196
|
+
knownDatabaseName() {
|
|
197
|
+
return this.databaseName ?? databaseNameFromClass(this.constructor.name) ?? this.constructor.name;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The tenant of an instance key of this database: null for a global
|
|
201
|
+
* database, else the key without exactly the dev epoch the build applied
|
|
202
|
+
* (`devEpochSuffix`) — never cut anywhere else, so a tenant id containing
|
|
203
|
+
* `__dev_` is kept whole. What `getTenantId()` answers in an action
|
|
204
|
+
* (the generated `rpc` hands it to the action's context) and an outbox
|
|
205
|
+
* envelope's `tenantId`.
|
|
206
|
+
*/
|
|
207
|
+
tenantOf(instanceKey) {
|
|
208
|
+
return tenantOfInstanceKey(instanceKey, {
|
|
209
|
+
instance: this.databaseInstance ?? "per-tenant",
|
|
210
|
+
devEpochSuffix: this.devEpochSuffix
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
169
214
|
* Where the outbox delivers (`./outbox`): the generated class sets it from
|
|
170
215
|
* `durableDb({ outbox })`. Null: `ctx.outbox.push()` refuses, naming the option.
|
|
171
216
|
*/
|
|
172
217
|
outboxSink = null;
|
|
218
|
+
/**
|
|
219
|
+
* How many counted failures move a message to `__outbox_dead`
|
|
220
|
+
* (`durableDb({ outbox: { maxAttempts } })`, which the generated class sets).
|
|
221
|
+
*/
|
|
222
|
+
outboxMaxAttempts = 100;
|
|
173
223
|
outboxReady = false;
|
|
224
|
+
/**
|
|
225
|
+
* Which storage this instance is on: `resetMigrationState()` (after
|
|
226
|
+
* `deleteAll()`) counts it up, so an alarm whose sink was still running
|
|
227
|
+
* when the storage was wiped settles nothing on the storage that replaced it.
|
|
228
|
+
*/
|
|
229
|
+
storageGeneration = 0;
|
|
174
230
|
ensureOutboxTable() {
|
|
175
231
|
if (this.outboxReady) return;
|
|
176
232
|
this.sql.exec(OUTBOX_DDL);
|
|
233
|
+
this.sql.exec(OUTBOX_SINK_DDL);
|
|
234
|
+
const columns = /* @__PURE__ */ new Map();
|
|
235
|
+
const has = (table, column) => {
|
|
236
|
+
let names = columns.get(table);
|
|
237
|
+
if (!names) {
|
|
238
|
+
names = new Set(this.sql.exec(`PRAGMA table_info(${table})`).toArray().map(({ name }) => name));
|
|
239
|
+
columns.set(table, names);
|
|
240
|
+
}
|
|
241
|
+
return names.has(column);
|
|
242
|
+
};
|
|
243
|
+
for (const { table, column, ddl } of OUTBOX_ADDED_COLUMNS) if (!has(table, column)) this.sql.exec(ddl);
|
|
177
244
|
this.outboxReady = true;
|
|
178
245
|
}
|
|
246
|
+
/** What the outbox knows of its sink (one row by its key; both 0 before it was written). */
|
|
247
|
+
outboxSinkState() {
|
|
248
|
+
return this.sql.exec(`SELECT down_until, down_rounds FROM __outbox_sink WHERE id = 1`).toArray()[0] ?? {
|
|
249
|
+
down_until: 0,
|
|
250
|
+
down_rounds: 0
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** Writes the sink's row when it changed. */
|
|
254
|
+
writeOutboxSinkState(was, state) {
|
|
255
|
+
if (state.down_until === was.down_until && state.down_rounds === was.down_rounds) return;
|
|
256
|
+
this.sql.exec(`INSERT INTO ${OUTBOX_SINK_TABLE} (id, down_until, down_rounds) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET down_until = excluded.down_until, down_rounds = excluded.down_rounds`, state.down_until, state.down_rounds);
|
|
257
|
+
}
|
|
179
258
|
/**
|
|
180
259
|
* Runs an action with `ctx.outbox`. The messages it pushed are written when
|
|
181
260
|
* it resolves — in the same synchronous block as its last writes, which the
|
|
182
261
|
* Durable Object commits together — and the alarm that delivers them is set
|
|
183
|
-
* with them
|
|
184
|
-
*
|
|
185
|
-
*
|
|
262
|
+
* with them: now, or, while the sink is taken for down, its next try, so a
|
|
263
|
+
* message recorded during an outage adds no alarm (the try still makes at
|
|
264
|
+
* most two sink calls). A handler that throws records nothing. An action
|
|
265
|
+
* called from another action of this database runs on the caller's context,
|
|
266
|
+
* and so on its outbox.
|
|
186
267
|
*/
|
|
187
268
|
async runWithOutbox(ctx, run) {
|
|
188
269
|
if (ctx.outbox) return run();
|
|
@@ -194,41 +275,211 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
194
275
|
this.ensureOutboxTable();
|
|
195
276
|
const now = Date.now();
|
|
196
277
|
for (const message of messages) this.sql.exec(`INSERT INTO ${OUTBOX_TABLE} (instance_key, message, recorded_at) VALUES (?, ?, ?)`, ctx.instanceKey, message, now);
|
|
197
|
-
await this.ctx.storage.setAlarm(now);
|
|
278
|
+
await this.ctx.storage.setAlarm(Math.max(now, this.outboxSinkState().down_until));
|
|
198
279
|
}
|
|
199
280
|
return result;
|
|
200
281
|
}
|
|
201
282
|
/**
|
|
202
|
-
* Delivers the outbox
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
283
|
+
* Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
|
|
284
|
+
* A failure is judged only by what the sink did in the same alarm.
|
|
285
|
+
*
|
|
286
|
+
* While the sink is taken for down (`down_until` later than now) nothing is
|
|
287
|
+
* read or called, and the alarm is set to that time. Its next try hands it
|
|
288
|
+
* the newest message alone and, if the sink does not take it, the one tried
|
|
289
|
+
* or recorded longest ago alone (`max(tried_at, recorded_at)`), their own
|
|
290
|
+
* clocks ignored. A message a try handed that the sink neither delivered nor
|
|
291
|
+
* answered in `{ dead }` gets `tried_at` and its `last_error`, nothing else:
|
|
292
|
+
* no count, no clock. One it answered in `{ dead }` is moved to
|
|
293
|
+
* `__outbox_dead`, and is no delivery. When the sink takes one, it is up and
|
|
294
|
+
* the alarm goes on; else the next try backs off (5 s, doubling, at most 5
|
|
295
|
+
* minutes).
|
|
296
|
+
*
|
|
297
|
+
* Then it reads the oldest due messages, by id, at most 100, and hands them
|
|
298
|
+
* to the sink in one call. What a call did not deliver — all of it when the
|
|
299
|
+
* sink threw or answered malformed — is halved, and both halves are tried
|
|
300
|
+
* next, the first first. The one message of a call not delivered fails
|
|
301
|
+
* alone: it waits on its own backoff (`tries`), and the failure counts
|
|
302
|
+
* toward `outboxMaxAttempts` (`counted`) only when the sink delivered
|
|
303
|
+
* another message in this alarm, in that call or earlier; at the cap it is
|
|
304
|
+
* moved to `__outbox_dead`. A failure alone before anything was delivered in
|
|
305
|
+
* the alarm cannot be told from an outage: it counts nothing, and the sink is
|
|
306
|
+
* taken for down until its next try, in 5 s. A message the sink answers in
|
|
307
|
+
* `{ dead }` is moved to `__outbox_dead` at once, and is no delivery. The
|
|
308
|
+
* alarm is then set to the earliest message waiting — now, when one is due.
|
|
309
|
+
*
|
|
310
|
+
* After every awaited sink call the alarm checks that the storage is still
|
|
311
|
+
* the one it read, and writes nothing more when `destroyDatabase()` wiped it
|
|
312
|
+
* meanwhile. A message arrives at least once. A subclass with an alarm of its
|
|
313
|
+
* own calls `super.alarm()`.
|
|
207
314
|
*/
|
|
208
315
|
async alarm() {
|
|
209
316
|
if (!this.outboxSink) return;
|
|
210
317
|
this.ensureOutboxTable();
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
318
|
+
const was = this.outboxSinkState();
|
|
319
|
+
const now = Date.now();
|
|
320
|
+
if (was.down_until > now) {
|
|
321
|
+
await this.ctx.storage.setAlarm(was.down_until);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const generation = this.storageGeneration;
|
|
325
|
+
const failures = {
|
|
326
|
+
retried: 0,
|
|
327
|
+
buried: 0,
|
|
328
|
+
error: void 0
|
|
329
|
+
};
|
|
330
|
+
let delivered = false;
|
|
331
|
+
let calls = 0;
|
|
332
|
+
if (was.down_until > 0) {
|
|
333
|
+
let tried = 0;
|
|
334
|
+
for (const order of OUTBOX_TRY_ORDER) {
|
|
335
|
+
const row = this.sql.exec(`SELECT ${OUTBOX_ROW} FROM ${OUTBOX_TABLE} WHERE id <> ? ORDER BY ${order} LIMIT 1`, tried).toArray()[0];
|
|
336
|
+
if (!row) break;
|
|
337
|
+
const call = await this.callOutboxSink([row], generation);
|
|
338
|
+
if (!call || this.storageGeneration !== generation) return;
|
|
339
|
+
calls++;
|
|
340
|
+
tried = row.id;
|
|
341
|
+
if (call.delivered) {
|
|
342
|
+
delivered = true;
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
if (call.failed.length > 0) {
|
|
346
|
+
failures.error = call.error;
|
|
347
|
+
this.sql.exec(`UPDATE ${OUTBOX_TABLE} SET tried_at = ?, last_error = ? WHERE id = ?`, Date.now(), outboxErrorText(call.error), row.id);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (!delivered) {
|
|
351
|
+
if (calls === 0) return this.writeOutboxSinkState(was, {
|
|
352
|
+
down_until: 0,
|
|
353
|
+
down_rounds: 0
|
|
354
|
+
});
|
|
355
|
+
return this.takeOutboxSinkForDown(was, was.down_rounds + 1, failures);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const rows = this.sql.exec(`SELECT ${OUTBOX_ROW} FROM ${OUTBOX_TABLE} WHERE next_attempt_at <= ? ORDER BY id LIMIT ?`, now, 100).toArray();
|
|
359
|
+
const groups = rows.length > 0 ? [rows] : [];
|
|
360
|
+
while (groups.length > 0 && calls < 16) {
|
|
361
|
+
const call = await this.callOutboxSink(groups.shift(), generation);
|
|
362
|
+
if (!call || this.storageGeneration !== generation) return;
|
|
363
|
+
calls++;
|
|
364
|
+
if (call.delivered) delivered = true;
|
|
365
|
+
const { failed } = call;
|
|
366
|
+
if (failed.length > 1) {
|
|
367
|
+
const half = Math.ceil(failed.length / 2);
|
|
368
|
+
groups.unshift(failed.slice(0, half), failed.slice(half));
|
|
369
|
+
} else if (failed.length === 1) {
|
|
370
|
+
this.failOutboxRowAlone(failed[0], call.error, delivered, failures);
|
|
371
|
+
if (!delivered) return this.takeOutboxSinkForDown(was, 1, failures);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
this.writeOutboxSinkState(was, {
|
|
375
|
+
down_until: 0,
|
|
376
|
+
down_rounds: 0
|
|
377
|
+
});
|
|
378
|
+
this.logOutboxFailures(failures);
|
|
379
|
+
const { at } = this.sql.exec(`SELECT min(next_attempt_at) AS at FROM ${OUTBOX_TABLE}`).toArray()[0];
|
|
380
|
+
if (at !== null) await this.ctx.storage.setAlarm(Math.max(at, Date.now()));
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Takes the sink for down until its next try, for its `rounds`-th round in a
|
|
384
|
+
* row (1 when an alarm takes it down, one more for each try that finds it
|
|
385
|
+
* down): nothing is read or called before then (5 s, doubling, at most 5
|
|
386
|
+
* minutes), and the alarm is set to that time.
|
|
387
|
+
*/
|
|
388
|
+
async takeOutboxSinkForDown(was, rounds, failures) {
|
|
389
|
+
const now = Date.now();
|
|
390
|
+
const state = {
|
|
391
|
+
down_until: now + outboxRetryDelay(rounds),
|
|
392
|
+
down_rounds: rounds
|
|
393
|
+
};
|
|
394
|
+
this.writeOutboxSinkState(was, state);
|
|
395
|
+
this.logOutboxFailures(failures, state.down_until - now);
|
|
396
|
+
await this.ctx.storage.setAlarm(state.down_until);
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* One sink call: `rows` handed to the sink as envelopes, in a frozen list of
|
|
400
|
+
* its own. What it delivered is deleted and what it gave up on (`{ dead }`)
|
|
401
|
+
* buried, in the synchronous block after the call. Null when the storage was
|
|
402
|
+
* wiped while the sink ran (`storageGeneration` moved on from `generation`):
|
|
403
|
+
* nothing is written then — the rows are gone, and an id now names another
|
|
404
|
+
* row.
|
|
405
|
+
*/
|
|
406
|
+
async callOutboxSink(rows, generation) {
|
|
407
|
+
const database = this.knownDatabaseName();
|
|
408
|
+
const rowOf = /* @__PURE__ */ new Map();
|
|
409
|
+
for (const row of rows) rowOf.set({
|
|
215
410
|
message: JSON.parse(row.message),
|
|
411
|
+
database,
|
|
216
412
|
instanceKey: row.instance_key,
|
|
217
|
-
tenantId:
|
|
218
|
-
recordedAt: row.recorded_at
|
|
219
|
-
|
|
413
|
+
tenantId: this.tenantOf(row.instance_key),
|
|
414
|
+
recordedAt: row.recorded_at,
|
|
415
|
+
attempts: row.counted
|
|
416
|
+
}, row);
|
|
417
|
+
const envelopes = [...rowOf.keys()];
|
|
418
|
+
let answer;
|
|
220
419
|
try {
|
|
221
|
-
await this.outboxSink.deliver(envelopes, { env: this.env });
|
|
420
|
+
answer = settleOutboxDelivery(envelopes, await this.outboxSink.deliver(Object.freeze(envelopes.slice()), { env: this.env }));
|
|
222
421
|
} catch (error) {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
422
|
+
answer = {
|
|
423
|
+
retry: new Set(envelopes),
|
|
424
|
+
error,
|
|
425
|
+
dead: /* @__PURE__ */ new Set(),
|
|
426
|
+
deadError: void 0
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
if (this.storageGeneration !== generation) {
|
|
430
|
+
debugMigrations("The storage was wiped while the outbox sink ran: %d message(s) not settled", rows.length);
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
const failed = [];
|
|
434
|
+
let dead = 0;
|
|
435
|
+
let delivered = 0;
|
|
436
|
+
const now = Date.now();
|
|
437
|
+
for (const [envelope, row] of rowOf) if (answer.dead.has(envelope)) {
|
|
438
|
+
this.buryOutboxRow(row, row.counted, answer.deadError, now);
|
|
439
|
+
dead++;
|
|
440
|
+
} else if (answer.retry.has(envelope)) failed.push(row);
|
|
441
|
+
else {
|
|
442
|
+
this.sql.exec(`DELETE FROM ${OUTBOX_TABLE} WHERE id = ?`, row.id);
|
|
443
|
+
delivered++;
|
|
444
|
+
}
|
|
445
|
+
if (dead > 0) console.error(`[db] ${dead} outbox message(s) of ${database} the sink answered in { dead } were moved ${OUTBOX_ASIDE} The error:`, answer.deadError);
|
|
446
|
+
return {
|
|
447
|
+
failed,
|
|
448
|
+
error: answer.error,
|
|
449
|
+
delivered: delivered > 0
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* A message that failed alone: `tries` moves on, and with it its backoff
|
|
454
|
+
* (`next_attempt_at`). When it `counts` — the sink delivered another message
|
|
455
|
+
* in this alarm, in its call or earlier — `counted` moves on too, and at
|
|
456
|
+
* `outboxMaxAttempts` the message is moved to `__outbox_dead`.
|
|
457
|
+
*/
|
|
458
|
+
failOutboxRowAlone(row, error, counts, failures) {
|
|
459
|
+
const now = Date.now();
|
|
460
|
+
failures.error = error;
|
|
461
|
+
const tries = row.tries + 1;
|
|
462
|
+
const counted = row.counted + (counts ? 1 : 0);
|
|
463
|
+
if (counts && counted >= this.outboxMaxAttempts) {
|
|
464
|
+
this.buryOutboxRow(row, counted, error, now);
|
|
465
|
+
failures.buried++;
|
|
228
466
|
return;
|
|
229
467
|
}
|
|
230
|
-
this.sql.exec(`
|
|
231
|
-
|
|
468
|
+
this.sql.exec(`UPDATE ${OUTBOX_TABLE} SET tries = ?, counted = ?, next_attempt_at = ?, last_error = ? WHERE id = ?`, tries, counted, now + outboxRetryDelay(tries), outboxErrorText(error), row.id);
|
|
469
|
+
failures.retried++;
|
|
470
|
+
}
|
|
471
|
+
/** What the alarm logs of its failures: one line for those retried (or for the sink taken for down), one for those buried. */
|
|
472
|
+
logOutboxFailures({ retried, buried, error }, nextTryIn) {
|
|
473
|
+
const database = this.knownDatabaseName();
|
|
474
|
+
if (nextTryIn !== void 0) console.error(`[db] The outbox sink of ${database} is taken for down: it delivered nothing in this alarm. Its next try, the newest message and then the one waiting longest, is in ${nextTryIn / 1e3}s. The error:`, error);
|
|
475
|
+
else if (retried > 0) console.error(`[db] ${retried} outbox message(s) of ${database} failed alone and wait for their retry (5 s, doubling, at most 5 minutes). The last error:`, error);
|
|
476
|
+
if (buried > 0) console.error(`[db] ${buried} outbox message(s) of ${database} reached ${this.outboxMaxAttempts} counted failures (outbox maxAttempts) and were moved ${OUTBOX_ASIDE} The last error:`, error);
|
|
477
|
+
}
|
|
478
|
+
/** A row to `__outbox_dead`, as it was in `__outbox` (its id kept), with its counted failures and last error. */
|
|
479
|
+
buryOutboxRow(row, attempts, error, now) {
|
|
480
|
+
this.sql.exec(OUTBOX_DEAD_DDL);
|
|
481
|
+
this.sql.exec(`INSERT INTO ${OUTBOX_DEAD_TABLE} (id, instance_key, message, recorded_at, attempts, last_error, dead_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, row.id, row.instance_key, row.message, row.recorded_at, attempts, outboxErrorText(error), now);
|
|
482
|
+
this.sql.exec(`DELETE FROM ${OUTBOX_TABLE} WHERE id = ?`, row.id);
|
|
232
483
|
}
|
|
233
484
|
/**
|
|
234
485
|
* Check if PITR is available on this DO's storage.
|
|
@@ -254,6 +505,8 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
254
505
|
*/
|
|
255
506
|
resetMigrationState() {
|
|
256
507
|
this.migrationsApplied = false;
|
|
508
|
+
this.outboxReady = false;
|
|
509
|
+
this.storageGeneration++;
|
|
257
510
|
this.migrating = void 0;
|
|
258
511
|
debugMigrations("Migration state reset; migrations will re-run on next access");
|
|
259
512
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./index-bUUlOWfP.js";
|
|
2
|
-
import {
|
|
2
|
+
import { n as Outbox } from "./outbox-DpyNU99x.js";
|
|
3
3
|
import { type } from "arktype";
|
|
4
4
|
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
5
5
|
import { AliasNode, AliasedExpression, ColumnType, Expression, ExpressionBuilder, Kysely, KyselyPlugin, OperationNode, Selectable, SqlBool } from "kysely";
|