rivetkit 2.0.2 → 2.0.4

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 (246) hide show
  1. package/README.md +3 -5
  2. package/dist/schemas/actor-persist/v1.ts +225 -0
  3. package/dist/schemas/client-protocol/v1.ts +435 -0
  4. package/dist/schemas/file-system-driver/v1.ts +102 -0
  5. package/dist/tsup/actor/errors.cjs +77 -0
  6. package/dist/tsup/actor/errors.cjs.map +1 -0
  7. package/dist/tsup/actor/errors.d.cts +156 -0
  8. package/dist/tsup/actor/errors.d.ts +156 -0
  9. package/dist/tsup/actor/errors.js +77 -0
  10. package/dist/tsup/actor/errors.js.map +1 -0
  11. package/dist/tsup/chunk-3F2YSRJL.js +117 -0
  12. package/dist/tsup/chunk-3F2YSRJL.js.map +1 -0
  13. package/dist/tsup/chunk-4CXBCT26.cjs +250 -0
  14. package/dist/tsup/chunk-4CXBCT26.cjs.map +1 -0
  15. package/dist/tsup/chunk-4R73YDN3.cjs +20 -0
  16. package/dist/tsup/chunk-4R73YDN3.cjs.map +1 -0
  17. package/dist/tsup/chunk-6LJT3QRL.cjs +539 -0
  18. package/dist/tsup/chunk-6LJT3QRL.cjs.map +1 -0
  19. package/dist/tsup/chunk-GICQ3YCU.cjs +1792 -0
  20. package/dist/tsup/chunk-GICQ3YCU.cjs.map +1 -0
  21. package/dist/tsup/chunk-H26RP6GD.js +251 -0
  22. package/dist/tsup/chunk-H26RP6GD.js.map +1 -0
  23. package/dist/tsup/chunk-HI3HWJRC.js +20 -0
  24. package/dist/tsup/chunk-HI3HWJRC.js.map +1 -0
  25. package/dist/tsup/chunk-HLLF4B4Q.js +1792 -0
  26. package/dist/tsup/chunk-HLLF4B4Q.js.map +1 -0
  27. package/dist/tsup/chunk-IH6CKNDW.cjs +117 -0
  28. package/dist/tsup/chunk-IH6CKNDW.cjs.map +1 -0
  29. package/dist/tsup/chunk-LV2S3OU3.js +250 -0
  30. package/dist/tsup/chunk-LV2S3OU3.js.map +1 -0
  31. package/dist/tsup/chunk-LWNKVZG5.cjs +251 -0
  32. package/dist/tsup/chunk-LWNKVZG5.cjs.map +1 -0
  33. package/dist/tsup/chunk-NFU2BBT5.js +374 -0
  34. package/dist/tsup/chunk-NFU2BBT5.js.map +1 -0
  35. package/dist/tsup/chunk-PQY7KKTL.js +539 -0
  36. package/dist/tsup/chunk-PQY7KKTL.js.map +1 -0
  37. package/dist/tsup/chunk-QK72M5JB.js +45 -0
  38. package/dist/tsup/chunk-QK72M5JB.js.map +1 -0
  39. package/dist/tsup/chunk-QNNXFOQV.cjs +45 -0
  40. package/dist/tsup/chunk-QNNXFOQV.cjs.map +1 -0
  41. package/dist/tsup/chunk-SBHHJ6QS.cjs +374 -0
  42. package/dist/tsup/chunk-SBHHJ6QS.cjs.map +1 -0
  43. package/dist/tsup/chunk-TQ62L3X7.js +325 -0
  44. package/dist/tsup/chunk-TQ62L3X7.js.map +1 -0
  45. package/dist/tsup/chunk-VO7ZRVVD.cjs +6293 -0
  46. package/dist/tsup/chunk-VO7ZRVVD.cjs.map +1 -0
  47. package/dist/tsup/chunk-WHBPJNGW.cjs +325 -0
  48. package/dist/tsup/chunk-WHBPJNGW.cjs.map +1 -0
  49. package/dist/tsup/chunk-XJQHKJ4P.js +6293 -0
  50. package/dist/tsup/chunk-XJQHKJ4P.js.map +1 -0
  51. package/dist/tsup/client/mod.cjs +32 -0
  52. package/dist/tsup/client/mod.cjs.map +1 -0
  53. package/dist/tsup/client/mod.d.cts +20 -0
  54. package/dist/tsup/client/mod.d.ts +20 -0
  55. package/dist/tsup/client/mod.js +32 -0
  56. package/dist/tsup/client/mod.js.map +1 -0
  57. package/dist/tsup/common/log.cjs +21 -0
  58. package/dist/tsup/common/log.cjs.map +1 -0
  59. package/dist/tsup/common/log.d.cts +26 -0
  60. package/dist/tsup/common/log.d.ts +26 -0
  61. package/dist/tsup/common/log.js +21 -0
  62. package/dist/tsup/common/log.js.map +1 -0
  63. package/dist/tsup/common/websocket.cjs +10 -0
  64. package/dist/tsup/common/websocket.cjs.map +1 -0
  65. package/dist/tsup/common/websocket.d.cts +3 -0
  66. package/dist/tsup/common/websocket.d.ts +3 -0
  67. package/dist/tsup/common/websocket.js +10 -0
  68. package/dist/tsup/common/websocket.js.map +1 -0
  69. package/dist/tsup/common-CXCe7s6i.d.cts +218 -0
  70. package/dist/tsup/common-CXCe7s6i.d.ts +218 -0
  71. package/dist/tsup/connection-BI-6UIBJ.d.ts +2087 -0
  72. package/dist/tsup/connection-Dyd4NLGW.d.cts +2087 -0
  73. package/dist/tsup/driver-helpers/mod.cjs +30 -0
  74. package/dist/tsup/driver-helpers/mod.cjs.map +1 -0
  75. package/dist/tsup/driver-helpers/mod.d.cts +17 -0
  76. package/dist/tsup/driver-helpers/mod.d.ts +17 -0
  77. package/dist/tsup/driver-helpers/mod.js +30 -0
  78. package/dist/tsup/driver-helpers/mod.js.map +1 -0
  79. package/dist/tsup/driver-test-suite/mod.cjs +3411 -0
  80. package/dist/tsup/driver-test-suite/mod.cjs.map +1 -0
  81. package/dist/tsup/driver-test-suite/mod.d.cts +63 -0
  82. package/dist/tsup/driver-test-suite/mod.d.ts +63 -0
  83. package/dist/tsup/driver-test-suite/mod.js +3411 -0
  84. package/dist/tsup/driver-test-suite/mod.js.map +1 -0
  85. package/dist/tsup/inspector/mod.cjs +51 -0
  86. package/dist/tsup/inspector/mod.cjs.map +1 -0
  87. package/dist/tsup/inspector/mod.d.cts +408 -0
  88. package/dist/tsup/inspector/mod.d.ts +408 -0
  89. package/dist/tsup/inspector/mod.js +51 -0
  90. package/dist/tsup/inspector/mod.js.map +1 -0
  91. package/dist/tsup/mod.cjs +67 -0
  92. package/dist/tsup/mod.cjs.map +1 -0
  93. package/dist/tsup/mod.d.cts +105 -0
  94. package/dist/tsup/mod.d.ts +105 -0
  95. package/dist/tsup/mod.js +67 -0
  96. package/dist/tsup/mod.js.map +1 -0
  97. package/dist/tsup/router-endpoints-BTe_Rsdn.d.cts +65 -0
  98. package/dist/tsup/router-endpoints-CBSrKHmo.d.ts +65 -0
  99. package/dist/tsup/test/mod.cjs +17 -0
  100. package/dist/tsup/test/mod.cjs.map +1 -0
  101. package/dist/tsup/test/mod.d.cts +26 -0
  102. package/dist/tsup/test/mod.d.ts +26 -0
  103. package/dist/tsup/test/mod.js +17 -0
  104. package/dist/tsup/test/mod.js.map +1 -0
  105. package/dist/tsup/utils-fwx3o3K9.d.cts +18 -0
  106. package/dist/tsup/utils-fwx3o3K9.d.ts +18 -0
  107. package/dist/tsup/utils.cjs +26 -0
  108. package/dist/tsup/utils.cjs.map +1 -0
  109. package/dist/tsup/utils.d.cts +36 -0
  110. package/dist/tsup/utils.d.ts +36 -0
  111. package/dist/tsup/utils.js +26 -0
  112. package/dist/tsup/utils.js.map +1 -0
  113. package/package.json +208 -5
  114. package/src/actor/action.ts +178 -0
  115. package/src/actor/config.ts +497 -0
  116. package/src/actor/connection.ts +257 -0
  117. package/src/actor/context.ts +168 -0
  118. package/src/actor/database.ts +23 -0
  119. package/src/actor/definition.ts +82 -0
  120. package/src/actor/driver.ts +84 -0
  121. package/src/actor/errors.ts +422 -0
  122. package/src/actor/generic-conn-driver.ts +246 -0
  123. package/src/actor/instance.ts +1844 -0
  124. package/src/actor/keys.test.ts +266 -0
  125. package/src/actor/keys.ts +89 -0
  126. package/src/actor/log.ts +6 -0
  127. package/src/actor/mod.ts +108 -0
  128. package/src/actor/persisted.ts +42 -0
  129. package/src/actor/protocol/old.ts +297 -0
  130. package/src/actor/protocol/serde.ts +131 -0
  131. package/src/actor/router-endpoints.ts +688 -0
  132. package/src/actor/router.ts +265 -0
  133. package/src/actor/schedule.ts +17 -0
  134. package/src/actor/unstable-react.ts +110 -0
  135. package/src/actor/utils.ts +102 -0
  136. package/src/client/actor-common.ts +30 -0
  137. package/src/client/actor-conn.ts +865 -0
  138. package/src/client/actor-handle.ts +268 -0
  139. package/src/client/actor-query.ts +65 -0
  140. package/src/client/client.ts +554 -0
  141. package/src/client/config.ts +44 -0
  142. package/src/client/errors.ts +42 -0
  143. package/src/client/log.ts +5 -0
  144. package/src/client/mod.ts +60 -0
  145. package/src/client/raw-utils.ts +149 -0
  146. package/src/client/test.ts +44 -0
  147. package/src/client/utils.ts +152 -0
  148. package/src/common/eventsource-interface.ts +47 -0
  149. package/src/common/eventsource.ts +80 -0
  150. package/src/common/fake-event-source.ts +267 -0
  151. package/src/common/inline-websocket-adapter2.ts +454 -0
  152. package/src/common/log-levels.ts +27 -0
  153. package/src/common/log.ts +214 -0
  154. package/src/common/logfmt.ts +219 -0
  155. package/src/common/network.ts +2 -0
  156. package/src/common/router.ts +80 -0
  157. package/src/common/utils.ts +336 -0
  158. package/src/common/versioned-data.ts +95 -0
  159. package/src/common/websocket-interface.ts +49 -0
  160. package/src/common/websocket.ts +42 -0
  161. package/src/driver-helpers/mod.ts +22 -0
  162. package/src/driver-helpers/utils.ts +17 -0
  163. package/src/driver-test-suite/log.ts +5 -0
  164. package/src/driver-test-suite/mod.ts +239 -0
  165. package/src/driver-test-suite/tests/action-features.ts +136 -0
  166. package/src/driver-test-suite/tests/actor-conn-state.ts +249 -0
  167. package/src/driver-test-suite/tests/actor-conn.ts +349 -0
  168. package/src/driver-test-suite/tests/actor-driver.ts +25 -0
  169. package/src/driver-test-suite/tests/actor-error-handling.ts +158 -0
  170. package/src/driver-test-suite/tests/actor-handle.ts +292 -0
  171. package/src/driver-test-suite/tests/actor-inline-client.ts +152 -0
  172. package/src/driver-test-suite/tests/actor-inspector.ts +570 -0
  173. package/src/driver-test-suite/tests/actor-metadata.ts +116 -0
  174. package/src/driver-test-suite/tests/actor-onstatechange.ts +95 -0
  175. package/src/driver-test-suite/tests/actor-schedule.ts +108 -0
  176. package/src/driver-test-suite/tests/actor-sleep.ts +413 -0
  177. package/src/driver-test-suite/tests/actor-state.ts +54 -0
  178. package/src/driver-test-suite/tests/actor-vars.ts +93 -0
  179. package/src/driver-test-suite/tests/manager-driver.ts +367 -0
  180. package/src/driver-test-suite/tests/raw-http-direct-registry.ts +227 -0
  181. package/src/driver-test-suite/tests/raw-http-request-properties.ts +414 -0
  182. package/src/driver-test-suite/tests/raw-http.ts +347 -0
  183. package/src/driver-test-suite/tests/raw-websocket-direct-registry.ts +393 -0
  184. package/src/driver-test-suite/tests/raw-websocket.ts +484 -0
  185. package/src/driver-test-suite/tests/request-access.ts +230 -0
  186. package/src/driver-test-suite/utils.ts +71 -0
  187. package/src/drivers/default.ts +34 -0
  188. package/src/drivers/engine/actor-driver.ts +369 -0
  189. package/src/drivers/engine/config.ts +31 -0
  190. package/src/drivers/engine/kv.ts +3 -0
  191. package/src/drivers/engine/log.ts +5 -0
  192. package/src/drivers/engine/mod.ts +35 -0
  193. package/src/drivers/file-system/actor.ts +91 -0
  194. package/src/drivers/file-system/global-state.ts +686 -0
  195. package/src/drivers/file-system/log.ts +5 -0
  196. package/src/drivers/file-system/manager.ts +329 -0
  197. package/src/drivers/file-system/mod.ts +48 -0
  198. package/src/drivers/file-system/utils.ts +109 -0
  199. package/src/globals.d.ts +6 -0
  200. package/src/inspector/actor.ts +298 -0
  201. package/src/inspector/config.ts +88 -0
  202. package/src/inspector/log.ts +5 -0
  203. package/src/inspector/manager.ts +86 -0
  204. package/src/inspector/mod.ts +2 -0
  205. package/src/inspector/protocol/actor.ts +10 -0
  206. package/src/inspector/protocol/common.ts +196 -0
  207. package/src/inspector/protocol/manager.ts +10 -0
  208. package/src/inspector/protocol/mod.ts +2 -0
  209. package/src/inspector/utils.ts +76 -0
  210. package/src/manager/driver.ts +88 -0
  211. package/src/manager/hono-websocket-adapter.ts +342 -0
  212. package/src/manager/log.ts +5 -0
  213. package/src/manager/mod.ts +2 -0
  214. package/src/manager/protocol/mod.ts +24 -0
  215. package/src/manager/protocol/query.ts +89 -0
  216. package/src/manager/router.ts +412 -0
  217. package/src/manager-api/routes/actors-create.ts +16 -0
  218. package/src/manager-api/routes/actors-delete.ts +4 -0
  219. package/src/manager-api/routes/actors-get-by-id.ts +7 -0
  220. package/src/manager-api/routes/actors-get-or-create-by-id.ts +29 -0
  221. package/src/manager-api/routes/actors-get.ts +7 -0
  222. package/src/manager-api/routes/common.ts +18 -0
  223. package/src/mod.ts +18 -0
  224. package/src/registry/config.ts +32 -0
  225. package/src/registry/log.ts +5 -0
  226. package/src/registry/mod.ts +157 -0
  227. package/src/registry/run-config.ts +52 -0
  228. package/src/registry/serve.ts +52 -0
  229. package/src/remote-manager-driver/actor-http-client.ts +72 -0
  230. package/src/remote-manager-driver/actor-websocket-client.ts +63 -0
  231. package/src/remote-manager-driver/api-endpoints.ts +79 -0
  232. package/src/remote-manager-driver/api-utils.ts +43 -0
  233. package/src/remote-manager-driver/log.ts +5 -0
  234. package/src/remote-manager-driver/mod.ts +274 -0
  235. package/src/remote-manager-driver/ws-proxy.ts +180 -0
  236. package/src/schemas/actor-persist/mod.ts +1 -0
  237. package/src/schemas/actor-persist/versioned.ts +25 -0
  238. package/src/schemas/client-protocol/mod.ts +1 -0
  239. package/src/schemas/client-protocol/versioned.ts +63 -0
  240. package/src/schemas/file-system-driver/mod.ts +1 -0
  241. package/src/schemas/file-system-driver/versioned.ts +28 -0
  242. package/src/serde.ts +90 -0
  243. package/src/test/config.ts +16 -0
  244. package/src/test/log.ts +5 -0
  245. package/src/test/mod.ts +154 -0
  246. package/src/utils.ts +172 -0
@@ -0,0 +1,554 @@
1
+ import type { AnyActorDefinition } from "@/actor/definition";
2
+ import type { Transport } from "@/actor/protocol/old";
3
+ import type { Encoding } from "@/actor/protocol/serde";
4
+ import type { ManagerDriver } from "@/driver-helpers/mod";
5
+ import type { ActorQuery } from "@/manager/protocol/query";
6
+ import type { Registry } from "@/mod";
7
+ import type { ActorActionFunction } from "./actor-common";
8
+ import {
9
+ type ActorConn,
10
+ type ActorConnRaw,
11
+ CONNECT_SYMBOL,
12
+ } from "./actor-conn";
13
+ import { type ActorHandle, ActorHandleRaw } from "./actor-handle";
14
+ import { queryActor } from "./actor-query";
15
+ import type { ClientConfig } from "./config";
16
+ import { logger } from "./log";
17
+
18
+ export type { ClientConfig, ClientConfigInput } from "./config";
19
+
20
+ /** Extract the actor registry from the registry definition. */
21
+ export type ExtractActorsFromRegistry<A extends Registry<any>> =
22
+ A extends Registry<infer Actors> ? Actors : never;
23
+
24
+ /** Extract the registry definition from the client. */
25
+ export type ExtractRegistryFromClient<C extends Client<Registry<{}>>> =
26
+ C extends Client<infer A> ? A : never;
27
+
28
+ /**
29
+ * Represents a actor accessor that provides methods to interact with a specific actor.
30
+ */
31
+ export interface ActorAccessor<AD extends AnyActorDefinition> {
32
+ /**
33
+ * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
34
+ * The actor name is automatically injected from the property accessor.
35
+ *
36
+ * @template AD The actor class that this handle is for.
37
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
38
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
39
+ * @returns {ActorHandle<AD>} - A handle to the actor.
40
+ */
41
+ get(key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
42
+
43
+ /**
44
+ * Gets a stateless handle to a actor by its key, creating it if necessary.
45
+ * The actor name is automatically injected from the property accessor.
46
+ *
47
+ * @template AD The actor class that this handle is for.
48
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
49
+ * @param {GetOptions} [opts] - Options for getting the actor.
50
+ * @returns {ActorHandle<AD>} - A handle to the actor.
51
+ */
52
+ getOrCreate(
53
+ key?: string | string[],
54
+ opts?: GetOrCreateOptions,
55
+ ): ActorHandle<AD>;
56
+
57
+ /**
58
+ * Gets a stateless handle to a actor by its ID.
59
+ *
60
+ * @template AD The actor class that this handle is for.
61
+ * @param {string} actorId - The ID of the actor.
62
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
63
+ * @returns {ActorHandle<AD>} - A handle to the actor.
64
+ */
65
+ getForId(actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
66
+
67
+ /**
68
+ * Creates a new actor with the name automatically injected from the property accessor,
69
+ * and returns a stateless handle to it with the actor ID resolved.
70
+ *
71
+ * @template AD The actor class that this handle is for.
72
+ * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
73
+ * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
74
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
75
+ */
76
+ create(
77
+ key?: string | string[],
78
+ opts?: CreateOptions,
79
+ ): Promise<ActorHandle<AD>>;
80
+ }
81
+
82
+ /**
83
+ * Options for querying actors.
84
+ * @typedef {Object} QueryOptions
85
+ * @property {unknown} [parameters] - Parameters to pass to the connection.
86
+ */
87
+ export interface QueryOptions {
88
+ /** Parameters to pass to the connection. */
89
+ params?: unknown;
90
+ /** Signal to abort the request. */
91
+ signal?: AbortSignal;
92
+ }
93
+
94
+ /**
95
+ * Options for getting a actor by ID.
96
+ * @typedef {QueryOptions} GetWithIdOptions
97
+ */
98
+ export interface GetWithIdOptions extends QueryOptions {}
99
+
100
+ /**
101
+ * Options for getting a actor.
102
+ * @typedef {QueryOptions} GetOptions
103
+ */
104
+ export interface GetOptions extends QueryOptions {}
105
+
106
+ /**
107
+ * Options for getting or creating a actor.
108
+ * @typedef {QueryOptions} GetOrCreateOptions
109
+ * @property {string} [createInRegion] - Region to create the actor in if it doesn't exist.
110
+ */
111
+ export interface GetOrCreateOptions extends QueryOptions {
112
+ /** Region to create the actor in if it doesn't exist. */
113
+ createInRegion?: string;
114
+ /** Input data to pass to the actor. */
115
+ createWithInput?: unknown;
116
+ }
117
+
118
+ /**
119
+ * Options for creating a actor.
120
+ * @typedef {QueryOptions} CreateOptions
121
+ * @property {string} [region] - The region to create the actor in.
122
+ */
123
+ export interface CreateOptions extends QueryOptions {
124
+ /** The region to create the actor in. */
125
+ region?: string;
126
+ /** Input data to pass to the actor. */
127
+ input?: unknown;
128
+ }
129
+
130
+ /**
131
+ * Represents a region to connect to.
132
+ * @typedef {Object} Region
133
+ * @property {string} id - The region ID.
134
+ * @property {string} name - The region name.
135
+ * @see {@link https://rivet.dev/docs/edge|Edge Networking}
136
+ * @see {@link https://rivet.dev/docs/regions|Available Regions}
137
+ */
138
+ export interface Region {
139
+ /**
140
+ * The region slug.
141
+ */
142
+ id: string;
143
+
144
+ /**
145
+ * The human-friendly region name.
146
+ */
147
+ name: string;
148
+ }
149
+
150
+ export const ACTOR_CONNS_SYMBOL = Symbol("actorConns");
151
+ export const CREATE_ACTOR_CONN_PROXY = Symbol("createActorConnProxy");
152
+ export const TRANSPORT_SYMBOL = Symbol("transport");
153
+
154
+ /**
155
+ * Client for managing & connecting to actors.
156
+ *
157
+ * @template A The actors map type that defines the available actors.
158
+ * @see {@link https://rivet.dev/docs/manage|Create & Manage Actors}
159
+ */
160
+ export class ClientRaw {
161
+ #disposed = false;
162
+
163
+ [ACTOR_CONNS_SYMBOL] = new Set<ActorConnRaw>();
164
+
165
+ #driver: ManagerDriver;
166
+ #encodingKind: Encoding;
167
+ [TRANSPORT_SYMBOL]: Transport;
168
+
169
+ /**
170
+ * Creates an instance of Client.
171
+ *
172
+ * @param {string} managerEndpoint - The manager endpoint. See {@link https://rivet.dev/docs/setup|Initial Setup} for instructions on getting the manager endpoint.
173
+ * @param {ClientConfig} [opts] - Options for configuring the client.
174
+ * @see {@link https://rivet.dev/docs/setup|Initial Setup}
175
+ */
176
+ public constructor(driver: ManagerDriver, opts?: ClientConfig) {
177
+ this.#driver = driver;
178
+
179
+ this.#encodingKind = opts?.encoding ?? "bare";
180
+ this[TRANSPORT_SYMBOL] = opts?.transport ?? "websocket";
181
+ }
182
+
183
+ /**
184
+ * Gets a stateless handle to a actor by its ID.
185
+ *
186
+ * @template AD The actor class that this handle is for.
187
+ * @param {string} name - The name of the actor.
188
+ * @param {string} actorId - The ID of the actor.
189
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
190
+ * @returns {ActorHandle<AD>} - A handle to the actor.
191
+ */
192
+ getForId<AD extends AnyActorDefinition>(
193
+ name: string,
194
+ actorId: string,
195
+ opts?: GetWithIdOptions,
196
+ ): ActorHandle<AD> {
197
+ logger().debug({
198
+ msg: "get handle to actor with id",
199
+ name,
200
+ actorId,
201
+ params: opts?.params,
202
+ });
203
+
204
+ const actorQuery: ActorQuery = {
205
+ getForId: {
206
+ name,
207
+ actorId,
208
+ },
209
+ };
210
+
211
+ const handle = this.#createHandle(opts?.params, actorQuery);
212
+ return createActorProxy(handle) as ActorHandle<AD>;
213
+ }
214
+
215
+ /**
216
+ * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
217
+ *
218
+ * @template AD The actor class that this handle is for.
219
+ * @param {string} name - The name of the actor.
220
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
221
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
222
+ * @returns {ActorHandle<AD>} - A handle to the actor.
223
+ */
224
+ get<AD extends AnyActorDefinition>(
225
+ name: string,
226
+ key?: string | string[],
227
+ opts?: GetWithIdOptions,
228
+ ): ActorHandle<AD> {
229
+ // Convert string to array of strings
230
+ const keyArray: string[] = typeof key === "string" ? [key] : key || [];
231
+
232
+ logger().debug({
233
+ msg: "get handle to actor",
234
+ name,
235
+ key: keyArray,
236
+ parameters: opts?.params,
237
+ });
238
+
239
+ const actorQuery: ActorQuery = {
240
+ getForKey: {
241
+ name,
242
+ key: keyArray,
243
+ },
244
+ };
245
+
246
+ const handle = this.#createHandle(opts?.params, actorQuery);
247
+ return createActorProxy(handle) as ActorHandle<AD>;
248
+ }
249
+
250
+ /**
251
+ * Gets a stateless handle to a actor by its key, creating it if necessary.
252
+ *
253
+ * @template AD The actor class that this handle is for.
254
+ * @param {string} name - The name of the actor.
255
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
256
+ * @param {GetOptions} [opts] - Options for getting the actor.
257
+ * @returns {ActorHandle<AD>} - A handle to the actor.
258
+ */
259
+ getOrCreate<AD extends AnyActorDefinition>(
260
+ name: string,
261
+ key?: string | string[],
262
+ opts?: GetOrCreateOptions,
263
+ ): ActorHandle<AD> {
264
+ // Convert string to array of strings
265
+ const keyArray: string[] = typeof key === "string" ? [key] : key || [];
266
+
267
+ logger().debug({
268
+ msg: "get or create handle to actor",
269
+ name,
270
+ key: keyArray,
271
+ parameters: opts?.params,
272
+ createInRegion: opts?.createInRegion,
273
+ });
274
+
275
+ const actorQuery: ActorQuery = {
276
+ getOrCreateForKey: {
277
+ name,
278
+ key: keyArray,
279
+ input: opts?.createWithInput,
280
+ region: opts?.createInRegion,
281
+ },
282
+ };
283
+
284
+ const handle = this.#createHandle(opts?.params, actorQuery);
285
+ return createActorProxy(handle) as ActorHandle<AD>;
286
+ }
287
+
288
+ /**
289
+ * Creates a new actor with the provided key and returns a stateless handle to it.
290
+ * Resolves the actor ID and returns a handle with getForId query.
291
+ *
292
+ * @template AD The actor class that this handle is for.
293
+ * @param {string} name - The name of the actor.
294
+ * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
295
+ * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
296
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
297
+ */
298
+ async create<AD extends AnyActorDefinition>(
299
+ name: string,
300
+ key?: string | string[],
301
+ opts?: CreateOptions,
302
+ ): Promise<ActorHandle<AD>> {
303
+ // Convert string to array of strings
304
+ const keyArray: string[] = typeof key === "string" ? [key] : key || [];
305
+
306
+ const createQuery = {
307
+ create: {
308
+ ...opts,
309
+ // Do these last to override `opts`
310
+ name,
311
+ key: keyArray,
312
+ },
313
+ } satisfies ActorQuery;
314
+
315
+ logger().debug({
316
+ msg: "create actor handle",
317
+ name,
318
+ key: keyArray,
319
+ parameters: opts?.params,
320
+ create: createQuery.create,
321
+ });
322
+
323
+ // Create the actor
324
+ const { actorId } = await queryActor(undefined, createQuery, this.#driver);
325
+ logger().debug({
326
+ msg: "created actor with ID",
327
+ name,
328
+ key: keyArray,
329
+ actorId,
330
+ });
331
+
332
+ // Create handle with actor ID
333
+ const getForIdQuery = {
334
+ getForId: {
335
+ name,
336
+ actorId,
337
+ },
338
+ } satisfies ActorQuery;
339
+ const handle = this.#createHandle(opts?.params, getForIdQuery);
340
+
341
+ const proxy = createActorProxy(handle) as ActorHandle<AD>;
342
+
343
+ return proxy;
344
+ }
345
+
346
+ #createHandle(params: unknown, actorQuery: ActorQuery): ActorHandleRaw {
347
+ return new ActorHandleRaw(
348
+ this,
349
+ this.#driver,
350
+ params,
351
+ this.#encodingKind,
352
+ actorQuery,
353
+ );
354
+ }
355
+
356
+ [CREATE_ACTOR_CONN_PROXY]<AD extends AnyActorDefinition>(
357
+ conn: ActorConnRaw,
358
+ ): ActorConn<AD> {
359
+ // Save to connection list
360
+ this[ACTOR_CONNS_SYMBOL].add(conn);
361
+
362
+ // Start connection
363
+ conn[CONNECT_SYMBOL]();
364
+
365
+ return createActorProxy(conn) as ActorConn<AD>;
366
+ }
367
+
368
+ /**
369
+ * Disconnects from all actors.
370
+ *
371
+ * @returns {Promise<void>} A promise that resolves when all connections are closed.
372
+ */
373
+ async dispose(): Promise<void> {
374
+ if (this.#disposed) {
375
+ logger().warn({ msg: "client already disconnected" });
376
+ return;
377
+ }
378
+ this.#disposed = true;
379
+
380
+ logger().debug({ msg: "disposing client" });
381
+
382
+ const disposePromises = [];
383
+
384
+ // Dispose all connections
385
+ for (const conn of this[ACTOR_CONNS_SYMBOL].values()) {
386
+ disposePromises.push(conn.dispose());
387
+ }
388
+
389
+ await Promise.all(disposePromises);
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Client type with actor accessors.
395
+ * This adds property accessors for actor names to the ClientRaw base class.
396
+ *
397
+ * @template A The actor registry type.
398
+ */
399
+ export type Client<A extends Registry<any>> = ClientRaw & {
400
+ [K in keyof ExtractActorsFromRegistry<A>]: ActorAccessor<
401
+ ExtractActorsFromRegistry<A>[K]
402
+ >;
403
+ };
404
+
405
+ export type AnyClient = Client<Registry<any>>;
406
+
407
+ export function createClientWithDriver<A extends Registry<any>>(
408
+ driver: ManagerDriver,
409
+ config?: ClientConfig,
410
+ ): Client<A> {
411
+ const client = new ClientRaw(driver, config);
412
+
413
+ // Create proxy for accessing actors by name
414
+ return new Proxy(client, {
415
+ get: (target: ClientRaw, prop: string | symbol, receiver: unknown) => {
416
+ // Get the real property if it exists
417
+ if (typeof prop === "symbol" || prop in target) {
418
+ const value = Reflect.get(target, prop, receiver);
419
+ // Preserve method binding
420
+ if (typeof value === "function") {
421
+ return value.bind(target);
422
+ }
423
+ return value;
424
+ }
425
+
426
+ // Handle actor accessor for string properties (actor names)
427
+ if (typeof prop === "string") {
428
+ // Return actor accessor object with methods
429
+ return {
430
+ // Handle methods (stateless action)
431
+ get: (
432
+ key?: string | string[],
433
+ opts?: GetWithIdOptions,
434
+ ): ActorHandle<ExtractActorsFromRegistry<A>[typeof prop]> => {
435
+ return target.get<ExtractActorsFromRegistry<A>[typeof prop]>(
436
+ prop,
437
+ key,
438
+ opts,
439
+ );
440
+ },
441
+ getOrCreate: (
442
+ key?: string | string[],
443
+ opts?: GetOptions,
444
+ ): ActorHandle<ExtractActorsFromRegistry<A>[typeof prop]> => {
445
+ return target.getOrCreate<
446
+ ExtractActorsFromRegistry<A>[typeof prop]
447
+ >(prop, key, opts);
448
+ },
449
+ getForId: (
450
+ actorId: string,
451
+ opts?: GetWithIdOptions,
452
+ ): ActorHandle<ExtractActorsFromRegistry<A>[typeof prop]> => {
453
+ return target.getForId<ExtractActorsFromRegistry<A>[typeof prop]>(
454
+ prop,
455
+ actorId,
456
+ opts,
457
+ );
458
+ },
459
+ create: async (
460
+ key: string | string[],
461
+ opts: CreateOptions = {},
462
+ ): Promise<
463
+ ActorHandle<ExtractActorsFromRegistry<A>[typeof prop]>
464
+ > => {
465
+ return await target.create<
466
+ ExtractActorsFromRegistry<A>[typeof prop]
467
+ >(prop, key, opts);
468
+ },
469
+ } as ActorAccessor<ExtractActorsFromRegistry<A>[typeof prop]>;
470
+ }
471
+
472
+ return undefined;
473
+ },
474
+ }) as Client<A>;
475
+ }
476
+
477
+ /**
478
+ * Creates a proxy for a actor that enables calling actions without explicitly using `.action`.
479
+ **/
480
+ function createActorProxy<AD extends AnyActorDefinition>(
481
+ handle: ActorHandleRaw | ActorConnRaw,
482
+ ): ActorHandle<AD> | ActorConn<AD> {
483
+ // Stores returned action functions for faster calls
484
+ const methodCache = new Map<string, ActorActionFunction>();
485
+ return new Proxy(handle, {
486
+ get(target: ActorHandleRaw, prop: string | symbol, receiver: unknown) {
487
+ // Handle built-in Symbol properties
488
+ if (typeof prop === "symbol") {
489
+ return Reflect.get(target, prop, receiver);
490
+ }
491
+
492
+ // Handle built-in Promise methods and existing properties
493
+ if (prop === "constructor" || prop in target) {
494
+ const value = Reflect.get(target, prop, receiver);
495
+ // Preserve method binding
496
+ if (typeof value === "function") {
497
+ return value.bind(target);
498
+ }
499
+ return value;
500
+ }
501
+
502
+ // Create action function that preserves 'this' context
503
+ if (typeof prop === "string") {
504
+ // If JS is attempting to calling this as a promise, ignore it
505
+ if (prop === "then") return undefined;
506
+
507
+ let method = methodCache.get(prop);
508
+ if (!method) {
509
+ method = (...args: unknown[]) => target.action({ name: prop, args });
510
+ methodCache.set(prop, method);
511
+ }
512
+ return method;
513
+ }
514
+ },
515
+
516
+ // Support for 'in' operator
517
+ has(target: ActorHandleRaw, prop: string | symbol) {
518
+ // All string properties are potentially action functions
519
+ if (typeof prop === "string") {
520
+ return true;
521
+ }
522
+ // For symbols, defer to the target's own has behavior
523
+ return Reflect.has(target, prop);
524
+ },
525
+
526
+ // Support instanceof checks
527
+ getPrototypeOf(target: ActorHandleRaw) {
528
+ return Reflect.getPrototypeOf(target);
529
+ },
530
+
531
+ // Prevent property enumeration of non-existent action methods
532
+ ownKeys(target: ActorHandleRaw) {
533
+ return Reflect.ownKeys(target);
534
+ },
535
+
536
+ // Support proper property descriptors
537
+ getOwnPropertyDescriptor(target: ActorHandleRaw, prop: string | symbol) {
538
+ const targetDescriptor = Reflect.getOwnPropertyDescriptor(target, prop);
539
+ if (targetDescriptor) {
540
+ return targetDescriptor;
541
+ }
542
+ if (typeof prop === "string") {
543
+ // Make action methods appear non-enumerable
544
+ return {
545
+ configurable: true,
546
+ enumerable: false,
547
+ writable: false,
548
+ value: (...args: unknown[]) => target.action({ name: prop, args }),
549
+ };
550
+ }
551
+ return undefined;
552
+ },
553
+ }) as ActorHandle<AD> | ActorConn<AD>;
554
+ }
@@ -0,0 +1,44 @@
1
+ import z from "zod";
2
+ import { TransportSchema } from "@/actor/protocol/old";
3
+ import { EncodingSchema } from "@/actor/protocol/serde";
4
+ import { getEnvUniversal, type UpgradeWebSocket } from "@/utils";
5
+
6
+ export type GetUpgradeWebSocket = () => UpgradeWebSocket;
7
+
8
+ export const ClientConfigSchema = z.object({
9
+ /** Configure serving the API */
10
+ api: z
11
+ .object({
12
+ host: z.string().default("127.0.0.1"),
13
+ port: z.number().default(6420),
14
+ })
15
+ .default({}),
16
+
17
+ /** Endpoint to connect to the Rivet engine. Can be configured via RIVET_ENGINE env var. */
18
+ endpoint: z
19
+ .string()
20
+ .nullable()
21
+ .default(() => getEnvUniversal("RIVET_ENGINE") ?? null),
22
+
23
+ namespace: z
24
+ .string()
25
+ .default(() => getEnvUniversal("RIVET_NAMESPACE") ?? "default"),
26
+
27
+ runnerName: z
28
+ .string()
29
+ .default(() => getEnvUniversal("RIVET_RUNNER") ?? "rivetkit"),
30
+
31
+ encoding: EncodingSchema.default("bare"),
32
+
33
+ transport: TransportSchema.default("websocket"),
34
+
35
+ // This is a function to allow for lazy configuration of upgradeWebSocket on the
36
+ // fly. This is required since the dependencies that upgradeWebSocket
37
+ // (specifically Node.js) can sometimes only be specified after the router is
38
+ // created or must be imported async using `await import(...)`
39
+ getUpgradeWebSocket: z.custom<GetUpgradeWebSocket>().optional(),
40
+ });
41
+
42
+ export type ClientConfig = z.infer<typeof ClientConfigSchema>;
43
+
44
+ export type ClientConfigInput = z.input<typeof ClientConfigSchema>;
@@ -0,0 +1,42 @@
1
+ import { MAX_CONN_PARAMS_SIZE } from "@/common//network";
2
+
3
+ export class ActorClientError extends Error {}
4
+
5
+ export class InternalError extends ActorClientError {}
6
+
7
+ export class ManagerError extends ActorClientError {
8
+ constructor(error: string, opts?: ErrorOptions) {
9
+ super(`Manager error: ${error}`, opts);
10
+ }
11
+ }
12
+
13
+ export class MalformedResponseMessage extends ActorClientError {
14
+ constructor(cause?: unknown) {
15
+ super(`Malformed response message: ${cause}`, { cause });
16
+ }
17
+ }
18
+
19
+ export class ActorError extends ActorClientError {
20
+ __type = "ActorError";
21
+
22
+ constructor(
23
+ public readonly group: string,
24
+ public readonly code: string,
25
+ message: string,
26
+ public readonly metadata?: unknown,
27
+ ) {
28
+ super(message);
29
+ }
30
+ }
31
+
32
+ export class HttpRequestError extends ActorClientError {
33
+ constructor(message: string, opts?: { cause?: unknown }) {
34
+ super(`HTTP request error: ${message}`, { cause: opts?.cause });
35
+ }
36
+ }
37
+
38
+ export class ActorConnDisposed extends ActorClientError {
39
+ constructor() {
40
+ super("Attempting to interact with a disposed actor connection.");
41
+ }
42
+ }
@@ -0,0 +1,5 @@
1
+ import { getLogger } from "@/common/log";
2
+
3
+ export function logger() {
4
+ return getLogger("actor-client");
5
+ }
@@ -0,0 +1,60 @@
1
+ import type { Registry } from "@/registry/mod";
2
+ import { RemoteManagerDriver } from "@/remote-manager-driver/mod";
3
+ import {
4
+ type Client,
5
+ type ClientConfigInput,
6
+ createClientWithDriver,
7
+ } from "./client";
8
+ import { ClientConfigSchema } from "./config";
9
+
10
+ export {
11
+ ActorDefinition,
12
+ AnyActorDefinition,
13
+ } from "@/actor/definition";
14
+ export type { Transport } from "@/actor/protocol/old";
15
+ export type { Encoding } from "@/actor/protocol/serde";
16
+ export {
17
+ ActorClientError,
18
+ ActorError,
19
+ InternalError,
20
+ MalformedResponseMessage,
21
+ ManagerError,
22
+ } from "@/client/errors";
23
+ export type { CreateRequest } from "@/manager/protocol/query";
24
+ export type { ActorActionFunction } from "./actor-common";
25
+ export type { ActorConn, EventUnsubscribe } from "./actor-conn";
26
+ export { ActorConnRaw } from "./actor-conn";
27
+ export type { ActorHandle } from "./actor-handle";
28
+ export { ActorHandleRaw } from "./actor-handle";
29
+ export type {
30
+ ActorAccessor,
31
+ Client,
32
+ ClientRaw,
33
+ CreateOptions,
34
+ ExtractActorsFromRegistry,
35
+ ExtractRegistryFromClient,
36
+ GetOptions,
37
+ GetWithIdOptions,
38
+ QueryOptions,
39
+ Region,
40
+ } from "./client";
41
+
42
+ /**
43
+ * Creates a client with the actor accessor proxy.
44
+ */
45
+ export function createClient<A extends Registry<any>>(
46
+ endpointOrConfig?: string | ClientConfigInput,
47
+ ): Client<A> {
48
+ // Parse config
49
+ const configInput =
50
+ endpointOrConfig === undefined
51
+ ? {}
52
+ : typeof endpointOrConfig === "string"
53
+ ? { engine: endpointOrConfig }
54
+ : endpointOrConfig;
55
+ const config = ClientConfigSchema.parse(configInput);
56
+
57
+ // Create client
58
+ const driver = new RemoteManagerDriver(config);
59
+ return createClientWithDriver<A>(driver, config);
60
+ }