@rivetkit/cloudflare-workers 0.9.0 → 0.9.2

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.
package/dist/mod.cjs CHANGED
@@ -1,19 +1,24 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/actor-handler-do.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class;// src/handler.ts
2
+ var _async_hooks = require('async_hooks');
3
+ var _hono = require('hono');
4
+ var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant);
5
+
6
+ // src/actor-handler-do.ts
2
7
  var _cloudflareworkers = require('cloudflare:workers');
3
- var _driverhelpers = require('@rivetkit/core/driver-helpers');
4
8
 
5
- // src/log.ts
6
- var _log = require('@rivetkit/core/log');
7
- var LOGGER_NAME = "driver-cloudflare-workers";
8
- function logger() {
9
- return _log.getLogger.call(void 0, LOGGER_NAME);
10
- }
11
9
 
12
- // src/actor-handler-do.ts
13
- var _partition = require('@rivetkit/core/topologies/partition');
10
+
11
+
12
+ var _core = require('@rivetkit/core');
13
+ var _driverhelpers = require('@rivetkit/core/driver-helpers');
14
14
 
15
15
  // src/actor-driver.ts
16
- var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant);
16
+
17
+
18
+
19
+
20
+
21
+
17
22
  var CloudflareDurableObjectGlobalState = class {
18
23
  // Single map for all actor state
19
24
  #dos = /* @__PURE__ */ new Map();
@@ -26,14 +31,76 @@ var CloudflareDurableObjectGlobalState = class {
26
31
  this.#dos.set(actorId, state);
27
32
  }
28
33
  };
34
+ var ActorHandler = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this); }
35
+
36
+ __init() {this.actorPromise = Promise.withResolvers()}
37
+ __init2() {this.genericConnGlobalState = new (0, _core.GenericConnGlobalState)()}
38
+ }, _class);
29
39
  var CloudflareActorsActorDriver = class {
40
+ #registryConfig;
41
+ #runConfig;
42
+ #managerDriver;
43
+ #inlineClient;
30
44
  #globalState;
31
- constructor(globalState) {
45
+ #actors = /* @__PURE__ */ new Map();
46
+ constructor(registryConfig, runConfig, managerDriver, inlineClient, globalState) {
47
+ this.#registryConfig = registryConfig;
48
+ this.#runConfig = runConfig;
49
+ this.#managerDriver = managerDriver;
50
+ this.#inlineClient = inlineClient;
32
51
  this.#globalState = globalState;
33
52
  }
34
53
  #getDOCtx(actorId) {
35
54
  return this.#globalState.getDOState(actorId).ctx;
36
55
  }
56
+ async loadActor(actorId) {
57
+ var _a;
58
+ let handler = this.#actors.get(actorId);
59
+ if (handler) {
60
+ if (handler.actorPromise) await handler.actorPromise.promise;
61
+ if (!handler.actor) throw new Error("Actor should be loaded");
62
+ return handler.actor;
63
+ }
64
+ handler = new ActorHandler();
65
+ this.#actors.set(actorId, handler);
66
+ const doState = this.#globalState.getDOState(actorId);
67
+ const storage = doState.ctx.storage;
68
+ const [name, key] = await Promise.all([
69
+ storage.get(KEYS.NAME),
70
+ storage.get(KEYS.KEY)
71
+ ]);
72
+ if (!name) {
73
+ throw new Error(`Actor ${actorId} is not initialized - missing name`);
74
+ }
75
+ if (!key) {
76
+ throw new Error(`Actor ${actorId} is not initialized - missing key`);
77
+ }
78
+ const definition = _core.lookupInRegistry.call(void 0, this.#registryConfig, name);
79
+ handler.actor = definition.instantiate();
80
+ const connDrivers = _core.createGenericConnDrivers.call(void 0,
81
+ handler.genericConnGlobalState
82
+ );
83
+ await handler.actor.start(
84
+ connDrivers,
85
+ this,
86
+ this.#inlineClient,
87
+ actorId,
88
+ name,
89
+ key,
90
+ "unknown"
91
+ // TODO: Support regions in Cloudflare
92
+ );
93
+ (_a = handler.actorPromise) == null ? void 0 : _a.resolve();
94
+ handler.actorPromise = void 0;
95
+ return handler.actor;
96
+ }
97
+ getGenericConnGlobalState(actorId) {
98
+ const handler = this.#actors.get(actorId);
99
+ if (!handler) {
100
+ throw new Error(`Actor ${actorId} not loaded`);
101
+ }
102
+ return handler.genericConnGlobalState;
103
+ }
37
104
  getContext(actorId) {
38
105
  const state = this.#globalState.getDOState(actorId);
39
106
  return { ctx: state.ctx, env: state.env };
@@ -51,6 +118,24 @@ var CloudflareActorsActorDriver = class {
51
118
  return this.#getDOCtx(actorId).storage.sql;
52
119
  }
53
120
  };
121
+ function createCloudflareActorsActorDriverBuilder(globalState) {
122
+ return (registryConfig, runConfig, managerDriver, inlineClient) => {
123
+ return new CloudflareActorsActorDriver(
124
+ registryConfig,
125
+ runConfig,
126
+ managerDriver,
127
+ inlineClient,
128
+ globalState
129
+ );
130
+ };
131
+ }
132
+
133
+ // src/log.ts
134
+ var _log = require('@rivetkit/core/log');
135
+ var LOGGER_NAME = "driver-cloudflare-workers";
136
+ function logger() {
137
+ return _log.getLogger.call(void 0, LOGGER_NAME);
138
+ }
54
139
 
55
140
  // src/actor-handler-do.ts
56
141
  var KEYS = {
@@ -92,23 +177,27 @@ function createActorDurableObject(registry, runConfig) {
92
177
  return this.#actor;
93
178
  }
94
179
  if (!this.#initialized) throw new Error("Not initialized");
95
- runConfig.driver.actor = new CloudflareActorsActorDriver(globalState);
96
- const actorTopology = new (0, _partition.PartitionTopologyActor)(
180
+ const actorId = this.ctx.id.toString();
181
+ globalState.setDOState(actorId, { ctx: this.ctx, env: this.env });
182
+ runConfig.driver.actor = createCloudflareActorsActorDriverBuilder(globalState);
183
+ const managerDriver = runConfig.driver.manager(
97
184
  registry.config,
98
185
  runConfig
99
186
  );
100
- const actorId = this.ctx.id.toString();
101
- globalState.setDOState(actorId, { ctx: this.ctx, env: this.env });
187
+ const inlineClient = _core.createClientWithDriver.call(void 0,
188
+ _core.createInlineClientDriver.call(void 0, managerDriver)
189
+ );
190
+ const actorDriver = runConfig.driver.actor(
191
+ registry.config,
192
+ runConfig,
193
+ managerDriver,
194
+ inlineClient
195
+ );
196
+ const actorRouter = _core.createActorRouter.call(void 0, runConfig, actorDriver);
102
197
  this.#actor = {
103
- actorTopology
198
+ actorRouter
104
199
  };
105
- await actorTopology.start(
106
- actorId,
107
- this.#initialized.name,
108
- this.#initialized.key,
109
- // TODO:
110
- "unknown"
111
- );
200
+ await actorDriver.loadActor(actorId);
112
201
  return this.#actor;
113
202
  }
114
203
  /** RPC called by the service that creates the DO to initialize it. */
@@ -129,27 +218,32 @@ function createActorDurableObject(registry, runConfig) {
129
218
  }
130
219
  async fetch(request) {
131
220
  return await CF_AMBIENT_ENV.run(this.env, async () => {
132
- const { actorTopology } = await this.#loadActor();
133
- const ctx = this.ctx;
134
- return await actorTopology.router.fetch(
135
- request,
136
- this.env,
137
- // Implement execution context so we can wait on requests
138
- {
139
- waitUntil(promise) {
140
- ctx.waitUntil(promise);
141
- },
142
- passThroughOnException() {
143
- },
144
- props: {}
145
- }
146
- );
221
+ const { actorRouter } = await this.#loadActor();
222
+ const actorId = this.ctx.id.toString();
223
+ return await actorRouter.fetch(request, {
224
+ actorId
225
+ });
147
226
  });
148
227
  }
149
228
  async alarm() {
150
229
  return await CF_AMBIENT_ENV.run(this.env, async () => {
151
- const { actorTopology } = await this.#loadActor();
152
- await actorTopology.actor.onAlarm();
230
+ await this.#loadActor();
231
+ const actorId = this.ctx.id.toString();
232
+ const managerDriver = runConfig.driver.manager(
233
+ registry.config,
234
+ runConfig
235
+ );
236
+ const inlineClient = _core.createClientWithDriver.call(void 0,
237
+ _core.createInlineClientDriver.call(void 0, managerDriver)
238
+ );
239
+ const actorDriver = runConfig.driver.actor(
240
+ registry.config,
241
+ runConfig,
242
+ managerDriver,
243
+ inlineClient
244
+ );
245
+ const actor = await actorDriver.loadActor(actorId);
246
+ await actor.onAlarm();
153
247
  });
154
248
  }
155
249
  };
@@ -162,10 +256,6 @@ var ConfigSchema = _driverhelpers.RunConfigSchema.removeDefault().omit({ driver:
162
256
  app: _zod.z.custom().optional()
163
257
  }).default({});
164
258
 
165
- // src/handler.ts
166
- var _hono = require('hono');
167
-
168
-
169
259
  // src/manager-driver.ts
170
260
 
171
261
 
@@ -221,105 +311,103 @@ var STANDARD_WEBSOCKET_HEADERS = [
221
311
  "sec-websocket-extensions"
222
312
  ];
223
313
  var CloudflareActorsManagerDriver = class {
224
-
225
- constructor() {
226
- this.connRoutingHandler = {
227
- custom: {
228
- sendRequest: async (actorId, actorRequest) => {
229
- const env = getCloudflareAmbientEnv();
230
- logger().debug("sending request to durable object", {
231
- actorId,
232
- method: actorRequest.method,
233
- url: actorRequest.url
234
- });
235
- const id = env.ACTOR_DO.idFromString(actorId);
236
- const stub = env.ACTOR_DO.get(id);
237
- return await stub.fetch(actorRequest);
238
- },
239
- openWebSocket: async (actorId, encodingKind, params) => {
240
- const env = getCloudflareAmbientEnv();
241
- logger().debug("opening websocket to durable object", { actorId });
242
- const id = env.ACTOR_DO.idFromString(actorId);
243
- const stub = env.ACTOR_DO.get(id);
244
- const headers = {
245
- Upgrade: "websocket",
246
- Connection: "Upgrade",
247
- [_driverhelpers.HEADER_EXPOSE_INTERNAL_ERROR]: "true",
248
- [_driverhelpers.HEADER_ENCODING]: encodingKind
249
- };
250
- if (params) {
251
- headers[_driverhelpers.HEADER_CONN_PARAMS] = JSON.stringify(params);
252
- }
253
- headers["sec-websocket-protocol"] = "rivetkit";
254
- const response = await stub.fetch("http://actor/connect/websocket", {
255
- headers
256
- });
257
- const webSocket = response.webSocket;
258
- if (!webSocket) {
259
- throw new (0, _errors.InternalError)(
260
- "missing websocket connection in response from DO"
261
- );
262
- }
263
- logger().debug("durable object websocket connection open", {
264
- actorId
265
- });
266
- webSocket.accept();
267
- setTimeout(() => {
268
- var _a;
269
- (_a = webSocket.onopen) == null ? void 0 : _a.call(webSocket, new Event("open"));
270
- }, 0);
271
- return webSocket;
272
- },
273
- proxyRequest: async (c, actorRequest, actorId) => {
274
- logger().debug("forwarding request to durable object", {
275
- actorId,
276
- method: actorRequest.method,
277
- url: actorRequest.url
278
- });
279
- const id = c.env.ACTOR_DO.idFromString(actorId);
280
- const stub = c.env.ACTOR_DO.get(id);
281
- return await stub.fetch(actorRequest);
282
- },
283
- proxyWebSocket: async (c, path, actorId, encoding, params, authData) => {
284
- logger().debug("forwarding websocket to durable object", {
285
- actorId,
286
- path
287
- });
288
- const upgradeHeader = c.req.header("Upgrade");
289
- if (!upgradeHeader || upgradeHeader !== "websocket") {
290
- return new Response("Expected Upgrade: websocket", {
291
- status: 426
292
- });
293
- }
294
- const newUrl = new URL(`http://actor${path}`);
295
- const actorRequest = new Request(newUrl, c.req.raw);
296
- const headerKeys = [];
297
- actorRequest.headers.forEach((v, k) => headerKeys.push(k));
298
- for (const k of headerKeys) {
299
- if (!STANDARD_WEBSOCKET_HEADERS.includes(k)) {
300
- actorRequest.headers.delete(k);
301
- }
302
- }
303
- actorRequest.headers.set(_driverhelpers.HEADER_EXPOSE_INTERNAL_ERROR, "true");
304
- actorRequest.headers.set(_driverhelpers.HEADER_ENCODING, encoding);
305
- if (params) {
306
- actorRequest.headers.set(
307
- _driverhelpers.HEADER_CONN_PARAMS,
308
- JSON.stringify(params)
309
- );
310
- }
311
- if (authData) {
312
- actorRequest.headers.set(
313
- _driverhelpers.HEADER_AUTH_DATA,
314
- JSON.stringify(authData)
315
- );
316
- }
317
- const id = c.env.ACTOR_DO.idFromString(actorId);
318
- const stub = c.env.ACTOR_DO.get(id);
319
- return await stub.fetch(actorRequest);
320
- }
321
- }
314
+ async sendRequest(actorId, actorRequest) {
315
+ const env = getCloudflareAmbientEnv();
316
+ logger().debug("sending request to durable object", {
317
+ actorId,
318
+ method: actorRequest.method,
319
+ url: actorRequest.url
320
+ });
321
+ const id = env.ACTOR_DO.idFromString(actorId);
322
+ const stub = env.ACTOR_DO.get(id);
323
+ return await stub.fetch(actorRequest);
324
+ }
325
+ async openWebSocket(path, actorId, encoding, params) {
326
+ const env = getCloudflareAmbientEnv();
327
+ logger().debug("opening websocket to durable object", { actorId, path });
328
+ const id = env.ACTOR_DO.idFromString(actorId);
329
+ const stub = env.ACTOR_DO.get(id);
330
+ const headers = {
331
+ Upgrade: "websocket",
332
+ Connection: "Upgrade",
333
+ [_driverhelpers.HEADER_EXPOSE_INTERNAL_ERROR]: "true",
334
+ [_driverhelpers.HEADER_ENCODING]: encoding
322
335
  };
336
+ if (params) {
337
+ headers[_driverhelpers.HEADER_CONN_PARAMS] = JSON.stringify(params);
338
+ }
339
+ headers["sec-websocket-protocol"] = "rivetkit";
340
+ const url = `http://actor${path}`;
341
+ logger().debug("rewriting websocket url", {
342
+ from: path,
343
+ to: url
344
+ });
345
+ const response = await stub.fetch(url, {
346
+ headers
347
+ });
348
+ const webSocket = response.webSocket;
349
+ if (!webSocket) {
350
+ throw new (0, _errors.InternalError)(
351
+ "missing websocket connection in response from DO"
352
+ );
353
+ }
354
+ logger().debug("durable object websocket connection open", {
355
+ actorId
356
+ });
357
+ webSocket.accept();
358
+ setTimeout(() => {
359
+ var _a;
360
+ const event = new Event("open");
361
+ (_a = webSocket.onopen) == null ? void 0 : _a.call(webSocket, event);
362
+ webSocket.dispatchEvent(event);
363
+ }, 0);
364
+ return webSocket;
365
+ }
366
+ async proxyRequest(c, actorRequest, actorId) {
367
+ logger().debug("forwarding request to durable object", {
368
+ actorId,
369
+ method: actorRequest.method,
370
+ url: actorRequest.url
371
+ });
372
+ const id = c.env.ACTOR_DO.idFromString(actorId);
373
+ const stub = c.env.ACTOR_DO.get(id);
374
+ return await stub.fetch(actorRequest);
375
+ }
376
+ async proxyWebSocket(c, path, actorId, encoding, params, authData) {
377
+ logger().debug("forwarding websocket to durable object", {
378
+ actorId,
379
+ path
380
+ });
381
+ const upgradeHeader = c.req.header("Upgrade");
382
+ if (!upgradeHeader || upgradeHeader !== "websocket") {
383
+ return new Response("Expected Upgrade: websocket", {
384
+ status: 426
385
+ });
386
+ }
387
+ const newUrl = new URL(`http://actor${path}`);
388
+ const actorRequest = new Request(newUrl, c.req.raw);
389
+ logger().debug("rewriting websocket url", {
390
+ from: c.req.url,
391
+ to: actorRequest.url
392
+ });
393
+ const headerKeys = [];
394
+ actorRequest.headers.forEach((v, k) => headerKeys.push(k));
395
+ for (const k of headerKeys) {
396
+ if (!STANDARD_WEBSOCKET_HEADERS.includes(k)) {
397
+ actorRequest.headers.delete(k);
398
+ }
399
+ }
400
+ actorRequest.headers.set(_driverhelpers.HEADER_EXPOSE_INTERNAL_ERROR, "true");
401
+ actorRequest.headers.set(_driverhelpers.HEADER_ENCODING, encoding);
402
+ if (params) {
403
+ actorRequest.headers.set(_driverhelpers.HEADER_CONN_PARAMS, JSON.stringify(params));
404
+ }
405
+ if (authData) {
406
+ actorRequest.headers.set(_driverhelpers.HEADER_AUTH_DATA, JSON.stringify(authData));
407
+ }
408
+ const id = c.env.ACTOR_DO.idFromString(actorId);
409
+ const stub = c.env.ACTOR_DO.get(id);
410
+ return await stub.fetch(actorRequest);
323
411
  }
324
412
  async getForId({
325
413
  c,
@@ -487,8 +575,6 @@ var upgradeWebSocket = _ws.defineWebSocketHelper.call(void 0, async (c, events)
487
575
  });
488
576
 
489
577
  // src/handler.ts
490
-
491
- var _async_hooks = require('async_hooks');
492
578
  var CF_AMBIENT_ENV = new (0, _async_hooks.AsyncLocalStorage)();
493
579
  function getCloudflareAmbientEnv() {
494
580
  const env = CF_AMBIENT_ENV.getStore();
@@ -503,30 +589,28 @@ function createServer(registry, inputConfig) {
503
589
  const config = ConfigSchema.parse(inputConfig);
504
590
  const runConfig = {
505
591
  driver: {
506
- topology: "partition",
507
- manager: new CloudflareActorsManagerDriver(),
508
- // HACK: We can't build the actor driver until we're inside the Druable Object
592
+ manager: () => new CloudflareActorsManagerDriver(),
593
+ // HACK: We can't build the actor driver until we're inside the Durable Object
509
594
  actor: void 0
510
595
  },
511
596
  getUpgradeWebSocket: () => upgradeWebSocket,
512
597
  ...config
513
598
  };
514
- const ActorHandler = createActorDurableObject(registry, runConfig);
515
- const managerTopology = new (0, _partition.PartitionTopologyManager)(
516
- registry.config,
517
- runConfig
518
- );
599
+ const ActorHandler2 = createActorDurableObject(registry, runConfig);
600
+ const serverOutput = registry.createServer(runConfig);
519
601
  return {
520
- client: managerTopology.inlineClient,
602
+ client: serverOutput.client,
521
603
  createHandler: (hono) => {
522
604
  const app = _nullishCoalesce(hono, () => ( new (0, _hono.Hono)()));
523
- app.route("/registry", managerTopology.router);
605
+ if (!hono) {
606
+ app.route("/registry", serverOutput.hono);
607
+ }
524
608
  const handler = {
525
609
  fetch: (request, env, ctx) => {
526
610
  return CF_AMBIENT_ENV.run(env, () => app.fetch(request, env, ctx));
527
611
  }
528
612
  };
529
- return { handler, ActorHandler };
613
+ return { handler, ActorHandler: ActorHandler2 };
530
614
  }
531
615
  };
532
616
  }