rivetkit 0.0.0-main.41efcce → 0.0.0-main.49693dc

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 (299) hide show
  1. package/dist/browser/client.d.ts +939 -104
  2. package/dist/browser/client.js +1867 -900
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2079 -233
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +6 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -74
  10. package/dist/tsup/actor/errors.d.ts +1 -74
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +2408 -2029
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +932 -114
  15. package/dist/tsup/agent-os/index.d.ts +932 -114
  16. package/dist/tsup/agent-os/index.js +2412 -2033
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-J27CEW6F.js → chunk-2OBVQZX6.js} +6 -6
  19. package/dist/tsup/chunk-2OBVQZX6.js.map +1 -0
  20. package/dist/tsup/chunk-3ZWHWMFJ.js +14 -0
  21. package/dist/tsup/chunk-3ZWHWMFJ.js.map +1 -0
  22. package/dist/tsup/{chunk-AK57AL7S.cjs → chunk-4KGXFC6M.cjs} +238 -22
  23. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  24. package/dist/tsup/{chunk-CVHUXINE.js → chunk-5IU3MI7X.js} +594 -72
  25. package/dist/tsup/chunk-5IU3MI7X.js.map +1 -0
  26. package/dist/tsup/{chunk-VD7AZIBR.js → chunk-6CXQMHZR.js} +1161 -361
  27. package/dist/tsup/chunk-6CXQMHZR.js.map +1 -0
  28. package/dist/tsup/{chunk-SBEFJ4IQ.js → chunk-6W2UIH3X.js} +70 -8
  29. package/dist/tsup/chunk-6W2UIH3X.js.map +1 -0
  30. package/dist/tsup/{chunk-7MRGNVSR.js → chunk-6W5VGLFT.js} +237 -21
  31. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  32. package/dist/tsup/{chunk-RF3MEJV6.cjs → chunk-B73TBMMG.cjs} +18 -11
  33. package/dist/tsup/chunk-B73TBMMG.cjs.map +1 -0
  34. package/dist/tsup/chunk-D6TORRA4.js +243 -0
  35. package/dist/tsup/chunk-D6TORRA4.js.map +1 -0
  36. package/dist/tsup/{chunk-PXLJOMJD.js → chunk-FXT3HN32.js} +2 -2
  37. package/dist/tsup/{chunk-ZGWSH7YV.js → chunk-IXBD7BXC.js} +48 -72
  38. package/dist/tsup/chunk-IXBD7BXC.js.map +1 -0
  39. package/dist/tsup/{chunk-3BFYSYRU.js → chunk-JI6GZ2C2.js} +4 -12
  40. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  41. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  42. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  43. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  44. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  45. package/dist/tsup/{chunk-SPMMF6TR.cjs → chunk-LGOWPZJ5.cjs} +3 -3
  46. package/dist/tsup/chunk-LGOWPZJ5.cjs.map +1 -0
  47. package/dist/tsup/chunk-LYNWTX6R.cjs +14 -0
  48. package/dist/tsup/chunk-LYNWTX6R.cjs.map +1 -0
  49. package/dist/tsup/{chunk-LLD2D5LO.cjs → chunk-MYWZCDML.cjs} +4 -12
  50. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  51. package/dist/tsup/{chunk-XSC2WWXD.js → chunk-NYDZLWHZ.js} +16 -9
  52. package/dist/tsup/chunk-NYDZLWHZ.js.map +1 -0
  53. package/dist/tsup/{chunk-AV54CVAG.cjs → chunk-RB7WUDX6.cjs} +1290 -490
  54. package/dist/tsup/chunk-RB7WUDX6.cjs.map +1 -0
  55. package/dist/tsup/{chunk-JTL6Y2UN.cjs → chunk-SPJORZMM.cjs} +49 -73
  56. package/dist/tsup/chunk-SPJORZMM.cjs.map +1 -0
  57. package/dist/tsup/chunk-SSMKIYEX.cjs +243 -0
  58. package/dist/tsup/chunk-SSMKIYEX.cjs.map +1 -0
  59. package/dist/tsup/{chunk-TQSL4NJ3.cjs → chunk-TQ4HSX2U.cjs} +72 -10
  60. package/dist/tsup/chunk-TQ4HSX2U.cjs.map +1 -0
  61. package/dist/tsup/{chunk-EVADNK6Z.cjs → chunk-U6ZQELGJ.cjs} +10 -10
  62. package/dist/tsup/chunk-U6ZQELGJ.cjs.map +1 -0
  63. package/dist/tsup/chunk-XLBMKZD3.cjs +1257 -0
  64. package/dist/tsup/chunk-XLBMKZD3.cjs.map +1 -0
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +18 -7
  68. package/dist/tsup/client/mod.d.ts +18 -7
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-B3RIidaJ.d.ts → config-BXSV17G7.d.cts} +987 -72
  79. package/dist/tsup/{config-D6WxBYjV.d.cts → config-Bi1r6gI7.d.ts} +987 -72
  80. package/dist/tsup/{config-B9qUIHX4.d.ts → config-ey2I2zz5.d.cts} +82 -15
  81. package/dist/tsup/{config-B9qUIHX4.d.cts → config-ey2I2zz5.d.ts} +82 -15
  82. package/dist/tsup/context-4fJemY0D.d.cts +129 -0
  83. package/dist/tsup/context-D4sNYboo.d.ts +129 -0
  84. package/dist/tsup/db/drizzle.cjs +168 -103
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +170 -105
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -163
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +12 -4
  93. package/dist/tsup/db/mod.d.ts +12 -4
  94. package/dist/tsup/db/mod.js +5 -162
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +24 -0
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  98. package/dist/tsup/dynamic/mod.d.cts +38 -0
  99. package/dist/tsup/dynamic/mod.d.ts +38 -0
  100. package/dist/tsup/dynamic/mod.js +24 -0
  101. package/dist/tsup/dynamic/mod.js.map +1 -0
  102. package/dist/tsup/inspector/mod.cjs +47 -12
  103. package/dist/tsup/inspector/mod.cjs.map +1 -1
  104. package/dist/tsup/inspector/mod.d.cts +26 -136
  105. package/dist/tsup/inspector/mod.d.ts +26 -136
  106. package/dist/tsup/inspector/mod.js +46 -11
  107. package/dist/tsup/inspector/mod.js.map +1 -1
  108. package/dist/tsup/inspector/workflow.cjs +21 -0
  109. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  110. package/dist/tsup/inspector/workflow.d.cts +144 -0
  111. package/dist/tsup/inspector/workflow.d.ts +144 -0
  112. package/dist/tsup/inspector/workflow.js +21 -0
  113. package/dist/tsup/inspector/workflow.js.map +1 -0
  114. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  115. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  116. package/dist/tsup/inspector-tab/mod.d.cts +241 -0
  117. package/dist/tsup/inspector-tab/mod.d.ts +241 -0
  118. package/dist/tsup/inspector-tab/mod.js +162 -0
  119. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  120. package/dist/tsup/mod.cjs +4268 -944
  121. package/dist/tsup/mod.cjs.map +1 -1
  122. package/dist/tsup/mod.d.cts +9 -8
  123. package/dist/tsup/mod.d.ts +9 -8
  124. package/dist/tsup/mod.js +4229 -905
  125. package/dist/tsup/mod.js.map +1 -1
  126. package/dist/tsup/test/mod.cjs +26 -21
  127. package/dist/tsup/test/mod.cjs.map +1 -1
  128. package/dist/tsup/test/mod.d.cts +7 -6
  129. package/dist/tsup/test/mod.d.ts +7 -6
  130. package/dist/tsup/test/mod.js +25 -20
  131. package/dist/tsup/test/mod.js.map +1 -1
  132. package/dist/tsup/unstable/migrations.cjs +101 -0
  133. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  134. package/dist/tsup/unstable/migrations.d.cts +29 -0
  135. package/dist/tsup/unstable/migrations.d.ts +29 -0
  136. package/dist/tsup/unstable/migrations.js +101 -0
  137. package/dist/tsup/unstable/migrations.js.map +1 -0
  138. package/dist/tsup/utils-Bbz-3411.d.cts +162 -0
  139. package/dist/tsup/utils-BqdWVlzm.d.ts +162 -0
  140. package/dist/tsup/utils-vvJQyygr.d.cts +109 -0
  141. package/dist/tsup/utils-vvJQyygr.d.ts +109 -0
  142. package/dist/tsup/utils.cjs +7 -3
  143. package/dist/tsup/utils.cjs.map +1 -1
  144. package/dist/tsup/utils.d.cts +4 -147
  145. package/dist/tsup/utils.d.ts +4 -147
  146. package/dist/tsup/utils.js +6 -2
  147. package/dist/tsup/workflow/mod.cjs +517 -412
  148. package/dist/tsup/workflow/mod.cjs.map +1 -1
  149. package/dist/tsup/workflow/mod.d.cts +11 -10
  150. package/dist/tsup/workflow/mod.d.ts +11 -10
  151. package/dist/tsup/workflow/mod.js +511 -406
  152. package/dist/tsup/workflow/mod.js.map +1 -1
  153. package/package.json +62 -14
  154. package/src/actor/actions.ts +119 -0
  155. package/src/actor/config.test.ts +78 -0
  156. package/src/actor/config.ts +518 -96
  157. package/src/actor/contexts/index.ts +7 -2
  158. package/src/actor/definition.ts +38 -26
  159. package/src/actor/errors.ts +101 -89
  160. package/src/actor/keys.ts +2 -1
  161. package/src/actor/mod.ts +32 -21
  162. package/src/actor/schema.ts +2 -2
  163. package/src/agent-os/actor/cron.ts +37 -2
  164. package/src/agent-os/actor/index.ts +39 -19
  165. package/src/agent-os/actor/preview.ts +1 -2
  166. package/src/agent-os/actor/session.ts +2 -2
  167. package/src/agent-os/config.ts +1 -1
  168. package/src/agent-os/fs/database-vfs.ts +1 -1
  169. package/src/agent-os/index.ts +16 -15
  170. package/src/agent-os/types.ts +11 -0
  171. package/src/client/actor-common.ts +106 -53
  172. package/src/client/actor-conn.ts +94 -45
  173. package/src/client/actor-handle.ts +198 -79
  174. package/src/client/actor-query.ts +13 -6
  175. package/src/client/client.ts +43 -15
  176. package/src/client/config.ts +8 -0
  177. package/src/client/errors.ts +4 -2
  178. package/src/client/lifecycle-errors.ts +28 -4
  179. package/src/client/mod.ts +9 -4
  180. package/src/client/query.ts +3 -1
  181. package/src/client/queue.ts +8 -3
  182. package/src/client/raw-utils.ts +24 -16
  183. package/src/client/resolve-gateway-target.ts +3 -1
  184. package/src/client/utils.ts +36 -10
  185. package/src/common/actor-router-consts.ts +7 -0
  186. package/src/common/actor-websocket.ts +3 -1
  187. package/src/common/bare/actor-persist/v1.ts +205 -163
  188. package/src/common/bare/actor-persist/v2.ts +265 -213
  189. package/src/common/bare/actor-persist/v3.ts +176 -172
  190. package/src/common/bare/actor-persist/v4.ts +254 -253
  191. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  192. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  193. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  194. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  195. package/src/common/bare/transport/v1.ts +694 -542
  196. package/src/common/client-protocol-versioned.ts +176 -67
  197. package/src/common/client-protocol-zod.ts +7 -0
  198. package/src/common/client-protocol.ts +1 -1
  199. package/src/common/database/config.ts +103 -10
  200. package/src/common/database/mod.test.ts +364 -0
  201. package/src/common/database/mod.ts +278 -149
  202. package/src/common/database/native-database.test.ts +220 -0
  203. package/src/common/database/native-database.ts +394 -58
  204. package/src/common/database/shared.ts +25 -0
  205. package/src/common/encoding.ts +302 -38
  206. package/src/common/engine.ts +28 -1
  207. package/src/common/eventsource.ts +1 -1
  208. package/src/common/fetch-like.ts +49 -0
  209. package/src/common/inline-websocket-adapter.ts +14 -13
  210. package/src/common/inspector-transport.ts +12 -2
  211. package/src/common/log.ts +117 -14
  212. package/src/common/router.ts +49 -23
  213. package/src/common/utils.ts +23 -203
  214. package/src/common/websocket-interface.ts +1 -1
  215. package/src/db/drizzle.test.ts +164 -0
  216. package/src/db/drizzle.ts +207 -121
  217. package/src/db/mod.ts +6 -1
  218. package/src/devtools-loader/index.ts +4 -7
  219. package/src/devtools-loader/serve-devtools.ts +26 -0
  220. package/src/dynamic/instance.ts +32 -0
  221. package/src/dynamic/internal.ts +50 -0
  222. package/src/dynamic/isolate-runtime.ts +64 -0
  223. package/src/dynamic/mod.ts +32 -0
  224. package/src/engine-client/actor-http-client.ts +23 -4
  225. package/src/engine-client/actor-websocket-client.ts +32 -5
  226. package/src/engine-client/api-endpoints.ts +52 -2
  227. package/src/engine-client/api-utils.ts +2 -2
  228. package/src/engine-client/driver.ts +21 -17
  229. package/src/engine-client/mod.ts +116 -64
  230. package/src/engine-client/ws-proxy.ts +9 -4
  231. package/src/globals.d.ts +4 -0
  232. package/src/inspector/client.browser.ts +127 -15
  233. package/src/inspector/mod.ts +2 -4
  234. package/src/inspector/workflow.ts +61 -0
  235. package/src/inspector-tab/mod.ts +301 -0
  236. package/src/registry/config/envoy.ts +1 -2
  237. package/src/registry/config/index.ts +160 -53
  238. package/src/registry/config/serverless.ts +7 -1
  239. package/src/registry/index.ts +659 -96
  240. package/src/registry/napi-runtime.ts +1154 -0
  241. package/src/registry/native-validation.ts +10 -12
  242. package/src/registry/native.ts +2005 -955
  243. package/src/registry/process-metrics.ts +250 -0
  244. package/src/registry/run-handler-coordinator.test.ts +252 -0
  245. package/src/registry/run-handler-coordinator.ts +219 -0
  246. package/src/registry/runtime.test.ts +50 -0
  247. package/src/registry/runtime.ts +839 -0
  248. package/src/registry/wasm-runtime.ts +1283 -0
  249. package/src/registry/write-through-proxy.ts +141 -0
  250. package/src/serde.ts +8 -2
  251. package/src/serverless/configure.ts +102 -49
  252. package/src/test/mod.ts +2 -17
  253. package/src/test/ready.ts +22 -0
  254. package/src/unstable/migrations.test.ts +170 -0
  255. package/src/unstable/migrations.ts +141 -0
  256. package/src/utils/crypto.ts +14 -0
  257. package/src/utils/endpoint-parser.ts +1 -1
  258. package/src/utils/env-vars.ts +39 -0
  259. package/src/utils/node.ts +44 -28
  260. package/src/utils/router.ts +1 -1
  261. package/src/utils.ts +4 -2
  262. package/src/workflow/context.ts +683 -242
  263. package/src/workflow/driver.test.ts +62 -0
  264. package/src/workflow/driver.ts +246 -119
  265. package/src/workflow/inspector.ts +24 -24
  266. package/src/workflow/mod.ts +76 -84
  267. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  268. package/dist/tsup/chunk-3BFYSYRU.js.map +0 -1
  269. package/dist/tsup/chunk-6AVUJ52Q.cjs +0 -253
  270. package/dist/tsup/chunk-6AVUJ52Q.cjs.map +0 -1
  271. package/dist/tsup/chunk-7MRGNVSR.js.map +0 -1
  272. package/dist/tsup/chunk-7X7RVTFF.cjs +0 -735
  273. package/dist/tsup/chunk-7X7RVTFF.cjs.map +0 -1
  274. package/dist/tsup/chunk-AK57AL7S.cjs.map +0 -1
  275. package/dist/tsup/chunk-AV54CVAG.cjs.map +0 -1
  276. package/dist/tsup/chunk-CVHUXINE.js.map +0 -1
  277. package/dist/tsup/chunk-EVADNK6Z.cjs.map +0 -1
  278. package/dist/tsup/chunk-J27CEW6F.js.map +0 -1
  279. package/dist/tsup/chunk-JTL6Y2UN.cjs.map +0 -1
  280. package/dist/tsup/chunk-LLD2D5LO.cjs.map +0 -1
  281. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  282. package/dist/tsup/chunk-RF3MEJV6.cjs.map +0 -1
  283. package/dist/tsup/chunk-SB4MXRN2.js +0 -253
  284. package/dist/tsup/chunk-SB4MXRN2.js.map +0 -1
  285. package/dist/tsup/chunk-SBEFJ4IQ.js.map +0 -1
  286. package/dist/tsup/chunk-SPMMF6TR.cjs.map +0 -1
  287. package/dist/tsup/chunk-TQSL4NJ3.cjs.map +0 -1
  288. package/dist/tsup/chunk-VD7AZIBR.js.map +0 -1
  289. package/dist/tsup/chunk-XSC2WWXD.js.map +0 -1
  290. package/dist/tsup/chunk-ZGWSH7YV.js.map +0 -1
  291. package/dist/tsup/context-BxvHh9wi.d.cts +0 -92
  292. package/dist/tsup/context-CNIZBIKl.d.ts +0 -92
  293. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  294. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  295. package/src/actor/driver.ts +0 -141
  296. package/src/actor/instance/mod.ts +0 -2501
  297. package/src/drivers/engine/actor-driver.ts +0 -2470
  298. package/src/utils/serve.ts +0 -217
  299. /package/dist/tsup/{chunk-PXLJOMJD.js.map → chunk-FXT3HN32.js.map} +0 -0
@@ -1,2501 +0,0 @@
1
- // TODO(sleep-cleanup): investigate whether ActorInstance / drivers/engine
2
- // path is still needed after native path maturation. preventSleep tracking
3
- // below is retained for legacy driver compatibility but no longer drives core.
4
- import type { OtlpExportTraceServiceRequestJson } from "@rivetkit/traces";
5
- import {
6
- createNoopTraces,
7
- createTraces,
8
- type SpanHandle,
9
- type SpanStatusInput,
10
- type Traces,
11
- } from "@rivetkit/traces";
12
- import { ActorMetrics, type StartupTimingKey } from "@/actor/metrics";
13
- import invariant from "invariant";
14
- import type { Client } from "@/client/client";
15
- import { getBaseLogger, getIncludeTarget, type Logger } from "@/common/log";
16
- import { stringifyError } from "@/common/utils";
17
- import type { UniversalWebSocket } from "@/common/websocket-interface";
18
- import { ActorInspector } from "@/inspector/actor-inspector";
19
- import type { ActorKey } from "@/client/query";
20
- import type { Registry } from "@/mod";
21
- import {
22
- ACTOR_VERSIONED,
23
- CONN_VERSIONED,
24
- } from "@/schemas/actor-persist/versioned";
25
- import { EXTRA_ERROR_LOG } from "@/utils";
26
- import { getRivetExperimentalOtel } from "@/utils/env-vars";
27
- import { promiseWithResolvers } from "@/utils";
28
- import {
29
- type Actions,
30
- type ActorConfig,
31
- type ActorConfigInput,
32
- ActorConfigSchema,
33
- getRunFunction,
34
- } from "../config";
35
- import type { ConnDriver } from "../conn/driver";
36
- import { createHttpDriver } from "../conn/drivers/http";
37
- import {
38
- HibernatableWebSocketAckState,
39
- handleInboundHibernatableWebSocketMessage as applyInboundHibernatableWebSocketMessage,
40
- } from "../conn/hibernatable-websocket-ack-state";
41
- import {
42
- CONN_DRIVER_SYMBOL,
43
- CONN_STATE_MANAGER_SYMBOL,
44
- type AnyConn,
45
- type Conn,
46
- type ConnId,
47
- } from "../conn/mod";
48
- import {
49
- convertConnFromBarePersistedConn,
50
- type PersistedConn,
51
- } from "../conn/persisted";
52
- import {
53
- ActionContext,
54
- ActorContext,
55
- RequestContext,
56
- WebSocketContext,
57
- } from "../contexts";
58
-
59
- import type { AnyDatabaseProvider, InferDatabaseClient } from "../database";
60
- import { ActorDefinition } from "../definition";
61
- import type { ActorDriver } from "../driver";
62
- import * as errors from "../errors";
63
- import { serializeActorKey } from "../keys";
64
- import { getValueLength, processMessage } from "../protocol/old";
65
- import type { InputData } from "../protocol/serde";
66
- import { Schedule } from "../schedule";
67
- import {
68
- type EventSchemaConfig,
69
- getEventCanSubscribe,
70
- getQueueCanPublish,
71
- type QueueSchemaConfig,
72
- } from "../schema";
73
- import {
74
- assertUnreachable,
75
- DeadlineError,
76
- deadline,
77
- generateSecureToken,
78
- } from "../utils";
79
- import { ConnectionManager } from "./connection-manager";
80
- import { EventManager } from "./event-manager";
81
- import { KEYS, workflowStoragePrefix } from "./keys";
82
- import {
83
- type PreloadedEntries,
84
- type PreloadHit,
85
- type PreloadMap,
86
- } from "./preload-map";
87
- import {
88
- convertActorFromBarePersisted,
89
- type PersistedActor,
90
- } from "./persisted";
91
- import { QueueManager } from "./queue-manager";
92
- import { ScheduleManager } from "./schedule-manager";
93
- import { type SaveStateOptions, StateManager } from "./state-manager";
94
- import { TrackedWebSocket } from "./tracked-websocket";
95
- import { ActorTracesDriver } from "./traces-driver";
96
- import { WriteCollector } from "./write-collector";
97
-
98
- export type { SaveStateOptions };
99
-
100
- /**
101
- * Symbol used by subsystems (e.g., queue-manager) to access the
102
- * unexpected KV round-trip warning without exposing it as a public method.
103
- */
104
- export const WARN_UNEXPECTED_KV_ROUND_TRIP = Symbol(
105
- "warnUnexpectedKvRoundTrip",
106
- );
107
-
108
- export function actor<
109
- TState,
110
- TConnParams,
111
- TConnState,
112
- TVars,
113
- TInput,
114
- TDatabase extends AnyDatabaseProvider,
115
- TEvents extends EventSchemaConfig = Record<never, never>,
116
- TQueues extends QueueSchemaConfig = Record<never, never>,
117
- TActions extends Actions<
118
- TState,
119
- TConnParams,
120
- TConnState,
121
- TVars,
122
- TInput,
123
- TDatabase,
124
- TEvents,
125
- TQueues
126
- > = Actions<
127
- TState,
128
- TConnParams,
129
- TConnState,
130
- TVars,
131
- TInput,
132
- TDatabase,
133
- TEvents,
134
- TQueues
135
- >,
136
- >(
137
- input: ActorConfigInput<
138
- TState,
139
- TConnParams,
140
- TConnState,
141
- TVars,
142
- TInput,
143
- TDatabase,
144
- TEvents,
145
- TQueues,
146
- TActions
147
- >,
148
- ): ActorDefinition<
149
- TState,
150
- TConnParams,
151
- TConnState,
152
- TVars,
153
- TInput,
154
- TDatabase,
155
- TEvents,
156
- TQueues,
157
- TActions
158
- > {
159
- const config = ActorConfigSchema.parse(input) as ActorConfig<
160
- TState,
161
- TConnParams,
162
- TConnState,
163
- TVars,
164
- TInput,
165
- TDatabase,
166
- TEvents,
167
- TQueues
168
- >;
169
- return new ActorDefinition(config);
170
- }
171
-
172
- enum CanSleep {
173
- Yes,
174
- NotReady,
175
- NotStarted,
176
- PreventSleep,
177
- ActiveConns,
178
- ActiveDisconnectCallbacks,
179
- ActiveHonoHttpRequests,
180
- ActiveKeepAwake,
181
- ActiveInternalKeepAwake,
182
- ActiveRun,
183
- ActiveWebSocketCallbacks,
184
- }
185
-
186
- /**
187
- * Names of actor-managed async regions that should keep the actor awake while
188
- * work is still running.
189
- */
190
- interface ActiveAsyncRegionCounts {
191
- keepAwake: number;
192
- internalKeepAwake: number;
193
- websocketCallbacks: number;
194
- }
195
-
196
- /**
197
- * Error messages for the async-region counters. These are used when a counter
198
- * underflows, which indicates mismatched begin/end bookkeeping.
199
- */
200
- const ACTIVE_ASYNC_REGION_ERROR_MESSAGES: Record<
201
- keyof ActiveAsyncRegionCounts,
202
- string
203
- > = {
204
- keepAwake: "active keep awake count went below 0, this is a RivetKit bug",
205
- internalKeepAwake:
206
- "active internal keep awake count went below 0, this is a RivetKit bug",
207
- websocketCallbacks:
208
- "active websocket callback count went below 0, this is a RivetKit bug",
209
- };
210
-
211
- /**
212
- * Minimal lifecycle contract shared by static and dynamic actor instances.
213
- *
214
- * Runtime internals (connections, inspector, queue manager, etc) are exposed
215
- * only on `ActorInstance`.
216
- */
217
- export interface BaseActorInstance<
218
- S = any,
219
- CP = any,
220
- CS = any,
221
- V = any,
222
- I = any,
223
- DB extends AnyDatabaseProvider = AnyDatabaseProvider,
224
- E extends EventSchemaConfig = Record<never, never>,
225
- Q extends QueueSchemaConfig = Record<never, never>,
226
- > {
227
- readonly id: string;
228
- readonly isStopping: boolean;
229
- onStop(mode: "sleep" | "destroy"): Promise<void>;
230
- onAlarm(): Promise<void>;
231
- cleanupPersistedConnections?(reason?: string): Promise<number>;
232
- getHibernatingWebSocketMetadata?(): Array<{
233
- gatewayId: ArrayBuffer;
234
- requestId: ArrayBuffer;
235
- serverMessageIndex: number;
236
- clientMessageIndex: number;
237
- path: string;
238
- headers: Record<string, string>;
239
- }>;
240
- }
241
-
242
- /** Actor type alias with all `any` types. */
243
- export type AnyActorInstance = BaseActorInstance<
244
- any,
245
- any,
246
- any,
247
- any,
248
- any,
249
- any,
250
- any,
251
- any
252
- >;
253
-
254
- /** Static actor type alias with all `any` types. */
255
- export type AnyStaticActorInstance = ActorInstance<
256
- any,
257
- any,
258
- any,
259
- any,
260
- any,
261
- any,
262
- any,
263
- any
264
- >;
265
-
266
- export function isStaticActorInstance(
267
- actor: AnyActorInstance,
268
- ): actor is AnyStaticActorInstance {
269
- if (actor instanceof ActorInstance) {
270
- return true;
271
- }
272
-
273
- if (!actor || typeof actor !== "object") {
274
- return false;
275
- }
276
-
277
- const candidate = actor as Partial<AnyStaticActorInstance>;
278
- return (
279
- typeof candidate.executeAction === "function" &&
280
- typeof candidate.beginHonoHttpRequest === "function" &&
281
- typeof candidate.endHonoHttpRequest === "function" &&
282
- typeof candidate.connectionManager === "object" &&
283
- candidate.connectionManager !== null
284
- );
285
- }
286
-
287
- export type ExtractActorState<A extends AnyActorInstance> =
288
- A extends ActorInstance<infer State, any, any, any, any, any, any, any>
289
- ? State
290
- : never;
291
-
292
- export type ExtractActorConnParams<A extends AnyActorInstance> =
293
- A extends ActorInstance<any, infer ConnParams, any, any, any, any, any, any>
294
- ? ConnParams
295
- : never;
296
-
297
- export type ExtractActorConnState<A extends AnyActorInstance> =
298
- A extends ActorInstance<any, any, infer ConnState, any, any, any, any, any>
299
- ? ConnState
300
- : never;
301
-
302
- // MARK: - Main ActorInstance Class
303
- export class ActorInstance<
304
- S,
305
- CP,
306
- CS,
307
- V,
308
- I,
309
- DB extends AnyDatabaseProvider,
310
- E extends EventSchemaConfig = Record<never, never>,
311
- Q extends QueueSchemaConfig = Record<never, never>,
312
- > implements BaseActorInstance<S, CP, CS, V, I, DB, E, Q>
313
- {
314
- // MARK: - Core Properties
315
- actorContext: ActorContext<S, CP, CS, V, I, DB, E, Q>;
316
- #config: ActorConfig<S, CP, CS, V, I, DB, E, Q>;
317
- driver!: ActorDriver;
318
- #inlineClient!: Client<Registry<any>>;
319
- #actorId!: string;
320
- #name!: string;
321
- #key!: ActorKey;
322
- #actorKeyString!: string;
323
- #region!: string;
324
-
325
- // MARK: - Managers
326
- connectionManager!: ConnectionManager<S, CP, CS, V, I, DB, E, Q>;
327
-
328
- stateManager!: StateManager<S, CP, CS, I, E, Q>;
329
-
330
- eventManager!: EventManager<S, CP, CS, V, I, DB, E, Q>;
331
-
332
- #scheduleManager!: ScheduleManager<S, CP, CS, V, I, DB, E, Q>;
333
-
334
- queueManager!: QueueManager<S, CP, CS, V, I, DB, E, Q>;
335
-
336
- // MARK: - Logging
337
- #log!: Logger;
338
- #rLog!: Logger;
339
-
340
- // MARK: - Lifecycle State
341
- /**
342
- * If the core actor initiation has set up.
343
- *
344
- * Almost all actions on this actor will throw an error if false.
345
- **/
346
- #ready = false;
347
- /**
348
- * If the actor has fully started.
349
- *
350
- * The only purpose of this is to prevent sleeping until started.
351
- */
352
- #started = false;
353
- #sleepCalled = false;
354
- #destroyCalled = false;
355
- #stopCalled = false;
356
- #shutdownComplete = false;
357
- #sleepTimeout?: NodeJS.Timeout;
358
- #abortController = new AbortController();
359
-
360
- // MARK: - Variables & Database
361
- #vars?: V;
362
- #db?: InferDatabaseClient<DB>;
363
- #metrics = new ActorMetrics();
364
-
365
- // MARK: - Preload
366
- #workflowPreloadEntries?: PreloadedEntries;
367
- #expectNoKvRoundTrips = false;
368
-
369
- // MARK: - Background Tasks
370
- #backgroundPromises: Promise<void>[] = [];
371
- #websocketCallbackPromises: Promise<void>[] = [];
372
- #preventSleepClearedPromise?: ReturnType<typeof promiseWithResolvers<void>>;
373
- #runPromise?: Promise<void>;
374
- #runHandlerActive = false;
375
- #activeQueueWaitCount = 0;
376
-
377
- // MARK: - HTTP/WebSocket Tracking
378
- #activeHonoHttpRequests = 0;
379
- #activeAsyncRegionCounts: ActiveAsyncRegionCounts = {
380
- keepAwake: 0,
381
- internalKeepAwake: 0,
382
- websocketCallbacks: 0,
383
- };
384
- #preventSleep = false;
385
-
386
- // MARK: - Deprecated (kept for compatibility)
387
- #schedule!: Schedule;
388
-
389
- // MARK: - Hibernatable WebSocket State
390
- #hibernatableWebSocketAckState = new HibernatableWebSocketAckState();
391
-
392
- // MARK: - Inspector
393
- #inspectorToken?: string;
394
- #inspector: ActorInspector;
395
-
396
- // MARK: - Tracing
397
- #traces!: Traces<OtlpExportTraceServiceRequestJson>;
398
-
399
- // MARK: - Driver Overrides
400
- /**
401
- * Per-instance config option overrides applied by the driver after creation.
402
- * When set, the effective option value is the minimum of the base config
403
- * value and the override value.
404
- */
405
- overrides: {
406
- sleepGracePeriod?: number;
407
- } = {};
408
-
409
- // MARK: - Constructor
410
- constructor(config: ActorConfig<S, CP, CS, V, I, DB, E, Q>) {
411
- this.#config = config;
412
- this.actorContext = new ActorContext(this);
413
- this.#inspector = new ActorInspector(this);
414
- }
415
-
416
- // MARK: - Public Getters
417
- get log(): Logger {
418
- invariant(this.#log, "log not configured");
419
- return this.#log;
420
- }
421
-
422
- get rLog(): Logger {
423
- invariant(this.#rLog, "log not configured");
424
- return this.#rLog;
425
- }
426
-
427
- get isStopping(): boolean {
428
- return this.#stopCalled;
429
- }
430
-
431
- get id(): string {
432
- return this.#actorId;
433
- }
434
-
435
- get name(): string {
436
- return this.#name;
437
- }
438
-
439
- get key(): ActorKey {
440
- return this.#key;
441
- }
442
-
443
- get region(): string {
444
- return this.#region;
445
- }
446
-
447
- get inlineClient(): Client<Registry<any>> {
448
- return this.#inlineClient;
449
- }
450
-
451
- get inspector(): ActorInspector {
452
- return this.#inspector;
453
- }
454
-
455
- get traces(): Traces<OtlpExportTraceServiceRequestJson> {
456
- return this.#traces;
457
- }
458
-
459
- get inspectorToken(): string | undefined {
460
- return this.#inspectorToken;
461
- }
462
-
463
- get metrics(): ActorMetrics {
464
- return this.#metrics;
465
- }
466
-
467
- // MARK: - Tracing
468
- getCurrentTraceSpan(): SpanHandle | null {
469
- return this.#traces.getCurrentSpan();
470
- }
471
-
472
- startTraceSpan(
473
- name: string,
474
- attributes?: Record<string, unknown>,
475
- ): SpanHandle {
476
- return this.#traces.startSpan(name, {
477
- parent: this.#traces.getCurrentSpan() ?? undefined,
478
- attributes: this.#traceAttributes(attributes),
479
- });
480
- }
481
-
482
- endTraceSpan(handle: SpanHandle, status?: SpanStatusInput): void {
483
- this.#traces.endSpan(handle, status ? { status } : undefined);
484
- }
485
-
486
- async runInTraceSpan<T>(
487
- name: string,
488
- attributes: Record<string, unknown> | undefined,
489
- fn: () => T | Promise<T>,
490
- ): Promise<T> {
491
- const span = this.startTraceSpan(name, attributes);
492
- try {
493
- const result = this.#traces.withSpan(span, fn);
494
- const resolved = result instanceof Promise ? await result : result;
495
- this.#traces.endSpan(span, {
496
- status: { code: "OK" },
497
- });
498
- return resolved;
499
- } catch (error) {
500
- this.#traces.endSpan(span, {
501
- status: {
502
- code: "ERROR",
503
- message: stringifyError(error),
504
- },
505
- });
506
- throw error;
507
- }
508
- }
509
-
510
- emitTraceEvent(
511
- name: string,
512
- attributes?: Record<string, unknown>,
513
- handle?: SpanHandle,
514
- ): void {
515
- const span = handle ?? this.#traces.getCurrentSpan();
516
- if (!span) {
517
- return;
518
- }
519
- this.#traces.emitEvent(span, name, {
520
- attributes: this.#traceAttributes(attributes),
521
- timeUnixMs: Date.now(),
522
- });
523
- }
524
-
525
- get workflowPreloadEntries(): PreloadedEntries | undefined {
526
- return this.#workflowPreloadEntries;
527
- }
528
-
529
- [WARN_UNEXPECTED_KV_ROUND_TRIP](method: string): void {
530
- if (this.#expectNoKvRoundTrips) {
531
- this.#rLog.warn({
532
- msg: "unexpected KV round-trip during startup",
533
- method,
534
- });
535
- this.#expectNoKvRoundTrips = false;
536
- }
537
- }
538
-
539
- static #userStartupKeys: Set<StartupTimingKey> = new Set([
540
- "createStateMs",
541
- "onCreateMs",
542
- "onWakeMs",
543
- "createVarsMs",
544
- "dbMigrateMs",
545
- ]);
546
-
547
- /**
548
- * Measure the duration of an async startup step. Logs at debug level
549
- * and records the duration on the startup metrics object.
550
- *
551
- * When `pauseKvGuard` is true, the unexpected KV round-trip guard is
552
- * suspended for the duration of the callback (used for user code
553
- * callbacks that may legitimately issue KV reads).
554
- */
555
- async #measureStartup<T>(
556
- name: StartupTimingKey,
557
- fn: () => Promise<T> | T,
558
- opts?: { pauseKvGuard?: boolean },
559
- ): Promise<T> {
560
- const savedGuard = this.#expectNoKvRoundTrips;
561
- if (opts?.pauseKvGuard) {
562
- this.#expectNoKvRoundTrips = false;
563
- }
564
- const start = performance.now();
565
- try {
566
- const result = await fn();
567
- return result;
568
- } finally {
569
- const durationMs = performance.now() - start;
570
- this.#metrics.startup[name] = durationMs;
571
- const prefix = ActorInstance.#userStartupKeys.has(name)
572
- ? "perf user"
573
- : "perf internal";
574
- this.#rLog.debug({ msg: `${prefix}: ${name}`, durationMs });
575
- if (opts?.pauseKvGuard) {
576
- this.#expectNoKvRoundTrips = savedGuard;
577
- }
578
- }
579
- }
580
-
581
- get conns(): Map<ConnId, Conn<S, CP, CS, V, I, DB, E, Q>> {
582
- return this.connectionManager.connections;
583
- }
584
-
585
- /**
586
- * Records delivery of an inbound indexed hibernatable websocket message and
587
- * schedules persistence so the index is only acked after a durable write.
588
- */
589
- handleInboundHibernatableWebSocketMessage(
590
- conn: AnyConn | undefined,
591
- payload: InputData,
592
- rivetMessageIndex: number | undefined,
593
- ): void {
594
- if (!conn?.isHibernatable) {
595
- return;
596
- }
597
-
598
- const connStateManager = conn[CONN_STATE_MANAGER_SYMBOL];
599
- const hibernatable = connStateManager.hibernatableData;
600
- if (!hibernatable) {
601
- return;
602
- }
603
-
604
- invariant(
605
- typeof rivetMessageIndex === "number",
606
- "missing rivetMessageIndex for hibernatable websocket message",
607
- );
608
-
609
- applyInboundHibernatableWebSocketMessage({
610
- connId: conn.id,
611
- hibernatable,
612
- messageLength: getValueLength(payload),
613
- rivetMessageIndex,
614
- ackState: this.#hibernatableWebSocketAckState,
615
- saveState: (opts) => {
616
- void this.stateManager.saveState(opts).catch((error) => {
617
- this.#rLog.error({
618
- msg: "failed to schedule hibernatable websocket persistence",
619
- connId: conn.id,
620
- error: stringifyError(error),
621
- });
622
- });
623
- },
624
- });
625
- }
626
-
627
- onCreateHibernatableConn(conn: AnyConn): void {
628
- const hibernatable = conn[CONN_STATE_MANAGER_SYMBOL].hibernatableData;
629
- if (!hibernatable) {
630
- return;
631
- }
632
-
633
- this.#hibernatableWebSocketAckState.createConnEntry(
634
- conn.id,
635
- hibernatable.serverMessageIndex,
636
- );
637
- }
638
-
639
- onDestroyHibernatableConn(conn: AnyConn): void {
640
- this.#hibernatableWebSocketAckState.deleteConnEntry(conn.id);
641
- }
642
-
643
- onBeforePersistHibernatableConn(conn: AnyConn): void {
644
- const hibernatable =
645
- conn[CONN_STATE_MANAGER_SYMBOL].hibernatableDataOrError();
646
- this.#hibernatableWebSocketAckState.onBeforePersist(
647
- conn.id,
648
- hibernatable.serverMessageIndex,
649
- );
650
- }
651
-
652
- onAfterPersistHibernatableConn(conn: AnyConn): void {
653
- const hibernatable =
654
- conn[CONN_STATE_MANAGER_SYMBOL].hibernatableDataOrError();
655
- const ackServerMessageIndex =
656
- this.#hibernatableWebSocketAckState.consumeAck(conn.id);
657
- if (ackServerMessageIndex === undefined) {
658
- return;
659
- }
660
-
661
- this.driver.ackHibernatableWebSocketMessage?.(
662
- hibernatable.gatewayId,
663
- hibernatable.requestId,
664
- ackServerMessageIndex,
665
- );
666
- }
667
-
668
- getHibernatingWebSocketMetadata(): Array<{
669
- gatewayId: ArrayBuffer;
670
- requestId: ArrayBuffer;
671
- serverMessageIndex: number;
672
- clientMessageIndex: number;
673
- path: string;
674
- headers: Record<string, string>;
675
- }> {
676
- return Array.from(this.conns.values(), (conn) => {
677
- const hibernatable =
678
- conn[CONN_STATE_MANAGER_SYMBOL].hibernatableData;
679
- if (!hibernatable) {
680
- return undefined;
681
- }
682
- return {
683
- gatewayId: hibernatable.gatewayId.slice(0),
684
- requestId: hibernatable.requestId.slice(0),
685
- serverMessageIndex: hibernatable.serverMessageIndex,
686
- clientMessageIndex: hibernatable.clientMessageIndex,
687
- path: hibernatable.requestPath,
688
- headers: { ...hibernatable.requestHeaders },
689
- };
690
- }).filter((entry) => entry !== undefined);
691
- }
692
-
693
- get schedule(): Schedule {
694
- return this.#schedule;
695
- }
696
-
697
- get abortSignal(): AbortSignal {
698
- return this.#abortController.signal;
699
- }
700
-
701
- get preventSleep(): boolean {
702
- return this.#preventSleep;
703
- }
704
-
705
- get actions(): string[] {
706
- return Object.keys(this.#config.actions ?? {});
707
- }
708
-
709
- get config(): ActorConfig<S, CP, CS, V, I, DB, E, Q> {
710
- return this.#config;
711
- }
712
-
713
- // MARK: - State Access
714
- get persist(): PersistedActor<S, I> {
715
- return this.stateManager.persist;
716
- }
717
-
718
- get state(): S {
719
- return this.stateManager.state;
720
- }
721
-
722
- set state(value: S) {
723
- this.stateManager.state = value;
724
- }
725
-
726
- get stateEnabled(): boolean {
727
- return this.stateManager.stateEnabled;
728
- }
729
-
730
- get connStateEnabled(): boolean {
731
- return "createConnState" in this.#config || "connState" in this.#config;
732
- }
733
-
734
- // MARK: - Variables & Database
735
- get vars(): V {
736
- this.#validateVarsEnabled();
737
- invariant(this.#vars !== undefined, "vars not enabled");
738
- return this.#vars;
739
- }
740
-
741
- get db(): InferDatabaseClient<DB> {
742
- if (!this.#db) {
743
- if (this.#shutdownComplete && "db" in this.#config) {
744
- throw new errors.ActorStopping(
745
- "database accessed after actor stopped. If you are using setInterval or other background timers, clean them up with c.abortSignal.",
746
- );
747
- }
748
- throw new errors.DatabaseNotEnabled();
749
- }
750
- return this.#db;
751
- }
752
-
753
- // MARK: - Initialization
754
- async start(
755
- actorDriver: ActorDriver,
756
- inlineClient: Client<Registry<any>>,
757
- actorId: string,
758
- name: string,
759
- key: ActorKey,
760
- region: string,
761
- preload?: PreloadMap,
762
- ) {
763
- const startupStart = performance.now();
764
-
765
- // Initialize properties
766
- this.driver = actorDriver;
767
- this.#inlineClient = inlineClient;
768
- this.#actorId = actorId;
769
- this.#name = name;
770
- this.#key = key;
771
- this.#actorKeyString = serializeActorKey(this.#key);
772
- this.#region = region;
773
-
774
- // Initialize tracing
775
- this.#initializeTraces();
776
-
777
- // Initialize logging
778
- this.#initializeLogging();
779
-
780
- // Initialize managers
781
- this.connectionManager = new ConnectionManager(this);
782
- this.stateManager = new StateManager(this, actorDriver, this.#config);
783
- this.eventManager = new EventManager(this);
784
- this.queueManager = new QueueManager(this, actorDriver);
785
- this.#scheduleManager = new ScheduleManager(
786
- this,
787
- actorDriver,
788
- this.#config,
789
- );
790
-
791
- // Legacy schedule object (for compatibility)
792
- this.#schedule = new Schedule(this);
793
-
794
- // Enable unexpected KV round-trip detection when preload data was
795
- // provided.
796
- if (preload) {
797
- this.#expectNoKvRoundTrips = true;
798
- }
799
-
800
- // Extract workflow preload data for lazy consumption by workflow engine.
801
- if (preload) {
802
- const workflowEntries = preload.listPrefix(workflowStoragePrefix());
803
- if (workflowEntries !== undefined) {
804
- this.#workflowPreloadEntries = workflowEntries;
805
- }
806
- }
807
-
808
- // Setup database before lifecycle hooks so c.db is available in
809
- // createState, onCreate, createVars, and onWake.
810
- await this.#setupDatabase(preload);
811
-
812
- // Create a write collector to batch new-actor init writes into a
813
- // single kvBatchPut.
814
- const writeCollector = new WriteCollector(actorDriver, actorId);
815
-
816
- // Load state
817
- await this.#measureStartup("loadStateMs", () =>
818
- this.#loadState(preload, writeCollector),
819
- );
820
-
821
- await this.#measureStartup("initQueueMs", () =>
822
- this.queueManager.initialize(preload, writeCollector),
823
- );
824
-
825
- await this.#measureStartup("initInspectorTokenMs", () =>
826
- this.#initializeInspectorToken(preload, writeCollector),
827
- );
828
-
829
- // Flush any batched writes from new actor initialization.
830
- await this.#measureStartup("flushWritesMs", async () => {
831
- this.#metrics.startup.flushWritesEntries = writeCollector.size;
832
- await writeCollector.flush();
833
- });
834
-
835
- // Initialize variables.
836
- await this.#measureStartup(
837
- "createVarsMs",
838
- async () => {
839
- if (this.#varsEnabled) {
840
- await this.#initializeVars();
841
- }
842
- },
843
- { pauseKvGuard: true },
844
- );
845
-
846
- // Call onStart lifecycle.
847
- await this.#measureStartup("onWakeMs", () => this.#callOnStart(), {
848
- pauseKvGuard: true,
849
- });
850
- // Initialize alarms
851
- await this.#measureStartup("initAlarmsMs", () =>
852
- this.#scheduleManager.initializeAlarms(),
853
- );
854
-
855
- // Mark as ready
856
- this.#ready = true;
857
-
858
- // Finish up any remaining initiation
859
- //
860
- // Do this after #ready = true since this can call any actor callbacks
861
- // (which require #assertReady)
862
- await this.#measureStartup("onBeforeActorStartMs", async () => {
863
- await this.driver.onBeforeActorStart?.(this);
864
- });
865
-
866
- // Mark as started
867
- //
868
- // We do this after onBeforeActorStart to prevent the actor from going
869
- // to sleep before finishing setup
870
- this.#started = true;
871
-
872
- // Clear KV round-trip detection after startup completes.
873
- this.#expectNoKvRoundTrips = false;
874
-
875
- // Release workflow preload data after startup completes.
876
- this.#workflowPreloadEntries = undefined;
877
-
878
- // Record total startup time.
879
- this.#metrics.startup.totalMs = performance.now() - startupStart;
880
- this.#rLog.info({
881
- msg: "actor started",
882
- startupMs: this.#metrics.startup.totalMs,
883
- kvRoundTrips: this.#metrics.startup.kvRoundTrips,
884
- });
885
-
886
- // Start sleep timer after setting #started since this affects the
887
- // timer
888
- this.resetSleepTimer();
889
-
890
- // Start run handler in background (does not block startup)
891
- this.#startRunHandler();
892
-
893
- // Trigger any pending alarms
894
- await this.onAlarm();
895
- }
896
-
897
- // MARK: - Ready Check
898
- isReady(): boolean {
899
- return this.#ready;
900
- }
901
-
902
- assertReady() {
903
- if (!this.#ready) throw new errors.InternalError("Actor not ready");
904
- this.assertNotShutdown();
905
- }
906
-
907
- assertNotShutdown() {
908
- if (this.#shutdownComplete)
909
- throw new errors.ActorStopping("Actor has shut down");
910
- }
911
-
912
- async cleanupPersistedConnections(reason?: string): Promise<number> {
913
- this.assertReady();
914
- return await this.connectionManager.cleanupPersistedHibernatableConnections(
915
- reason,
916
- );
917
- }
918
-
919
- async restartRunHandler(): Promise<void> {
920
- this.assertReady();
921
- if (this.#stopCalled)
922
- throw errors.actorRestarting({ phase: "stopping" });
923
- if (this.#runHandlerActive && this.#runPromise) {
924
- await this.#runPromise;
925
- }
926
- if (this.#runHandlerActive) {
927
- return;
928
- }
929
-
930
- this.#startRunHandler();
931
- }
932
-
933
- isRunHandlerActive(): boolean {
934
- return this.#runHandlerActive;
935
- }
936
-
937
- // MARK: - Stop
938
- async onStop(mode: "sleep" | "destroy") {
939
- if (this.#stopCalled) {
940
- this.#rLog.warn({ msg: "already stopping actor" });
941
- return;
942
- }
943
- this.#stopCalled = true;
944
- this.#rLog.info({
945
- msg: "setting stopCalled=true",
946
- mode,
947
- });
948
-
949
- try {
950
- // Clear sleep timeout
951
- if (this.#sleepTimeout) {
952
- clearTimeout(this.#sleepTimeout);
953
- this.#sleepTimeout = undefined;
954
- }
955
-
956
- // Cancel alarm timeouts so they cannot fire during shutdown.
957
- // Scheduled events are persisted and will be re-initialized
958
- // on wake via initializeAlarms().
959
- this.driver.cancelAlarm?.(this.#actorId);
960
-
961
- // Abort listeners in the canonical stop path.
962
- // This must run for all stop modes, including sleep and remote stop.
963
- // Destroy may have already triggered an early abort, but repeating abort
964
- // is intentional and safe.
965
- try {
966
- this.#abortController.abort();
967
- } catch {}
968
-
969
- // The run-handler join, lifecycle hooks, and remaining shutdown
970
- // tasks all share the single sleepGracePeriod budget.
971
- const shutdownTaskDeadlineTs =
972
- Date.now() + this.#getEffectiveSleepGracePeriod();
973
-
974
- await this.#waitForRunHandler(shutdownTaskDeadlineTs - Date.now());
975
-
976
- // Call onStop lifecycle
977
- if (mode === "sleep") {
978
- await this.#waitForIdleSleepWindow(shutdownTaskDeadlineTs);
979
- await this.#callOnSleep(shutdownTaskDeadlineTs);
980
- } else if (mode === "destroy") {
981
- await this.#callOnDestroy(shutdownTaskDeadlineTs);
982
- } else {
983
- assertUnreachable(mode);
984
- }
985
-
986
- // Wait for shutdown tasks that were already in flight before
987
- // connection teardown starts.
988
- await this.#waitShutdownTasks(shutdownTaskDeadlineTs);
989
-
990
- // Disconnect non-hibernatable connections
991
- await this.#disconnectConnections();
992
-
993
- // Drain async WebSocket close handlers and any waitUntil work they
994
- // enqueue before persisting final state.
995
- await this.#waitShutdownTasks(shutdownTaskDeadlineTs);
996
-
997
- // Clear timeouts and save state
998
- this.#rLog.info({ msg: "clearing pending save timeouts" });
999
- this.stateManager.clearPendingSaveTimeout();
1000
- this.#rLog.info({ msg: "saving state immediately" });
1001
- await this.stateManager.saveState({
1002
- immediate: true,
1003
- });
1004
-
1005
- // Wait for write queues
1006
- await this.stateManager.waitForPendingWrites();
1007
- await this.#scheduleManager.waitForPendingAlarmWrites();
1008
- } finally {
1009
- this.#shutdownComplete = true;
1010
- await this.#cleanupDatabase();
1011
- }
1012
- }
1013
-
1014
- async debugForceCrash() {
1015
- if (this.#shutdownComplete) {
1016
- return;
1017
- }
1018
- if (this.#stopCalled) {
1019
- this.#rLog.warn({
1020
- msg: "already stopping actor during hard crash",
1021
- });
1022
- return;
1023
- }
1024
- this.#stopCalled = true;
1025
-
1026
- try {
1027
- if (this.#sleepTimeout) {
1028
- clearTimeout(this.#sleepTimeout);
1029
- this.#sleepTimeout = undefined;
1030
- }
1031
-
1032
- this.driver.cancelAlarm?.(this.#actorId);
1033
- this.stateManager.clearPendingSaveTimeout();
1034
-
1035
- try {
1036
- this.#abortController.abort();
1037
- } catch {}
1038
- } finally {
1039
- this.#shutdownComplete = true;
1040
- await this.#cleanupDatabase();
1041
- }
1042
- }
1043
-
1044
- // MARK: - Sleep
1045
- startSleep() {
1046
- if (this.#stopCalled || this.#destroyCalled) {
1047
- this.#rLog.debug({
1048
- msg: "cannot call startSleep if actor already stopping",
1049
- });
1050
- return;
1051
- }
1052
-
1053
- if (this.#sleepCalled) {
1054
- this.#rLog.warn({
1055
- msg: "cannot call startSleep twice, actor already sleeping",
1056
- });
1057
- return;
1058
- }
1059
- this.#sleepCalled = true;
1060
-
1061
- const sleep = this.driver.startSleep?.bind(this.driver, this.#actorId);
1062
- invariant(this.#sleepingSupported, "sleeping not supported");
1063
- invariant(sleep, "no sleep on driver");
1064
-
1065
- this.#rLog.info({ msg: "actor sleeping" });
1066
-
1067
- // Start sleep on next tick so call site of startSleep can exit
1068
- setImmediate(() => {
1069
- sleep();
1070
- });
1071
- }
1072
-
1073
- // MARK: - Destroy
1074
- startDestroy() {
1075
- if (this.#stopCalled || this.#sleepCalled) {
1076
- this.#rLog.debug({
1077
- msg: "cannot call startDestroy if actor already stopping or sleeping",
1078
- });
1079
- return;
1080
- }
1081
-
1082
- if (this.#destroyCalled) {
1083
- this.#rLog.warn({
1084
- msg: "cannot call startDestroy twice, actor already destroying",
1085
- });
1086
- return;
1087
- }
1088
- this.#destroyCalled = true;
1089
-
1090
- // Abort immediately so in flight waits can exit before the driver stop
1091
- // handshake completes.
1092
- // The onStop path will call abort again as a safety net for all stop
1093
- // modes.
1094
- try {
1095
- this.#abortController.abort();
1096
- } catch {}
1097
-
1098
- const destroy = this.driver.startDestroy.bind(
1099
- this.driver,
1100
- this.#actorId,
1101
- );
1102
-
1103
- this.#rLog.info({ msg: "actor destroying" });
1104
-
1105
- // Start destroy on next tick so call site of startDestroy can exit
1106
- setImmediate(() => {
1107
- destroy();
1108
- });
1109
- }
1110
-
1111
- // MARK: - HTTP Request Tracking
1112
- beginHonoHttpRequest() {
1113
- this.#activeHonoHttpRequests++;
1114
- this.resetSleepTimer();
1115
- }
1116
-
1117
- endHonoHttpRequest() {
1118
- this.#activeHonoHttpRequests--;
1119
- if (this.#activeHonoHttpRequests < 0) {
1120
- this.#activeHonoHttpRequests = 0;
1121
- this.#rLog.warn({
1122
- msg: "active hono requests went below 0, this is a RivetKit bug",
1123
- ...EXTRA_ERROR_LOG,
1124
- });
1125
- }
1126
- this.resetSleepTimer();
1127
- }
1128
-
1129
- // MARK: - Message Processing
1130
- async processMessage(
1131
- message: {
1132
- body:
1133
- | {
1134
- tag: "ActionRequest";
1135
- val: { id: bigint; name: string; args: unknown };
1136
- }
1137
- | {
1138
- tag: "SubscriptionRequest";
1139
- val: { eventName: string; subscribe: boolean };
1140
- };
1141
- },
1142
- conn: Conn<S, CP, CS, V, I, DB, E, Q>,
1143
- ) {
1144
- // Hibernating WebSocket connections intentionally do not keep the
1145
- // actor alive so the actor can sleep while connections are idle.
1146
- // Reset the sleep timer on each message so the actor stays awake
1147
- // while clients are actively communicating.
1148
- this.resetSleepTimer();
1149
-
1150
- await processMessage(message, this, conn, {
1151
- onExecuteAction: async (ctx, name, args) => {
1152
- return await this.executeAction(ctx, name, args);
1153
- },
1154
- onSubscribe: async (eventName, conn) => {
1155
- this.eventManager.addSubscription(eventName, conn, false);
1156
- },
1157
- onUnsubscribe: async (eventName, conn) => {
1158
- this.eventManager.removeSubscription(eventName, conn, false);
1159
- },
1160
- });
1161
- }
1162
-
1163
- async assertCanSubscribe(
1164
- ctx: ActionContext<S, CP, CS, V, I, DB, E, Q>,
1165
- eventName: string,
1166
- ): Promise<void> {
1167
- const canSubscribe = getEventCanSubscribe(
1168
- this.#config.events,
1169
- eventName,
1170
- );
1171
- if (!canSubscribe) {
1172
- return;
1173
- }
1174
-
1175
- const result = await canSubscribe(ctx);
1176
- if (typeof result !== "boolean") {
1177
- throw new errors.InvalidCanSubscribeResponse();
1178
- }
1179
- if (!result) {
1180
- throw new errors.Forbidden();
1181
- }
1182
- }
1183
-
1184
- async assertCanPublish(
1185
- ctx: ActionContext<S, CP, CS, V, I, DB, E, Q>,
1186
- queueName: string,
1187
- ): Promise<void> {
1188
- const canPublish = getQueueCanPublish<
1189
- ActionContext<S, CP, CS, V, I, DB, E, Q>
1190
- >(this.#config.queues, queueName);
1191
- if (!canPublish) {
1192
- return;
1193
- }
1194
-
1195
- const result = await canPublish(ctx);
1196
- if (typeof result !== "boolean") {
1197
- throw new errors.InvalidCanPublishResponse();
1198
- }
1199
- if (!result) {
1200
- throw new errors.Forbidden();
1201
- }
1202
- }
1203
-
1204
- // MARK: - Action Execution
1205
- async invokeActionByName(
1206
- ctx: ActorContext<S, CP, CS, V, I, DB, E, Q>,
1207
- actionName: string,
1208
- args: unknown[],
1209
- timeoutMs?: number,
1210
- ): Promise<unknown> {
1211
- this.assertReady();
1212
-
1213
- const actions = this.#config.actions ?? {};
1214
- if (!(actionName in actions)) {
1215
- this.#rLog.warn({ msg: "action does not exist", actionName });
1216
- throw new errors.ActionNotFound(actionName);
1217
- }
1218
-
1219
- const actionFunction = actions[actionName];
1220
- if (typeof actionFunction !== "function") {
1221
- this.#rLog.warn({
1222
- msg: "action is not a function",
1223
- actionName,
1224
- type: typeof actionFunction,
1225
- });
1226
- throw new errors.ActionNotFound(actionName);
1227
- }
1228
-
1229
- const outputOrPromise = actionFunction.call(
1230
- undefined,
1231
- // TODO: Replace this cast after scheduled actions and direct actions
1232
- // share a properly typed internal action invocation context.
1233
- ctx as any,
1234
- ...args,
1235
- );
1236
- const maybeThenable = outputOrPromise as {
1237
- then?: (onfulfilled?: unknown, onrejected?: unknown) => unknown;
1238
- };
1239
- if (maybeThenable && typeof maybeThenable.then === "function") {
1240
- const promise = Promise.resolve(outputOrPromise);
1241
- return await (timeoutMs === undefined
1242
- ? promise
1243
- : deadline(promise, timeoutMs));
1244
- }
1245
-
1246
- return outputOrPromise;
1247
- }
1248
-
1249
- async executeAction(
1250
- ctx: ActionContext<S, CP, CS, V, I, DB, E, Q>,
1251
- actionName: string,
1252
- args: unknown[],
1253
- ): Promise<unknown> {
1254
- this.assertReady();
1255
-
1256
- this.#beginActiveAsyncRegion("internalKeepAwake");
1257
- this.#metrics.actionCalls++;
1258
- const actionStart = performance.now();
1259
- const actionSpan = this.startTraceSpan(`actor.action.${actionName}`, {
1260
- "rivet.action.name": actionName,
1261
- });
1262
- let spanEnded = false;
1263
-
1264
- try {
1265
- const output = await this.#traces.withSpan(actionSpan, async () => {
1266
- this.#rLog.debug({
1267
- msg: "executing action",
1268
- actionName,
1269
- args,
1270
- });
1271
-
1272
- let output = await this.invokeActionByName(
1273
- ctx,
1274
- actionName,
1275
- args,
1276
- this.#config.options.actionTimeout,
1277
- );
1278
-
1279
- // Process through onBeforeActionResponse if configured
1280
- if (this.#config.onBeforeActionResponse) {
1281
- try {
1282
- output = await this.runInTraceSpan(
1283
- "actor.onBeforeActionResponse",
1284
- { "rivet.action.name": actionName },
1285
- () =>
1286
- this.#config.onBeforeActionResponse!(
1287
- this.actorContext,
1288
- actionName,
1289
- args,
1290
- output,
1291
- ),
1292
- );
1293
- } catch (error) {
1294
- this.#rLog.error({
1295
- msg: "error in `onBeforeActionResponse`",
1296
- error: stringifyError(error),
1297
- });
1298
- }
1299
- }
1300
-
1301
- return output;
1302
- });
1303
-
1304
- return output;
1305
- } catch (error) {
1306
- this.#metrics.actionErrors++;
1307
- const isTimeout = error instanceof DeadlineError;
1308
- const message = isTimeout
1309
- ? "ActionTimedOut"
1310
- : stringifyError(error);
1311
- this.#traces.setAttributes(actionSpan, {
1312
- "error.message": message,
1313
- "error.type":
1314
- error instanceof Error ? error.name : typeof error,
1315
- });
1316
- this.#traces.endSpan(actionSpan, {
1317
- status: { code: "ERROR", message },
1318
- });
1319
- spanEnded = true;
1320
- if (isTimeout) {
1321
- throw new errors.ActionTimedOut();
1322
- }
1323
- this.#rLog.error({
1324
- msg: "action error",
1325
- actionName,
1326
- error: stringifyError(error),
1327
- });
1328
- throw error;
1329
- } finally {
1330
- this.#metrics.actionTotalMs += performance.now() - actionStart;
1331
- if (!spanEnded && actionSpan.isActive()) {
1332
- this.#traces.endSpan(actionSpan, {
1333
- status: { code: "OK" },
1334
- });
1335
- }
1336
- this.#endActiveAsyncRegion("internalKeepAwake");
1337
- this.stateManager.savePersistThrottled();
1338
- }
1339
- }
1340
-
1341
- // MARK: - HTTP/WebSocket Handlers
1342
- //
1343
- // handleRawRequest intentionally has no isStopping guard (unlike
1344
- // handleRawWebSocket). In-flight HTTP requests from pre-existing
1345
- // connections are allowed during the graceful shutdown window.
1346
- // New external requests cannot reach a stopping actor because the
1347
- // driver layer blocks them.
1348
- async handleRawRequest(
1349
- conn: Conn<S, CP, CS, V, I, DB, E, Q>,
1350
- request: Request,
1351
- ): Promise<Response> {
1352
- this.assertReady();
1353
-
1354
- if (!this.#config.onRequest) {
1355
- throw new errors.RequestHandlerNotDefined();
1356
- }
1357
- const onRequest = this.#config.onRequest;
1358
-
1359
- return await this.runInTraceSpan(
1360
- "actor.onRequest",
1361
- {
1362
- "http.method": request.method,
1363
- "http.url": request.url,
1364
- "rivet.conn.id": conn.id,
1365
- },
1366
- async () => {
1367
- const ctx = new RequestContext(this, conn, request);
1368
- try {
1369
- const response = await onRequest(ctx, request);
1370
- if (!response) {
1371
- throw new errors.InvalidRequestHandlerResponse();
1372
- }
1373
- return response;
1374
- } catch (error) {
1375
- this.#rLog.error({
1376
- msg: "onRequest error",
1377
- error: stringifyError(error),
1378
- });
1379
- throw error;
1380
- } finally {
1381
- this.stateManager.savePersistThrottled();
1382
- }
1383
- },
1384
- );
1385
- }
1386
-
1387
- handleRawWebSocket(
1388
- conn: Conn<S, CP, CS, V, I, DB, E, Q>,
1389
- websocket: UniversalWebSocket,
1390
- request?: Request,
1391
- ) {
1392
- // NOTE: All code before `onWebSocket` must be synchronous in order to ensure the order of `open` events happen in the correct order.
1393
-
1394
- this.assertReady();
1395
- if (this.#stopCalled)
1396
- throw new errors.InternalError("Actor is stopping");
1397
-
1398
- if (!this.#config.onWebSocket) {
1399
- throw new errors.InternalError("onWebSocket handler not defined");
1400
- }
1401
-
1402
- const span = this.startTraceSpan("actor.onWebSocket", {
1403
- "http.url": request?.url,
1404
- "rivet.conn.id": conn.id,
1405
- });
1406
- let spanEnded = false;
1407
-
1408
- try {
1409
- // Reset sleep timer when handling WebSocket
1410
- this.resetSleepTimer();
1411
-
1412
- // Handle WebSocket
1413
- const ctx = new WebSocketContext(this, conn, request);
1414
- const trackedWebSocket = this.#createTrackedWebSocket(websocket);
1415
-
1416
- // NOTE: This is async and will run in the background
1417
- const voidOrPromise = this.#traces.withSpan(span, () =>
1418
- this.#config.onWebSocket!(ctx, trackedWebSocket),
1419
- );
1420
-
1421
- // Save changes from the WebSocket open
1422
- if (voidOrPromise instanceof Promise) {
1423
- voidOrPromise
1424
- .then(() => {
1425
- if (!spanEnded) {
1426
- this.endTraceSpan(span, { code: "OK" });
1427
- spanEnded = true;
1428
- }
1429
- })
1430
- .catch((error) => {
1431
- if (!spanEnded) {
1432
- this.endTraceSpan(span, {
1433
- code: "ERROR",
1434
- message: stringifyError(error),
1435
- });
1436
- spanEnded = true;
1437
- }
1438
- this.#rLog.error({
1439
- msg: "onWebSocket error",
1440
- error: stringifyError(error),
1441
- });
1442
- })
1443
- .finally(() => {
1444
- this.stateManager.savePersistThrottled();
1445
- });
1446
- } else {
1447
- if (!spanEnded) {
1448
- this.endTraceSpan(span, { code: "OK" });
1449
- spanEnded = true;
1450
- }
1451
- this.stateManager.savePersistThrottled();
1452
- }
1453
- } catch (error) {
1454
- if (!spanEnded) {
1455
- this.endTraceSpan(span, {
1456
- code: "ERROR",
1457
- message: stringifyError(error),
1458
- });
1459
- spanEnded = true;
1460
- }
1461
- this.#rLog.error({
1462
- msg: "onWebSocket error",
1463
- error: stringifyError(error),
1464
- });
1465
- throw error;
1466
- }
1467
- }
1468
-
1469
- // MARK: - Scheduling
1470
- async scheduleEvent(
1471
- timestamp: number,
1472
- action: string,
1473
- args: unknown[],
1474
- ): Promise<void> {
1475
- await this.#scheduleManager.scheduleEvent(timestamp, action, args);
1476
- }
1477
-
1478
- async onAlarm() {
1479
- if (this.#stopCalled) return;
1480
- this.resetSleepTimer();
1481
- await this.#scheduleManager.onAlarm();
1482
- }
1483
-
1484
- // MARK: - Background Tasks
1485
- waitUntil(promise: Promise<void>) {
1486
- this.assertNotShutdown();
1487
-
1488
- const nonfailablePromise = promise
1489
- .then(() => {
1490
- this.#rLog.debug({ msg: "wait until promise complete" });
1491
- })
1492
- .catch((error) => {
1493
- this.#rLog.error({
1494
- msg: "wait until promise failed",
1495
- error: stringifyError(error),
1496
- });
1497
- });
1498
- this.#backgroundPromises.push(nonfailablePromise);
1499
- }
1500
-
1501
- #getEffectiveSleepGracePeriod(): number {
1502
- if (this.overrides.sleepGracePeriod !== undefined) {
1503
- return Math.min(
1504
- this.#config.options.sleepGracePeriod,
1505
- this.overrides.sleepGracePeriod,
1506
- );
1507
- }
1508
- return this.#config.options.sleepGracePeriod;
1509
- }
1510
-
1511
- #beginActiveAsyncRegion(region: keyof ActiveAsyncRegionCounts) {
1512
- this.#activeAsyncRegionCounts[region]++;
1513
- this.resetSleepTimer();
1514
- }
1515
-
1516
- #endActiveAsyncRegion(region: keyof ActiveAsyncRegionCounts) {
1517
- this.#activeAsyncRegionCounts[region]--;
1518
- if (this.#activeAsyncRegionCounts[region] < 0) {
1519
- this.#activeAsyncRegionCounts[region] = 0;
1520
- this.#rLog.warn({
1521
- msg: ACTIVE_ASYNC_REGION_ERROR_MESSAGES[region],
1522
- ...EXTRA_ERROR_LOG,
1523
- });
1524
- }
1525
-
1526
- this.resetSleepTimer();
1527
- }
1528
-
1529
- #trackWebSocketCallback(eventType: string, promise: Promise<void>) {
1530
- this.#beginActiveAsyncRegion("websocketCallbacks");
1531
-
1532
- const trackedPromise = promise
1533
- .then(() => {
1534
- this.#rLog.debug({
1535
- msg: "websocket callback complete",
1536
- eventType,
1537
- });
1538
- })
1539
- .catch((error) => {
1540
- this.#rLog.error({
1541
- msg: "websocket callback failed",
1542
- eventType,
1543
- error: stringifyError(error),
1544
- });
1545
- })
1546
- .finally(() => {
1547
- this.#endActiveAsyncRegion("websocketCallbacks");
1548
- });
1549
-
1550
- this.#websocketCallbackPromises.push(trackedPromise);
1551
- }
1552
-
1553
- /**
1554
- * Prevents the actor from sleeping while the given promise is running.
1555
- *
1556
- * Use this when performing async operations in the `run` handler or other
1557
- * background contexts where you need to ensure the actor stays awake.
1558
- *
1559
- * Returns the resolved value and resets the sleep timer on completion.
1560
- * Errors are propagated to the caller.
1561
- *
1562
- * @deprecated Use `setPreventSleep(true)` while work is active, or move
1563
- * shutdown and flush work to `onSleep` if it can wait until the actor is
1564
- * sleeping.
1565
- */
1566
- async keepAwake<T>(promise: Promise<T>): Promise<T> {
1567
- this.assertNotShutdown();
1568
-
1569
- this.#beginActiveAsyncRegion("keepAwake");
1570
-
1571
- try {
1572
- return await promise;
1573
- } finally {
1574
- this.#endActiveAsyncRegion("keepAwake");
1575
- }
1576
- }
1577
-
1578
- /**
1579
- * Internal sleep blocker used by runtime subsystems.
1580
- *
1581
- * Accepts either a promise or a thunk. The thunk form exists so the actor
1582
- * can enter the sleep-blocking region before user code starts running. This
1583
- * avoids a race where work begins, but the actor is not yet marked active,
1584
- * which can allow the sleep timer to fire underneath that work.
1585
- */
1586
- internalKeepAwake<T>(promise: Promise<T>): Promise<T>;
1587
- internalKeepAwake<T>(run: () => T | Promise<T>): Promise<T>;
1588
- async internalKeepAwake<T>(
1589
- promiseOrRun: Promise<T> | (() => T | Promise<T>),
1590
- ): Promise<T> {
1591
- this.assertNotShutdown();
1592
-
1593
- this.#beginActiveAsyncRegion("internalKeepAwake");
1594
-
1595
- try {
1596
- if (typeof promiseOrRun === "function") {
1597
- return await promiseOrRun();
1598
- }
1599
- return await promiseOrRun;
1600
- } finally {
1601
- this.#endActiveAsyncRegion("internalKeepAwake");
1602
- }
1603
- }
1604
-
1605
- setPreventSleep(prevent: boolean) {
1606
- if (this.#preventSleep === prevent) return;
1607
-
1608
- this.#preventSleep = prevent;
1609
- if (!prevent) {
1610
- this.#preventSleepClearedPromise?.resolve();
1611
- this.#preventSleepClearedPromise = undefined;
1612
- }
1613
- this.#rLog.debug({
1614
- msg: "updated prevent sleep state",
1615
- prevent,
1616
- });
1617
- this.resetSleepTimer();
1618
- }
1619
-
1620
- beginQueueWait() {
1621
- this.assertReady();
1622
- this.#activeQueueWaitCount++;
1623
- this.resetSleepTimer();
1624
- }
1625
-
1626
- endQueueWait() {
1627
- this.#activeQueueWaitCount--;
1628
- if (this.#activeQueueWaitCount < 0) {
1629
- this.#activeQueueWaitCount = 0;
1630
- this.#rLog.warn({
1631
- msg: "active queue wait count went below 0, this is a RivetKit bug",
1632
- ...EXTRA_ERROR_LOG,
1633
- });
1634
- }
1635
- this.resetSleepTimer();
1636
- }
1637
-
1638
- // MARK: - Private Helper Methods
1639
- #initializeTraces() {
1640
- if (getRivetExperimentalOtel()) {
1641
- // Experimental mode persists trace data to actor storage so inspector
1642
- // queries can return OTel payloads.
1643
- this.#traces = createTraces({
1644
- driver: new ActorTracesDriver(this.driver, this.#actorId),
1645
- });
1646
- } else {
1647
- // Keep the tracing API calls active while disabling trace persistence
1648
- // until the experimental flag is enabled.
1649
- this.#traces = createNoopTraces();
1650
- }
1651
- }
1652
-
1653
- #traceAttributes(
1654
- attributes?: Record<string, unknown>,
1655
- ): Record<string, unknown> {
1656
- return {
1657
- "rivet.actor.id": this.#actorId,
1658
- "rivet.actor.name": this.#name,
1659
- "rivet.actor.key": this.#actorKeyString,
1660
- "rivet.actor.region": this.#region,
1661
- ...(attributes ?? {}),
1662
- };
1663
- }
1664
-
1665
- #patchLoggerForTraces(logger: Logger) {
1666
- const levels: Array<
1667
- "trace" | "debug" | "info" | "warn" | "error" | "fatal"
1668
- > = ["trace", "debug", "info", "warn", "error", "fatal"];
1669
- for (const level of levels) {
1670
- const original = logger[level].bind(logger) as (
1671
- ...args: any[]
1672
- ) => unknown;
1673
- logger[level] = ((...args: unknown[]) => {
1674
- this.#emitLogEvent(level, args);
1675
- return original(...(args as any[]));
1676
- }) as Logger[typeof level];
1677
- }
1678
- }
1679
-
1680
- #emitLogEvent(level: string, args: unknown[]) {
1681
- const span = this.#traces.getCurrentSpan();
1682
- if (!span || !span.isActive()) {
1683
- return;
1684
- }
1685
-
1686
- let message: string | undefined;
1687
- if (args.length >= 2) {
1688
- message = String(args[1]);
1689
- } else if (args.length === 1) {
1690
- const [value] = args;
1691
- if (typeof value === "string") {
1692
- message = value;
1693
- } else if (
1694
- typeof value === "number" ||
1695
- typeof value === "boolean"
1696
- ) {
1697
- message = String(value);
1698
- } else if (value && typeof value === "object") {
1699
- const maybeMsg = (value as { msg?: unknown }).msg;
1700
- if (maybeMsg !== undefined) {
1701
- message = String(maybeMsg);
1702
- }
1703
- }
1704
- }
1705
-
1706
- this.#traces.emitEvent(span, "log", {
1707
- attributes: this.#traceAttributes({
1708
- "log.level": level,
1709
- ...(message ? { "log.message": message } : {}),
1710
- }),
1711
- timeUnixMs: Date.now(),
1712
- });
1713
- }
1714
-
1715
- #initializeLogging() {
1716
- const logParams = {
1717
- actor: this.#name,
1718
- key: this.#actorKeyString,
1719
- actorId: this.#actorId,
1720
- };
1721
-
1722
- const extraLogParams = this.driver.getExtraActorLogParams?.();
1723
- if (extraLogParams) Object.assign(logParams, extraLogParams);
1724
-
1725
- this.#log = getBaseLogger().child(
1726
- Object.assign(
1727
- getIncludeTarget() ? { target: "actor" } : {},
1728
- logParams,
1729
- ),
1730
- );
1731
- this.#rLog = getBaseLogger().child(
1732
- Object.assign(
1733
- getIncludeTarget() ? { target: "actor-runtime" } : {},
1734
- logParams,
1735
- ),
1736
- );
1737
-
1738
- this.#patchLoggerForTraces(this.#log);
1739
- this.#patchLoggerForTraces(this.#rLog);
1740
- }
1741
-
1742
- async #loadState(preload?: PreloadMap, writeCollector?: WriteCollector) {
1743
- let persistDataBuffer: Uint8Array | null;
1744
- const preloaded = preload?.get(KEYS.PERSIST_DATA);
1745
- if (preloaded) {
1746
- persistDataBuffer = preloaded.value;
1747
- } else {
1748
- this[WARN_UNEXPECTED_KV_ROUND_TRIP]("kvBatchGet");
1749
- this.#metrics.startup.kvRoundTrips++;
1750
- const [buf] = await this.driver.kvBatchGet(this.#actorId, [
1751
- KEYS.PERSIST_DATA,
1752
- ]);
1753
- persistDataBuffer = buf;
1754
- }
1755
-
1756
- invariant(
1757
- persistDataBuffer !== null,
1758
- "persist data has not been set, it should be set when initialized",
1759
- );
1760
-
1761
- const bareData =
1762
- ACTOR_VERSIONED.deserializeWithEmbeddedVersion(persistDataBuffer);
1763
- const persistData = convertActorFromBarePersisted<S, I>(bareData);
1764
-
1765
- if (persistData.hasInitialized) {
1766
- await this.#measureStartup("restoreConnectionsMs", () =>
1767
- this.#restoreExistingActor(persistData, preload),
1768
- );
1769
- } else {
1770
- this.#metrics.startup.isNew = true;
1771
- await this.#createNewActor(persistData, writeCollector);
1772
- }
1773
-
1774
- // Pass persist reference to schedule manager
1775
- this.#scheduleManager.setPersist(this.stateManager.persist);
1776
- }
1777
-
1778
- async #createNewActor(
1779
- persistData: PersistedActor<S, I>,
1780
- writeCollector?: WriteCollector,
1781
- ) {
1782
- this.#rLog.info({ msg: "actor creating" });
1783
-
1784
- // Initialize state
1785
- await this.#measureStartup("createStateMs", () =>
1786
- this.stateManager.initializeState(persistData, writeCollector),
1787
- );
1788
-
1789
- // Call onCreate lifecycle
1790
- if (this.#config.onCreate) {
1791
- const onCreate = this.#config.onCreate;
1792
- await this.#measureStartup(
1793
- "onCreateMs",
1794
- () =>
1795
- this.runInTraceSpan("actor.onCreate", undefined, () =>
1796
- onCreate(this.actorContext as any, persistData.input!),
1797
- ),
1798
- { pauseKvGuard: true },
1799
- );
1800
- }
1801
- }
1802
-
1803
- async #restoreExistingActor(
1804
- persistData: PersistedActor<S, I>,
1805
- preload?: PreloadMap,
1806
- ) {
1807
- let connEntries: [Uint8Array, Uint8Array][];
1808
- const preloadedConns = preload?.listPrefix(KEYS.CONN_PREFIX);
1809
- if (preloadedConns !== undefined) {
1810
- connEntries = preloadedConns;
1811
- } else {
1812
- this[WARN_UNEXPECTED_KV_ROUND_TRIP]("kvListPrefix");
1813
- this.#metrics.startup.kvRoundTrips++;
1814
- connEntries = await this.driver.kvListPrefix(
1815
- this.#actorId,
1816
- KEYS.CONN_PREFIX,
1817
- );
1818
- }
1819
-
1820
- // Decode connections
1821
- const connections: PersistedConn<CP, CS>[] = [];
1822
- for (const [_key, value] of connEntries) {
1823
- try {
1824
- const bareData = CONN_VERSIONED.deserializeWithEmbeddedVersion(
1825
- new Uint8Array(value),
1826
- );
1827
- const conn = convertConnFromBarePersistedConn<CP, CS>(bareData);
1828
- connections.push(conn);
1829
- } catch (error) {
1830
- this.#rLog.error({
1831
- msg: "failed to decode connection",
1832
- error: stringifyError(error),
1833
- });
1834
- }
1835
- }
1836
-
1837
- this.#metrics.startup.restoreConnectionsCount = connections.length;
1838
- this.#rLog.info({
1839
- msg: "actor restoring",
1840
- connections: connections.length,
1841
- });
1842
-
1843
- // Initialize state
1844
- this.stateManager.initPersistProxy(persistData);
1845
-
1846
- // Restore connections
1847
- this.connectionManager.restoreConnections(connections);
1848
- }
1849
-
1850
- async #initializeInspectorToken(
1851
- preload?: PreloadMap,
1852
- writeCollector?: WriteCollector,
1853
- ) {
1854
- let tokenBuffer: Uint8Array | null;
1855
- const preloaded = preload?.get(KEYS.INSPECTOR_TOKEN);
1856
- if (preloaded) {
1857
- tokenBuffer = preloaded.value;
1858
- } else {
1859
- this[WARN_UNEXPECTED_KV_ROUND_TRIP]("kvBatchGet");
1860
- this.#metrics.startup.kvRoundTrips++;
1861
- const [buf] = await this.driver.kvBatchGet(this.#actorId, [
1862
- KEYS.INSPECTOR_TOKEN,
1863
- ]);
1864
- tokenBuffer = buf;
1865
- }
1866
-
1867
- if (tokenBuffer !== null) {
1868
- const decoder = new TextDecoder();
1869
- this.#inspectorToken = decoder.decode(tokenBuffer);
1870
- this.#rLog.debug({ msg: "loaded existing inspector token" });
1871
- } else {
1872
- this.#inspectorToken = generateSecureToken();
1873
- const tokenBytes = new TextEncoder().encode(this.#inspectorToken);
1874
- if (writeCollector) {
1875
- writeCollector.add(KEYS.INSPECTOR_TOKEN, tokenBytes);
1876
- } else {
1877
- this.#metrics.startup.kvRoundTrips++;
1878
- await this.driver.kvBatchPut(this.#actorId, [
1879
- [KEYS.INSPECTOR_TOKEN, tokenBytes],
1880
- ]);
1881
- }
1882
- this.#rLog.debug({ msg: "generated new inspector token" });
1883
- }
1884
- }
1885
-
1886
- async #initializeVars() {
1887
- let vars: V | undefined;
1888
- if ("createVars" in this.#config) {
1889
- const createVars = this.#config.createVars;
1890
- vars = await this.runInTraceSpan(
1891
- "actor.createVars",
1892
- undefined,
1893
- () => {
1894
- const dataOrPromise = createVars!(
1895
- this.actorContext as any,
1896
- this.driver.getContext(this.#actorId),
1897
- );
1898
- if (dataOrPromise instanceof Promise) {
1899
- return deadline(
1900
- dataOrPromise,
1901
- this.#config.options.createVarsTimeout,
1902
- );
1903
- }
1904
- return dataOrPromise;
1905
- },
1906
- );
1907
- } else if ("vars" in this.#config) {
1908
- vars = structuredClone(this.#config.vars);
1909
- } else {
1910
- throw new Error(
1911
- "Could not create variables from 'createVars' or 'vars'",
1912
- );
1913
- }
1914
- this.#vars = vars;
1915
- }
1916
-
1917
- async #callOnStart() {
1918
- this.#rLog.info({ msg: "actor starting" });
1919
- if (this.#config.onWake) {
1920
- const onWake = this.#config.onWake;
1921
- await this.runInTraceSpan("actor.onWake", undefined, () =>
1922
- onWake(this.actorContext),
1923
- );
1924
- }
1925
- }
1926
-
1927
- async #callOnSleep(deadlineTs: number) {
1928
- if (this.#config.onSleep) {
1929
- const onSleep = this.#config.onSleep;
1930
- try {
1931
- this.#rLog.debug({ msg: "calling onSleep" });
1932
- await this.runInTraceSpan(
1933
- "actor.onSleep",
1934
- undefined,
1935
- async () => {
1936
- const result = onSleep(this.actorContext);
1937
- if (result instanceof Promise) {
1938
- const remaining = deadlineTs - Date.now();
1939
- if (remaining <= 0) {
1940
- throw new DeadlineError();
1941
- }
1942
- await deadline(result, remaining);
1943
- }
1944
- },
1945
- );
1946
- this.#rLog.debug({ msg: "onSleep completed" });
1947
- } catch (error) {
1948
- if (error instanceof DeadlineError) {
1949
- this.#rLog.error({ msg: "onSleep timed out" });
1950
- } else {
1951
- this.#rLog.error({
1952
- msg: "error in onSleep",
1953
- error: stringifyError(error),
1954
- });
1955
- }
1956
- }
1957
- }
1958
- }
1959
-
1960
- async #callOnDestroy(deadlineTs: number) {
1961
- if (this.#config.onDestroy) {
1962
- const onDestroy = this.#config.onDestroy;
1963
- try {
1964
- this.#rLog.debug({ msg: "calling onDestroy" });
1965
- await this.runInTraceSpan(
1966
- "actor.onDestroy",
1967
- undefined,
1968
- async () => {
1969
- const result = onDestroy(this.actorContext);
1970
- if (result instanceof Promise) {
1971
- const remaining = deadlineTs - Date.now();
1972
- if (remaining <= 0) {
1973
- throw new DeadlineError();
1974
- }
1975
- await deadline(result, remaining);
1976
- }
1977
- },
1978
- );
1979
- this.#rLog.debug({ msg: "onDestroy completed" });
1980
- } catch (error) {
1981
- if (error instanceof DeadlineError) {
1982
- this.#rLog.error({ msg: "onDestroy timed out" });
1983
- } else {
1984
- this.#rLog.error({
1985
- msg: "error in onDestroy",
1986
- error: stringifyError(error),
1987
- });
1988
- }
1989
- }
1990
- }
1991
- }
1992
-
1993
- #startRunHandler() {
1994
- const runFn = getRunFunction(this.#config.run);
1995
- if (!runFn) return;
1996
-
1997
- this.#rLog.debug({ msg: "starting run handler" });
1998
- this.#runHandlerActive = true;
1999
- this.resetSleepTimer();
2000
-
2001
- const runSpan = this.startTraceSpan("actor.run");
2002
- const runResult = this.#traces.withSpan(runSpan, () =>
2003
- runFn(this.actorContext),
2004
- );
2005
-
2006
- // Do not destroy or immediately sleep the actor when run exits. Finished
2007
- // workflows must stay inspectable when something goes wrong, and callers
2008
- // may still need to invoke actions after the run handler has completed.
2009
- if (runResult instanceof Promise) {
2010
- this.#runPromise = runResult
2011
- .then(() => {
2012
- if (this.#stopCalled) {
2013
- if (runSpan.isActive()) {
2014
- this.endTraceSpan(runSpan, { code: "OK" });
2015
- }
2016
- this.#rLog.debug({
2017
- msg: "run handler exited during actor stop",
2018
- });
2019
- return;
2020
- }
2021
-
2022
- if (runSpan.isActive()) {
2023
- this.endTraceSpan(runSpan, { code: "OK" });
2024
- }
2025
- this.#rLog.info({
2026
- msg: "run handler exited",
2027
- });
2028
- })
2029
- .catch((error) => {
2030
- if (this.#stopCalled) {
2031
- if (runSpan.isActive()) {
2032
- this.endTraceSpan(runSpan, { code: "OK" });
2033
- }
2034
- this.#rLog.debug({
2035
- msg: "run handler threw during actor stop",
2036
- error: stringifyError(error),
2037
- });
2038
- return;
2039
- }
2040
-
2041
- this.endTraceSpan(runSpan, {
2042
- code: "ERROR",
2043
- message: stringifyError(error),
2044
- });
2045
- this.#rLog.error({
2046
- msg: "run handler threw error",
2047
- error: stringifyError(error),
2048
- });
2049
- })
2050
- .finally(() => {
2051
- this.#runHandlerActive = false;
2052
- this.resetSleepTimer();
2053
- });
2054
- } else if (runSpan.isActive()) {
2055
- this.endTraceSpan(runSpan, { code: "OK" });
2056
- this.#rLog.info({
2057
- msg: "run handler exited",
2058
- });
2059
- this.#runHandlerActive = false;
2060
- this.resetSleepTimer();
2061
- }
2062
- }
2063
-
2064
- async #waitForRunHandler(timeoutMs: number) {
2065
- if (!this.#runPromise) {
2066
- return;
2067
- }
2068
-
2069
- this.#rLog.debug({ msg: "waiting for run handler to complete" });
2070
-
2071
- if (timeoutMs <= 0) {
2072
- this.#rLog.warn({
2073
- msg: "run handler did not complete in time, it may have leaked - ensure you use c.aborted (or the abort signal c.abortSignal) to exit gracefully",
2074
- timeoutMs,
2075
- });
2076
- return;
2077
- }
2078
-
2079
- const timedOut = await Promise.race([
2080
- this.#runPromise.then(() => false).catch(() => false),
2081
- new Promise<true>((resolve) =>
2082
- setTimeout(() => resolve(true), timeoutMs),
2083
- ),
2084
- ]);
2085
-
2086
- if (timedOut) {
2087
- this.#rLog.warn({
2088
- msg: "run handler did not complete in time, it may have leaked - ensure you use c.aborted (or the abort signal c.abortSignal) to exit gracefully",
2089
- timeoutMs,
2090
- });
2091
- } else {
2092
- this.#rLog.debug({ msg: "run handler completed" });
2093
- }
2094
- }
2095
-
2096
- async #setupDatabase(preload?: PreloadMap) {
2097
- if (!("db" in this.#config) || !this.#config.db) {
2098
- return;
2099
- }
2100
-
2101
- const dbProvider = this.#config.db;
2102
-
2103
- let client: InferDatabaseClient<DB> | undefined;
2104
- try {
2105
- client = await this.#measureStartup("setupDatabaseClientMs", () =>
2106
- dbProvider.createClient({
2107
- actorId: this.#actorId,
2108
- overrideRawDatabaseClient: this.driver
2109
- .overrideRawDatabaseClient
2110
- ? () =>
2111
- this.driver.overrideRawDatabaseClient!(
2112
- this.#actorId,
2113
- )
2114
- : undefined,
2115
- overrideDrizzleDatabaseClient: this.driver
2116
- .overrideDrizzleDatabaseClient
2117
- ? () =>
2118
- this.driver.overrideDrizzleDatabaseClient!(
2119
- this.#actorId,
2120
- )
2121
- : undefined,
2122
- kv: {
2123
- batchPut: (entries: [Uint8Array, Uint8Array][]) =>
2124
- this.driver.kvBatchPut(this.#actorId, entries),
2125
- batchGet: (keys: Uint8Array[]) =>
2126
- this.driver.kvBatchGet(this.#actorId, keys),
2127
- batchDelete: (keys: Uint8Array[]) =>
2128
- this.driver.kvBatchDelete(this.#actorId, keys),
2129
- deleteRange: (start: Uint8Array, end: Uint8Array) =>
2130
- this.driver.kvDeleteRange(
2131
- this.#actorId,
2132
- start,
2133
- end,
2134
- ),
2135
- },
2136
- metrics: this.#metrics,
2137
- log: this.#rLog,
2138
- nativeDatabaseProvider:
2139
- this.driver.getNativeDatabaseProvider?.(),
2140
- }),
2141
- );
2142
- this.#rLog.info({ msg: "database migration starting" });
2143
- await this.#measureStartup("dbMigrateMs", async () => {
2144
- await dbProvider.onMigrate?.(client!);
2145
- });
2146
- this.#rLog.info({ msg: "database migration complete" });
2147
- this.#db = client;
2148
- } catch (error) {
2149
- if (client) {
2150
- try {
2151
- await client.close();
2152
- } catch (cleanupError) {
2153
- this.#rLog.error({
2154
- msg: "database setup cleanup failed",
2155
- error: stringifyError(cleanupError),
2156
- });
2157
- }
2158
- }
2159
- if (error instanceof Error) {
2160
- this.#rLog.error({
2161
- msg: "database setup failed",
2162
- error: stringifyError(error),
2163
- });
2164
- throw error;
2165
- }
2166
- const wrappedError = new Error(
2167
- `Database setup failed: ${String(error)}`,
2168
- );
2169
- this.#rLog.error({
2170
- msg: "database setup failed with non-Error object",
2171
- error: String(error),
2172
- errorType: typeof error,
2173
- });
2174
- throw wrappedError;
2175
- }
2176
- }
2177
-
2178
- async #cleanupDatabase() {
2179
- const client = this.#db;
2180
- const dbConfig = "db" in this.#config ? this.#config.db : undefined;
2181
- this.#db = undefined;
2182
-
2183
- if (client && dbConfig) {
2184
- try {
2185
- await client.close();
2186
- } catch (error) {
2187
- this.#rLog.error({
2188
- msg: "database cleanup failed",
2189
- error: stringifyError(error),
2190
- });
2191
- }
2192
- }
2193
- }
2194
-
2195
- async #disconnectConnections() {
2196
- const promises: Promise<unknown>[] = [];
2197
- this.#rLog.debug({
2198
- msg: "disconnecting connections on actor stop",
2199
- totalConns: this.connectionManager.connections.size,
2200
- });
2201
- for (const connection of this.connectionManager.connections.values()) {
2202
- this.#rLog.debug({
2203
- msg: "checking connection for disconnect",
2204
- connId: connection.id,
2205
- isHibernatable: connection.isHibernatable,
2206
- });
2207
- if (!connection.isHibernatable) {
2208
- this.#rLog.debug({
2209
- msg: "disconnecting non-hibernatable connection on actor stop",
2210
- connId: connection.id,
2211
- });
2212
- promises.push(connection.disconnect());
2213
- } else {
2214
- this.#rLog.debug({
2215
- msg: "preserving hibernatable connection on actor stop",
2216
- connId: connection.id,
2217
- });
2218
- }
2219
- }
2220
-
2221
- // Wait with timeout
2222
- let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
2223
- const res = await Promise.race([
2224
- Promise.all(promises).then(() => {
2225
- if (timeoutHandle !== undefined) clearTimeout(timeoutHandle);
2226
- return false;
2227
- }),
2228
- new Promise<boolean>((res) => {
2229
- timeoutHandle = globalThis.setTimeout(() => res(true), 1500);
2230
- }),
2231
- ]);
2232
-
2233
- if (res) {
2234
- this.#rLog.warn({
2235
- msg: "timed out waiting for connections to close, shutting down anyway",
2236
- });
2237
- }
2238
- }
2239
-
2240
- /**
2241
- * Drain shutdown blockers within the shared shutdown deadline.
2242
- *
2243
- * This method is intentionally called multiple times during shutdown so
2244
- * work created by earlier shutdown phases, such as async WebSocket close
2245
- * handlers or waitUntil calls they enqueue, is also drained before final
2246
- * persistence.
2247
- */
2248
- async #waitShutdownTasks(deadlineTs: number) {
2249
- while (
2250
- this.#backgroundPromises.length > 0 ||
2251
- this.#websocketCallbackPromises.length > 0 ||
2252
- this.#preventSleep
2253
- ) {
2254
- await this.#drainPromiseQueue(
2255
- this.#backgroundPromises,
2256
- "background tasks",
2257
- deadlineTs,
2258
- );
2259
- await this.#drainPromiseQueue(
2260
- this.#websocketCallbackPromises,
2261
- "websocket callbacks",
2262
- deadlineTs,
2263
- );
2264
- await this.#waitForPreventSleepClear(deadlineTs);
2265
-
2266
- if (deadlineTs - Date.now() <= 0) {
2267
- break;
2268
- }
2269
- }
2270
- }
2271
-
2272
- #sleepWindowBlocker():
2273
- | "activeHonoHttpRequests"
2274
- | "keepAwake"
2275
- | "internalKeepAwake"
2276
- | "pendingDisconnectCallbacks"
2277
- | null {
2278
- if (this.#activeHonoHttpRequests > 0) {
2279
- return "activeHonoHttpRequests";
2280
- }
2281
- if (this.#activeAsyncRegionCounts.keepAwake > 0) {
2282
- return "keepAwake";
2283
- }
2284
- if (this.#activeAsyncRegionCounts.internalKeepAwake > 0) {
2285
- return "internalKeepAwake";
2286
- }
2287
- if (this.connectionManager.pendingDisconnectCount > 0) {
2288
- return "pendingDisconnectCallbacks";
2289
- }
2290
- return null;
2291
- }
2292
-
2293
- async #waitForIdleSleepWindow(deadlineTs: number) {
2294
- while (true) {
2295
- const blocker = this.#sleepWindowBlocker();
2296
- if (!blocker) {
2297
- return;
2298
- }
2299
-
2300
- const remaining = deadlineTs - Date.now();
2301
- if (remaining <= 0) {
2302
- this.#rLog.warn({
2303
- msg: "timed out waiting for actor to become idle before onSleep",
2304
- blocker,
2305
- });
2306
- return;
2307
- }
2308
-
2309
- await new Promise<void>((resolve) =>
2310
- setTimeout(resolve, Math.min(25, remaining)),
2311
- );
2312
- }
2313
- }
2314
-
2315
- async #drainPromiseQueue(
2316
- promises: Promise<void>[],
2317
- label: string,
2318
- deadlineTs: number,
2319
- ) {
2320
- // Drain in a loop so that work scheduled from earlier callbacks is also
2321
- // awaited within the same deadline.
2322
- while (promises.length > 0) {
2323
- const remaining = deadlineTs - Date.now();
2324
- if (remaining <= 0) {
2325
- this.#rLog.error({
2326
- msg: `timed out waiting for ${label}`,
2327
- count: promises.length,
2328
- });
2329
- break;
2330
- }
2331
-
2332
- const batch = promises.length;
2333
-
2334
- let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
2335
- const timedOut = await Promise.race([
2336
- Promise.allSettled(promises.slice(0, batch)).then(() => {
2337
- if (timeoutHandle !== undefined)
2338
- clearTimeout(timeoutHandle);
2339
- return false;
2340
- }),
2341
- new Promise<true>((resolve) => {
2342
- timeoutHandle = setTimeout(() => resolve(true), remaining);
2343
- }),
2344
- ]);
2345
-
2346
- if (timedOut) {
2347
- this.#rLog.error({
2348
- msg: `timed out waiting for ${label}`,
2349
- count: promises.length,
2350
- });
2351
- break;
2352
- }
2353
-
2354
- promises.splice(0, batch);
2355
- }
2356
-
2357
- if (promises.length === 0) {
2358
- this.#rLog.debug({ msg: `${label} finished` });
2359
- }
2360
- }
2361
-
2362
- async #waitForPreventSleepClear(deadlineTs: number) {
2363
- while (this.#preventSleep) {
2364
- const remaining = deadlineTs - Date.now();
2365
- if (remaining <= 0) {
2366
- this.#rLog.error({
2367
- msg: "timed out waiting for preventSleep to clear during shutdown",
2368
- });
2369
- break;
2370
- }
2371
-
2372
- if (!this.#preventSleepClearedPromise) {
2373
- this.#preventSleepClearedPromise = promiseWithResolvers<void>(
2374
- (reason: unknown) =>
2375
- this.#rLog.warn({
2376
- msg: "preventSleep clear waiter rejected unexpectedly",
2377
- reason: stringifyError(reason),
2378
- ...EXTRA_ERROR_LOG,
2379
- }),
2380
- );
2381
- }
2382
-
2383
- let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
2384
- const timedOut = await Promise.race([
2385
- this.#preventSleepClearedPromise.promise.then(() => {
2386
- if (timeoutHandle !== undefined)
2387
- clearTimeout(timeoutHandle);
2388
- return false;
2389
- }),
2390
- new Promise<true>((resolve) => {
2391
- timeoutHandle = setTimeout(() => resolve(true), remaining);
2392
- }),
2393
- ]);
2394
-
2395
- if (timedOut) {
2396
- this.#rLog.error({
2397
- msg: "timed out waiting for preventSleep to clear during shutdown",
2398
- });
2399
- break;
2400
- }
2401
- }
2402
- }
2403
-
2404
- #createTrackedWebSocket(websocket: UniversalWebSocket): TrackedWebSocket {
2405
- return new TrackedWebSocket(websocket, {
2406
- onPromise: (eventType, promise) => {
2407
- this.#trackWebSocketCallback(eventType, promise);
2408
- },
2409
- onError: (eventType, error) => {
2410
- this.#rLog.error({
2411
- msg: "error in websocket event handler",
2412
- eventType,
2413
- error: stringifyError(error),
2414
- });
2415
- },
2416
- });
2417
- }
2418
-
2419
- resetSleepTimer() {
2420
- if (this.#config.options.noSleep || !this.#sleepingSupported) return;
2421
- if (this.#stopCalled) return;
2422
-
2423
- const canSleep = this.#canSleep();
2424
- let timeoutMs: number | undefined;
2425
-
2426
- if (canSleep === CanSleep.Yes) {
2427
- timeoutMs = this.#config.options.sleepTimeout;
2428
- }
2429
-
2430
- this.#rLog.debug({
2431
- msg: "resetting sleep timer",
2432
- canSleep: CanSleep[canSleep],
2433
- existingTimeout: !!this.#sleepTimeout,
2434
- timeout: timeoutMs,
2435
- });
2436
-
2437
- if (this.#sleepTimeout) {
2438
- clearTimeout(this.#sleepTimeout);
2439
- this.#sleepTimeout = undefined;
2440
- }
2441
-
2442
- if (this.#sleepCalled) return;
2443
-
2444
- if (timeoutMs !== undefined) {
2445
- this.#sleepTimeout = setTimeout(() => {
2446
- if (this.#canSleep() !== CanSleep.Yes) {
2447
- this.resetSleepTimer();
2448
- return;
2449
- }
2450
- this.startSleep();
2451
- }, timeoutMs);
2452
- }
2453
- }
2454
-
2455
- #canSleep(): CanSleep {
2456
- if (!this.#ready) return CanSleep.NotReady;
2457
- if (!this.#started) return CanSleep.NotReady;
2458
- if (this.#preventSleep) return CanSleep.PreventSleep;
2459
- if (this.#activeHonoHttpRequests > 0)
2460
- return CanSleep.ActiveHonoHttpRequests;
2461
- if (this.#activeAsyncRegionCounts.keepAwake > 0) {
2462
- return CanSleep.ActiveKeepAwake;
2463
- }
2464
- if (this.#activeAsyncRegionCounts.internalKeepAwake > 0) {
2465
- return CanSleep.ActiveInternalKeepAwake;
2466
- }
2467
- if (this.#runHandlerActive && this.#activeQueueWaitCount === 0) {
2468
- return CanSleep.ActiveRun;
2469
- }
2470
-
2471
- for (const _conn of this.connectionManager.connections.values()) {
2472
- if (!_conn.isHibernatable) {
2473
- return CanSleep.ActiveConns;
2474
- }
2475
- }
2476
-
2477
- if (this.connectionManager.pendingDisconnectCount > 0) {
2478
- return CanSleep.ActiveDisconnectCallbacks;
2479
- }
2480
-
2481
- if (this.#activeAsyncRegionCounts.websocketCallbacks > 0) {
2482
- return CanSleep.ActiveWebSocketCallbacks;
2483
- }
2484
-
2485
- return CanSleep.Yes;
2486
- }
2487
-
2488
- get #sleepingSupported(): boolean {
2489
- return this.driver.startSleep !== undefined;
2490
- }
2491
-
2492
- get #varsEnabled(): boolean {
2493
- return "createVars" in this.#config || "vars" in this.#config;
2494
- }
2495
-
2496
- #validateVarsEnabled() {
2497
- if (!this.#varsEnabled) {
2498
- throw new errors.VarsNotEnabled();
2499
- }
2500
- }
2501
- }