rivetkit 2.0.22-rc.1 → 2.0.22

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 (124) hide show
  1. package/dist/schemas/actor-persist/v2.ts +259 -0
  2. package/dist/tsup/{chunk-LCQDY73V.cjs → chunk-2GJILCGQ.cjs} +3 -3
  3. package/dist/tsup/{chunk-LCQDY73V.cjs.map → chunk-2GJILCGQ.cjs.map} +1 -1
  4. package/dist/tsup/{chunk-JN6GPVFY.js → chunk-2K2LR56Q.js} +3 -3
  5. package/dist/tsup/{chunk-EEXX243L.js → chunk-2WVCZCJL.js} +6 -6
  6. package/dist/tsup/{chunk-FETQGZN4.js → chunk-3BJJSSTM.js} +272 -89
  7. package/dist/tsup/chunk-3BJJSSTM.js.map +1 -0
  8. package/dist/tsup/{chunk-ZZYMCYAY.cjs → chunk-3LFMVAJV.cjs} +14 -14
  9. package/dist/tsup/{chunk-ZZYMCYAY.cjs.map → chunk-3LFMVAJV.cjs.map} +1 -1
  10. package/dist/tsup/{chunk-NDLOG2JH.js → chunk-6YQKMAMV.js} +2 -2
  11. package/dist/tsup/{chunk-C2U6KGOG.cjs → chunk-AR4S2QJ7.cjs} +3 -3
  12. package/dist/tsup/{chunk-C2U6KGOG.cjs.map → chunk-AR4S2QJ7.cjs.map} +1 -1
  13. package/dist/tsup/{chunk-PELXJCJS.cjs → chunk-B4QZKOMH.cjs} +8 -8
  14. package/dist/tsup/{chunk-PELXJCJS.cjs.map → chunk-B4QZKOMH.cjs.map} +1 -1
  15. package/dist/tsup/{chunk-5EB77IQ2.cjs → chunk-CYA35VI3.cjs} +6 -6
  16. package/dist/tsup/{chunk-5EB77IQ2.cjs.map → chunk-CYA35VI3.cjs.map} +1 -1
  17. package/dist/tsup/{chunk-UBCUW7HD.js → chunk-D7AA2DK5.js} +2 -2
  18. package/dist/tsup/{chunk-I7EJWHYV.js → chunk-EBSGEDD3.js} +51 -47
  19. package/dist/tsup/chunk-EBSGEDD3.js.map +1 -0
  20. package/dist/tsup/{chunk-R6XOZKMU.cjs → chunk-HSO2H2SB.cjs} +467 -284
  21. package/dist/tsup/chunk-HSO2H2SB.cjs.map +1 -0
  22. package/dist/tsup/{chunk-VJLGVVGP.cjs → chunk-HZ4ZM3FL.cjs} +31 -12
  23. package/dist/tsup/chunk-HZ4ZM3FL.cjs.map +1 -0
  24. package/dist/tsup/{chunk-7FEMVD3D.cjs → chunk-LMZSOCYD.cjs} +12 -12
  25. package/dist/tsup/{chunk-7FEMVD3D.cjs.map → chunk-LMZSOCYD.cjs.map} +1 -1
  26. package/dist/tsup/{chunk-ZVEDMBFT.js → chunk-PBFLG45S.js} +3 -3
  27. package/dist/tsup/{chunk-GJPOIJHZ.js → chunk-ST6FGRCH.js} +26 -7
  28. package/dist/tsup/chunk-ST6FGRCH.js.map +1 -0
  29. package/dist/tsup/{chunk-BIOPK7IB.cjs → chunk-TI72NLP3.cjs} +71 -67
  30. package/dist/tsup/chunk-TI72NLP3.cjs.map +1 -0
  31. package/dist/tsup/{chunk-RPI45FGS.js → chunk-TQ4OAC2G.js} +2 -2
  32. package/dist/tsup/{chunk-4B25D5OW.js → chunk-UB4OHFDW.js} +385 -104
  33. package/dist/tsup/chunk-UB4OHFDW.js.map +1 -0
  34. package/dist/tsup/{chunk-6Z3YA6QR.cjs → chunk-V6C34TVH.cjs} +35 -15
  35. package/dist/tsup/chunk-V6C34TVH.cjs.map +1 -0
  36. package/dist/tsup/{chunk-OAB7ECAB.cjs → chunk-WVUAO2F7.cjs} +558 -277
  37. package/dist/tsup/chunk-WVUAO2F7.cjs.map +1 -0
  38. package/dist/tsup/{chunk-JKNDUKFI.js → chunk-WWAZJHTS.js} +36 -16
  39. package/dist/tsup/chunk-WWAZJHTS.js.map +1 -0
  40. package/dist/tsup/client/mod.cjs +9 -9
  41. package/dist/tsup/client/mod.d.cts +2 -2
  42. package/dist/tsup/client/mod.d.ts +2 -2
  43. package/dist/tsup/client/mod.js +8 -8
  44. package/dist/tsup/common/log.cjs +3 -3
  45. package/dist/tsup/common/log.js +2 -2
  46. package/dist/tsup/common/websocket.cjs +4 -4
  47. package/dist/tsup/common/websocket.js +3 -3
  48. package/dist/tsup/{conn-Clu655RU.d.ts → conn-BYXlxnh0.d.ts} +111 -102
  49. package/dist/tsup/{conn-lUvFLo_q.d.cts → conn-BiazosE_.d.cts} +111 -102
  50. package/dist/tsup/driver-helpers/mod.cjs +5 -5
  51. package/dist/tsup/driver-helpers/mod.d.cts +1 -1
  52. package/dist/tsup/driver-helpers/mod.d.ts +1 -1
  53. package/dist/tsup/driver-helpers/mod.js +4 -4
  54. package/dist/tsup/driver-test-suite/mod.cjs +71 -71
  55. package/dist/tsup/driver-test-suite/mod.d.cts +1 -1
  56. package/dist/tsup/driver-test-suite/mod.d.ts +1 -1
  57. package/dist/tsup/driver-test-suite/mod.js +11 -11
  58. package/dist/tsup/inspector/mod.cjs +6 -6
  59. package/dist/tsup/inspector/mod.d.cts +2 -2
  60. package/dist/tsup/inspector/mod.d.ts +2 -2
  61. package/dist/tsup/inspector/mod.js +5 -5
  62. package/dist/tsup/mod.cjs +10 -10
  63. package/dist/tsup/mod.d.cts +3 -3
  64. package/dist/tsup/mod.d.ts +3 -3
  65. package/dist/tsup/mod.js +9 -9
  66. package/dist/tsup/test/mod.cjs +11 -11
  67. package/dist/tsup/test/mod.d.cts +1 -1
  68. package/dist/tsup/test/mod.d.ts +1 -1
  69. package/dist/tsup/test/mod.js +10 -10
  70. package/dist/tsup/utils.cjs +8 -2
  71. package/dist/tsup/utils.cjs.map +1 -1
  72. package/dist/tsup/utils.d.cts +8 -1
  73. package/dist/tsup/utils.d.ts +8 -1
  74. package/dist/tsup/utils.js +7 -1
  75. package/package.json +5 -4
  76. package/src/actor/config.ts +10 -0
  77. package/src/actor/conn-drivers.ts +43 -1
  78. package/src/actor/conn-socket.ts +1 -1
  79. package/src/actor/conn.ts +22 -2
  80. package/src/actor/context.ts +1 -1
  81. package/src/actor/driver.ts +13 -2
  82. package/src/actor/instance.ts +248 -57
  83. package/src/actor/persisted.ts +7 -0
  84. package/src/actor/router-endpoints.ts +67 -45
  85. package/src/actor/router.ts +25 -17
  86. package/src/client/actor-conn.ts +9 -5
  87. package/src/common/cors.ts +57 -0
  88. package/src/common/log.ts +26 -5
  89. package/src/common/utils.ts +5 -9
  90. package/src/common/websocket-interface.ts +10 -0
  91. package/src/driver-helpers/utils.ts +1 -0
  92. package/src/drivers/engine/actor-driver.ts +261 -14
  93. package/src/drivers/engine/config.ts +2 -4
  94. package/src/drivers/file-system/actor.ts +3 -2
  95. package/src/drivers/file-system/global-state.ts +1 -1
  96. package/src/drivers/file-system/manager.ts +3 -0
  97. package/src/engine-process/mod.ts +22 -4
  98. package/src/inspector/config.ts +0 -45
  99. package/src/manager/gateway.ts +45 -32
  100. package/src/manager/hono-websocket-adapter.ts +31 -3
  101. package/src/manager/router.ts +11 -17
  102. package/src/registry/run-config.ts +2 -8
  103. package/src/remote-manager-driver/actor-http-client.ts +5 -8
  104. package/src/remote-manager-driver/actor-websocket-client.ts +2 -14
  105. package/src/remote-manager-driver/mod.ts +0 -1
  106. package/src/schemas/actor-persist/mod.ts +1 -1
  107. package/src/schemas/actor-persist/versioned.ts +22 -10
  108. package/src/utils.ts +26 -0
  109. package/dist/tsup/chunk-4B25D5OW.js.map +0 -1
  110. package/dist/tsup/chunk-6Z3YA6QR.cjs.map +0 -1
  111. package/dist/tsup/chunk-BIOPK7IB.cjs.map +0 -1
  112. package/dist/tsup/chunk-FETQGZN4.js.map +0 -1
  113. package/dist/tsup/chunk-GJPOIJHZ.js.map +0 -1
  114. package/dist/tsup/chunk-I7EJWHYV.js.map +0 -1
  115. package/dist/tsup/chunk-JKNDUKFI.js.map +0 -1
  116. package/dist/tsup/chunk-OAB7ECAB.cjs.map +0 -1
  117. package/dist/tsup/chunk-R6XOZKMU.cjs.map +0 -1
  118. package/dist/tsup/chunk-VJLGVVGP.cjs.map +0 -1
  119. /package/dist/tsup/{chunk-JN6GPVFY.js.map → chunk-2K2LR56Q.js.map} +0 -0
  120. /package/dist/tsup/{chunk-EEXX243L.js.map → chunk-2WVCZCJL.js.map} +0 -0
  121. /package/dist/tsup/{chunk-NDLOG2JH.js.map → chunk-6YQKMAMV.js.map} +0 -0
  122. /package/dist/tsup/{chunk-UBCUW7HD.js.map → chunk-D7AA2DK5.js.map} +0 -0
  123. /package/dist/tsup/{chunk-ZVEDMBFT.js.map → chunk-PBFLG45S.js.map} +0 -0
  124. /package/dist/tsup/{chunk-RPI45FGS.js.map → chunk-TQ4OAC2G.js.map} +0 -0
@@ -3,11 +3,11 @@ import {
3
3
  ForeignKeysSchema,
4
4
  PatchSchema,
5
5
  TablesSchema
6
- } from "./chunk-RPI45FGS.js";
6
+ } from "./chunk-TQ4OAC2G.js";
7
7
  import {
8
8
  importWebSocket,
9
9
  logger
10
- } from "./chunk-UBCUW7HD.js";
10
+ } from "./chunk-D7AA2DK5.js";
11
11
  import {
12
12
  ActionContext,
13
13
  HTTP_ACTION_REQUEST_VERSIONED,
@@ -18,7 +18,7 @@ import {
18
18
  TO_SERVER_VERSIONED,
19
19
  inputDataToBuffer,
20
20
  processMessage
21
- } from "./chunk-I7EJWHYV.js";
21
+ } from "./chunk-EBSGEDD3.js";
22
22
  import {
23
23
  CachedSerializer,
24
24
  DeadlineError,
@@ -26,18 +26,14 @@ import {
26
26
  HEADER_CONN_PARAMS,
27
27
  HEADER_CONN_TOKEN,
28
28
  HEADER_ENCODING,
29
- HEADER_RIVET_ACTOR,
30
- HEADER_RIVET_TARGET,
31
29
  HEADER_RIVET_TOKEN,
32
30
  PATH_CONNECT_WEBSOCKET,
33
31
  PATH_RAW_WEBSOCKET_PREFIX,
34
- WS_PROTOCOL_ACTOR,
35
32
  WS_PROTOCOL_CONN_ID,
36
33
  WS_PROTOCOL_CONN_PARAMS,
37
34
  WS_PROTOCOL_CONN_TOKEN,
38
35
  WS_PROTOCOL_ENCODING,
39
36
  WS_PROTOCOL_STANDARD,
40
- WS_PROTOCOL_TARGET,
41
37
  WS_PROTOCOL_TOKEN,
42
38
  assertUnreachable as assertUnreachable2,
43
39
  contentTypeForEncoding,
@@ -50,14 +46,16 @@ import {
50
46
  jsonStringifyCompat,
51
47
  serializeWithEncoding,
52
48
  uint8ArrayToBase64
53
- } from "./chunk-ZVEDMBFT.js";
49
+ } from "./chunk-PBFLG45S.js";
54
50
  import {
55
51
  getBaseLogger,
56
52
  getIncludeTarget,
57
53
  getLogger
58
- } from "./chunk-GJPOIJHZ.js";
54
+ } from "./chunk-ST6FGRCH.js";
59
55
  import {
56
+ EXTRA_ERROR_LOG,
60
57
  SinglePromiseQueue,
58
+ arrayBuffersEqual,
61
59
  assertUnreachable,
62
60
  bufferToArrayBuffer,
63
61
  combineUrlPath,
@@ -68,7 +66,7 @@ import {
68
66
  noopNext,
69
67
  promiseWithResolvers,
70
68
  stringifyError
71
- } from "./chunk-JKNDUKFI.js";
69
+ } from "./chunk-WWAZJHTS.js";
72
70
  import {
73
71
  ActionNotFound,
74
72
  ActionTimedOut,
@@ -89,7 +87,15 @@ import * as cbor from "cbor-x";
89
87
 
90
88
  // src/actor/conn-drivers.ts
91
89
  var WEBSOCKET_DRIVER = {
92
- sendMessage: (actor, _conn, state, message) => {
90
+ sendMessage: (actor, conn, state, message) => {
91
+ if (state.websocket.readyState !== 1 /* OPEN */) {
92
+ actor.rLog.warn({
93
+ msg: "attempting to send message to closed websocket, this is likely a bug in RivetKit",
94
+ connId: conn.id,
95
+ wsReadyState: state.websocket.readyState
96
+ });
97
+ return;
98
+ }
93
99
  const serialized = message.serialize(state.encoding);
94
100
  actor.rLog.debug({
95
101
  msg: "sending websocket message",
@@ -133,6 +139,15 @@ var WEBSOCKET_DRIVER = {
133
139
  },
134
140
  getConnectionReadyState: (_actor, _conn, state) => {
135
141
  return state.websocket.readyState;
142
+ },
143
+ isHibernatable(_actor, _conn, state) {
144
+ if (state.websocket.raw) {
145
+ const raw = state.websocket.raw;
146
+ if (typeof raw.isHibernatable === "boolean") {
147
+ return raw.isHibernatable;
148
+ }
149
+ }
150
+ return false;
136
151
  }
137
152
  };
138
153
  var SSE_DRIVER = {
@@ -149,6 +164,9 @@ var SSE_DRIVER = {
149
164
  return 3 /* CLOSED */;
150
165
  }
151
166
  return 1 /* OPEN */;
167
+ },
168
+ isHibernatable() {
169
+ return false;
152
170
  }
153
171
  };
154
172
  var HTTP_DRIVER = {
@@ -156,6 +174,9 @@ var HTTP_DRIVER = {
156
174
  return 1 /* OPEN */;
157
175
  },
158
176
  disconnect: async () => {
177
+ },
178
+ isHibernatable() {
179
+ return false;
159
180
  }
160
181
  };
161
182
  var CONN_DRIVERS = {
@@ -177,7 +198,7 @@ function generateConnId() {
177
198
  function generateConnToken() {
178
199
  return generateSecureToken(32);
179
200
  }
180
- function generateConnSocketId() {
201
+ function generateConnRequestId() {
181
202
  return crypto.randomUUID();
182
203
  }
183
204
  var Conn = class {
@@ -250,6 +271,24 @@ var Conn = class {
250
271
  get status() {
251
272
  return this.__status;
252
273
  }
274
+ /**
275
+ * @experimental
276
+ *
277
+ * If the underlying connection can hibernate.
278
+ */
279
+ get isHibernatable() {
280
+ if (this.__driverState) {
281
+ const driverKind = getConnDriverKindFromState(this.__driverState);
282
+ const driver = CONN_DRIVERS[driverKind];
283
+ return driver.isHibernatable(
284
+ this.#actor,
285
+ this,
286
+ this.__driverState[driverKind]
287
+ );
288
+ } else {
289
+ return false;
290
+ }
291
+ }
253
292
  /**
254
293
  * Timestamp of the last time the connection was seen, i.e. the last time the connection was active and checked for liveness.
255
294
  */
@@ -354,7 +393,7 @@ var Conn = class {
354
393
  conn: this.id
355
394
  });
356
395
  }
357
- this.#actor.__connDisconnected(this, true, this.__socket.socketId);
396
+ this.#actor.__connDisconnected(this, true, this.__socket.requestId);
358
397
  } else {
359
398
  this.#actor.rLog.warn({
360
399
  msg: "missing connection driver state for disconnect",
@@ -733,7 +772,7 @@ var ActorContext = class {
733
772
  * @experimental
734
773
  */
735
774
  sleep() {
736
- this.#actor._sleep();
775
+ this.#actor._startSleep();
737
776
  }
738
777
  };
739
778
 
@@ -810,6 +849,15 @@ var Schedule = class {
810
849
  };
811
850
 
812
851
  // src/actor/instance.ts
852
+ var PERSIST_SYMBOL = Symbol("persist");
853
+ var CanSleep = /* @__PURE__ */ ((CanSleep2) => {
854
+ CanSleep2[CanSleep2["Yes"] = 0] = "Yes";
855
+ CanSleep2[CanSleep2["NotReady"] = 1] = "NotReady";
856
+ CanSleep2[CanSleep2["ActiveConns"] = 2] = "ActiveConns";
857
+ CanSleep2[CanSleep2["ActiveHonoHttpRequests"] = 3] = "ActiveHonoHttpRequests";
858
+ CanSleep2[CanSleep2["ActiveRawWebSockets"] = 4] = "ActiveRawWebSockets";
859
+ return CanSleep2;
860
+ })(CanSleep || {});
813
861
  var ActorInstance = class {
814
862
  // Shared actor context for this instance
815
863
  actorContext;
@@ -820,7 +868,7 @@ var ActorInstance = class {
820
868
  #sleepCalled = false;
821
869
  #stopCalled = false;
822
870
  get isStopping() {
823
- return this.#stopCalled || this.#sleepCalled;
871
+ return this.#stopCalled;
824
872
  }
825
873
  #persistChanged = false;
826
874
  #isInOnStateChange = false;
@@ -830,6 +878,9 @@ var ActorInstance = class {
830
878
  * Any data that should be stored indefinitely should be held within this object.
831
879
  */
832
880
  #persist;
881
+ get [PERSIST_SYMBOL]() {
882
+ return this.#persist;
883
+ }
833
884
  /** Raw state without the proxy wrapper */
834
885
  #persistRaw;
835
886
  #persistWriteQueue = new SinglePromiseQueue();
@@ -851,8 +902,11 @@ var ActorInstance = class {
851
902
  #subscriptionIndex = /* @__PURE__ */ new Map();
852
903
  #checkConnLivenessInterval;
853
904
  #sleepTimeout;
854
- // Track active raw requests so sleep logic can account for them
855
- #activeRawFetchCount = 0;
905
+ /**
906
+ * Track active HTTP requests through Hono router so sleep logic can
907
+ * account for them. Does not include WebSockets.
908
+ **/
909
+ #activeHonoHttpRequests = 0;
856
910
  #activeRawWebSockets = /* @__PURE__ */ new Set();
857
911
  #schedule;
858
912
  #db;
@@ -876,12 +930,21 @@ var ActorInstance = class {
876
930
  },
877
931
  getConnections: async () => {
878
932
  return Array.from(this.#connections.entries()).map(
879
- ([id, conn]) => ({
880
- id,
881
- stateEnabled: conn.__stateEnabled,
882
- params: conn.params,
883
- state: conn.__stateEnabled ? conn.state : void 0
884
- })
933
+ ([id, conn]) => {
934
+ var _a;
935
+ return {
936
+ id,
937
+ params: conn.params,
938
+ state: conn.__stateEnabled ? conn.state : void 0,
939
+ status: conn.status,
940
+ subscriptions: conn.subscriptions.size,
941
+ lastSeen: conn.lastSeen,
942
+ stateEnabled: conn.__stateEnabled,
943
+ isHibernatable: conn.isHibernatable,
944
+ requestId: (_a = conn.__socket) == null ? void 0 : _a.requestId,
945
+ driver: conn.__driverState ? getConnDriverKindFromState(conn.__driverState) : void 0
946
+ };
947
+ }
885
948
  );
886
949
  },
887
950
  setState: async (state) => {
@@ -890,10 +953,10 @@ var ActorInstance = class {
890
953
  await this.saveState({ immediate: true });
891
954
  },
892
955
  executeAction: async (name, params) => {
893
- const socketId = generateConnSocketId();
956
+ const requestId = generateConnRequestId();
894
957
  const conn = await this.createConn(
895
958
  {
896
- socketId,
959
+ requestId,
897
960
  driverState: { [2 /* HTTP */]: {} }
898
961
  },
899
962
  void 0,
@@ -906,7 +969,7 @@ var ActorInstance = class {
906
969
  params || []
907
970
  );
908
971
  } finally {
909
- this.__connDisconnected(conn, true, socketId);
972
+ this.__connDisconnected(conn, true, requestId);
910
973
  }
911
974
  }
912
975
  };
@@ -921,7 +984,7 @@ var ActorInstance = class {
921
984
  return this.#inspector;
922
985
  }
923
986
  get #sleepingSupported() {
924
- return this.#actorDriver.sleep !== void 0;
987
+ return this.#actorDriver.startSleep !== void 0;
925
988
  }
926
989
  /**
927
990
  * This constructor should never be used directly.
@@ -935,12 +998,14 @@ var ActorInstance = class {
935
998
  this.actorContext = new ActorContext(this);
936
999
  }
937
1000
  async start(actorDriver, inlineClient, actorId, name, key, region) {
938
- var _a, _b;
1001
+ var _a, _b, _c;
939
1002
  const logParams = {
940
1003
  actor: name,
941
1004
  key: serializeActorKey(key),
942
1005
  actorId
943
1006
  };
1007
+ const extraLogParams = (_a = actorDriver.getExtraActorLogParams) == null ? void 0 : _a.call(actorDriver);
1008
+ if (extraLogParams) Object.assign(logParams, extraLogParams);
944
1009
  this.#log = getBaseLogger().child(
945
1010
  Object.assign(
946
1011
  getIncludeTarget() ? { target: "actor" } : {},
@@ -997,7 +1062,7 @@ var ActorInstance = class {
997
1062
  getDatabase: () => actorDriver.getDatabase(this.#actorId)
998
1063
  });
999
1064
  this.#rLog.info({ msg: "database migration starting" });
1000
- await ((_b = (_a = this.#config.db).onMigrate) == null ? void 0 : _b.call(_a, client));
1065
+ await ((_c = (_b = this.#config.db).onMigrate) == null ? void 0 : _c.call(_b, client));
1001
1066
  this.#rLog.info({ msg: "database migration complete" });
1002
1067
  this.#db = client;
1003
1068
  }
@@ -1344,13 +1409,13 @@ var ActorInstance = class {
1344
1409
  *
1345
1410
  * If not a clean disconnect, will keep the connection alive for a given interval to wait for reconnect.
1346
1411
  */
1347
- __connDisconnected(conn, wasClean, socketId) {
1348
- if (socketId && conn.__socket && socketId !== conn.__socket.socketId) {
1412
+ __connDisconnected(conn, wasClean, requestId) {
1413
+ if (requestId && conn.__socket && requestId !== conn.__socket.requestId) {
1349
1414
  this.#rLog.debug({
1350
1415
  msg: "ignoring stale disconnect event",
1351
1416
  connId: conn.id,
1352
- eventSocketId: socketId,
1353
- currentSocketId: conn.__socket.socketId
1417
+ eventRequestId: requestId,
1418
+ currentRequestId: conn.__socket.requestId
1354
1419
  });
1355
1420
  return;
1356
1421
  }
@@ -1644,8 +1709,6 @@ var ActorInstance = class {
1644
1709
  }
1645
1710
  #assertReady(allowStoppingState = false) {
1646
1711
  if (!this.#ready) throw new InternalError("Actor not ready");
1647
- if (!allowStoppingState && this.#sleepCalled)
1648
- throw new InternalError("Actor is going to sleep");
1649
1712
  if (!allowStoppingState && this.#stopCalled)
1650
1713
  throw new InternalError("Actor is stopping");
1651
1714
  }
@@ -1655,13 +1718,18 @@ var ActorInstance = class {
1655
1718
  */
1656
1719
  #checkConnectionsLiveness() {
1657
1720
  this.#rLog.debug({ msg: "checking connections liveness" });
1721
+ let connected = 0;
1722
+ let reconnecting = 0;
1723
+ let removed = 0;
1658
1724
  for (const conn of this.#connections.values()) {
1659
1725
  if (conn.__status === "connected") {
1726
+ connected += 1;
1660
1727
  this.#rLog.debug({
1661
1728
  msg: "connection is alive",
1662
1729
  connId: conn.id
1663
1730
  });
1664
1731
  } else {
1732
+ reconnecting += 1;
1665
1733
  const lastSeen = conn.__persist.lastSeen;
1666
1734
  const sinceLastSeen = Date.now() - lastSeen;
1667
1735
  if (sinceLastSeen < this.#config.options.connectionLivenessTimeout) {
@@ -1678,9 +1746,17 @@ var ActorInstance = class {
1678
1746
  connId: conn.id,
1679
1747
  lastSeen
1680
1748
  });
1749
+ removed += 1;
1681
1750
  this.#removeConn(conn);
1682
1751
  }
1683
1752
  }
1753
+ this.#rLog.debug({
1754
+ msg: "checked connection liveness",
1755
+ total: connected + reconnecting,
1756
+ connected,
1757
+ reconnecting,
1758
+ removed
1759
+ });
1684
1760
  }
1685
1761
  /**
1686
1762
  * Check if the actor is ready to handle requests.
@@ -1812,8 +1888,6 @@ var ActorInstance = class {
1812
1888
  if (!this.#config.onFetch) {
1813
1889
  throw new FetchHandlerNotDefined();
1814
1890
  }
1815
- this.#activeRawFetchCount++;
1816
- this.#resetSleepTimer();
1817
1891
  try {
1818
1892
  const response = await this.#config.onFetch(
1819
1893
  this.actorContext,
@@ -1831,11 +1905,6 @@ var ActorInstance = class {
1831
1905
  });
1832
1906
  throw error;
1833
1907
  } finally {
1834
- this.#activeRawFetchCount = Math.max(
1835
- 0,
1836
- this.#activeRawFetchCount - 1
1837
- );
1838
- this.#resetSleepTimer();
1839
1908
  this.#savePersistThrottled();
1840
1909
  }
1841
1910
  }
@@ -1851,8 +1920,81 @@ var ActorInstance = class {
1851
1920
  const stateBeforeHandler = this.#persistChanged;
1852
1921
  this.#activeRawWebSockets.add(websocket);
1853
1922
  this.#resetSleepTimer();
1854
- const onSocketClosed = () => {
1923
+ let rivetRequestId;
1924
+ let persistedHibernatableWebSocket;
1925
+ const onSocketOpened = (event) => {
1926
+ rivetRequestId = event == null ? void 0 : event.rivetRequestId;
1927
+ if (rivetRequestId) {
1928
+ const rivetRequestIdLocal = rivetRequestId;
1929
+ persistedHibernatableWebSocket = this.#persist.hibernatableWebSocket.find(
1930
+ (ws) => arrayBuffersEqual(
1931
+ ws.requestId,
1932
+ rivetRequestIdLocal
1933
+ )
1934
+ );
1935
+ if (persistedHibernatableWebSocket) {
1936
+ persistedHibernatableWebSocket.lastSeenTimestamp = BigInt(Date.now());
1937
+ }
1938
+ }
1939
+ this.#rLog.debug({
1940
+ msg: "actor instance onSocketOpened",
1941
+ rivetRequestId,
1942
+ isHibernatable: !!persistedHibernatableWebSocket,
1943
+ hibernationMsgIndex: persistedHibernatableWebSocket == null ? void 0 : persistedHibernatableWebSocket.msgIndex
1944
+ });
1945
+ };
1946
+ const onSocketMessage = (event) => {
1947
+ if (persistedHibernatableWebSocket) {
1948
+ persistedHibernatableWebSocket.lastSeenTimestamp = BigInt(
1949
+ Date.now()
1950
+ );
1951
+ persistedHibernatableWebSocket.msgIndex = BigInt(
1952
+ event.rivetMessageIndex
1953
+ );
1954
+ }
1955
+ this.#rLog.debug({
1956
+ msg: "actor instance onSocketMessage",
1957
+ rivetRequestId,
1958
+ isHibernatable: !!persistedHibernatableWebSocket,
1959
+ hibernationMsgIndex: persistedHibernatableWebSocket == null ? void 0 : persistedHibernatableWebSocket.msgIndex
1960
+ });
1961
+ };
1962
+ const onSocketClosed = (_event) => {
1963
+ if (rivetRequestId) {
1964
+ const rivetRequestIdLocal = rivetRequestId;
1965
+ const wsIndex = this.#persist.hibernatableWebSocket.findIndex(
1966
+ (ws) => arrayBuffersEqual(
1967
+ ws.requestId,
1968
+ rivetRequestIdLocal
1969
+ )
1970
+ );
1971
+ const removed = this.#persist.hibernatableWebSocket.splice(
1972
+ wsIndex,
1973
+ 1
1974
+ );
1975
+ if (removed.length > 0) {
1976
+ this.#rLog.debug({
1977
+ msg: "removed hibernatable websocket",
1978
+ rivetRequestId,
1979
+ hibernationMsgIndex: persistedHibernatableWebSocket == null ? void 0 : persistedHibernatableWebSocket.msgIndex
1980
+ });
1981
+ } else {
1982
+ this.#rLog.warn({
1983
+ msg: "could not find hibernatable websocket to remove",
1984
+ rivetRequestId,
1985
+ hibernationMsgIndex: persistedHibernatableWebSocket == null ? void 0 : persistedHibernatableWebSocket.msgIndex
1986
+ });
1987
+ }
1988
+ }
1989
+ this.#rLog.debug({
1990
+ msg: "actor instance onSocketMessage",
1991
+ rivetRequestId,
1992
+ isHibernatable: !!persistedHibernatableWebSocket,
1993
+ hibernatableWebSocketCount: this.#persist.hibernatableWebSocket.length
1994
+ });
1855
1995
  try {
1996
+ websocket.removeEventListener("open", onSocketOpened);
1997
+ websocket.removeEventListener("message", onSocketMessage);
1856
1998
  websocket.removeEventListener("close", onSocketClosed);
1857
1999
  websocket.removeEventListener("error", onSocketClosed);
1858
2000
  } catch {
@@ -1861,6 +2003,8 @@ var ActorInstance = class {
1861
2003
  this.#resetSleepTimer();
1862
2004
  };
1863
2005
  try {
2006
+ websocket.addEventListener("open", onSocketOpened);
2007
+ websocket.addEventListener("message", onSocketMessage);
1864
2008
  websocket.addEventListener("close", onSocketClosed);
1865
2009
  websocket.addEventListener("error", onSocketClosed);
1866
2010
  } catch {
@@ -2025,6 +2169,27 @@ var ActorInstance = class {
2025
2169
  }
2026
2170
  }
2027
2171
  }
2172
+ /**
2173
+ * Called by router middleware when an HTTP request begins.
2174
+ */
2175
+ __beginHonoHttpRequest() {
2176
+ this.#activeHonoHttpRequests++;
2177
+ this.#resetSleepTimer();
2178
+ }
2179
+ /**
2180
+ * Called by router middleware when an HTTP request ends.
2181
+ */
2182
+ __endHonoHttpRequest() {
2183
+ this.#activeHonoHttpRequests--;
2184
+ if (this.#activeHonoHttpRequests < 0) {
2185
+ this.#activeHonoHttpRequests = 0;
2186
+ this.#rLog.warn({
2187
+ msg: "active hono requests went below 0, this is a RivetKit bug",
2188
+ ...EXTRA_ERROR_LOG
2189
+ });
2190
+ }
2191
+ this.#resetSleepTimer();
2192
+ }
2028
2193
  // MARK: Sleep
2029
2194
  /**
2030
2195
  * Reset timer from the last actor interaction that allows it to be put to sleep.
@@ -2041,56 +2206,68 @@ var ActorInstance = class {
2041
2206
  const canSleep = this.#canSleep();
2042
2207
  this.#rLog.debug({
2043
2208
  msg: "resetting sleep timer",
2044
- canSleep,
2045
- existingTimeout: !!this.#sleepTimeout
2209
+ canSleep: CanSleep[canSleep],
2210
+ existingTimeout: !!this.#sleepTimeout,
2211
+ timeout: this.#config.options.sleepTimeout
2046
2212
  });
2047
2213
  if (this.#sleepTimeout) {
2048
2214
  clearTimeout(this.#sleepTimeout);
2049
2215
  this.#sleepTimeout = void 0;
2050
2216
  }
2051
2217
  if (this.#sleepCalled) return;
2052
- if (canSleep) {
2218
+ if (canSleep === 0 /* Yes */) {
2053
2219
  this.#sleepTimeout = setTimeout(() => {
2054
- this._sleep().catch((error) => {
2055
- this.#rLog.error({
2056
- msg: "error during sleep",
2057
- error: stringifyError(error)
2058
- });
2059
- });
2220
+ this._startSleep();
2060
2221
  }, this.#config.options.sleepTimeout);
2061
2222
  }
2062
2223
  }
2063
2224
  /** If this actor can be put in a sleeping state. */
2064
2225
  #canSleep() {
2065
- if (!this.#ready) return false;
2226
+ if (!this.#ready) return 1 /* NotReady */;
2227
+ if (this.#activeHonoHttpRequests > 0)
2228
+ return 3 /* ActiveHonoHttpRequests */;
2229
+ if (this.#activeRawWebSockets.size > 0)
2230
+ return 4 /* ActiveRawWebSockets */;
2066
2231
  for (const conn of this.#connections.values()) {
2067
- if (conn.status === "connected") return false;
2232
+ if (conn.status === "connected") return 2 /* ActiveConns */;
2068
2233
  }
2069
- if (this.#activeRawFetchCount > 0) return false;
2070
- if (this.#activeRawWebSockets.size > 0) return false;
2071
- return true;
2234
+ return 0 /* Yes */;
2072
2235
  }
2073
- /** Puts an actor to sleep. This should just start the sleep sequence, most shutdown logic should be in _stop (which is called by the ActorDriver when sleeping). */
2074
- async _sleep() {
2236
+ /**
2237
+ * Puts an actor to sleep. This should just start the sleep sequence, most shutdown logic should be in _stop (which is called by the ActorDriver when sleeping).
2238
+ *
2239
+ * For the engine, this will:
2240
+ * 1. Publish EventActorIntent with ActorIntentSleep (via driver.startSleep)
2241
+ * 2. Engine runner will wait for CommandStopActor
2242
+ * 3. Engine runner will call _onStop and wait for it to finish
2243
+ * 4. Engine runner will publish EventActorStateUpdate with ActorStateSTop
2244
+ **/
2245
+ _startSleep() {
2075
2246
  var _a;
2076
- const sleep = (_a = this.#actorDriver.sleep) == null ? void 0 : _a.bind(
2077
- this.#actorDriver,
2078
- this.#actorId
2079
- );
2080
- invariant(this.#sleepingSupported, "sleeping not supported");
2081
- invariant(sleep, "no sleep on driver");
2082
2247
  if (this.#sleepCalled) {
2083
2248
  this.#rLog.warn({ msg: "already sleeping actor" });
2084
2249
  return;
2085
2250
  }
2086
2251
  this.#sleepCalled = true;
2252
+ const sleep = (_a = this.#actorDriver.startSleep) == null ? void 0 : _a.bind(
2253
+ this.#actorDriver,
2254
+ this.#actorId
2255
+ );
2256
+ invariant(this.#sleepingSupported, "sleeping not supported");
2257
+ invariant(sleep, "no sleep on driver");
2087
2258
  this.#rLog.info({ msg: "actor sleeping" });
2088
- setImmediate(async () => {
2089
- await sleep();
2259
+ setImmediate(() => {
2260
+ sleep();
2090
2261
  });
2091
2262
  }
2092
2263
  // MARK: Stop
2093
- async _stop() {
2264
+ /**
2265
+ * For the engine:
2266
+ * 1. Engine runner receives CommandStopActor
2267
+ * 2. Engine runner calls _onStop and waits for it to finish
2268
+ * 3. Engine runner publishes EventActorStateUpdate with ActorStateSTop
2269
+ */
2270
+ async _onStop() {
2094
2271
  if (this.#stopCalled) {
2095
2272
  this.#rLog.warn({ msg: "already stopping actor" });
2096
2273
  return;
@@ -2205,6 +2382,11 @@ var ActorInstance = class {
2205
2382
  args: event.kind.generic.args ?? null
2206
2383
  }
2207
2384
  }
2385
+ })),
2386
+ hibernatableWebSocket: persist.hibernatableWebSocket.map((ws) => ({
2387
+ requestId: ws.requestId,
2388
+ lastSeenTimestamp: ws.lastSeenTimestamp,
2389
+ msgIndex: ws.msgIndex
2208
2390
  }))
2209
2391
  };
2210
2392
  }
@@ -2232,6 +2414,11 @@ var ActorInstance = class {
2232
2414
  args: event.kind.val.args
2233
2415
  }
2234
2416
  }
2417
+ })),
2418
+ hibernatableWebSocket: bareData.hibernatableWebSocket.map((ws) => ({
2419
+ requestId: ws.requestId,
2420
+ lastSeenTimestamp: ws.lastSeenTimestamp,
2421
+ msgIndex: ws.msgIndex
2235
2422
  }))
2236
2423
  };
2237
2424
  }
@@ -3389,11 +3576,15 @@ var ActorConnRaw = class {
3389
3576
  }
3390
3577
  /** Called by the onclose event from drivers. */
3391
3578
  #handleOnClose(event) {
3392
- if (this.#onOpenPromise) {
3393
- this.#onOpenPromise.reject(new Error("Closed"));
3394
- }
3395
3579
  const closeEvent = event;
3396
3580
  const wasClean = closeEvent.wasClean;
3581
+ if (this.#onOpenPromise) {
3582
+ this.#onOpenPromise.reject(
3583
+ new Error(
3584
+ `websocket closed with code ${closeEvent.code}: ${closeEvent.reason}`
3585
+ )
3586
+ );
3587
+ }
3397
3588
  logger().info({
3398
3589
  msg: "socket closed",
3399
3590
  code: closeEvent.code,
@@ -3801,7 +3992,10 @@ async function apiCall(config, method, path, body) {
3801
3992
  async function sendHttpRequestToActor(runConfig, actorId, actorRequest) {
3802
3993
  const url = new URL(actorRequest.url);
3803
3994
  const endpoint = getEndpoint(runConfig);
3804
- const guardUrl = combineUrlPath(endpoint, url.pathname + url.search);
3995
+ const guardUrl = combineUrlPath(
3996
+ endpoint,
3997
+ `/gateway/${actorId}${url.pathname}${url.search}`
3998
+ );
3805
3999
  let bodyToSend = null;
3806
4000
  const guardHeaders = buildGuardHeadersForHttp(
3807
4001
  runConfig,
@@ -3838,8 +4032,6 @@ function buildGuardHeadersForHttp(runConfig, actorRequest, actorId) {
3838
4032
  for (const [key, value] of Object.entries(runConfig.headers)) {
3839
4033
  headers.set(key, value);
3840
4034
  }
3841
- headers.set(HEADER_RIVET_TARGET, "actor");
3842
- headers.set(HEADER_RIVET_ACTOR, actorId);
3843
4035
  if (runConfig.token) {
3844
4036
  headers.set(HEADER_RIVET_TOKEN, runConfig.token);
3845
4037
  }
@@ -3850,7 +4042,7 @@ function buildGuardHeadersForHttp(runConfig, actorRequest, actorId) {
3850
4042
  async function openWebSocketToActor(runConfig, path, actorId, encoding, params, connId, connToken) {
3851
4043
  const WebSocket2 = await importWebSocket();
3852
4044
  const endpoint = getEndpoint(runConfig);
3853
- const guardUrl = combineUrlPath(endpoint, path);
4045
+ const guardUrl = combineUrlPath(endpoint, `/gateway/${actorId}${path}`);
3854
4046
  logger2().debug({
3855
4047
  msg: "opening websocket to actor via guard",
3856
4048
  actorId,
@@ -3859,24 +4051,15 @@ async function openWebSocketToActor(runConfig, path, actorId, encoding, params,
3859
4051
  });
3860
4052
  const ws = new WebSocket2(
3861
4053
  guardUrl,
3862
- buildWebSocketProtocols(
3863
- runConfig,
3864
- actorId,
3865
- encoding,
3866
- params,
3867
- connId,
3868
- connToken
3869
- )
4054
+ buildWebSocketProtocols(runConfig, encoding, params, connId, connToken)
3870
4055
  );
3871
4056
  ws.binaryType = "arraybuffer";
3872
4057
  logger2().debug({ msg: "websocket connection opened", actorId });
3873
4058
  return ws;
3874
4059
  }
3875
- function buildWebSocketProtocols(runConfig, actorId, encoding, params, connId, connToken) {
4060
+ function buildWebSocketProtocols(runConfig, encoding, params, connId, connToken) {
3876
4061
  const protocols = [];
3877
4062
  protocols.push(WS_PROTOCOL_STANDARD);
3878
- protocols.push(`${WS_PROTOCOL_TARGET}actor`);
3879
- protocols.push(`${WS_PROTOCOL_ACTOR}${actorId}`);
3880
4063
  protocols.push(`${WS_PROTOCOL_ENCODING}${encoding}`);
3881
4064
  if (runConfig.token) {
3882
4065
  protocols.push(`${WS_PROTOCOL_TOKEN}${runConfig.token}`);
@@ -4324,7 +4507,6 @@ var RemoteManagerDriver = class {
4324
4507
  });
4325
4508
  const protocols = buildWebSocketProtocols(
4326
4509
  this.#config,
4327
- actorId,
4328
4510
  encoding,
4329
4511
  params,
4330
4512
  connId,
@@ -4344,10 +4526,11 @@ var RemoteManagerDriver = class {
4344
4526
  export {
4345
4527
  generateConnId,
4346
4528
  generateConnToken,
4347
- generateConnSocketId,
4529
+ generateConnRequestId,
4348
4530
  createActorInspectorRouter,
4349
4531
  serializeActorKey,
4350
4532
  deserializeActorKey,
4533
+ PERSIST_SYMBOL,
4351
4534
  ActorDefinition,
4352
4535
  lookupInRegistry,
4353
4536
  ActorClientError,
@@ -4363,4 +4546,4 @@ export {
4363
4546
  updateRunnerConfig,
4364
4547
  RemoteManagerDriver
4365
4548
  };
4366
- //# sourceMappingURL=chunk-FETQGZN4.js.map
4549
+ //# sourceMappingURL=chunk-3BJJSSTM.js.map