nestjs-cloudflare 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +583 -2
- package/dist/bindings/get-binding-token.d.ts +6 -0
- package/dist/bindings/get-binding-token.js +8 -0
- package/dist/cloudflare.module.d.ts +11 -0
- package/dist/cloudflare.module.js +55 -0
- package/dist/constants.d.ts +6 -0
- package/dist/constants.js +6 -0
- package/dist/decorators/inject-binding.decorator.d.ts +7 -0
- package/dist/decorators/inject-binding.decorator.js +10 -0
- 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 +12 -0
- package/dist/index.js +9 -0
- package/dist/interfaces/worker-options.interface.d.ts +45 -0
- package/dist/interfaces/worker-options.interface.js +1 -0
- package/dist/interfaces/worker.interface.d.ts +21 -0
- package/dist/interfaces/worker.interface.js +1 -0
- package/dist/queue/client.d.ts +19 -0
- package/dist/queue/client.js +44 -0
- package/dist/queue/constants.d.ts +6 -0
- package/dist/queue/constants.js +6 -0
- package/dist/queue/context.d.ts +25 -0
- package/dist/queue/context.js +27 -0
- package/dist/queue/index.d.ts +8 -0
- package/dist/queue/index.js +6 -0
- package/dist/queue/interfaces/client-options.interface.d.ts +14 -0
- package/dist/queue/interfaces/client-options.interface.js +1 -0
- package/dist/queue/interfaces/server-options.interface.d.ts +16 -0
- package/dist/queue/interfaces/server-options.interface.js +1 -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/queue/server.d.ts +28 -0
- package/dist/queue/server.js +102 -0
- package/dist/schedule/constants.d.ts +3 -0
- package/dist/schedule/constants.js +3 -0
- package/dist/schedule/cron.explorer.d.ts +20 -0
- package/dist/schedule/cron.explorer.js +121 -0
- package/dist/schedule/index.d.ts +1 -0
- package/dist/schedule/index.js +1 -0
- package/dist/schedule/schedule.module.d.ts +10 -0
- package/dist/schedule/schedule.module.js +33 -0
- package/dist/websockets/adapter.d.ts +76 -0
- package/dist/websockets/adapter.js +186 -0
- package/dist/websockets/context.d.ts +12 -0
- package/dist/websockets/context.js +15 -0
- package/dist/websockets/durable-object.d.ts +24 -0
- package/dist/websockets/durable-object.js +77 -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 +11 -0
- package/dist/websockets/index.js +5 -0
- package/dist/websockets/interfaces/adapter-options.interface.d.ts +14 -0
- package/dist/websockets/interfaces/adapter-options.interface.js +1 -0
- package/dist/websockets/interfaces/durable-object-options.interface.d.ts +15 -0
- package/dist/websockets/interfaces/durable-object-options.interface.js +1 -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/interfaces/message.interface.d.ts +11 -0
- package/dist/websockets/interfaces/message.interface.js +1 -0
- package/dist/websockets/interfaces/server.interface.d.ts +9 -0
- package/dist/websockets/interfaces/server.interface.js +1 -0
- package/dist/websockets/invalid-message.exception.d.ts +8 -0
- package/dist/websockets/invalid-message.exception.js +11 -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 +11 -0
- package/dist/worker/create-worker.js +223 -0
- 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 +111 -4
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { type WsMessageHandler } from '@nestjs/common';
|
|
2
|
+
import { AbstractWsAdapter } from '@nestjs/websockets';
|
|
3
|
+
import { type Observable } from 'rxjs';
|
|
4
|
+
import { type CloudflareWebSocketContext } from './context.js';
|
|
5
|
+
import type { CloudflareWebSocketAdapterOptions } from './interfaces/adapter-options.interface.js';
|
|
6
|
+
import type { CloudflareWebSocketServer } from './interfaces/server.interface.js';
|
|
7
|
+
type ConnectHandler = (client: WebSocket, request?: Request) => void;
|
|
8
|
+
type DisconnectHandler = (reason?: string) => void;
|
|
9
|
+
type Transform = (data: unknown) => Observable<unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* Connects Nest gateways to the Durable Object WebSocket Hibernation API.
|
|
12
|
+
*
|
|
13
|
+
* @publicApi
|
|
14
|
+
*/
|
|
15
|
+
export declare class CloudflareWebSocketAdapter extends AbstractWsAdapter<any, any> {
|
|
16
|
+
private readonly maxConcurrentMessages;
|
|
17
|
+
private readonly logger;
|
|
18
|
+
private readonly servers;
|
|
19
|
+
private readonly aliases;
|
|
20
|
+
private readonly clients;
|
|
21
|
+
private readonly messageParser;
|
|
22
|
+
private readonly messageSerializer;
|
|
23
|
+
/**
|
|
24
|
+
* Configures how native frames map to Nest gateway messages.
|
|
25
|
+
*/
|
|
26
|
+
constructor(options?: CloudflareWebSocketAdapterOptions);
|
|
27
|
+
/**
|
|
28
|
+
* Creates a logical gateway server without opening a TCP listener.
|
|
29
|
+
*/
|
|
30
|
+
create(port: number, options?: {
|
|
31
|
+
path?: string;
|
|
32
|
+
namespace?: string;
|
|
33
|
+
}): CloudflareWebSocketServer;
|
|
34
|
+
/**
|
|
35
|
+
* Registers Nest's connection callback for a gateway server.
|
|
36
|
+
*/
|
|
37
|
+
bindClientConnect(server: CloudflareWebSocketServer, callback: ConnectHandler): void;
|
|
38
|
+
/** Registers an additional path for an already discovered gateway. */
|
|
39
|
+
registerPathAlias(path: string, targetPath: string): void;
|
|
40
|
+
/**
|
|
41
|
+
* Registers Nest's disconnection callback for a native socket.
|
|
42
|
+
*/
|
|
43
|
+
bindClientDisconnect(client: WebSocket, callback: DisconnectHandler): void;
|
|
44
|
+
/**
|
|
45
|
+
* Retains the message callbacks and result transform provided by Nest.
|
|
46
|
+
*/
|
|
47
|
+
bindMessageHandlers(client: WebSocket, handlers: WsMessageHandler[], transform: Transform): void;
|
|
48
|
+
/**
|
|
49
|
+
* Binds a connection or a restored socket through Nest's gateway pipeline.
|
|
50
|
+
*/
|
|
51
|
+
connect(path: string, socket: WebSocket, request?: Request, context?: CloudflareWebSocketContext<unknown, unknown>): void;
|
|
52
|
+
/**
|
|
53
|
+
* Dispatches a JSON event through Nest and sends every returned value.
|
|
54
|
+
*/
|
|
55
|
+
message(socket: WebSocket, frame: string | ArrayBuffer): Promise<void>;
|
|
56
|
+
private dispatchMessage;
|
|
57
|
+
/**
|
|
58
|
+
* Dispatches disconnection hooks and releases this socket's callbacks.
|
|
59
|
+
*/
|
|
60
|
+
disconnect(socket: WebSocket, reason: string): void;
|
|
61
|
+
/**
|
|
62
|
+
* Logs a native socket error through Nest and closes the connection.
|
|
63
|
+
*/
|
|
64
|
+
error(socket: WebSocket, error: unknown): void;
|
|
65
|
+
/**
|
|
66
|
+
* Removes gateway registration while Durable Objects retain socket ownership.
|
|
67
|
+
*/
|
|
68
|
+
close(server: CloudflareWebSocketServer): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Releases gateway registrations when the Nest application shuts down.
|
|
71
|
+
*/
|
|
72
|
+
dispose(): Promise<void>;
|
|
73
|
+
private server;
|
|
74
|
+
private client;
|
|
75
|
+
}
|
|
76
|
+
export {};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { Logger } from '@nestjs/common';
|
|
2
|
+
import { AbstractWsAdapter } from '@nestjs/websockets';
|
|
3
|
+
import { lastValueFrom, tap } from 'rxjs';
|
|
4
|
+
import { attachCloudflareWebSocketContext, detachCloudflareWebSocketContext, } from './context.js';
|
|
5
|
+
import { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
6
|
+
import { WebSocketMessageDispatcher } from './message-dispatcher.js';
|
|
7
|
+
/**
|
|
8
|
+
* Connects Nest gateways to the Durable Object WebSocket Hibernation API.
|
|
9
|
+
*
|
|
10
|
+
* @publicApi
|
|
11
|
+
*/
|
|
12
|
+
// AbstractWsAdapter constrains clients and servers to Node event emitters.
|
|
13
|
+
// Durable Objects own native WebSockets and their hibernation callbacks.
|
|
14
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
15
|
+
export class CloudflareWebSocketAdapter extends AbstractWsAdapter {
|
|
16
|
+
maxConcurrentMessages;
|
|
17
|
+
logger = new Logger(CloudflareWebSocketAdapter.name);
|
|
18
|
+
servers = new Map();
|
|
19
|
+
aliases = new Map();
|
|
20
|
+
clients = new WeakMap();
|
|
21
|
+
messageParser;
|
|
22
|
+
messageSerializer;
|
|
23
|
+
/**
|
|
24
|
+
* Configures how native frames map to Nest gateway messages.
|
|
25
|
+
*/
|
|
26
|
+
constructor(options = {}) {
|
|
27
|
+
super();
|
|
28
|
+
this.maxConcurrentMessages = options.maxConcurrentMessages ?? 1000;
|
|
29
|
+
this.messageParser = options.messageParser ?? parseMessage;
|
|
30
|
+
this.messageSerializer = options.messageSerializer ?? JSON.stringify;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a logical gateway server without opening a TCP listener.
|
|
34
|
+
*/
|
|
35
|
+
create(port, options = {}) {
|
|
36
|
+
if (port !== 0 || options.namespace !== undefined) {
|
|
37
|
+
throw new Error('Durable Object gateways require port 0 and do not support Socket.IO namespaces');
|
|
38
|
+
}
|
|
39
|
+
const path = options.path ?? '/';
|
|
40
|
+
if (!path.startsWith('/')) {
|
|
41
|
+
throw new Error('WebSocket gateway path must start with /');
|
|
42
|
+
}
|
|
43
|
+
const entry = this.servers.get(path);
|
|
44
|
+
if (entry) {
|
|
45
|
+
return entry.server;
|
|
46
|
+
}
|
|
47
|
+
const server = { path };
|
|
48
|
+
this.servers.set(path, { server, connect: [] });
|
|
49
|
+
return server;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Registers Nest's connection callback for a gateway server.
|
|
53
|
+
*/
|
|
54
|
+
bindClientConnect(server, callback) {
|
|
55
|
+
this.server(server.path).connect.push(callback);
|
|
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
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Registers Nest's disconnection callback for a native socket.
|
|
64
|
+
*/
|
|
65
|
+
bindClientDisconnect(client, callback) {
|
|
66
|
+
this.client(client).disconnect.push(callback);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Retains the message callbacks and result transform provided by Nest.
|
|
70
|
+
*/
|
|
71
|
+
bindMessageHandlers(client, handlers, transform) {
|
|
72
|
+
this.client(client).messages.push({ handlers, transform });
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Binds a connection or a restored socket through Nest's gateway pipeline.
|
|
76
|
+
*/
|
|
77
|
+
connect(path, socket, request, context) {
|
|
78
|
+
if (this.clients.has(socket)) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const { connect } = this.server(path);
|
|
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
|
+
}
|
|
90
|
+
for (const callback of connect) {
|
|
91
|
+
callback(socket, request);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Dispatches a JSON event through Nest and sends every returned value.
|
|
96
|
+
*/
|
|
97
|
+
message(socket, frame) {
|
|
98
|
+
return this.client(socket).dispatcher.dispatch(frame);
|
|
99
|
+
}
|
|
100
|
+
async dispatchMessage(socket, frame) {
|
|
101
|
+
const packet = this.messageParser(frame);
|
|
102
|
+
if (!packet) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const { event, data } = packet;
|
|
106
|
+
await Promise.all(this.client(socket).messages.flatMap(({ handlers, transform }) => handlers
|
|
107
|
+
.filter(handler => handler.message === event)
|
|
108
|
+
.map(async (handler) => {
|
|
109
|
+
await lastValueFrom(transform(handler.callback(data, event)).pipe(tap(result => {
|
|
110
|
+
if (result !== undefined &&
|
|
111
|
+
result !== null &&
|
|
112
|
+
socket.readyState === WebSocket.OPEN) {
|
|
113
|
+
socket.send(this.messageSerializer(result));
|
|
114
|
+
}
|
|
115
|
+
})), { defaultValue: undefined });
|
|
116
|
+
})));
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Dispatches disconnection hooks and releases this socket's callbacks.
|
|
120
|
+
*/
|
|
121
|
+
disconnect(socket, reason) {
|
|
122
|
+
const handlers = this.client(socket);
|
|
123
|
+
handlers.dispatcher.close();
|
|
124
|
+
this.clients.delete(socket);
|
|
125
|
+
detachCloudflareWebSocketContext(socket);
|
|
126
|
+
for (const callback of handlers.disconnect) {
|
|
127
|
+
callback(reason);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Logs a native socket error through Nest and closes the connection.
|
|
132
|
+
*/
|
|
133
|
+
error(socket, error) {
|
|
134
|
+
this.logger.error(error);
|
|
135
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
136
|
+
socket.close(1011, 'WebSocket error');
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Removes gateway registration while Durable Objects retain socket ownership.
|
|
141
|
+
*/
|
|
142
|
+
async close(server) {
|
|
143
|
+
this.servers.delete(server.path);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Releases gateway registrations when the Nest application shuts down.
|
|
147
|
+
*/
|
|
148
|
+
async dispose() {
|
|
149
|
+
this.servers.clear();
|
|
150
|
+
this.aliases.clear();
|
|
151
|
+
}
|
|
152
|
+
server(path) {
|
|
153
|
+
const server = this.servers.get(this.aliases.get(path) ?? path);
|
|
154
|
+
if (!server) {
|
|
155
|
+
throw new Error(`No Nest WebSocket gateway registered for path: ${path}`);
|
|
156
|
+
}
|
|
157
|
+
return server;
|
|
158
|
+
}
|
|
159
|
+
client(socket) {
|
|
160
|
+
const client = this.clients.get(socket);
|
|
161
|
+
if (!client) {
|
|
162
|
+
throw new Error('WebSocket has not been attached to a Nest gateway');
|
|
163
|
+
}
|
|
164
|
+
return client;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function parseMessage(frame) {
|
|
168
|
+
const text = typeof frame === 'string' ? frame : new TextDecoder().decode(frame);
|
|
169
|
+
let packet;
|
|
170
|
+
try {
|
|
171
|
+
packet = JSON.parse(text);
|
|
172
|
+
}
|
|
173
|
+
catch (cause) {
|
|
174
|
+
throw new InvalidWebSocketMessageException('WebSocket message must be valid JSON', { cause });
|
|
175
|
+
}
|
|
176
|
+
if (typeof packet !== 'object' ||
|
|
177
|
+
packet === null ||
|
|
178
|
+
!('event' in packet) ||
|
|
179
|
+
typeof packet.event !== 'string') {
|
|
180
|
+
throw new InvalidWebSocketMessageException('WebSocket message requires a string event');
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
event: packet.event,
|
|
184
|
+
data: 'data' in packet ? packet.data : undefined,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { InjectionToken } from '@nestjs/common';
|
|
2
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
3
|
+
import type { CloudflareWebSocketDurableObjectOptions } from './interfaces/durable-object-options.interface.js';
|
|
4
|
+
/**
|
|
5
|
+
* Hosts a Nest gateway using the Durable Object WebSocket Hibernation API.
|
|
6
|
+
*
|
|
7
|
+
* @publicApi
|
|
8
|
+
*/
|
|
9
|
+
export declare abstract class CloudflareWebSocketDurableObject<Env = Cloudflare.Env> extends DurableObject<Env> {
|
|
10
|
+
private readonly options;
|
|
11
|
+
private readonly ready;
|
|
12
|
+
private readonly tag;
|
|
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>;
|
|
16
|
+
/** Accepts upgrades and registers connections for hibernation. */
|
|
17
|
+
fetch(request: Request): Promise<Response>;
|
|
18
|
+
/** Waits for Nest startup and gateway message handling. */
|
|
19
|
+
webSocketMessage(socket: WebSocket, message: string | ArrayBuffer): Promise<void>;
|
|
20
|
+
/** Completes the close handshake and dispatches disconnection hooks. */
|
|
21
|
+
webSocketClose(socket: WebSocket, code: number, reason: string, _wasClean: boolean): Promise<void>;
|
|
22
|
+
/** Reports native socket errors through the Nest adapter. */
|
|
23
|
+
webSocketError(socket: WebSocket, error: unknown): Promise<void>;
|
|
24
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { attachDurableObjectContext, resolveForDurableObject, } from '../durable-objects/context.js';
|
|
3
|
+
import { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
4
|
+
/**
|
|
5
|
+
* Hosts a Nest gateway using the Durable Object WebSocket Hibernation API.
|
|
6
|
+
*
|
|
7
|
+
* @publicApi
|
|
8
|
+
*/
|
|
9
|
+
export class CloudflareWebSocketDurableObject extends DurableObject {
|
|
10
|
+
options;
|
|
11
|
+
ready;
|
|
12
|
+
tag;
|
|
13
|
+
constructor(ctx, env, options) {
|
|
14
|
+
super(ctx, env);
|
|
15
|
+
this.options = options;
|
|
16
|
+
const tag = `nestjs:${options.path}`;
|
|
17
|
+
this.tag = tag;
|
|
18
|
+
this.ready = (async () => {
|
|
19
|
+
await options.getApplication();
|
|
20
|
+
for (const socket of ctx.getWebSockets(tag)) {
|
|
21
|
+
attachDurableObjectContext(socket, ctx);
|
|
22
|
+
options.adapter.connect(options.path, socket);
|
|
23
|
+
}
|
|
24
|
+
})();
|
|
25
|
+
}
|
|
26
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
27
|
+
async resolve(token) {
|
|
28
|
+
return resolveForDurableObject(await this.options.getApplication(), this.ctx, token);
|
|
29
|
+
}
|
|
30
|
+
/** Accepts upgrades and registers connections for hibernation. */
|
|
31
|
+
async fetch(request) {
|
|
32
|
+
await this.ready;
|
|
33
|
+
if (new URL(request.url).pathname !== this.options.path) {
|
|
34
|
+
return new Response('Not found', { status: 404 });
|
|
35
|
+
}
|
|
36
|
+
if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') {
|
|
37
|
+
return new Response('WebSocket upgrade required', { status: 426 });
|
|
38
|
+
}
|
|
39
|
+
const pair = new WebSocketPair();
|
|
40
|
+
this.ctx.acceptWebSocket(pair[1], [this.tag]);
|
|
41
|
+
attachDurableObjectContext(pair[1], this.ctx);
|
|
42
|
+
this.options.adapter.connect(this.options.path, pair[1], request);
|
|
43
|
+
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
44
|
+
}
|
|
45
|
+
/** Waits for Nest startup and gateway message handling. */
|
|
46
|
+
async webSocketMessage(socket, message) {
|
|
47
|
+
await this.ready;
|
|
48
|
+
try {
|
|
49
|
+
await this.options.adapter.message(socket, message);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (error instanceof InvalidWebSocketMessageException) {
|
|
53
|
+
socket.close(1007, error.message);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
this.options.adapter.error(socket, error);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Completes the close handshake and dispatches disconnection hooks. */
|
|
60
|
+
async webSocketClose(socket, code, reason, _wasClean) {
|
|
61
|
+
await this.ready;
|
|
62
|
+
try {
|
|
63
|
+
if (socket.readyState === WebSocket.OPEN ||
|
|
64
|
+
socket.readyState === WebSocket.CLOSING) {
|
|
65
|
+
socket.close(code === 1005 || code === 1006 ? 1000 : code, reason);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
this.options.adapter.disconnect(socket, reason);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Reports native socket errors through the Nest adapter. */
|
|
73
|
+
async webSocketError(socket, error) {
|
|
74
|
+
await this.ready;
|
|
75
|
+
this.options.adapter.error(socket, error);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { InjectionToken } from '@nestjs/common';
|
|
2
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
3
|
+
import type { CloudflareWebSocketGatewayOptions } from './interfaces/gateway-options.interface.js';
|
|
4
|
+
/** Hosts Nest gateways with the non-hibernating WebSocket API. */
|
|
5
|
+
export declare abstract class CloudflareWebSocketGatewayDurableObject<Env = Cloudflare.Env> extends DurableObject<Env> {
|
|
6
|
+
private readonly ready;
|
|
7
|
+
private readonly sockets;
|
|
8
|
+
private readonly options;
|
|
9
|
+
protected constructor(ctx: DurableObjectState, env: Env, options: CloudflareWebSocketGatewayOptions);
|
|
10
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
11
|
+
protected resolve<T>(token: InjectionToken<T>): Promise<T>;
|
|
12
|
+
/** Accepts a matching upgrade with server.accept(). */
|
|
13
|
+
fetch(request: Request): Promise<Response>;
|
|
14
|
+
/** Handles requests that are not WebSocket upgrades. */
|
|
15
|
+
protected nonWebSocketFetch(_request: Request): Response | Promise<Response>;
|
|
16
|
+
private handleMessage;
|
|
17
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { attachDurableObjectContext, resolveForDurableObject, } from '../durable-objects/context.js';
|
|
3
|
+
import { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
4
|
+
/** Hosts Nest gateways with the non-hibernating WebSocket API. */
|
|
5
|
+
export class CloudflareWebSocketGatewayDurableObject extends DurableObject {
|
|
6
|
+
ready;
|
|
7
|
+
sockets = new Set();
|
|
8
|
+
options;
|
|
9
|
+
constructor(ctx, env, options) {
|
|
10
|
+
super(ctx, env);
|
|
11
|
+
this.options = options;
|
|
12
|
+
for (const path of options.paths) {
|
|
13
|
+
if (!path.startsWith('/')) {
|
|
14
|
+
throw new Error(`WebSocket gateway path must start with /: ${path}`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
this.ready = options.getApplication().then(() => {
|
|
18
|
+
const firstPath = options.paths[0];
|
|
19
|
+
if (firstPath) {
|
|
20
|
+
for (const path of options.paths.slice(1)) {
|
|
21
|
+
options.adapter.registerPathAlias(path, firstPath);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** Resolves object-owned providers from fetch, alarm, and RPC handlers. */
|
|
27
|
+
async resolve(token) {
|
|
28
|
+
return resolveForDurableObject(await this.options.getApplication(), this.ctx, token);
|
|
29
|
+
}
|
|
30
|
+
/** Accepts a matching upgrade with server.accept(). */
|
|
31
|
+
async fetch(request) {
|
|
32
|
+
await this.ready;
|
|
33
|
+
const path = new URL(request.url).pathname;
|
|
34
|
+
const isUpgrade = request.headers.get('Upgrade')?.toLowerCase() === 'websocket';
|
|
35
|
+
if (!isUpgrade) {
|
|
36
|
+
return this.nonWebSocketFetch(request);
|
|
37
|
+
}
|
|
38
|
+
if (request.method !== 'GET' || !this.options.paths.includes(path)) {
|
|
39
|
+
return new Response('Not found', { status: 404 });
|
|
40
|
+
}
|
|
41
|
+
const pair = new WebSocketPair();
|
|
42
|
+
const [client, server] = Object.values(pair);
|
|
43
|
+
server.accept();
|
|
44
|
+
const context = {
|
|
45
|
+
ctx: this.ctx,
|
|
46
|
+
env: this.env,
|
|
47
|
+
object: this,
|
|
48
|
+
storage: this.ctx.storage,
|
|
49
|
+
sockets: this.sockets,
|
|
50
|
+
};
|
|
51
|
+
this.sockets.add(server);
|
|
52
|
+
attachDurableObjectContext(server, this.ctx);
|
|
53
|
+
this.options.adapter.connect(path, server, request, context);
|
|
54
|
+
server.addEventListener('message', event => {
|
|
55
|
+
void this.handleMessage(server, event.data);
|
|
56
|
+
});
|
|
57
|
+
server.addEventListener('close', event => {
|
|
58
|
+
this.sockets.delete(server);
|
|
59
|
+
this.options.adapter.disconnect(server, event.reason);
|
|
60
|
+
});
|
|
61
|
+
server.addEventListener('error', event => {
|
|
62
|
+
this.options.adapter.error(server, event);
|
|
63
|
+
});
|
|
64
|
+
return new Response(null, { status: 101, webSocket: client });
|
|
65
|
+
}
|
|
66
|
+
/** Handles requests that are not WebSocket upgrades. */
|
|
67
|
+
nonWebSocketFetch(_request) {
|
|
68
|
+
return new Response('WebSocket upgrade required', { status: 426 });
|
|
69
|
+
}
|
|
70
|
+
async handleMessage(socket, data) {
|
|
71
|
+
try {
|
|
72
|
+
await this.options.adapter.message(socket, data);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error instanceof InvalidWebSocketMessageException) {
|
|
76
|
+
socket.close(1007, error.message);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
this.options.adapter.error(socket, error);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { CloudflareWebSocketAdapter } from './adapter.js';
|
|
2
|
+
export type { CloudflareWebSocketContext } from './context.js';
|
|
3
|
+
export { getCloudflareWebSocketContext } from './context.js';
|
|
4
|
+
export { CloudflareWebSocketDurableObject } from './durable-object.js';
|
|
5
|
+
export { CloudflareWebSocketGatewayDurableObject } from './gateway-durable-object.js';
|
|
6
|
+
export type { CloudflareWebSocketAdapterOptions } from './interfaces/adapter-options.interface.js';
|
|
7
|
+
export type { CloudflareWebSocketDurableObjectOptions } from './interfaces/durable-object-options.interface.js';
|
|
8
|
+
export type { CloudflareWebSocketGatewayOptions } from './interfaces/gateway-options.interface.js';
|
|
9
|
+
export type { CloudflareWebSocketMessage } from './interfaces/message.interface.js';
|
|
10
|
+
export type { CloudflareWebSocketServer } from './interfaces/server.interface.js';
|
|
11
|
+
export { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { CloudflareWebSocketAdapter } from './adapter.js';
|
|
2
|
+
export { getCloudflareWebSocketContext } from './context.js';
|
|
3
|
+
export { CloudflareWebSocketDurableObject } from './durable-object.js';
|
|
4
|
+
export { CloudflareWebSocketGatewayDurableObject } from './gateway-durable-object.js';
|
|
5
|
+
export { InvalidWebSocketMessageException } from './invalid-message.exception.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CloudflareWebSocketMessage } from './message.interface.js';
|
|
2
|
+
/**
|
|
3
|
+
* Configures parsing of native WebSocket frames before Nest dispatch.
|
|
4
|
+
*
|
|
5
|
+
* @publicApi
|
|
6
|
+
*/
|
|
7
|
+
export interface CloudflareWebSocketAdapterOptions {
|
|
8
|
+
/** Maximum active messages per connection. Defaults to 1000; use 1 for serial handling. */
|
|
9
|
+
maxConcurrentMessages?: number;
|
|
10
|
+
/** Maps a frame to an event and payload, or returns void to ignore it. */
|
|
11
|
+
messageParser?: (data: string | ArrayBuffer) => CloudflareWebSocketMessage | void;
|
|
12
|
+
/** Serializes values returned by gateway handlers before sending them. */
|
|
13
|
+
messageSerializer?: (data: unknown) => string | ArrayBuffer;
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { INestApplication } from '@nestjs/common';
|
|
2
|
+
import type { CloudflareWebSocketAdapter } from '../adapter.js';
|
|
3
|
+
/**
|
|
4
|
+
* Selects the gateway and application used by a Durable Object.
|
|
5
|
+
*
|
|
6
|
+
* @publicApi
|
|
7
|
+
*/
|
|
8
|
+
export interface CloudflareWebSocketDurableObjectOptions {
|
|
9
|
+
/** Adapter installed on the Nest application. */
|
|
10
|
+
adapter: CloudflareWebSocketAdapter;
|
|
11
|
+
/** Path declared by the gateway's WebSocketGateway options. */
|
|
12
|
+
path: string;
|
|
13
|
+
/** Starts or retrieves the initialized Nest application. */
|
|
14
|
+
getApplication: () => Promise<INestApplication>;
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { INestApplicationContext } from '@nestjs/common';
|
|
2
|
+
import type { CloudflareWebSocketAdapter } from '../adapter.js';
|
|
3
|
+
/** Options for a non-hibernating Durable Object gateway host. */
|
|
4
|
+
export interface CloudflareWebSocketGatewayOptions {
|
|
5
|
+
/** Adapter installed on the Nest application. */
|
|
6
|
+
adapter: CloudflareWebSocketAdapter;
|
|
7
|
+
/** Gateway paths served by this Durable Object. */
|
|
8
|
+
paths: readonly string[];
|
|
9
|
+
/** Starts or retrieves the initialized Nest application. */
|
|
10
|
+
getApplication: () => Promise<INestApplicationContext>;
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A message mapped to a Nest gateway event.
|
|
3
|
+
*
|
|
4
|
+
* @publicApi
|
|
5
|
+
*/
|
|
6
|
+
export interface CloudflareWebSocketMessage {
|
|
7
|
+
/** Name matched against SubscribeMessage metadata. */
|
|
8
|
+
event: string;
|
|
9
|
+
/** Payload passed to the gateway's message handler. */
|
|
10
|
+
data: unknown;
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identifies a frame that cannot be decoded as an application message.
|
|
3
|
+
*
|
|
4
|
+
* @publicApi
|
|
5
|
+
*/
|
|
6
|
+
export class InvalidWebSocketMessageException extends Error {
|
|
7
|
+
constructor(message, options) {
|
|
8
|
+
super(message, options);
|
|
9
|
+
this.name = 'InvalidWebSocketMessageException';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Applies a concurrency limit to one socket's asynchronous dispatch. */
|
|
2
|
+
export declare class WebSocketMessageDispatcher {
|
|
3
|
+
private readonly pending;
|
|
4
|
+
private closed;
|
|
5
|
+
constructor(handle: (frame: string | ArrayBuffer) => Promise<void>, concurrency: number);
|
|
6
|
+
dispatch(frame: string | ArrayBuffer): Promise<void>;
|
|
7
|
+
close(): void;
|
|
8
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { catchError, defer, EMPTY, mergeMap, Subject, tap } from 'rxjs';
|
|
2
|
+
/** Applies a concurrency limit to one socket's asynchronous dispatch. */
|
|
3
|
+
export class WebSocketMessageDispatcher {
|
|
4
|
+
pending = new Subject();
|
|
5
|
+
closed = false;
|
|
6
|
+
constructor(handle, concurrency) {
|
|
7
|
+
this.pending
|
|
8
|
+
.pipe(mergeMap(task => defer(() => this.closed ? Promise.resolve() : handle(task.frame)).pipe(tap(() => task.resolve()), catchError((error) => {
|
|
9
|
+
task.reject(error);
|
|
10
|
+
return EMPTY;
|
|
11
|
+
})), concurrency))
|
|
12
|
+
.subscribe();
|
|
13
|
+
}
|
|
14
|
+
dispatch(frame) {
|
|
15
|
+
if (this.closed) {
|
|
16
|
+
return Promise.resolve();
|
|
17
|
+
}
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
this.pending.next({ frame, resolve, reject });
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
close() {
|
|
23
|
+
this.closed = true;
|
|
24
|
+
this.pending.complete();
|
|
25
|
+
}
|
|
26
|
+
}
|