@nmtjs/ws-transport 0.0.1
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.md +7 -0
- package/README.md +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/providers.js +2 -0
- package/dist/lib/providers.js.map +1 -0
- package/dist/lib/server.js +347 -0
- package/dist/lib/server.js.map +1 -0
- package/dist/lib/transport.js +11 -0
- package/dist/lib/transport.js.map +1 -0
- package/dist/lib/types.js +1 -0
- package/dist/lib/types.js.map +1 -0
- package/dist/lib/utils.js +63 -0
- package/dist/lib/utils.js.map +1 -0
- package/index.ts +5 -0
- package/lib/providers.ts +5 -0
- package/lib/server.ts +469 -0
- package/lib/transport.ts +16 -0
- package/lib/types.ts +72 -0
- package/lib/utils.ts +115 -0
- package/package.json +37 -0
- package/tsconfig.json +3 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright (c) 2024 Denis Ilchyshyn
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
## WebSockets transport for [Neemata](https://github.com/neematajs/neemata)
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../index.ts"],"sourcesContent":["export * from './lib/server.ts'\nexport * from './lib/transport.ts'\nexport * from './lib/types.ts'\nexport * from './lib/utils.ts'\nexport * from './lib/providers.ts'\n"],"names":[],"mappings":"AAAA,cAAc,kBAAiB;AAC/B,cAAc,qBAAoB;AAClC,cAAc,iBAAgB;AAC9B,cAAc,iBAAgB;AAC9B,cAAc,qBAAoB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/providers.ts"],"sourcesContent":["import { providers } from '@nmtjs/application'\nimport type { WsConnectionData } from './types.ts'\n\nexport const connectionData =\n providers.connectionData.$withType<WsConnectionData>()\n"],"names":["providers","connectionData","$withType"],"mappings":"AAAA,SAASA,SAAS,QAAQ,qBAAoB;AAG9C,OAAO,MAAMC,iBACXD,UAAUC,cAAc,CAACC,SAAS,GAAoB"}
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ApiError, Scope, ServerDownStream, ServerUpStream, SubscriptionResponse, onAbort } from '@nmtjs/application';
|
|
3
|
+
import { MessageType, TransportType, decodeNumber, encodeNumber } from '@nmtjs/common';
|
|
4
|
+
import { App, SSLApp } from 'uWebSockets.js';
|
|
5
|
+
import { connectionData } from "./providers.js";
|
|
6
|
+
import { InternalError, getFormat, getRequestData, send, sendMessage, sendRpcMessage } from "./utils.js";
|
|
7
|
+
export class WsTransportServer {
|
|
8
|
+
application;
|
|
9
|
+
options;
|
|
10
|
+
server;
|
|
11
|
+
transportType;
|
|
12
|
+
constructor(application, options){
|
|
13
|
+
this.application = application;
|
|
14
|
+
this.options = options;
|
|
15
|
+
this.transportType = TransportType.WS;
|
|
16
|
+
this.server = this.options.tls ? SSLApp(options.tls) : App();
|
|
17
|
+
this.server.get('/healthy', (res)=>{
|
|
18
|
+
res.writeHeader('Access-Control-Allow-Origin', '*');
|
|
19
|
+
res.writeHeader('Access-Control-Allow-Headers', 'Content-Type');
|
|
20
|
+
res.writeHeader('Access-Control-Allow-Methods', 'GET');
|
|
21
|
+
res.writeHeader('Content-Type', 'text/plain');
|
|
22
|
+
res.end('OK');
|
|
23
|
+
}).ws('/api', {
|
|
24
|
+
sendPingsAutomatically: true,
|
|
25
|
+
maxPayloadLength: this.options.maxPayloadLength,
|
|
26
|
+
upgrade: (res, req, context)=>{
|
|
27
|
+
const requestData = getRequestData(req);
|
|
28
|
+
const container = this.application.container.createScope(Scope.Connection);
|
|
29
|
+
const services = requestData.query.getAll('services');
|
|
30
|
+
for (const serviceName of services){
|
|
31
|
+
const service = this.application.registry.services.get(serviceName);
|
|
32
|
+
if (!service) throw new Response(`Service ${service} not found`, {
|
|
33
|
+
status: 400
|
|
34
|
+
});
|
|
35
|
+
if (this.transportType in service.contract.transports === false) throw new Response(`Service ${service} not supported`, {
|
|
36
|
+
status: 400
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
const data = {
|
|
40
|
+
id: randomUUID(),
|
|
41
|
+
format: getFormat(requestData, this.application.format),
|
|
42
|
+
container,
|
|
43
|
+
streams: {
|
|
44
|
+
up: new Map(),
|
|
45
|
+
down: new Map(),
|
|
46
|
+
streamId: 0
|
|
47
|
+
},
|
|
48
|
+
abortControllers: new Map(),
|
|
49
|
+
subscriptions: new Map(),
|
|
50
|
+
services,
|
|
51
|
+
data: {
|
|
52
|
+
query: requestData.query,
|
|
53
|
+
headers: requestData.headers,
|
|
54
|
+
proxiedRemoteAddress: Buffer.from(res.getProxiedRemoteAddressAsText()).toString(),
|
|
55
|
+
remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString()
|
|
56
|
+
},
|
|
57
|
+
backpressure: null,
|
|
58
|
+
context: {}
|
|
59
|
+
};
|
|
60
|
+
res.upgrade(data, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
|
|
61
|
+
},
|
|
62
|
+
open: (ws)=>{
|
|
63
|
+
const data = ws.getUserData();
|
|
64
|
+
data.context.decode = this.createDecodeRpcContext(ws);
|
|
65
|
+
data.context.encode = this.createEncodeRpcContext(ws);
|
|
66
|
+
data.container.provide(connectionData, data.data);
|
|
67
|
+
this.application.connections.add({
|
|
68
|
+
id: data.id,
|
|
69
|
+
services: data.services,
|
|
70
|
+
type: this.transportType,
|
|
71
|
+
subscriptions: data.subscriptions,
|
|
72
|
+
sendEvent: (service, event, payload)=>sendMessage(ws, MessageType.Event, [
|
|
73
|
+
service,
|
|
74
|
+
event,
|
|
75
|
+
payload
|
|
76
|
+
])
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
message: async (ws, event)=>{
|
|
80
|
+
const buffer = event;
|
|
81
|
+
const messageType = decodeNumber(buffer, 'Uint8');
|
|
82
|
+
if (messageType in this === false) {
|
|
83
|
+
ws.end(1011, 'Unknown message type');
|
|
84
|
+
} else {
|
|
85
|
+
try {
|
|
86
|
+
await this[messageType](ws, buffer.slice(Uint8Array.BYTES_PER_ELEMENT));
|
|
87
|
+
} catch (error) {
|
|
88
|
+
this.logError(error, 'Error while processing message');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
drain: (ws)=>{
|
|
93
|
+
const data = ws.getUserData();
|
|
94
|
+
data.backpressure?.resolve();
|
|
95
|
+
data.backpressure = null;
|
|
96
|
+
},
|
|
97
|
+
close: (ws)=>{
|
|
98
|
+
const data = ws.getUserData();
|
|
99
|
+
this.application.connections.remove(data.id);
|
|
100
|
+
const error = new Error('Connection closed');
|
|
101
|
+
for (const ac of data.abortControllers.values()){
|
|
102
|
+
ac.abort(error);
|
|
103
|
+
}
|
|
104
|
+
data.abortControllers.clear();
|
|
105
|
+
for (const stream of data.streams.down.values()){
|
|
106
|
+
stream.destroy(error);
|
|
107
|
+
}
|
|
108
|
+
data.streams.down.clear();
|
|
109
|
+
for (const stream of data.streams.up.values()){
|
|
110
|
+
stream.destroy(error);
|
|
111
|
+
}
|
|
112
|
+
data.streams.up.clear();
|
|
113
|
+
for (const subscription of data.subscriptions.values()){
|
|
114
|
+
subscription.destroy();
|
|
115
|
+
}
|
|
116
|
+
data.subscriptions.clear();
|
|
117
|
+
this.handleContainerDisposal(data.container);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
async start() {
|
|
122
|
+
return new Promise((resolve, reject)=>{
|
|
123
|
+
const hostname = this.options.hostname ?? '127.0.0.1';
|
|
124
|
+
this.server.listen(hostname, this.options.port, (socket)=>{
|
|
125
|
+
if (socket) {
|
|
126
|
+
this.logger.info('Server started on %s:%s', hostname, this.options.port);
|
|
127
|
+
resolve();
|
|
128
|
+
} else {
|
|
129
|
+
reject(new Error('Failed to start server'));
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
async stop() {
|
|
135
|
+
this.server.close();
|
|
136
|
+
}
|
|
137
|
+
get api() {
|
|
138
|
+
return this.application.api;
|
|
139
|
+
}
|
|
140
|
+
get logger() {
|
|
141
|
+
return this.application.logger;
|
|
142
|
+
}
|
|
143
|
+
async logError(cause, message = 'Unknown error while processing request') {
|
|
144
|
+
this.logger.error(new Error(message, {
|
|
145
|
+
cause
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
handleContainerDisposal(container) {
|
|
149
|
+
container.dispose();
|
|
150
|
+
}
|
|
151
|
+
async handleRPC(options) {
|
|
152
|
+
return await this.api.call({
|
|
153
|
+
...options,
|
|
154
|
+
transport: this.transportType
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
createEncodeRpcContext(ws) {
|
|
158
|
+
const data = ws.getUserData();
|
|
159
|
+
return {
|
|
160
|
+
addStream: (blob)=>{
|
|
161
|
+
const id = ++data.streams.streamId;
|
|
162
|
+
const downstream = new ServerDownStream(id, blob);
|
|
163
|
+
downstream.pause();
|
|
164
|
+
downstream.on('error', console.dir);
|
|
165
|
+
downstream.once('error', (err)=>{
|
|
166
|
+
console.log({
|
|
167
|
+
err
|
|
168
|
+
});
|
|
169
|
+
if (downstream.errored?.message !== 'Aborted by client') send(ws, MessageType.DownStreamAbort, encodeNumber(id, 'Uint32'));
|
|
170
|
+
});
|
|
171
|
+
downstream.on('data', (chunk)=>{
|
|
172
|
+
downstream.pause();
|
|
173
|
+
send(ws, MessageType.DownStreamPush, encodeNumber(id, 'Uint32'), Buffer.from(chunk).buffer);
|
|
174
|
+
});
|
|
175
|
+
data.streams.down.set(id, downstream);
|
|
176
|
+
return {
|
|
177
|
+
id,
|
|
178
|
+
metadata: blob.metadata
|
|
179
|
+
};
|
|
180
|
+
},
|
|
181
|
+
getStream: (id)=>{
|
|
182
|
+
return data.streams.down.get(id);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
createDecodeRpcContext(ws) {
|
|
187
|
+
const data = ws.getUserData();
|
|
188
|
+
return {
|
|
189
|
+
addStream (signal, id, metadata) {
|
|
190
|
+
const upstream = new ServerUpStream(metadata, {
|
|
191
|
+
read: (size)=>{
|
|
192
|
+
send(ws, MessageType.UpStreamPull, encodeNumber(id, 'Uint32'), encodeNumber(size, 'Uint32'));
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
data.streams.up.set(id, upstream);
|
|
196
|
+
onAbort(signal, ()=>{
|
|
197
|
+
upstream.destroy(new Error('Call aborted by client'));
|
|
198
|
+
});
|
|
199
|
+
upstream.once('error', (error)=>{
|
|
200
|
+
if (error.message !== 'Aborted by server') send(ws, MessageType.UpStreamAbort, encodeNumber(id, 'Uint32'));
|
|
201
|
+
});
|
|
202
|
+
upstream.once('close', ()=>{
|
|
203
|
+
if (upstream.errored?.message !== 'Aborted by server') send(ws, MessageType.UpStreamEnd, encodeNumber(id, 'Uint32'));
|
|
204
|
+
});
|
|
205
|
+
return upstream;
|
|
206
|
+
},
|
|
207
|
+
getStream (id) {
|
|
208
|
+
return data.streams.down.get(id);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
async [MessageType.Rpc](ws, buffer) {
|
|
213
|
+
const data = ws.getUserData();
|
|
214
|
+
const connection = this.application.connections.get(data.id);
|
|
215
|
+
if (!connection) return void ws.end(1011, 'Unknown connection');
|
|
216
|
+
const ac = new AbortController();
|
|
217
|
+
const rpc = data.format.decoder.decodeRpc(buffer, {
|
|
218
|
+
...data.context.decode,
|
|
219
|
+
addStream: data.context.decode.addStream.bind(null, ac.signal)
|
|
220
|
+
});
|
|
221
|
+
data.abortControllers.set(rpc.callId, ac);
|
|
222
|
+
const container = data.container.createScope(Scope.Call);
|
|
223
|
+
try {
|
|
224
|
+
const { service, procedure } = this.api.find(rpc.service, rpc.procedure, this.transportType);
|
|
225
|
+
const response = await this.handleRPC({
|
|
226
|
+
connection,
|
|
227
|
+
service,
|
|
228
|
+
procedure,
|
|
229
|
+
container,
|
|
230
|
+
signal: ac.signal,
|
|
231
|
+
payload: rpc.payload
|
|
232
|
+
});
|
|
233
|
+
if (response instanceof SubscriptionResponse) {
|
|
234
|
+
sendRpcMessage(ws, MessageType.RpcSubscription, {
|
|
235
|
+
callId: rpc.callId,
|
|
236
|
+
error: null,
|
|
237
|
+
payload: [
|
|
238
|
+
response.subscription.key,
|
|
239
|
+
response.payload
|
|
240
|
+
]
|
|
241
|
+
});
|
|
242
|
+
response.subscription.on('event', (event, payload)=>{
|
|
243
|
+
sendMessage(ws, MessageType.ServerSubscriptionEvent, [
|
|
244
|
+
response.subscription.key,
|
|
245
|
+
event,
|
|
246
|
+
payload
|
|
247
|
+
]);
|
|
248
|
+
});
|
|
249
|
+
response.subscription.once('end', ()=>{
|
|
250
|
+
sendMessage(ws, MessageType.ServerUnsubscribe, [
|
|
251
|
+
response.subscription.key
|
|
252
|
+
]);
|
|
253
|
+
});
|
|
254
|
+
} else {
|
|
255
|
+
sendRpcMessage(ws, MessageType.Rpc, {
|
|
256
|
+
callId: rpc.callId,
|
|
257
|
+
error: null,
|
|
258
|
+
payload: response
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error instanceof ApiError) {
|
|
263
|
+
this.logger.debug(new Error('Api error', {
|
|
264
|
+
cause: error
|
|
265
|
+
}));
|
|
266
|
+
sendRpcMessage(ws, MessageType.Rpc, {
|
|
267
|
+
callId: rpc.callId,
|
|
268
|
+
error,
|
|
269
|
+
payload: null
|
|
270
|
+
});
|
|
271
|
+
} else {
|
|
272
|
+
this.logger.error(new Error('Unexpected error', {
|
|
273
|
+
cause: error
|
|
274
|
+
}));
|
|
275
|
+
sendRpcMessage(ws, MessageType.Rpc, {
|
|
276
|
+
callId: rpc.callId,
|
|
277
|
+
error: InternalError(),
|
|
278
|
+
payload: null
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
} finally{
|
|
282
|
+
data.abortControllers.delete(rpc.callId);
|
|
283
|
+
this.handleContainerDisposal(container);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async [MessageType.UpStreamPush](ws, buffer) {
|
|
287
|
+
const data = ws.getUserData();
|
|
288
|
+
const id = decodeNumber(buffer, 'Uint32');
|
|
289
|
+
const stream = data.streams.up.get(id);
|
|
290
|
+
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
291
|
+
stream.push(Buffer.from(buffer.slice(Uint32Array.BYTES_PER_ELEMENT)));
|
|
292
|
+
}
|
|
293
|
+
async [MessageType.UpStreamEnd](ws, buffer) {
|
|
294
|
+
const data = ws.getUserData();
|
|
295
|
+
const id = decodeNumber(buffer, 'Uint32');
|
|
296
|
+
const stream = data.streams.up.get(id);
|
|
297
|
+
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
298
|
+
stream.push(null);
|
|
299
|
+
data.streams.up.delete(id);
|
|
300
|
+
}
|
|
301
|
+
async [MessageType.UpStreamAbort](ws, buffer) {
|
|
302
|
+
const data = ws.getUserData();
|
|
303
|
+
const id = decodeNumber(buffer, 'Uint32');
|
|
304
|
+
const stream = data.streams.up.get(id);
|
|
305
|
+
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
306
|
+
stream.destroy(new Error('Aborted by client'));
|
|
307
|
+
data.streams.up.delete(id);
|
|
308
|
+
}
|
|
309
|
+
async [MessageType.DownStreamPull](ws, buffer) {
|
|
310
|
+
const data = ws.getUserData();
|
|
311
|
+
const id = decodeNumber(buffer, 'Uint32');
|
|
312
|
+
const stream = data.streams.down.get(id);
|
|
313
|
+
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
314
|
+
await data.backpressure?.promise;
|
|
315
|
+
if (stream.readableEnded) send(ws, MessageType.DownStreamEnd, encodeNumber(id, 'Uint32'));
|
|
316
|
+
else stream.resume();
|
|
317
|
+
}
|
|
318
|
+
async [MessageType.DownStreamEnd](ws, buffer) {
|
|
319
|
+
const data = ws.getUserData();
|
|
320
|
+
const id = decodeNumber(buffer, 'Uint32');
|
|
321
|
+
const stream = data.streams.down.get(id);
|
|
322
|
+
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
323
|
+
data.streams.down.delete(id);
|
|
324
|
+
}
|
|
325
|
+
async [MessageType.DownStreamAbort](ws, buffer) {
|
|
326
|
+
const data = ws.getUserData();
|
|
327
|
+
const id = decodeNumber(buffer, 'Uint32');
|
|
328
|
+
const stream = data.streams.down.get(id);
|
|
329
|
+
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
330
|
+
stream.destroy(new Error('Aborted by client'));
|
|
331
|
+
data.streams.down.delete(id);
|
|
332
|
+
}
|
|
333
|
+
async [MessageType.ClientUnsubscribe](ws, buffer) {
|
|
334
|
+
const data = ws.getUserData();
|
|
335
|
+
const [key] = data.format.decoder.decode(buffer);
|
|
336
|
+
const subscription = data.subscriptions.get(key);
|
|
337
|
+
if (!subscription) return void ws.end();
|
|
338
|
+
subscription.destroy();
|
|
339
|
+
data.subscriptions.delete(key);
|
|
340
|
+
}
|
|
341
|
+
async [MessageType.RpcAbort](ws, buffer) {
|
|
342
|
+
const data = ws.getUserData();
|
|
343
|
+
const callId = decodeNumber(buffer, 'Uint32');
|
|
344
|
+
const ac = data.abortControllers.get(callId);
|
|
345
|
+
if (ac) ac.abort(new Error('Aborted by client'));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport {\n type AnyProcedure,\n ApiError,\n type ApplicationContext,\n type Connection,\n type Container,\n Scope,\n ServerDownStream,\n ServerUpStream,\n type Service,\n SubscriptionResponse,\n onAbort,\n} from '@nmtjs/application'\nimport {\n type ApiBlobMetadata,\n type EncodeRpcContext,\n MessageType,\n TransportType,\n decodeNumber,\n encodeNumber,\n} from '@nmtjs/common'\nimport { App, SSLApp, type TemplatedApp } from 'uWebSockets.js'\nimport { connectionData } from './providers.ts'\nimport type {\n WsTransportOptions,\n WsTransportSocket,\n WsUserData,\n} from './types.ts'\nimport {\n InternalError,\n getFormat,\n getRequestData,\n send,\n sendMessage,\n sendRpcMessage,\n} from './utils.ts'\n\nexport class WsTransportServer {\n protected server!: TemplatedApp\n protected readonly transportType = TransportType.WS\n\n constructor(\n protected readonly application: ApplicationContext,\n protected readonly options: WsTransportOptions,\n ) {\n this.server = this.options.tls ? SSLApp(options.tls!) : App()\n\n this.server\n .get('/healthy', (res) => {\n // cors\n res.writeHeader('Access-Control-Allow-Origin', '*')\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET')\n res.writeHeader('Content-Type', 'text/plain')\n res.end('OK')\n })\n .ws<WsUserData>('/api', {\n sendPingsAutomatically: true,\n maxPayloadLength: this.options.maxPayloadLength,\n upgrade: (res, req, context) => {\n const requestData = getRequestData(req)\n const container = this.application.container.createScope(\n Scope.Connection,\n )\n const services = requestData.query.getAll('services')\n\n for (const serviceName of services) {\n const service = this.application.registry.services.get(serviceName)\n if (!service)\n throw new Response(`Service ${service} not found`, {\n status: 400,\n })\n if (this.transportType in service.contract.transports === false)\n throw new Response(`Service ${service} not supported`, {\n status: 400,\n })\n }\n\n const data: WsUserData = {\n id: randomUUID(),\n format: getFormat(requestData, this.application.format),\n container,\n streams: {\n up: new Map(),\n down: new Map(),\n streamId: 0,\n },\n abortControllers: new Map(),\n subscriptions: new Map(),\n services,\n data: {\n query: requestData.query,\n headers: requestData.headers,\n proxiedRemoteAddress: Buffer.from(\n res.getProxiedRemoteAddressAsText(),\n ).toString(),\n remoteAddress: Buffer.from(\n res.getRemoteAddressAsText(),\n ).toString(),\n },\n backpressure: null,\n context: {} as any,\n }\n\n res.upgrade(\n data,\n req.getHeader('sec-websocket-key'),\n req.getHeader('sec-websocket-protocol'),\n req.getHeader('sec-websocket-extensions'),\n context,\n )\n },\n open: (ws: WsTransportSocket) => {\n const data = ws.getUserData()\n data.context.decode = this.createDecodeRpcContext(ws)\n data.context.encode = this.createEncodeRpcContext(ws)\n data.container.provide(connectionData, data.data)\n this.application.connections.add({\n id: data.id,\n services: data.services,\n type: this.transportType,\n subscriptions: data.subscriptions,\n sendEvent: (service, event, payload) =>\n sendMessage(ws, MessageType.Event, [service, event, payload]),\n })\n },\n message: async (ws: WsTransportSocket, event) => {\n const buffer = event as unknown as ArrayBuffer\n const messageType = decodeNumber(buffer, 'Uint8')\n if (messageType in this === false) {\n ws.end(1011, 'Unknown message type')\n } else {\n try {\n await this[messageType](\n ws,\n buffer.slice(Uint8Array.BYTES_PER_ELEMENT),\n )\n } catch (error: any) {\n this.logError(error, 'Error while processing message')\n }\n }\n },\n drain: (ws: WsTransportSocket) => {\n const data = ws.getUserData()\n data.backpressure?.resolve()\n data.backpressure = null\n },\n close: (ws: WsTransportSocket) => {\n const data = ws.getUserData()\n\n this.application.connections.remove(data.id)\n const error = new Error('Connection closed')\n\n for (const ac of data.abortControllers.values()) {\n ac.abort(error)\n }\n data.abortControllers.clear()\n\n for (const stream of data.streams.down.values()) {\n stream.destroy(error)\n }\n data.streams.down.clear()\n\n for (const stream of data.streams.up.values()) {\n stream.destroy(error)\n }\n data.streams.up.clear()\n\n for (const subscription of data.subscriptions.values()) {\n subscription.destroy()\n }\n data.subscriptions.clear()\n\n this.handleContainerDisposal(data.container)\n },\n })\n }\n\n async start() {\n return new Promise<void>((resolve, reject) => {\n const hostname = this.options.hostname ?? '127.0.0.1'\n this.server.listen(hostname, this.options.port!, (socket) => {\n if (socket) {\n this.logger.info(\n 'Server started on %s:%s',\n hostname,\n this.options.port!,\n )\n resolve()\n } else {\n reject(new Error('Failed to start server'))\n }\n })\n })\n }\n\n async stop() {\n this.server.close()\n }\n\n protected get api() {\n return this.application.api\n }\n\n protected get logger() {\n return this.application.logger\n }\n\n protected async logError(\n cause: Error,\n message = 'Unknown error while processing request',\n ) {\n this.logger.error(new Error(message, { cause }))\n }\n\n protected handleContainerDisposal(container: Container) {\n container.dispose()\n }\n\n protected async handleRPC(options: {\n connection: Connection\n service: Service\n procedure: AnyProcedure\n container: Container\n signal: AbortSignal\n payload: any\n }) {\n return await this.api.call({\n ...options,\n transport: this.transportType,\n })\n }\n\n protected createEncodeRpcContext(ws: WsTransportSocket): EncodeRpcContext {\n const data = ws.getUserData()\n return {\n addStream: (blob) => {\n const id = ++data.streams.streamId\n const downstream = new ServerDownStream(id, blob)\n downstream.pause()\n downstream.on('error', console.dir)\n downstream.once('error', (err) => {\n console.log({ err })\n if (downstream.errored?.message !== 'Aborted by client')\n send(ws, MessageType.DownStreamAbort, encodeNumber(id, 'Uint32'))\n })\n downstream.on('data', (chunk) => {\n downstream.pause()\n send(\n ws,\n MessageType.DownStreamPush,\n encodeNumber(id, 'Uint32'),\n Buffer.from(chunk).buffer as ArrayBuffer,\n )\n })\n data.streams.down.set(id, downstream)\n return { id, metadata: blob.metadata }\n },\n getStream: (id) => {\n return data.streams.down.get(id)!\n },\n }\n }\n\n protected createDecodeRpcContext(ws: WsTransportSocket) {\n const data = ws.getUserData()\n return {\n addStream(signal: AbortSignal, id: number, metadata: ApiBlobMetadata) {\n const upstream = new ServerUpStream(metadata, {\n read: (size) => {\n send(\n ws,\n MessageType.UpStreamPull,\n encodeNumber(id, 'Uint32'),\n encodeNumber(size, 'Uint32'),\n )\n },\n })\n\n data.streams.up.set(id, upstream)\n onAbort(signal, () => {\n upstream.destroy(new Error('Call aborted by client'))\n })\n upstream.once('error', (error) => {\n if (error.message !== 'Aborted by server')\n send(ws, MessageType.UpStreamAbort, encodeNumber(id, 'Uint32'))\n })\n upstream.once('close', () => {\n if (upstream.errored?.message !== 'Aborted by server')\n send(ws, MessageType.UpStreamEnd, encodeNumber(id, 'Uint32'))\n })\n\n return upstream\n },\n getStream(id) {\n return data.streams.down.get(id)\n },\n }\n }\n\n protected async [MessageType.Rpc](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n\n const connection = this.application.connections.get(data.id)\n if (!connection) return void ws.end(1011, 'Unknown connection')\n\n const ac = new AbortController()\n const rpc = data.format.decoder.decodeRpc(buffer, {\n ...data.context.decode,\n addStream: data.context.decode.addStream.bind(null, ac.signal),\n })\n\n data.abortControllers.set(rpc.callId, ac)\n\n const container = data.container.createScope(Scope.Call)\n\n try {\n const { service, procedure } = this.api.find(\n rpc.service,\n rpc.procedure,\n this.transportType,\n )\n\n const response = await this.handleRPC({\n connection,\n service,\n procedure,\n container,\n signal: ac.signal,\n payload: rpc.payload,\n })\n\n if (response instanceof SubscriptionResponse) {\n sendRpcMessage(ws, MessageType.RpcSubscription, {\n callId: rpc.callId,\n error: null,\n payload: [response.subscription.key, response.payload],\n })\n\n response.subscription.on('event', (event, payload) => {\n sendMessage(ws, MessageType.ServerSubscriptionEvent, [\n response.subscription.key,\n event,\n payload,\n ])\n })\n response.subscription.once('end', () => {\n sendMessage(ws, MessageType.ServerUnsubscribe, [\n response.subscription.key,\n ])\n })\n } else {\n sendRpcMessage(ws, MessageType.Rpc, {\n callId: rpc.callId,\n error: null,\n payload: response,\n })\n }\n } catch (error) {\n if (error instanceof ApiError) {\n this.logger.debug(new Error('Api error', { cause: error }))\n sendRpcMessage(ws, MessageType.Rpc, {\n callId: rpc.callId,\n error,\n payload: null,\n })\n } else {\n this.logger.error(new Error('Unexpected error', { cause: error }))\n sendRpcMessage(ws, MessageType.Rpc, {\n callId: rpc.callId,\n error: InternalError(),\n payload: null,\n })\n }\n } finally {\n data.abortControllers.delete(rpc.callId)\n this.handleContainerDisposal(container)\n }\n }\n\n async [MessageType.UpStreamPush](ws: WsTransportSocket, buffer: ArrayBuffer) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.up.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.push(Buffer.from(buffer.slice(Uint32Array.BYTES_PER_ELEMENT)))\n }\n\n async [MessageType.UpStreamEnd](ws: WsTransportSocket, buffer: ArrayBuffer) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.up.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.push(null)\n data.streams.up.delete(id)\n }\n\n async [MessageType.UpStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.up.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.destroy(new Error('Aborted by client'))\n data.streams.up.delete(id)\n }\n\n async [MessageType.DownStreamPull](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.down.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n await data.backpressure?.promise\n if (stream.readableEnded)\n send(ws, MessageType.DownStreamEnd, encodeNumber(id, 'Uint32'))\n else stream.resume()\n }\n\n async [MessageType.DownStreamEnd](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.down.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n data.streams.down.delete(id)\n }\n\n async [MessageType.DownStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const id = decodeNumber(buffer, 'Uint32')\n const stream = data.streams.down.get(id)\n if (!stream) return ws.end(1011, 'Unknown stream')\n stream.destroy(new Error('Aborted by client'))\n data.streams.down.delete(id)\n }\n\n async [MessageType.ClientUnsubscribe](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const data = ws.getUserData()\n const [key] = data.format.decoder.decode(buffer)\n const subscription = data.subscriptions.get(key)\n if (!subscription) return void ws.end()\n subscription.destroy()\n data.subscriptions.delete(key)\n }\n\n async [MessageType.RpcAbort](ws: WsTransportSocket, buffer: ArrayBuffer) {\n const data = ws.getUserData()\n const callId = decodeNumber(buffer, 'Uint32')\n const ac = data.abortControllers.get(callId)\n if (ac) ac.abort(new Error('Aborted by client'))\n }\n}\n"],"names":["randomUUID","ApiError","Scope","ServerDownStream","ServerUpStream","SubscriptionResponse","onAbort","MessageType","TransportType","decodeNumber","encodeNumber","App","SSLApp","connectionData","InternalError","getFormat","getRequestData","send","sendMessage","sendRpcMessage","WsTransportServer","server","transportType","constructor","application","options","WS","tls","get","res","writeHeader","end","ws","sendPingsAutomatically","maxPayloadLength","upgrade","req","context","requestData","container","createScope","Connection","services","query","getAll","serviceName","service","registry","Response","status","contract","transports","data","id","format","streams","up","Map","down","streamId","abortControllers","subscriptions","headers","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","backpressure","getHeader","open","getUserData","decode","createDecodeRpcContext","encode","createEncodeRpcContext","provide","connections","add","type","sendEvent","event","payload","Event","message","buffer","messageType","slice","Uint8Array","BYTES_PER_ELEMENT","error","logError","drain","resolve","close","remove","Error","ac","values","abort","clear","stream","destroy","subscription","handleContainerDisposal","start","Promise","reject","hostname","listen","port","socket","logger","info","stop","api","cause","dispose","handleRPC","call","transport","addStream","blob","downstream","pause","on","console","dir","once","err","log","errored","DownStreamAbort","chunk","DownStreamPush","set","metadata","getStream","signal","upstream","read","size","UpStreamPull","UpStreamAbort","UpStreamEnd","Rpc","connection","AbortController","rpc","decoder","decodeRpc","bind","callId","Call","procedure","find","response","RpcSubscription","key","ServerSubscriptionEvent","ServerUnsubscribe","debug","delete","UpStreamPush","push","Uint32Array","DownStreamPull","promise","readableEnded","DownStreamEnd","resume","ClientUnsubscribe","RpcAbort"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAa;AACxC,SAEEC,QAAQ,EAIRC,KAAK,EACLC,gBAAgB,EAChBC,cAAc,EAEdC,oBAAoB,EACpBC,OAAO,QACF,qBAAoB;AAC3B,SAGEC,WAAW,EACXC,aAAa,EACbC,YAAY,EACZC,YAAY,QACP,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAA2B,iBAAgB;AAC/D,SAASC,cAAc,QAAQ,iBAAgB;AAM/C,SACEC,aAAa,EACbC,SAAS,EACTC,cAAc,EACdC,IAAI,EACJC,WAAW,EACXC,cAAc,QACT,aAAY;AAEnB,OAAO,MAAMC;;;IACDC,OAAqB;IACZC,cAAgC;IAEnDC,YACE,AAAmBC,WAA+B,EAClD,AAAmBC,OAA2B,CAC9C;aAFmBD,cAAAA;aACAC,UAAAA;aAJFH,gBAAgBd,cAAckB,EAAE;QAMjD,IAAI,CAACL,MAAM,GAAG,IAAI,CAACI,OAAO,CAACE,GAAG,GAAGf,OAAOa,QAAQE,GAAG,IAAKhB;QAExD,IAAI,CAACU,MAAM,CACRO,GAAG,CAAC,YAAY,CAACC;YAEhBA,IAAIC,WAAW,CAAC,+BAA+B;YAC/CD,IAAIC,WAAW,CAAC,g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AK/C,KAAKQ,gBAAgB,CAAChC,GAAG,CAAC8H;QACrC,IAAIvD,IAAIA,GAAGE,KAAK,CAAC,IAAIH,MAAM;IAC7B;AACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Hook, createPlugin } from '@nmtjs/application';
|
|
2
|
+
import { WsTransportServer } from "./server.js";
|
|
3
|
+
export const WsTransport = createPlugin('WsTransport', (app, options)=>{
|
|
4
|
+
const server = new WsTransportServer(app, options);
|
|
5
|
+
app.hooks.add(Hook.OnStartup, async ()=>{
|
|
6
|
+
await server.start();
|
|
7
|
+
});
|
|
8
|
+
app.hooks.add(Hook.OnShutdown, async ()=>{
|
|
9
|
+
await server.stop();
|
|
10
|
+
});
|
|
11
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import { Hook, createPlugin } from '@nmtjs/application'\nimport { WsTransportServer } from './server.ts'\nimport type { WsTransportOptions } from './types.ts'\n\nexport const WsTransport = createPlugin<WsTransportOptions>(\n 'WsTransport',\n (app, options) => {\n const server = new WsTransportServer(app, options)\n app.hooks.add(Hook.OnStartup, async () => {\n await server.start()\n })\n app.hooks.add(Hook.OnShutdown, async () => {\n await server.stop()\n })\n },\n)\n"],"names":["Hook","createPlugin","WsTransportServer","WsTransport","app","options","server","hooks","add","OnStartup","start","OnShutdown","stop"],"mappings":"AAAA,SAASA,IAAI,EAAEC,YAAY,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,cAAa;AAG/C,OAAO,MAAMC,cAAcF,aACzB,eACA,CAACG,KAAKC;IACJ,MAAMC,SAAS,IAAIJ,kBAAkBE,KAAKC;IAC1CD,IAAIG,KAAK,CAACC,GAAG,CAACR,KAAKS,SAAS,EAAE;QAC5B,MAAMH,OAAOI,KAAK;IACpB;IACAN,IAAIG,KAAK,CAACC,GAAG,CAACR,KAAKW,UAAU,EAAE;QAC7B,MAAML,OAAOM,IAAI;IACnB;AACF,GACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type {\n Callback,\n Connection,\n Container,\n ServerDownStream,\n ServerUpStream,\n Subscription,\n} from '@nmtjs/application'\nimport type {\n BaseServerDecoder,\n BaseServerEncoder,\n BaseServerFormat,\n DecodeRpcContext,\n EncodeRpcContext,\n} from '@nmtjs/common'\nimport type { AppOptions, WebSocket } from 'uWebSockets.js'\n\nexport type WsUserData = {\n id: Connection['id']\n services: string[]\n backpressure: null | {\n promise: Promise<void>\n resolve: Callback\n }\n abortControllers: Map<number, AbortController>\n streams: {\n /**\n * Client to server streams\n */\n up: Map<number, ServerUpStream>\n /**\n * Server to client streams\n */\n down: Map<number, ServerDownStream>\n streamId: number\n }\n subscriptions: Map<string, Subscription>\n container: Container\n data: WsConnectionData\n format: {\n encoder: BaseServerEncoder\n decoder: BaseServerDecoder\n }\n context: {\n decode: Omit<DecodeRpcContext, 'addStream'> & {\n addStream: (\n signal: AbortSignal,\n ...args: Parameters<DecodeRpcContext['addStream']>\n ) => any\n }\n encode: EncodeRpcContext\n }\n}\n\nexport type WsTransportSocket = WebSocket<WsUserData>\n\nexport type WsTransportOptions = {\n port?: number\n hostname?: string\n unix?: string\n tls?: AppOptions\n maxPayloadLength?: number\n maxStreamChunkLength?: number\n // cors?: ServerOptions['cors']\n}\n\nexport type WsConnectionData = {\n headers: Map<string, string>\n query: URLSearchParams\n remoteAddress: string\n proxiedRemoteAddress: string\n}\n"],"names":[],"mappings":"AAkEA,WAKC"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ApiError } from '@nmtjs/application';
|
|
2
|
+
import { ErrorCode, concat, encodeNumber } from '@nmtjs/common';
|
|
3
|
+
export const sendMessage = (ws, type, payload)=>{
|
|
4
|
+
return send(ws, type, ws.getUserData().format.encoder.encode(payload));
|
|
5
|
+
};
|
|
6
|
+
export const sendRpcMessage = (ws, type, rpc)=>{
|
|
7
|
+
const data = ws.getUserData();
|
|
8
|
+
return send(ws, type, data.format.encoder.encodeRpc(rpc, data.context.encode));
|
|
9
|
+
};
|
|
10
|
+
export const send = (ws, type, ...buffers)=>{
|
|
11
|
+
const data = ws.getUserData();
|
|
12
|
+
try {
|
|
13
|
+
const result = ws.send(concat(encodeNumber(type, 'Uint8'), ...buffers), true);
|
|
14
|
+
if (result === 0) {
|
|
15
|
+
data.backpressure = Promise.withResolvers();
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
if (result === 2) {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
return true;
|
|
22
|
+
} catch (error) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
export const getFormat = ({ headers, query }, format)=>{
|
|
27
|
+
const contentType = headers.get('content-type') || query.get('content-type');
|
|
28
|
+
const acceptType = headers.get('accept') || query.get('accept');
|
|
29
|
+
const encoder = contentType ? format.supportsEncoder(contentType) : undefined;
|
|
30
|
+
if (!encoder) throw new Error('Unsupported content-type');
|
|
31
|
+
const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined;
|
|
32
|
+
if (!decoder) throw new Error('Unsupported accept');
|
|
33
|
+
return {
|
|
34
|
+
encoder,
|
|
35
|
+
decoder
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
export const toRecord = (input)=>{
|
|
39
|
+
const obj = {};
|
|
40
|
+
input.forEach((value, key)=>{
|
|
41
|
+
obj[key] = value;
|
|
42
|
+
});
|
|
43
|
+
return obj;
|
|
44
|
+
};
|
|
45
|
+
export const getRequestData = (req)=>{
|
|
46
|
+
const url = req.getUrl();
|
|
47
|
+
const method = req.getMethod();
|
|
48
|
+
const headers = new Map();
|
|
49
|
+
req.forEach((key, value)=>headers.set(key, value));
|
|
50
|
+
const query = new URLSearchParams(req.getQuery());
|
|
51
|
+
const origin = headers.has('origin') ? new URL(url, headers.get('origin')) : null;
|
|
52
|
+
return {
|
|
53
|
+
url,
|
|
54
|
+
origin,
|
|
55
|
+
method,
|
|
56
|
+
headers,
|
|
57
|
+
query
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export const InternalError = (message = 'Internal Server Error')=>new ApiError(ErrorCode.InternalServerError, message);
|
|
61
|
+
export const NotFoundError = (message = 'Not Found')=>new ApiError(ErrorCode.NotFound, message);
|
|
62
|
+
export const ForbiddenError = (message = 'Forbidden')=>new ApiError(ErrorCode.Forbidden, message);
|
|
63
|
+
export const RequestTimeoutError = (message = 'Request Timeout')=>new ApiError(ErrorCode.RequestTimeout, message);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lib/utils.ts"],"sourcesContent":["import { ApiError, type Format } from '@nmtjs/application'\nimport {\n ErrorCode,\n type RpcResponse,\n concat,\n encodeNumber,\n} from '@nmtjs/common'\nimport type { HttpRequest } from 'uWebSockets.js'\nimport type { WsTransportSocket } from './types.ts'\n\nexport const sendMessage = (\n ws: WsTransportSocket,\n type: number,\n payload: any,\n) => {\n return send(ws, type, ws.getUserData().format.encoder.encode(payload))\n}\n\nexport const sendRpcMessage = (\n ws: WsTransportSocket,\n type: number,\n rpc: RpcResponse,\n) => {\n const data = ws.getUserData()\n return send(ws, type, data.format.encoder.encodeRpc(rpc, data.context.encode))\n}\n\nexport const send = (\n ws: WsTransportSocket,\n type: number,\n ...buffers: ArrayBuffer[]\n): boolean | null => {\n const data = ws.getUserData()\n try {\n const result = ws.send(\n concat(encodeNumber(type, 'Uint8'), ...buffers),\n true,\n )\n if (result === 0) {\n data.backpressure = Promise.withResolvers()\n return false\n }\n if (result === 2) {\n return null\n }\n return true\n } catch (error) {\n return null\n }\n}\n\nexport const getFormat = ({ headers, query }: RequestData, format: Format) => {\n const contentType = headers.get('content-type') || query.get('content-type')\n const acceptType = headers.get('accept') || query.get('accept')\n\n const encoder = contentType ? format.supportsEncoder(contentType) : undefined\n if (!encoder) throw new Error('Unsupported content-type')\n\n const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined\n if (!decoder) throw new Error('Unsupported accept')\n\n return {\n encoder,\n decoder,\n }\n}\n\nexport const toRecord = (input: {\n forEach: (cb: (value, key) => void) => void\n}) => {\n const obj: Record<string, string> = {}\n input.forEach((value, key) => {\n obj[key] = value\n })\n return obj\n}\n\ntype RequestData = {\n url: string\n origin: URL | null\n method: string\n headers: Map<string, string>\n query: URLSearchParams\n}\n\nexport const getRequestData = (req: HttpRequest): RequestData => {\n const url = req.getUrl()\n const method = req.getMethod()\n const headers = new Map()\n req.forEach((key, value) => headers.set(key, value))\n const query = new URLSearchParams(req.getQuery())\n const origin = headers.has('origin')\n ? new URL(url, headers.get('origin'))\n : null\n\n return {\n url,\n origin,\n method,\n headers,\n query,\n }\n}\n\nexport const InternalError = (message = 'Internal Server Error') =>\n new ApiError(ErrorCode.InternalServerError, message)\n\nexport const NotFoundError = (message = 'Not Found') =>\n new ApiError(ErrorCode.NotFound, message)\n\nexport const ForbiddenError = (message = 'Forbidden') =>\n new ApiError(ErrorCode.Forbidden, message)\n\nexport const RequestTimeoutError = (message = 'Request Timeout') =>\n new ApiError(ErrorCode.RequestTimeout, message)\n"],"names":["ApiError","ErrorCode","concat","encodeNumber","sendMessage","ws","type","payload","send","getUserData","format","encoder","encode","sendRpcMessage","rpc","data","encodeRpc","context","buffers","result","backpressure","Promise","withResolvers","error","getFormat","headers","query","contentType","get","acceptType","supportsEncoder","undefined","Error","decoder","supportsDecoder","toRecord","input","obj","forEach","value","key","getRequestData","req","url","getUrl","method","getMethod","Map","set","URLSearchParams","getQuery","origin","has","URL","InternalError","message","InternalServerError","NotFoundError","NotFound","ForbiddenError","Forbidden","RequestTimeoutError","RequestTimeout"],"mappings":"AAAA,SAASA,QAAQ,QAAqB,qBAAoB;AAC1D,SACEC,SAAS,EAETC,MAAM,EACNC,YAAY,QACP,gBAAe;AAItB,OAAO,MAAMC,cAAc,CACzBC,IACAC,MACAC;IAEA,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IAAI,GAAGD;IACb;IACA,OAAOF;AACT,EAAC;AAUD,OAAO,MAAMI,iBAAiB,CAACC;IAC7B,MAAMC,MAAMD,IAAIE,MAAM;IACtB,MAAMC,SAASH,IAAII,SAAS;IAC5B,MAAMrB,UAAU,IAAIsB;IACpBL,IAAIJ,OAAO,CAAC,CAACE,KAAKD,QAAUd,QAAQuB,GAAG,CAACR,KAAKD;IAC7C,MAAMb,QAAQ,IAAIuB,gBAAgBP,IAAIQ,QAAQ;IAC9C,MAAMC,SAAS1B,QAAQ2B,GAAG,CAAC,YACvB,IAAIC,IAAIV,KAAKlB,QAAQG,GAAG,CAAC,aACzB;IAEJ,OAAO;QACLe;QACAQ;QACAN;QACApB;QACAC;IACF;AACF,EAAC;AAED,OAAO,MAAM4B,gBAAgB,CAACC,UAAU,uBAAuB,GAC7D,IAAIvD,SAASC,UAAUuD,mBAAmB,EAAED,SAAQ;AAEtD,OAAO,MAAME,gBAAgB,CAACF,UAAU,WAAW,GACjD,IAAIvD,SAASC,UAAUyD,QAAQ,EAAEH,SAAQ;AAE3C,OAAO,MAAMI,iBAAiB,CAACJ,UAAU,WAAW,GAClD,IAAIvD,SAASC,UAAU2D,SAAS,EAAEL,SAAQ;AAE5C,OAAO,MAAMM,sBAAsB,CAACN,UAAU,iBAAiB,GAC7D,IAAIvD,SAASC,UAAU6D,cAAc,EAAEP,SAAQ"}
|
package/index.ts
ADDED
package/lib/providers.ts
ADDED
package/lib/server.ts
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
type AnyProcedure,
|
|
4
|
+
ApiError,
|
|
5
|
+
type ApplicationContext,
|
|
6
|
+
type Connection,
|
|
7
|
+
type Container,
|
|
8
|
+
Scope,
|
|
9
|
+
ServerDownStream,
|
|
10
|
+
ServerUpStream,
|
|
11
|
+
type Service,
|
|
12
|
+
SubscriptionResponse,
|
|
13
|
+
onAbort,
|
|
14
|
+
} from '@nmtjs/application'
|
|
15
|
+
import {
|
|
16
|
+
type ApiBlobMetadata,
|
|
17
|
+
type EncodeRpcContext,
|
|
18
|
+
MessageType,
|
|
19
|
+
TransportType,
|
|
20
|
+
decodeNumber,
|
|
21
|
+
encodeNumber,
|
|
22
|
+
} from '@nmtjs/common'
|
|
23
|
+
import { App, SSLApp, type TemplatedApp } from 'uWebSockets.js'
|
|
24
|
+
import { connectionData } from './providers.ts'
|
|
25
|
+
import type {
|
|
26
|
+
WsTransportOptions,
|
|
27
|
+
WsTransportSocket,
|
|
28
|
+
WsUserData,
|
|
29
|
+
} from './types.ts'
|
|
30
|
+
import {
|
|
31
|
+
InternalError,
|
|
32
|
+
getFormat,
|
|
33
|
+
getRequestData,
|
|
34
|
+
send,
|
|
35
|
+
sendMessage,
|
|
36
|
+
sendRpcMessage,
|
|
37
|
+
} from './utils.ts'
|
|
38
|
+
|
|
39
|
+
export class WsTransportServer {
|
|
40
|
+
protected server!: TemplatedApp
|
|
41
|
+
protected readonly transportType = TransportType.WS
|
|
42
|
+
|
|
43
|
+
constructor(
|
|
44
|
+
protected readonly application: ApplicationContext,
|
|
45
|
+
protected readonly options: WsTransportOptions,
|
|
46
|
+
) {
|
|
47
|
+
this.server = this.options.tls ? SSLApp(options.tls!) : App()
|
|
48
|
+
|
|
49
|
+
this.server
|
|
50
|
+
.get('/healthy', (res) => {
|
|
51
|
+
// cors
|
|
52
|
+
res.writeHeader('Access-Control-Allow-Origin', '*')
|
|
53
|
+
res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')
|
|
54
|
+
res.writeHeader('Access-Control-Allow-Methods', 'GET')
|
|
55
|
+
res.writeHeader('Content-Type', 'text/plain')
|
|
56
|
+
res.end('OK')
|
|
57
|
+
})
|
|
58
|
+
.ws<WsUserData>('/api', {
|
|
59
|
+
sendPingsAutomatically: true,
|
|
60
|
+
maxPayloadLength: this.options.maxPayloadLength,
|
|
61
|
+
upgrade: (res, req, context) => {
|
|
62
|
+
const requestData = getRequestData(req)
|
|
63
|
+
const container = this.application.container.createScope(
|
|
64
|
+
Scope.Connection,
|
|
65
|
+
)
|
|
66
|
+
const services = requestData.query.getAll('services')
|
|
67
|
+
|
|
68
|
+
for (const serviceName of services) {
|
|
69
|
+
const service = this.application.registry.services.get(serviceName)
|
|
70
|
+
if (!service)
|
|
71
|
+
throw new Response(`Service ${service} not found`, {
|
|
72
|
+
status: 400,
|
|
73
|
+
})
|
|
74
|
+
if (this.transportType in service.contract.transports === false)
|
|
75
|
+
throw new Response(`Service ${service} not supported`, {
|
|
76
|
+
status: 400,
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const data: WsUserData = {
|
|
81
|
+
id: randomUUID(),
|
|
82
|
+
format: getFormat(requestData, this.application.format),
|
|
83
|
+
container,
|
|
84
|
+
streams: {
|
|
85
|
+
up: new Map(),
|
|
86
|
+
down: new Map(),
|
|
87
|
+
streamId: 0,
|
|
88
|
+
},
|
|
89
|
+
abortControllers: new Map(),
|
|
90
|
+
subscriptions: new Map(),
|
|
91
|
+
services,
|
|
92
|
+
data: {
|
|
93
|
+
query: requestData.query,
|
|
94
|
+
headers: requestData.headers,
|
|
95
|
+
proxiedRemoteAddress: Buffer.from(
|
|
96
|
+
res.getProxiedRemoteAddressAsText(),
|
|
97
|
+
).toString(),
|
|
98
|
+
remoteAddress: Buffer.from(
|
|
99
|
+
res.getRemoteAddressAsText(),
|
|
100
|
+
).toString(),
|
|
101
|
+
},
|
|
102
|
+
backpressure: null,
|
|
103
|
+
context: {} as any,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
res.upgrade(
|
|
107
|
+
data,
|
|
108
|
+
req.getHeader('sec-websocket-key'),
|
|
109
|
+
req.getHeader('sec-websocket-protocol'),
|
|
110
|
+
req.getHeader('sec-websocket-extensions'),
|
|
111
|
+
context,
|
|
112
|
+
)
|
|
113
|
+
},
|
|
114
|
+
open: (ws: WsTransportSocket) => {
|
|
115
|
+
const data = ws.getUserData()
|
|
116
|
+
data.context.decode = this.createDecodeRpcContext(ws)
|
|
117
|
+
data.context.encode = this.createEncodeRpcContext(ws)
|
|
118
|
+
data.container.provide(connectionData, data.data)
|
|
119
|
+
this.application.connections.add({
|
|
120
|
+
id: data.id,
|
|
121
|
+
services: data.services,
|
|
122
|
+
type: this.transportType,
|
|
123
|
+
subscriptions: data.subscriptions,
|
|
124
|
+
sendEvent: (service, event, payload) =>
|
|
125
|
+
sendMessage(ws, MessageType.Event, [service, event, payload]),
|
|
126
|
+
})
|
|
127
|
+
},
|
|
128
|
+
message: async (ws: WsTransportSocket, event) => {
|
|
129
|
+
const buffer = event as unknown as ArrayBuffer
|
|
130
|
+
const messageType = decodeNumber(buffer, 'Uint8')
|
|
131
|
+
if (messageType in this === false) {
|
|
132
|
+
ws.end(1011, 'Unknown message type')
|
|
133
|
+
} else {
|
|
134
|
+
try {
|
|
135
|
+
await this[messageType](
|
|
136
|
+
ws,
|
|
137
|
+
buffer.slice(Uint8Array.BYTES_PER_ELEMENT),
|
|
138
|
+
)
|
|
139
|
+
} catch (error: any) {
|
|
140
|
+
this.logError(error, 'Error while processing message')
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
drain: (ws: WsTransportSocket) => {
|
|
145
|
+
const data = ws.getUserData()
|
|
146
|
+
data.backpressure?.resolve()
|
|
147
|
+
data.backpressure = null
|
|
148
|
+
},
|
|
149
|
+
close: (ws: WsTransportSocket) => {
|
|
150
|
+
const data = ws.getUserData()
|
|
151
|
+
|
|
152
|
+
this.application.connections.remove(data.id)
|
|
153
|
+
const error = new Error('Connection closed')
|
|
154
|
+
|
|
155
|
+
for (const ac of data.abortControllers.values()) {
|
|
156
|
+
ac.abort(error)
|
|
157
|
+
}
|
|
158
|
+
data.abortControllers.clear()
|
|
159
|
+
|
|
160
|
+
for (const stream of data.streams.down.values()) {
|
|
161
|
+
stream.destroy(error)
|
|
162
|
+
}
|
|
163
|
+
data.streams.down.clear()
|
|
164
|
+
|
|
165
|
+
for (const stream of data.streams.up.values()) {
|
|
166
|
+
stream.destroy(error)
|
|
167
|
+
}
|
|
168
|
+
data.streams.up.clear()
|
|
169
|
+
|
|
170
|
+
for (const subscription of data.subscriptions.values()) {
|
|
171
|
+
subscription.destroy()
|
|
172
|
+
}
|
|
173
|
+
data.subscriptions.clear()
|
|
174
|
+
|
|
175
|
+
this.handleContainerDisposal(data.container)
|
|
176
|
+
},
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async start() {
|
|
181
|
+
return new Promise<void>((resolve, reject) => {
|
|
182
|
+
const hostname = this.options.hostname ?? '127.0.0.1'
|
|
183
|
+
this.server.listen(hostname, this.options.port!, (socket) => {
|
|
184
|
+
if (socket) {
|
|
185
|
+
this.logger.info(
|
|
186
|
+
'Server started on %s:%s',
|
|
187
|
+
hostname,
|
|
188
|
+
this.options.port!,
|
|
189
|
+
)
|
|
190
|
+
resolve()
|
|
191
|
+
} else {
|
|
192
|
+
reject(new Error('Failed to start server'))
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
})
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async stop() {
|
|
199
|
+
this.server.close()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
protected get api() {
|
|
203
|
+
return this.application.api
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
protected get logger() {
|
|
207
|
+
return this.application.logger
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
protected async logError(
|
|
211
|
+
cause: Error,
|
|
212
|
+
message = 'Unknown error while processing request',
|
|
213
|
+
) {
|
|
214
|
+
this.logger.error(new Error(message, { cause }))
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
protected handleContainerDisposal(container: Container) {
|
|
218
|
+
container.dispose()
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
protected async handleRPC(options: {
|
|
222
|
+
connection: Connection
|
|
223
|
+
service: Service
|
|
224
|
+
procedure: AnyProcedure
|
|
225
|
+
container: Container
|
|
226
|
+
signal: AbortSignal
|
|
227
|
+
payload: any
|
|
228
|
+
}) {
|
|
229
|
+
return await this.api.call({
|
|
230
|
+
...options,
|
|
231
|
+
transport: this.transportType,
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
protected createEncodeRpcContext(ws: WsTransportSocket): EncodeRpcContext {
|
|
236
|
+
const data = ws.getUserData()
|
|
237
|
+
return {
|
|
238
|
+
addStream: (blob) => {
|
|
239
|
+
const id = ++data.streams.streamId
|
|
240
|
+
const downstream = new ServerDownStream(id, blob)
|
|
241
|
+
downstream.pause()
|
|
242
|
+
downstream.on('error', console.dir)
|
|
243
|
+
downstream.once('error', (err) => {
|
|
244
|
+
console.log({ err })
|
|
245
|
+
if (downstream.errored?.message !== 'Aborted by client')
|
|
246
|
+
send(ws, MessageType.DownStreamAbort, encodeNumber(id, 'Uint32'))
|
|
247
|
+
})
|
|
248
|
+
downstream.on('data', (chunk) => {
|
|
249
|
+
downstream.pause()
|
|
250
|
+
send(
|
|
251
|
+
ws,
|
|
252
|
+
MessageType.DownStreamPush,
|
|
253
|
+
encodeNumber(id, 'Uint32'),
|
|
254
|
+
Buffer.from(chunk).buffer as ArrayBuffer,
|
|
255
|
+
)
|
|
256
|
+
})
|
|
257
|
+
data.streams.down.set(id, downstream)
|
|
258
|
+
return { id, metadata: blob.metadata }
|
|
259
|
+
},
|
|
260
|
+
getStream: (id) => {
|
|
261
|
+
return data.streams.down.get(id)!
|
|
262
|
+
},
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
protected createDecodeRpcContext(ws: WsTransportSocket) {
|
|
267
|
+
const data = ws.getUserData()
|
|
268
|
+
return {
|
|
269
|
+
addStream(signal: AbortSignal, id: number, metadata: ApiBlobMetadata) {
|
|
270
|
+
const upstream = new ServerUpStream(metadata, {
|
|
271
|
+
read: (size) => {
|
|
272
|
+
send(
|
|
273
|
+
ws,
|
|
274
|
+
MessageType.UpStreamPull,
|
|
275
|
+
encodeNumber(id, 'Uint32'),
|
|
276
|
+
encodeNumber(size, 'Uint32'),
|
|
277
|
+
)
|
|
278
|
+
},
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
data.streams.up.set(id, upstream)
|
|
282
|
+
onAbort(signal, () => {
|
|
283
|
+
upstream.destroy(new Error('Call aborted by client'))
|
|
284
|
+
})
|
|
285
|
+
upstream.once('error', (error) => {
|
|
286
|
+
if (error.message !== 'Aborted by server')
|
|
287
|
+
send(ws, MessageType.UpStreamAbort, encodeNumber(id, 'Uint32'))
|
|
288
|
+
})
|
|
289
|
+
upstream.once('close', () => {
|
|
290
|
+
if (upstream.errored?.message !== 'Aborted by server')
|
|
291
|
+
send(ws, MessageType.UpStreamEnd, encodeNumber(id, 'Uint32'))
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
return upstream
|
|
295
|
+
},
|
|
296
|
+
getStream(id) {
|
|
297
|
+
return data.streams.down.get(id)
|
|
298
|
+
},
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
protected async [MessageType.Rpc](
|
|
303
|
+
ws: WsTransportSocket,
|
|
304
|
+
buffer: ArrayBuffer,
|
|
305
|
+
) {
|
|
306
|
+
const data = ws.getUserData()
|
|
307
|
+
|
|
308
|
+
const connection = this.application.connections.get(data.id)
|
|
309
|
+
if (!connection) return void ws.end(1011, 'Unknown connection')
|
|
310
|
+
|
|
311
|
+
const ac = new AbortController()
|
|
312
|
+
const rpc = data.format.decoder.decodeRpc(buffer, {
|
|
313
|
+
...data.context.decode,
|
|
314
|
+
addStream: data.context.decode.addStream.bind(null, ac.signal),
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
data.abortControllers.set(rpc.callId, ac)
|
|
318
|
+
|
|
319
|
+
const container = data.container.createScope(Scope.Call)
|
|
320
|
+
|
|
321
|
+
try {
|
|
322
|
+
const { service, procedure } = this.api.find(
|
|
323
|
+
rpc.service,
|
|
324
|
+
rpc.procedure,
|
|
325
|
+
this.transportType,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
const response = await this.handleRPC({
|
|
329
|
+
connection,
|
|
330
|
+
service,
|
|
331
|
+
procedure,
|
|
332
|
+
container,
|
|
333
|
+
signal: ac.signal,
|
|
334
|
+
payload: rpc.payload,
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
if (response instanceof SubscriptionResponse) {
|
|
338
|
+
sendRpcMessage(ws, MessageType.RpcSubscription, {
|
|
339
|
+
callId: rpc.callId,
|
|
340
|
+
error: null,
|
|
341
|
+
payload: [response.subscription.key, response.payload],
|
|
342
|
+
})
|
|
343
|
+
|
|
344
|
+
response.subscription.on('event', (event, payload) => {
|
|
345
|
+
sendMessage(ws, MessageType.ServerSubscriptionEvent, [
|
|
346
|
+
response.subscription.key,
|
|
347
|
+
event,
|
|
348
|
+
payload,
|
|
349
|
+
])
|
|
350
|
+
})
|
|
351
|
+
response.subscription.once('end', () => {
|
|
352
|
+
sendMessage(ws, MessageType.ServerUnsubscribe, [
|
|
353
|
+
response.subscription.key,
|
|
354
|
+
])
|
|
355
|
+
})
|
|
356
|
+
} else {
|
|
357
|
+
sendRpcMessage(ws, MessageType.Rpc, {
|
|
358
|
+
callId: rpc.callId,
|
|
359
|
+
error: null,
|
|
360
|
+
payload: response,
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (error instanceof ApiError) {
|
|
365
|
+
this.logger.debug(new Error('Api error', { cause: error }))
|
|
366
|
+
sendRpcMessage(ws, MessageType.Rpc, {
|
|
367
|
+
callId: rpc.callId,
|
|
368
|
+
error,
|
|
369
|
+
payload: null,
|
|
370
|
+
})
|
|
371
|
+
} else {
|
|
372
|
+
this.logger.error(new Error('Unexpected error', { cause: error }))
|
|
373
|
+
sendRpcMessage(ws, MessageType.Rpc, {
|
|
374
|
+
callId: rpc.callId,
|
|
375
|
+
error: InternalError(),
|
|
376
|
+
payload: null,
|
|
377
|
+
})
|
|
378
|
+
}
|
|
379
|
+
} finally {
|
|
380
|
+
data.abortControllers.delete(rpc.callId)
|
|
381
|
+
this.handleContainerDisposal(container)
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async [MessageType.UpStreamPush](ws: WsTransportSocket, buffer: ArrayBuffer) {
|
|
386
|
+
const data = ws.getUserData()
|
|
387
|
+
const id = decodeNumber(buffer, 'Uint32')
|
|
388
|
+
const stream = data.streams.up.get(id)
|
|
389
|
+
if (!stream) return ws.end(1011, 'Unknown stream')
|
|
390
|
+
stream.push(Buffer.from(buffer.slice(Uint32Array.BYTES_PER_ELEMENT)))
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async [MessageType.UpStreamEnd](ws: WsTransportSocket, buffer: ArrayBuffer) {
|
|
394
|
+
const data = ws.getUserData()
|
|
395
|
+
const id = decodeNumber(buffer, 'Uint32')
|
|
396
|
+
const stream = data.streams.up.get(id)
|
|
397
|
+
if (!stream) return ws.end(1011, 'Unknown stream')
|
|
398
|
+
stream.push(null)
|
|
399
|
+
data.streams.up.delete(id)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async [MessageType.UpStreamAbort](
|
|
403
|
+
ws: WsTransportSocket,
|
|
404
|
+
buffer: ArrayBuffer,
|
|
405
|
+
) {
|
|
406
|
+
const data = ws.getUserData()
|
|
407
|
+
const id = decodeNumber(buffer, 'Uint32')
|
|
408
|
+
const stream = data.streams.up.get(id)
|
|
409
|
+
if (!stream) return ws.end(1011, 'Unknown stream')
|
|
410
|
+
stream.destroy(new Error('Aborted by client'))
|
|
411
|
+
data.streams.up.delete(id)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async [MessageType.DownStreamPull](
|
|
415
|
+
ws: WsTransportSocket,
|
|
416
|
+
buffer: ArrayBuffer,
|
|
417
|
+
) {
|
|
418
|
+
const data = ws.getUserData()
|
|
419
|
+
const id = decodeNumber(buffer, 'Uint32')
|
|
420
|
+
const stream = data.streams.down.get(id)
|
|
421
|
+
if (!stream) return ws.end(1011, 'Unknown stream')
|
|
422
|
+
await data.backpressure?.promise
|
|
423
|
+
if (stream.readableEnded)
|
|
424
|
+
send(ws, MessageType.DownStreamEnd, encodeNumber(id, 'Uint32'))
|
|
425
|
+
else stream.resume()
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async [MessageType.DownStreamEnd](
|
|
429
|
+
ws: WsTransportSocket,
|
|
430
|
+
buffer: ArrayBuffer,
|
|
431
|
+
) {
|
|
432
|
+
const data = ws.getUserData()
|
|
433
|
+
const id = decodeNumber(buffer, 'Uint32')
|
|
434
|
+
const stream = data.streams.down.get(id)
|
|
435
|
+
if (!stream) return ws.end(1011, 'Unknown stream')
|
|
436
|
+
data.streams.down.delete(id)
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async [MessageType.DownStreamAbort](
|
|
440
|
+
ws: WsTransportSocket,
|
|
441
|
+
buffer: ArrayBuffer,
|
|
442
|
+
) {
|
|
443
|
+
const data = ws.getUserData()
|
|
444
|
+
const id = decodeNumber(buffer, 'Uint32')
|
|
445
|
+
const stream = data.streams.down.get(id)
|
|
446
|
+
if (!stream) return ws.end(1011, 'Unknown stream')
|
|
447
|
+
stream.destroy(new Error('Aborted by client'))
|
|
448
|
+
data.streams.down.delete(id)
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async [MessageType.ClientUnsubscribe](
|
|
452
|
+
ws: WsTransportSocket,
|
|
453
|
+
buffer: ArrayBuffer,
|
|
454
|
+
) {
|
|
455
|
+
const data = ws.getUserData()
|
|
456
|
+
const [key] = data.format.decoder.decode(buffer)
|
|
457
|
+
const subscription = data.subscriptions.get(key)
|
|
458
|
+
if (!subscription) return void ws.end()
|
|
459
|
+
subscription.destroy()
|
|
460
|
+
data.subscriptions.delete(key)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async [MessageType.RpcAbort](ws: WsTransportSocket, buffer: ArrayBuffer) {
|
|
464
|
+
const data = ws.getUserData()
|
|
465
|
+
const callId = decodeNumber(buffer, 'Uint32')
|
|
466
|
+
const ac = data.abortControllers.get(callId)
|
|
467
|
+
if (ac) ac.abort(new Error('Aborted by client'))
|
|
468
|
+
}
|
|
469
|
+
}
|
package/lib/transport.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Hook, createPlugin } from '@nmtjs/application'
|
|
2
|
+
import { WsTransportServer } from './server.ts'
|
|
3
|
+
import type { WsTransportOptions } from './types.ts'
|
|
4
|
+
|
|
5
|
+
export const WsTransport = createPlugin<WsTransportOptions>(
|
|
6
|
+
'WsTransport',
|
|
7
|
+
(app, options) => {
|
|
8
|
+
const server = new WsTransportServer(app, options)
|
|
9
|
+
app.hooks.add(Hook.OnStartup, async () => {
|
|
10
|
+
await server.start()
|
|
11
|
+
})
|
|
12
|
+
app.hooks.add(Hook.OnShutdown, async () => {
|
|
13
|
+
await server.stop()
|
|
14
|
+
})
|
|
15
|
+
},
|
|
16
|
+
)
|
package/lib/types.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Callback,
|
|
3
|
+
Connection,
|
|
4
|
+
Container,
|
|
5
|
+
ServerDownStream,
|
|
6
|
+
ServerUpStream,
|
|
7
|
+
Subscription,
|
|
8
|
+
} from '@nmtjs/application'
|
|
9
|
+
import type {
|
|
10
|
+
BaseServerDecoder,
|
|
11
|
+
BaseServerEncoder,
|
|
12
|
+
BaseServerFormat,
|
|
13
|
+
DecodeRpcContext,
|
|
14
|
+
EncodeRpcContext,
|
|
15
|
+
} from '@nmtjs/common'
|
|
16
|
+
import type { AppOptions, WebSocket } from 'uWebSockets.js'
|
|
17
|
+
|
|
18
|
+
export type WsUserData = {
|
|
19
|
+
id: Connection['id']
|
|
20
|
+
services: string[]
|
|
21
|
+
backpressure: null | {
|
|
22
|
+
promise: Promise<void>
|
|
23
|
+
resolve: Callback
|
|
24
|
+
}
|
|
25
|
+
abortControllers: Map<number, AbortController>
|
|
26
|
+
streams: {
|
|
27
|
+
/**
|
|
28
|
+
* Client to server streams
|
|
29
|
+
*/
|
|
30
|
+
up: Map<number, ServerUpStream>
|
|
31
|
+
/**
|
|
32
|
+
* Server to client streams
|
|
33
|
+
*/
|
|
34
|
+
down: Map<number, ServerDownStream>
|
|
35
|
+
streamId: number
|
|
36
|
+
}
|
|
37
|
+
subscriptions: Map<string, Subscription>
|
|
38
|
+
container: Container
|
|
39
|
+
data: WsConnectionData
|
|
40
|
+
format: {
|
|
41
|
+
encoder: BaseServerEncoder
|
|
42
|
+
decoder: BaseServerDecoder
|
|
43
|
+
}
|
|
44
|
+
context: {
|
|
45
|
+
decode: Omit<DecodeRpcContext, 'addStream'> & {
|
|
46
|
+
addStream: (
|
|
47
|
+
signal: AbortSignal,
|
|
48
|
+
...args: Parameters<DecodeRpcContext['addStream']>
|
|
49
|
+
) => any
|
|
50
|
+
}
|
|
51
|
+
encode: EncodeRpcContext
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type WsTransportSocket = WebSocket<WsUserData>
|
|
56
|
+
|
|
57
|
+
export type WsTransportOptions = {
|
|
58
|
+
port?: number
|
|
59
|
+
hostname?: string
|
|
60
|
+
unix?: string
|
|
61
|
+
tls?: AppOptions
|
|
62
|
+
maxPayloadLength?: number
|
|
63
|
+
maxStreamChunkLength?: number
|
|
64
|
+
// cors?: ServerOptions['cors']
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type WsConnectionData = {
|
|
68
|
+
headers: Map<string, string>
|
|
69
|
+
query: URLSearchParams
|
|
70
|
+
remoteAddress: string
|
|
71
|
+
proxiedRemoteAddress: string
|
|
72
|
+
}
|
package/lib/utils.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { ApiError, type Format } from '@nmtjs/application'
|
|
2
|
+
import {
|
|
3
|
+
ErrorCode,
|
|
4
|
+
type RpcResponse,
|
|
5
|
+
concat,
|
|
6
|
+
encodeNumber,
|
|
7
|
+
} from '@nmtjs/common'
|
|
8
|
+
import type { HttpRequest } from 'uWebSockets.js'
|
|
9
|
+
import type { WsTransportSocket } from './types.ts'
|
|
10
|
+
|
|
11
|
+
export const sendMessage = (
|
|
12
|
+
ws: WsTransportSocket,
|
|
13
|
+
type: number,
|
|
14
|
+
payload: any,
|
|
15
|
+
) => {
|
|
16
|
+
return send(ws, type, ws.getUserData().format.encoder.encode(payload))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const sendRpcMessage = (
|
|
20
|
+
ws: WsTransportSocket,
|
|
21
|
+
type: number,
|
|
22
|
+
rpc: RpcResponse,
|
|
23
|
+
) => {
|
|
24
|
+
const data = ws.getUserData()
|
|
25
|
+
return send(ws, type, data.format.encoder.encodeRpc(rpc, data.context.encode))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const send = (
|
|
29
|
+
ws: WsTransportSocket,
|
|
30
|
+
type: number,
|
|
31
|
+
...buffers: ArrayBuffer[]
|
|
32
|
+
): boolean | null => {
|
|
33
|
+
const data = ws.getUserData()
|
|
34
|
+
try {
|
|
35
|
+
const result = ws.send(
|
|
36
|
+
concat(encodeNumber(type, 'Uint8'), ...buffers),
|
|
37
|
+
true,
|
|
38
|
+
)
|
|
39
|
+
if (result === 0) {
|
|
40
|
+
data.backpressure = Promise.withResolvers()
|
|
41
|
+
return false
|
|
42
|
+
}
|
|
43
|
+
if (result === 2) {
|
|
44
|
+
return null
|
|
45
|
+
}
|
|
46
|
+
return true
|
|
47
|
+
} catch (error) {
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const getFormat = ({ headers, query }: RequestData, format: Format) => {
|
|
53
|
+
const contentType = headers.get('content-type') || query.get('content-type')
|
|
54
|
+
const acceptType = headers.get('accept') || query.get('accept')
|
|
55
|
+
|
|
56
|
+
const encoder = contentType ? format.supportsEncoder(contentType) : undefined
|
|
57
|
+
if (!encoder) throw new Error('Unsupported content-type')
|
|
58
|
+
|
|
59
|
+
const decoder = acceptType ? format.supportsDecoder(acceptType) : undefined
|
|
60
|
+
if (!decoder) throw new Error('Unsupported accept')
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
encoder,
|
|
64
|
+
decoder,
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const toRecord = (input: {
|
|
69
|
+
forEach: (cb: (value, key) => void) => void
|
|
70
|
+
}) => {
|
|
71
|
+
const obj: Record<string, string> = {}
|
|
72
|
+
input.forEach((value, key) => {
|
|
73
|
+
obj[key] = value
|
|
74
|
+
})
|
|
75
|
+
return obj
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type RequestData = {
|
|
79
|
+
url: string
|
|
80
|
+
origin: URL | null
|
|
81
|
+
method: string
|
|
82
|
+
headers: Map<string, string>
|
|
83
|
+
query: URLSearchParams
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const getRequestData = (req: HttpRequest): RequestData => {
|
|
87
|
+
const url = req.getUrl()
|
|
88
|
+
const method = req.getMethod()
|
|
89
|
+
const headers = new Map()
|
|
90
|
+
req.forEach((key, value) => headers.set(key, value))
|
|
91
|
+
const query = new URLSearchParams(req.getQuery())
|
|
92
|
+
const origin = headers.has('origin')
|
|
93
|
+
? new URL(url, headers.get('origin'))
|
|
94
|
+
: null
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
url,
|
|
98
|
+
origin,
|
|
99
|
+
method,
|
|
100
|
+
headers,
|
|
101
|
+
query,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export const InternalError = (message = 'Internal Server Error') =>
|
|
106
|
+
new ApiError(ErrorCode.InternalServerError, message)
|
|
107
|
+
|
|
108
|
+
export const NotFoundError = (message = 'Not Found') =>
|
|
109
|
+
new ApiError(ErrorCode.NotFound, message)
|
|
110
|
+
|
|
111
|
+
export const ForbiddenError = (message = 'Forbidden') =>
|
|
112
|
+
new ApiError(ErrorCode.Forbidden, message)
|
|
113
|
+
|
|
114
|
+
export const RequestTimeoutError = (message = 'Request Timeout') =>
|
|
115
|
+
new ApiError(ErrorCode.RequestTimeout, message)
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nmtjs/ws-transport",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"exports": {
|
|
5
|
+
".": {
|
|
6
|
+
"default": "./dist/index.js",
|
|
7
|
+
"types": "./index.ts"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.47.0"
|
|
12
|
+
},
|
|
13
|
+
"peerDependencies": {
|
|
14
|
+
"@nmtjs/application": "^0.0.1",
|
|
15
|
+
"@nmtjs/common": "^0.0.1"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@nmtjs/application": "^0.0.1",
|
|
19
|
+
"@nmtjs/common": "^0.0.1"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18.9.0"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"index.ts",
|
|
26
|
+
"lib",
|
|
27
|
+
"dist",
|
|
28
|
+
"tsconfig.json",
|
|
29
|
+
"LICENSE.md",
|
|
30
|
+
"README.md"
|
|
31
|
+
],
|
|
32
|
+
"version": "0.0.1",
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "neemata-build ./index.ts './lib/**/*.ts'",
|
|
35
|
+
"type-check": "tsc --noEmit"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/tsconfig.json
ADDED