nestjs-cloudflare 0.1.0 → 0.4.0
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/README.md +270 -4
- package/dist/cloudflare.module.d.ts +1 -0
- package/dist/cloudflare.module.js +12 -2
- package/dist/durable-objects/client.d.ts +13 -0
- package/dist/durable-objects/client.js +67 -0
- package/dist/durable-objects/constants.d.ts +1 -0
- package/dist/durable-objects/constants.js +1 -0
- package/dist/durable-objects/context.d.ts +18 -0
- package/dist/durable-objects/context.js +53 -0
- package/dist/durable-objects/context.transport.d.ts +9 -0
- package/dist/durable-objects/context.transport.js +13 -0
- package/dist/durable-objects/durable-object.d.ts +11 -0
- package/dist/durable-objects/durable-object.js +21 -0
- package/dist/durable-objects/index.d.ts +9 -0
- package/dist/durable-objects/index.js +7 -0
- package/dist/durable-objects/interfaces/client-options.interface.d.ts +15 -0
- package/dist/durable-objects/interfaces/client-options.interface.js +1 -0
- package/dist/durable-objects/interfaces/server-options.interface.d.ts +14 -0
- package/dist/durable-objects/interfaces/server-options.interface.js +1 -0
- package/dist/durable-objects/record-builder.d.ts +16 -0
- package/dist/durable-objects/record-builder.js +28 -0
- package/dist/durable-objects/record.serializer.d.ts +10 -0
- package/dist/durable-objects/record.serializer.js +10 -0
- package/dist/durable-objects/server.d.ts +16 -0
- package/dist/durable-objects/server.js +101 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/interfaces/worker-options.interface.d.ts +32 -1
- package/dist/interfaces/worker.interface.d.ts +3 -1
- package/dist/queue/client.js +10 -2
- package/dist/queue/index.d.ts +2 -0
- package/dist/queue/index.js +2 -0
- package/dist/queue/record-builder.d.ts +19 -0
- package/dist/queue/record-builder.js +32 -0
- package/dist/queue/record.serializer.d.ts +10 -0
- package/dist/queue/record.serializer.js +14 -0
- package/dist/schedule/cron.explorer.d.ts +3 -0
- package/dist/schedule/cron.explorer.js +20 -4
- package/dist/websockets/adapter.d.ts +8 -1
- package/dist/websockets/adapter.js +30 -5
- package/dist/websockets/context.d.ts +12 -0
- package/dist/websockets/context.js +15 -0
- package/dist/websockets/durable-object.d.ts +3 -0
- package/dist/websockets/durable-object.js +7 -0
- package/dist/websockets/gateway-durable-object.d.ts +17 -0
- package/dist/websockets/gateway-durable-object.js +82 -0
- package/dist/websockets/index.d.ts +4 -0
- package/dist/websockets/index.js +2 -0
- package/dist/websockets/interfaces/adapter-options.interface.d.ts +4 -0
- package/dist/websockets/interfaces/gateway-options.interface.d.ts +11 -0
- package/dist/websockets/interfaces/gateway-options.interface.js +1 -0
- package/dist/websockets/message-dispatcher.d.ts +8 -0
- package/dist/websockets/message-dispatcher.js +26 -0
- package/dist/worker/create-worker.d.ts +1 -0
- package/dist/worker/create-worker.js +167 -43
- package/dist/worker/request-context.d.ts +19 -0
- package/dist/worker/request-context.js +38 -0
- package/dist/worker/websocket-routing.d.ts +3 -0
- package/dist/worker/websocket-routing.js +10 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -46,6 +46,54 @@ export default createWorker(bootstrap);
|
|
|
46
46
|
|
|
47
47
|
Keep Nest creation inside `bootstrap`. Cloudflare's upload validation runs module initialization without all bindings and disallows I/O and random number generation. Deferring Nest startup to an event avoids those restrictions. Choose HTTP adapters, application options, global guards, pipes, filters, and interceptors in your bootstrap function.
|
|
48
48
|
|
|
49
|
+
For incremental HTTP migration, pass a native fallback. `fetch` checks the initialized Express route table before dispatch and leaves unmatched request bodies untouched:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { CloudflareRequestContext } from 'nestjs-cloudflare';
|
|
53
|
+
|
|
54
|
+
const worker = createWorker(bootstrap, {
|
|
55
|
+
fallback: {
|
|
56
|
+
async fetch(request, env, ctx) {
|
|
57
|
+
const app = await worker.getApplication();
|
|
58
|
+
const error = app.get(CloudflareRequestContext).getRouteError();
|
|
59
|
+
if (error) return new Response('Invalid route encoding', { status: 400 });
|
|
60
|
+
return legacyRouter.fetch(request, env, ctx);
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
routing: { headImplicitMatch: false },
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
await worker.matches(request); // true for a configured WebSocket path or Nest route
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Configure Express before constructing the Nest adapter so its router uses the
|
|
70
|
+
same settings during pre-matching and dispatch:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import express from 'express';
|
|
74
|
+
import { ExpressAdapter } from '@nestjs/platform-express';
|
|
75
|
+
|
|
76
|
+
async function bootstrap() {
|
|
77
|
+
const instance = express();
|
|
78
|
+
instance.set('case sensitive routing', true);
|
|
79
|
+
instance.set('strict routing', true);
|
|
80
|
+
return NestFactory.create(AppModule, new ExpressAdapter(instance));
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The optional `routing.caseSensitive` and `routing.strict` values validate these
|
|
85
|
+
Express settings. Their aliases are `caseSensitiveRouting` and `strictRouting`.
|
|
86
|
+
A mismatch fails startup with instructions to configure Express before creating
|
|
87
|
+
the adapter. They do not change an existing router. Omit them to use the
|
|
88
|
+
bootstrap settings. The default Express configuration remains case-insensitive
|
|
89
|
+
and accepts trailing slashes.
|
|
90
|
+
|
|
91
|
+
Set `routing.headImplicitMatch: false` when a `HEAD` request should match only
|
|
92
|
+
an explicitly registered `HEAD` route. Unmatched requests go to `fallback.fetch`.
|
|
93
|
+
The default preserves Express's implicit `GET` handling.
|
|
94
|
+
|
|
95
|
+
Use `around.fetch`, `around.scheduled`, or `around.queue` to wrap complete event dispatch. Each hook receives the native event values and a `next` function. `CloudflareRequestContext` is a singleton provider exported by `CloudflareModule.forRoot()`; inject it to read `getRequest()`, `getEnv()`, `getExecutionContext()`, and `getRouteError()` from the current event. When Express cannot decode a route parameter, pre-matching sends the request to `fallback.fetch` and `getRouteError()` returns the `URIError`.
|
|
96
|
+
|
|
49
97
|
## Bindings
|
|
50
98
|
|
|
51
99
|
`CloudflareModule.forRoot()` registers global providers for the bindings in `cloudflare:workers`' imported `env`. Import it once in the root module. Bindings are injected directly, including primitive variables.
|
|
@@ -111,7 +159,7 @@ Register the service as a provider. Do not import Nest's `ScheduleModule`: Cloud
|
|
|
111
159
|
|
|
112
160
|
Expressions must have five fields and match `ScheduledController.cron` exactly. Workers schedules use UTC. Empty and six-field expressions produce startup warnings; six-field values from Nest's `CronExpression` enum cannot match Workers triggers. Every matching method runs. Non-static providers are skipped with a warning.
|
|
113
161
|
|
|
114
|
-
`disabled` suppresses a handler. `waitForCompletion` skips overlapping invocations within one isolate. Timer-specific options such as `timeZone` do not configure Cloudflare triggers.
|
|
162
|
+
`disabled` suppresses a handler. `waitForCompletion` skips overlapping invocations within one isolate. Timer-specific options such as `timeZone` do not configure Cloudflare triggers. `scheduled()` waits for all matching handlers to finish and rejects with an `AggregateError` if any handler fails. Unmatched events use `fallback.scheduled` when provided and otherwise produce a warning.
|
|
115
163
|
|
|
116
164
|
## Queues
|
|
117
165
|
|
|
@@ -163,6 +211,20 @@ class NotificationsService {
|
|
|
163
211
|
class NotificationsModule {}
|
|
164
212
|
```
|
|
165
213
|
|
|
214
|
+
Use `CloudflareQueueRecordBuilder` to attach native `QueueSendOptions`, following Nest's transport record builder convention:
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
import { CloudflareQueueRecordBuilder } from 'nestjs-cloudflare/queue';
|
|
218
|
+
|
|
219
|
+
const record = new CloudflareQueueRecordBuilder({ id: 'activity' })
|
|
220
|
+
.setOptions({ delaySeconds: 60, contentType: 'json' })
|
|
221
|
+
.build();
|
|
222
|
+
|
|
223
|
+
await firstValueFrom(client.emit('notifications', record));
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
The default serializer unwraps the record and passes its options to `queue.send`. Options are not included in the message body. A custom serializer replaces the default and must return `{ ...packet, data, options }` to use send options.
|
|
227
|
+
|
|
166
228
|
For dependency injection into the client factory, use `ClientsModule.registerAsync` with `inject: [getBindingToken<Env>('NOTIFICATIONS')]` and return `{ customClass: CloudflareQueueClient, options: { queue } }`. Client and server options accept Nest serializers and deserializers. `emit` sends the Nest event packet, preserving its pattern and metadata. One Queue can carry multiple patterns. `send` rejects because Cloudflare Queues do not support request-response messaging.
|
|
167
229
|
|
|
168
230
|
```ts
|
|
@@ -188,7 +250,7 @@ class NotificationsController {
|
|
|
188
250
|
}
|
|
189
251
|
```
|
|
190
252
|
|
|
191
|
-
The context exposes the original message, batch, execution context, and pattern. For messages sent by other producers without a Nest packet, the Queue name is the event pattern. Successful messages are acknowledged automatically by default. Set `noAck: false`
|
|
253
|
+
The context exposes the original message, batch, execution context, and pattern. For messages sent by other producers without a Nest packet, the Queue name is the event pattern. Successful messages are acknowledged automatically by default. Set `noAck: false` for manual acknowledgement. A handler can discard an invalid message with `context.getMessage().ack()` or retry a locked message with `context.getMessage().retry({ delaySeconds: 30 })`. Return normally after either call so the handler controls that message's outcome. Failed handlers request retries in either mode.
|
|
192
254
|
|
|
193
255
|
Batches are sequential by default. Set `concurrency: 'parallel'` on the server to process messages concurrently. Unhandled messages use `fallback.queue` when supplied. Missing transports and unhandled events are reported explicitly. Fallbacks are passed as the second argument to `createWorker`:
|
|
194
256
|
|
|
@@ -270,9 +332,73 @@ export class ChatRoom extends CloudflareWebSocketDurableObject<Env> {
|
|
|
270
332
|
}
|
|
271
333
|
```
|
|
272
334
|
|
|
273
|
-
Register the gateway as an application provider.
|
|
335
|
+
Register the gateway as an application provider. Configure the Durable Object binding and migration, then declare native forwarding in `createWorker`:
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
const worker = createWorker<Env>(bootstrap, {
|
|
339
|
+
websockets: [{ paths: ['/chat'], binding: 'CHAT', object: 'shared-chat' }],
|
|
340
|
+
});
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Each entry selects exact URL pathnames, a Durable Object namespace binding from the event's `env`, and an object name. For a shared API object, use `{ paths: ['/ws', '/mobula'], binding: 'API_WEBSOCKET', object: 'api-websocket' }`. These paths must also be configured on the object's gateway host and declared with `@WebSocketGateway({ path })`. Entries are checked in order; the first matching entry wins. Matching is case-sensitive, distinguishes trailing slashes, ignores query strings, and is independent of Express routing settings.
|
|
344
|
+
|
|
345
|
+
Use `object: request => new URL(request.url).searchParams.get('room') ?? 'default'` to select a name per request. Strings are resolved with the namespace's `idFromName()`. A resolver may instead return a native `DurableObjectId`, such as `object: request => env.CHAT.idFromString(new URL(request.url).searchParams.get('id')!)`.
|
|
346
|
+
|
|
347
|
+
Forwarding runs inside `around.fetch`, before Express and `fallback.fetch`. The original request, including its URL, headers, and body, goes directly to `namespace.get(id).fetch(request)`. The object's response is returned unchanged, including the WebSocket on a `101` response. Matching non-upgrade requests also go to the object: both gateway hosts return `426` by default, and `CloudflareWebSocketGatewayDurableObject` subclasses can override `nonWebSocketFetch`. `worker.matches(request)` returns `true` for configured paths regardless of method or upgrade headers, without starting Nest or calling the object resolver. Unmatched paths retain the usual Nest and fallback behavior.
|
|
348
|
+
|
|
349
|
+
`CloudflareWebSocketAdapter` accepts `maxConcurrentMessages`, matching Nest's `@nestjs/platform-ws` option. The default is `1000`, so asynchronous messages on one connection can overlap. Use `new CloudflareWebSocketAdapter({ maxConcurrentMessages: 1 })` when authentication must finish before a later subscription is handled. The limit applies per connection to both Durable Object hosts, including messages delivered through `webSocketMessage` after hibernation. Other connections can keep processing independently. An in-progress handler must finish before the next queued message starts when the limit is `1`.
|
|
350
|
+
|
|
351
|
+
Gateways use port `0`, the default. Separate listening ports and Socket.IO namespaces are unsupported.
|
|
352
|
+
|
|
353
|
+
The base class implements `fetch`, `webSocketMessage`, `webSocketClose`, and `webSocketError`. It accepts connections through `ctx.acceptWebSocket` and waits for Nest startup before dispatching events after hibernation. Restored connections are registered with Nest again, so `handleConnection` can run more than once for a socket. Singleton gateways are shared by the application. Inject durable providers for object-owned I/O and keep persistent room state in Durable Object storage or socket attachments.
|
|
354
|
+
|
|
355
|
+
For Durable Objects that must keep in-memory sessions, timers, and upstream sockets, use the non-hibernating gateway host. It calls `server.accept()` and keeps each object's sockets isolated:
|
|
356
|
+
|
|
357
|
+
```ts
|
|
358
|
+
import {
|
|
359
|
+
ConnectedSocket,
|
|
360
|
+
SubscribeMessage,
|
|
361
|
+
WebSocketGateway,
|
|
362
|
+
} from '@nestjs/websockets';
|
|
363
|
+
import {
|
|
364
|
+
CloudflareWebSocketAdapter,
|
|
365
|
+
CloudflareWebSocketGatewayDurableObject,
|
|
366
|
+
getCloudflareWebSocketContext,
|
|
367
|
+
} from 'nestjs-cloudflare/websockets';
|
|
368
|
+
|
|
369
|
+
@WebSocketGateway({ path: '/ws' })
|
|
370
|
+
@WebSocketGateway({ path: '/mobula' })
|
|
371
|
+
class ApiGateway {
|
|
372
|
+
@SubscribeMessage('publish')
|
|
373
|
+
publish(@ConnectedSocket() socket: WebSocket, value: unknown): null {
|
|
374
|
+
const { sockets } = getCloudflareWebSocketContext(socket);
|
|
375
|
+
for (const peer of sockets) {
|
|
376
|
+
peer.send(JSON.stringify(value));
|
|
377
|
+
}
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const adapter = new CloudflareWebSocketAdapter({
|
|
383
|
+
messageSerializer: value => JSON.stringify(value),
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
export class ApiWebSocket extends CloudflareWebSocketGatewayDurableObject<Env> {
|
|
387
|
+
constructor(ctx: DurableObjectState, env: Env) {
|
|
388
|
+
super(ctx, env, {
|
|
389
|
+
adapter,
|
|
390
|
+
paths: ['/ws', '/mobula'],
|
|
391
|
+
getApplication: worker.getApplication,
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
protected nonWebSocketFetch(request: Request): Response {
|
|
396
|
+
return new Response(`internal:${new URL(request.url).pathname}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
```
|
|
274
400
|
|
|
275
|
-
|
|
401
|
+
`getCloudflareWebSocketContext(socket)` exposes the owning object's `ctx`, `storage`, `env`, object instance, and in-memory `sockets` set. `messageSerializer` may return a string or `ArrayBuffer`, so binary or protocol-specific frames are supported. The `paths` list lets one Durable Object serve multiple gateway paths; in the example the same gateway handles `/ws` and `/mobula`. Override `nonWebSocketFetch` for the object's other requests.
|
|
276
402
|
|
|
277
403
|
Clients send `{"event":"echo","data":"hello"}`. The handler receives `data` and its return value is JSON-serialized directly to the client. Promise and observable results are supported. Configure `messageParser` for another wire protocol:
|
|
278
404
|
|
|
@@ -289,6 +415,146 @@ const adapter = new CloudflareWebSocketAdapter({
|
|
|
289
415
|
|
|
290
416
|
A parser can return `undefined` to ignore a frame. The default parser closes malformed JSON messages with code `1007`. A custom parser can throw `InvalidWebSocketMessageException` for that close code; unexpected failures close with `1011`.
|
|
291
417
|
|
|
418
|
+
## Durable Object microservices
|
|
419
|
+
|
|
420
|
+
Install `@nestjs/microservices`. Connect a `CloudflareDurableObjectServer` during bootstrap, just like the Queue transport. Import `CloudflareModule.forRoot()` in `AppModule` to provide `CloudflareRequestContext`.
|
|
421
|
+
|
|
422
|
+
```ts
|
|
423
|
+
import { NestFactory } from '@nestjs/core';
|
|
424
|
+
import {
|
|
425
|
+
CloudflareDurableObject,
|
|
426
|
+
CloudflareDurableObjectServer,
|
|
427
|
+
} from 'nestjs-cloudflare/durable-objects';
|
|
428
|
+
|
|
429
|
+
const transport = new CloudflareDurableObjectServer();
|
|
430
|
+
let application: ReturnType<typeof bootstrap> | undefined;
|
|
431
|
+
|
|
432
|
+
async function bootstrap() {
|
|
433
|
+
const app = await NestFactory.create(AppModule);
|
|
434
|
+
app.connectMicroservice({ strategy: transport }, { inheritAppConfig: true });
|
|
435
|
+
await app.init();
|
|
436
|
+
await app.startAllMicroservices();
|
|
437
|
+
return app;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export class JobLease extends CloudflareDurableObject<Env> {
|
|
441
|
+
constructor(state: DurableObjectState, env: Env) {
|
|
442
|
+
super(state, env, {
|
|
443
|
+
server: transport,
|
|
444
|
+
getApplication: () => (application ??= bootstrap()),
|
|
445
|
+
alarmPattern: 'alarm',
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
Export the class from the Worker entry point and register it in Wrangler's Durable Object bindings and migrations. This transport uses native Workers RPC and requires a compatibility date of `2024-04-03` or later. It does not expose an HTTP URL. Each message carries Nest's pattern and data to the object's `dispatch` RPC method.
|
|
452
|
+
|
|
453
|
+
Register handlers as Nest controllers. `@Ctx()` receives the native state, environment, and normalized pattern. Durable providers use the same object isolation described below; ordinary request providers are recreated for each invocation.
|
|
454
|
+
|
|
455
|
+
```ts
|
|
456
|
+
import { Controller, Injectable, Scope } from '@nestjs/common';
|
|
457
|
+
import {
|
|
458
|
+
Ctx,
|
|
459
|
+
EventPattern,
|
|
460
|
+
MessagePattern,
|
|
461
|
+
Payload,
|
|
462
|
+
} from '@nestjs/microservices';
|
|
463
|
+
import { CloudflareDurableObjectContext } from 'nestjs-cloudflare/durable-objects';
|
|
464
|
+
|
|
465
|
+
@Injectable({ scope: Scope.REQUEST, durable: true })
|
|
466
|
+
class LeaseService {
|
|
467
|
+
async acquire(state: DurableObjectState, owner: string) {
|
|
468
|
+
return state.storage.transaction(async storage => {
|
|
469
|
+
if (await storage.get('owner')) {
|
|
470
|
+
return { acquired: false };
|
|
471
|
+
}
|
|
472
|
+
await storage.put('owner', owner);
|
|
473
|
+
return { acquired: true };
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
@Controller()
|
|
479
|
+
class LeaseController {
|
|
480
|
+
constructor(private readonly leases: LeaseService) {}
|
|
481
|
+
|
|
482
|
+
@MessagePattern('acquire')
|
|
483
|
+
acquire(
|
|
484
|
+
@Payload() owner: string,
|
|
485
|
+
@Ctx() context: CloudflareDurableObjectContext,
|
|
486
|
+
) {
|
|
487
|
+
return this.leases.acquire(context.getState(), owner);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
@EventPattern('alarm')
|
|
491
|
+
async alarm(@Ctx() context: CloudflareDurableObjectContext) {
|
|
492
|
+
await context.getState().storage.delete('owner');
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
Register `LeaseController` in `controllers` and `LeaseService` in `providers`. Schedule alarms with `context.getState().storage.setAlarm(timestamp)`. The base class dispatches native alarms to `@EventPattern('alarm')`, or to the configured `alarmPattern`, and awaits completion so failures can trigger Cloudflare's alarm retries. Alarm data is `undefined`.
|
|
498
|
+
|
|
499
|
+
Register the client through `ClientsModule` and select the target separately for each message using Nest's record builder convention:
|
|
500
|
+
|
|
501
|
+
```ts
|
|
502
|
+
import { ClientsModule } from '@nestjs/microservices';
|
|
503
|
+
import { env } from 'cloudflare:workers';
|
|
504
|
+
import { firstValueFrom } from 'rxjs';
|
|
505
|
+
import {
|
|
506
|
+
CloudflareDurableObjectClient,
|
|
507
|
+
CloudflareDurableObjectRecordBuilder,
|
|
508
|
+
} from 'nestjs-cloudflare/durable-objects';
|
|
509
|
+
|
|
510
|
+
const clients = ClientsModule.register([
|
|
511
|
+
{
|
|
512
|
+
name: 'JOB_LEASES',
|
|
513
|
+
customClass: CloudflareDurableObjectClient,
|
|
514
|
+
options: { namespace: env.JOB_LEASES },
|
|
515
|
+
},
|
|
516
|
+
]);
|
|
517
|
+
|
|
518
|
+
// Import clients in a Nest module and inject its ClientProxy with @Inject('JOB_LEASES').
|
|
519
|
+
const record = new CloudflareDurableObjectRecordBuilder('worker-owner')
|
|
520
|
+
.setOptions({ name: 'job:sync-feed' })
|
|
521
|
+
.build();
|
|
522
|
+
const result = await firstValueFrom(client.send('acquire', record));
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
Use `{ id: durableObjectId.toString() }` instead of `{ name }` to address an existing ID. Address options stay outside handler data. `ClientsModule.registerAsync` can inject a namespace using `getBindingToken`, as with Queues. `emit` invokes `@EventPattern` handlers and awaits their completion.
|
|
526
|
+
|
|
527
|
+
Both client and server accept Nest serializers and deserializers. The default client serializer unwraps records into `{ ...packet, data, options }`; a replacement serializer must preserve that shape to select an object. `send` preserves the payload from `RpcException`, including structured error codes, as the Observable error. Handler Observable replies are collected until completion and returned in order by the RPC call; use finite streams.
|
|
528
|
+
|
|
529
|
+
`CloudflareRequestContext` is available inside request and alarm handlers. `getEnv()` returns the object's environment, `getRequest()` returns `undefined`, and `getExecutionContext()` returns its native `DurableObjectState`, including `waitUntil`. The execution-context type also permits Worker `ExecutionContext` for Worker events; narrow the union before using event-specific methods.
|
|
530
|
+
|
|
531
|
+
## Durable Object dependency scopes
|
|
532
|
+
|
|
533
|
+
Mark providers that own upstream sockets, fetch streams, or timers with Nest's `@Injectable({ scope: Scope.REQUEST, durable: true })`. Both gateway hosts bind each accepted or restored socket to its owning Durable Object before Nest resolves the gateway. Nest's durable dependency tree is reused across connections and events in that object. Default singleton providers remain shared across the application, and ordinary request-scoped providers retain their event or connection scope.
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
import { Injectable, Scope } from '@nestjs/common';
|
|
537
|
+
import { resolveForDurableObject } from 'nestjs-cloudflare';
|
|
538
|
+
|
|
539
|
+
@Injectable({ scope: Scope.REQUEST, durable: true })
|
|
540
|
+
class UpstreamClient {
|
|
541
|
+
// Create and retain upstream I/O here, in the owning object's event.
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// Inside a native Durable Object's fetch, alarm, or RPC method:
|
|
545
|
+
const client = await resolveForDurableObject(
|
|
546
|
+
await worker.getApplication(),
|
|
547
|
+
this.ctx,
|
|
548
|
+
UpstreamClient,
|
|
549
|
+
);
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
Register the provider in a Nest module. A gateway can inject it through its constructor; durability propagates through the dependency tree according to [Nest's durable provider rules](https://docs.nestjs.com/fundamentals/injection-scopes#durable-providers). In subclasses of either gateway host, use `await this.resolve(UpstreamClient)` from `fetch`, `nonWebSocketFetch`, `alarm`, or RPC handlers. Native Durable Objects use `resolveForDurableObject(app, ctx, token)` in each event. Resolve within the owning object's event so workerd also assigns any new I/O to that object.
|
|
553
|
+
|
|
554
|
+
The package installs `DurableObjectContextIdStrategy` globally through `ContextIdFactory.apply` on first use. It associates Nest event contexts with the object's state and ID, and selects their shared parent only for durable dependency trees. This occupies Nest's single global strategy slot; applications with another custom strategy must compose the strategies. `getDurableObjectContextId(ctx)` exposes the event context for direct Nest integration. The helper also registers the context payload, so `@Inject(REQUEST)` can receive `{ durableObjectId, ctx }`.
|
|
555
|
+
|
|
556
|
+
Context ownership is weakly keyed by the native `DurableObjectState`, so an evicted activation does not leave an isolate-wide ID cache behind. Hibernation, eviction, or isolate restart creates a new in-memory provider tree; durable providers do not persist sockets, timers, or JavaScript state across those boundaries. Use non-hibernating hosts when upstream sessions must stay in memory, and use Durable Object storage for persistent state. Nest does not run application lifecycle hooks for request-scoped providers; manage object-owned resources explicitly.
|
|
557
|
+
|
|
292
558
|
## Build and local development
|
|
293
559
|
|
|
294
560
|
Compile application TypeScript with `experimentalDecorators` and `emitDecoratorMetadata` before Wrangler bundles the emitted JavaScript. Wrangler's esbuild compilation does not emit the metadata Nest needs for dependency injection. Enable `nodejs_compat` and `enable_nodejs_http_server_modules` for Node HTTP support.
|
|
@@ -9,6 +9,8 @@ import { Global, Module, } from '@nestjs/common';
|
|
|
9
9
|
import { env } from 'cloudflare:workers';
|
|
10
10
|
import { getBindingToken } from './bindings/get-binding-token.js';
|
|
11
11
|
import { CLOUDFLARE_ENV } from './constants.js';
|
|
12
|
+
import { CloudflareRequestContext } from './worker/request-context.js';
|
|
13
|
+
export { CloudflareRequestContext } from './worker/request-context.js';
|
|
12
14
|
/**
|
|
13
15
|
* Makes the native Cloudflare environment and its bindings available to Nest.
|
|
14
16
|
*
|
|
@@ -27,8 +29,16 @@ let CloudflareModule = CloudflareModule_1 = class CloudflareModule {
|
|
|
27
29
|
}
|
|
28
30
|
return {
|
|
29
31
|
module: CloudflareModule_1,
|
|
30
|
-
providers: [
|
|
31
|
-
|
|
32
|
+
providers: [
|
|
33
|
+
CloudflareRequestContext,
|
|
34
|
+
{ provide: CLOUDFLARE_ENV, useValue: env },
|
|
35
|
+
...bindings,
|
|
36
|
+
],
|
|
37
|
+
exports: [
|
|
38
|
+
CloudflareRequestContext,
|
|
39
|
+
CLOUDFLARE_ENV,
|
|
40
|
+
...bindings.map(binding => binding.provide),
|
|
41
|
+
],
|
|
32
42
|
};
|
|
33
43
|
}
|
|
34
44
|
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ClientProxy, type ReadPacket, type WritePacket } from '@nestjs/microservices';
|
|
2
|
+
import type { CloudflareDurableObjectClientOptions } from './interfaces/client-options.interface.js';
|
|
3
|
+
/** Publishes Nest packets through native Durable Object RPC. */
|
|
4
|
+
export declare class CloudflareDurableObjectClient extends ClientProxy {
|
|
5
|
+
private readonly options;
|
|
6
|
+
constructor(options: CloudflareDurableObjectClientOptions);
|
|
7
|
+
connect(): Promise<DurableObjectNamespace>;
|
|
8
|
+
close(): void;
|
|
9
|
+
unwrap<T>(): T;
|
|
10
|
+
protected publish(packet: ReadPacket, callback: (packet: WritePacket) => void): () => void;
|
|
11
|
+
protected dispatchEvent<T>(packet: ReadPacket): Promise<T>;
|
|
12
|
+
private request;
|
|
13
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { ClientProxy, } from '@nestjs/microservices';
|
|
2
|
+
import { CloudflareDurableObjectRecordSerializer } from './record.serializer.js';
|
|
3
|
+
/** Publishes Nest packets through native Durable Object RPC. */
|
|
4
|
+
export class CloudflareDurableObjectClient extends ClientProxy {
|
|
5
|
+
options;
|
|
6
|
+
constructor(options) {
|
|
7
|
+
super();
|
|
8
|
+
this.options = options;
|
|
9
|
+
this.initializeSerializer({
|
|
10
|
+
...options,
|
|
11
|
+
serializer: options.serializer ?? new CloudflareDurableObjectRecordSerializer(),
|
|
12
|
+
});
|
|
13
|
+
this.initializeDeserializer(options);
|
|
14
|
+
}
|
|
15
|
+
async connect() {
|
|
16
|
+
return this.options.namespace;
|
|
17
|
+
}
|
|
18
|
+
close() { }
|
|
19
|
+
unwrap() {
|
|
20
|
+
return this.options.namespace;
|
|
21
|
+
}
|
|
22
|
+
publish(packet, callback) {
|
|
23
|
+
let active = true;
|
|
24
|
+
void this.request(this.assignPacketId(packet))
|
|
25
|
+
.then(async (replies) => {
|
|
26
|
+
for (const reply of replies) {
|
|
27
|
+
const response = await this.deserializer.deserialize(reply);
|
|
28
|
+
if (active) {
|
|
29
|
+
callback(response);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
.catch((err) => {
|
|
34
|
+
if (active) {
|
|
35
|
+
callback({ err });
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
return () => {
|
|
39
|
+
active = false;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async dispatchEvent(packet) {
|
|
43
|
+
const replies = await this.request(packet);
|
|
44
|
+
const packets = await Promise.all(replies.map(reply => this.deserializer.deserialize(reply)));
|
|
45
|
+
const failure = packets.find(reply => reply.err !== undefined);
|
|
46
|
+
if (failure) {
|
|
47
|
+
throw failure.err;
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
async request(packet) {
|
|
52
|
+
const { options, ...message } = await this.serializer.serialize({
|
|
53
|
+
...packet,
|
|
54
|
+
pattern: this.normalizePattern(packet.pattern),
|
|
55
|
+
});
|
|
56
|
+
if (!options ||
|
|
57
|
+
(typeof options.name !== 'string' && typeof options.id !== 'string')) {
|
|
58
|
+
throw new Error('Durable Object messages require a record with a name or ID');
|
|
59
|
+
}
|
|
60
|
+
const namespace = this.options.namespace;
|
|
61
|
+
const id = options.id === undefined
|
|
62
|
+
? namespace.idFromName(options.name)
|
|
63
|
+
: namespace.idFromString(options.id);
|
|
64
|
+
const stub = namespace.get(id);
|
|
65
|
+
return stub.dispatch(message);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const CLOUDFLARE_DURABLE_OBJECT_TRANSPORT: unique symbol;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const CLOUDFLARE_DURABLE_OBJECT_TRANSPORT = Symbol('CLOUDFLARE_DURABLE_OBJECT_TRANSPORT');
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { INestApplicationContext, InjectionToken } from '@nestjs/common';
|
|
2
|
+
import { type ContextId, type ContextIdStrategy, type HostComponentInfo } from '@nestjs/core';
|
|
3
|
+
/** Groups durable dependency trees by their owning Durable Object activation. */
|
|
4
|
+
export declare class DurableObjectContextIdStrategy implements ContextIdStrategy<object> {
|
|
5
|
+
attach(contextId: ContextId, request: object): {
|
|
6
|
+
resolve: (info: HostComponentInfo) => ContextId;
|
|
7
|
+
payload: {
|
|
8
|
+
durableObjectId: string;
|
|
9
|
+
ctx: DurableObjectState<unknown>;
|
|
10
|
+
};
|
|
11
|
+
} | undefined;
|
|
12
|
+
}
|
|
13
|
+
/** Associates a native event source with its object's Nest dependency tree. */
|
|
14
|
+
export declare function attachDurableObjectContext(source: object, ctx: DurableObjectState): void;
|
|
15
|
+
/** Creates an event context whose durable providers belong to this object. */
|
|
16
|
+
export declare function getDurableObjectContextId(ctx: DurableObjectState): ContextId;
|
|
17
|
+
/** Resolves a provider for fetch, alarm, or RPC in the current object. */
|
|
18
|
+
export declare function resolveForDurableObject<T>(app: INestApplicationContext, ctx: DurableObjectState, token: InjectionToken<T>): Promise<T>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { ContextIdFactory, } from '@nestjs/core';
|
|
2
|
+
const owners = new WeakMap();
|
|
3
|
+
const contexts = new WeakMap();
|
|
4
|
+
let installed = false;
|
|
5
|
+
/** Groups durable dependency trees by their owning Durable Object activation. */
|
|
6
|
+
export class DurableObjectContextIdStrategy {
|
|
7
|
+
attach(contextId, request) {
|
|
8
|
+
const ctx = owners.get(request) ?? getWrappedOwner(request);
|
|
9
|
+
if (!ctx) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
let parent = contexts.get(ctx);
|
|
13
|
+
if (!parent) {
|
|
14
|
+
parent = ContextIdFactory.create();
|
|
15
|
+
contexts.set(ctx, parent);
|
|
16
|
+
}
|
|
17
|
+
const durableContextId = parent;
|
|
18
|
+
return {
|
|
19
|
+
resolve: (info) => info.isTreeDurable ? durableContextId : contextId,
|
|
20
|
+
payload: { durableObjectId: ctx.id.toString(), ctx },
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Associates a native event source with its object's Nest dependency tree. */
|
|
25
|
+
export function attachDurableObjectContext(source, ctx) {
|
|
26
|
+
if (!installed) {
|
|
27
|
+
ContextIdFactory.apply(new DurableObjectContextIdStrategy());
|
|
28
|
+
installed = true;
|
|
29
|
+
}
|
|
30
|
+
owners.set(source, ctx);
|
|
31
|
+
}
|
|
32
|
+
/** Creates an event context whose durable providers belong to this object. */
|
|
33
|
+
export function getDurableObjectContextId(ctx) {
|
|
34
|
+
const event = {};
|
|
35
|
+
attachDurableObjectContext(event, ctx);
|
|
36
|
+
return ContextIdFactory.getByRequest(event);
|
|
37
|
+
}
|
|
38
|
+
/** Resolves a provider for fetch, alarm, or RPC in the current object. */
|
|
39
|
+
export function resolveForDurableObject(app, ctx, token) {
|
|
40
|
+
const contextId = getDurableObjectContextId(ctx);
|
|
41
|
+
app.registerRequestByContextId(contextId.payload, contextId);
|
|
42
|
+
return app.resolve(token, contextId, { strict: false });
|
|
43
|
+
}
|
|
44
|
+
/** Reads the public Nest RequestContext wrapper without depending on Nest internals. */
|
|
45
|
+
function getWrappedOwner(request) {
|
|
46
|
+
if (!('getContext' in request) || typeof request.getContext !== 'function') {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const context = request.getContext();
|
|
50
|
+
return context !== null && typeof context === 'object'
|
|
51
|
+
? owners.get(context)
|
|
52
|
+
: undefined;
|
|
53
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { BaseRpcContext } from '@nestjs/microservices';
|
|
2
|
+
type ContextArgs<Env> = [DurableObjectState, Env, string];
|
|
3
|
+
/** Exposes the native object event and matched Nest pattern. */
|
|
4
|
+
export declare class CloudflareDurableObjectContext<Env = Cloudflare.Env> extends BaseRpcContext<ContextArgs<Env>> {
|
|
5
|
+
getState(): DurableObjectState;
|
|
6
|
+
getEnv(): Env;
|
|
7
|
+
getPattern(): string;
|
|
8
|
+
}
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BaseRpcContext } from '@nestjs/microservices';
|
|
2
|
+
/** Exposes the native object event and matched Nest pattern. */
|
|
3
|
+
export class CloudflareDurableObjectContext extends BaseRpcContext {
|
|
4
|
+
getState() {
|
|
5
|
+
return this.args[0];
|
|
6
|
+
}
|
|
7
|
+
getEnv() {
|
|
8
|
+
return this.args[1];
|
|
9
|
+
}
|
|
10
|
+
getPattern() {
|
|
11
|
+
return this.args[2];
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ReadPacket, WritePacket } from '@nestjs/microservices';
|
|
2
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
3
|
+
import type { CloudflareDurableObjectOptions } from './interfaces/server-options.interface.js';
|
|
4
|
+
/** Hosts a Nest microservice transport inside a native Durable Object. */
|
|
5
|
+
export declare abstract class CloudflareDurableObject<Env = Cloudflare.Env> extends DurableObject<Env> {
|
|
6
|
+
private readonly options;
|
|
7
|
+
constructor(state: DurableObjectState, env: Env, options: CloudflareDurableObjectOptions);
|
|
8
|
+
dispatch(packet: ReadPacket): Promise<WritePacket[]>;
|
|
9
|
+
alarm(): Promise<void>;
|
|
10
|
+
private run;
|
|
11
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { CloudflareRequestContext } from '../worker/request-context.js';
|
|
3
|
+
/** Hosts a Nest microservice transport inside a native Durable Object. */
|
|
4
|
+
export class CloudflareDurableObject extends DurableObject {
|
|
5
|
+
options;
|
|
6
|
+
constructor(state, env, options) {
|
|
7
|
+
super(state, env);
|
|
8
|
+
this.options = options;
|
|
9
|
+
}
|
|
10
|
+
async dispatch(packet) {
|
|
11
|
+
return this.run(() => this.options.server.dispatch(packet, this.ctx, this.env));
|
|
12
|
+
}
|
|
13
|
+
async alarm() {
|
|
14
|
+
await this.run(() => this.options.server.dispatchAlarm(this.options.alarmPattern ?? 'alarm', this.ctx, this.env));
|
|
15
|
+
}
|
|
16
|
+
async run(callback) {
|
|
17
|
+
const app = await this.options.getApplication();
|
|
18
|
+
const context = app.get(CloudflareRequestContext);
|
|
19
|
+
return context.run({ env: this.env, ctx: this.ctx }, callback);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { CloudflareDurableObjectClient } from './client.js';
|
|
2
|
+
export { CLOUDFLARE_DURABLE_OBJECT_TRANSPORT } from './constants.js';
|
|
3
|
+
export { CloudflareDurableObjectContext } from './context.transport.js';
|
|
4
|
+
export { CloudflareDurableObject } from './durable-object.js';
|
|
5
|
+
export type * from './interfaces/client-options.interface.js';
|
|
6
|
+
export type * from './interfaces/server-options.interface.js';
|
|
7
|
+
export { CloudflareDurableObjectRecordSerializer } from './record.serializer.js';
|
|
8
|
+
export * from './record-builder.js';
|
|
9
|
+
export { CloudflareDurableObjectServer } from './server.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { CloudflareDurableObjectClient } from './client.js';
|
|
2
|
+
export { CLOUDFLARE_DURABLE_OBJECT_TRANSPORT } from './constants.js';
|
|
3
|
+
export { CloudflareDurableObjectContext } from './context.transport.js';
|
|
4
|
+
export { CloudflareDurableObject } from './durable-object.js';
|
|
5
|
+
export { CloudflareDurableObjectRecordSerializer } from './record.serializer.js';
|
|
6
|
+
export * from './record-builder.js';
|
|
7
|
+
export { CloudflareDurableObjectServer } from './server.js';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Deserializer, Serializer } from '@nestjs/microservices';
|
|
2
|
+
/** Configures a Durable Object client registered through ClientsModule. */
|
|
3
|
+
export interface CloudflareDurableObjectClientOptions {
|
|
4
|
+
namespace: DurableObjectNamespace;
|
|
5
|
+
serializer?: Serializer;
|
|
6
|
+
deserializer?: Deserializer;
|
|
7
|
+
}
|
|
8
|
+
/** Selects one object for an outgoing message. IDs use their string representation. */
|
|
9
|
+
export type CloudflareDurableObjectRecordOptions = {
|
|
10
|
+
name: string;
|
|
11
|
+
id?: never;
|
|
12
|
+
} | {
|
|
13
|
+
id: string;
|
|
14
|
+
name?: never;
|
|
15
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { INestApplicationContext } from '@nestjs/common';
|
|
2
|
+
import type { Deserializer, MsPattern, Serializer } from '@nestjs/microservices';
|
|
3
|
+
import type { CloudflareDurableObjectServer } from '../server.js';
|
|
4
|
+
/** Configures Nest packet serialization. */
|
|
5
|
+
export interface CloudflareDurableObjectServerOptions {
|
|
6
|
+
serializer?: Serializer;
|
|
7
|
+
deserializer?: Deserializer;
|
|
8
|
+
}
|
|
9
|
+
/** Selects the application's transport and native alarm event pattern. */
|
|
10
|
+
export interface CloudflareDurableObjectOptions {
|
|
11
|
+
server: CloudflareDurableObjectServer;
|
|
12
|
+
getApplication: () => Promise<INestApplicationContext>;
|
|
13
|
+
alarmPattern?: MsPattern;
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|