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
@@ -52,13 +52,18 @@ export interface SqliteTransactionOptions {
52
52
  * to change without notice.
53
53
  */
54
54
  export interface SqliteProfilingOptions {
55
- /** Exact SQL statements to give fingerprint labels. Profiling defaults to actor
56
- * aggregates without fingerprint labels. Profile logs remain enabled.
57
- * RIVETKIT_SQLITE_PROFILING overrides selection with a JSON object containing
58
- * queries and/or fingerprints arrays. An empty object clears fingerprint selection. */
59
- queries?: string[];
60
- /** Exact query fingerprints to label separately, as reported in profile logs. */
61
- fingerprints?: string[];
55
+ /** Existing v2 switch. Default: true. */
56
+ enabled?: boolean;
57
+ /** Exact SQL filter. Union with filterQueryFingerprints; both empty means all queries. */
58
+ filterQueries?: string[];
59
+ /** Fingerprint filter, including transaction fingerprints. Filters metrics, not diagnostic logs. */
60
+ filterQueryFingerprints?: string[];
61
+ /** Metric defaults apply even when omitted. Disabled metrics allocate no series. */
62
+ metrics?: SqliteProfilingMetricsOptions;
63
+ /** Duration buckets in seconds. Default [0.01, 0.1, 1]. Positive, finite, strictly increasing.
64
+ * All actors in a process enabling the duration histogram must use identical buckets. */
65
+ durationHistogramBucketsSeconds?: number[];
66
+ /** Maximum distinct statement fingerprints per process. Default: 512. */
62
67
  maxTrackedStatementFingerprints?: number;
63
68
  maxTrackedTransactionFingerprints?: number;
64
69
  maxPrometheusSeries?: number;
@@ -71,6 +76,46 @@ export interface SqliteProfilingOptions {
71
76
  diagnosticEventQueueCapacity?: number;
72
77
  }
73
78
 
79
+ /** SQLite profiling metrics. Physical-request metrics and gauges have no query labels. */
80
+ export interface SqliteProfilingMetricsOptions {
81
+ /** Execution count and cumulative seconds. Uses histogram count/sum when enabled, otherwise counters. Default: true. */
82
+ duration?: boolean;
83
+ /** Execution duration histogram. Only applies when duration is enabled. Default: true. */
84
+ durationHistogram?: boolean;
85
+ /** Outcome counters, including success and errors. Default: true. */
86
+ outcomes?: boolean;
87
+ /** Per-query timing phase histograms. Default: false. */
88
+ phaseDurationHistogram?: boolean;
89
+ /** Storage round trips per operation histogram. Default: false. */
90
+ getPagesRoundTripsHistogram?: boolean;
91
+ /** Statements per transaction histogram. Default: false. */
92
+ transactionStatementCountHistogram?: boolean;
93
+ /** Per-query pages returned from storage, including returned prefetch pages. Default: true. */
94
+ pagesFetched?: boolean;
95
+ /** Actor-level page counters by page kind (no query labels). Default: false. */
96
+ localPages?: boolean;
97
+ /** Actor-level byte counters by byte kind (no query labels). Default: false. */
98
+ localBytes?: boolean;
99
+ /** Actor-level physical storage request duration histogram. Default: false. */
100
+ getPagesDurationHistogram?: boolean;
101
+ /** Actor-level pages per storage request histograms, by page kind. Default: false. */
102
+ getPagesPagesHistogram?: boolean;
103
+ /** Actor-level storage response byte histogram. Default: false. */
104
+ getPagesResponseBytesHistogram?: boolean;
105
+ /** Actor-level missing response page counter. Default: false. */
106
+ getPagesMissingPages?: boolean;
107
+ /** Queued SQLite work, aggregated by actor name. Default: true. */
108
+ workerQueueDepth?: boolean;
109
+ /** Executing SQLite work, aggregated by actor name. Default: true. */
110
+ workerInflight?: boolean;
111
+ /** Transaction waiters, aggregated by actor name. Default: true. */
112
+ coordinatorQueueDepth?: boolean;
113
+ /** Counts observations exceeding fingerprint or series limits. Default: true. */
114
+ fingerprintOverflow?: boolean;
115
+ /** Counts diagnostic events dropped by rate limits or backpressure. Default: true. */
116
+ eventDropped?: boolean;
117
+ }
118
+
74
119
  export interface SqliteNativeMetrics {
75
120
  requestBuildNs: number;
76
121
  serializeNs: number;
@@ -90,12 +135,7 @@ export interface SqliteDatabase {
90
135
  sql: string,
91
136
  callback?: (row: unknown[], columns: string[]) => void,
92
137
  ): Promise<void>;
93
- execSync?(
94
- sql: string,
95
- callback?: (row: unknown[], columns: string[]) => void,
96
- ): void;
97
138
  execute(sql: string, params?: SqliteBindings): Promise<SqliteExecuteResult>;
98
- executeSync?(sql: string, params?: SqliteBindings): SqliteExecuteResult;
99
139
  executeBatch(
100
140
  statements: SqliteBatchStatement[],
101
141
  ): Promise<SqliteExecuteResult[]>;
@@ -103,31 +143,12 @@ export interface SqliteDatabase {
103
143
  timeoutMs?: number,
104
144
  name?: string,
105
145
  ): Promise<SqliteTransactionDatabase>;
106
- beginTransactionSync?(
107
- timeoutMs?: number,
108
- name?: string,
109
- ): SynchronousSqliteTransactionDatabase;
110
146
  run(sql: string, params?: SqliteBindings): Promise<void>;
111
147
  query(sql: string, params?: SqliteBindings): Promise<SqliteQueryResult>;
112
148
  nativeMetrics?():
113
149
  | SqliteNativeMetrics
114
150
  | Promise<SqliteNativeMetrics | null>
115
151
  | null;
116
- /**
117
- * Returns the ticket of the latest local commit. Synchronous writes return before they are
118
- * durable; pass the ticket to `whenDurable` before releasing output that depends on them.
119
- */
120
- commitTicket?(): number;
121
- /**
122
- * Resolves once the commit `ticket` names and every earlier commit are durable. Rejects with
123
- * `sqlite.durability_failed` once the database broke and the actor is restarting.
124
- */
125
- whenDurable?(ticket: number): Promise<void>;
126
- /**
127
- * Restarts the owning actor from durable state. Every later write fails, including the final
128
- * state save. For native database providers whose in-memory state can no longer be trusted.
129
- */
130
- abortGeneration?(reason: string): void;
131
152
  close(): Promise<void>;
132
153
  }
133
154
 
@@ -136,26 +157,11 @@ export interface SqliteTransactionDatabase {
136
157
  sql: string,
137
158
  callback?: (row: unknown[], columns: string[]) => void,
138
159
  ): Promise<void>;
139
- execSync?(
140
- sql: string,
141
- callback?: (row: unknown[], columns: string[]) => void,
142
- ): void;
143
160
  execute(sql: string, params?: SqliteBindings): Promise<SqliteExecuteResult>;
144
- executeSync?(sql: string, params?: SqliteBindings): SqliteExecuteResult;
145
161
  commit(): Promise<void>;
146
162
  rollback(): Promise<void>;
147
163
  }
148
164
 
149
- export type SynchronousSqliteTransactionDatabase = SqliteTransactionDatabase & {
150
- execSync(
151
- sql: string,
152
- callback?: (row: unknown[], columns: string[]) => void,
153
- ): void;
154
- executeSync(sql: string, params?: SqliteBindings): SqliteExecuteResult;
155
- commitSync(): void;
156
- rollbackSync(): void;
157
- };
158
-
159
165
  /**
160
166
  * Provider for opening native databases from the active runtime.
161
167
  */
@@ -0,0 +1,364 @@
1
+ import { pino } from "pino";
2
+ import { beforeEach, describe, expect, test } from "vitest";
3
+ import { configureBaseLogger } from "@/common/log";
4
+ import type {
5
+ DatabaseProviderContext,
6
+ SqliteBindings,
7
+ SqliteDatabase,
8
+ SqliteExecuteResult,
9
+ SqliteTransactionDatabase,
10
+ } from "./config";
11
+ import { db, registerNativeStateTransactionOpener } from "./mod";
12
+
13
+ let logLines: string[];
14
+
15
+ class FakeSqliteDatabase implements SqliteDatabase {
16
+ failSql = new Map<string, Error>();
17
+ executeCalls: { sql: string; params?: SqliteBindings }[] = [];
18
+ stateTransactionTimeouts: Array<number | undefined> = [];
19
+ transactionTimeouts: Array<number | undefined> = [];
20
+ transactionNames: Array<string | undefined> = [];
21
+
22
+ async exec(): Promise<void> {}
23
+
24
+ async execute(
25
+ sql: string,
26
+ params?: SqliteBindings,
27
+ ): Promise<SqliteExecuteResult> {
28
+ this.record(sql, params);
29
+ return emptyResult();
30
+ }
31
+
32
+ async beginTransaction(
33
+ timeoutMs?: number,
34
+ name?: string,
35
+ ): Promise<SqliteTransactionDatabase> {
36
+ this.transactionTimeouts.push(timeoutMs);
37
+ this.transactionNames.push(name);
38
+ this.record("BEGIN");
39
+ return {
40
+ exec: async () => {},
41
+ execute: async (sql, params) => {
42
+ this.record(sql, params);
43
+ return emptyResult();
44
+ },
45
+ commit: async () => this.record("COMMIT"),
46
+ rollback: async () => this.record("ROLLBACK"),
47
+ };
48
+ }
49
+ async beginStateTransaction(
50
+ timeoutMs?: number,
51
+ ): Promise<SqliteTransactionDatabase> {
52
+ this.stateTransactionTimeouts.push(timeoutMs);
53
+ this.record("BEGIN_STATE");
54
+ return {
55
+ exec: async () => {},
56
+ execute: async (sql, params) => {
57
+ this.record(sql, params);
58
+ return emptyResult();
59
+ },
60
+ commit: async () => this.record("COMMIT"),
61
+ rollback: async () => this.record("ROLLBACK"),
62
+ };
63
+ }
64
+
65
+ async executeBatch(
66
+ statements: Array<{ sql: string; params?: SqliteBindings }>,
67
+ ): Promise<SqliteExecuteResult[]> {
68
+ const results: SqliteExecuteResult[] = [];
69
+ for (const statement of statements) {
70
+ results.push(await this.execute(statement.sql, statement.params));
71
+ }
72
+ return results;
73
+ }
74
+
75
+ async run(sql: string, params?: SqliteBindings): Promise<void> {
76
+ await this.execute(sql, params);
77
+ }
78
+
79
+ async query(sql: string, params?: SqliteBindings) {
80
+ const { columns, rows } = await this.execute(sql, params);
81
+ return { columns, rows };
82
+ }
83
+
84
+ async close(): Promise<void> {}
85
+
86
+ private record(sql: string, params?: SqliteBindings): void {
87
+ this.executeCalls.push({ sql, params });
88
+ const error = this.failSql.get(sql);
89
+ if (error) throw error;
90
+ }
91
+ }
92
+
93
+ function emptyResult(): SqliteExecuteResult {
94
+ return {
95
+ columns: [],
96
+ rows: [],
97
+ changes: 0,
98
+ lastInsertRowId: null,
99
+ };
100
+ }
101
+
102
+ function testProviderContext(
103
+ database: FakeSqliteDatabase,
104
+ includeStateTransactions = false,
105
+ ): DatabaseProviderContext {
106
+ return {
107
+ actorId: "actor-a",
108
+ kv: {
109
+ batchPut: async () => {},
110
+ batchGet: async (keys) => keys.map(() => null),
111
+ batchDelete: async () => {},
112
+ deleteRange: async () => {},
113
+ },
114
+ nativeDatabaseProvider: includeStateTransactions
115
+ ? registerNativeStateTransactionOpener(
116
+ { open: async () => database },
117
+ async (timeoutMs?: number) =>
118
+ await database.beginStateTransaction(timeoutMs),
119
+ )
120
+ : { open: async () => database },
121
+ };
122
+ }
123
+
124
+ describe("db", () => {
125
+ beforeEach(() => {
126
+ logLines = [];
127
+ configureBaseLogger(
128
+ pino(
129
+ { level: "warn", base: {}, timestamp: false },
130
+ { write: (line: string) => logLines.push(line) },
131
+ ),
132
+ );
133
+ });
134
+
135
+ test("runs onMigrate through the shared transaction handle", async () => {
136
+ const nativeDb = new FakeSqliteDatabase();
137
+ const provider = db({
138
+ onMigrate: async (client) => {
139
+ await client.execute(
140
+ "CREATE TABLE items(id INTEGER PRIMARY KEY)",
141
+ );
142
+ },
143
+ });
144
+ const client = await provider.createClient(
145
+ testProviderContext(nativeDb),
146
+ );
147
+ await provider.onMigrate(client);
148
+
149
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
150
+ "BEGIN",
151
+ "SAVEPOINT __rivet_on_migrate",
152
+ "CREATE TABLE items(id INTEGER PRIMARY KEY)",
153
+ "RELEASE SAVEPOINT __rivet_on_migrate",
154
+ "COMMIT",
155
+ ]);
156
+ expect(nativeDb.transactionTimeouts).toEqual([300_000]);
157
+ expect(nativeDb.transactionNames).toEqual(["rivetkit-migration"]);
158
+ });
159
+
160
+ test("exposes profiling controls to the actor runtime", () => {
161
+ const provider = db({
162
+ profiling: {
163
+ enabled: false,
164
+ maxTrackedStatementFingerprints: 12,
165
+ baselineSampleRate: 0.25,
166
+ },
167
+ });
168
+
169
+ expect(provider.sqliteProfiling).toEqual({
170
+ enabled: false,
171
+ maxTrackedStatementFingerprints: 12,
172
+ baselineSampleRate: 0.25,
173
+ });
174
+ });
175
+
176
+ test("rolls back migrations when onMigrate fails", async () => {
177
+ const nativeDb = new FakeSqliteDatabase();
178
+ const provider = db({
179
+ onMigrate: async () => {
180
+ throw new Error("migration failed");
181
+ },
182
+ });
183
+ const client = await provider.createClient(
184
+ testProviderContext(nativeDb),
185
+ );
186
+ await expect(provider.onMigrate(client)).rejects.toThrow(
187
+ "migration failed",
188
+ );
189
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
190
+ "BEGIN",
191
+ "SAVEPOINT __rivet_on_migrate",
192
+ "ROLLBACK TO SAVEPOINT __rivet_on_migrate",
193
+ "RELEASE SAVEPOINT __rivet_on_migrate",
194
+ "ROLLBACK",
195
+ ]);
196
+ });
197
+
198
+ test("commits transaction work and forwards timeout", async () => {
199
+ const nativeDb = new FakeSqliteDatabase();
200
+ const client = await db().createClient(testProviderContext(nativeDb));
201
+ const value = await client.transaction(
202
+ async (tx) => {
203
+ await tx.execute(
204
+ "INSERT INTO items(value) VALUES (?)",
205
+ "inside",
206
+ );
207
+ return 42;
208
+ },
209
+ { name: "insert-item", timeout: 120_000 },
210
+ );
211
+ expect(value).toBe(42);
212
+ expect(nativeDb.transactionTimeouts).toEqual([120_000]);
213
+ expect(nativeDb.transactionNames).toEqual(["insert-item"]);
214
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
215
+ "BEGIN",
216
+ "INSERT INTO items(value) VALUES (?)",
217
+ "COMMIT",
218
+ ]);
219
+ });
220
+
221
+ test("validates transaction names", async () => {
222
+ const client = await db().createClient(
223
+ testProviderContext(new FakeSqliteDatabase()),
224
+ );
225
+ await expect(
226
+ client.transaction(async () => {}, { name: "" }),
227
+ ).rejects.toThrow("must not be empty");
228
+ });
229
+
230
+ test("defers the configured transaction name byte limit to the runtime", async () => {
231
+ const nativeDb = new FakeSqliteDatabase();
232
+ const client = await db().createClient(testProviderContext(nativeDb));
233
+ const name = "x".repeat(129);
234
+
235
+ await client.transaction(async () => {}, { name });
236
+
237
+ expect(nativeDb.transactionNames).toEqual([name]);
238
+ });
239
+
240
+ test("rolls back a transaction when the callback throws", async () => {
241
+ const nativeDb = new FakeSqliteDatabase();
242
+ const client = await db().createClient(testProviderContext(nativeDb));
243
+ await expect(
244
+ client.transaction(async (tx) => {
245
+ await tx.execute(
246
+ "INSERT INTO items(value) VALUES (?)",
247
+ "inside",
248
+ );
249
+ throw new Error("callback failed");
250
+ }),
251
+ ).rejects.toThrow("callback failed");
252
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
253
+ "BEGIN",
254
+ "INSERT INTO items(value) VALUES (?)",
255
+ "ROLLBACK",
256
+ ]);
257
+ });
258
+
259
+ test("uses the state-aware transaction bridge when explicitly requested", async () => {
260
+ const nativeDb = new FakeSqliteDatabase();
261
+ const client = await db().createClient(
262
+ testProviderContext(nativeDb, true),
263
+ );
264
+
265
+ await client.transaction(
266
+ async (tx) => {
267
+ await tx.execute(
268
+ "INSERT INTO items(value) VALUES (?)",
269
+ "inside",
270
+ );
271
+ },
272
+ {
273
+ timeout: 120_000,
274
+ experimental: { includeState: true },
275
+ },
276
+ );
277
+
278
+ expect(nativeDb.transactionTimeouts).toEqual([]);
279
+ expect(nativeDb.stateTransactionTimeouts).toEqual([120_000]);
280
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
281
+ "BEGIN_STATE",
282
+ "INSERT INTO items(value) VALUES (?)",
283
+ "COMMIT",
284
+ ]);
285
+ });
286
+
287
+ test("rolls back state-aware transactions when the callback throws", async () => {
288
+ const nativeDb = new FakeSqliteDatabase();
289
+ const client = await db().createClient(
290
+ testProviderContext(nativeDb, true),
291
+ );
292
+
293
+ await expect(
294
+ client.transaction(
295
+ async (tx) => {
296
+ await tx.execute(
297
+ "INSERT INTO items(value) VALUES (?)",
298
+ "inside",
299
+ );
300
+ throw new Error("callback failed");
301
+ },
302
+ { experimental: { includeState: true } },
303
+ ),
304
+ ).rejects.toThrow("callback failed");
305
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
306
+ "BEGIN_STATE",
307
+ "INSERT INTO items(value) VALUES (?)",
308
+ "ROLLBACK",
309
+ ]);
310
+ });
311
+
312
+ test("rejects nested state-aware transactions", async () => {
313
+ const nativeDb = new FakeSqliteDatabase();
314
+ const client = await db().createClient(
315
+ testProviderContext(nativeDb, true),
316
+ );
317
+
318
+ await expect(
319
+ client.transaction(
320
+ async (tx) => {
321
+ await tx.transaction(async () => {}, {
322
+ experimental: { includeState: true },
323
+ });
324
+ },
325
+ { experimental: { includeState: true } },
326
+ ),
327
+ ).rejects.toThrow("not supported for nested transactions");
328
+ expect(nativeDb.executeCalls.map(({ sql }) => sql)).toEqual([
329
+ "BEGIN_STATE",
330
+ "ROLLBACK",
331
+ ]);
332
+ });
333
+
334
+ test("validates transaction timeouts", async () => {
335
+ const client = await db().createClient(
336
+ testProviderContext(new FakeSqliteDatabase()),
337
+ );
338
+ for (const timeout of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
339
+ await expect(
340
+ client.transaction(async () => {}, { timeout }),
341
+ ).rejects.toThrow("positive finite");
342
+ }
343
+ });
344
+
345
+ test("warns once for manual cross-call transactions and names the opt-out", async () => {
346
+ const client = await db().createClient(
347
+ testProviderContext(new FakeSqliteDatabase()),
348
+ );
349
+ await client.execute("BEGIN");
350
+ await client.execute("COMMIT");
351
+ expect(logLines).toHaveLength(1);
352
+ expect(JSON.parse(logLines[0] ?? "{}").msg).toContain(
353
+ "Set warnOnManualTransactions: false",
354
+ );
355
+ });
356
+
357
+ test("can suppress the manual transaction warning", async () => {
358
+ const client = await db({
359
+ warnOnManualTransactions: false,
360
+ }).createClient(testProviderContext(new FakeSqliteDatabase()));
361
+ await client.execute("BEGIN");
362
+ expect(logLines).toHaveLength(0);
363
+ });
364
+ });