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
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { CloudflareDurableObjectRecordOptions } from './interfaces/client-options.interface.js';
|
|
2
|
+
/** Carries message data and per-call object addressing. */
|
|
3
|
+
export declare class CloudflareDurableObjectRecord<T = unknown> {
|
|
4
|
+
readonly data: T;
|
|
5
|
+
readonly options?: CloudflareDurableObjectRecordOptions | undefined;
|
|
6
|
+
constructor(data: T, options?: CloudflareDurableObjectRecordOptions | undefined);
|
|
7
|
+
}
|
|
8
|
+
/** Builds transport records using Nest's record builder convention. */
|
|
9
|
+
export declare class CloudflareDurableObjectRecordBuilder<T = unknown> {
|
|
10
|
+
private data;
|
|
11
|
+
private options?;
|
|
12
|
+
constructor(data: T);
|
|
13
|
+
setData(data: T): this;
|
|
14
|
+
setOptions(options: CloudflareDurableObjectRecordOptions): this;
|
|
15
|
+
build(): CloudflareDurableObjectRecord<T>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Carries message data and per-call object addressing. */
|
|
2
|
+
export class CloudflareDurableObjectRecord {
|
|
3
|
+
data;
|
|
4
|
+
options;
|
|
5
|
+
constructor(data, options) {
|
|
6
|
+
this.data = data;
|
|
7
|
+
this.options = options;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Builds transport records using Nest's record builder convention. */
|
|
11
|
+
export class CloudflareDurableObjectRecordBuilder {
|
|
12
|
+
data;
|
|
13
|
+
options;
|
|
14
|
+
constructor(data) {
|
|
15
|
+
this.data = data;
|
|
16
|
+
}
|
|
17
|
+
setData(data) {
|
|
18
|
+
this.data = data;
|
|
19
|
+
return this;
|
|
20
|
+
}
|
|
21
|
+
setOptions(options) {
|
|
22
|
+
this.options = options;
|
|
23
|
+
return this;
|
|
24
|
+
}
|
|
25
|
+
build() {
|
|
26
|
+
return new CloudflareDurableObjectRecord(this.data, this.options);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ReadPacket, Serializer } from '@nestjs/microservices';
|
|
2
|
+
/** Removes native addressing options from the Nest message body. */
|
|
3
|
+
export declare class CloudflareDurableObjectRecordSerializer implements Serializer {
|
|
4
|
+
serialize(packet: ReadPacket): ReadPacket<any> | {
|
|
5
|
+
data: any;
|
|
6
|
+
options: import("./index.js").CloudflareDurableObjectRecordOptions | undefined;
|
|
7
|
+
pattern: any;
|
|
8
|
+
metadata?: import("@nestjs/microservices").PacketMetadata;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { CloudflareDurableObjectRecord } from './record-builder.js';
|
|
2
|
+
/** Removes native addressing options from the Nest message body. */
|
|
3
|
+
export class CloudflareDurableObjectRecordSerializer {
|
|
4
|
+
serialize(packet) {
|
|
5
|
+
const record = packet.data;
|
|
6
|
+
return record instanceof CloudflareDurableObjectRecord
|
|
7
|
+
? { ...packet, data: record.data, options: record.options }
|
|
8
|
+
: packet;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type CustomTransportStrategy, type MsPattern, type ReadPacket, Server, type WritePacket } from '@nestjs/microservices';
|
|
2
|
+
import { CloudflareDurableObjectContext } from './context.transport.js';
|
|
3
|
+
import type { CloudflareDurableObjectServerOptions } from './interfaces/server-options.interface.js';
|
|
4
|
+
/** Dispatches native object messages through Nest microservice handlers. */
|
|
5
|
+
export declare class CloudflareDurableObjectServer extends Server implements CustomTransportStrategy {
|
|
6
|
+
readonly propagatesEventHandlerErrors = true;
|
|
7
|
+
transportId: symbol;
|
|
8
|
+
constructor(options?: CloudflareDurableObjectServerOptions);
|
|
9
|
+
listen(callback: () => void): void;
|
|
10
|
+
close(): void;
|
|
11
|
+
on(): never;
|
|
12
|
+
unwrap<T>(): T;
|
|
13
|
+
dispatch(raw: ReadPacket, state: DurableObjectState, env: unknown): Promise<WritePacket[]>;
|
|
14
|
+
handleEvent(pattern: string, packet: ReadPacket, context: CloudflareDurableObjectContext<unknown>): Promise<void>;
|
|
15
|
+
dispatchAlarm(pattern: MsPattern, state: DurableObjectState, env: unknown): Promise<void>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { Server, } from '@nestjs/microservices';
|
|
2
|
+
import { finalize, isObservable, lastValueFrom } from 'rxjs';
|
|
3
|
+
import { CLOUDFLARE_DURABLE_OBJECT_TRANSPORT } from './constants.js';
|
|
4
|
+
import { attachDurableObjectContext } from './context.js';
|
|
5
|
+
import { CloudflareDurableObjectContext } from './context.transport.js';
|
|
6
|
+
/** Dispatches native object messages through Nest microservice handlers. */
|
|
7
|
+
export class CloudflareDurableObjectServer extends Server {
|
|
8
|
+
propagatesEventHandlerErrors = true;
|
|
9
|
+
transportId = CLOUDFLARE_DURABLE_OBJECT_TRANSPORT;
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
super();
|
|
12
|
+
this.initializeSerializer(options);
|
|
13
|
+
this.initializeDeserializer(options);
|
|
14
|
+
}
|
|
15
|
+
listen(callback) {
|
|
16
|
+
callback();
|
|
17
|
+
}
|
|
18
|
+
close() { }
|
|
19
|
+
on() {
|
|
20
|
+
throw new Error('Durable Object transport has no connection events');
|
|
21
|
+
}
|
|
22
|
+
unwrap() {
|
|
23
|
+
return this;
|
|
24
|
+
}
|
|
25
|
+
async dispatch(raw, state, env) {
|
|
26
|
+
const packet = await this.deserializer.deserialize(raw);
|
|
27
|
+
const pattern = this.normalizePattern(packet.pattern);
|
|
28
|
+
const context = new CloudflareDurableObjectContext([state, env, pattern]);
|
|
29
|
+
attachDurableObjectContext(context, state);
|
|
30
|
+
const handler = this.getHandlerByPattern(pattern);
|
|
31
|
+
if (!handler) {
|
|
32
|
+
return [{ err: `No handler for pattern: ${pattern}`, isDisposed: true }];
|
|
33
|
+
}
|
|
34
|
+
if (!('id' in packet) || packet.id === undefined) {
|
|
35
|
+
try {
|
|
36
|
+
await this.handleEvent(pattern, packet, context);
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
return [
|
|
41
|
+
await this.serializer.serialize({
|
|
42
|
+
err,
|
|
43
|
+
isDisposed: true,
|
|
44
|
+
id: '',
|
|
45
|
+
}),
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
this.warnIfEventHandlerReplies(handler, pattern);
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const replies = [];
|
|
52
|
+
this.runWithProcessingHooks(context, async (end) => {
|
|
53
|
+
try {
|
|
54
|
+
const result = await handler(packet.data, context);
|
|
55
|
+
this.send(this.transformToObservable(result).pipe(finalize(end)), async (reply) => {
|
|
56
|
+
try {
|
|
57
|
+
replies.push(await this.serializer.serialize({ ...reply, id: packet.id }));
|
|
58
|
+
if (reply.isDisposed) {
|
|
59
|
+
resolve(replies);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
reject(error);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
end();
|
|
69
|
+
reject(error);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
async handleEvent(pattern, packet, context) {
|
|
75
|
+
const handler = this.getHandlerByPattern(pattern);
|
|
76
|
+
if (!handler?.isEventHandler) {
|
|
77
|
+
throw new Error(`No EventPattern handler for pattern: ${pattern}`);
|
|
78
|
+
}
|
|
79
|
+
await this.runWithProcessingHooks(context, async (end) => {
|
|
80
|
+
const result = await handler(packet.data, context);
|
|
81
|
+
if (isObservable(result)) {
|
|
82
|
+
await lastValueFrom(result.pipe(finalize(end)), {
|
|
83
|
+
defaultValue: undefined,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
end();
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
async dispatchAlarm(pattern, state, env) {
|
|
92
|
+
const normalized = this.normalizePattern(pattern);
|
|
93
|
+
const context = new CloudflareDurableObjectContext([
|
|
94
|
+
state,
|
|
95
|
+
env,
|
|
96
|
+
normalized,
|
|
97
|
+
]);
|
|
98
|
+
attachDurableObjectContext(context, state);
|
|
99
|
+
await this.handleEvent(normalized, { pattern, data: undefined }, context);
|
|
100
|
+
}
|
|
101
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,11 @@ export { getBindingToken } from './bindings/get-binding-token.js';
|
|
|
2
2
|
export { CloudflareModule } from './cloudflare.module.js';
|
|
3
3
|
export { CLOUDFLARE_ENV } from './constants.js';
|
|
4
4
|
export { InjectBinding } from './decorators/inject-binding.decorator.js';
|
|
5
|
+
export { DurableObjectContextIdStrategy } from './durable-objects/context.js';
|
|
6
|
+
export { getDurableObjectContextId } from './durable-objects/context.js';
|
|
7
|
+
export { resolveForDurableObject } from './durable-objects/context.js';
|
|
5
8
|
export type { CloudflareWorker } from './interfaces/worker.interface.js';
|
|
6
9
|
export type { CloudflareWorkerOptions } from './interfaces/worker-options.interface.js';
|
|
10
|
+
export type { CloudflareWorkerWebSocketRoute } from './interfaces/worker-options.interface.js';
|
|
7
11
|
export { createWorker } from './worker/create-worker.js';
|
|
12
|
+
export { CloudflareRequestContext } from './worker/request-context.js';
|
package/dist/index.js
CHANGED
|
@@ -2,4 +2,8 @@ export { getBindingToken } from './bindings/get-binding-token.js';
|
|
|
2
2
|
export { CloudflareModule } from './cloudflare.module.js';
|
|
3
3
|
export { CLOUDFLARE_ENV } from './constants.js';
|
|
4
4
|
export { InjectBinding } from './decorators/inject-binding.decorator.js';
|
|
5
|
+
export { DurableObjectContextIdStrategy } from './durable-objects/context.js';
|
|
6
|
+
export { getDurableObjectContextId } from './durable-objects/context.js';
|
|
7
|
+
export { resolveForDurableObject } from './durable-objects/context.js';
|
|
5
8
|
export { createWorker } from './worker/create-worker.js';
|
|
9
|
+
export { CloudflareRequestContext } from './worker/request-context.js';
|
|
@@ -1,14 +1,45 @@
|
|
|
1
1
|
type WorkerExecutionContext = ExecutionContext;
|
|
2
|
+
type IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
|
|
2
3
|
/**
|
|
3
|
-
* Configures native event
|
|
4
|
+
* Configures native event dispatch, routing, and fallbacks.
|
|
4
5
|
*
|
|
5
6
|
* @publicApi
|
|
6
7
|
*/
|
|
7
8
|
export interface CloudflareWorkerOptions<Env = Cloudflare.Env> {
|
|
9
|
+
/** Wraps complete native event dispatch. */
|
|
10
|
+
around?: {
|
|
11
|
+
fetch?: CloudflareWorkerAroundFetch<Env>;
|
|
12
|
+
scheduled?: CloudflareWorkerAroundScheduled<Env>;
|
|
13
|
+
queue?: CloudflareWorkerAroundQueue<Env>;
|
|
14
|
+
};
|
|
15
|
+
/** Forwards matching paths directly to Durable Objects, including non-upgrade requests. */
|
|
16
|
+
websockets?: readonly CloudflareWorkerWebSocketRoute<Env>[];
|
|
17
|
+
/** Validates Express settings and controls implicit HEAD pre-matching. */
|
|
18
|
+
routing?: {
|
|
19
|
+
caseSensitive?: boolean;
|
|
20
|
+
strict?: boolean;
|
|
21
|
+
/** Allows HEAD to pre-match GET routes. Defaults to true. */
|
|
22
|
+
headImplicitMatch?: boolean;
|
|
23
|
+
caseSensitiveRouting?: boolean;
|
|
24
|
+
strictRouting?: boolean;
|
|
25
|
+
};
|
|
8
26
|
/** Native handlers for events not handled by a connected Nest transport. */
|
|
9
27
|
fallback?: {
|
|
28
|
+
fetch?: (request: IncomingRequest, env: Env, ctx: WorkerExecutionContext) => Response | Promise<Response>;
|
|
10
29
|
scheduled?: (controller: ScheduledController, env: Env, ctx: WorkerExecutionContext) => void | Promise<void>;
|
|
11
30
|
queue?: (batch: MessageBatch, env: Env, ctx: WorkerExecutionContext) => void | Promise<void>;
|
|
12
31
|
};
|
|
13
32
|
}
|
|
33
|
+
export type CloudflareWorkerAroundFetch<Env> = (request: Request<unknown, IncomingRequestCfProperties>, env: Env, ctx: ExecutionContext, next: () => Promise<Response>) => Response | Promise<Response>;
|
|
34
|
+
export type CloudflareWorkerAroundScheduled<Env> = (controller: ScheduledController, env: Env, ctx: ExecutionContext, next: () => Promise<void>) => void | Promise<void>;
|
|
35
|
+
export type CloudflareWorkerAroundQueue<Env> = (batch: MessageBatch, env: Env, ctx: ExecutionContext, next: () => Promise<void>) => void | Promise<void>;
|
|
36
|
+
/** Configures native WebSocket forwarding to one Durable Object. */
|
|
37
|
+
export interface CloudflareWorkerWebSocketRoute<Env = Cloudflare.Env> {
|
|
38
|
+
/** Exact URL pathnames, independent of Express routing settings. */
|
|
39
|
+
paths: readonly string[];
|
|
40
|
+
/** Durable Object namespace binding in the event environment. */
|
|
41
|
+
binding: Extract<keyof Env, string>;
|
|
42
|
+
/** A name for idFromName(), or a request resolver returning a name or native ID. */
|
|
43
|
+
object: string | ((request: IncomingRequest) => string | DurableObjectId);
|
|
44
|
+
}
|
|
14
45
|
export {};
|
|
@@ -9,8 +9,10 @@ type IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
|
|
|
9
9
|
export interface CloudflareWorker<Env = Cloudflare.Env> {
|
|
10
10
|
/** Starts the application once and returns it to native Worker or Durable Object code. */
|
|
11
11
|
getApplication(): Promise<INestApplication>;
|
|
12
|
-
/**
|
|
12
|
+
/** Dispatches a request to a configured Durable Object, Nest, or the native fallback. */
|
|
13
13
|
fetch(request: IncomingRequest, env: Env, ctx: WorkerExecutionContext): Promise<Response>;
|
|
14
|
+
/** Reports whether a configured WebSocket path or Express route owns the request. */
|
|
15
|
+
matches(request: IncomingRequest): Promise<boolean>;
|
|
14
16
|
/** Dispatches an event to registered Nest cron methods or the native fallback. */
|
|
15
17
|
scheduled(controller: ScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void>;
|
|
16
18
|
/** Dispatches a batch to the application's Cloudflare Queue transport. */
|
package/dist/queue/client.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ClientProxy, } from '@nestjs/microservices';
|
|
2
|
+
import { CloudflareQueueRecordSerializer } from './record.serializer.js';
|
|
2
3
|
/**
|
|
3
4
|
* Publishes Nest event packets through a Cloudflare Queue binding.
|
|
4
5
|
*
|
|
@@ -9,7 +10,10 @@ export class CloudflareQueueClient extends ClientProxy {
|
|
|
9
10
|
constructor(options) {
|
|
10
11
|
super();
|
|
11
12
|
this.options = options;
|
|
12
|
-
this.initializeSerializer(
|
|
13
|
+
this.initializeSerializer({
|
|
14
|
+
...options,
|
|
15
|
+
serializer: options.serializer ?? new CloudflareQueueRecordSerializer(),
|
|
16
|
+
});
|
|
13
17
|
this.initializeDeserializer(options);
|
|
14
18
|
}
|
|
15
19
|
/** Returns the Queue binding without opening a broker connection. */
|
|
@@ -30,7 +34,11 @@ export class CloudflareQueueClient extends ClientProxy {
|
|
|
30
34
|
}
|
|
31
35
|
async dispatchEvent(packet) {
|
|
32
36
|
const pattern = this.normalizePattern(packet.pattern);
|
|
33
|
-
|
|
37
|
+
const { options, ...body } = await this.serializer.serialize({
|
|
38
|
+
...packet,
|
|
39
|
+
pattern,
|
|
40
|
+
});
|
|
41
|
+
await this.options.queue.send(body, options);
|
|
34
42
|
return undefined;
|
|
35
43
|
}
|
|
36
44
|
}
|
package/dist/queue/index.d.ts
CHANGED
|
@@ -3,4 +3,6 @@ export { CLOUDFLARE_QUEUE_TRANSPORT } from './constants.js';
|
|
|
3
3
|
export { CloudflareQueueContext } from './context.js';
|
|
4
4
|
export type { CloudflareQueueClientOptions } from './interfaces/client-options.interface.js';
|
|
5
5
|
export type { CloudflareQueueServerOptions } from './interfaces/server-options.interface.js';
|
|
6
|
+
export { CloudflareQueueRecord } from './record-builder.js';
|
|
7
|
+
export { CloudflareQueueRecordBuilder } from './record-builder.js';
|
|
6
8
|
export { CloudflareQueueServer } from './server.js';
|
package/dist/queue/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { CloudflareQueueClient } from './client.js';
|
|
2
2
|
export { CLOUDFLARE_QUEUE_TRANSPORT } from './constants.js';
|
|
3
3
|
export { CloudflareQueueContext } from './context.js';
|
|
4
|
+
export { CloudflareQueueRecord } from './record-builder.js';
|
|
5
|
+
export { CloudflareQueueRecordBuilder } from './record-builder.js';
|
|
4
6
|
export { CloudflareQueueServer } from './server.js';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Carries a Queue payload and native send options through Nest emit().
|
|
2
|
+
* @publicApi
|
|
3
|
+
*/
|
|
4
|
+
export declare class CloudflareQueueRecord<TData = unknown> {
|
|
5
|
+
readonly data: TData;
|
|
6
|
+
readonly options?: QueueSendOptions | undefined;
|
|
7
|
+
constructor(data: TData, options?: QueueSendOptions | undefined);
|
|
8
|
+
}
|
|
9
|
+
/** Builds a Queue record using Nest's transport record convention.
|
|
10
|
+
* @publicApi
|
|
11
|
+
*/
|
|
12
|
+
export declare class CloudflareQueueRecordBuilder<TData = unknown> {
|
|
13
|
+
private data?;
|
|
14
|
+
private options?;
|
|
15
|
+
constructor(data?: TData | undefined);
|
|
16
|
+
setData(data: TData): this;
|
|
17
|
+
setOptions(options: QueueSendOptions): this;
|
|
18
|
+
build(): CloudflareQueueRecord<TData | undefined>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Carries a Queue payload and native send options through Nest emit().
|
|
2
|
+
* @publicApi
|
|
3
|
+
*/
|
|
4
|
+
export class CloudflareQueueRecord {
|
|
5
|
+
data;
|
|
6
|
+
options;
|
|
7
|
+
constructor(data, options) {
|
|
8
|
+
this.data = data;
|
|
9
|
+
this.options = options;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Builds a Queue record using Nest's transport record convention.
|
|
13
|
+
* @publicApi
|
|
14
|
+
*/
|
|
15
|
+
export class CloudflareQueueRecordBuilder {
|
|
16
|
+
data;
|
|
17
|
+
options;
|
|
18
|
+
constructor(data) {
|
|
19
|
+
this.data = data;
|
|
20
|
+
}
|
|
21
|
+
setData(data) {
|
|
22
|
+
this.data = data;
|
|
23
|
+
return this;
|
|
24
|
+
}
|
|
25
|
+
setOptions(options) {
|
|
26
|
+
this.options = options;
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
build() {
|
|
30
|
+
return new CloudflareQueueRecord(this.data, this.options);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ReadPacket, Serializer } from '@nestjs/microservices';
|
|
2
|
+
/** Unwraps transport records while preserving Nest packet metadata. */
|
|
3
|
+
export declare class CloudflareQueueRecordSerializer implements Serializer {
|
|
4
|
+
serialize(packet: ReadPacket): ReadPacket<any> | {
|
|
5
|
+
data: any;
|
|
6
|
+
options: QueueSendOptions | undefined;
|
|
7
|
+
pattern: any;
|
|
8
|
+
metadata?: import("@nestjs/microservices").PacketMetadata;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CloudflareQueueRecord } from './record-builder.js';
|
|
2
|
+
/** Unwraps transport records while preserving Nest packet metadata. */
|
|
3
|
+
export class CloudflareQueueRecordSerializer {
|
|
4
|
+
serialize(packet) {
|
|
5
|
+
if (packet.data instanceof CloudflareQueueRecord) {
|
|
6
|
+
return {
|
|
7
|
+
...packet,
|
|
8
|
+
data: packet.data.data,
|
|
9
|
+
options: packet.data.options,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
return packet;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -13,5 +13,8 @@ export declare class CronExplorer implements OnModuleInit {
|
|
|
13
13
|
onModuleInit(): void;
|
|
14
14
|
/** Reports matched handler failures through the event execution context. */
|
|
15
15
|
dispatch(controller: ScheduledController, ctx: WorkerExecutionContext): boolean;
|
|
16
|
+
/** Runs matching handlers and resolves only after all handlers finish. */
|
|
17
|
+
dispatchAndWait(controller: ScheduledController, _ctx: WorkerExecutionContext): Promise<boolean>;
|
|
18
|
+
private execute;
|
|
16
19
|
}
|
|
17
20
|
export {};
|
|
@@ -69,11 +69,28 @@ let CronExplorer = CronExplorer_1 = class CronExplorer {
|
|
|
69
69
|
}
|
|
70
70
|
/** Reports matched handler failures through the event execution context. */
|
|
71
71
|
dispatch(controller, ctx) {
|
|
72
|
+
const execution = this.execute(controller, ctx);
|
|
73
|
+
if (!execution) {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
ctx.waitUntil(execution);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
/** Runs matching handlers and resolves only after all handlers finish. */
|
|
80
|
+
async dispatchAndWait(controller, _ctx) {
|
|
81
|
+
const execution = this.execute(controller, _ctx);
|
|
82
|
+
if (!execution) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
await execution;
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
execute(controller, ctx) {
|
|
72
89
|
const matches = this.handlers.filter(({ expression, options }) => !options.disabled && expression === controller.cron);
|
|
73
90
|
if (matches.length === 0) {
|
|
74
|
-
return
|
|
91
|
+
return undefined;
|
|
75
92
|
}
|
|
76
|
-
|
|
93
|
+
return Promise.allSettled(matches
|
|
77
94
|
.filter(handler => !handler.options.waitForCompletion || !handler.running)
|
|
78
95
|
.map(handler => {
|
|
79
96
|
handler.running = true;
|
|
@@ -92,8 +109,7 @@ let CronExplorer = CronExplorer_1 = class CronExplorer {
|
|
|
92
109
|
}
|
|
93
110
|
throw new AggregateError(errors, 'Cron handlers failed');
|
|
94
111
|
}
|
|
95
|
-
})
|
|
96
|
-
return true;
|
|
112
|
+
});
|
|
97
113
|
}
|
|
98
114
|
};
|
|
99
115
|
CronExplorer = CronExplorer_1 = __decorate([
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type WsMessageHandler } from '@nestjs/common';
|
|
2
2
|
import { AbstractWsAdapter } from '@nestjs/websockets';
|
|
3
3
|
import { type Observable } from 'rxjs';
|
|
4
|
+
import { type CloudflareWebSocketContext } from './context.js';
|
|
4
5
|
import type { CloudflareWebSocketAdapterOptions } from './interfaces/adapter-options.interface.js';
|
|
5
6
|
import type { CloudflareWebSocketServer } from './interfaces/server.interface.js';
|
|
6
7
|
type ConnectHandler = (client: WebSocket, request?: Request) => void;
|
|
@@ -12,10 +13,13 @@ type Transform = (data: unknown) => Observable<unknown>;
|
|
|
12
13
|
* @publicApi
|
|
13
14
|
*/
|
|
14
15
|
export declare class CloudflareWebSocketAdapter extends AbstractWsAdapter<any, any> {
|
|
16
|
+
private readonly maxConcurrentMessages;
|
|
15
17
|
private readonly logger;
|
|
16
18
|
private readonly servers;
|
|
19
|
+
private readonly aliases;
|
|
17
20
|
private readonly clients;
|
|
18
21
|
private readonly messageParser;
|
|
22
|
+
private readonly messageSerializer;
|
|
19
23
|
/**
|
|
20
24
|
* Configures how native frames map to Nest gateway messages.
|
|
21
25
|
*/
|
|
@@ -31,6 +35,8 @@ export declare class CloudflareWebSocketAdapter extends AbstractWsAdapter<any, a
|
|
|
31
35
|
* Registers Nest's connection callback for a gateway server.
|
|
32
36
|
*/
|
|
33
37
|
bindClientConnect(server: CloudflareWebSocketServer, callback: ConnectHandler): void;
|
|
38
|
+
/** Registers an additional path for an already discovered gateway. */
|
|
39
|
+
registerPathAlias(path: string, targetPath: string): void;
|
|
34
40
|
/**
|
|
35
41
|
* Registers Nest's disconnection callback for a native socket.
|
|
36
42
|
*/
|
|
@@ -42,11 +48,12 @@ export declare class CloudflareWebSocketAdapter extends AbstractWsAdapter<any, a
|
|
|
42
48
|
/**
|
|
43
49
|
* Binds a connection or a restored socket through Nest's gateway pipeline.
|
|
44
50
|
*/
|
|
45
|
-
connect(path: string, socket: WebSocket, request?: Request): void;
|
|
51
|
+
connect(path: string, socket: WebSocket, request?: Request, context?: CloudflareWebSocketContext<unknown, unknown>): void;
|
|
46
52
|
/**
|
|
47
53
|
* Dispatches a JSON event through Nest and sends every returned value.
|
|
48
54
|
*/
|
|
49
55
|
message(socket: WebSocket, frame: string | ArrayBuffer): Promise<void>;
|
|
56
|
+
private dispatchMessage;
|
|
50
57
|
/**
|
|
51
58
|
* Dispatches disconnection hooks and releases this socket's callbacks.
|
|
52
59
|
*/
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { Logger } from '@nestjs/common';
|
|
2
2
|
import { AbstractWsAdapter } from '@nestjs/websockets';
|
|
3
3
|
import { lastValueFrom, tap } from 'rxjs';
|
|
4
|
+
import { attachCloudflareWebSocketContext, detachCloudflareWebSocketContext, } from './context.js';
|
|
4
5
|
import { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
6
|
+
import { WebSocketMessageDispatcher } from './message-dispatcher.js';
|
|
5
7
|
/**
|
|
6
8
|
* Connects Nest gateways to the Durable Object WebSocket Hibernation API.
|
|
7
9
|
*
|
|
@@ -11,16 +13,21 @@ import { InvalidWebSocketMessageException } from './invalid-message.exception.js
|
|
|
11
13
|
// Durable Objects own native WebSockets and their hibernation callbacks.
|
|
12
14
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13
15
|
export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
16
|
+
maxConcurrentMessages;
|
|
14
17
|
logger = new Logger(CloudflareWebSocketAdapter.name);
|
|
15
18
|
servers = new Map();
|
|
19
|
+
aliases = new Map();
|
|
16
20
|
clients = new WeakMap();
|
|
17
21
|
messageParser;
|
|
22
|
+
messageSerializer;
|
|
18
23
|
/**
|
|
19
24
|
* Configures how native frames map to Nest gateway messages.
|
|
20
25
|
*/
|
|
21
26
|
constructor(options = {}) {
|
|
22
27
|
super();
|
|
28
|
+
this.maxConcurrentMessages = options.maxConcurrentMessages ?? 1000;
|
|
23
29
|
this.messageParser = options.messageParser ?? parseMessage;
|
|
30
|
+
this.messageSerializer = options.messageSerializer ?? JSON.stringify;
|
|
24
31
|
}
|
|
25
32
|
/**
|
|
26
33
|
* Creates a logical gateway server without opening a TCP listener.
|
|
@@ -47,6 +54,11 @@ export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
|
47
54
|
bindClientConnect(server, callback) {
|
|
48
55
|
this.server(server.path).connect.push(callback);
|
|
49
56
|
}
|
|
57
|
+
/** Registers an additional path for an already discovered gateway. */
|
|
58
|
+
registerPathAlias(path, targetPath) {
|
|
59
|
+
this.server(targetPath);
|
|
60
|
+
this.aliases.set(path, targetPath);
|
|
61
|
+
}
|
|
50
62
|
/**
|
|
51
63
|
* Registers Nest's disconnection callback for a native socket.
|
|
52
64
|
*/
|
|
@@ -62,12 +74,19 @@ export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
|
62
74
|
/**
|
|
63
75
|
* Binds a connection or a restored socket through Nest's gateway pipeline.
|
|
64
76
|
*/
|
|
65
|
-
connect(path, socket, request) {
|
|
77
|
+
connect(path, socket, request, context) {
|
|
66
78
|
if (this.clients.has(socket)) {
|
|
67
79
|
return;
|
|
68
80
|
}
|
|
69
81
|
const { connect } = this.server(path);
|
|
70
|
-
this.clients.set(socket, {
|
|
82
|
+
this.clients.set(socket, {
|
|
83
|
+
messages: [],
|
|
84
|
+
disconnect: [],
|
|
85
|
+
dispatcher: new WebSocketMessageDispatcher(frame => this.dispatchMessage(socket, frame), this.maxConcurrentMessages),
|
|
86
|
+
});
|
|
87
|
+
if (context) {
|
|
88
|
+
attachCloudflareWebSocketContext(socket, context);
|
|
89
|
+
}
|
|
71
90
|
for (const callback of connect) {
|
|
72
91
|
callback(socket, request);
|
|
73
92
|
}
|
|
@@ -75,7 +94,10 @@ export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
|
75
94
|
/**
|
|
76
95
|
* Dispatches a JSON event through Nest and sends every returned value.
|
|
77
96
|
*/
|
|
78
|
-
|
|
97
|
+
message(socket, frame) {
|
|
98
|
+
return this.client(socket).dispatcher.dispatch(frame);
|
|
99
|
+
}
|
|
100
|
+
async dispatchMessage(socket, frame) {
|
|
79
101
|
const packet = this.messageParser(frame);
|
|
80
102
|
if (!packet) {
|
|
81
103
|
return;
|
|
@@ -88,7 +110,7 @@ export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
|
88
110
|
if (result !== undefined &&
|
|
89
111
|
result !== null &&
|
|
90
112
|
socket.readyState === WebSocket.OPEN) {
|
|
91
|
-
socket.send(
|
|
113
|
+
socket.send(this.messageSerializer(result));
|
|
92
114
|
}
|
|
93
115
|
})), { defaultValue: undefined });
|
|
94
116
|
})));
|
|
@@ -98,7 +120,9 @@ export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
|
98
120
|
*/
|
|
99
121
|
disconnect(socket, reason) {
|
|
100
122
|
const handlers = this.client(socket);
|
|
123
|
+
handlers.dispatcher.close();
|
|
101
124
|
this.clients.delete(socket);
|
|
125
|
+
detachCloudflareWebSocketContext(socket);
|
|
102
126
|
for (const callback of handlers.disconnect) {
|
|
103
127
|
callback(reason);
|
|
104
128
|
}
|
|
@@ -123,9 +147,10 @@ export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
|
123
147
|
*/
|
|
124
148
|
async dispose() {
|
|
125
149
|
this.servers.clear();
|
|
150
|
+
this.aliases.clear();
|
|
126
151
|
}
|
|
127
152
|
server(path) {
|
|
128
|
-
const server = this.servers.get(path);
|
|
153
|
+
const server = this.servers.get(this.aliases.get(path) ?? path);
|
|
129
154
|
if (!server) {
|
|
130
155
|
throw new Error(`No Nest WebSocket gateway registered for path: ${path}`);
|
|
131
156
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** State belonging to the Durable Object that accepted a WebSocket. */
|
|
2
|
+
export interface CloudflareWebSocketContext<Env = unknown, ObjectType = unknown> {
|
|
3
|
+
readonly ctx: DurableObjectState;
|
|
4
|
+
readonly env: Env;
|
|
5
|
+
readonly object: ObjectType;
|
|
6
|
+
readonly storage: DurableObjectStorage;
|
|
7
|
+
readonly sockets: ReadonlySet<WebSocket>;
|
|
8
|
+
}
|
|
9
|
+
export declare function attachCloudflareWebSocketContext(socket: WebSocket, context: CloudflareWebSocketContext): void;
|
|
10
|
+
export declare function detachCloudflareWebSocketContext(socket: WebSocket): void;
|
|
11
|
+
/** Returns the owning Durable Object state for a gateway socket. */
|
|
12
|
+
export declare function getCloudflareWebSocketContext<Env = Cloudflare.Env, ObjectType = DurableObject>(socket: WebSocket): CloudflareWebSocketContext<Env, ObjectType>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const contexts = new WeakMap();
|
|
2
|
+
export function attachCloudflareWebSocketContext(socket, context) {
|
|
3
|
+
contexts.set(socket, context);
|
|
4
|
+
}
|
|
5
|
+
export function detachCloudflareWebSocketContext(socket) {
|
|
6
|
+
contexts.delete(socket);
|
|
7
|
+
}
|
|
8
|
+
/** Returns the owning Durable Object state for a gateway socket. */
|
|
9
|
+
export function getCloudflareWebSocketContext(socket) {
|
|
10
|
+
const context = contexts.get(socket);
|
|
11
|
+
if (!context) {
|
|
12
|
+
throw new Error('WebSocket is not attached to a Cloudflare Durable Object');
|
|
13
|
+
}
|
|
14
|
+
return context;
|
|
15
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { InjectionToken } from '@nestjs/common';
|
|
1
2
|
import { DurableObject } from 'cloudflare:workers';
|
|
2
3
|
import type { CloudflareWebSocketDurableObjectOptions } from './interfaces/durable-object-options.interface.js';
|
|
3
4
|
/**
|
|
@@ -10,6 +11,8 @@ export declare abstract class CloudflareWebSocketDurableObject<Env = Cloudflare.
|
|
|
10
11
|
private readonly ready;
|
|
11
12
|
private readonly tag;
|
|
12
13
|
constructor(ctx: DurableObjectState, env: Env, options: CloudflareWebSocketDurableObjectOptions);
|
|
14
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
15
|
+
protected resolve<T>(token: InjectionToken<T>): Promise<T>;
|
|
13
16
|
/** Accepts upgrades and registers connections for hibernation. */
|
|
14
17
|
fetch(request: Request): Promise<Response>;
|
|
15
18
|
/** Waits for Nest startup and gateway message handling. */
|