durable-db 0.14.2 → 0.15.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 +39 -4
- package/dist/cli/index.d.ts +2 -2
- package/dist/db/index.d.ts +2 -2
- package/dist/db/index.js +47 -19
- package/dist/{defineDatabase-Dj5DOPUM.d.ts → defineDatabase-Cc3LtKhn.d.ts} +12 -0
- package/dist/{index-Ba9mM6vU.d.ts → index-oTr2B0ap.d.ts} +21 -10
- package/dist/index.d.ts +1 -1
- package/dist/{kysely-Ddr685dO.js → kysely-BUmrdN9f.js} +11 -24
- package/dist/registry.d.ts +41 -8
- package/dist/registry.js +37 -9
- package/dist/testing/index.d.ts +6 -0
- package/dist/testing/index.js +94 -14
- package/dist/vite/durableDb.d.ts +1 -1
- package/dist/vite/durableDb.js +8 -5
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -274,7 +274,40 @@ Receives three arguments:
|
|
|
274
274
|
|----------|------|-------------|
|
|
275
275
|
| `db` | `Kysely<Schema>` | Type-safe Kysely query builder bound to your Drizzle schema |
|
|
276
276
|
| `args` | inferred from `args` | Validated arguments |
|
|
277
|
-
| `ctx` | `ActionContext` | Context with `env` (Cloudflare bindings) and `
|
|
277
|
+
| `ctx` | `ActionContext` | Context with `env` (Cloudflare bindings), `instanceKey`, `outbox` ([the outbox](#the-outbox)) and `transaction` (a part that may fail on its own, below) |
|
|
278
|
+
|
|
279
|
+
### One transaction
|
|
280
|
+
|
|
281
|
+
An action runs as one transaction of its Durable Object (`ctx.storage.transaction()`): when the handler resolves, its writes — and the messages it pushed to [the outbox](#the-outbox), with the alarm that delivers them — are committed together; when it throws, none of them are. A voucher and its lines, an invoice and its number: all or nothing.
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
export const postVoucher = action({
|
|
285
|
+
args: { series: 'string', lines: [{ account: 'string', amountOre: 'number.integer' }, '[]'] },
|
|
286
|
+
handler: async (db, args, ctx) => {
|
|
287
|
+
const last = await db.selectFrom('vouchers').select((eb) => eb.fn.max('number').as('n')).where('series', '=', args.series).executeTakeFirst();
|
|
288
|
+
const voucher = await db.insertInto('vouchers').values({ series: args.series, number: (last?.n ?? 0) + 1 }).returningAll().executeTakeFirstOrThrow();
|
|
289
|
+
await db.insertInto('lines').values(args.lines.map((line) => ({ voucherId: voucher.id, ...line }))).execute();
|
|
290
|
+
ctx.outbox.push({ type: 'voucher-posted', id: voucher.id });
|
|
291
|
+
return voucher;
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
- **No other call in between.** While an action runs, its object takes no other call: the runtime holds the next one until the action has resolved. So two actions never interleave — not at an `await` on another object or a `fetch`, not when several calls arrive while the object migrates —, and a read followed by a write (`max(number) + 1`, a balance) is never lost to another call.
|
|
297
|
+
- **A part that may fail on its own.** `ctx.transaction(async () => { … })` runs a part of the action as a savepoint: when it throws, its writes and the messages it pushed are rolled back, the error is the caller's to catch, and the action goes on. Two parts started at once run one after the other. An action called from another action of the same database runs as such a part, so it too is all or nothing.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
try {
|
|
301
|
+
await ctx.transaction(() => reserveSeat(db, args));
|
|
302
|
+
} catch {
|
|
303
|
+
await db.insertInto('waitlist').values(args).execute();
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
- **Kysely's `db.transaction()`** is refused, naming `ctx.transaction()`: the action already is one, and a Durable Object refuses SQL's `BEGIN` and `SAVEPOINT` anyway.
|
|
307
|
+
- **An action holds its object.** An action that waits on I/O — another database's action, a `fetch` — holds its object for that long, every other call of it waiting. Keep slow work out of actions (call it from the worker, or [push it to the outbox](#the-outbox)). The runtime resets an object whose action runs for more than 30 s, and the action's writes are rolled back.
|
|
308
|
+
- **Across objects nothing is atomic.** An action of another database (another object, or another tenant's) runs as a transaction of its own and commits on its own: when the calling action then throws, what the other one wrote stays. Use the outbox for the step that must follow a commit.
|
|
309
|
+
- **Calls between objects, in one direction.** An action that calls another database's action holds its object while the other runs. A call back into an object waiting on it — `billing → ledger → billing`, at any depth — would wait for itself; it is refused at once with an `ActionCycleError` naming the chain (from `durable-db/registry`). Two requests that call two objects in opposite orders (`billing → ledger` and `ledger → billing` at the same moment) wait for each other until the runtime resets them: keep calls between databases in one direction, or make them from the worker.
|
|
310
|
+
- **What it costs.** A transaction is about 0.07 ms of an action's time in the object (local workerd).
|
|
278
311
|
|
|
279
312
|
### File organization
|
|
280
313
|
|
|
@@ -1019,6 +1052,8 @@ t.destroy();
|
|
|
1019
1052
|
|
|
1020
1053
|
While a test database is live, an action called directly — from a page, a procedure, a job under test — runs against the newest live test database created with every table of the action's database.
|
|
1021
1054
|
|
|
1055
|
+
An action runs there as [in its Durable Object](#one-transaction): one transaction (`BEGIN … COMMIT`, rolled back when it throws), one at a time per test database — a run started while another runs waits for it —, `ctx.transaction()` and an action of the same database called from one as a savepoint, Kysely's `db.transaction()` refused, and a call back into a test database an action further out runs in refused with the `ActionCycleError` production gives. `t.runHandler(handler, args)` runs a handler whose args are already validated the same way, for a library that finds an action's handler itself.
|
|
1056
|
+
|
|
1022
1057
|
---
|
|
1023
1058
|
|
|
1024
1059
|
## Outerbase Studio Integration
|
|
@@ -1167,7 +1202,7 @@ export default async function deliver(envelopes: readonly OutboxEnvelope[], { en
|
|
|
1167
1202
|
}
|
|
1168
1203
|
```
|
|
1169
1204
|
|
|
1170
|
-
- **With the action's writes.** The messages are written to the object's `__outbox` table when the handler resolves, in the
|
|
1205
|
+
- **With the action's writes.** The messages are written to the object's `__outbox` table when the handler resolves, in [the action's transaction](#one-transaction), and the alarm that delivers them is set in it: committed with the action's writes, or — when it throws — none of them. A part of the action that is rolled back on its own (`ctx.transaction()`) takes the messages it pushed with it. An action called from another action of the same database shares its outbox.
|
|
1171
1206
|
- **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
1207
|
- **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
1208
|
- **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).
|
|
@@ -1210,8 +1245,8 @@ export const createUser = action({
|
|
|
1210
1245
|
|
|
1211
1246
|
### Routing behavior
|
|
1212
1247
|
|
|
1213
|
-
- **Same database**: The call uses a direct fast path via AsyncLocalStorage (no RPC overhead). The registry detects that we're already inside the target DO and calls the handler directly.
|
|
1214
|
-
- **Cross database**: The call routes through RPC to the other database's Durable Object, using the appropriate instance key based on the target database's strategy.
|
|
1248
|
+
- **Same database**: The call uses a direct fast path via AsyncLocalStorage (no RPC overhead). The registry detects that we're already inside the target DO and calls the handler directly, as a part of the caller's transaction (`ctx.transaction()`): when it throws, its writes are rolled back and the caller may go on.
|
|
1249
|
+
- **Cross database**: The call routes through RPC to the other database's Durable Object, using the appropriate instance key based on the target database's strategy. It is a transaction of its own there, and the caller's object waits for it: a call back into an object waiting on it is refused (`ActionCycleError`, see [One transaction](#one-transaction)).
|
|
1215
1250
|
|
|
1216
1251
|
---
|
|
1217
1252
|
|
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-Cc3LtKhn.js";
|
|
4
|
+
import "../index-oTr2B0ap.js";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import "vite";
|
|
7
7
|
import "@babel/types";
|
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-
|
|
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-Cc3LtKhn.js";
|
|
3
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-
|
|
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-oTr2B0ap.js";
|
|
5
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
|
@@ -2,7 +2,7 @@ import { a as setDebugSpec, i as init_debug, n as debugMigrations } from "../deb
|
|
|
2
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-xd-9vnhm.js";
|
|
3
3
|
import { r as type } from "../type-C7apBBQw.js";
|
|
4
4
|
import "../actionArgs-BAmU_AIB.js";
|
|
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-
|
|
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-BUmrdN9f.js";
|
|
6
6
|
import { t as guardReferencingRows } from "../referencingRows-B6rU7TDW.js";
|
|
7
7
|
import { CamelCasePlugin } from "kysely";
|
|
8
8
|
import { DurableObject } from "cloudflare:workers";
|
|
@@ -257,28 +257,56 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
257
257
|
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);
|
|
258
258
|
}
|
|
259
259
|
/**
|
|
260
|
-
* Runs an action
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
*
|
|
260
|
+
* Runs an action as one transaction (`ctx.storage.transaction()`): its
|
|
261
|
+
* writes, the messages it pushed to `ctx.outbox` and the alarm that delivers
|
|
262
|
+
* them are committed together when it resolves, and none of them when it
|
|
263
|
+
* throws. While it runs the object takes no other call — the runtime holds
|
|
264
|
+
* the next one until it resolves —, so two actions never interleave at an
|
|
265
|
+
* await, and an action that waits on I/O (another object, a fetch) holds
|
|
266
|
+
* its object for that long; after 30 s the runtime resets the object.
|
|
267
|
+
*
|
|
268
|
+
* `ctx.transaction(fn)` runs a part that may fail on its own: its writes and
|
|
269
|
+
* messages are rolled back when it throws, the rest of the action goes on
|
|
270
|
+
* (a savepoint). Two parts started at once run one after the other. An
|
|
271
|
+
* action called from another action of this database runs on the caller's
|
|
272
|
+
* context, in a part of its own.
|
|
273
|
+
*
|
|
274
|
+
* The messages are written to `__outbox` once the handler has resolved, and
|
|
275
|
+
* the alarm set to now — or, while the sink is taken for down, to its next
|
|
276
|
+
* try, so a message recorded during an outage adds no alarm (the try still
|
|
277
|
+
* makes at most two sink calls).
|
|
268
278
|
*/
|
|
269
|
-
async
|
|
270
|
-
|
|
279
|
+
async runAction(ctx, run) {
|
|
280
|
+
const storage = this.ctx.storage;
|
|
281
|
+
if (ctx.outbox) return ctx.transaction ? ctx.transaction(run) : storage.transaction(() => run());
|
|
271
282
|
const outbox = createActionOutbox(this.outboxSink !== null);
|
|
272
283
|
ctx.outbox = outbox;
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
284
|
+
ctx.transaction = (fn) => storage.transaction(async () => {
|
|
285
|
+
const mark = outbox.mark();
|
|
286
|
+
try {
|
|
287
|
+
return await fn();
|
|
288
|
+
} catch (error) {
|
|
289
|
+
outbox.rewind(mark);
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
const outboxWasReady = this.outboxReady;
|
|
294
|
+
try {
|
|
295
|
+
return await storage.transaction(async () => {
|
|
296
|
+
const result = await run();
|
|
297
|
+
const messages = outbox.take();
|
|
298
|
+
if (messages.length > 0) {
|
|
299
|
+
this.ensureOutboxTable();
|
|
300
|
+
const now = Date.now();
|
|
301
|
+
for (const message of messages) this.sql.exec(`INSERT INTO ${OUTBOX_TABLE} (instance_key, message, recorded_at) VALUES (?, ?, ?)`, ctx.instanceKey, message, now);
|
|
302
|
+
await storage.setAlarm(Math.max(now, this.outboxSinkState().down_until));
|
|
303
|
+
}
|
|
304
|
+
return result;
|
|
305
|
+
});
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (!outboxWasReady) this.outboxReady = false;
|
|
308
|
+
throw error;
|
|
280
309
|
}
|
|
281
|
-
return result;
|
|
282
310
|
}
|
|
283
311
|
/**
|
|
284
312
|
* Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
|
|
@@ -302,6 +302,18 @@ interface ActionContext<TEnv = unknown> {
|
|
|
302
302
|
* writes, at least once; a handler that throws records none.
|
|
303
303
|
*/
|
|
304
304
|
outbox: Outbox;
|
|
305
|
+
/**
|
|
306
|
+
* Runs a part of the action that may fail on its own. The action itself is
|
|
307
|
+
* one transaction — all of its writes, or none when it throws —; a part run
|
|
308
|
+
* here is rolled back alone when it throws (its writes and the messages it
|
|
309
|
+
* pushed), and the action can go on:
|
|
310
|
+
*
|
|
311
|
+
* try { await ctx.transaction(() => reserve(db, args)) } catch { await waitlist(db, args) }
|
|
312
|
+
*
|
|
313
|
+
* Two parts started at once run one after the other. An action called from
|
|
314
|
+
* another action of the same database runs as such a part.
|
|
315
|
+
*/
|
|
316
|
+
transaction<T>(fn: () => Promise<T>): Promise<T>;
|
|
305
317
|
}
|
|
306
318
|
/**
|
|
307
319
|
* Configuration for an action
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./defineDatabase-
|
|
1
|
+
import "./defineDatabase-Cc3LtKhn.js";
|
|
2
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";
|
|
@@ -232,18 +232,29 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
|
|
|
232
232
|
/** Writes the sink's row when it changed. */
|
|
233
233
|
private writeOutboxSinkState;
|
|
234
234
|
/**
|
|
235
|
-
* Runs an action
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
235
|
+
* Runs an action as one transaction (`ctx.storage.transaction()`): its
|
|
236
|
+
* writes, the messages it pushed to `ctx.outbox` and the alarm that delivers
|
|
237
|
+
* them are committed together when it resolves, and none of them when it
|
|
238
|
+
* throws. While it runs the object takes no other call — the runtime holds
|
|
239
|
+
* the next one until it resolves —, so two actions never interleave at an
|
|
240
|
+
* await, and an action that waits on I/O (another object, a fetch) holds
|
|
241
|
+
* its object for that long; after 30 s the runtime resets the object.
|
|
242
|
+
*
|
|
243
|
+
* `ctx.transaction(fn)` runs a part that may fail on its own: its writes and
|
|
244
|
+
* messages are rolled back when it throws, the rest of the action goes on
|
|
245
|
+
* (a savepoint). Two parts started at once run one after the other. An
|
|
246
|
+
* action called from another action of this database runs on the caller's
|
|
247
|
+
* context, in a part of its own.
|
|
248
|
+
*
|
|
249
|
+
* The messages are written to `__outbox` once the handler has resolved, and
|
|
250
|
+
* the alarm set to now — or, while the sink is taken for down, to its next
|
|
251
|
+
* try, so a message recorded during an outage adds no alarm (the try still
|
|
252
|
+
* makes at most two sink calls).
|
|
243
253
|
*/
|
|
244
|
-
protected
|
|
254
|
+
protected runAction<T>(ctx: {
|
|
245
255
|
instanceKey: string;
|
|
246
256
|
outbox?: Outbox;
|
|
257
|
+
transaction?: <R>(fn: () => Promise<R>) => Promise<R>;
|
|
247
258
|
}, run: () => Promise<T>): Promise<T>;
|
|
248
259
|
/**
|
|
249
260
|
* Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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-
|
|
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-Cc3LtKhn.js";
|
|
3
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";
|
|
@@ -249,7 +249,9 @@ function tenantOfInstanceKey(instanceKey, origin) {
|
|
|
249
249
|
* The outbox of one action run: `push()` collects, and once the handler has
|
|
250
250
|
* resolved `take()` hands the messages over to be written. A message must be
|
|
251
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.
|
|
252
|
+
* the action that pushed it rather than a delivery later. A part of the run
|
|
253
|
+
* that is rolled back on its own (`ctx.transaction()`, an action it calls)
|
|
254
|
+
* takes its messages with it: `rewind()` to the `mark()` it began at.
|
|
253
255
|
*/
|
|
254
256
|
function createActionOutbox(sinkConfigured) {
|
|
255
257
|
let messages = [];
|
|
@@ -264,6 +266,10 @@ function createActionOutbox(sinkConfigured) {
|
|
|
264
266
|
const taken = messages;
|
|
265
267
|
messages = [];
|
|
266
268
|
return taken;
|
|
269
|
+
},
|
|
270
|
+
mark: () => messages.length,
|
|
271
|
+
rewind(mark) {
|
|
272
|
+
messages.length = Math.min(messages.length, mark);
|
|
267
273
|
}
|
|
268
274
|
};
|
|
269
275
|
}
|
|
@@ -386,34 +392,15 @@ var CloudflareSqliteDriver = class {
|
|
|
386
392
|
async acquireConnection() {
|
|
387
393
|
return new CloudflareSqliteConnection(this.sql);
|
|
388
394
|
}
|
|
389
|
-
async beginTransaction(
|
|
390
|
-
|
|
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"));
|
|
395
|
+
async beginTransaction() {
|
|
396
|
+
throw new Error("[db] db.transaction() is not available: every action already runs as one transaction — all of its writes, or none when it throws. For a part that may fail on its own, use ctx.transaction(async () => { … }) (the handler's third argument): its writes are rolled back when it throws, and the action goes on.");
|
|
398
397
|
}
|
|
398
|
+
async commitTransaction() {}
|
|
399
|
+
async rollbackTransaction() {}
|
|
399
400
|
async releaseConnection() {}
|
|
400
401
|
async destroy() {}
|
|
401
402
|
};
|
|
402
403
|
/**
|
|
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
404
|
* A Kysely connection that wraps Cloudflare's SqlStorage
|
|
418
405
|
*/
|
|
419
406
|
var CloudflareSqliteConnection = class {
|
package/dist/registry.d.ts
CHANGED
|
@@ -50,6 +50,18 @@ export interface DoContext {
|
|
|
50
50
|
* as its key, `'global'` as no tenant, when no resolver is set.
|
|
51
51
|
*/
|
|
52
52
|
tenantId?: string | null;
|
|
53
|
+
/**
|
|
54
|
+
* The objects waiting on this call, outermost first: each is inside an
|
|
55
|
+
* action that called the next one. An action holds its object until it
|
|
56
|
+
* resolves (a transaction), so a call into one of them would wait for
|
|
57
|
+
* itself — `batchedRpc` refuses it (`ActionCycleError`).
|
|
58
|
+
*/
|
|
59
|
+
via?: ActionCaller[];
|
|
60
|
+
}
|
|
61
|
+
/** An object waiting on a call it made: its database and instance key. */
|
|
62
|
+
export interface ActionCaller {
|
|
63
|
+
database: string;
|
|
64
|
+
instanceKey: string;
|
|
53
65
|
}
|
|
54
66
|
export interface RpcContext {
|
|
55
67
|
env: Record<string, unknown>;
|
|
@@ -57,8 +69,23 @@ export interface RpcContext {
|
|
|
57
69
|
dbBindingNames: Record<string, string>;
|
|
58
70
|
dbTransports?: Record<string, 'rpc' | 'websocket'>;
|
|
59
71
|
instanceKey: string;
|
|
60
|
-
/** The action run's outbox (`
|
|
72
|
+
/** The action run's outbox (`runAction`); an action called from another of the same database shares it. */
|
|
61
73
|
outbox?: Outbox;
|
|
74
|
+
/**
|
|
75
|
+
* Runs `fn` as a part of the action that may fail on its own: its writes
|
|
76
|
+
* and the messages it pushed are rolled back when it throws, and the rest
|
|
77
|
+
* of the action goes on (`runAction`). An action called from another of
|
|
78
|
+
* the same database runs in one.
|
|
79
|
+
*/
|
|
80
|
+
transaction?: <T>(fn: () => Promise<T>) => Promise<T>;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* A call into an object that is waiting on it: an action holds its object
|
|
84
|
+
* until it resolves, so the call would wait for itself (for 30 s, after
|
|
85
|
+
* which the runtime resets the object).
|
|
86
|
+
*/
|
|
87
|
+
export declare class ActionCycleError extends Error {
|
|
88
|
+
constructor(via: readonly ActionCaller[], target: ActionCaller, action?: string);
|
|
62
89
|
}
|
|
63
90
|
export declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
|
|
64
91
|
export declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
|
|
@@ -90,16 +117,17 @@ export type BatchedResult = {
|
|
|
90
117
|
message: string;
|
|
91
118
|
};
|
|
92
119
|
};
|
|
120
|
+
/** What a call tells the object it reaches: its instance key, and the objects waiting on it. */
|
|
121
|
+
export interface RpcOptions {
|
|
122
|
+
instanceKey: string;
|
|
123
|
+
via?: ActionCaller[];
|
|
124
|
+
}
|
|
93
125
|
interface ActionStub {
|
|
94
|
-
rpc(action: string, args: unknown, options:
|
|
95
|
-
instanceKey: string;
|
|
96
|
-
}): Promise<unknown>;
|
|
126
|
+
rpc(action: string, args: unknown, options: RpcOptions): Promise<unknown>;
|
|
97
127
|
rpcBatch(calls: Array<{
|
|
98
128
|
action: string;
|
|
99
129
|
args: unknown;
|
|
100
|
-
}>, options:
|
|
101
|
-
instanceKey: string;
|
|
102
|
-
}): Promise<BatchedResult[]>;
|
|
130
|
+
}>, options: RpcOptions): Promise<BatchedResult[]>;
|
|
103
131
|
}
|
|
104
132
|
interface ActionNamespace {
|
|
105
133
|
idFromName(name: string): unknown;
|
|
@@ -131,7 +159,12 @@ export declare function batchScope<T>(fn: () => T): T;
|
|
|
131
159
|
* own caller; a lone call, and every call outside a scope, is a plain `rpc`.
|
|
132
160
|
* Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
|
|
133
161
|
* (React Server Components refuse symbol-keyed props).
|
|
162
|
+
*
|
|
163
|
+
* Made from an action (inside a Durable Object), the call names the objects
|
|
164
|
+
* waiting on it (`via`), and one into any of them is refused at once
|
|
165
|
+
* (`ActionCycleError`): `database` is the target's name, which the build
|
|
166
|
+
* passes.
|
|
134
167
|
*/
|
|
135
|
-
export declare function batchedRpc(namespace: ActionNamespace, instanceKey: string, action: string, args: unknown): Promise<unknown>;
|
|
168
|
+
export declare function batchedRpc(namespace: ActionNamespace, instanceKey: string, action: string, args: unknown, database?: string): Promise<unknown>;
|
|
136
169
|
//#endregion
|
|
137
170
|
export { actionArgsType as type };
|
package/dist/registry.js
CHANGED
|
@@ -4,6 +4,18 @@ import { t as ACTION_INFO } from "./describeAction-CEKfxTQ4.js";
|
|
|
4
4
|
import { WebSocketTransport } from "./transport/websocket.js";
|
|
5
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
6
|
//#region src/registry.ts
|
|
7
|
+
/**
|
|
8
|
+
* A call into an object that is waiting on it: an action holds its object
|
|
9
|
+
* until it resolves, so the call would wait for itself (for 30 s, after
|
|
10
|
+
* which the runtime resets the object).
|
|
11
|
+
*/
|
|
12
|
+
var ActionCycleError = class extends Error {
|
|
13
|
+
constructor(via, target, action) {
|
|
14
|
+
const name = ({ database, instanceKey }) => `${database} (${instanceKey})`;
|
|
15
|
+
super(`[db] ${action ? `${action}: a call` : "A call"} into ${name(target)}, which is waiting on this call: ${[...via, target].map(name).join(" → ")}. An action holds its object until it resolves, so the call would wait for itself. Make the calls from the worker, one after the other, or have the first action push the work to its outbox.`);
|
|
16
|
+
this.name = "ActionCycleError";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
7
19
|
const actionsByDb = /* @__PURE__ */ new Map();
|
|
8
20
|
const als = new AsyncLocalStorage();
|
|
9
21
|
const wsTransportCache = /* @__PURE__ */ new Map();
|
|
@@ -88,7 +100,7 @@ async function callAction(db, targetDb, actionName, args, ctx) {
|
|
|
88
100
|
const entry = getOrThrow(targetDb, actionName);
|
|
89
101
|
const validated = entry.validator(args);
|
|
90
102
|
if (validated instanceof type.errors) throw new Error(`[db] Invalid args for ${targetDb}/${actionName}: ${validated.summary}`);
|
|
91
|
-
if (ctx.dbName === targetDb) return entry.handler(db, validated, ctx);
|
|
103
|
+
if (ctx.dbName === targetDb) return ctx.transaction ? ctx.transaction(() => entry.handler(db, validated, ctx)) : entry.handler(db, validated, ctx);
|
|
92
104
|
const bindingName = ctx.dbBindingNames[targetDb];
|
|
93
105
|
if (!bindingName) {
|
|
94
106
|
const known = Object.keys(ctx.dbBindingNames);
|
|
@@ -137,8 +149,22 @@ function batchScope(fn) {
|
|
|
137
149
|
* own caller; a lone call, and every call outside a scope, is a plain `rpc`.
|
|
138
150
|
* Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
|
|
139
151
|
* (React Server Components refuse symbol-keyed props).
|
|
152
|
+
*
|
|
153
|
+
* Made from an action (inside a Durable Object), the call names the objects
|
|
154
|
+
* waiting on it (`via`), and one into any of them is refused at once
|
|
155
|
+
* (`ActionCycleError`): `database` is the target's name, which the build
|
|
156
|
+
* passes.
|
|
140
157
|
*/
|
|
141
|
-
function batchedRpc(namespace, instanceKey, action, args) {
|
|
158
|
+
function batchedRpc(namespace, instanceKey, action, args, database) {
|
|
159
|
+
const caller = als.getStore();
|
|
160
|
+
const via = caller ? [...caller.via ?? [], {
|
|
161
|
+
database: caller.dbName,
|
|
162
|
+
instanceKey: caller.instanceKey
|
|
163
|
+
}] : void 0;
|
|
164
|
+
if (via && database !== void 0 && via.some((waiting) => waiting.database === database && waiting.instanceKey === instanceKey)) return Promise.reject(new ActionCycleError(via, {
|
|
165
|
+
database,
|
|
166
|
+
instanceKey
|
|
167
|
+
}, action));
|
|
142
168
|
const scope = batchScopes.getStore();
|
|
143
169
|
return new Promise((resolve, reject) => {
|
|
144
170
|
const call = {
|
|
@@ -147,8 +173,11 @@ function batchedRpc(namespace, instanceKey, action, args) {
|
|
|
147
173
|
resolve,
|
|
148
174
|
reject
|
|
149
175
|
};
|
|
150
|
-
if (!scope) {
|
|
151
|
-
sendCalls(namespace,
|
|
176
|
+
if (!scope || via) {
|
|
177
|
+
sendCalls(namespace, via ? {
|
|
178
|
+
instanceKey,
|
|
179
|
+
via
|
|
180
|
+
} : { instanceKey }, [call]);
|
|
152
181
|
return;
|
|
153
182
|
}
|
|
154
183
|
let byKey = scope.pending.get(namespace);
|
|
@@ -165,18 +194,17 @@ function batchedRpc(namespace, instanceKey, action, args) {
|
|
|
165
194
|
function flushCalls(namespace, instanceKey, byKey) {
|
|
166
195
|
const calls = byKey.get(instanceKey) ?? [];
|
|
167
196
|
byKey.delete(instanceKey);
|
|
168
|
-
sendCalls(namespace, instanceKey, calls);
|
|
197
|
+
sendCalls(namespace, { instanceKey }, calls);
|
|
169
198
|
}
|
|
170
|
-
function sendCalls(namespace,
|
|
199
|
+
function sendCalls(namespace, options, calls) {
|
|
171
200
|
if (calls.length === 0) return;
|
|
172
201
|
let stub;
|
|
173
202
|
try {
|
|
174
|
-
stub = namespace.get(namespace.idFromName(instanceKey));
|
|
203
|
+
stub = namespace.get(namespace.idFromName(options.instanceKey));
|
|
175
204
|
} catch (error) {
|
|
176
205
|
for (const call of calls) call.reject(error);
|
|
177
206
|
return;
|
|
178
207
|
}
|
|
179
|
-
const options = { instanceKey };
|
|
180
208
|
if (calls.length === 1) {
|
|
181
209
|
const [call] = calls;
|
|
182
210
|
stub.rpc(call.action, call.args, options).then((value) => call.resolve(structuredClone(value)), call.reject);
|
|
@@ -197,4 +225,4 @@ function sendCalls(namespace, instanceKey, calls) {
|
|
|
197
225
|
});
|
|
198
226
|
}
|
|
199
227
|
//#endregion
|
|
200
|
-
export { batchScope, batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
|
|
228
|
+
export { ActionCycleError, batchScope, batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -58,6 +58,12 @@ export interface TestDatabase<TSchema = any> {
|
|
|
58
58
|
* every table of the action's database.
|
|
59
59
|
*/
|
|
60
60
|
run<TArgs, TResult>(action: (args: TArgs) => Promise<TResult>, args: TArgs): Promise<TResult>;
|
|
61
|
+
/**
|
|
62
|
+
* Run an action's handler with `args` already validated, as {@link run}
|
|
63
|
+
* does once it has validated them: for a library that finds an action's
|
|
64
|
+
* handler itself (a database driver of its own).
|
|
65
|
+
*/
|
|
66
|
+
runHandler<TResult>(handler: (db: any, args: any, ctx: any) => Promise<TResult>, args: unknown): Promise<TResult>;
|
|
61
67
|
/** The raw `node:sqlite` handle, for escape-hatch SQL. */
|
|
62
68
|
sqlite: DatabaseSync;
|
|
63
69
|
/** Every message the actions run here pushed to `ctx.outbox` (successful ones only), oldest first. */
|
package/dist/testing/index.js
CHANGED
|
@@ -2,9 +2,11 @@ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase
|
|
|
2
2
|
import { r as type } from "../type-C7apBBQw.js";
|
|
3
3
|
import "../actionArgs-BAmU_AIB.js";
|
|
4
4
|
import { setTenantIdResolver } from "../context/index.js";
|
|
5
|
-
import { h as tenantOfInstanceKey, l as createActionOutbox, t as createKyselyFromSql } from "../kysely-
|
|
5
|
+
import { h as tenantOfInstanceKey, l as createActionOutbox, t as createKyselyFromSql } from "../kysely-BUmrdN9f.js";
|
|
6
6
|
import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-4RsNw1yr.js";
|
|
7
|
+
import { ActionCycleError } from "../registry.js";
|
|
7
8
|
import { createRequire } from "node:module";
|
|
9
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
10
|
//#region src/testing/index.ts
|
|
9
11
|
let sqlite;
|
|
10
12
|
/** `node:sqlite`, loaded without Node 22's experimental notice: for a test that opens a database of its own. */
|
|
@@ -49,6 +51,53 @@ function sqlStorageShim(sqlite) {
|
|
|
49
51
|
return { toArray: () => rows };
|
|
50
52
|
} };
|
|
51
53
|
}
|
|
54
|
+
const FRAMES = Symbol.for("durable-db.testTransactions");
|
|
55
|
+
const frames = globalThis[FRAMES] ??= new AsyncLocalStorage();
|
|
56
|
+
/**
|
|
57
|
+
* Runs `fn` in a transaction of `transactions` — BEGIN, or a SAVEPOINT inside
|
|
58
|
+
* the one the calling code is in — once it is this one's turn, committing it
|
|
59
|
+
* when `fn` resolves and rolling it back when it throws.
|
|
60
|
+
*/
|
|
61
|
+
async function inTransaction(sqlite, transactions, ctx, fn) {
|
|
62
|
+
const stack = frames.getStore() ?? [];
|
|
63
|
+
let inside;
|
|
64
|
+
for (const frame of stack) if (frame.transactions === transactions) inside = frame.level;
|
|
65
|
+
const parent = inside !== void 0 && transactions.open.includes(inside) ? inside : void 0;
|
|
66
|
+
while (transactions.open.at(-1) !== parent) await new Promise((resolve) => transactions.waiting.push(resolve));
|
|
67
|
+
const level = Symbol("transaction");
|
|
68
|
+
transactions.open.push(level);
|
|
69
|
+
const depth = transactions.open.length;
|
|
70
|
+
const savepoint = `durable_db_test_${depth}`;
|
|
71
|
+
sqlite.exec(depth === 1 ? "BEGIN" : `SAVEPOINT ${savepoint}`);
|
|
72
|
+
try {
|
|
73
|
+
const result = await frames.run([...stack, {
|
|
74
|
+
transactions,
|
|
75
|
+
level,
|
|
76
|
+
ctx
|
|
77
|
+
}], fn);
|
|
78
|
+
sqlite.exec(depth === 1 ? "COMMIT" : `RELEASE ${savepoint}`);
|
|
79
|
+
return result;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
sqlite.exec(depth === 1 ? "ROLLBACK" : `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}`);
|
|
82
|
+
throw error;
|
|
83
|
+
} finally {
|
|
84
|
+
transactions.open.pop();
|
|
85
|
+
const waiting = transactions.waiting.splice(0);
|
|
86
|
+
if (waiting.length > 0) setImmediate(() => waiting.forEach((wake) => wake()));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** A part of the action of `ctx`: a savepoint, and what it pushed goes with it when it throws. */
|
|
90
|
+
function partOf(sqlite, transactions, ctx) {
|
|
91
|
+
return (fn) => inTransaction(sqlite, transactions, ctx, async () => {
|
|
92
|
+
const mark = ctx.outbox.mark();
|
|
93
|
+
try {
|
|
94
|
+
return await fn();
|
|
95
|
+
} catch (error) {
|
|
96
|
+
ctx.outbox.rewind(mark);
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
52
101
|
async function deriveStatements(schema) {
|
|
53
102
|
const snapshot = await generateSnapshotFromSchema(schema);
|
|
54
103
|
return generateMigrationStatements(createEmptySnapshot(), snapshot);
|
|
@@ -78,25 +127,47 @@ async function createTestDatabase(options) {
|
|
|
78
127
|
const ddl = statements ?? await deriveStatements(schema);
|
|
79
128
|
for (const stmt of ddl) sqlite.exec(stmt);
|
|
80
129
|
setTenantIdResolver(() => tenantId);
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
const
|
|
130
|
+
const instance = (meta) => options.instance ?? meta?.instance ?? "per-tenant";
|
|
131
|
+
const transactions = {
|
|
132
|
+
name: database,
|
|
133
|
+
open: [],
|
|
134
|
+
waiting: []
|
|
135
|
+
};
|
|
136
|
+
async function execute(handler, validated, kind) {
|
|
137
|
+
const instanceKey = kind === "global" ? "global" : tenantId;
|
|
138
|
+
const stack = frames.getStore() ?? [];
|
|
139
|
+
const innermost = stack.at(-1);
|
|
140
|
+
if (innermost?.transactions === transactions) return innermost.ctx.transaction(() => handler(db, validated, innermost.ctx));
|
|
141
|
+
if (stack.some((frame) => frame.transactions === transactions)) {
|
|
142
|
+
const via = stack.map((frame) => ({
|
|
143
|
+
database: frame.transactions.name,
|
|
144
|
+
instanceKey: frame.ctx.instanceKey
|
|
145
|
+
}));
|
|
146
|
+
throw new ActionCycleError(via, {
|
|
147
|
+
database,
|
|
148
|
+
instanceKey
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
const ctx = {
|
|
90
152
|
env,
|
|
153
|
+
dbName: database,
|
|
91
154
|
instanceKey,
|
|
92
|
-
outbox
|
|
155
|
+
outbox: createActionOutbox(true),
|
|
156
|
+
transaction: (fn) => part(fn)
|
|
157
|
+
};
|
|
158
|
+
const part = partOf(sqlite, transactions, ctx);
|
|
159
|
+
let recordedAt = 0;
|
|
160
|
+
const result = await inTransaction(sqlite, transactions, ctx, async () => {
|
|
161
|
+
const value = await handler(db, validated, ctx);
|
|
162
|
+
recordedAt = Date.now();
|
|
163
|
+
return value;
|
|
93
164
|
});
|
|
94
|
-
const envelopes = outbox.take().map((message) => ({
|
|
165
|
+
const envelopes = ctx.outbox.take().map((message) => ({
|
|
95
166
|
message: JSON.parse(message),
|
|
96
167
|
database,
|
|
97
168
|
instanceKey,
|
|
98
|
-
tenantId: tenantOfInstanceKey(instanceKey, { instance }),
|
|
99
|
-
recordedAt
|
|
169
|
+
tenantId: tenantOfInstanceKey(instanceKey, { instance: kind }),
|
|
170
|
+
recordedAt,
|
|
100
171
|
attempts: 0
|
|
101
172
|
}));
|
|
102
173
|
if (envelopes.length > 0) {
|
|
@@ -105,6 +176,14 @@ async function createTestDatabase(options) {
|
|
|
105
176
|
}
|
|
106
177
|
return result;
|
|
107
178
|
}
|
|
179
|
+
async function run(action, args) {
|
|
180
|
+
const meta = action[ACTION_TEST_META];
|
|
181
|
+
if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
|
|
182
|
+
const validated = meta.validator(args);
|
|
183
|
+
if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
|
|
184
|
+
return execute(meta.handler, validated, instance(meta));
|
|
185
|
+
}
|
|
186
|
+
const runHandler = (handler, args) => execute(handler, args, instance());
|
|
108
187
|
const live = {
|
|
109
188
|
tables: new Set(Object.values(schema)),
|
|
110
189
|
run: (action, args) => run(action, args),
|
|
@@ -123,6 +202,7 @@ async function createTestDatabase(options) {
|
|
|
123
202
|
return {
|
|
124
203
|
db,
|
|
125
204
|
run,
|
|
205
|
+
runHandler,
|
|
126
206
|
sqlite,
|
|
127
207
|
outbox: recorded,
|
|
128
208
|
destroy() {
|
package/dist/vite/durableDb.d.ts
CHANGED
package/dist/vite/durableDb.js
CHANGED
|
@@ -978,11 +978,12 @@ function buildDoContextTenantProperty() {
|
|
|
978
978
|
return t.objectProperty(t.identifier("tenantId"), t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("tenantOf")), [t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey"))]));
|
|
979
979
|
}
|
|
980
980
|
/**
|
|
981
|
-
* `this.
|
|
982
|
-
* the handler with `ctx.outbox
|
|
981
|
+
* `this.runAction(ctx, async () => entry.handler(this.db, validated, ctx))`:
|
|
982
|
+
* the handler as one transaction, with `ctx.outbox` and `ctx.transaction` —
|
|
983
|
+
* its writes and its messages committed together when it resolves.
|
|
983
984
|
*/
|
|
984
985
|
function buildOutboxHandlerCall() {
|
|
985
|
-
return t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("
|
|
986
|
+
return t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("runAction")), [t.identifier("ctx"), t.arrowFunctionExpression([], t.callExpression(t.memberExpression(t.identifier("entry"), t.identifier("handler")), [
|
|
986
987
|
t.memberExpression(t.thisExpression(), t.identifier("db")),
|
|
987
988
|
t.identifier("validated"),
|
|
988
989
|
t.identifier("ctx")
|
|
@@ -1021,7 +1022,8 @@ function buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr) {
|
|
|
1021
1022
|
t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
|
|
1022
1023
|
t.objectProperty(t.identifier("dbName"), dbNameLiteral),
|
|
1023
1024
|
t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey"))),
|
|
1024
|
-
buildDoContextTenantProperty()
|
|
1025
|
+
buildDoContextTenantProperty(),
|
|
1026
|
+
t.objectProperty(t.identifier("via"), t.optionalMemberExpression(t.identifier("rpcContext"), t.identifier("via"), false, true))
|
|
1025
1027
|
]), t.arrowFunctionExpression([], buildOutboxHandlerCall(), true)]))
|
|
1026
1028
|
]);
|
|
1027
1029
|
return t.classMethod("method", t.identifier("rpc"), [
|
|
@@ -1164,7 +1166,8 @@ function buildStubBodyStatements(config) {
|
|
|
1164
1166
|
bindingExpr,
|
|
1165
1167
|
t.identifier("instanceKey"),
|
|
1166
1168
|
t.stringLiteral(action.exportName),
|
|
1167
|
-
t.identifier("validatedArgs")
|
|
1169
|
+
t.identifier("validatedArgs"),
|
|
1170
|
+
t.stringLiteral(database.name)
|
|
1168
1171
|
]))];
|
|
1169
1172
|
}
|
|
1170
1173
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "durable-db",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/eagerpatch/durable-db.git"
|
|
@@ -79,7 +79,8 @@
|
|
|
79
79
|
"dev": "tsdown --watch",
|
|
80
80
|
"type-check": "tsc --noEmit -p . && tsc -p tests/type/tsconfig.json",
|
|
81
81
|
"test": "vitest",
|
|
82
|
-
"test:run": "vitest run",
|
|
82
|
+
"test:run": "vitest run && vitest run -c vitest.workers.config.ts",
|
|
83
|
+
"test:workers": "vitest run -c vitest.workers.config.ts",
|
|
83
84
|
"changeset": "changeset"
|
|
84
85
|
},
|
|
85
86
|
"dependencies": {
|