rivetkit 2.3.18 → 2.3.19

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 (136) hide show
  1. package/dist/browser/client.d.ts +723 -616
  2. package/dist/browser/client.js +184 -28
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +3 -1
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/actor/errors.cjs +6 -2
  7. package/dist/tsup/actor/errors.cjs.map +1 -1
  8. package/dist/tsup/actor/errors.d.cts +1 -1
  9. package/dist/tsup/actor/errors.d.ts +1 -1
  10. package/dist/tsup/actor/errors.js +5 -1
  11. package/dist/tsup/agent-os/index.cjs +3 -1
  12. package/dist/tsup/agent-os/index.cjs.map +1 -1
  13. package/dist/tsup/agent-os/index.d.cts +110 -3
  14. package/dist/tsup/agent-os/index.d.ts +110 -3
  15. package/dist/tsup/agent-os/index.js +3 -1
  16. package/dist/tsup/agent-os/index.js.map +1 -1
  17. package/dist/tsup/{chunk-4XECVATQ.js → chunk-464WE4RF.js} +2 -2
  18. package/dist/tsup/{chunk-QIFZELUQ.js → chunk-4SC2NSAV.js} +2 -2
  19. package/dist/tsup/{chunk-ZRTESY7V.cjs → chunk-7A5EIXJJ.cjs} +7 -7
  20. package/dist/tsup/{chunk-ZRTESY7V.cjs.map → chunk-7A5EIXJJ.cjs.map} +1 -1
  21. package/dist/tsup/{chunk-O7RSU3UC.cjs → chunk-7BRRGBRY.cjs} +10 -10
  22. package/dist/tsup/{chunk-O7RSU3UC.cjs.map → chunk-7BRRGBRY.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-IPXIZSE7.js → chunk-7HTST3NX.js} +3 -3
  24. package/dist/tsup/{chunk-PXKNBNVU.js → chunk-BKX7UDTA.js} +188 -31
  25. package/dist/tsup/chunk-BKX7UDTA.js.map +1 -0
  26. package/dist/tsup/{chunk-2MK75JFR.js → chunk-DK3L22R6.js} +4 -4
  27. package/dist/tsup/{chunk-7EPLADKM.js → chunk-DN6MD3KK.js} +7 -7
  28. package/dist/tsup/chunk-DN6MD3KK.js.map +1 -0
  29. package/dist/tsup/{chunk-6W5VGLFT.js → chunk-EB77NZL4.js} +1 -1
  30. package/dist/tsup/chunk-EB77NZL4.js.map +1 -0
  31. package/dist/tsup/{chunk-4KGXFC6M.cjs → chunk-EO5UOXXY.cjs} +1 -1
  32. package/dist/tsup/chunk-EO5UOXXY.cjs.map +1 -0
  33. package/dist/tsup/{chunk-25Z2RK7C.cjs → chunk-G4U5L6AX.cjs} +3 -3
  34. package/dist/tsup/{chunk-25Z2RK7C.cjs.map → chunk-G4U5L6AX.cjs.map} +1 -1
  35. package/dist/tsup/{chunk-NRIRV3Z2.cjs → chunk-IJUXBWH4.cjs} +352 -195
  36. package/dist/tsup/chunk-IJUXBWH4.cjs.map +1 -0
  37. package/dist/tsup/{chunk-2JSYYH6P.cjs → chunk-JX2ITWAV.cjs} +13 -2
  38. package/dist/tsup/chunk-JX2ITWAV.cjs.map +1 -0
  39. package/dist/tsup/{chunk-OKVVWOC3.cjs → chunk-OGPFN6BT.cjs} +3 -3
  40. package/dist/tsup/{chunk-OKVVWOC3.cjs.map → chunk-OGPFN6BT.cjs.map} +1 -1
  41. package/dist/tsup/{chunk-OUQUIBVW.js → chunk-P2OFXH4G.js} +12 -1
  42. package/dist/tsup/chunk-P2OFXH4G.js.map +1 -0
  43. package/dist/tsup/{chunk-IKZ6DJMP.cjs → chunk-PPEIPCW4.cjs} +4 -4
  44. package/dist/tsup/{chunk-IKZ6DJMP.cjs.map → chunk-PPEIPCW4.cjs.map} +1 -1
  45. package/dist/tsup/{chunk-2IDK6NX3.cjs → chunk-RJC5O2SD.cjs} +13 -13
  46. package/dist/tsup/chunk-RJC5O2SD.cjs.map +1 -0
  47. package/dist/tsup/{chunk-TNSLNSQH.js → chunk-WME6KOXW.js} +2 -2
  48. package/dist/tsup/{chunk-LAITPJRA.js → chunk-X7RMJQGY.js} +2 -2
  49. package/dist/tsup/{chunk-T6JUXRNI.cjs → chunk-Z4RAXFSD.cjs} +3 -3
  50. package/dist/tsup/{chunk-T6JUXRNI.cjs.map → chunk-Z4RAXFSD.cjs.map} +1 -1
  51. package/dist/tsup/client/mod.cjs +6 -6
  52. package/dist/tsup/client/mod.d.cts +5 -5
  53. package/dist/tsup/client/mod.d.ts +5 -5
  54. package/dist/tsup/client/mod.js +5 -5
  55. package/dist/tsup/common/log.cjs +3 -3
  56. package/dist/tsup/common/log.js +2 -2
  57. package/dist/tsup/common/websocket.cjs +4 -4
  58. package/dist/tsup/common/websocket.js +3 -3
  59. package/dist/tsup/{config-gvHwMas-.d.cts → config-8n2AOhXK.d.cts} +114 -10
  60. package/dist/tsup/{config-Ug5M2MOr.d.ts → config-DEm0yIVV.d.ts} +114 -10
  61. package/dist/tsup/{context-DererUCI.d.ts → context-DGg2-IOm.d.ts} +1 -1
  62. package/dist/tsup/{context-BSCBvbfM.d.cts → context-DwjOVvlE.d.cts} +1 -1
  63. package/dist/tsup/db/drizzle.cjs +3 -3
  64. package/dist/tsup/db/drizzle.js +2 -2
  65. package/dist/tsup/db/mod.cjs +4 -4
  66. package/dist/tsup/db/mod.js +3 -3
  67. package/dist/tsup/dynamic/mod.cjs +2 -2
  68. package/dist/tsup/dynamic/mod.d.cts +3 -3
  69. package/dist/tsup/dynamic/mod.d.ts +3 -3
  70. package/dist/tsup/dynamic/mod.js +1 -1
  71. package/dist/tsup/inspector/mod.cjs +6 -6
  72. package/dist/tsup/inspector/mod.js +5 -5
  73. package/dist/tsup/inspector/workflow.cjs +5 -5
  74. package/dist/tsup/inspector/workflow.js +4 -4
  75. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  76. package/dist/tsup/inspector-tab/mod.d.cts +4 -4
  77. package/dist/tsup/inspector-tab/mod.d.ts +4 -4
  78. package/dist/tsup/inspector-tab/mod.js +1 -1
  79. package/dist/tsup/mod.cjs +492 -319
  80. package/dist/tsup/mod.cjs.map +1 -1
  81. package/dist/tsup/mod.d.cts +5 -5
  82. package/dist/tsup/mod.d.ts +5 -5
  83. package/dist/tsup/mod.js +367 -194
  84. package/dist/tsup/mod.js.map +1 -1
  85. package/dist/tsup/test/mod.cjs +7 -7
  86. package/dist/tsup/test/mod.d.cts +3 -3
  87. package/dist/tsup/test/mod.d.ts +3 -3
  88. package/dist/tsup/test/mod.js +5 -5
  89. package/dist/tsup/{utils-Bbz-3411.d.cts → utils-CNFeS-Dk.d.cts} +1 -1
  90. package/dist/tsup/{utils-vvJQyygr.d.ts → utils-DsoDinPz.d.cts} +9 -1
  91. package/dist/tsup/{utils-vvJQyygr.d.cts → utils-DsoDinPz.d.ts} +9 -1
  92. package/dist/tsup/{utils-BqdWVlzm.d.ts → utils-OQHBjfcM.d.ts} +1 -1
  93. package/dist/tsup/utils.cjs +3 -3
  94. package/dist/tsup/utils.d.cts +2 -2
  95. package/dist/tsup/utils.d.ts +2 -2
  96. package/dist/tsup/utils.js +2 -2
  97. package/dist/tsup/workflow/mod.cjs +33 -27
  98. package/dist/tsup/workflow/mod.cjs.map +1 -1
  99. package/dist/tsup/workflow/mod.d.cts +5 -5
  100. package/dist/tsup/workflow/mod.d.ts +5 -5
  101. package/dist/tsup/workflow/mod.js +25 -19
  102. package/dist/tsup/workflow/mod.js.map +1 -1
  103. package/package.json +10 -8
  104. package/src/actor/config.ts +38 -0
  105. package/src/actor/errors.ts +31 -0
  106. package/src/client/actor-conn.ts +7 -0
  107. package/src/client/actor-handle.ts +57 -17
  108. package/src/client/client.ts +26 -6
  109. package/src/client/outbound-telemetry.ts +66 -0
  110. package/src/client/queue.ts +3 -0
  111. package/src/client/raw-utils.ts +3 -0
  112. package/src/common/actor-router-consts.ts +3 -0
  113. package/src/common/actor-telemetry-context.ts +19 -0
  114. package/src/common/otel-context.ts +99 -0
  115. package/src/common/utils.ts +1 -19
  116. package/src/engine-client/actor-http-client.ts +15 -0
  117. package/src/registry/index.ts +6 -0
  118. package/src/registry/napi-runtime.ts +155 -35
  119. package/src/registry/native.ts +277 -191
  120. package/src/registry/runtime.ts +66 -0
  121. package/src/registry/wasm-runtime.ts +40 -0
  122. package/src/workflow/driver.ts +20 -12
  123. package/dist/tsup/chunk-2IDK6NX3.cjs.map +0 -1
  124. package/dist/tsup/chunk-2JSYYH6P.cjs.map +0 -1
  125. package/dist/tsup/chunk-4KGXFC6M.cjs.map +0 -1
  126. package/dist/tsup/chunk-6W5VGLFT.js.map +0 -1
  127. package/dist/tsup/chunk-7EPLADKM.js.map +0 -1
  128. package/dist/tsup/chunk-NRIRV3Z2.cjs.map +0 -1
  129. package/dist/tsup/chunk-OUQUIBVW.js.map +0 -1
  130. package/dist/tsup/chunk-PXKNBNVU.js.map +0 -1
  131. /package/dist/tsup/{chunk-4XECVATQ.js.map → chunk-464WE4RF.js.map} +0 -0
  132. /package/dist/tsup/{chunk-QIFZELUQ.js.map → chunk-4SC2NSAV.js.map} +0 -0
  133. /package/dist/tsup/{chunk-IPXIZSE7.js.map → chunk-7HTST3NX.js.map} +0 -0
  134. /package/dist/tsup/{chunk-2MK75JFR.js.map → chunk-DK3L22R6.js.map} +0 -0
  135. /package/dist/tsup/{chunk-TNSLNSQH.js.map → chunk-WME6KOXW.js.map} +0 -0
  136. /package/dist/tsup/{chunk-LAITPJRA.js.map → chunk-X7RMJQGY.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,6 +1,3 @@
1
- import {
2
- decodeWorkflowHistoryTransport
3
- } from "./chunk-QIFZELUQ.js";
4
1
  import {
5
2
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
6
3
  ActorConfigSchema,
@@ -16,7 +13,10 @@ import {
16
13
  getRunInspectorKind,
17
14
  getRunMetadata,
18
15
  hasRunInspectorConfig
19
- } from "./chunk-6W5VGLFT.js";
16
+ } from "./chunk-EB77NZL4.js";
17
+ import {
18
+ decodeWorkflowHistoryTransport
19
+ } from "./chunk-4SC2NSAV.js";
20
20
  import {
21
21
  ALLOWED_PUBLIC_HEADERS,
22
22
  HEADER_CONN_PARAMS,
@@ -26,20 +26,22 @@ import {
26
26
  createClientWithDriver,
27
27
  getDatacenters,
28
28
  isResponseLike,
29
+ readActiveTraceHeaders,
30
+ runWithActorInvocationSpan,
29
31
  tryParseEndpoint,
30
32
  updateRunnerConfig
31
- } from "./chunk-PXKNBNVU.js";
33
+ } from "./chunk-BKX7UDTA.js";
32
34
  import {
33
35
  makePrefixedKey,
34
36
  removePrefixFromKey
35
37
  } from "./chunk-JI6GZ2C2.js";
38
+ import "./chunk-X7RMJQGY.js";
36
39
  import {
37
40
  bindNativeStateTransactionContext,
38
41
  db,
39
42
  registerNativeStateTransactionOpener
40
- } from "./chunk-TNSLNSQH.js";
43
+ } from "./chunk-WME6KOXW.js";
41
44
  import "./chunk-JTHHCZCZ.js";
42
- import "./chunk-LAITPJRA.js";
43
45
  import {
44
46
  LogLevelSchema,
45
47
  VERSION,
@@ -73,19 +75,20 @@ import {
73
75
  parsePortEnv,
74
76
  stringifyError,
75
77
  toUint8Array
76
- } from "./chunk-7EPLADKM.js";
78
+ } from "./chunk-DN6MD3KK.js";
77
79
  import {
78
80
  INTERNAL_ERROR_CODE,
79
81
  RivetError,
80
82
  UserError,
81
83
  decodeBridgeRivetError,
82
84
  encodeBridgeRivetError,
85
+ encodeErrorForBridge,
83
86
  forbiddenError,
84
87
  isActorAbortedError,
85
88
  isRivetErrorLike,
86
89
  toRivetError,
87
90
  unsupportedFeature
88
- } from "./chunk-OUQUIBVW.js";
91
+ } from "./chunk-P2OFXH4G.js";
89
92
 
90
93
  // src/actor/log.ts
91
94
  function loggerWithoutContext() {
@@ -1545,20 +1548,43 @@ function toNapiQueueMessage(message) {
1545
1548
  var NapiCoreRuntime = class {
1546
1549
  kind = "napi";
1547
1550
  #bindings;
1548
- #sql = /* @__PURE__ */ new WeakMap();
1549
- constructor(bindings) {
1551
+ #sqlOpened = /* @__PURE__ */ new WeakSet();
1552
+ #invocationContext;
1553
+ constructor(bindings, invocationContext) {
1550
1554
  this.#bindings = bindings;
1555
+ this.#invocationContext = invocationContext;
1551
1556
  }
1552
- #actorSql(ctx) {
1553
- const nativeCtx = asNativeActorContext(ctx);
1554
- let database = this.#sql.get(nativeCtx);
1555
- if (!database) {
1556
- database = nativeCtx.sql();
1557
- this.#sql.set(nativeCtx, database);
1557
+ #actorContextForOperation(owner) {
1558
+ const ownerCtx = asNativeActorContext(owner);
1559
+ const active = this.#invocationContext.getStore();
1560
+ if (!(active == null ? void 0 : active.sameActorInstance(ownerCtx))) {
1561
+ return ownerCtx;
1558
1562
  }
1559
- return database;
1563
+ const applicationSpan = readActiveTraceHeaders();
1564
+ if (!applicationSpan) {
1565
+ return active;
1566
+ }
1567
+ return active.withApplicationSpan(
1568
+ applicationSpan.traceparent,
1569
+ applicationSpan.tracestate ?? null
1570
+ );
1571
+ }
1572
+ #actorSql(ctx) {
1573
+ this.#sqlOpened.add(asNativeActorContext(ctx));
1574
+ return this.#actorContextForOperation(ctx).sql();
1560
1575
  }
1561
1576
  createRegistry() {
1577
+ this.#bindings.setTelemetryLogSink(
1578
+ (event2) => {
1579
+ const fields = { otelEvent: event2.name };
1580
+ const message = event2.message || event2.name;
1581
+ if (event2.level === "error") {
1582
+ logger2().error(fields, message);
1583
+ } else {
1584
+ logger2().warn(fields, message);
1585
+ }
1586
+ }
1587
+ );
1562
1588
  return asRegistryHandle(new this.#bindings.CoreRegistry());
1563
1589
  }
1564
1590
  registerActor(registry, name, factory) {
@@ -1573,6 +1599,9 @@ var NapiCoreRuntime = class {
1573
1599
  async shutdownRegistry(registry) {
1574
1600
  await asNativeRegistry(registry).shutdown();
1575
1601
  }
1602
+ async shutdownTelemetry() {
1603
+ await this.#bindings.shutdownTelemetry();
1604
+ }
1576
1605
  async registryActorStopThresholdMs(registry) {
1577
1606
  return await asNativeRegistry(registry).actorStopThresholdMs() ?? void 0;
1578
1607
  }
@@ -1726,6 +1755,57 @@ var NapiCoreRuntime = class {
1726
1755
  actorId(ctx) {
1727
1756
  return asNativeActorContext(ctx).actorId();
1728
1757
  }
1758
+ runWithActorInvocationContext(ctx, run) {
1759
+ return this.#runAs(asNativeActorContext(ctx), run);
1760
+ }
1761
+ #runAs(nativeCtx, run) {
1762
+ var _a;
1763
+ const span = (_a = nativeCtx.invocationTraceContext()) == null ? void 0 : _a.span;
1764
+ return this.#invocationContext.run(
1765
+ nativeCtx,
1766
+ () => runWithActorInvocationSpan(span, run)
1767
+ );
1768
+ }
1769
+ actorInvocationTraceContext(ctx) {
1770
+ return this.#actorContextForOperation(ctx).invocationTraceContext() ?? void 0;
1771
+ }
1772
+ startCallSpan(ctx, actorName, actionName) {
1773
+ const call = this.#actorContextForOperation(ctx).startCallSpan(
1774
+ actorName,
1775
+ actionName
1776
+ );
1777
+ if (!call) return void 0;
1778
+ return {
1779
+ span: call.spanContext() ?? void 0,
1780
+ finish: (error) => call.finish(error)
1781
+ };
1782
+ }
1783
+ async startWorkflowSpan(ctx) {
1784
+ const span = await asNativeActorContext(ctx).startWorkflowSpan();
1785
+ const spanCtx = span.ctx();
1786
+ return {
1787
+ run: (body) => this.#runAs(spanCtx, body),
1788
+ startStep: (name, attempt) => {
1789
+ const step = spanCtx.startWorkflowStepSpan(name, attempt);
1790
+ if (!step) return void 0;
1791
+ const stepCtx = step.ctx();
1792
+ return {
1793
+ run: (body) => this.#runAs(stepCtx, body),
1794
+ finish: (outcome, error) => step.finish(
1795
+ outcome,
1796
+ error === void 0 ? void 0 : encodeErrorForBridge(error)
1797
+ )
1798
+ };
1799
+ },
1800
+ finish: (outcome) => span.finish(outcome)
1801
+ };
1802
+ }
1803
+ runOutsideActorInvocationContext(run) {
1804
+ return this.#invocationContext.exit(run);
1805
+ }
1806
+ currentInvocationScope() {
1807
+ return this.#invocationContext.getStore();
1808
+ }
1729
1809
  actorName(ctx) {
1730
1810
  return asNativeActorContext(ctx).name();
1731
1811
  }
@@ -1757,7 +1837,7 @@ var NapiCoreRuntime = class {
1757
1837
  asNativeActorContext(ctx).broadcast(name, toNapiBuffer(args));
1758
1838
  }
1759
1839
  actorWaitUntil(ctx, promise) {
1760
- asNativeActorContext(ctx).waitUntil(promise);
1840
+ this.#actorContextForOperation(ctx).waitUntil(promise);
1761
1841
  }
1762
1842
  async actorWaitForTrackedShutdownWork(ctx) {
1763
1843
  return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
@@ -1858,7 +1938,7 @@ var NapiCoreRuntime = class {
1858
1938
  await asNativeSqlTransaction(transaction).rollback();
1859
1939
  }
1860
1940
  async actorBeginStateTransaction(ctx, timeoutMs) {
1861
- return await asNativeActorContext(ctx).beginStateTransaction(
1941
+ return await this.#actorContextForOperation(ctx).beginStateTransaction(
1862
1942
  timeoutMs
1863
1943
  );
1864
1944
  }
@@ -1896,23 +1976,21 @@ var NapiCoreRuntime = class {
1896
1976
  }
1897
1977
  async actorSqlClose(ctx) {
1898
1978
  const nativeCtx = asNativeActorContext(ctx);
1899
- const database = this.#sql.get(nativeCtx);
1900
- if (!database) {
1979
+ if (!this.#sqlOpened.delete(nativeCtx)) {
1901
1980
  return;
1902
1981
  }
1903
- this.#sql.delete(nativeCtx);
1904
- await database.close();
1982
+ await nativeCtx.sql().close();
1905
1983
  }
1906
1984
  async actorRuntimeSocketProvision(ctx) {
1907
1985
  return await asNativeActorContext(ctx).provisionActorRuntimeSocket();
1908
1986
  }
1909
1987
  async actorQueueSend(ctx, name, body) {
1910
1988
  return toNapiQueueMessage(
1911
- await asNativeActorContext(ctx).queue().send(name, toNapiBuffer(body))
1989
+ await this.#actorContextForOperation(ctx).queue().send(name, toNapiBuffer(body))
1912
1990
  );
1913
1991
  }
1914
1992
  async actorQueueNextBatch(ctx, options, signal) {
1915
- const messages = await asNativeActorContext(ctx).queue().nextBatch(
1993
+ const messages = await this.#actorContextForOperation(ctx).queue().nextBatch(
1916
1994
  options,
1917
1995
  signal ? asNativeCancellationToken(signal) : signal
1918
1996
  );
@@ -1920,7 +1998,7 @@ var NapiCoreRuntime = class {
1920
1998
  }
1921
1999
  async actorQueueWaitForNames(ctx, names, options, signal) {
1922
2000
  return toNapiQueueMessage(
1923
- await asNativeActorContext(ctx).queue().waitForNames(
2001
+ await this.#actorContextForOperation(ctx).queue().waitForNames(
1924
2002
  names,
1925
2003
  options,
1926
2004
  signal ? asNativeCancellationToken(signal) : signal
@@ -1942,7 +2020,7 @@ var NapiCoreRuntime = class {
1942
2020
  );
1943
2021
  }
1944
2022
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1945
- return await asNativeActorContext(ctx).queue().enqueueAndWait(
2023
+ return await this.#actorContextForOperation(ctx).queue().enqueueAndWait(
1946
2024
  name,
1947
2025
  toNapiBuffer(body),
1948
2026
  options,
@@ -1962,22 +2040,22 @@ var NapiCoreRuntime = class {
1962
2040
  await asNativeActorContext(ctx).queue().reset();
1963
2041
  }
1964
2042
  async actorScheduleAfter(ctx, durationMs, actionName, args) {
1965
- return await asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
2043
+ return await this.#actorContextForOperation(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1966
2044
  }
1967
2045
  async actorScheduleAt(ctx, timestampMs, actionName, args) {
1968
- return await asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
2046
+ return await this.#actorContextForOperation(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
1969
2047
  }
1970
2048
  async actorScheduleCancel(ctx, id) {
1971
- return await asNativeActorContext(ctx).schedule().cancel(id);
2049
+ return await this.#actorContextForOperation(ctx).schedule().cancel(id);
1972
2050
  }
1973
2051
  async actorScheduleGet(ctx, id) {
1974
- return await asNativeActorContext(ctx).schedule().get(id) ?? void 0;
2052
+ return await this.#actorContextForOperation(ctx).schedule().get(id) ?? void 0;
1975
2053
  }
1976
2054
  async actorScheduleList(ctx) {
1977
- return await asNativeActorContext(ctx).schedule().list();
2055
+ return await this.#actorContextForOperation(ctx).schedule().list();
1978
2056
  }
1979
2057
  async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
1980
- await asNativeActorContext(ctx).schedule().cronSet(
2058
+ await this.#actorContextForOperation(ctx).schedule().cronSet(
1981
2059
  name,
1982
2060
  expression,
1983
2061
  timezone,
@@ -1987,7 +2065,7 @@ var NapiCoreRuntime = class {
1987
2065
  );
1988
2066
  }
1989
2067
  async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
1990
- await asNativeActorContext(ctx).schedule().cronEvery(
2068
+ await this.#actorContextForOperation(ctx).schedule().cronEvery(
1991
2069
  name,
1992
2070
  intervalMs,
1993
2071
  actionName,
@@ -1996,16 +2074,16 @@ var NapiCoreRuntime = class {
1996
2074
  );
1997
2075
  }
1998
2076
  async actorCronGet(ctx, name) {
1999
- return await asNativeActorContext(ctx).schedule().cronGet(name) ?? void 0;
2077
+ return await this.#actorContextForOperation(ctx).schedule().cronGet(name) ?? void 0;
2000
2078
  }
2001
2079
  async actorCronList(ctx) {
2002
- return await asNativeActorContext(ctx).schedule().cronList();
2080
+ return await this.#actorContextForOperation(ctx).schedule().cronList();
2003
2081
  }
2004
2082
  async actorCronDelete(ctx, name) {
2005
- return await asNativeActorContext(ctx).schedule().cronDelete(name);
2083
+ return await this.#actorContextForOperation(ctx).schedule().cronDelete(name);
2006
2084
  }
2007
2085
  async actorCronHistory(ctx, name, limit) {
2008
- return await asNativeActorContext(ctx).schedule().cronHistory(name, limit);
2086
+ return await this.#actorContextForOperation(ctx).schedule().cronHistory(name, limit);
2009
2087
  }
2010
2088
  connId(conn) {
2011
2089
  return asNativeConn(conn).id();
@@ -2039,10 +2117,13 @@ var NapiCoreRuntime = class {
2039
2117
  }
2040
2118
  };
2041
2119
  async function loadNapiRuntime() {
2042
- const bindings = await import(["@rivetkit", "rivetkit-napi"].join("/"));
2120
+ const [{ AsyncLocalStorage }, bindings] = await Promise.all([
2121
+ import("async_hooks"),
2122
+ import(["@rivetkit", "rivetkit-napi"].join("/"))
2123
+ ]);
2043
2124
  return {
2044
2125
  bindings,
2045
- runtime: new NapiCoreRuntime(bindings)
2126
+ runtime: new NapiCoreRuntime(bindings, new AsyncLocalStorage())
2046
2127
  };
2047
2128
  }
2048
2129
 
@@ -2742,6 +2823,29 @@ var WasmCoreRuntime = class {
2742
2823
  actorId(ctx) {
2743
2824
  return callHandle(asWasmActorContext(ctx), "actorId");
2744
2825
  }
2826
+ runWithActorInvocationContext(_ctx, run) {
2827
+ return run();
2828
+ }
2829
+ actorInvocationTraceContext(_ctx) {
2830
+ return void 0;
2831
+ }
2832
+ startCallSpan(_ctx, _actorName, _actionName) {
2833
+ return void 0;
2834
+ }
2835
+ async startWorkflowSpan(_ctx) {
2836
+ return {
2837
+ run: (body) => body(),
2838
+ startStep: () => void 0,
2839
+ finish: async () => {
2840
+ }
2841
+ };
2842
+ }
2843
+ runOutsideActorInvocationContext(run) {
2844
+ return run();
2845
+ }
2846
+ currentInvocationScope() {
2847
+ return void 0;
2848
+ }
2745
2849
  actorName(ctx) {
2746
2850
  return callHandle(asWasmActorContext(ctx), "name");
2747
2851
  }
@@ -5055,6 +5159,7 @@ var NativeConnectionMap = class {
5055
5159
  }
5056
5160
  [Symbol.toStringTag] = "NativeConnectionMap";
5057
5161
  };
5162
+ var NO_INVOCATION_SCOPE = {};
5058
5163
  var ActorContextHandleAdapter = class {
5059
5164
  #runtime;
5060
5165
  #ctx;
@@ -5069,6 +5174,7 @@ var ActorContextHandleAdapter = class {
5069
5174
  #db;
5070
5175
  #dispatchCancelToken;
5071
5176
  #kv;
5177
+ #logByInvocationScope = /* @__PURE__ */ new WeakMap();
5072
5178
  #queue;
5073
5179
  #request;
5074
5180
  #schedule;
@@ -5211,7 +5317,11 @@ var ActorContextHandleAdapter = class {
5211
5317
  await callNative(
5212
5318
  () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
5213
5319
  );
5214
- }
5320
+ },
5321
+ startWorkflowSpan: () => callNative(
5322
+ () => this.#runtime.startWorkflowSpan(this.#ctx)
5323
+ ),
5324
+ runOutsideWorkflowSpan: (body) => this.#runtime.runOutsideActorInvocationContext(body)
5215
5325
  };
5216
5326
  }
5217
5327
  return this.#run;
@@ -5256,8 +5366,29 @@ var ActorContextHandleAdapter = class {
5256
5366
  }
5257
5367
  return this.#connMap;
5258
5368
  }
5369
+ #invocationTraceContext() {
5370
+ return callNativeSync(
5371
+ () => this.#runtime.actorInvocationTraceContext(this.#ctx)
5372
+ );
5373
+ }
5374
+ /** Cached per invocation, because the `run` context outlives workflow runs and steps. */
5259
5375
  get log() {
5260
- return logger2();
5376
+ const scope = this.#runtime.currentInvocationScope() ?? NO_INVOCATION_SCOPE;
5377
+ const cached = this.#logByInvocationScope.get(scope);
5378
+ if (cached) return cached;
5379
+ const invocation = this.#invocationTraceContext();
5380
+ const log = logger2().child({
5381
+ actorId: this.actorId,
5382
+ actorName: this.name,
5383
+ actorKey: this.key,
5384
+ ...(invocation == null ? void 0 : invocation.rayId) && { rayId: invocation.rayId },
5385
+ ...(invocation == null ? void 0 : invocation.span) && {
5386
+ traceId: invocation.span.traceId,
5387
+ spanId: invocation.span.spanId
5388
+ }
5389
+ });
5390
+ this.#logByInvocationScope.set(scope, log);
5391
+ return log;
5261
5392
  }
5262
5393
  get abortSignal() {
5263
5394
  if (!this.#abortSignal) {
@@ -6045,11 +6176,19 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6045
6176
  events: config.events,
6046
6177
  queues: config.queues
6047
6178
  };
6048
- const createClient = () => createClientWithDriver(
6179
+ const createClient = (ctx) => createClientWithDriver(
6049
6180
  new RemoteEngineControlClient(
6050
6181
  convertRegistryConfigToClientConfig(registryConfig)
6051
6182
  ),
6052
- { encoding: "bare" }
6183
+ {
6184
+ encoding: "bare",
6185
+ currentActorInvocation: () => callNativeSync(
6186
+ () => runtime.actorInvocationTraceContext(ctx)
6187
+ ),
6188
+ startCallSpan: (actorName, actionName) => callNativeSync(
6189
+ () => runtime.startCallSpan(ctx, actorName, actionName)
6190
+ )
6191
+ }
6053
6192
  );
6054
6193
  const run = getRunFunction(config.run);
6055
6194
  const runHandlerCoordinator = getRunInspectorKind(config.run) === "workflow" ? new RunHandlerCoordinator(config.run) : void 0;
@@ -6072,7 +6211,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6072
6211
  const makeActorCtx = (ctx, request, cancelToken) => new ActorContextHandleAdapter(
6073
6212
  runtime,
6074
6213
  ctx,
6075
- createClient,
6214
+ () => createClient(ctx),
6076
6215
  schemaConfig,
6077
6216
  databaseProvider,
6078
6217
  request,
@@ -6085,7 +6224,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6085
6224
  runtime,
6086
6225
  ctx,
6087
6226
  conn,
6088
- createClient,
6227
+ () => createClient(ctx),
6089
6228
  schemaConfig,
6090
6229
  databaseProvider,
6091
6230
  request,
@@ -6798,111 +6937,125 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6798
6937
  async (error, payload) => {
6799
6938
  try {
6800
6939
  const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error, payload);
6801
- const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
6802
- if (inspectorResponse) {
6803
- await cancelNativeHttpRequestBody(request.bodyStream);
6804
- return (await convertNativeHttpResponse(
6805
- inspectorResponse,
6806
- responseBodyStream
6807
- )).response;
6808
- }
6809
- if (typeof config.onRequest !== "function") {
6810
- await cancelNativeHttpRequestBody(request.bodyStream);
6811
- return (await convertNativeHttpResponse(
6812
- new Response(null, { status: 404 }),
6813
- responseBodyStream
6814
- )).response;
6815
- }
6816
- const requestAbortController = new AbortController();
6817
- const handlerRequest = buildNativeHttpRequest({
6818
- ...request,
6819
- abortController: requestAbortController
6820
- });
6821
- const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
6822
- let requestCtx;
6823
- let conn;
6824
- let removeRequestAbortListener;
6825
- let cleanupDeferredToBody = false;
6826
- let cleanedUp = false;
6827
- const cleanupRequest = async () => {
6828
- if (cleanedUp) return;
6829
- cleanedUp = true;
6830
- removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
6831
- try {
6832
- await (requestCtx == null ? void 0 : requestCtx.dispose());
6833
- } finally {
6834
- if (conn) {
6835
- await runtime.connDisconnect(conn);
6836
- }
6837
- }
6838
- };
6839
- try {
6840
- const connParams = validateConnParams(
6841
- schemaConfig.connParamsSchema,
6842
- rawConnParams ? JSON.parse(rawConnParams) : void 0
6843
- );
6844
- conn = await callNative(
6845
- () => runtime.actorConnectConn(
6940
+ return await runtime.runWithActorInvocationContext(
6941
+ ctx,
6942
+ async () => {
6943
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(
6846
6944
  ctx,
6847
- encodeValue(connParams),
6848
6945
  request
6849
- )
6850
- );
6851
- requestCtx = makeConnCtx(
6852
- ctx,
6853
- conn,
6854
- handlerRequest,
6855
- cancelToken
6856
- );
6857
- const ctxAbortSignal = requestCtx.abortSignal;
6858
- const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
6859
- if (ctxAbortSignal.aborted) {
6860
- abortRequest();
6861
- } else {
6862
- ctxAbortSignal.addEventListener(
6863
- "abort",
6864
- abortRequest,
6865
- { once: true }
6866
- );
6867
- removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
6868
- "abort",
6869
- abortRequest
6870
- );
6871
- }
6872
- const response = await config.onRequest(
6873
- requestCtx,
6874
- handlerRequest
6875
- );
6876
- if (!isResponseLike(response)) {
6877
- throw new Error(
6878
- "onRequest handler must return a Response"
6879
6946
  );
6880
- }
6881
- const conversion = await convertNativeHttpResponse(
6882
- response,
6883
- responseBodyStream
6884
- );
6885
- if (conversion.bodyCompletion) {
6886
- cleanupDeferredToBody = true;
6887
- void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
6888
- logger2().error({
6889
- msg: "failed to clean up native streaming http request",
6890
- error: cleanupError
6891
- });
6947
+ if (inspectorResponse) {
6948
+ await cancelNativeHttpRequestBody(
6949
+ request.bodyStream
6950
+ );
6951
+ return (await convertNativeHttpResponse(
6952
+ inspectorResponse,
6953
+ responseBodyStream
6954
+ )).response;
6955
+ }
6956
+ if (typeof config.onRequest !== "function") {
6957
+ await cancelNativeHttpRequestBody(
6958
+ request.bodyStream
6959
+ );
6960
+ return (await convertNativeHttpResponse(
6961
+ new Response(null, { status: 404 }),
6962
+ responseBodyStream
6963
+ )).response;
6964
+ }
6965
+ const requestAbortController = new AbortController();
6966
+ const handlerRequest = buildNativeHttpRequest({
6967
+ ...request,
6968
+ abortController: requestAbortController
6892
6969
  });
6893
- }
6894
- return conversion.response;
6895
- } finally {
6896
- try {
6897
- await cancelNativeHttpRequestBody(
6898
- request.bodyStream
6899
- );
6900
- } finally {
6901
- if (!cleanupDeferredToBody) {
6902
- await cleanupRequest();
6970
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
6971
+ let requestCtx;
6972
+ let conn;
6973
+ let removeRequestAbortListener;
6974
+ let cleanupDeferredToBody = false;
6975
+ let cleanedUp = false;
6976
+ const cleanupRequest = async () => {
6977
+ if (cleanedUp) return;
6978
+ cleanedUp = true;
6979
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
6980
+ try {
6981
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
6982
+ } finally {
6983
+ if (conn) {
6984
+ await runtime.connDisconnect(conn);
6985
+ }
6986
+ }
6987
+ };
6988
+ try {
6989
+ const connParams = validateConnParams(
6990
+ schemaConfig.connParamsSchema,
6991
+ rawConnParams ? JSON.parse(rawConnParams) : void 0
6992
+ );
6993
+ conn = await callNative(
6994
+ () => runtime.actorConnectConn(
6995
+ ctx,
6996
+ encodeValue(connParams),
6997
+ request
6998
+ )
6999
+ );
7000
+ requestCtx = makeConnCtx(
7001
+ ctx,
7002
+ conn,
7003
+ handlerRequest,
7004
+ cancelToken
7005
+ );
7006
+ const ctxAbortSignal = requestCtx.abortSignal;
7007
+ const abortRequest = () => requestAbortController.abort(
7008
+ ctxAbortSignal.reason
7009
+ );
7010
+ if (ctxAbortSignal.aborted) {
7011
+ abortRequest();
7012
+ } else {
7013
+ ctxAbortSignal.addEventListener(
7014
+ "abort",
7015
+ abortRequest,
7016
+ { once: true }
7017
+ );
7018
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
7019
+ "abort",
7020
+ abortRequest
7021
+ );
7022
+ }
7023
+ const response = await config.onRequest(
7024
+ requestCtx,
7025
+ handlerRequest
7026
+ );
7027
+ if (!isResponseLike(response)) {
7028
+ throw new Error(
7029
+ "onRequest handler must return a Response"
7030
+ );
7031
+ }
7032
+ const conversion = await convertNativeHttpResponse(
7033
+ response,
7034
+ responseBodyStream
7035
+ );
7036
+ if (conversion.bodyCompletion) {
7037
+ cleanupDeferredToBody = true;
7038
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
7039
+ logger2().error({
7040
+ msg: "failed to clean up native streaming http request",
7041
+ error: cleanupError
7042
+ });
7043
+ });
7044
+ }
7045
+ return conversion.response;
7046
+ } finally {
7047
+ try {
7048
+ await cancelNativeHttpRequestBody(
7049
+ request.bodyStream
7050
+ );
7051
+ } finally {
7052
+ if (!cleanupDeferredToBody) {
7053
+ await cleanupRequest();
7054
+ }
7055
+ }
6903
7056
  }
6904
7057
  }
6905
- }
7058
+ );
6906
7059
  } catch (error2) {
6907
7060
  logger2().error({
6908
7061
  msg: "native onRequest failed",
@@ -6990,21 +7143,27 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6990
7143
  async (error, payload) => {
6991
7144
  const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error, payload);
6992
7145
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
6993
- try {
6994
- return encodeValue(
6995
- await handler(
6996
- actorCtx,
6997
- ...validateActionArgs(
6998
- schemaConfig.actionInputSchemas,
6999
- name,
7000
- decodeArgs(args)
7001
- ),
7002
- ...scheduledFire ? [scheduledFire] : []
7003
- )
7004
- );
7005
- } finally {
7006
- await actorCtx.dispose();
7007
- }
7146
+ const runAction = async () => {
7147
+ try {
7148
+ return encodeValue(
7149
+ await handler(
7150
+ actorCtx,
7151
+ ...validateActionArgs(
7152
+ schemaConfig.actionInputSchemas,
7153
+ name,
7154
+ decodeArgs(args)
7155
+ ),
7156
+ ...scheduledFire ? [scheduledFire] : []
7157
+ )
7158
+ );
7159
+ } finally {
7160
+ await actorCtx.dispose();
7161
+ }
7162
+ };
7163
+ return await runtime.runWithActorInvocationContext(
7164
+ ctx,
7165
+ runAction
7166
+ );
7008
7167
  }
7009
7168
  )
7010
7169
  ])
@@ -7026,7 +7185,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
7026
7185
  runtime,
7027
7186
  ctx,
7028
7187
  conn,
7029
- createClient,
7188
+ () => createClient(ctx),
7030
7189
  schemaConfig,
7031
7190
  databaseProvider,
7032
7191
  jsRequest,
@@ -7035,43 +7194,48 @@ function buildNativeFactory(runtime, registryConfig, definition) {
7035
7194
  cancelToken,
7036
7195
  run !== void 0
7037
7196
  );
7038
- try {
7039
- if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
7040
- return { status: "completed" };
7041
- }
7042
- const canPublish = getQueueCanPublish(
7043
- schemaConfig.queues,
7044
- name
7045
- );
7046
- if (canPublish && !await canPublish(actorCtx)) {
7047
- throw forbiddenError();
7048
- }
7049
- const decodedBody = decodeValue(body);
7050
- if (wait) {
7197
+ return await runtime.runWithActorInvocationContext(
7198
+ ctx,
7199
+ async () => {
7051
7200
  try {
7052
- const response = await actorCtx.queue.enqueueAndWait(
7053
- name,
7054
- decodedBody,
7055
- {
7056
- timeout: timeoutMs === void 0 || timeoutMs === null ? void 0 : Number(timeoutMs)
7057
- }
7201
+ if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
7202
+ return { status: "completed" };
7203
+ }
7204
+ const canPublish = getQueueCanPublish(
7205
+ schemaConfig.queues,
7206
+ name
7058
7207
  );
7059
- return {
7060
- status: "completed",
7061
- response: response === void 0 ? void 0 : encodeValue(response)
7062
- };
7063
- } catch (error2) {
7064
- if (error2.group === "queue" && error2.code === "timed_out") {
7065
- return { status: "timedOut" };
7208
+ if (canPublish && !await canPublish(actorCtx)) {
7209
+ throw forbiddenError();
7066
7210
  }
7067
- throw error2;
7211
+ const decodedBody = decodeValue(body);
7212
+ if (wait) {
7213
+ try {
7214
+ const response = await actorCtx.queue.enqueueAndWait(
7215
+ name,
7216
+ decodedBody,
7217
+ {
7218
+ timeout: timeoutMs === void 0 || timeoutMs === null ? void 0 : Number(timeoutMs)
7219
+ }
7220
+ );
7221
+ return {
7222
+ status: "completed",
7223
+ response: response === void 0 ? void 0 : encodeValue(response)
7224
+ };
7225
+ } catch (error2) {
7226
+ if (error2.group === "queue" && error2.code === "timed_out") {
7227
+ return { status: "timedOut" };
7228
+ }
7229
+ throw error2;
7230
+ }
7231
+ }
7232
+ await actorCtx.queue.send(name, decodedBody);
7233
+ return { status: "completed" };
7234
+ } finally {
7235
+ await actorCtx.dispose();
7068
7236
  }
7069
7237
  }
7070
- await actorCtx.queue.send(name, decodedBody);
7071
- return { status: "completed" };
7072
- } finally {
7073
- await actorCtx.dispose();
7074
- }
7238
+ );
7075
7239
  }
7076
7240
  ),
7077
7241
  serializeState: wrapNativeCallback(
@@ -7721,6 +7885,7 @@ var Registry = class {
7721
7885
  var _a;
7722
7886
  const modeAPromise = this.#runtimeServeConfiguredPromise;
7723
7887
  const modeBPromise = this.#runtimeServerlessPromise;
7888
+ const runtimes = /* @__PURE__ */ new Set();
7724
7889
  const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise) ?? 30 * 60 * 1e3;
7725
7890
  const drain = async () => {
7726
7891
  const registries = [];
@@ -7729,6 +7894,7 @@ var Registry = class {
7729
7894
  (async () => {
7730
7895
  try {
7731
7896
  const { runtime, registry } = await modeAPromise;
7897
+ runtimes.add(runtime);
7732
7898
  await runtime.shutdownRegistry(registry);
7733
7899
  } catch (err) {
7734
7900
  logger2().warn(
@@ -7744,6 +7910,7 @@ var Registry = class {
7744
7910
  (async () => {
7745
7911
  try {
7746
7912
  const { runtime, registry } = await modeBPromise;
7913
+ runtimes.add(runtime);
7747
7914
  await runtime.shutdownRegistry(registry);
7748
7915
  } catch (err) {
7749
7916
  logger2().warn(
@@ -7772,6 +7939,12 @@ var Registry = class {
7772
7939
  }
7773
7940
  )
7774
7941
  ]);
7942
+ await Promise.all(
7943
+ [...runtimes].map((runtime) => {
7944
+ var _a2;
7945
+ return (_a2 = runtime.shutdownTelemetry) == null ? void 0 : _a2.call(runtime);
7946
+ })
7947
+ );
7775
7948
  }
7776
7949
  async #actorStopThresholdMs(configuredRegistryPromise) {
7777
7950
  var _a;