rivetkit 2.3.18 → 2.3.20

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 (140) hide show
  1. package/dist/browser/client.d.ts +754 -608
  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 +36 -1
  12. package/dist/tsup/agent-os/index.cjs.map +1 -1
  13. package/dist/tsup/agent-os/index.d.cts +149 -3
  14. package/dist/tsup/agent-os/index.d.ts +149 -3
  15. package/dist/tsup/agent-os/index.js +36 -1
  16. package/dist/tsup/agent-os/index.js.map +1 -1
  17. package/dist/tsup/{chunk-2IDK6NX3.cjs → chunk-2CE5UNWK.cjs} +13 -13
  18. package/dist/tsup/chunk-2CE5UNWK.cjs.map +1 -0
  19. package/dist/tsup/{chunk-IPXIZSE7.js → chunk-2NXLTFWI.js} +3 -3
  20. package/dist/tsup/{chunk-OKVVWOC3.cjs → chunk-3WS7Z64U.cjs} +3 -3
  21. package/dist/tsup/{chunk-OKVVWOC3.cjs.map → chunk-3WS7Z64U.cjs.map} +1 -1
  22. package/dist/tsup/{chunk-LAITPJRA.js → chunk-553CIQJY.js} +2 -2
  23. package/dist/tsup/{chunk-PXKNBNVU.js → chunk-5G2J26VM.js} +188 -31
  24. package/dist/tsup/chunk-5G2J26VM.js.map +1 -0
  25. package/dist/tsup/{chunk-IKZ6DJMP.cjs → chunk-76YTS32R.cjs} +4 -4
  26. package/dist/tsup/{chunk-IKZ6DJMP.cjs.map → chunk-76YTS32R.cjs.map} +1 -1
  27. package/dist/tsup/{chunk-NRIRV3Z2.cjs → chunk-A36FMKOV.cjs} +352 -195
  28. package/dist/tsup/chunk-A36FMKOV.cjs.map +1 -0
  29. package/dist/tsup/{chunk-6W5VGLFT.js → chunk-CSOHAAZK.js} +33 -1
  30. package/dist/tsup/chunk-CSOHAAZK.js.map +1 -0
  31. package/dist/tsup/{chunk-T6JUXRNI.cjs → chunk-CVLNRT7O.cjs} +3 -3
  32. package/dist/tsup/{chunk-T6JUXRNI.cjs.map → chunk-CVLNRT7O.cjs.map} +1 -1
  33. package/dist/tsup/{chunk-7EPLADKM.js → chunk-DHWZTUKA.js} +7 -7
  34. package/dist/tsup/chunk-DHWZTUKA.js.map +1 -0
  35. package/dist/tsup/{chunk-4XECVATQ.js → chunk-DMQUERRN.js} +2 -2
  36. package/dist/tsup/{chunk-25Z2RK7C.cjs → chunk-IHKDFKM4.cjs} +3 -3
  37. package/dist/tsup/{chunk-25Z2RK7C.cjs.map → chunk-IHKDFKM4.cjs.map} +1 -1
  38. package/dist/tsup/{chunk-2JSYYH6P.cjs → chunk-JX2ITWAV.cjs} +13 -2
  39. package/dist/tsup/chunk-JX2ITWAV.cjs.map +1 -0
  40. package/dist/tsup/{chunk-4KGXFC6M.cjs → chunk-NWCAIWHL.cjs} +34 -2
  41. package/dist/tsup/chunk-NWCAIWHL.cjs.map +1 -0
  42. package/dist/tsup/{chunk-OUQUIBVW.js → chunk-P2OFXH4G.js} +12 -1
  43. package/dist/tsup/chunk-P2OFXH4G.js.map +1 -0
  44. package/dist/tsup/{chunk-ZRTESY7V.cjs → chunk-RSIOGT2U.cjs} +7 -7
  45. package/dist/tsup/{chunk-ZRTESY7V.cjs.map → chunk-RSIOGT2U.cjs.map} +1 -1
  46. package/dist/tsup/{chunk-QIFZELUQ.js → chunk-SNNVRHLX.js} +2 -2
  47. package/dist/tsup/{chunk-2MK75JFR.js → chunk-TZVAVPGJ.js} +4 -4
  48. package/dist/tsup/{chunk-TNSLNSQH.js → chunk-W2PXGWMR.js} +2 -2
  49. package/dist/tsup/{chunk-O7RSU3UC.cjs → chunk-WAISW7KR.cjs} +10 -10
  50. package/dist/tsup/{chunk-O7RSU3UC.cjs.map → chunk-WAISW7KR.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-Ug5M2MOr.d.ts → config-Be-VOHaX.d.ts} +155 -11
  60. package/dist/tsup/{config-gvHwMas-.d.cts → config-Ct5uXxXk.d.cts} +155 -11
  61. package/dist/tsup/{context-DererUCI.d.ts → context-CXLa0BIM.d.ts} +1 -1
  62. package/dist/tsup/{context-BSCBvbfM.d.cts → context-Cw-11Q-B.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 +506 -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 +381 -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/actions.ts +36 -0
  105. package/src/actor/config.ts +65 -0
  106. package/src/actor/definition.ts +6 -1
  107. package/src/actor/errors.ts +31 -0
  108. package/src/actor/mod.ts +5 -0
  109. package/src/actor/tracing.ts +28 -0
  110. package/src/client/actor-conn.ts +7 -0
  111. package/src/client/actor-handle.ts +57 -17
  112. package/src/client/client.ts +26 -6
  113. package/src/client/outbound-telemetry.ts +66 -0
  114. package/src/client/queue.ts +3 -0
  115. package/src/client/raw-utils.ts +3 -0
  116. package/src/common/actor-router-consts.ts +3 -0
  117. package/src/common/actor-telemetry-context.ts +19 -0
  118. package/src/common/otel-context.ts +99 -0
  119. package/src/common/utils.ts +1 -19
  120. package/src/engine-client/actor-http-client.ts +15 -0
  121. package/src/registry/index.ts +6 -0
  122. package/src/registry/napi-runtime.ts +155 -35
  123. package/src/registry/native.ts +295 -191
  124. package/src/registry/runtime.ts +74 -0
  125. package/src/registry/wasm-runtime.ts +40 -0
  126. package/src/workflow/driver.ts +20 -12
  127. package/dist/tsup/chunk-2IDK6NX3.cjs.map +0 -1
  128. package/dist/tsup/chunk-2JSYYH6P.cjs.map +0 -1
  129. package/dist/tsup/chunk-4KGXFC6M.cjs.map +0 -1
  130. package/dist/tsup/chunk-6W5VGLFT.js.map +0 -1
  131. package/dist/tsup/chunk-7EPLADKM.js.map +0 -1
  132. package/dist/tsup/chunk-NRIRV3Z2.cjs.map +0 -1
  133. package/dist/tsup/chunk-OUQUIBVW.js.map +0 -1
  134. package/dist/tsup/chunk-PXKNBNVU.js.map +0 -1
  135. /package/dist/tsup/{chunk-IPXIZSE7.js.map → chunk-2NXLTFWI.js.map} +0 -0
  136. /package/dist/tsup/{chunk-LAITPJRA.js.map → chunk-553CIQJY.js.map} +0 -0
  137. /package/dist/tsup/{chunk-4XECVATQ.js.map → chunk-DMQUERRN.js.map} +0 -0
  138. /package/dist/tsup/{chunk-QIFZELUQ.js.map → chunk-SNNVRHLX.js.map} +0 -0
  139. /package/dist/tsup/{chunk-2MK75JFR.js.map → chunk-TZVAVPGJ.js.map} +0 -0
  140. /package/dist/tsup/{chunk-TNSLNSQH.js.map → chunk-W2PXGWMR.js.map} +0 -0
@@ -2,12 +2,15 @@ import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
2
2
  import {
3
3
  flattenActionHandlers,
4
4
  flattenActionInputSchemas,
5
+ flattenActionTraceSamplers,
5
6
  } from "@/actor/actions";
6
7
  import {
7
8
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
8
9
  type ActorCron,
9
10
  type ActorCronEveryOptions,
10
11
  type ActorCronSetOptions,
12
+ type ActorLogger,
13
+ type ActorRun,
11
14
  type ActorSchedule,
12
15
  CONN_STATE_MANAGER_SYMBOL,
13
16
  type CronFire,
@@ -39,6 +42,7 @@ import {
39
42
  getQueueCanPublish,
40
43
  hasSchemaConfigKey,
41
44
  } from "@/actor/schema";
45
+ import type { ActionSampleRates } from "@/actor/tracing";
42
46
  import {
43
47
  type AnyClient,
44
48
  type Client,
@@ -46,6 +50,7 @@ import {
46
50
  } from "@/client/client";
47
51
  import { convertRegistryConfigToClientConfig } from "@/client/config";
48
52
  import { HEADER_CONN_PARAMS } from "@/common/actor-router-consts";
53
+ import type { ActorInvocationTraceContext } from "@/common/actor-telemetry-context";
49
54
  import type {
50
55
  AnyDatabaseProvider,
51
56
  SqliteProfilingOptions,
@@ -109,6 +114,7 @@ import type {
109
114
  CoreRuntime,
110
115
  RegistryHandle,
111
116
  RuntimeActorConfig,
117
+ RuntimeActorTracingConfig,
112
118
  RuntimeBytes,
113
119
  RuntimeCronFire,
114
120
  RuntimeCronJobInfo,
@@ -2706,6 +2712,9 @@ class NativeConnectionMap implements ReadonlyMap<string, NativeConnAdapter> {
2706
2712
  readonly [Symbol.toStringTag] = "NativeConnectionMap";
2707
2713
  }
2708
2714
 
2715
+ /** Logger cache key for code that runs outside any invocation. */
2716
+ const NO_INVOCATION_SCOPE = {};
2717
+
2709
2718
  export class ActorContextHandleAdapter {
2710
2719
  #runtime: CoreRuntime;
2711
2720
  #ctx: ActorContextHandle;
@@ -2720,10 +2729,11 @@ export class ActorContextHandleAdapter {
2720
2729
  #db?: unknown;
2721
2730
  #dispatchCancelToken?: CancellationTokenHandle;
2722
2731
  #kv?: NativeKvAdapter;
2732
+ #logByInvocationScope = new WeakMap<object, ActorLogger>();
2723
2733
  #queue?: NativeQueueAdapter;
2724
2734
  #request?: Request;
2725
2735
  #schedule?: NativeScheduleAdapter;
2726
- #run?: { setWakeAt(timestamp: number | null): Promise<void> };
2736
+ #run?: ActorRun;
2727
2737
  #runHandlerConfigured: boolean;
2728
2738
  #onStateChange?: NativeOnStateChangeHandler;
2729
2739
  #stateEnabled: boolean;
@@ -2904,6 +2914,12 @@ export class ActorContextHandleAdapter {
2904
2914
  this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp),
2905
2915
  );
2906
2916
  },
2917
+ startWorkflowSpan: () =>
2918
+ callNative(() =>
2919
+ this.#runtime.startWorkflowSpan(this.#ctx),
2920
+ ),
2921
+ runOutsideWorkflowSpan: (body) =>
2922
+ this.#runtime.runOutsideActorInvocationContext(body),
2907
2923
  };
2908
2924
  }
2909
2925
  return this.#run;
@@ -2956,8 +2972,32 @@ export class ActorContextHandleAdapter {
2956
2972
  return this.#connMap;
2957
2973
  }
2958
2974
 
2975
+ #invocationTraceContext(): ActorInvocationTraceContext | undefined {
2976
+ return callNativeSync(() =>
2977
+ this.#runtime.actorInvocationTraceContext(this.#ctx),
2978
+ );
2979
+ }
2980
+
2981
+ /** Cached per invocation, because the `run` context outlives workflow runs and steps. */
2959
2982
  get log() {
2960
- return logger();
2983
+ const scope =
2984
+ this.#runtime.currentInvocationScope() ?? NO_INVOCATION_SCOPE;
2985
+ const cached = this.#logByInvocationScope.get(scope);
2986
+ if (cached) return cached;
2987
+
2988
+ const invocation = this.#invocationTraceContext();
2989
+ const log = logger().child({
2990
+ actorId: this.actorId,
2991
+ actorName: this.name,
2992
+ actorKey: this.key,
2993
+ ...(invocation?.rayId && { rayId: invocation.rayId }),
2994
+ ...(invocation?.span && {
2995
+ traceId: invocation.span.traceId,
2996
+ spanId: invocation.span.spanId,
2997
+ }),
2998
+ });
2999
+ this.#logByInvocationScope.set(scope, log);
3000
+ return log;
2961
3001
  }
2962
3002
 
2963
3003
  get abortSignal(): AbortSignal {
@@ -3817,6 +3857,17 @@ function withConnContext(
3817
3857
  });
3818
3858
  }
3819
3859
 
3860
+ function buildActorTracingConfig(
3861
+ actions: unknown,
3862
+ tracing: { sampler?: number; actions?: ActionSampleRates } | undefined,
3863
+ ): RuntimeActorTracingConfig | undefined {
3864
+ if (tracing === undefined) return undefined;
3865
+ return {
3866
+ sampler: tracing.sampler,
3867
+ actions: flattenActionTraceSamplers(actions, tracing.actions),
3868
+ };
3869
+ }
3870
+
3820
3871
  function buildActorConfig(
3821
3872
  definition: AnyActorDefinition,
3822
3873
  registryConfig: RegistryConfig,
@@ -3837,6 +3888,10 @@ function buildActorConfig(
3837
3888
  hasDatabase: true,
3838
3889
  remoteSqlite: usesRemoteSqlite,
3839
3890
  sqliteProfiling,
3891
+ tracing: buildActorTracingConfig(
3892
+ definition.config.actions,
3893
+ definition.config.tracing,
3894
+ ),
3840
3895
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
3841
3896
  hasState:
3842
3897
  config.state !== undefined ||
@@ -3995,12 +4050,22 @@ export function buildNativeFactory(
3995
4050
  events: config.events,
3996
4051
  queues: config.queues,
3997
4052
  };
3998
- const createClient = () =>
4053
+ const createClient = (ctx: ActorContextHandle) =>
3999
4054
  createClientWithDriver(
4000
4055
  new RemoteEngineControlClient(
4001
4056
  convertRegistryConfigToClientConfig(registryConfig),
4002
4057
  ),
4003
- { encoding: "bare" },
4058
+ {
4059
+ encoding: "bare",
4060
+ currentActorInvocation: () =>
4061
+ callNativeSync(() =>
4062
+ runtime.actorInvocationTraceContext(ctx),
4063
+ ),
4064
+ startCallSpan: (actorName, actionName) =>
4065
+ callNativeSync(() =>
4066
+ runtime.startCallSpan(ctx, actorName, actionName),
4067
+ ),
4068
+ },
4004
4069
  );
4005
4070
  const run = getRunFunction(config.run);
4006
4071
  const runHandlerCoordinator =
@@ -4044,7 +4109,7 @@ export function buildNativeFactory(
4044
4109
  new ActorContextHandleAdapter(
4045
4110
  runtime,
4046
4111
  ctx,
4047
- createClient,
4112
+ () => createClient(ctx),
4048
4113
  schemaConfig,
4049
4114
  databaseProvider,
4050
4115
  request,
@@ -4063,7 +4128,7 @@ export function buildNativeFactory(
4063
4128
  runtime,
4064
4129
  ctx,
4065
4130
  conn,
4066
- createClient,
4131
+ () => createClient(ctx),
4067
4132
  schemaConfig,
4068
4133
  databaseProvider,
4069
4134
  request,
@@ -5041,129 +5106,147 @@ export function buildNativeFactory(
5041
5106
  try {
5042
5107
  const { ctx, request, cancelToken, responseBodyStream } =
5043
5108
  unwrapTsfnPayload(error, payload);
5044
- const inspectorResponse =
5045
- await maybeHandleNativeInspectorRequest(ctx, request);
5046
- if (inspectorResponse) {
5047
- await cancelNativeHttpRequestBody(request.bodyStream);
5048
- return (
5049
- await convertNativeHttpResponse(
5050
- inspectorResponse,
5051
- responseBodyStream,
5052
- )
5053
- ).response;
5054
- }
5055
-
5056
- if (typeof config.onRequest !== "function") {
5057
- await cancelNativeHttpRequestBody(request.bodyStream);
5058
- return (
5059
- await convertNativeHttpResponse(
5060
- new Response(null, { status: 404 }),
5061
- responseBodyStream,
5062
- )
5063
- ).response;
5064
- }
5109
+ return await runtime.runWithActorInvocationContext(
5110
+ ctx,
5111
+ async () => {
5112
+ const inspectorResponse =
5113
+ await maybeHandleNativeInspectorRequest(
5114
+ ctx,
5115
+ request,
5116
+ );
5117
+ if (inspectorResponse) {
5118
+ await cancelNativeHttpRequestBody(
5119
+ request.bodyStream,
5120
+ );
5121
+ return (
5122
+ await convertNativeHttpResponse(
5123
+ inspectorResponse,
5124
+ responseBodyStream,
5125
+ )
5126
+ ).response;
5127
+ }
5065
5128
 
5066
- const requestAbortController = new AbortController();
5067
- const handlerRequest = buildNativeHttpRequest({
5068
- ...request,
5069
- abortController: requestAbortController,
5070
- });
5071
- const rawConnParams =
5072
- handlerRequest.headers.get(HEADER_CONN_PARAMS);
5073
- let requestCtx:
5074
- | ReturnType<typeof withConnContext>
5075
- | undefined;
5076
- let conn: ConnHandle | undefined;
5077
- let removeRequestAbortListener: (() => void) | undefined;
5078
- let cleanupDeferredToBody = false;
5079
- let cleanedUp = false;
5080
- const cleanupRequest = async () => {
5081
- if (cleanedUp) return;
5082
- cleanedUp = true;
5083
- removeRequestAbortListener?.();
5084
- try {
5085
- await requestCtx?.dispose();
5086
- } finally {
5087
- if (conn) {
5088
- await runtime.connDisconnect(conn);
5129
+ if (typeof config.onRequest !== "function") {
5130
+ await cancelNativeHttpRequestBody(
5131
+ request.bodyStream,
5132
+ );
5133
+ return (
5134
+ await convertNativeHttpResponse(
5135
+ new Response(null, { status: 404 }),
5136
+ responseBodyStream,
5137
+ )
5138
+ ).response;
5089
5139
  }
5090
- }
5091
- };
5092
- try {
5093
- const connParams = validateConnParams(
5094
- schemaConfig.connParamsSchema,
5095
- rawConnParams
5096
- ? JSON.parse(rawConnParams)
5097
- : undefined,
5098
- );
5099
- conn = await callNative(() =>
5100
- runtime.actorConnectConn(
5101
- ctx,
5102
- encodeValue(connParams),
5103
- request,
5104
- ),
5105
- );
5106
- requestCtx = makeConnCtx(
5107
- ctx,
5108
- conn,
5109
- handlerRequest,
5110
- cancelToken,
5111
- );
5112
- const ctxAbortSignal = requestCtx.abortSignal;
5113
- const abortRequest = () =>
5114
- requestAbortController.abort(ctxAbortSignal.reason);
5115
- if (ctxAbortSignal.aborted) {
5116
- abortRequest();
5117
- } else {
5118
- ctxAbortSignal.addEventListener(
5119
- "abort",
5120
- abortRequest,
5121
- { once: true },
5122
- );
5123
- removeRequestAbortListener = () =>
5124
- ctxAbortSignal.removeEventListener(
5125
- "abort",
5126
- abortRequest,
5140
+
5141
+ const requestAbortController =
5142
+ new AbortController();
5143
+ const handlerRequest = buildNativeHttpRequest({
5144
+ ...request,
5145
+ abortController: requestAbortController,
5146
+ });
5147
+ const rawConnParams =
5148
+ handlerRequest.headers.get(HEADER_CONN_PARAMS);
5149
+ let requestCtx:
5150
+ | ReturnType<typeof withConnContext>
5151
+ | undefined;
5152
+ let conn: ConnHandle | undefined;
5153
+ let removeRequestAbortListener:
5154
+ | (() => void)
5155
+ | undefined;
5156
+ let cleanupDeferredToBody = false;
5157
+ let cleanedUp = false;
5158
+ const cleanupRequest = async () => {
5159
+ if (cleanedUp) return;
5160
+ cleanedUp = true;
5161
+ removeRequestAbortListener?.();
5162
+ try {
5163
+ await requestCtx?.dispose();
5164
+ } finally {
5165
+ if (conn) {
5166
+ await runtime.connDisconnect(conn);
5167
+ }
5168
+ }
5169
+ };
5170
+ try {
5171
+ const connParams = validateConnParams(
5172
+ schemaConfig.connParamsSchema,
5173
+ rawConnParams
5174
+ ? JSON.parse(rawConnParams)
5175
+ : undefined,
5127
5176
  );
5128
- }
5129
- const response = await config.onRequest(
5130
- requestCtx,
5131
- handlerRequest,
5132
- );
5133
- if (!isResponseLike(response)) {
5134
- throw new Error(
5135
- "onRequest handler must return a Response",
5136
- );
5137
- }
5138
- const conversion = await convertNativeHttpResponse(
5139
- response,
5140
- responseBodyStream,
5141
- );
5142
- if (conversion.bodyCompletion) {
5143
- cleanupDeferredToBody = true;
5144
- void conversion.bodyCompletion
5145
- .then(cleanupRequest)
5146
- .catch((cleanupError) => {
5147
- logger().error({
5148
- msg: "failed to clean up native streaming http request",
5149
- error: cleanupError,
5150
- });
5151
- });
5152
- }
5153
- return conversion.response;
5154
- } finally {
5155
- try {
5156
- // Handler completion ends upload ownership even when
5157
- // the Web Request body is locked or partly consumed.
5158
- await cancelNativeHttpRequestBody(
5159
- request.bodyStream,
5160
- );
5161
- } finally {
5162
- if (!cleanupDeferredToBody) {
5163
- await cleanupRequest();
5177
+ conn = await callNative(() =>
5178
+ runtime.actorConnectConn(
5179
+ ctx,
5180
+ encodeValue(connParams),
5181
+ request,
5182
+ ),
5183
+ );
5184
+ requestCtx = makeConnCtx(
5185
+ ctx,
5186
+ conn,
5187
+ handlerRequest,
5188
+ cancelToken,
5189
+ );
5190
+ const ctxAbortSignal = requestCtx.abortSignal;
5191
+ const abortRequest = () =>
5192
+ requestAbortController.abort(
5193
+ ctxAbortSignal.reason,
5194
+ );
5195
+ if (ctxAbortSignal.aborted) {
5196
+ abortRequest();
5197
+ } else {
5198
+ ctxAbortSignal.addEventListener(
5199
+ "abort",
5200
+ abortRequest,
5201
+ { once: true },
5202
+ );
5203
+ removeRequestAbortListener = () =>
5204
+ ctxAbortSignal.removeEventListener(
5205
+ "abort",
5206
+ abortRequest,
5207
+ );
5208
+ }
5209
+ const response = await config.onRequest(
5210
+ requestCtx,
5211
+ handlerRequest,
5212
+ );
5213
+ if (!isResponseLike(response)) {
5214
+ throw new Error(
5215
+ "onRequest handler must return a Response",
5216
+ );
5217
+ }
5218
+ const conversion =
5219
+ await convertNativeHttpResponse(
5220
+ response,
5221
+ responseBodyStream,
5222
+ );
5223
+ if (conversion.bodyCompletion) {
5224
+ cleanupDeferredToBody = true;
5225
+ void conversion.bodyCompletion
5226
+ .then(cleanupRequest)
5227
+ .catch((cleanupError) => {
5228
+ logger().error({
5229
+ msg: "failed to clean up native streaming http request",
5230
+ error: cleanupError,
5231
+ });
5232
+ });
5233
+ }
5234
+ return conversion.response;
5235
+ } finally {
5236
+ try {
5237
+ // Handler completion ends upload ownership even when
5238
+ // the Web Request body is locked or partly consumed.
5239
+ await cancelNativeHttpRequestBody(
5240
+ request.bodyStream,
5241
+ );
5242
+ } finally {
5243
+ if (!cleanupDeferredToBody) {
5244
+ await cleanupRequest();
5245
+ }
5246
+ }
5164
5247
  }
5165
- }
5166
- }
5248
+ },
5249
+ );
5167
5250
  } catch (error) {
5168
5251
  logger().error({
5169
5252
  msg: "native onRequest failed",
@@ -5312,21 +5395,29 @@ export function buildNativeFactory(
5312
5395
  conn != null
5313
5396
  ? makeConnCtx(ctx, conn, undefined, cancelToken)
5314
5397
  : makeActorCtx(ctx, undefined, cancelToken);
5315
- try {
5316
- return encodeValue(
5317
- await handler(
5318
- actorCtx,
5319
- ...validateActionArgs(
5320
- schemaConfig.actionInputSchemas,
5321
- name,
5322
- decodeArgs(args),
5398
+ const runAction = async () => {
5399
+ try {
5400
+ return encodeValue(
5401
+ await handler(
5402
+ actorCtx,
5403
+ ...validateActionArgs(
5404
+ schemaConfig.actionInputSchemas,
5405
+ name,
5406
+ decodeArgs(args),
5407
+ ),
5408
+ ...(scheduledFire
5409
+ ? [scheduledFire]
5410
+ : []),
5323
5411
  ),
5324
- ...(scheduledFire ? [scheduledFire] : []),
5325
- ),
5326
- );
5327
- } finally {
5328
- await actorCtx.dispose();
5329
- }
5412
+ );
5413
+ } finally {
5414
+ await actorCtx.dispose();
5415
+ }
5416
+ };
5417
+ return await runtime.runWithActorInvocationContext(
5418
+ ctx,
5419
+ runAction,
5420
+ );
5330
5421
  },
5331
5422
  ),
5332
5423
  ]),
@@ -5365,7 +5456,7 @@ export function buildNativeFactory(
5365
5456
  runtime,
5366
5457
  ctx,
5367
5458
  conn,
5368
- createClient,
5459
+ () => createClient(ctx),
5369
5460
  schemaConfig,
5370
5461
  databaseProvider,
5371
5462
  jsRequest,
@@ -5374,62 +5465,75 @@ export function buildNativeFactory(
5374
5465
  cancelToken,
5375
5466
  run !== undefined,
5376
5467
  );
5377
- try {
5378
- if (
5379
- !schemaConfig.queues ||
5380
- !hasSchemaConfigKey(schemaConfig.queues, name)
5381
- ) {
5382
- return { status: "completed" };
5383
- }
5384
-
5385
- const canPublish = getQueueCanPublish(
5386
- schemaConfig.queues,
5387
- name,
5388
- );
5389
- if (canPublish && !(await canPublish(actorCtx))) {
5390
- throw forbiddenError();
5391
- }
5392
-
5393
- const decodedBody = decodeValue(body);
5394
- if (wait) {
5468
+ return await runtime.runWithActorInvocationContext(
5469
+ ctx,
5470
+ async () => {
5395
5471
  try {
5396
- const response =
5397
- await actorCtx.queue.enqueueAndWait(
5398
- name,
5399
- decodedBody,
5400
- {
5401
- timeout:
5402
- timeoutMs === undefined ||
5403
- timeoutMs === null
5404
- ? undefined
5405
- : Number(timeoutMs),
5406
- },
5407
- );
5408
- return {
5409
- status: "completed",
5410
- response:
5411
- response === undefined
5412
- ? undefined
5413
- : encodeValue(response),
5414
- };
5415
- } catch (error) {
5416
5472
  if (
5417
- (error as { group?: string; code?: string })
5418
- .group === "queue" &&
5419
- (error as { group?: string; code?: string })
5420
- .code === "timed_out"
5473
+ !schemaConfig.queues ||
5474
+ !hasSchemaConfigKey(schemaConfig.queues, name)
5421
5475
  ) {
5422
- return { status: "timedOut" };
5476
+ return { status: "completed" };
5423
5477
  }
5424
- throw error;
5425
- }
5426
- }
5427
5478
 
5428
- await actorCtx.queue.send(name, decodedBody);
5429
- return { status: "completed" };
5430
- } finally {
5431
- await actorCtx.dispose();
5432
- }
5479
+ const canPublish = getQueueCanPublish(
5480
+ schemaConfig.queues,
5481
+ name,
5482
+ );
5483
+ if (canPublish && !(await canPublish(actorCtx))) {
5484
+ throw forbiddenError();
5485
+ }
5486
+
5487
+ const decodedBody = decodeValue(body);
5488
+ if (wait) {
5489
+ try {
5490
+ const response =
5491
+ await actorCtx.queue.enqueueAndWait(
5492
+ name,
5493
+ decodedBody,
5494
+ {
5495
+ timeout:
5496
+ timeoutMs === undefined ||
5497
+ timeoutMs === null
5498
+ ? undefined
5499
+ : Number(timeoutMs),
5500
+ },
5501
+ );
5502
+ return {
5503
+ status: "completed",
5504
+ response:
5505
+ response === undefined
5506
+ ? undefined
5507
+ : encodeValue(response),
5508
+ };
5509
+ } catch (error) {
5510
+ if (
5511
+ (
5512
+ error as {
5513
+ group?: string;
5514
+ code?: string;
5515
+ }
5516
+ ).group === "queue" &&
5517
+ (
5518
+ error as {
5519
+ group?: string;
5520
+ code?: string;
5521
+ }
5522
+ ).code === "timed_out"
5523
+ ) {
5524
+ return { status: "timedOut" };
5525
+ }
5526
+ throw error;
5527
+ }
5528
+ }
5529
+
5530
+ await actorCtx.queue.send(name, decodedBody);
5531
+ return { status: "completed" };
5532
+ } finally {
5533
+ await actorCtx.dispose();
5534
+ }
5535
+ },
5536
+ );
5433
5537
  },
5434
5538
  ),
5435
5539
  serializeState: wrapNativeCallback(