rivetkit 2.3.11-rc.9 → 2.3.11

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 (152) hide show
  1. package/dist/browser/client.d.ts +96 -14
  2. package/dist/browser/client.js +12 -2
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +139 -139
  5. package/dist/browser/inspector/client.js +12 -2
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/agent-os/index.cjs +146 -76
  8. package/dist/tsup/agent-os/index.cjs.map +1 -1
  9. package/dist/tsup/agent-os/index.d.cts +83 -9
  10. package/dist/tsup/agent-os/index.d.ts +83 -9
  11. package/dist/tsup/agent-os/index.js +146 -76
  12. package/dist/tsup/agent-os/index.js.map +1 -1
  13. package/dist/tsup/{chunk-HOZ3ZLZ2.js → chunk-3ZR542SK.js} +6 -6
  14. package/dist/tsup/chunk-3ZR542SK.js.map +1 -0
  15. package/dist/tsup/{chunk-HNHLBM3Y.cjs → chunk-4KGXFC6M.cjs} +42 -5
  16. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  17. package/dist/tsup/chunk-5UYWLCRO.js +14 -0
  18. package/dist/tsup/chunk-5UYWLCRO.js.map +1 -0
  19. package/dist/tsup/{chunk-QWLJCP3X.js → chunk-6W5VGLFT.js} +42 -5
  20. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  21. package/dist/tsup/chunk-6WYATRS4.js +243 -0
  22. package/dist/tsup/chunk-6WYATRS4.js.map +1 -0
  23. package/dist/tsup/chunk-B3W74FBB.cjs +14 -0
  24. package/dist/tsup/chunk-B3W74FBB.cjs.map +1 -0
  25. package/dist/tsup/{chunk-XOOESJY7.js → chunk-FWROC5LA.js} +2 -2
  26. package/dist/tsup/{chunk-V5CVATRU.cjs → chunk-GLIPKKEC.cjs} +7 -7
  27. package/dist/tsup/{chunk-V5CVATRU.cjs.map → chunk-GLIPKKEC.cjs.map} +1 -1
  28. package/dist/tsup/{chunk-T5XVTVQY.cjs → chunk-GN2EUMEW.cjs} +3 -3
  29. package/dist/tsup/{chunk-T5XVTVQY.cjs.map → chunk-GN2EUMEW.cjs.map} +1 -1
  30. package/dist/tsup/{chunk-T56IZ42M.cjs → chunk-GU7ML3KE.cjs} +13 -3
  31. package/dist/tsup/chunk-GU7ML3KE.cjs.map +1 -0
  32. package/dist/tsup/{chunk-IOLZ3ONU.js → chunk-JQ2AZ5FN.js} +3 -3
  33. package/dist/tsup/{chunk-7AFZMFPQ.js → chunk-JTHHCZCZ.js} +10 -1
  34. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  35. package/dist/tsup/{chunk-UEULFXUI.cjs → chunk-KVFIONKQ.cjs} +11 -2
  36. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  37. package/dist/tsup/chunk-LWQFXGKS.cjs +243 -0
  38. package/dist/tsup/chunk-LWQFXGKS.cjs.map +1 -0
  39. package/dist/tsup/{chunk-QVCO6DTZ.js → chunk-MO2SSUOR.js} +8 -7
  40. package/dist/tsup/chunk-MO2SSUOR.js.map +1 -0
  41. package/dist/tsup/{chunk-LZ4TSBIP.js → chunk-OUENKQHB.js} +13 -3
  42. package/dist/tsup/chunk-OUENKQHB.js.map +1 -0
  43. package/dist/tsup/{chunk-6SBPWTXJ.cjs → chunk-PUZY2XCD.cjs} +10 -9
  44. package/dist/tsup/chunk-PUZY2XCD.cjs.map +1 -0
  45. package/dist/tsup/{chunk-C5TORAVP.js → chunk-QFJ24MBU.js} +27 -2
  46. package/dist/tsup/{chunk-C5TORAVP.js.map → chunk-QFJ24MBU.js.map} +1 -1
  47. package/dist/tsup/{chunk-BZWKY6WO.cjs → chunk-RXXDNJXB.cjs} +140 -140
  48. package/dist/tsup/{chunk-BZWKY6WO.cjs.map → chunk-RXXDNJXB.cjs.map} +1 -1
  49. package/dist/tsup/{chunk-IMRDHZM2.cjs → chunk-VBJQIBXI.cjs} +30 -5
  50. package/dist/tsup/chunk-VBJQIBXI.cjs.map +1 -0
  51. package/dist/tsup/client/mod.cjs +6 -6
  52. package/dist/tsup/client/mod.d.cts +4 -3
  53. package/dist/tsup/client/mod.d.ts +4 -3
  54. package/dist/tsup/client/mod.js +5 -5
  55. package/dist/tsup/common/log.cjs +2 -2
  56. package/dist/tsup/common/log.js +1 -1
  57. package/dist/tsup/common/websocket.cjs +3 -3
  58. package/dist/tsup/common/websocket.js +2 -2
  59. package/dist/tsup/{config-CZcjyT5B.d.ts → config-C4OSv0QP.d.ts} +92 -7
  60. package/dist/tsup/{config-rGWrumlO.d.cts → config-DTGoWdkG.d.cts} +92 -7
  61. package/dist/tsup/{config-BxOimoGX.d.cts → config-ey2I2zz5.d.cts} +46 -6
  62. package/dist/tsup/{config-BxOimoGX.d.ts → config-ey2I2zz5.d.ts} +46 -6
  63. package/dist/tsup/{context-B8W8E8nW.d.cts → context-C6cvDNyk.d.cts} +2 -2
  64. package/dist/tsup/{context-_UrDZhEh.d.ts → context-CMygeBxS.d.ts} +2 -2
  65. package/dist/tsup/db/drizzle.cjs +18 -10
  66. package/dist/tsup/db/drizzle.cjs.map +1 -1
  67. package/dist/tsup/db/drizzle.d.cts +5 -6
  68. package/dist/tsup/db/drizzle.d.ts +5 -6
  69. package/dist/tsup/db/drizzle.js +13 -5
  70. package/dist/tsup/db/drizzle.js.map +1 -1
  71. package/dist/tsup/db/mod.cjs +5 -175
  72. package/dist/tsup/db/mod.cjs.map +1 -1
  73. package/dist/tsup/db/mod.d.cts +11 -4
  74. package/dist/tsup/db/mod.d.ts +11 -4
  75. package/dist/tsup/db/mod.js +4 -174
  76. package/dist/tsup/db/mod.js.map +1 -1
  77. package/dist/tsup/dynamic/mod.cjs +2 -2
  78. package/dist/tsup/dynamic/mod.d.cts +3 -2
  79. package/dist/tsup/dynamic/mod.d.ts +3 -2
  80. package/dist/tsup/dynamic/mod.js +1 -1
  81. package/dist/tsup/inspector/mod.cjs +5 -4
  82. package/dist/tsup/inspector/mod.cjs.map +1 -1
  83. package/dist/tsup/inspector/mod.d.cts +12 -146
  84. package/dist/tsup/inspector/mod.d.ts +12 -146
  85. package/dist/tsup/inspector/mod.js +4 -3
  86. package/dist/tsup/inspector/mod.js.map +1 -1
  87. package/dist/tsup/inspector/workflow.cjs +21 -0
  88. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  89. package/dist/tsup/inspector/workflow.d.cts +144 -0
  90. package/dist/tsup/inspector/workflow.d.ts +144 -0
  91. package/dist/tsup/inspector/workflow.js +21 -0
  92. package/dist/tsup/inspector/workflow.js.map +1 -0
  93. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  94. package/dist/tsup/inspector-tab/mod.d.cts +4 -3
  95. package/dist/tsup/inspector-tab/mod.d.ts +4 -3
  96. package/dist/tsup/inspector-tab/mod.js +1 -1
  97. package/dist/tsup/mod.cjs +743 -247
  98. package/dist/tsup/mod.cjs.map +1 -1
  99. package/dist/tsup/mod.d.cts +6 -5
  100. package/dist/tsup/mod.d.ts +6 -5
  101. package/dist/tsup/mod.js +670 -174
  102. package/dist/tsup/mod.js.map +1 -1
  103. package/dist/tsup/test/mod.cjs +7 -7
  104. package/dist/tsup/test/mod.d.cts +3 -2
  105. package/dist/tsup/test/mod.d.ts +3 -2
  106. package/dist/tsup/test/mod.js +5 -5
  107. package/dist/tsup/unstable/migrations.d.cts +1 -1
  108. package/dist/tsup/unstable/migrations.d.ts +1 -1
  109. package/dist/tsup/utils.cjs +2 -2
  110. package/dist/tsup/utils.js +1 -1
  111. package/dist/tsup/workflow/mod.cjs +89 -95
  112. package/dist/tsup/workflow/mod.cjs.map +1 -1
  113. package/dist/tsup/workflow/mod.d.cts +5 -4
  114. package/dist/tsup/workflow/mod.d.ts +5 -4
  115. package/dist/tsup/workflow/mod.js +86 -92
  116. package/dist/tsup/workflow/mod.js.map +1 -1
  117. package/package.json +19 -9
  118. package/src/actor/config.test.ts +65 -1
  119. package/src/actor/config.ts +169 -5
  120. package/src/actor/mod.ts +10 -1
  121. package/src/client/actor-common.ts +5 -14
  122. package/src/common/database/config.ts +50 -3
  123. package/src/common/database/mod.test.ts +142 -4
  124. package/src/common/database/mod.ts +210 -98
  125. package/src/common/database/native-database.ts +42 -3
  126. package/src/common/database/shared.ts +9 -0
  127. package/src/db/drizzle.test.ts +8 -1
  128. package/src/db/drizzle.ts +15 -4
  129. package/src/db/mod.ts +3 -0
  130. package/src/inspector/workflow.ts +61 -0
  131. package/src/registry/napi-runtime.ts +69 -1
  132. package/src/registry/native.ts +474 -161
  133. package/src/registry/run-handler-coordinator.test.ts +252 -0
  134. package/src/registry/run-handler-coordinator.ts +219 -0
  135. package/src/registry/runtime.ts +34 -1
  136. package/src/registry/wasm-runtime.ts +122 -17
  137. package/src/utils/node.ts +44 -28
  138. package/src/workflow/driver.ts +56 -58
  139. package/src/workflow/inspector.ts +10 -15
  140. package/src/workflow/mod.ts +48 -70
  141. package/dist/tsup/chunk-6SBPWTXJ.cjs.map +0 -1
  142. package/dist/tsup/chunk-7AFZMFPQ.js.map +0 -1
  143. package/dist/tsup/chunk-HNHLBM3Y.cjs.map +0 -1
  144. package/dist/tsup/chunk-HOZ3ZLZ2.js.map +0 -1
  145. package/dist/tsup/chunk-IMRDHZM2.cjs.map +0 -1
  146. package/dist/tsup/chunk-LZ4TSBIP.js.map +0 -1
  147. package/dist/tsup/chunk-QVCO6DTZ.js.map +0 -1
  148. package/dist/tsup/chunk-QWLJCP3X.js.map +0 -1
  149. package/dist/tsup/chunk-T56IZ42M.cjs.map +0 -1
  150. package/dist/tsup/chunk-UEULFXUI.cjs.map +0 -1
  151. /package/dist/tsup/{chunk-XOOESJY7.js.map → chunk-FWROC5LA.js.map} +0 -0
  152. /package/dist/tsup/{chunk-IOLZ3ONU.js.map → chunk-JQ2AZ5FN.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,18 +1,22 @@
1
1
  import {
2
2
  decodeWorkflowHistoryTransport
3
- } from "./chunk-C5TORAVP.js";
3
+ } from "./chunk-QFJ24MBU.js";
4
4
  import {
5
5
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
6
6
  ActorConfigSchema,
7
7
  CONN_STATE_MANAGER_SYMBOL,
8
8
  RAW_STATE_SYMBOL,
9
+ createRunInspector,
10
+ defineRunHandler,
9
11
  disposeRunInspector,
10
12
  flattenActionHandlers,
11
13
  flattenActionInputSchemas,
12
14
  getRunFunction,
13
15
  getRunInspectorConfig,
14
- getRunMetadata
15
- } from "./chunk-QWLJCP3X.js";
16
+ getRunInspectorKind,
17
+ getRunMetadata,
18
+ hasRunInspectorConfig
19
+ } from "./chunk-6W5VGLFT.js";
16
20
  import {
17
21
  ALLOWED_PUBLIC_HEADERS,
18
22
  HEADER_CONN_PARAMS,
@@ -23,13 +27,18 @@ import {
23
27
  isResponseLike,
24
28
  tryParseEndpoint,
25
29
  updateRunnerConfig
26
- } from "./chunk-HOZ3ZLZ2.js";
30
+ } from "./chunk-3ZR542SK.js";
27
31
  import {
28
32
  makePrefixedKey,
29
33
  removePrefixFromKey
30
34
  } from "./chunk-JI6GZ2C2.js";
31
- import "./chunk-XOOESJY7.js";
32
- import "./chunk-7AFZMFPQ.js";
35
+ import {
36
+ bindNativeStateTransactionContext,
37
+ db,
38
+ registerNativeStateTransactionOpener
39
+ } from "./chunk-6WYATRS4.js";
40
+ import "./chunk-JTHHCZCZ.js";
41
+ import "./chunk-FWROC5LA.js";
33
42
  import {
34
43
  LogLevelSchema,
35
44
  VERSION,
@@ -62,7 +71,7 @@ import {
62
71
  parsePortEnv,
63
72
  stringifyError,
64
73
  toUint8Array
65
- } from "./chunk-LZ4TSBIP.js";
74
+ } from "./chunk-OUENKQHB.js";
66
75
  import {
67
76
  INTERNAL_ERROR_CODE,
68
77
  RivetError,
@@ -1193,11 +1202,33 @@ function wrapJsNativeDatabase(database) {
1193
1202
  release();
1194
1203
  }
1195
1204
  },
1196
- async beginTransaction(timeoutMs) {
1205
+ async beginTransaction(timeoutMs, name) {
1206
+ const release = gate.enter();
1207
+ let transaction;
1208
+ try {
1209
+ transaction = await database.beginTransaction(timeoutMs, name);
1210
+ } catch (error) {
1211
+ enrichNativeDatabaseError(database, error);
1212
+ } finally {
1213
+ release();
1214
+ }
1215
+ return wrapTransaction(database, transaction, gate, (result) => {
1216
+ if (result.lastInsertRowId !== void 0) {
1217
+ lastInsertRowId = result.lastInsertRowId;
1218
+ }
1219
+ });
1220
+ },
1221
+ async beginStateTransaction(timeoutMs, context) {
1222
+ if (!database.beginStateTransaction) {
1223
+ throw new Error("actor state transactions are not configured");
1224
+ }
1197
1225
  const release = gate.enter();
1198
1226
  let transaction;
1199
1227
  try {
1200
- transaction = await database.beginTransaction(timeoutMs);
1228
+ transaction = await database.beginStateTransaction(
1229
+ timeoutMs,
1230
+ context
1231
+ );
1201
1232
  } catch (error) {
1202
1233
  enrichNativeDatabaseError(database, error);
1203
1234
  } finally {
@@ -1307,45 +1338,37 @@ var nodeChildProcess;
1307
1338
  var nodeStream;
1308
1339
  var nodeUrl;
1309
1340
  var hasImportedDependencies = false;
1310
- function getRequireFn() {
1311
- return createRequire(import.meta.url);
1341
+ var fallbackRequire;
1342
+ function loadNodeBuiltin(id) {
1343
+ var _a;
1344
+ const nodeProcess = globalThis.process;
1345
+ const builtin = (_a = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a.call(nodeProcess, id);
1346
+ if (builtin !== void 0) {
1347
+ return builtin;
1348
+ }
1349
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
1350
+ throw new Error("Node.js built-ins are not available");
1351
+ }
1352
+ fallbackRequire ??= createRequire(nodeProcess.execPath);
1353
+ return fallbackRequire(id);
1312
1354
  }
1313
1355
  function importNodeDependencies() {
1314
1356
  if (hasImportedDependencies) return;
1315
1357
  try {
1316
- const requireFn = getRequireFn();
1317
- nodeCrypto = requireFn(
1318
- /* webpackIgnore: true */
1319
- "node:crypto"
1320
- );
1321
- nodeFsSync = requireFn(
1322
- /* webpackIgnore: true */
1323
- "node:fs"
1324
- );
1325
- nodeFs = requireFn(
1326
- /* webpackIgnore: true */
1358
+ nodeCrypto = loadNodeBuiltin("node:crypto");
1359
+ nodeFsSync = loadNodeBuiltin("node:fs");
1360
+ nodeFs = loadNodeBuiltin(
1327
1361
  "node:fs/promises"
1328
1362
  );
1329
- nodePath = requireFn(
1330
- /* webpackIgnore: true */
1331
- "node:path"
1332
- );
1333
- nodeOs = requireFn(
1334
- /* webpackIgnore: true */
1335
- "node:os"
1336
- );
1337
- nodeChildProcess = requireFn(
1338
- /* webpackIgnore: true */
1363
+ nodePath = loadNodeBuiltin("node:path");
1364
+ nodeOs = loadNodeBuiltin("node:os");
1365
+ nodeChildProcess = loadNodeBuiltin(
1339
1366
  "node:child_process"
1340
1367
  );
1341
- nodeStream = requireFn(
1342
- /* webpackIgnore: true */
1368
+ nodeStream = loadNodeBuiltin(
1343
1369
  "node:stream/promises"
1344
1370
  );
1345
- nodeUrl = requireFn(
1346
- /* webpackIgnore: true */
1347
- "node:url"
1348
- );
1371
+ nodeUrl = loadNodeBuiltin("node:url");
1349
1372
  hasImportedDependencies = true;
1350
1373
  } catch (err) {
1351
1374
  console.warn(
@@ -1396,6 +1419,9 @@ function asNativeWebSocket(handle) {
1396
1419
  function asNativeSqlTransaction(handle) {
1397
1420
  return handle;
1398
1421
  }
1422
+ function asNativeActorStateTransaction(handle) {
1423
+ return handle;
1424
+ }
1399
1425
  function asNativeCancellationToken(handle) {
1400
1426
  return handle;
1401
1427
  }
@@ -1619,6 +1645,9 @@ var NapiCoreRuntime = class {
1619
1645
  actorSetAlarm(ctx, timestampMs) {
1620
1646
  asNativeActorContext(ctx).setAlarm(timestampMs);
1621
1647
  }
1648
+ async actorSetRunWakeAt(ctx, timestampMs) {
1649
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
1650
+ }
1622
1651
  actorRequestSave(ctx, opts) {
1623
1652
  asNativeActorContext(ctx).requestSave(opts);
1624
1653
  }
@@ -1779,9 +1808,10 @@ var NapiCoreRuntime = class {
1779
1808
  );
1780
1809
  return results.map(normalizeRuntimeSqlExecuteResult);
1781
1810
  }
1782
- async actorSqlBeginTransaction(ctx, timeoutMs) {
1811
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
1783
1812
  return await this.#actorSql(ctx).beginTransaction(
1784
- timeoutMs
1813
+ timeoutMs,
1814
+ name
1785
1815
  );
1786
1816
  }
1787
1817
  async actorSqlTransactionExec(transaction, sql) {
@@ -1800,6 +1830,26 @@ var NapiCoreRuntime = class {
1800
1830
  async actorSqlTransactionRollback(transaction) {
1801
1831
  await asNativeSqlTransaction(transaction).rollback();
1802
1832
  }
1833
+ async actorBeginStateTransaction(ctx, timeoutMs) {
1834
+ return await asNativeActorContext(ctx).beginStateTransaction(
1835
+ timeoutMs
1836
+ );
1837
+ }
1838
+ async actorStateTransactionExecute(transaction, sql, params) {
1839
+ const result = await asNativeActorStateTransaction(transaction).execute(
1840
+ sql,
1841
+ toNapiSqlBindParams(params)
1842
+ );
1843
+ return normalizeRuntimeSqlExecuteResult(result);
1844
+ }
1845
+ async actorStateTransactionCommit(transaction, payload) {
1846
+ await asNativeActorStateTransaction(transaction).commit(
1847
+ toNapiStateDeltaPayload(payload)
1848
+ );
1849
+ }
1850
+ async actorStateTransactionRollback(transaction) {
1851
+ await asNativeActorStateTransaction(transaction).rollback();
1852
+ }
1803
1853
  async actorSqlQuery(ctx, sql, params) {
1804
1854
  return await this.#actorSql(ctx).query(
1805
1855
  sql,
@@ -1857,6 +1907,13 @@ var NapiCoreRuntime = class {
1857
1907
  signal ? asNativeCancellationToken(signal) : signal
1858
1908
  );
1859
1909
  }
1910
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
1911
+ return await asNativeActorContext(ctx).queue().completePersisted(
1912
+ messageId,
1913
+ expectedName,
1914
+ response == null ? response : toNapiBuffer(response)
1915
+ );
1916
+ }
1860
1917
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1861
1918
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
1862
1919
  name,
@@ -2046,7 +2103,167 @@ function validationError(target, issues) {
2046
2103
  });
2047
2104
  }
2048
2105
 
2106
+ // src/registry/run-handler-coordinator.ts
2107
+ function runUnavailable(actorId, reason) {
2108
+ return new RivetError(
2109
+ "actor",
2110
+ "run_handler_unavailable",
2111
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
2112
+ {
2113
+ public: true,
2114
+ statusCode: 409,
2115
+ metadata: { actorId, reason }
2116
+ }
2117
+ );
2118
+ }
2119
+ function notifyStateChanged(state) {
2120
+ const waiters = [...state.waiters];
2121
+ state.waiters.clear();
2122
+ for (const waiter of waiters) {
2123
+ waiter();
2124
+ }
2125
+ }
2126
+ function waitForStateChange(state) {
2127
+ return new Promise((resolve) => {
2128
+ state.waiters.add(resolve);
2129
+ });
2130
+ }
2131
+ var RunHandlerCoordinator = class {
2132
+ #run;
2133
+ #states = /* @__PURE__ */ new Map();
2134
+ constructor(run) {
2135
+ this.#run = run;
2136
+ }
2137
+ get inspectorKind() {
2138
+ return getRunInspectorKind(this.#run);
2139
+ }
2140
+ async run(actorId, restart, callback) {
2141
+ const state = this.#getOrCreate(actorId);
2142
+ state.restart = restart;
2143
+ this.#initializeInspector(actorId, state);
2144
+ state.queued += 1;
2145
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
2146
+ try {
2147
+ while (!state.closed && (state.exclusive || state.active)) {
2148
+ await waitForStateChange(state);
2149
+ }
2150
+ } finally {
2151
+ state.queued -= 1;
2152
+ }
2153
+ if (state.closed) {
2154
+ return "closed";
2155
+ }
2156
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
2157
+ return "suppressed";
2158
+ }
2159
+ state.active = true;
2160
+ try {
2161
+ await callback();
2162
+ return "ran";
2163
+ } finally {
2164
+ state.active = false;
2165
+ notifyStateChanged(state);
2166
+ }
2167
+ }
2168
+ getInspector(actorId, restart) {
2169
+ var _a;
2170
+ const state = this.#getOrCreate(actorId);
2171
+ state.restart = restart;
2172
+ this.#initializeInspector(actorId, state);
2173
+ return (_a = state.inspector) == null ? void 0 : _a.inspector;
2174
+ }
2175
+ destroy(actorId) {
2176
+ var _a, _b;
2177
+ const state = this.#states.get(actorId);
2178
+ if (!state) return;
2179
+ state.closed = true;
2180
+ (_b = (_a = state.inspector) == null ? void 0 : _a.dispose) == null ? void 0 : _b.call(_a);
2181
+ state.inspector = void 0;
2182
+ notifyStateChanged(state);
2183
+ this.#states.delete(actorId);
2184
+ }
2185
+ #control(actorId, state) {
2186
+ return {
2187
+ run: {
2188
+ withInactive: async (options, callback) => {
2189
+ if (state.closed) {
2190
+ throw runUnavailable(actorId, "actor is destroyed");
2191
+ }
2192
+ if (state.active || state.queued > 0 || state.exclusive) {
2193
+ throw runUnavailable(
2194
+ actorId,
2195
+ "the run handler is active or waiting to start"
2196
+ );
2197
+ }
2198
+ state.exclusive = true;
2199
+ state.exclusiveGeneration += 1;
2200
+ state.exclusiveOutcome = void 0;
2201
+ try {
2202
+ const result = await callback();
2203
+ if (state.closed) {
2204
+ throw runUnavailable(actorId, "actor is destroyed");
2205
+ }
2206
+ state.exclusiveOutcome = "success";
2207
+ if (options.restartOnSuccess && state.queued === 0) {
2208
+ if (!state.restart) {
2209
+ throw runUnavailable(
2210
+ actorId,
2211
+ "the runtime restart callback is not available"
2212
+ );
2213
+ }
2214
+ await state.restart();
2215
+ }
2216
+ return result;
2217
+ } catch (error) {
2218
+ state.exclusiveOutcome = "failure";
2219
+ throw error;
2220
+ } finally {
2221
+ state.exclusive = false;
2222
+ notifyStateChanged(state);
2223
+ }
2224
+ }
2225
+ }
2226
+ };
2227
+ }
2228
+ #getOrCreate(actorId) {
2229
+ let state = this.#states.get(actorId);
2230
+ if (!state) {
2231
+ state = {
2232
+ active: false,
2233
+ closed: false,
2234
+ exclusive: false,
2235
+ exclusiveGeneration: 0,
2236
+ inspectorInitialized: false,
2237
+ queued: 0,
2238
+ waiters: /* @__PURE__ */ new Set()
2239
+ };
2240
+ this.#states.set(actorId, state);
2241
+ }
2242
+ return state;
2243
+ }
2244
+ #initializeInspector(actorId, state) {
2245
+ if (state.inspectorInitialized) return;
2246
+ const inspector = createRunInspector(this.#run, {
2247
+ actorId,
2248
+ control: this.#control(actorId, state)
2249
+ });
2250
+ if (this.inspectorKind === "workflow") {
2251
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
2252
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
2253
+ throw new TypeError(
2254
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
2255
+ );
2256
+ }
2257
+ }
2258
+ state.inspector = inspector;
2259
+ state.inspectorInitialized = true;
2260
+ }
2261
+ };
2262
+
2049
2263
  // src/registry/wasm-runtime.ts
2264
+ function asWasmConstructors(bindings) {
2265
+ return bindings;
2266
+ }
2050
2267
  function asWasmRegistry(handle) {
2051
2268
  return handle;
2052
2269
  }
@@ -2171,10 +2388,10 @@ function childHandle(handle, name) {
2171
2388
  }
2172
2389
  var WasmCoreRuntime = class {
2173
2390
  kind = "wasm";
2174
- #bindings;
2391
+ #constructors;
2175
2392
  #sql = /* @__PURE__ */ new WeakMap();
2176
2393
  constructor(bindings) {
2177
- this.#bindings = bindings;
2394
+ this.#constructors = asWasmConstructors(bindings);
2178
2395
  }
2179
2396
  #actorSql(ctx) {
2180
2397
  const wasmCtx = asWasmActorContext(ctx);
@@ -2187,7 +2404,7 @@ var WasmCoreRuntime = class {
2187
2404
  }
2188
2405
  createRegistry() {
2189
2406
  return callWasmSync(
2190
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
2407
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
2191
2408
  );
2192
2409
  }
2193
2410
  registerActor(registry, name, factory) {
@@ -2242,13 +2459,13 @@ var WasmCoreRuntime = class {
2242
2459
  createActorFactory(callbacks, config) {
2243
2460
  return callWasmSync(
2244
2461
  () => asActorFactoryHandle2(
2245
- new this.#bindings.ActorFactory(callbacks, config)
2462
+ new this.#constructors.ActorFactory(callbacks, config)
2246
2463
  )
2247
2464
  );
2248
2465
  }
2249
2466
  createCancellationToken() {
2250
2467
  return callWasmSync(
2251
- () => new this.#bindings.CancellationToken()
2468
+ () => new this.#constructors.CancellationToken()
2252
2469
  );
2253
2470
  }
2254
2471
  cancellationTokenAborted(token) {
@@ -2283,6 +2500,13 @@ var WasmCoreRuntime = class {
2283
2500
  optionalWasmNumber(timestampMs)
2284
2501
  );
2285
2502
  }
2503
+ async actorSetRunWakeAt(ctx, timestampMs) {
2504
+ await callHandleAsync(
2505
+ asWasmActorContext(ctx),
2506
+ "setRunWakeAt",
2507
+ optionalWasmNumber(timestampMs)
2508
+ );
2509
+ }
2286
2510
  actorRequestSave(ctx, opts) {
2287
2511
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
2288
2512
  }
@@ -2497,9 +2721,9 @@ var WasmCoreRuntime = class {
2497
2721
  );
2498
2722
  return results.map(normalizeRuntimeSqlExecuteResult);
2499
2723
  }
2500
- async actorSqlBeginTransaction(ctx, timeoutMs) {
2724
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
2501
2725
  return await callWasm(
2502
- () => this.#actorSql(ctx).beginTransaction(timeoutMs)
2726
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
2503
2727
  );
2504
2728
  }
2505
2729
  async actorSqlTransactionExec(transaction, sql) {
@@ -2523,6 +2747,27 @@ var WasmCoreRuntime = class {
2523
2747
  () => transaction.rollback()
2524
2748
  );
2525
2749
  }
2750
+ async actorBeginStateTransaction(ctx, timeoutMs) {
2751
+ return await callWasm(
2752
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
2753
+ );
2754
+ }
2755
+ async actorStateTransactionExecute(transaction, sql, params) {
2756
+ const result = await callWasm(
2757
+ () => transaction.execute(sql, params)
2758
+ );
2759
+ return normalizeRuntimeSqlExecuteResult(result);
2760
+ }
2761
+ async actorStateTransactionCommit(transaction, payload) {
2762
+ await callWasm(
2763
+ () => transaction.commit(payload)
2764
+ );
2765
+ }
2766
+ async actorStateTransactionRollback(transaction) {
2767
+ await callWasm(
2768
+ () => transaction.rollback()
2769
+ );
2770
+ }
2526
2771
  async actorSqlQuery(ctx, sql, params) {
2527
2772
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2528
2773
  }
@@ -2595,6 +2840,16 @@ var WasmCoreRuntime = class {
2595
2840
  signal
2596
2841
  );
2597
2842
  }
2843
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
2844
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2845
+ return await callHandleAsync(
2846
+ queue2,
2847
+ "completePersisted",
2848
+ messageId,
2849
+ expectedName,
2850
+ response
2851
+ );
2852
+ }
2598
2853
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2599
2854
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2600
2855
  return optionalBytes(
@@ -3018,6 +3273,14 @@ function stateMutationReentrantError() {
3018
3273
  "State mutations are not allowed inside onStateChange."
3019
3274
  );
3020
3275
  }
3276
+ function stateTransactionConflictError() {
3277
+ return new RivetError(
3278
+ "actor",
3279
+ "state_transaction_conflict",
3280
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
3281
+ { public: true, statusCode: 409 }
3282
+ );
3283
+ }
3021
3284
  function databaseNotConfiguredError() {
3022
3285
  return new RivetError(
3023
3286
  "actor",
@@ -3034,6 +3297,14 @@ function databaseClientNotReadyError() {
3034
3297
  { public: true }
3035
3298
  );
3036
3299
  }
3300
+ function runHandlerNotConfiguredError() {
3301
+ return new RivetError(
3302
+ "actor",
3303
+ "run_handler_unavailable",
3304
+ "Cannot schedule a run wake because this actor does not define a run handler.",
3305
+ { public: true, statusCode: 409 }
3306
+ );
3307
+ }
3037
3308
  function stateNotEnabledError() {
3038
3309
  return new RivetError(
3039
3310
  "actor",
@@ -3136,10 +3407,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
3136
3407
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
3137
3408
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3138
3409
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3139
- beginTransaction: async (timeoutMs) => {
3410
+ beginTransaction: async (timeoutMs, name) => {
3140
3411
  const transaction = await runtime.actorSqlBeginTransaction(
3141
3412
  ctx,
3142
- timeoutMs
3413
+ timeoutMs,
3414
+ name
3143
3415
  );
3144
3416
  return {
3145
3417
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -3152,6 +3424,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
3152
3424
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
3153
3425
  };
3154
3426
  },
3427
+ beginStateTransaction: async (timeoutMs, context) => {
3428
+ const scope = context;
3429
+ if (!scope) {
3430
+ throw new Error(
3431
+ "actor state transaction context is not configured"
3432
+ );
3433
+ }
3434
+ const transaction = await runtime.actorBeginStateTransaction(
3435
+ ctx,
3436
+ timeoutMs
3437
+ );
3438
+ return {
3439
+ exec: async () => {
3440
+ throw new Error(
3441
+ "actor state transactions only support single-statement execute calls"
3442
+ );
3443
+ },
3444
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
3445
+ transaction,
3446
+ sql,
3447
+ params
3448
+ ),
3449
+ commit: async () => {
3450
+ await runtime.actorStateTransactionCommit(
3451
+ transaction,
3452
+ scope.actorContext.serializeForTick("save")
3453
+ );
3454
+ scope.committed = true;
3455
+ },
3456
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
3457
+ };
3458
+ },
3155
3459
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
3156
3460
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
3157
3461
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -3532,12 +3836,16 @@ var NativeConnAdapter = class {
3532
3836
  #schemas;
3533
3837
  #ctx;
3534
3838
  #queueHibernationRemoval;
3535
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
3839
+ #assertCanMutateState;
3840
+ #stateProxy;
3841
+ #stateProxyTarget;
3842
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
3536
3843
  this.#runtime = runtime;
3537
3844
  this.#conn = conn;
3538
3845
  this.#schemas = schemas;
3539
3846
  this.#ctx = ctx;
3540
3847
  this.#queueHibernationRemoval = queueHibernationRemoval;
3848
+ this.#assertCanMutateState = assertCanMutateState;
3541
3849
  this[CONN_STATE_MANAGER_SYMBOL] = {
3542
3850
  stateEnabled: true,
3543
3851
  get state() {
@@ -3563,29 +3871,35 @@ var NativeConnAdapter = class {
3563
3871
  if (!this.#ctx) {
3564
3872
  return this.#createStateProxy(nextState);
3565
3873
  }
3566
- const connState = getNativeConnPersistState(
3567
- this.#runtime,
3568
- this.#ctx,
3569
- this.#conn
3570
- );
3571
- if (connState.stateProxy === void 0 || connState.stateProxyTarget !== nextState) {
3572
- connState.stateProxyTarget = nextState;
3573
- connState.stateProxy = this.#createStateProxy(nextState);
3874
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
3875
+ this.#stateProxyTarget = nextState;
3876
+ this.#stateProxy = this.#createStateProxy(nextState);
3574
3877
  }
3575
- return connState.stateProxy;
3878
+ return this.#stateProxy;
3576
3879
  }
3577
3880
  #createStateProxy(state) {
3881
+ const assertCurrentState = () => {
3882
+ var _a;
3883
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
3884
+ if (this.#ctx && this.#readState() !== state) {
3885
+ throw stateTransactionConflictError();
3886
+ }
3887
+ };
3578
3888
  return createWriteThroughProxy(
3579
3889
  state,
3580
3890
  (nextValue) => {
3891
+ assertCurrentState();
3581
3892
  this.#writeState(nextValue, { writeNative: true });
3582
3893
  },
3583
3894
  (newValue) => {
3895
+ assertCurrentState();
3584
3896
  assertJsonCompatValue(newValue);
3585
3897
  }
3586
3898
  );
3587
3899
  }
3588
3900
  set state(value) {
3901
+ var _a;
3902
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
3589
3903
  const nextValue = unwrapWriteThroughProxy(value);
3590
3904
  assertJsonCompatValue(nextValue);
3591
3905
  this.#writeState(nextValue, { writeNative: true });
@@ -3911,8 +4225,9 @@ var NativeKvAdapter = class {
3911
4225
  };
3912
4226
  function wrapQueueMessage(message, schemas) {
3913
4227
  const name = callNativeSync(() => message.name());
4228
+ const id = callNativeSync(() => message.id());
3914
4229
  return {
3915
- id: Number(callNativeSync(() => message.id())),
4230
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
3916
4231
  name,
3917
4232
  body: validateQueueBody(
3918
4233
  schemas,
@@ -4050,6 +4365,25 @@ var NativeQueueAdapter = class {
4050
4365
  cleanup == null ? void 0 : cleanup();
4051
4366
  }
4052
4367
  }
4368
+ async waitForAvailable(names, options) {
4369
+ await this.waitForNamesAvailable(names ?? [], options);
4370
+ }
4371
+ async complete(message, response) {
4372
+ const validatedResponse = validateQueueComplete(
4373
+ this.#schemas,
4374
+ message.name,
4375
+ response
4376
+ );
4377
+ await callNative(
4378
+ () => this.#runtime.actorQueueCompletePersisted(
4379
+ this.#ctx,
4380
+ BigInt(message.id),
4381
+ message.name,
4382
+ encodeValue(validatedResponse)
4383
+ )
4384
+ );
4385
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
4386
+ }
4053
4387
  async enqueueAndWait(name, body, options) {
4054
4388
  const validatedBody = validateQueueBody(this.#schemas, name, body);
4055
4389
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -4486,10 +4820,12 @@ var NativeConnectionMap = class {
4486
4820
  #runtime;
4487
4821
  #ctx;
4488
4822
  #schemas;
4489
- constructor(runtime, ctx, schemas) {
4823
+ #assertCanMutateState;
4824
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
4490
4825
  this.#runtime = runtime;
4491
4826
  this.#ctx = ctx;
4492
4827
  this.#schemas = schemas;
4828
+ this.#assertCanMutateState = assertCanMutateState;
4493
4829
  }
4494
4830
  #connToAdapter(conn) {
4495
4831
  return new NativeConnAdapter(
@@ -4502,7 +4838,8 @@ var NativeConnectionMap = class {
4502
4838
  this.#ctx,
4503
4839
  connId
4504
4840
  )
4505
- )
4841
+ ),
4842
+ this.#assertCanMutateState
4506
4843
  );
4507
4844
  }
4508
4845
  get size() {
@@ -4561,17 +4898,20 @@ var ActorContextHandleAdapter = class {
4561
4898
  #queue;
4562
4899
  #request;
4563
4900
  #schedule;
4564
- #sql;
4565
- #runHandlerActiveProvider;
4901
+ #run;
4902
+ #runHandlerConfigured;
4566
4903
  #onStateChange;
4567
4904
  #stateEnabled;
4568
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
4905
+ #stateProxy;
4906
+ #stateProxyTarget;
4907
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
4908
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
4569
4909
  this.#runtime = runtime;
4570
4910
  this.#ctx = ctx;
4571
4911
  this.#clientFactory = clientFactory;
4572
4912
  this.#schemas = schemas;
4573
4913
  this.#dispatchCancelToken = dispatchCancelToken;
4574
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
4914
+ this.#runHandlerConfigured = runHandlerConfigured;
4575
4915
  this.#onStateChange = onStateChange;
4576
4916
  this.#stateEnabled = stateEnabled;
4577
4917
  if (databaseProvider) {
@@ -4588,12 +4928,6 @@ var ActorContextHandleAdapter = class {
4588
4928
  }
4589
4929
  return this.#kv;
4590
4930
  }
4591
- get sql() {
4592
- if (!this.#sql) {
4593
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
4594
- }
4595
- return this.#sql;
4596
- }
4597
4931
  async actorRuntimeSocket() {
4598
4932
  return await callNative(
4599
4933
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -4609,7 +4943,7 @@ var ActorContextHandleAdapter = class {
4609
4943
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4610
4944
  const cachedClient = runtimeState.databaseClient;
4611
4945
  if (cachedClient) {
4612
- this.#db = cachedClient.client;
4946
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4613
4947
  return this.#db;
4614
4948
  }
4615
4949
  throw databaseClientNotReadyError();
@@ -4624,22 +4958,28 @@ var ActorContextHandleAdapter = class {
4624
4958
  if (!this.#stateEnabled) {
4625
4959
  throw stateNotEnabledError();
4626
4960
  }
4627
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
4628
4961
  const nextState = this.#readState();
4629
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4630
- actorState.stateProxyTarget = nextState;
4631
- actorState.stateProxy = createWriteThroughProxy(
4962
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
4963
+ const assertCurrentState = () => {
4964
+ this.#assertCanMutateState();
4965
+ if (this.#readState() !== nextState) {
4966
+ throw stateTransactionConflictError();
4967
+ }
4968
+ };
4969
+ this.#stateProxyTarget = nextState;
4970
+ this.#stateProxy = createWriteThroughProxy(
4632
4971
  nextState,
4633
4972
  (nextValue) => {
4973
+ assertCurrentState();
4634
4974
  this.#writeState(nextValue, { scheduleSave: true });
4635
4975
  },
4636
4976
  (newValue) => {
4637
- this.#assertCanMutateState();
4977
+ assertCurrentState();
4638
4978
  assertJsonCompatValue(newValue);
4639
4979
  }
4640
4980
  );
4641
4981
  }
4642
- return actorState.stateProxy;
4982
+ return this.#stateProxy;
4643
4983
  }
4644
4984
  set state(value) {
4645
4985
  if (!this.#stateEnabled) {
@@ -4682,6 +5022,26 @@ var ActorContextHandleAdapter = class {
4682
5022
  }
4683
5023
  return this.#queue;
4684
5024
  }
5025
+ get run() {
5026
+ if (!this.#run) {
5027
+ this.#run = {
5028
+ setWakeAt: async (timestamp) => {
5029
+ if (timestamp !== null && !this.#runHandlerConfigured) {
5030
+ throw runHandlerNotConfiguredError();
5031
+ }
5032
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
5033
+ throw new TypeError(
5034
+ "Run wake timestamp must be a non-negative safe integer or null"
5035
+ );
5036
+ }
5037
+ await callNative(
5038
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
5039
+ );
5040
+ }
5041
+ };
5042
+ }
5043
+ return this.#run;
5044
+ }
4685
5045
  get schedule() {
4686
5046
  if (!this.#schedule) {
4687
5047
  this.#schedule = new NativeScheduleAdapter(
@@ -4716,7 +5076,8 @@ var ActorContextHandleAdapter = class {
4716
5076
  this.#connMap = new NativeConnectionMap(
4717
5077
  this.#runtime,
4718
5078
  this.#ctx,
4719
- this.#schemas
5079
+ this.#schemas,
5080
+ () => this.#assertCanMutateState()
4720
5081
  );
4721
5082
  }
4722
5083
  return this.#connMap;
@@ -4785,11 +5146,11 @@ var ActorContextHandleAdapter = class {
4785
5146
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4786
5147
  const cachedClient = runtimeState.databaseClient;
4787
5148
  if (cachedClient) {
4788
- this.#db = cachedClient.client;
5149
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4789
5150
  return this.#db;
4790
5151
  }
4791
5152
  const actorId = this.actorId;
4792
- const client = await this.#databaseProvider.createClient({
5153
+ const createdClient = await this.#databaseProvider.createClient({
4793
5154
  actorId,
4794
5155
  kv: {
4795
5156
  batchPut: async (entries) => {
@@ -4810,21 +5171,126 @@ var ActorContextHandleAdapter = class {
4810
5171
  log: {
4811
5172
  debug: (obj) => logger2().debug(obj)
4812
5173
  },
4813
- nativeDatabaseProvider: {
4814
- open: async (requestedActorId) => {
4815
- void requestedActorId;
4816
- return getOrCreateNativeSqlDatabase(
4817
- this.#runtime,
4818
- this.#ctx
4819
- );
4820
- }
4821
- }
5174
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
5175
+ {
5176
+ open: async (requestedActorId) => {
5177
+ void requestedActorId;
5178
+ return getOrCreateNativeSqlDatabase(
5179
+ this.#runtime,
5180
+ this.#ctx
5181
+ );
5182
+ }
5183
+ },
5184
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
5185
+ this.#runtime,
5186
+ this.#ctx
5187
+ ).beginStateTransaction(timeoutMs, context)
5188
+ )
4822
5189
  });
4823
5190
  runtimeState.databaseClient = {
4824
- client
5191
+ client: createdClient
4825
5192
  };
4826
- this.#db = client;
4827
- return client;
5193
+ this.#db = this.#bindDatabaseClient(createdClient);
5194
+ return this.#db;
5195
+ }
5196
+ #bindDatabaseClient(client) {
5197
+ return bindNativeStateTransactionContext(client, {
5198
+ enter: async () => await this.#enterStateTransaction(),
5199
+ exit: (scope) => this.#exitStateTransaction(
5200
+ scope
5201
+ )
5202
+ });
5203
+ }
5204
+ async #enterStateTransaction() {
5205
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5206
+ let pendingOwners = actorState.pendingStateTransactionOwners;
5207
+ if (!pendingOwners) {
5208
+ pendingOwners = /* @__PURE__ */ new Set();
5209
+ actorState.pendingStateTransactionOwners = pendingOwners;
5210
+ }
5211
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
5212
+ throw stateTransactionConflictError();
5213
+ }
5214
+ pendingOwners.add(this.#stateTransactionOwner);
5215
+ const predecessor = actorState.stateTransactionTail ?? Promise.resolve();
5216
+ let release;
5217
+ const hold = new Promise((resolve) => {
5218
+ release = resolve;
5219
+ });
5220
+ actorState.stateTransactionTail = predecessor.then(
5221
+ async () => await hold
5222
+ );
5223
+ try {
5224
+ await predecessor;
5225
+ pendingOwners.delete(this.#stateTransactionOwner);
5226
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
5227
+ return {
5228
+ actorContext: this,
5229
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
5230
+ connectionStateBaselines: new Map(
5231
+ callNativeSync(
5232
+ () => this.#runtime.actorConns(this.#ctx)
5233
+ ).map((conn) => [
5234
+ callNativeSync(() => this.#runtime.connId(conn)),
5235
+ new Uint8Array(
5236
+ callNativeSync(() => this.#runtime.connState(conn))
5237
+ )
5238
+ ])
5239
+ ),
5240
+ committed: false,
5241
+ release
5242
+ };
5243
+ } catch (error) {
5244
+ pendingOwners.delete(this.#stateTransactionOwner);
5245
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5246
+ actorState.activeStateTransactionOwner = void 0;
5247
+ }
5248
+ release();
5249
+ throw error;
5250
+ }
5251
+ }
5252
+ #exitStateTransaction(scope) {
5253
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5254
+ try {
5255
+ if (!scope.committed) {
5256
+ this.#restoreStateTransactionBaseline(scope);
5257
+ }
5258
+ } finally {
5259
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5260
+ actorState.activeStateTransactionOwner = void 0;
5261
+ }
5262
+ if (actorState.stateTransactionSaveDeferred) {
5263
+ actorState.stateTransactionSaveDeferred = false;
5264
+ this.#scheduleSave();
5265
+ }
5266
+ scope.release();
5267
+ }
5268
+ }
5269
+ #restoreStateTransactionBaseline(scope) {
5270
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5271
+ if (actorState.pendingSaveHandle !== void 0) {
5272
+ clearImmediate(actorState.pendingSaveHandle);
5273
+ }
5274
+ actorState.pendingSaveHandle = void 0;
5275
+ actorState.saveScheduled = false;
5276
+ if (this.#stateEnabled) {
5277
+ actorState.state = structuredClone(scope.actorStateBaseline);
5278
+ }
5279
+ for (const conn of callNativeSync(
5280
+ () => this.#runtime.actorConns(this.#ctx)
5281
+ )) {
5282
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
5283
+ const baseline = scope.connectionStateBaselines.get(connId);
5284
+ if (baseline === void 0) {
5285
+ continue;
5286
+ }
5287
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
5288
+ const cached = actorState.connStates.get(connId);
5289
+ if (cached) {
5290
+ cached.state = decodeValue(baseline);
5291
+ }
5292
+ }
5293
+ this.#scheduleSave();
4828
5294
  }
4829
5295
  async prepare() {
4830
5296
  if (!this.#databaseProvider) {
@@ -4842,7 +5308,6 @@ var ActorContextHandleAdapter = class {
4842
5308
  }
4843
5309
  async closeDatabase() {
4844
5310
  this.#db = void 0;
4845
- this.#sql = void 0;
4846
5311
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
4847
5312
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
4848
5313
  }
@@ -4862,6 +5327,7 @@ var ActorContextHandleAdapter = class {
4862
5327
  }
4863
5328
  async saveState(opts) {
4864
5329
  if (opts == null ? void 0 : opts.immediate) {
5330
+ this.#assertCanAwaitStateSave();
4865
5331
  await callNative(
4866
5332
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
4867
5333
  immediate: true
@@ -4882,10 +5348,17 @@ var ActorContextHandleAdapter = class {
4882
5348
  );
4883
5349
  }
4884
5350
  async saveStateAndWorkflowBatch(writes) {
5351
+ this.#assertCanAwaitStateSave();
4885
5352
  await callNative(
4886
5353
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
4887
5354
  );
4888
5355
  }
5356
+ #assertCanAwaitStateSave() {
5357
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5358
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5359
+ throw stateTransactionConflictError();
5360
+ }
5361
+ }
4889
5362
  serializeForTick(reason) {
4890
5363
  void reason;
4891
5364
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4939,10 +5412,6 @@ var ActorContextHandleAdapter = class {
4939
5412
  }
4940
5413
  return promise;
4941
5414
  }
4942
- runHandlerActive() {
4943
- var _a;
4944
- return ((_a = this.#runHandlerActiveProvider) == null ? void 0 : _a.call(this)) ?? false;
4945
- }
4946
5415
  internalKeepAwake(run) {
4947
5416
  const promise = typeof run === "function" ? run() : run;
4948
5417
  const trackedPromise = promise.then(
@@ -5024,7 +5493,6 @@ var ActorContextHandleAdapter = class {
5024
5493
  var _a;
5025
5494
  this.#flushStateChange();
5026
5495
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
5027
- this.#sql = void 0;
5028
5496
  }
5029
5497
  #createActorAbortSignal() {
5030
5498
  const nativeSignal = callNativeSync(
@@ -5058,10 +5526,18 @@ var ActorContextHandleAdapter = class {
5058
5526
  this.#scheduleSave();
5059
5527
  }
5060
5528
  #assertCanMutateState() {
5529
+ var _a;
5061
5530
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
5062
5531
  if (actorState.isInOnStateChange) {
5063
5532
  throw stateMutationReentrantError();
5064
5533
  }
5534
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (((_a = actorState.pendingStateTransactionOwners) == null ? void 0 : _a.size) ?? 0) > 0)) {
5535
+ throw stateTransactionConflictError();
5536
+ }
5537
+ }
5538
+ /** @internal */
5539
+ assertCanMutateState() {
5540
+ this.#assertCanMutateState();
5065
5541
  }
5066
5542
  // Coalesce the request-save and onStateChange work to once per event loop
5067
5543
  // tick. A synchronous burst of mutations (for example
@@ -5083,6 +5559,15 @@ var ActorContextHandleAdapter = class {
5083
5559
  if (!actorState.saveScheduled) {
5084
5560
  return;
5085
5561
  }
5562
+ if (actorState.activeStateTransactionOwner !== void 0) {
5563
+ actorState.saveScheduled = false;
5564
+ if (actorState.pendingSaveHandle !== void 0) {
5565
+ clearImmediate(actorState.pendingSaveHandle);
5566
+ actorState.pendingSaveHandle = void 0;
5567
+ }
5568
+ actorState.stateTransactionSaveDeferred = true;
5569
+ return;
5570
+ }
5086
5571
  actorState.saveScheduled = false;
5087
5572
  if (actorState.pendingSaveHandle !== void 0) {
5088
5573
  clearImmediate(actorState.pendingSaveHandle);
@@ -5206,9 +5691,6 @@ var NativeWorkflowRuntimeAdapter = class {
5206
5691
  }
5207
5692
  };
5208
5693
  }
5209
- isRunHandlerActive() {
5210
- return this.#ctx.runHandlerActive();
5211
- }
5212
5694
  async restartRunHandler() {
5213
5695
  await this.#ctx.restartRunHandler();
5214
5696
  }
@@ -5241,43 +5723,45 @@ var NativeWorkflowRuntimeAdapter = class {
5241
5723
  };
5242
5724
  }
5243
5725
  };
5244
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
5245
- return Object.assign(
5246
- new ActorContextHandleAdapter(
5726
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
5727
+ const actorContext = new ActorContextHandleAdapter(
5728
+ runtime,
5729
+ ctx,
5730
+ clientFactory,
5731
+ schemas,
5732
+ databaseProvider,
5733
+ request,
5734
+ stateEnabled,
5735
+ onStateChange,
5736
+ dispatchCancelToken,
5737
+ runHandlerConfigured
5738
+ );
5739
+ return Object.assign(actorContext, {
5740
+ conn: new NativeConnAdapter(
5247
5741
  runtime,
5248
- ctx,
5249
- clientFactory,
5742
+ conn,
5250
5743
  schemas,
5251
- databaseProvider,
5252
- request,
5253
- stateEnabled,
5254
- void 0,
5255
- onStateChange,
5256
- dispatchCancelToken
5257
- ),
5258
- {
5259
- conn: new NativeConnAdapter(
5260
- runtime,
5261
- conn,
5262
- schemas,
5263
- ctx,
5264
- (connId) => callNativeSync(
5265
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
5266
- )
5267
- )
5268
- }
5269
- );
5744
+ ctx,
5745
+ (connId) => callNativeSync(
5746
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
5747
+ ),
5748
+ () => actorContext.assertCanMutateState()
5749
+ )
5750
+ });
5270
5751
  }
5271
5752
  function buildActorConfig(definition, registryConfig, runtimeKind) {
5753
+ var _a;
5272
5754
  const config = definition.config;
5273
5755
  const options = config.options ?? {};
5274
5756
  const canHibernate = options.canHibernateWebSocket;
5275
5757
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
5758
+ const sqliteProfiling = (_a = config.db) == null ? void 0 : _a.sqliteProfiling;
5276
5759
  return {
5277
5760
  name: options.name,
5278
5761
  icon: options.icon,
5279
- hasDatabase: config.db !== void 0 || usesRemoteSqlite,
5762
+ hasDatabase: true,
5280
5763
  remoteSqlite: usesRemoteSqlite,
5764
+ sqliteProfiling,
5281
5765
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
5282
5766
  hasState: config.state !== void 0 || typeof config.createState === "function",
5283
5767
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -5376,7 +5860,7 @@ function validateInspectorTabSource(tabId, resolved) {
5376
5860
  function buildNativeFactory(runtime, registryConfig, definition) {
5377
5861
  var _a;
5378
5862
  const config = definition.config;
5379
- const databaseProvider = config.db;
5863
+ const databaseProvider = config.db ?? db();
5380
5864
  const actionHandlers = flattenActionHandlers(config.actions);
5381
5865
  const schemaConfig = {
5382
5866
  actionInputSchemas: flattenActionInputSchemas(
@@ -5393,16 +5877,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5393
5877
  ),
5394
5878
  { encoding: "bare" }
5395
5879
  );
5396
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
5397
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
5398
- callNativeSync(() => runtime.actorId(ctx))
5399
- ) ?? false;
5880
+ const run = getRunFunction(config.run);
5881
+ const runHandlerCoordinator = getRunInspectorKind(config.run) === "workflow" ? new RunHandlerCoordinator(config.run) : void 0;
5400
5882
  const getNativeWorkflowInspector = (ctx) => {
5401
- var _a2;
5402
- return (_a2 = getRunInspectorConfig(
5403
- config.run,
5404
- callNativeSync(() => runtime.actorId(ctx))
5405
- )) == null ? void 0 : _a2.workflow;
5883
+ var _a2, _b;
5884
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5885
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
5886
+ return ((_a2 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(actorId, restart)) == null ? void 0 : _a2.workflow) ?? ((_b = getRunInspectorConfig(config.run, actorId)) == null ? void 0 : _b.workflow);
5406
5887
  };
5407
5888
  const onStateChange = typeof config.onStateChange === "function" ? (actorCtx, nextState) => {
5408
5889
  config.onStateChange(actorCtx, nextState);
@@ -5422,9 +5903,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5422
5903
  databaseProvider,
5423
5904
  request,
5424
5905
  stateEnabled,
5425
- () => isNativeRunHandlerActive(ctx),
5426
5906
  onStateChange,
5427
- cancelToken
5907
+ cancelToken,
5908
+ run !== void 0
5428
5909
  );
5429
5910
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
5430
5911
  runtime,
@@ -5436,7 +5917,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5436
5917
  request,
5437
5918
  stateEnabled,
5438
5919
  onStateChange,
5439
- cancelToken
5920
+ cancelToken,
5921
+ run !== void 0
5440
5922
  );
5441
5923
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
5442
5924
  var _a2, _b, _c, _d;
@@ -5487,6 +5969,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5487
5969
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
5488
5970
  };
5489
5971
  const actorCtx = makeActorCtx(ctx, jsRequest);
5972
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
5490
5973
  try {
5491
5974
  if (url.pathname === "/inspector/state" && jsRequest.method === "GET") {
5492
5975
  return jsonResponse({
@@ -5614,9 +6097,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5614
6097
  }
5615
6098
  }
5616
6099
  if (url.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
5617
- const db = actorCtx.sql;
6100
+ const db2 = sql;
5618
6101
  const tables = queryRows(
5619
- await db.query(
6102
+ await db2.query(
5620
6103
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
5621
6104
  )
5622
6105
  );
@@ -5624,13 +6107,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5624
6107
  for (const table of tables) {
5625
6108
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
5626
6109
  const columns = queryRows(
5627
- await db.query(`PRAGMA table_info(${quoted})`)
6110
+ await db2.query(`PRAGMA table_info(${quoted})`)
5628
6111
  );
5629
6112
  const foreignKeys = queryRows(
5630
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
6113
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
5631
6114
  );
5632
6115
  const countResult = queryRows(
5633
- await db.query(
6116
+ await db2.query(
5634
6117
  `SELECT COUNT(*) as count FROM ${quoted}`
5635
6118
  )
5636
6119
  );
@@ -5665,7 +6148,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5665
6148
  );
5666
6149
  const quoted = `"${table.replace(/"/g, '""')}"`;
5667
6150
  const rows = queryRows(
5668
- await actorCtx.sql.query(
6151
+ await sql.query(
5669
6152
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
5670
6153
  [
5671
6154
  Math.max(0, Math.min(limit, 500)),
@@ -5693,15 +6176,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5693
6176
  const bindings = normalizeSqlitePropertyBindings(
5694
6177
  body.properties
5695
6178
  );
5696
- const rows2 = queryRows(
5697
- await actorCtx.sql.query(body.sql, bindings)
5698
- );
6179
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
5699
6180
  return jsonResponse({ rows: jsonSafe(rows2) });
5700
6181
  }
5701
6182
  const args = Array.isArray(body.args) ? body.args : [];
5702
- const rows = queryRows(
5703
- await actorCtx.sql.query(body.sql, args)
5704
- );
6183
+ const rows = queryRows(await sql.query(body.sql, args));
5705
6184
  return jsonResponse({ rows: jsonSafe(rows) });
5706
6185
  }
5707
6186
  if (url.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -5727,7 +6206,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5727
6206
  rpcs: Object.keys(actionHandlers).sort(),
5728
6207
  queueSize: inspectorSnapshot.queueSize,
5729
6208
  isStateEnabled: stateEnabled,
5730
- isDatabaseEnabled: databaseProvider !== void 0,
6209
+ isDatabaseEnabled: true,
5731
6210
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
5732
6211
  workflowState: await workflowState(),
5733
6212
  workflowHistory: workflowHistory()
@@ -5917,6 +6396,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5917
6396
  async (error, payload) => {
5918
6397
  const { ctx } = unwrapTsfnPayload(error, payload);
5919
6398
  const actorCtx = makeActorCtx(ctx);
6399
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5920
6400
  const saveActorState = async () => {
5921
6401
  if (runtime.kind === "wasm") {
5922
6402
  await runtime.actorSaveState(
@@ -5942,6 +6422,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5942
6422
  saveActorState
5943
6423
  );
5944
6424
  } finally {
6425
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6426
+ disposeRunInspector(config.run, actorId);
5945
6427
  await actorCtx.dispose();
5946
6428
  }
5947
6429
  }
@@ -5951,14 +6433,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5951
6433
  async (error, payload) => {
5952
6434
  const { ctx } = unwrapTsfnPayload(error, payload);
5953
6435
  const actorCtx = makeActorCtx(ctx);
6436
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6437
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6438
+ disposeRunInspector(config.run, actorId);
5954
6439
  try {
5955
6440
  if (typeof config.onDestroy === "function") {
5956
6441
  await config.onDestroy(actorCtx);
5957
6442
  }
5958
6443
  } finally {
5959
- const actorId = callNativeSync(() => runtime.actorId(ctx));
5960
- nativeRunHandlerActiveByActorId.delete(actorId);
5961
- disposeRunInspector(config.run, actorId);
5962
6444
  resolveNativeDestroy(runtime, ctx);
5963
6445
  await actorCtx.closeDatabase();
5964
6446
  clearNativeRuntimeState(runtime, ctx);
@@ -6006,7 +6488,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6006
6488
  ctx,
6007
6489
  connId
6008
6490
  )
6009
- )
6491
+ ),
6492
+ () => actorCtx.assertCanMutateState()
6010
6493
  );
6011
6494
  try {
6012
6495
  const nextConnState = hasStaticConnState ? structuredClone(config.connState) : await config.createConnState(
@@ -6043,7 +6526,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6043
6526
  ctx,
6044
6527
  connId
6045
6528
  )
6046
- )
6529
+ ),
6530
+ () => actorCtx.assertCanMutateState()
6047
6531
  );
6048
6532
  try {
6049
6533
  await config.onConnect(
@@ -6075,7 +6559,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6075
6559
  ctx,
6076
6560
  connId
6077
6561
  )
6078
- )
6562
+ ),
6563
+ () => actorCtx.assertCanMutateState()
6079
6564
  )
6080
6565
  );
6081
6566
  }
@@ -6219,7 +6704,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6219
6704
  }
6220
6705
  ) : void 0,
6221
6706
  run: (() => {
6222
- const run = getRunFunction(config.run);
6223
6707
  if (!run) {
6224
6708
  return void 0;
6225
6709
  }
@@ -6227,18 +6711,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6227
6711
  async (error, payload) => {
6228
6712
  const { ctx } = unwrapTsfnPayload(error, payload);
6229
6713
  const actorId = callNativeSync(() => runtime.actorId(ctx));
6230
- const actorCtx = makeActorCtx(ctx);
6231
- nativeRunHandlerActiveByActorId.set(actorId, true);
6232
- try {
6233
- await run(actorCtx);
6234
- } finally {
6235
- nativeRunHandlerActiveByActorId.delete(actorId);
6236
- await actorCtx.dispose();
6714
+ const executeRun = async () => {
6715
+ const actorCtx = makeActorCtx(ctx);
6716
+ try {
6717
+ await run(actorCtx);
6718
+ } finally {
6719
+ await actorCtx.dispose();
6720
+ }
6721
+ };
6722
+ if (runHandlerCoordinator) {
6723
+ const outcome = await runHandlerCoordinator.run(
6724
+ actorId,
6725
+ () => callNativeSync(
6726
+ () => runtime.actorRestartRunHandler(ctx)
6727
+ ),
6728
+ executeRun
6729
+ );
6730
+ return outcome !== "suppressed";
6237
6731
  }
6732
+ await executeRun();
6733
+ return true;
6238
6734
  }
6239
6735
  );
6240
6736
  })(),
6241
- getWorkflowHistory: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
6737
+ getWorkflowHistory: hasRunInspectorConfig(config.run) ? wrapNativeCallback(
6242
6738
  async (error, payload) => {
6243
6739
  var _a2;
6244
6740
  const { ctx } = unwrapTsfnPayload(error, payload);
@@ -6246,7 +6742,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6246
6742
  return history == null ? void 0 : toUint8Array(history);
6247
6743
  }
6248
6744
  ) : void 0,
6249
- replayWorkflow: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
6745
+ replayWorkflow: hasRunInspectorConfig(config.run) ? wrapNativeCallback(
6250
6746
  async (error, payload) => {
6251
6747
  const { ctx, entryId } = unwrapTsfnPayload(
6252
6748
  error,
@@ -6256,9 +6752,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6256
6752
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
6257
6753
  return void 0;
6258
6754
  }
6259
- const history = await workflowInspector.replayFromStep(
6260
- entryId
6261
- ) ?? null;
6755
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
6262
6756
  return history == null ? void 0 : toUint8Array(history);
6263
6757
  }
6264
6758
  ) : void 0,
@@ -6311,7 +6805,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6311
6805
  jsRequest,
6312
6806
  stateEnabled,
6313
6807
  onStateChange,
6314
- cancelToken
6808
+ cancelToken,
6809
+ run !== void 0
6315
6810
  );
6316
6811
  try {
6317
6812
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -7217,6 +7712,7 @@ export {
7217
7712
  actor,
7218
7713
  buildActorNames,
7219
7714
  createClientWithDriver,
7715
+ defineRunHandler,
7220
7716
  event,
7221
7717
  isStaticActorDefinition,
7222
7718
  isStaticActorInstance,