rivetkit 0.0.0-sqlite-sync-3x-release.a00b07f → 0.0.0-sqlite-query-metrics-v2.f5d3605

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.
Files changed (137) hide show
  1. package/dist/browser/client.d.ts +59 -99
  2. package/dist/browser/client.js +20 -193
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +2 -1
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-D5WUPE47.js → chunk-3URZ4UV5.js} +2 -2
  7. package/dist/tsup/{chunk-TSQTI6H6.js → chunk-D4G35VTO.js} +4 -4
  8. package/dist/tsup/{chunk-OTVJYZ2L.cjs → chunk-DDS7OOVF.cjs} +166 -326
  9. package/dist/tsup/chunk-DDS7OOVF.cjs.map +1 -0
  10. package/dist/tsup/{chunk-6KXVLIXL.cjs → chunk-DHL2M2E2.cjs} +3 -3
  11. package/dist/tsup/{chunk-6KXVLIXL.cjs.map → chunk-DHL2M2E2.cjs.map} +1 -1
  12. package/dist/tsup/{chunk-ZYK4B5WV.js → chunk-E2CUROR3.js} +2 -2
  13. package/dist/tsup/{chunk-JUWMP5O3.js → chunk-EPRA2TCT.js} +2 -2
  14. package/dist/tsup/{chunk-3DONDAMG.js → chunk-F7IGTKGM.js} +2 -2
  15. package/dist/tsup/{chunk-BTSDFFDC.cjs → chunk-FYDB45YU.cjs} +10 -10
  16. package/dist/tsup/{chunk-BTSDFFDC.cjs.map → chunk-FYDB45YU.cjs.map} +1 -1
  17. package/dist/tsup/{chunk-73RNTXHB.cjs → chunk-HO76AEDH.cjs} +3 -3
  18. package/dist/tsup/{chunk-73RNTXHB.cjs.map → chunk-HO76AEDH.cjs.map} +1 -1
  19. package/dist/tsup/{chunk-A2CF6PFH.js → chunk-JI6GZ2C2.js} +1 -18
  20. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  21. package/dist/tsup/{chunk-Z7E2G3JZ.cjs → chunk-JW2WPE6Z.cjs} +4 -4
  22. package/dist/tsup/{chunk-Z7E2G3JZ.cjs.map → chunk-JW2WPE6Z.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-2MOLY6AM.cjs → chunk-KDT56V3Y.cjs} +11 -10
  24. package/dist/tsup/chunk-KDT56V3Y.cjs.map +1 -0
  25. package/dist/tsup/{chunk-DJUBJQEQ.js → chunk-KSP3NXGY.js} +3 -3
  26. package/dist/tsup/{chunk-JUHXV3HF.cjs → chunk-L3Z3W44Q.cjs} +3 -3
  27. package/dist/tsup/{chunk-JUHXV3HF.cjs.map → chunk-L3Z3W44Q.cjs.map} +1 -1
  28. package/dist/tsup/{chunk-RTWH3AX3.cjs → chunk-MYWZCDML.cjs} +2 -19
  29. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  30. package/dist/tsup/{chunk-TRUHDXOU.js → chunk-PJ5EXY6F.js} +25 -185
  31. package/dist/tsup/chunk-PJ5EXY6F.js.map +1 -0
  32. package/dist/tsup/{chunk-TM76Z7XT.cjs → chunk-QR6EAWEC.cjs} +7 -7
  33. package/dist/tsup/{chunk-TM76Z7XT.cjs.map → chunk-QR6EAWEC.cjs.map} +1 -1
  34. package/dist/tsup/{chunk-BRH4PQS5.js → chunk-USKGKQZM.js} +11 -10
  35. package/dist/tsup/chunk-USKGKQZM.js.map +1 -0
  36. package/dist/tsup/client/mod.cjs +6 -6
  37. package/dist/tsup/client/mod.d.cts +3 -15
  38. package/dist/tsup/client/mod.d.ts +3 -15
  39. package/dist/tsup/client/mod.js +5 -5
  40. package/dist/tsup/common/log.cjs +2 -2
  41. package/dist/tsup/common/log.js +1 -1
  42. package/dist/tsup/common/websocket.cjs +3 -3
  43. package/dist/tsup/common/websocket.js +2 -2
  44. package/dist/tsup/{config-DK144OAw.d.cts → config-CkmVg2fG.d.cts} +12 -58
  45. package/dist/tsup/{config-B4erdavw.d.ts → config-Cw_BwH_G.d.ts} +12 -58
  46. package/dist/tsup/{config-BfG1qpYz.d.cts → config-D4clT6mq.d.cts} +52 -34
  47. package/dist/tsup/{config-BfG1qpYz.d.ts → config-D4clT6mq.d.ts} +52 -34
  48. package/dist/tsup/{context-Oxi6YWcG.d.ts → context-BYOKTQJi.d.ts} +2 -2
  49. package/dist/tsup/{context-Cvnf3BRe.d.cts → context-_xIcgBnE.d.cts} +2 -2
  50. package/dist/tsup/db/drizzle.cjs +2 -2
  51. package/dist/tsup/db/drizzle.d.cts +1 -1
  52. package/dist/tsup/db/drizzle.d.ts +1 -1
  53. package/dist/tsup/db/drizzle.js +1 -1
  54. package/dist/tsup/db/mod.cjs +3 -3
  55. package/dist/tsup/db/mod.d.cts +2 -2
  56. package/dist/tsup/db/mod.d.ts +2 -2
  57. package/dist/tsup/db/mod.js +2 -2
  58. package/dist/tsup/dynamic/mod.d.cts +2 -2
  59. package/dist/tsup/dynamic/mod.d.ts +2 -2
  60. package/dist/tsup/inspector/mod.cjs +5 -5
  61. package/dist/tsup/inspector/mod.js +4 -4
  62. package/dist/tsup/inspector/workflow.cjs +4 -4
  63. package/dist/tsup/inspector/workflow.js +3 -3
  64. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  65. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  66. package/dist/tsup/mod.cjs +201 -548
  67. package/dist/tsup/mod.cjs.map +1 -1
  68. package/dist/tsup/mod.d.cts +4 -4
  69. package/dist/tsup/mod.d.ts +4 -4
  70. package/dist/tsup/mod.js +116 -463
  71. package/dist/tsup/mod.js.map +1 -1
  72. package/dist/tsup/test/mod.cjs +7 -7
  73. package/dist/tsup/test/mod.d.cts +2 -2
  74. package/dist/tsup/test/mod.d.ts +2 -2
  75. package/dist/tsup/test/mod.js +5 -5
  76. package/dist/tsup/unstable/migrations.d.cts +1 -1
  77. package/dist/tsup/unstable/migrations.d.ts +1 -1
  78. package/dist/tsup/utils.cjs +2 -2
  79. package/dist/tsup/utils.js +1 -1
  80. package/dist/tsup/workflow/mod.cjs +17 -17
  81. package/dist/tsup/workflow/mod.cjs.map +1 -1
  82. package/dist/tsup/workflow/mod.d.cts +4 -4
  83. package/dist/tsup/workflow/mod.d.ts +4 -4
  84. package/dist/tsup/workflow/mod.js +5 -5
  85. package/package.json +10 -9
  86. package/src/actor/config.test.ts +78 -0
  87. package/src/actor/keys.test.ts +275 -0
  88. package/src/actor/keys.ts +0 -86
  89. package/src/actor/utils.test.ts +48 -0
  90. package/src/client/actor-conn.ts +6 -92
  91. package/src/client/actor-handle.ts +3 -21
  92. package/src/client/client.ts +0 -6
  93. package/src/client/config.ts +1 -12
  94. package/src/client/lifecycle-errors.ts +1 -16
  95. package/src/client/test.ts +44 -0
  96. package/src/client/token-provider.test.ts +86 -0
  97. package/src/client/utils.ts +2 -13
  98. package/src/common/database/config.ts +52 -46
  99. package/src/common/database/mod.test.ts +364 -0
  100. package/src/common/database/native-database.test.ts +220 -0
  101. package/src/common/database/native-database.ts +27 -247
  102. package/src/common/inline-websocket-adapter.test.ts +51 -0
  103. package/src/common/router.ts +1 -1
  104. package/src/db/drizzle.test.ts +164 -0
  105. package/src/db/mod.ts +1 -0
  106. package/src/engine-api/actors.ts +3 -3
  107. package/src/engine-client/actor-websocket-client.ts +2 -4
  108. package/src/engine-client/api-endpoints.ts +14 -44
  109. package/src/engine-client/mod.ts +2 -2
  110. package/src/registry/config/envoy.ts +1 -1
  111. package/src/registry/config/index.test.ts +25 -0
  112. package/src/registry/config/index.ts +31 -28
  113. package/src/registry/index.ts +19 -51
  114. package/src/registry/napi-runtime.ts +2 -81
  115. package/src/registry/native.ts +51 -183
  116. package/src/registry/run-handler-coordinator.test.ts +252 -0
  117. package/src/registry/runtime.test.ts +124 -0
  118. package/src/registry/runtime.ts +10 -79
  119. package/src/registry/wasm-runtime.ts +3 -94
  120. package/src/unstable/migrations.test.ts +170 -0
  121. package/src/utils/endpoint-parser.test.ts +206 -0
  122. package/src/utils/env-vars.ts +10 -15
  123. package/src/utils.test.ts +34 -0
  124. package/src/workflow/driver.test.ts +62 -0
  125. package/dist/tsup/chunk-2MOLY6AM.cjs.map +0 -1
  126. package/dist/tsup/chunk-A2CF6PFH.js.map +0 -1
  127. package/dist/tsup/chunk-BRH4PQS5.js.map +0 -1
  128. package/dist/tsup/chunk-OTVJYZ2L.cjs.map +0 -1
  129. package/dist/tsup/chunk-RTWH3AX3.cjs.map +0 -1
  130. package/dist/tsup/chunk-TRUHDXOU.js.map +0 -1
  131. package/src/client/retry-budget.ts +0 -78
  132. /package/dist/tsup/{chunk-D5WUPE47.js.map → chunk-3URZ4UV5.js.map} +0 -0
  133. /package/dist/tsup/{chunk-TSQTI6H6.js.map → chunk-D4G35VTO.js.map} +0 -0
  134. /package/dist/tsup/{chunk-ZYK4B5WV.js.map → chunk-E2CUROR3.js.map} +0 -0
  135. /package/dist/tsup/{chunk-JUWMP5O3.js.map → chunk-EPRA2TCT.js.map} +0 -0
  136. /package/dist/tsup/{chunk-3DONDAMG.js.map → chunk-F7IGTKGM.js.map} +0 -0
  137. /package/dist/tsup/{chunk-DJUBJQEQ.js.map → chunk-KSP3NXGY.js.map} +0 -0
@@ -0,0 +1,220 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { BRIDGE_RIVET_ERROR_PREFIX } from "@/actor/errors";
3
+ import {
4
+ type JsNativeDatabaseLike,
5
+ wrapJsNativeDatabase,
6
+ } from "./native-database";
7
+
8
+ type NativeParams = Parameters<JsNativeDatabaseLike["execute"]>[1];
9
+ type NativeExecuteResult = Awaited<ReturnType<JsNativeDatabaseLike["execute"]>>;
10
+
11
+ function deferred<T>() {
12
+ let resolve!: (value: T) => void;
13
+ let reject!: (error: unknown) => void;
14
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
15
+ resolve = resolvePromise;
16
+ reject = rejectPromise;
17
+ });
18
+ return { promise, resolve, reject };
19
+ }
20
+
21
+ class FakeNativeDatabase implements JsNativeDatabaseLike {
22
+ async beginTransaction() {
23
+ return {
24
+ exec: async (_sql: string) => this.exec(),
25
+ execute: async (sql: string, params?: NativeParams) =>
26
+ this.execute(sql, params),
27
+ commit: async () => {},
28
+ rollback: async () => {},
29
+ };
30
+ }
31
+ active = 0;
32
+ maxActive = 0;
33
+ closed = false;
34
+ executeCalls: { sql: string; params?: NativeParams; write: boolean }[] = [];
35
+ #pending: ReturnType<typeof deferred<NativeExecuteResult>>[] = [];
36
+
37
+ async exec() {
38
+ return { columns: [], rows: [] };
39
+ }
40
+
41
+ async execute(sql: string, params?: NativeParams) {
42
+ return await this.#startExecute(sql, params, false);
43
+ }
44
+
45
+ async query(sql: string, params?: NativeParams) {
46
+ const { columns, rows } = await this.execute(sql, params);
47
+ return { columns, rows };
48
+ }
49
+
50
+ async run(sql: string, params?: NativeParams) {
51
+ const { changes } = await this.execute(sql, params);
52
+ return { changes };
53
+ }
54
+
55
+ takeLastKvError() {
56
+ return null;
57
+ }
58
+
59
+ async close() {
60
+ this.closed = true;
61
+ }
62
+
63
+ resolveNext(result: Partial<NativeExecuteResult> = {}) {
64
+ const pending = this.#pending.shift();
65
+ if (!pending) {
66
+ throw new Error("no pending native execute call");
67
+ }
68
+ pending.resolve({
69
+ columns: [],
70
+ rows: [],
71
+ changes: 0,
72
+ lastInsertRowId: null,
73
+ ...result,
74
+ });
75
+ }
76
+
77
+ rejectNext(error: unknown) {
78
+ const pending = this.#pending.shift();
79
+ if (!pending) {
80
+ throw new Error("no pending native execute call");
81
+ }
82
+ pending.reject(error);
83
+ }
84
+
85
+ async #startExecute(
86
+ sql: string,
87
+ params: NativeParams,
88
+ write: boolean,
89
+ ): Promise<NativeExecuteResult> {
90
+ this.executeCalls.push({ sql, params, write });
91
+ this.active++;
92
+ this.maxActive = Math.max(this.maxActive, this.active);
93
+ const pending = deferred<NativeExecuteResult>();
94
+ this.#pending.push(pending);
95
+ try {
96
+ return await pending.promise;
97
+ } finally {
98
+ this.active--;
99
+ }
100
+ }
101
+ }
102
+
103
+ describe("wrapJsNativeDatabase", () => {
104
+ test("admits Promise.all read queries concurrently", async () => {
105
+ const native = new FakeNativeDatabase();
106
+ const db = wrapJsNativeDatabase(native);
107
+
108
+ const first = db.query("SELECT 1");
109
+ const second = db.query("SELECT 2");
110
+
111
+ expect(native.maxActive).toBe(2);
112
+ native.resolveNext({ columns: ["value"], rows: [[1]] });
113
+ native.resolveNext({ columns: ["value"], rows: [[2]] });
114
+
115
+ await expect(first).resolves.toEqual({
116
+ columns: ["value"],
117
+ rows: [[1]],
118
+ });
119
+ await expect(second).resolves.toEqual({
120
+ columns: ["value"],
121
+ rows: [[2]],
122
+ });
123
+ });
124
+
125
+ test("normalizes supported sqlite bind values", async () => {
126
+ const native = new FakeNativeDatabase();
127
+ const db = wrapJsNativeDatabase(native);
128
+ const blob = new Uint8Array([1, 2, 3]);
129
+
130
+ const query = db.query("SELECT ?, ?, ?, ?, ?, ?, ?", [
131
+ 1n,
132
+ true,
133
+ "text",
134
+ 1.5,
135
+ null,
136
+ undefined,
137
+ blob,
138
+ ]);
139
+
140
+ expect(native.executeCalls[0]?.params).toEqual([
141
+ { kind: "int", intValue: 1 },
142
+ { kind: "int", intValue: 1 },
143
+ { kind: "text", textValue: "text" },
144
+ { kind: "float", floatValue: 1.5 },
145
+ { kind: "null" },
146
+ { kind: "null" },
147
+ { kind: "blob", blobValue: Buffer.from(blob) },
148
+ ]);
149
+
150
+ native.resolveNext({ columns: ["value"], rows: [[1]] });
151
+
152
+ await expect(query).resolves.toEqual({
153
+ columns: ["value"],
154
+ rows: [[1]],
155
+ });
156
+ });
157
+
158
+ test("returns native execute metadata", async () => {
159
+ const native = new FakeNativeDatabase();
160
+ const db = wrapJsNativeDatabase(native);
161
+
162
+ const write = db.execute("INSERT INTO test VALUES (1)");
163
+ native.resolveNext({ changes: 1, lastInsertRowId: 7 });
164
+ await expect(write).resolves.toMatchObject({
165
+ changes: 1,
166
+ lastInsertRowId: 7,
167
+ });
168
+
169
+ const fallback = db.execute("SELECT last_insert_rowid()");
170
+ await expect(fallback).resolves.toMatchObject({
171
+ rows: [[7]],
172
+ });
173
+ });
174
+
175
+ test("close waits for admitted native calls and rejects new work", async () => {
176
+ const native = new FakeNativeDatabase();
177
+ const db = wrapJsNativeDatabase(native);
178
+
179
+ const query = db.query("SELECT 1");
180
+ const close = db.close();
181
+ await Promise.resolve();
182
+
183
+ expect(native.closed).toBe(false);
184
+ native.resolveNext({ columns: ["value"], rows: [[1]] });
185
+
186
+ await query;
187
+ await close;
188
+
189
+ expect(native.closed).toBe(true);
190
+ await expect(db.query("SELECT 2")).rejects.toThrow(
191
+ "Database is closed",
192
+ );
193
+ });
194
+
195
+ test("decodes sanitized native bridge errors without logging", async () => {
196
+ const native = new FakeNativeDatabase();
197
+ const db = wrapJsNativeDatabase(native);
198
+ const query = db.execute("SELECT broken", [1, "two"]);
199
+ const bridgeReason = `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
200
+ group: "rivetkit",
201
+ code: "internal_error",
202
+ message: "An internal error occurred",
203
+ statusCode: 500,
204
+ })}`;
205
+
206
+ native.rejectNext(new Error(bridgeReason));
207
+
208
+ await expect(query).rejects.toMatchObject({
209
+ name: "RivetError",
210
+ group: "rivetkit",
211
+ code: "internal_error",
212
+ message: "An internal error occurred",
213
+ });
214
+
215
+ await query.catch((error) => {
216
+ expect(error.stack).toContain("decodeBridgeRivetError");
217
+ expect(error.stack).toContain("enrichNativeDatabaseError");
218
+ });
219
+ });
220
+ });
@@ -6,7 +6,6 @@ import type {
6
6
  SqliteExecuteResult,
7
7
  SqliteNativeMetrics,
8
8
  SqliteTransactionDatabase,
9
- SynchronousSqliteTransactionDatabase,
10
9
  } from "./config";
11
10
 
12
11
  type NativeBindNoValues = {
@@ -75,15 +74,10 @@ interface NativeBatchStatement {
75
74
 
76
75
  export interface JsNativeDatabaseLike {
77
76
  exec(sql: string): Promise<NativeExecResult>;
78
- execSync(sql: string): NativeExecResult;
79
77
  execute(
80
78
  sql: string,
81
79
  params?: NativeBindParam[] | null,
82
80
  ): Promise<NativeExecuteResult>;
83
- executeSync(
84
- sql: string,
85
- params?: NativeBindParam[] | null,
86
- ): NativeExecuteResult;
87
81
  executeBatch?(
88
82
  statements: NativeBatchStatement[],
89
83
  ): Promise<NativeExecuteResult[]>;
@@ -95,10 +89,6 @@ export interface JsNativeDatabaseLike {
95
89
  timeoutMs?: number,
96
90
  name?: string,
97
91
  ): Promise<JsNativeTransactionLike>;
98
- beginTransactionSync(
99
- timeoutMs?: number,
100
- name?: string,
101
- ): JsNativeSynchronousTransactionLike;
102
92
  query(
103
93
  sql: string,
104
94
  params?: NativeBindParam[] | null,
@@ -109,27 +99,15 @@ export interface JsNativeDatabaseLike {
109
99
  ): Promise<NativeRunResult>;
110
100
  metrics?(): SqliteNativeMetrics | null;
111
101
  takeLastKvError?(): string | null;
112
- open(): Promise<void>;
113
- commitTicket(): number;
114
- whenDurable(ticket: number): Promise<void>;
115
- abortGeneration(reason: string): void;
116
102
  close(): Promise<void>;
117
103
  }
118
104
  export type StateAwareSqliteDatabase = SqliteDatabase & {
119
- open(): Promise<void>;
120
- commitTicket(): number;
121
- whenDurable(ticket: number): Promise<void>;
122
105
  beginStateTransaction(
123
106
  timeoutMs?: number,
124
107
  context?: unknown,
125
108
  ): Promise<SqliteTransactionDatabase>;
126
109
  };
127
110
 
128
- type NativeSqliteDatabase = StateAwareSqliteDatabase & {
129
- /** Stop JS calls while leaving the runtime-owned backend open. */
130
- detachForShutdown(): Promise<void>;
131
- };
132
-
133
111
  export interface JsNativeTransactionLike {
134
112
  exec(sql: string): Promise<NativeExecResult>;
135
113
  execute(
@@ -140,28 +118,6 @@ export interface JsNativeTransactionLike {
140
118
  rollback(): Promise<void>;
141
119
  }
142
120
 
143
- export interface JsNativeSynchronousTransactionLike
144
- extends JsNativeTransactionLike {
145
- execSync(sql: string): NativeExecResult;
146
- executeSync(
147
- sql: string,
148
- params?: NativeBindParam[] | null,
149
- ): NativeExecuteResult;
150
- commitSync(): void;
151
- rollbackSync(): void;
152
- }
153
-
154
- function isSynchronousTransaction(
155
- transaction: JsNativeTransactionLike,
156
- ): transaction is JsNativeSynchronousTransactionLike {
157
- const candidate =
158
- transaction as Partial<JsNativeSynchronousTransactionLike>;
159
- return (
160
- typeof candidate.commitSync === "function" &&
161
- typeof candidate.rollbackSync === "function"
162
- );
163
- }
164
-
165
121
  function shouldAttachNativeKvError(message: string): boolean {
166
122
  return /i\/o error|unable to open database file/i.test(message);
167
123
  }
@@ -200,19 +156,13 @@ function toNativeBinding(arg: unknown): NativeBindParam {
200
156
  if (arg === null || arg === undefined) {
201
157
  return { kind: "null" };
202
158
  }
203
- if (
204
- typeof arg === "bigint" ||
205
- (typeof arg === "number" && Number.isInteger(arg))
206
- ) {
207
- const value = Number(arg);
208
- if (!Number.isSafeInteger(value)) {
209
- throw new RangeError(
210
- "SQLite integer bindings must be within the JavaScript safe integer range.",
211
- );
212
- }
213
- return { kind: "int", intValue: value };
159
+ if (typeof arg === "bigint") {
160
+ return { kind: "int", intValue: Number(arg) };
214
161
  }
215
162
  if (typeof arg === "number") {
163
+ if (Number.isInteger(arg)) {
164
+ return { kind: "int", intValue: arg };
165
+ }
216
166
  return { kind: "float", floatValue: arg };
217
167
  }
218
168
  if (typeof arg === "string") {
@@ -230,13 +180,9 @@ function toNativeBinding(arg: unknown): NativeBindParam {
230
180
  function extractNamedSqliteParameters(sql: string): string[] {
231
181
  const orderedNames: string[] = [];
232
182
  const seen = new Set<string>();
233
- // SQLite identifiers may contain "$" and any non-ASCII character. Consume
234
- // whole identifiers so their suffixes cannot be mistaken for parameters.
235
- const pattern =
236
- /'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)|([:@$][\w$\u0080-\u{10FFFF}]+(?:::[\w$\u0080-\u{10FFFF}]+)*(?:\([^)]*\))?)|[A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*/gu;
183
+ const pattern = /([:@$][A-Za-z_][A-Za-z0-9_]*)/g;
237
184
  for (const match of sql.matchAll(pattern)) {
238
185
  const name = match[1];
239
- if (!name) continue;
240
186
  if (seen.has(name)) {
241
187
  continue;
242
188
  }
@@ -365,7 +311,7 @@ class NativeCloseGate {
365
311
  };
366
312
  }
367
313
 
368
- async close(callback?: () => Promise<void>): Promise<void> {
314
+ async close(callback: () => Promise<void>): Promise<void> {
369
315
  if (this.#closed) {
370
316
  return;
371
317
  }
@@ -373,66 +319,36 @@ class NativeCloseGate {
373
319
  if (this.#active > 0) {
374
320
  await new Promise<void>((resolve) => this.#waiters.push(resolve));
375
321
  }
376
- await callback?.();
322
+ await callback();
377
323
  }
378
324
  }
379
325
 
380
326
  export function wrapJsNativeDatabase(
381
327
  database: JsNativeDatabaseLike,
382
- ): NativeSqliteDatabase {
328
+ ): StateAwareSqliteDatabase {
383
329
  const gate = new NativeCloseGate();
384
- // Detach and explicit close are mutually exclusive terminal operations.
385
- // Whichever starts first defines whether the backend is physically closed.
386
- let terminalPromise: Promise<void> | undefined;
330
+ let closePromise: Promise<void> | undefined;
387
331
  let lastInsertRowId: number | null = null;
388
332
 
389
333
  const executeNative = async (
390
334
  sql: string,
391
335
  params?: SqliteBindings,
392
336
  ): Promise<SqliteExecuteResult> => {
393
- const release = gate.enter();
394
- try {
395
- const lastInsertRowIdColumn = lastInsertRowIdColumnName(sql);
396
- if (lastInsertRowIdColumn) {
397
- return {
398
- columns: [lastInsertRowIdColumn],
399
- rows: [[lastInsertRowId ?? 0]],
400
- changes: 0,
401
- lastInsertRowId,
402
- };
403
- }
404
-
405
- const nativeParams = toNativeBindings(sql, params);
406
- const result = await database.execute(sql, nativeParams);
407
- if (result.lastInsertRowId != null) {
408
- lastInsertRowId = result.lastInsertRowId;
409
- }
410
- return result;
411
- } catch (error) {
412
- enrichNativeDatabaseError(database, error);
413
- } finally {
414
- release();
337
+ const lastInsertRowIdColumn = lastInsertRowIdColumnName(sql);
338
+ if (lastInsertRowIdColumn) {
339
+ return {
340
+ columns: [lastInsertRowIdColumn],
341
+ rows: [[lastInsertRowId ?? 0]],
342
+ changes: 0,
343
+ lastInsertRowId,
344
+ };
415
345
  }
416
- };
417
- const executeNativeSync = (
418
- sql: string,
419
- params?: SqliteBindings,
420
- ): SqliteExecuteResult => {
346
+
421
347
  const release = gate.enter();
422
348
  try {
423
349
  const nativeParams = toNativeBindings(sql, params);
424
- const result = database.executeSync(sql, nativeParams);
425
- // Execute first so runtime availability and transaction admission are enforced.
426
- const rowIdColumn = lastInsertRowIdColumnName(sql);
427
- if (rowIdColumn) {
428
- return {
429
- columns: [rowIdColumn],
430
- rows: [[lastInsertRowId ?? 0]],
431
- changes: 0,
432
- lastInsertRowId,
433
- };
434
- }
435
- if (result.lastInsertRowId != null) {
350
+ const result = await database.execute(sql, nativeParams);
351
+ if (result.lastInsertRowId !== undefined) {
436
352
  lastInsertRowId = result.lastInsertRowId;
437
353
  }
438
354
  return result;
@@ -464,34 +380,12 @@ export function wrapJsNativeDatabase(
464
380
  callback(row, result.columns);
465
381
  }
466
382
  },
467
- execSync(
468
- sql: string,
469
- callback?: (row: unknown[], columns: string[]) => void,
470
- ): void {
471
- const release = gate.enter();
472
- let result: NativeExecResult;
473
- try {
474
- result = database.execSync(sql);
475
- } catch (error) {
476
- enrichNativeDatabaseError(database, error);
477
- } finally {
478
- release();
479
- }
480
- if (callback) {
481
- for (const row of result.rows) {
482
- callback(row, result.columns);
483
- }
484
- }
485
- },
486
383
  async execute(
487
384
  sql: string,
488
385
  params?: SqliteBindings,
489
386
  ): Promise<SqliteExecuteResult> {
490
387
  return await executeNative(sql, params);
491
388
  },
492
- executeSync(sql: string, params?: SqliteBindings): SqliteExecuteResult {
493
- return executeNativeSync(sql, params);
494
- },
495
389
  async executeBatch(
496
390
  statements: SqliteBatchStatement[],
497
391
  ): Promise<SqliteExecuteResult[]> {
@@ -518,7 +412,7 @@ export function wrapJsNativeDatabase(
518
412
  return transactionResults;
519
413
  })();
520
414
  for (const result of results) {
521
- if (result.lastInsertRowId != null) {
415
+ if (result.lastInsertRowId !== undefined) {
522
416
  lastInsertRowId = result.lastInsertRowId;
523
417
  }
524
418
  }
@@ -550,26 +444,7 @@ export function wrapJsNativeDatabase(
550
444
  release();
551
445
  }
552
446
  return wrapTransaction(database, transaction, gate, (result) => {
553
- if (result.lastInsertRowId != null) {
554
- lastInsertRowId = result.lastInsertRowId;
555
- }
556
- });
557
- },
558
- beginTransactionSync(
559
- timeoutMs?: number,
560
- name?: string,
561
- ): SynchronousSqliteTransactionDatabase {
562
- const release = gate.enter();
563
- let transaction: JsNativeSynchronousTransactionLike;
564
- try {
565
- transaction = database.beginTransactionSync(timeoutMs, name);
566
- } catch (error) {
567
- enrichNativeDatabaseError(database, error);
568
- } finally {
569
- release();
570
- }
571
- return wrapTransaction(database, transaction, gate, (result) => {
572
- if (result.lastInsertRowId != null) {
447
+ if (result.lastInsertRowId !== undefined) {
573
448
  lastInsertRowId = result.lastInsertRowId;
574
449
  }
575
450
  });
@@ -594,7 +469,7 @@ export function wrapJsNativeDatabase(
594
469
  release();
595
470
  }
596
471
  return wrapTransaction(database, transaction, gate, (result) => {
597
- if (result.lastInsertRowId != null) {
472
+ if (result.lastInsertRowId !== undefined) {
598
473
  lastInsertRowId = result.lastInsertRowId;
599
474
  }
600
475
  });
@@ -609,55 +484,20 @@ export function wrapJsNativeDatabase(
609
484
  nativeMetrics(): SqliteNativeMetrics | null {
610
485
  return normalizeNativeMetrics(database.metrics?.());
611
486
  },
612
- async open(): Promise<void> {
613
- const release = gate.enter();
614
- try {
615
- await database.open();
616
- } catch (error) {
617
- enrichNativeDatabaseError(database, error);
618
- } finally {
619
- release();
620
- }
621
- },
622
- commitTicket(): number {
623
- return database.commitTicket();
624
- },
625
- async whenDurable(ticket: number): Promise<void> {
626
- await database.whenDurable(ticket);
627
- },
628
- abortGeneration(reason: string): void {
629
- database.abortGeneration(reason);
630
- },
631
487
  async close(): Promise<void> {
632
- terminalPromise ??= gate.close(() => database.close());
633
- await terminalPromise;
634
- },
635
- async detachForShutdown(): Promise<void> {
636
- terminalPromise ??= gate.close();
637
- await terminalPromise;
488
+ closePromise ??= gate.close(() => database.close());
489
+ await closePromise;
638
490
  },
639
491
  };
640
492
  }
641
493
 
642
- function wrapTransaction(
643
- database: JsNativeDatabaseLike,
644
- transaction: JsNativeSynchronousTransactionLike,
645
- gate: NativeCloseGate,
646
- onExecute: (result: NativeExecuteResult) => void,
647
- ): SynchronousSqliteTransactionDatabase;
648
- function wrapTransaction(
649
- database: JsNativeDatabaseLike,
650
- transaction: JsNativeTransactionLike,
651
- gate: NativeCloseGate,
652
- onExecute: (result: NativeExecuteResult) => void,
653
- ): SqliteTransactionDatabase;
654
494
  function wrapTransaction(
655
495
  database: JsNativeDatabaseLike,
656
496
  transaction: JsNativeTransactionLike,
657
497
  gate: NativeCloseGate,
658
498
  onExecute: (result: NativeExecuteResult) => void,
659
499
  ): SqliteTransactionDatabase {
660
- const wrapped: SqliteTransactionDatabase = {
500
+ return {
661
501
  async exec(sql, callback) {
662
502
  const release = gate.enter();
663
503
  let result: NativeExecResult;
@@ -708,66 +548,6 @@ function wrapTransaction(
708
548
  }
709
549
  },
710
550
  };
711
-
712
- if (isSynchronousTransaction(transaction)) {
713
- return Object.assign(wrapped, {
714
- execSync(
715
- sql: string,
716
- callback?: (row: unknown[], columns: string[]) => void,
717
- ) {
718
- const release = gate.enter();
719
- let result: NativeExecResult;
720
- try {
721
- result = transaction.execSync(sql);
722
- } catch (error) {
723
- enrichNativeDatabaseError(database, error);
724
- } finally {
725
- release();
726
- }
727
- if (callback) {
728
- for (const row of result.rows)
729
- callback(row, result.columns);
730
- }
731
- },
732
- executeSync(sql: string, params?: SqliteBindings) {
733
- const release = gate.enter();
734
- try {
735
- const result = transaction.executeSync(
736
- sql,
737
- toNativeBindings(sql, params),
738
- );
739
- onExecute(result);
740
- return result;
741
- } catch (error) {
742
- enrichNativeDatabaseError(database, error);
743
- } finally {
744
- release();
745
- }
746
- },
747
- commitSync() {
748
- const release = gate.enter();
749
- try {
750
- transaction.commitSync();
751
- } catch (error) {
752
- enrichNativeDatabaseError(database, error);
753
- } finally {
754
- release();
755
- }
756
- },
757
- rollbackSync() {
758
- const release = gate.enter();
759
- try {
760
- transaction.rollbackSync();
761
- } catch (error) {
762
- enrichNativeDatabaseError(database, error);
763
- } finally {
764
- release();
765
- }
766
- },
767
- }) as SynchronousSqliteTransactionDatabase;
768
- }
769
-
770
- return wrapped;
771
551
  }
772
552
 
773
553
  function lastInsertRowIdColumnName(sql: string): string | undefined {
@@ -0,0 +1,51 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import { InlineWebSocketAdapter } from "./inline-websocket-adapter";
3
+
4
+ describe("InlineWebSocketAdapter", () => {
5
+ test("buffers client messages until open completes", async () => {
6
+ const events: string[] = [];
7
+ const adapter = new InlineWebSocketAdapter({
8
+ onOpen: () => {
9
+ events.push("handler.open");
10
+ },
11
+ onMessage: (event: {
12
+ data: string;
13
+ rivetMessageIndex?: number;
14
+ }) => {
15
+ events.push(
16
+ `handler.message:${event.data}:${event.rivetMessageIndex ?? "none"}`,
17
+ );
18
+ },
19
+ onClose: () => {},
20
+ onError: () => {},
21
+ });
22
+
23
+ adapter.clientWebSocket.addEventListener("open", () => {
24
+ events.push("client.open");
25
+ });
26
+ adapter.actorWebSocket.addEventListener("open", () => {
27
+ events.push("actor.open");
28
+ });
29
+ adapter.actorWebSocket.addEventListener(
30
+ "message",
31
+ (event: { data: string; rivetMessageIndex?: number }) => {
32
+ events.push(
33
+ `actor.message:${event.data}:${event.rivetMessageIndex ?? "none"}`,
34
+ );
35
+ },
36
+ );
37
+
38
+ adapter.dispatchClientMessageWithMetadata("hello", 7);
39
+ expect(events).toEqual([]);
40
+
41
+ await vi.waitFor(() => {
42
+ expect(events).toEqual([
43
+ "handler.open",
44
+ "client.open",
45
+ "actor.open",
46
+ "handler.message:hello:7",
47
+ "actor.message:hello:7",
48
+ ]);
49
+ });
50
+ });
51
+ });
@@ -182,7 +182,7 @@ export function handleMetadataRequest(
182
182
  version: VERSION,
183
183
  envoy: {
184
184
  kind: envoyKind,
185
- version: config.node.version,
185
+ version: config.envoy.version,
186
186
  },
187
187
  envoyProtocolVersion: envoyProtocol.VERSION,
188
188
  actorNames: buildActorNames(config),