durable-db 0.5.1 → 0.6.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 CHANGED
@@ -297,6 +297,8 @@ The resolver is called at the moment a database operation needs the tenant ID
297
297
 
298
298
  Behind the scenes, each action call is an RPC call to the correct Durable Object instance. The Vite plugin generates stubs that handle instance routing, argument validation, and DO communication transparently.
299
299
 
300
+ Calls to the **same** Durable Object instance that start in the same turn share one round trip: `Promise.all([countProducts({}), listProducts({ featuredOnly: true })])` (or sibling server components fetching at once) sends both in a single RPC, and the object runs them one after another, in the order they were made — each result or error goes back to its own caller. A lone call, or calls made one after another, are plain RPCs as before. Each action's args schema is compiled on its first call and reused.
301
+
300
302
  ---
301
303
 
302
304
  ## CLI
@@ -1,7 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
2
  import { S as parseRenameSpec, g as SchemaRenameRequiredError, h as SchemaAmbiguity, m as RenameAnswer, n as Snapshot, t as MigrationResolution, u as MigrationRisk } from "../snapshot-B9Ae2TrS.js";
3
3
  import { l as DatabaseInfo } from "../defineDatabase-zrUJrMd5.js";
4
- import "../index-BvSFkwM9.js";
4
+ import "../index-BlQu7F7I.js";
5
5
  import { Command } from "commander";
6
6
  //#region src/cli/command.d.ts
7
7
  /**
@@ -1,3 +1,3 @@
1
1
  import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, p as type, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-zrUJrMd5.js";
2
- import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-BvSFkwM9.js";
2
+ import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-BlQu7F7I.js";
3
3
  export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type ParsedDatabaseFile, type QueryResult, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
package/dist/db/index.js CHANGED
@@ -593,6 +593,33 @@ var SqliteDurableObject = class extends DurableObject {
593
593
  * Subclasses (e.g. Browsable-wrapped DOs) should call ensureMigrations()
594
594
  * before delegating to super.fetch().
595
595
  */
596
+ /**
597
+ * Several actions in one RPC — the calls a worker started to this object in
598
+ * the same turn (`batchedRpc` in the registry). Each runs through `rpc` (the
599
+ * generated method: migrations, validation, context), one after another in
600
+ * the order they were made, its result or error in its place: one call's
601
+ * error does not stop the next.
602
+ */
603
+ async rpcBatch(calls, options) {
604
+ const rpc = this.rpc;
605
+ if (typeof rpc !== "function") throw new Error("[db] rpcBatch: this Durable Object has no generated rpc method");
606
+ const results = [];
607
+ for (const call of calls) try {
608
+ results.push({
609
+ ok: true,
610
+ value: await rpc.call(this, call.action, call.args, options)
611
+ });
612
+ } catch (error) {
613
+ results.push({
614
+ ok: false,
615
+ error: {
616
+ name: error instanceof Error ? error.name : "Error",
617
+ message: error instanceof Error ? error.message : String(error)
618
+ }
619
+ });
620
+ }
621
+ return results;
622
+ }
596
623
  async fetch(request) {
597
624
  await this.ensureMigrations();
598
625
  if (request.headers.get("Upgrade") === "websocket") {
@@ -299,6 +299,28 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
299
299
  * Subclasses (e.g. Browsable-wrapped DOs) should call ensureMigrations()
300
300
  * before delegating to super.fetch().
301
301
  */
302
+ /**
303
+ * Several actions in one RPC — the calls a worker started to this object in
304
+ * the same turn (`batchedRpc` in the registry). Each runs through `rpc` (the
305
+ * generated method: migrations, validation, context), one after another in
306
+ * the order they were made, its result or error in its place: one call's
307
+ * error does not stop the next.
308
+ */
309
+ rpcBatch(calls: Array<{
310
+ action: string;
311
+ args: unknown;
312
+ }>, options: {
313
+ instanceKey: string;
314
+ }): Promise<Array<{
315
+ ok: true;
316
+ value: unknown;
317
+ } | {
318
+ ok: false;
319
+ error: {
320
+ name: string;
321
+ message: string;
322
+ };
323
+ }>>;
302
324
  fetch(request: Request): Promise<Response>;
303
325
  /**
304
326
  * Handle incoming WebSocket messages.
@@ -52,5 +52,46 @@ export declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
52
52
  * Call an action: validates args, then dispatches (direct call for same DB, RPC for cross-DB).
53
53
  */
54
54
  export declare function callAction(db: unknown, targetDb: string, actionName: string, args: unknown, ctx: RpcContext): Promise<unknown>;
55
+ /** What a Durable Object's `rpcBatch` returns for each call, in order. */
56
+ export type BatchedResult = {
57
+ ok: true;
58
+ value: unknown;
59
+ } | {
60
+ ok: false;
61
+ error: {
62
+ name: string;
63
+ message: string;
64
+ };
65
+ };
66
+ interface ActionStub {
67
+ rpc(action: string, args: unknown, options: {
68
+ instanceKey: string;
69
+ }): Promise<unknown>;
70
+ rpcBatch(calls: Array<{
71
+ action: string;
72
+ args: unknown;
73
+ }>, options: {
74
+ instanceKey: string;
75
+ }): Promise<BatchedResult[]>;
76
+ }
77
+ interface ActionNamespace {
78
+ idFromName(name: string): unknown;
79
+ get(id: unknown): ActionStub;
80
+ }
81
+ /**
82
+ * The args schema of an action, compiled on its first call in this isolate
83
+ * and kept — the compiled call site used to build it on every call.
84
+ */
85
+ export declare function cachedArgsSchema<T>(key: string, make: () => T): T;
86
+ /**
87
+ * Call an action on the Durable Object `instanceKey` of `namespace`. Calls to
88
+ * the same object started in the same turn — `Promise.all([a(), b()])`,
89
+ * sibling server components awaiting at once — travel in ONE RPC
90
+ * (`rpcBatch`) and run there one after another, in the order they were made,
91
+ * each result or error to its own caller; a lone call is a plain `rpc`, as
92
+ * before. Results are plain values: the RPC's top-level `Symbol.dispose` is
93
+ * dropped (React Server Components refuse symbol-keyed props).
94
+ */
95
+ export declare function batchedRpc(namespace: ActionNamespace, instanceKey: string, action: string, args: unknown): Promise<unknown>;
55
96
  //#endregion
56
97
  export { actionArgsType as type };
package/dist/registry.js CHANGED
@@ -68,5 +68,74 @@ async function callAction(db, targetDb, actionName, args, ctx) {
68
68
  const result = await stub.rpc(actionName, validated, { instanceKey: ctx.instanceKey });
69
69
  return structuredClone(result);
70
70
  }
71
+ const argsSchemas = /* @__PURE__ */ new Map();
72
+ /**
73
+ * The args schema of an action, compiled on its first call in this isolate
74
+ * and kept — the compiled call site used to build it on every call.
75
+ */
76
+ function cachedArgsSchema(key, make) {
77
+ let schema = argsSchemas.get(key);
78
+ if (!schema) argsSchemas.set(key, schema = make());
79
+ return schema;
80
+ }
81
+ const pending = /* @__PURE__ */ new WeakMap();
82
+ /**
83
+ * Call an action on the Durable Object `instanceKey` of `namespace`. Calls to
84
+ * the same object started in the same turn — `Promise.all([a(), b()])`,
85
+ * sibling server components awaiting at once — travel in ONE RPC
86
+ * (`rpcBatch`) and run there one after another, in the order they were made,
87
+ * each result or error to its own caller; a lone call is a plain `rpc`, as
88
+ * before. Results are plain values: the RPC's top-level `Symbol.dispose` is
89
+ * dropped (React Server Components refuse symbol-keyed props).
90
+ */
91
+ function batchedRpc(namespace, instanceKey, action, args) {
92
+ return new Promise((resolve, reject) => {
93
+ let byKey = pending.get(namespace);
94
+ if (!byKey) pending.set(namespace, byKey = /* @__PURE__ */ new Map());
95
+ let calls = byKey.get(instanceKey);
96
+ if (!calls) {
97
+ byKey.set(instanceKey, calls = []);
98
+ const queued = byKey;
99
+ queueMicrotask(() => flushCalls(namespace, instanceKey, queued));
100
+ }
101
+ calls.push({
102
+ action,
103
+ args,
104
+ resolve,
105
+ reject
106
+ });
107
+ });
108
+ }
109
+ function flushCalls(namespace, instanceKey, byKey) {
110
+ const calls = byKey.get(instanceKey) ?? [];
111
+ byKey.delete(instanceKey);
112
+ if (calls.length === 0) return;
113
+ let stub;
114
+ try {
115
+ stub = namespace.get(namespace.idFromName(instanceKey));
116
+ } catch (error) {
117
+ for (const call of calls) call.reject(error);
118
+ return;
119
+ }
120
+ const options = { instanceKey };
121
+ if (calls.length === 1) {
122
+ const [call] = calls;
123
+ stub.rpc(call.action, call.args, options).then((value) => call.resolve(structuredClone(value)), call.reject);
124
+ return;
125
+ }
126
+ stub.rpcBatch(calls.map(({ action, args }) => ({
127
+ action,
128
+ args
129
+ })), options).then((results) => {
130
+ calls.forEach((call, index) => {
131
+ const result = results[index];
132
+ if (!result) call.reject(/* @__PURE__ */ new Error(`[db] ${call.action}: no result in the batch from the Durable Object`));
133
+ else if (result.ok) call.resolve(result.value);
134
+ else call.reject(Object.assign(new Error(result.error.message), { name: result.error.name }));
135
+ });
136
+ }, (error) => {
137
+ for (const call of calls) call.reject(error);
138
+ });
139
+ }
71
140
  //#endregion
72
- export { callAction, getAction, getDoContext, registerAction, runWithDoContext, actionArgsType as type };
141
+ export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, runWithDoContext, actionArgsType as type };
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-BvSFkwM9.js";
2
+ import "../index-BlQu7F7I.js";
3
3
  import { Plugin } from "vite";
4
4
  //#region src/vite/modules/wrangler.d.ts
5
5
  /** A Durable Object binding as wrangler.jsonc declares it. */
@@ -680,6 +680,9 @@ const generate = typeof _generate === "function" ? _generate : _generate.default
680
680
  */
681
681
  const DEV_EPOCH_IMPORT = "virtual:durable-db/__devEpoch";
682
682
  const ARKTYPE_LOCAL = "__ddType";
683
+ /** The registry's cachedArgsSchema and batchedRpc, imported under aliases that never collide with the app's own names. */
684
+ const SCHEMA_LOCAL = "__ddSchema";
685
+ const RPC_LOCAL = "__ddRpc";
683
686
  function parseProgram(code) {
684
687
  return parse(code, {
685
688
  sourceType: "module",
@@ -1023,13 +1026,6 @@ function buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr) {
1023
1026
  ]);
1024
1027
  return t.classMethod("method", t.identifier("webSocketMessage"), [t.identifier("ws"), t.identifier("message")], body, false, false, false, true);
1025
1028
  }
1026
- function buildRpcCall(action) {
1027
- return t.callExpression(t.memberExpression(t.identifier("stub"), t.identifier("rpc")), [
1028
- t.stringLiteral(action.exportName),
1029
- t.identifier("validatedArgs"),
1030
- t.objectExpression([t.objectProperty(t.identifier("instanceKey"), t.identifier("instanceKey"))])
1031
- ]);
1032
- }
1033
1029
  function buildDoShortPath(config) {
1034
1030
  const { action, database } = config;
1035
1031
  return [t.variableDeclaration("const", [t.variableDeclarator(t.identifier("__do"), t.callExpression(t.identifier("getDoContext"), []))]), t.ifStatement(t.logicalExpression("&&", t.identifier("__do"), t.binaryExpression("===", t.memberExpression(t.identifier("__do"), t.identifier("dbName")), t.stringLiteral(database.name))), t.blockStatement([t.returnStatement(t.callExpression(t.identifier("callAction"), [
@@ -1054,15 +1050,15 @@ function buildStubBodyStatements(config) {
1054
1050
  const bindingExpr = t.memberExpression(t.identifier("env"), t.identifier(database.bindingName));
1055
1051
  const instanceKeyExpr = buildInstanceKeyExpr(database);
1056
1052
  const commonStatements = [
1057
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier("argsSchema"), t.callExpression(t.identifier(ARKTYPE_LOCAL), [parseExpression(action.argsSchemaSource)]))]),
1053
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier("argsSchema"), t.callExpression(t.identifier(SCHEMA_LOCAL), [t.stringLiteral(`${database.name}/${action.exportName}`), t.arrowFunctionExpression([], t.callExpression(t.identifier(ARKTYPE_LOCAL), [parseExpression(action.argsSchemaSource)]))]))]),
1058
1054
  t.variableDeclaration("const", [t.variableDeclarator(t.identifier("validatedArgs"), t.callExpression(t.memberExpression(t.identifier("argsSchema"), t.identifier("assert")), [t.identifier("args")]))]),
1059
1055
  ...buildDoShortPath(config),
1060
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier("instanceKey"), instanceKeyExpr)]),
1061
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier("id"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("idFromName")), [t.identifier("instanceKey")]))]),
1062
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier("stub"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("get")), [t.identifier("id")]))])
1056
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier("instanceKey"), instanceKeyExpr)])
1063
1057
  ];
1064
1058
  if (database.transport === "websocket") return [
1065
1059
  ...commonStatements,
1060
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier("id"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("idFromName")), [t.identifier("instanceKey")]))]),
1061
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier("stub"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("get")), [t.identifier("id")]))]),
1066
1062
  t.variableDeclaration("const", [t.variableDeclarator(t.identifier("wsTransport"), t.newExpression(t.identifier("WebSocketTransport"), [t.identifier("stub")]))]),
1067
1063
  t.returnStatement(t.callExpression(t.memberExpression(t.identifier("wsTransport"), t.identifier("call")), [
1068
1064
  t.stringLiteral(action.exportName),
@@ -1070,7 +1066,12 @@ function buildStubBodyStatements(config) {
1070
1066
  t.identifier("instanceKey")
1071
1067
  ]))
1072
1068
  ];
1073
- return [...commonStatements, t.returnStatement(t.callExpression(t.memberExpression(buildRpcCall(action), t.identifier("then")), [t.identifier("structuredClone")]))];
1069
+ return [...commonStatements, t.returnStatement(t.callExpression(t.identifier(RPC_LOCAL), [
1070
+ bindingExpr,
1071
+ t.identifier("instanceKey"),
1072
+ t.stringLiteral(action.exportName),
1073
+ t.identifier("validatedArgs")
1074
+ ]))];
1074
1075
  }
1075
1076
  /**
1076
1077
  * Rewrite `export const x = action({...})` declarations in the given program
@@ -1089,6 +1090,14 @@ function applyActionTransforms(body, ctx) {
1089
1090
  {
1090
1091
  imported: "type",
1091
1092
  local: ARKTYPE_LOCAL
1093
+ },
1094
+ {
1095
+ imported: "cachedArgsSchema",
1096
+ local: SCHEMA_LOCAL
1097
+ },
1098
+ {
1099
+ imported: "batchedRpc",
1100
+ local: RPC_LOCAL
1092
1101
  }
1093
1102
  ]);
1094
1103
  ensureNamedImports(body, DEV_EPOCH_IMPORT, ["applyDevEpoch"]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"