@nmtjs/ws-transport 0.1.7 → 0.2.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/dist/lib/injectables.js +5 -2
- package/dist/lib/injectables.js.map +1 -1
- package/dist/lib/server.js +84 -271
- package/dist/lib/server.js.map +1 -1
- package/dist/lib/transport.js +3 -9
- package/dist/lib/transport.js.map +1 -1
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/utils.js +10 -27
- package/dist/lib/utils.js.map +1 -1
- package/lib/injectables.ts +12 -10
- package/lib/server.ts +112 -329
- package/lib/transport.ts +8 -14
- package/lib/types.ts +12 -55
- package/lib/utils.ts +10 -49
- package/package.json +5 -8
package/dist/lib/injectables.js
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { ProtocolInjectables } from '@nmtjs/protocol/server';
|
|
2
|
+
const connectionData = ProtocolInjectables.connectionData;
|
|
3
|
+
export const WsTransportInjectables = {
|
|
4
|
+
connectionData
|
|
5
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../lib/injectables.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../lib/injectables.ts"],"sourcesContent":["import type { LazyInjectable, Scope } from '@nmtjs/core'\nimport { ProtocolInjectables } from '@nmtjs/protocol/server'\nimport type { WsUserData } from './types.ts'\n\nconst connectionData =\n ProtocolInjectables.connectionData as unknown as LazyInjectable<\n WsUserData['request'],\n Scope.Connection\n >\n\nexport const WsTransportInjectables = {\n connectionData,\n} as const\n"],"names":["ProtocolInjectables","connectionData","WsTransportInjectables"],"mappings":"AACA,SAASA,mBAAmB,QAAQ,yBAAwB;AAG5D,MAAMC,iBACJD,oBAAoBC,cAAc;AAKpC,OAAO,MAAMC,yBAAyB;IACpCD;AACF,EAAU"}
|
package/dist/lib/server.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { ApiError, Scope, ServerDownStream, ServerUpStream, SubscriptionResponse, builtin, onAbort } from '@nmtjs/application';
|
|
3
|
-
import { MessageType, TransportType, decodeNumber, encodeNumber } from '@nmtjs/common';
|
|
4
2
|
import { App, SSLApp } from 'uWebSockets.js';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
3
|
+
import { createPromise } from '@nmtjs/common';
|
|
4
|
+
import { ClientMessageType, decodeNumber } from '@nmtjs/protocol/common';
|
|
5
|
+
import { ProtocolInjectables } from '@nmtjs/protocol/server';
|
|
6
|
+
import { getRequestData, send } from "./utils.js";
|
|
7
7
|
export class WsTransportServer {
|
|
8
|
-
|
|
8
|
+
context;
|
|
9
9
|
options;
|
|
10
10
|
server;
|
|
11
|
-
|
|
12
|
-
constructor(
|
|
13
|
-
this.
|
|
11
|
+
clients;
|
|
12
|
+
constructor(context, options){
|
|
13
|
+
this.context = context;
|
|
14
14
|
this.options = options;
|
|
15
|
-
this.
|
|
15
|
+
this.clients = new Map();
|
|
16
16
|
this.server = this.options.tls ? SSLApp(options.tls) : App();
|
|
17
17
|
this.server.options('/*', (res, req)=>{
|
|
18
18
|
this.applyCors(res, req);
|
|
@@ -27,62 +27,51 @@ export class WsTransportServer {
|
|
|
27
27
|
maxPayloadLength: this.options.maxPayloadLength,
|
|
28
28
|
upgrade: (res, req, context)=>{
|
|
29
29
|
const requestData = getRequestData(req);
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
for (const serviceName of services){
|
|
33
|
-
const service = this.application.registry.services.get(serviceName);
|
|
34
|
-
if (!service) return void res.writeStatus('400 Bad Request').end(`Service ${service} not found`);
|
|
35
|
-
if (this.transportType in service.contract.transports === false) return void res.writeStatus('400 Bad Request').end(`Service ${service} not supported`);
|
|
36
|
-
}
|
|
30
|
+
const contentType = requestData.headers.get('content-type') || requestData.query.get('content-type');
|
|
31
|
+
const acceptType = requestData.headers.get('accept') || requestData.query.get('accept');
|
|
37
32
|
const data = {
|
|
38
33
|
id: randomUUID(),
|
|
39
|
-
|
|
40
|
-
container,
|
|
41
|
-
streams: {
|
|
42
|
-
up: new Map(),
|
|
43
|
-
down: new Map(),
|
|
44
|
-
streamId: 0
|
|
45
|
-
},
|
|
46
|
-
abortControllers: new Map(),
|
|
47
|
-
subscriptions: new Map(),
|
|
48
|
-
services,
|
|
49
|
-
data: {
|
|
34
|
+
request: {
|
|
50
35
|
query: requestData.query,
|
|
51
36
|
headers: requestData.headers,
|
|
52
37
|
proxiedRemoteAddress: Buffer.from(res.getProxiedRemoteAddressAsText()).toString(),
|
|
53
|
-
remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString()
|
|
38
|
+
remoteAddress: Buffer.from(res.getRemoteAddressAsText()).toString(),
|
|
39
|
+
contentType,
|
|
40
|
+
acceptType
|
|
54
41
|
},
|
|
42
|
+
opening: createPromise(),
|
|
55
43
|
backpressure: null,
|
|
56
44
|
context: {}
|
|
57
45
|
};
|
|
58
46
|
res.upgrade(data, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
|
|
59
47
|
},
|
|
60
|
-
open: (ws)=>{
|
|
61
|
-
const
|
|
62
|
-
this.
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
48
|
+
open: async (ws)=>{
|
|
49
|
+
const { id, context, request, opening } = ws.getUserData();
|
|
50
|
+
this.clients.set(id, ws);
|
|
51
|
+
this.logger.debug('Connection %s opened', id);
|
|
52
|
+
try {
|
|
53
|
+
const { context: _context, connection } = await this.context.protocol.connections.add(this, {
|
|
54
|
+
id,
|
|
55
|
+
data: request
|
|
56
|
+
}, {
|
|
57
|
+
acceptType: request.acceptType,
|
|
58
|
+
contentType: request.contentType
|
|
59
|
+
});
|
|
60
|
+
Object.assign(context, _context);
|
|
61
|
+
context.container.provide(ProtocolInjectables.connection, connection);
|
|
62
|
+
opening.resolve();
|
|
63
|
+
} catch (error) {
|
|
64
|
+
opening.reject(error);
|
|
65
|
+
}
|
|
78
66
|
},
|
|
79
|
-
message: async (ws,
|
|
80
|
-
const
|
|
67
|
+
message: async (ws, buffer)=>{
|
|
68
|
+
const { opening } = ws.getUserData();
|
|
81
69
|
const messageType = decodeNumber(buffer, 'Uint8');
|
|
82
70
|
if (messageType in this === false) {
|
|
83
71
|
ws.end(1011, 'Unknown message type');
|
|
84
72
|
} else {
|
|
85
73
|
try {
|
|
74
|
+
await opening.promise;
|
|
86
75
|
await this[messageType](ws, buffer.slice(Uint8Array.BYTES_PER_ELEMENT));
|
|
87
76
|
} catch (error) {
|
|
88
77
|
this.logError(error, 'Error while processing message');
|
|
@@ -94,31 +83,17 @@ export class WsTransportServer {
|
|
|
94
83
|
data.backpressure?.resolve();
|
|
95
84
|
data.backpressure = null;
|
|
96
85
|
},
|
|
97
|
-
close: (ws, code, message)=>{
|
|
98
|
-
const
|
|
99
|
-
this.logger.debug('Connection %s closed with code %s: %s',
|
|
100
|
-
this.
|
|
101
|
-
|
|
102
|
-
for (const ac of data.abortControllers.values()){
|
|
103
|
-
ac.abort(error);
|
|
104
|
-
}
|
|
105
|
-
data.abortControllers.clear();
|
|
106
|
-
for (const stream of data.streams.down.values()){
|
|
107
|
-
stream.destroy(error);
|
|
108
|
-
}
|
|
109
|
-
data.streams.down.clear();
|
|
110
|
-
for (const stream of data.streams.up.values()){
|
|
111
|
-
stream.destroy(error);
|
|
112
|
-
}
|
|
113
|
-
data.streams.up.clear();
|
|
114
|
-
for (const subscription of data.subscriptions.values()){
|
|
115
|
-
subscription.destroy();
|
|
116
|
-
}
|
|
117
|
-
data.subscriptions.clear();
|
|
118
|
-
this.handleContainerDisposal(data.container);
|
|
86
|
+
close: async (ws, code, message)=>{
|
|
87
|
+
const { id } = ws.getUserData();
|
|
88
|
+
this.logger.debug('Connection %s closed with code %s: %s', id, code, Buffer.from(message).toString());
|
|
89
|
+
this.clients.delete(id);
|
|
90
|
+
await this.protocol.connections.remove(id);
|
|
119
91
|
}
|
|
120
92
|
});
|
|
121
93
|
}
|
|
94
|
+
send(connection, messageType, buffer) {
|
|
95
|
+
send(connection.data.ws, messageType, buffer);
|
|
96
|
+
}
|
|
122
97
|
async start() {
|
|
123
98
|
return new Promise((resolve, reject)=>{
|
|
124
99
|
const hostname = this.options.hostname ?? '127.0.0.1';
|
|
@@ -135,11 +110,11 @@ export class WsTransportServer {
|
|
|
135
110
|
async stop() {
|
|
136
111
|
this.server.close();
|
|
137
112
|
}
|
|
138
|
-
get
|
|
139
|
-
return this.
|
|
113
|
+
get protocol() {
|
|
114
|
+
return this.context.protocol;
|
|
140
115
|
}
|
|
141
116
|
get logger() {
|
|
142
|
-
return this.
|
|
117
|
+
return this.context.logger;
|
|
143
118
|
}
|
|
144
119
|
async logError(cause, message = 'Unknown error while processing request') {
|
|
145
120
|
this.logger.error(new Error(message, {
|
|
@@ -154,203 +129,41 @@ export class WsTransportServer {
|
|
|
154
129
|
res.writeHeader('Access-Control-Allow-Methods', 'GET, POST');
|
|
155
130
|
res.writeHeader('Access-Control-Allow-Credentials', 'true');
|
|
156
131
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
createDecodeRpcContext(ws) {
|
|
196
|
-
const data = ws.getUserData();
|
|
197
|
-
return {
|
|
198
|
-
addStream (signal, id, metadata) {
|
|
199
|
-
const upstream = new ServerUpStream(metadata, {
|
|
200
|
-
read: (size)=>{
|
|
201
|
-
send(ws, MessageType.UpStreamPull, encodeNumber(id, 'Uint32'), encodeNumber(size, 'Uint32'));
|
|
202
|
-
}
|
|
203
|
-
});
|
|
204
|
-
data.streams.up.set(id, upstream);
|
|
205
|
-
onAbort(signal, ()=>{
|
|
206
|
-
upstream.destroy(new Error('Call aborted by client'));
|
|
207
|
-
});
|
|
208
|
-
upstream.once('error', (error)=>{
|
|
209
|
-
if (error.message !== 'Aborted by server') send(ws, MessageType.UpStreamAbort, encodeNumber(id, 'Uint32'));
|
|
210
|
-
});
|
|
211
|
-
upstream.once('close', ()=>{
|
|
212
|
-
if (upstream.errored?.message !== 'Aborted by server') send(ws, MessageType.UpStreamEnd, encodeNumber(id, 'Uint32'));
|
|
213
|
-
});
|
|
214
|
-
return upstream;
|
|
215
|
-
},
|
|
216
|
-
getStream (id) {
|
|
217
|
-
return data.streams.down.get(id);
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
async [MessageType.Rpc](ws, buffer) {
|
|
222
|
-
const data = ws.getUserData();
|
|
223
|
-
const connection = this.application.connections.get(data.id);
|
|
224
|
-
if (!connection) return void ws.end(1011, 'Unknown connection');
|
|
225
|
-
const ac = new AbortController();
|
|
226
|
-
const rpc = data.format.decoder.decodeRpc(buffer, {
|
|
227
|
-
...data.context.decode,
|
|
228
|
-
addStream: data.context.decode.addStream.bind(null, ac.signal)
|
|
229
|
-
});
|
|
230
|
-
data.abortControllers.set(rpc.callId, ac);
|
|
231
|
-
const container = data.container.createScope(Scope.Call);
|
|
232
|
-
try {
|
|
233
|
-
const { service, procedure } = this.api.find(rpc.service, rpc.procedure, this.transportType);
|
|
234
|
-
const response = await this.handleRPC({
|
|
235
|
-
connection,
|
|
236
|
-
service,
|
|
237
|
-
procedure,
|
|
238
|
-
container,
|
|
239
|
-
signal: ac.signal,
|
|
240
|
-
payload: rpc.payload
|
|
241
|
-
});
|
|
242
|
-
if (response instanceof SubscriptionResponse) {
|
|
243
|
-
sendRpcMessage(ws, MessageType.RpcSubscription, {
|
|
244
|
-
callId: rpc.callId,
|
|
245
|
-
error: null,
|
|
246
|
-
payload: [
|
|
247
|
-
response.subscription.key,
|
|
248
|
-
response.payload
|
|
249
|
-
]
|
|
250
|
-
});
|
|
251
|
-
response.subscription.on('event', (event, payload)=>{
|
|
252
|
-
sendMessage(ws, MessageType.ServerSubscriptionEvent, [
|
|
253
|
-
response.subscription.key,
|
|
254
|
-
event,
|
|
255
|
-
payload
|
|
256
|
-
]);
|
|
257
|
-
});
|
|
258
|
-
response.subscription.once('end', ()=>{
|
|
259
|
-
sendMessage(ws, MessageType.ServerUnsubscribe, [
|
|
260
|
-
response.subscription.key
|
|
261
|
-
]);
|
|
262
|
-
});
|
|
263
|
-
} else {
|
|
264
|
-
sendRpcMessage(ws, MessageType.Rpc, {
|
|
265
|
-
callId: rpc.callId,
|
|
266
|
-
error: null,
|
|
267
|
-
payload: response
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
} catch (error) {
|
|
271
|
-
if (error instanceof ApiError) {
|
|
272
|
-
this.logger.debug(new Error('Api error', {
|
|
273
|
-
cause: error
|
|
274
|
-
}));
|
|
275
|
-
sendRpcMessage(ws, MessageType.Rpc, {
|
|
276
|
-
callId: rpc.callId,
|
|
277
|
-
error,
|
|
278
|
-
payload: null
|
|
279
|
-
});
|
|
280
|
-
} else {
|
|
281
|
-
this.logger.error(new Error('Unexpected error', {
|
|
282
|
-
cause: error
|
|
283
|
-
}));
|
|
284
|
-
sendRpcMessage(ws, MessageType.Rpc, {
|
|
285
|
-
callId: rpc.callId,
|
|
286
|
-
error: InternalError(),
|
|
287
|
-
payload: null
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
} finally{
|
|
291
|
-
data.abortControllers.delete(rpc.callId);
|
|
292
|
-
this.handleContainerDisposal(container);
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
async [MessageType.UpStreamPush](ws, buffer) {
|
|
296
|
-
const data = ws.getUserData();
|
|
297
|
-
const id = decodeNumber(buffer, 'Uint32');
|
|
298
|
-
const stream = data.streams.up.get(id);
|
|
299
|
-
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
300
|
-
stream.push(Buffer.from(buffer.slice(Uint32Array.BYTES_PER_ELEMENT)));
|
|
301
|
-
}
|
|
302
|
-
async [MessageType.UpStreamEnd](ws, buffer) {
|
|
303
|
-
const data = ws.getUserData();
|
|
304
|
-
const id = decodeNumber(buffer, 'Uint32');
|
|
305
|
-
const stream = data.streams.up.get(id);
|
|
306
|
-
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
307
|
-
stream.push(null);
|
|
308
|
-
data.streams.up.delete(id);
|
|
309
|
-
}
|
|
310
|
-
async [MessageType.UpStreamAbort](ws, buffer) {
|
|
311
|
-
const data = ws.getUserData();
|
|
312
|
-
const id = decodeNumber(buffer, 'Uint32');
|
|
313
|
-
const stream = data.streams.up.get(id);
|
|
314
|
-
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
315
|
-
stream.destroy(new Error('Aborted by client'));
|
|
316
|
-
data.streams.up.delete(id);
|
|
317
|
-
}
|
|
318
|
-
async [MessageType.DownStreamPull](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
|
-
await data.backpressure?.promise;
|
|
324
|
-
if (stream.readableEnded) send(ws, MessageType.DownStreamEnd, encodeNumber(id, 'Uint32'));
|
|
325
|
-
else stream.resume();
|
|
326
|
-
}
|
|
327
|
-
async [MessageType.DownStreamEnd](ws, buffer) {
|
|
328
|
-
const data = ws.getUserData();
|
|
329
|
-
const id = decodeNumber(buffer, 'Uint32');
|
|
330
|
-
const stream = data.streams.down.get(id);
|
|
331
|
-
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
332
|
-
data.streams.down.delete(id);
|
|
333
|
-
}
|
|
334
|
-
async [MessageType.DownStreamAbort](ws, buffer) {
|
|
335
|
-
const data = ws.getUserData();
|
|
336
|
-
const id = decodeNumber(buffer, 'Uint32');
|
|
337
|
-
const stream = data.streams.down.get(id);
|
|
338
|
-
if (!stream) return ws.end(1011, 'Unknown stream');
|
|
339
|
-
stream.destroy(new Error('Aborted by client'));
|
|
340
|
-
data.streams.down.delete(id);
|
|
341
|
-
}
|
|
342
|
-
async [MessageType.ClientUnsubscribe](ws, buffer) {
|
|
343
|
-
const data = ws.getUserData();
|
|
344
|
-
const [key] = data.format.decoder.decode(buffer);
|
|
345
|
-
const subscription = data.subscriptions.get(key);
|
|
346
|
-
if (!subscription) return void ws.end();
|
|
347
|
-
subscription.destroy();
|
|
348
|
-
data.subscriptions.delete(key);
|
|
349
|
-
}
|
|
350
|
-
async [MessageType.RpcAbort](ws, buffer) {
|
|
351
|
-
const data = ws.getUserData();
|
|
352
|
-
const callId = decodeNumber(buffer, 'Uint32');
|
|
353
|
-
const ac = data.abortControllers.get(callId);
|
|
354
|
-
if (ac) ac.abort(new Error('Aborted by client'));
|
|
132
|
+
[ClientMessageType.Rpc](ws, buffer) {
|
|
133
|
+
const { id } = ws.getUserData();
|
|
134
|
+
this.protocol.rpcRaw(id, buffer);
|
|
135
|
+
}
|
|
136
|
+
[ClientMessageType.RpcAbort](ws, buffer) {
|
|
137
|
+
const { id } = ws.getUserData();
|
|
138
|
+
this.protocol.rpcAbortRaw(id, buffer);
|
|
139
|
+
}
|
|
140
|
+
[ClientMessageType.RpcStreamAbort](ws, buffer) {
|
|
141
|
+
const { id } = ws.getUserData();
|
|
142
|
+
this.protocol.rpcStreamAbortRaw(id, buffer);
|
|
143
|
+
}
|
|
144
|
+
[ClientMessageType.ClientStreamPush](ws, buffer) {
|
|
145
|
+
const { id } = ws.getUserData();
|
|
146
|
+
const streamId = decodeNumber(buffer, 'Uint32');
|
|
147
|
+
this.protocol.clientStreams.push(id, streamId, buffer.slice(Uint32Array.BYTES_PER_ELEMENT));
|
|
148
|
+
}
|
|
149
|
+
[ClientMessageType.ClientStreamEnd](ws, buffer) {
|
|
150
|
+
const { id } = ws.getUserData();
|
|
151
|
+
const streamId = decodeNumber(buffer, 'Uint32');
|
|
152
|
+
this.protocol.clientStreams.end(id, streamId);
|
|
153
|
+
}
|
|
154
|
+
[ClientMessageType.ClientStreamAbort](ws, buffer) {
|
|
155
|
+
const { id } = ws.getUserData();
|
|
156
|
+
const streamId = decodeNumber(buffer, 'Uint32');
|
|
157
|
+
this.protocol.clientStreams.abort(id, streamId);
|
|
158
|
+
}
|
|
159
|
+
[ClientMessageType.ServerStreamPull](ws, buffer) {
|
|
160
|
+
const { id } = ws.getUserData();
|
|
161
|
+
const streamId = decodeNumber(buffer, 'Uint32');
|
|
162
|
+
this.protocol.serverStreams.pull(id, streamId);
|
|
163
|
+
}
|
|
164
|
+
[ClientMessageType.ServerStreamAbort](ws, buffer) {
|
|
165
|
+
const { id } = ws.getUserData();
|
|
166
|
+
const streamId = decodeNumber(buffer, 'Uint32');
|
|
167
|
+
this.protocol.serverStreams.abort(id, streamId);
|
|
355
168
|
}
|
|
356
169
|
}
|
package/dist/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport {\n type AnyBaseProcedure,\n ApiError,\n type ApplicationContext,\n type Connection,\n type Container,\n Scope,\n ServerDownStream,\n ServerUpStream,\n type Service,\n SubscriptionResponse,\n builtin,\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 {\n App,\n type HttpRequest,\n type HttpResponse,\n SSLApp,\n type TemplatedApp,\n} from 'uWebSockets.js'\n\nimport { connectionData } from './injectables.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 .options('/*', (res, req) => {\n this.applyCors(res, req)\n res.writeStatus('200 OK')\n res.endWithoutBody()\n })\n .get('/healthy', (res, req) => {\n this.applyCors(res, req)\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 return void res\n .writeStatus('400 Bad Request')\n .end(`Service ${service} not found`)\n if (this.transportType in service.contract.transports === false)\n return void res\n .writeStatus('400 Bad Request')\n .end(`Service ${service} not supported`)\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 this.logger.debug('Connection %s opened', data.id)\n data.context.decode = this.createDecodeRpcContext(ws)\n data.context.encode = this.createEncodeRpcContext(ws)\n data.container.provide(connectionData, data.data)\n\n const connection = 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 data.container.provide(builtin.connection, connection)\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, code, message) => {\n const data = ws.getUserData()\n\n this.logger.debug(\n 'Connection %s closed with code %s: %s',\n data.id,\n code,\n Buffer.from(message).toString(),\n )\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 applyCors(res: HttpResponse, req: HttpRequest) {\n // TODO: this should be configurable\n const origin = req.getHeader('origin')\n if (!origin) return\n res.writeHeader('Access-Control-Allow-Origin', origin)\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET, POST')\n res.writeHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n protected async handleContainerDisposal(container: Container) {\n await container.dispose()\n }\n\n protected async handleRPC(options: {\n connection: Connection\n service: Service\n procedure: AnyBaseProcedure\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","builtin","onAbort","MessageType","TransportType","decodeNumber","encodeNumber","App","SSLApp","connectionData","InternalError","getFormat","getRequestData","send","sendMessage","sendRpcMessage","WsTransportServer","server","transportType","constructor","application","options","WS","tls","res","req","applyCors","writeStatus","endWithoutBody","get","writeHeader","end","ws","sendPingsAutomatically","maxPayloadLength","upgrade","context","requestData","container","createScope","Connection","services","query","getAll","serviceName","service","registry","contract","transports","data","id","format","streams","up","Map","down","streamId","abortControllers","subscriptions","headers","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","backpressure","getHeader","open","getUserData","logger","debug","decode","createDecodeRpcContext","encode","createEncodeRpcContext","provide","connection","connections","add","type","sendEvent","event","payload","Event","message","buffer","messageType","slice","Uint8Array","BYTES_PER_ELEMENT","error","logError","drain","resolve","close","code","remove","Error","ac","values","abort","clear","stream","destroy","subscription","handleContainerDisposal","start","Promise","reject","hostname","listen","port","socket","info","stop","api","cause","origin","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","AbortController","rpc","decoder","decodeRpc","bind","callId","Call","procedure","find","response","RpcSubscription","key","ServerSubscriptionEvent","ServerUnsubscribe","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,EACPC,OAAO,QACF,qBAAoB;AAC3B,SAGEC,WAAW,EACXC,aAAa,EACbC,YAAY,EACZC,YAAY,QACP,gBAAe;AACtB,SACEC,GAAG,EAGHC,MAAM,QAED,iBAAgB;AAEvB,SAASC,cAAc,QAAQ,mBAAkB;AAMjD,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,CACRI,OAAO,CAAC,MAAM,CAACG,KAAKC;YACnB,IAAI,CAACC,SAAS,CAACF,KAAKC;YACpBD,IAAIG,WAAW,CAAC;YAChBH,IAAII,cAAc;QACpB,GACCC,GAAG,CAAC,YAAY,CAACL,KAAKC;YACrB,IAAI,CAACC,SAAS,CAACF,KAAKC;YACpBD,IAAIM,WAAW,CAAC,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AM,CAAC/C,YAAYyK,iBAAiB,CAAC,CACnC5I,EAAqB,EACrBuD,MAAmB,EACnB;QACA,MAAMtC,OAAOjB,GAAGsC,WAAW;QAC3B,MAAM,CAAC0F,IAAI,GAAG/G,KAAKE,MAAM,CAACoG,OAAO,CAAC9E,MAAM,CAACc;QACzC,MAAMmB,eAAezD,KAAKS,aAAa,CAAC7B,GAAG,CAACmI;QAC5C,IAAI,CAACtD,cAAc,OAAO,KAAK1E,GAAGD,GAAG;QACrC2E,aAAaD,OAAO;QACpBxD,KAAKS,aAAa,CAACyG,MAAM,CAACH;IAC5B;IAEA,MAAM,CAAC7J,YAAY0K,QAAQ,CAAC,CAAC7I,EAAqB,EAAEuD,MAAmB,EAAE;QACvE,MAAMtC,OAAOjB,GAAGsC,WAAW;QAC3B,MAAMoF,SAASrJ,aAAakF,QAAQ;QACpC,MAAMa,KAAKnD,KAAKQ,gBAAgB,CAAC5B,GAAG,CAAC6H;QACrC,IAAItD,IAAIA,GAAGE,KAAK,CAAC,IAAIH,MAAM;IAC7B;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../lib/server.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport {\n App,\n type HttpRequest,\n type HttpResponse,\n SSLApp,\n type TemplatedApp,\n} from 'uWebSockets.js'\n\nimport { createPromise } from '@nmtjs/common'\nimport {\n ClientMessageType,\n type ServerMessageType,\n decodeNumber,\n decodeText,\n} from '@nmtjs/protocol/common'\nimport {\n type Connection,\n ProtocolInjectables,\n type Transport,\n type TransportPluginContext,\n} from '@nmtjs/protocol/server'\nimport type {\n WsTransportOptions,\n WsTransportSocket,\n WsUserData,\n} from './types.ts'\nimport { getRequestData, send } from './utils.ts'\n\nexport type WsConnectionData = {\n ws: WsTransportSocket\n}\n\nexport class WsTransportServer implements Transport<WsConnectionData> {\n protected server!: TemplatedApp\n protected clients: Map<string, WsTransportSocket> = new Map()\n\n constructor(\n protected readonly context: TransportPluginContext,\n protected readonly options: WsTransportOptions,\n ) {\n this.server = this.options.tls ? SSLApp(options.tls!) : App()\n\n this.server\n .options('/*', (res, req) => {\n this.applyCors(res, req)\n res.writeStatus('200 OK')\n res.endWithoutBody()\n })\n .get('/healthy', (res, req) => {\n this.applyCors(res, req)\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\n const contentType =\n requestData.headers.get('content-type') ||\n requestData.query.get('content-type')\n\n const acceptType =\n requestData.headers.get('accept') || requestData.query.get('accept')\n\n const data: WsUserData = {\n id: randomUUID(),\n request: {\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 contentType,\n acceptType,\n },\n opening: createPromise(),\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: async (ws: WsTransportSocket) => {\n const { id, context, request, opening } = ws.getUserData()\n this.clients.set(id, ws)\n this.logger.debug('Connection %s opened', id)\n try {\n const { context: _context, connection } =\n await this.context.protocol.connections.add(\n this,\n { id, data: request },\n {\n acceptType: request.acceptType,\n contentType: request.contentType,\n },\n )\n Object.assign(context, _context)\n context.container.provide(\n ProtocolInjectables.connection,\n connection,\n )\n opening.resolve()\n } catch (error) {\n opening.reject(error)\n }\n },\n message: async (ws: WsTransportSocket, buffer) => {\n const { opening } = ws.getUserData()\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 opening.promise\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: async (ws: WsTransportSocket, code, message) => {\n const { id } = ws.getUserData()\n\n this.logger.debug(\n 'Connection %s closed with code %s: %s',\n id,\n code,\n Buffer.from(message).toString(),\n )\n this.clients.delete(id)\n await this.protocol.connections.remove(id)\n },\n })\n }\n\n send(\n connection: Connection<WsConnectionData>,\n messageType: ServerMessageType,\n buffer: ArrayBuffer,\n ) {\n send(connection.data.ws, messageType, buffer)\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 protocol() {\n return this.context.protocol\n }\n\n protected get logger() {\n return this.context.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 applyCors(res: HttpResponse, req: HttpRequest) {\n // TODO: this should be configurable\n const origin = req.getHeader('origin')\n if (!origin) return\n res.writeHeader('Access-Control-Allow-Origin', origin)\n res.writeHeader('Access-Control-Allow-Headers', 'Content-Type')\n res.writeHeader('Access-Control-Allow-Methods', 'GET, POST')\n res.writeHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n protected [ClientMessageType.Rpc](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n this.protocol.rpcRaw(id, buffer)\n }\n\n protected [ClientMessageType.RpcAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n this.protocol.rpcAbortRaw(id, buffer)\n }\n\n protected [ClientMessageType.RpcStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n this.protocol.rpcStreamAbortRaw(id, buffer)\n }\n\n protected [ClientMessageType.ClientStreamPush](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.clientStreams.push(\n id,\n streamId,\n buffer.slice(Uint32Array.BYTES_PER_ELEMENT),\n )\n }\n\n protected [ClientMessageType.ClientStreamEnd](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.clientStreams.end(id, streamId)\n }\n\n protected [ClientMessageType.ClientStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.clientStreams.abort(id, streamId)\n }\n\n protected [ClientMessageType.ServerStreamPull](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.serverStreams.pull(id, streamId)\n }\n\n protected [ClientMessageType.ServerStreamAbort](\n ws: WsTransportSocket,\n buffer: ArrayBuffer,\n ) {\n const { id } = ws.getUserData()\n const streamId = decodeNumber(buffer, 'Uint32')\n this.protocol.serverStreams.abort(id, streamId)\n }\n}\n"],"names":["randomUUID","App","SSLApp","createPromise","ClientMessageType","decodeNumber","ProtocolInjectables","getRequestData","send","WsTransportServer","server","clients","constructor","context","options","Map","tls","res","req","applyCors","writeStatus","endWithoutBody","get","writeHeader","end","ws","sendPingsAutomatically","maxPayloadLength","upgrade","requestData","contentType","headers","query","acceptType","data","id","request","proxiedRemoteAddress","Buffer","from","getProxiedRemoteAddressAsText","toString","remoteAddress","getRemoteAddressAsText","opening","backpressure","getHeader","open","getUserData","set","logger","debug","_context","connection","protocol","connections","add","Object","assign","container","provide","resolve","error","reject","message","buffer","messageType","promise","slice","Uint8Array","BYTES_PER_ELEMENT","logError","drain","close","code","delete","remove","start","Promise","hostname","listen","port","socket","info","Error","stop","cause","origin","Rpc","rpcRaw","RpcAbort","rpcAbortRaw","RpcStreamAbort","rpcStreamAbortRaw","ClientStreamPush","streamId","clientStreams","push","Uint32Array","ClientStreamEnd","ClientStreamAbort","abort","ServerStreamPull","serverStreams","pull","ServerStreamAbort"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAa;AACxC,SACEC,GAAG,EAGHC,MAAM,QAED,iBAAgB;AAEvB,SAASC,aAAa,QAAQ,gBAAe;AAC7C,SACEC,iBAAiB,EAEjBC,YAAY,QAEP,yBAAwB;AAC/B,SAEEC,mBAAmB,QAGd,yBAAwB;AAM/B,SAASC,cAAc,EAAEC,IAAI,QAAQ,aAAY;AAMjD,OAAO,MAAMC;;;IACDC,OAAqB;IACrBC,QAAmD;IAE7DC,YACE,AAAmBC,OAA+B,EAClD,AAAmBC,OAA2B,CAC9C;aAFmBD,UAAAA;aACAC,UAAAA;aAJXH,UAA0C,IAAII;QAMtD,IAAI,CAACL,MAAM,GAAG,IAAI,CAACI,OAAO,CAACE,GAAG,GAAGd,OAAOY,QAAQE,GAAG,IAAKf;QAExD,IAAI,CAACS,MAAM,CACRI,OAAO,CAAC,MAAM,CAACG,KAAKC;YACnB,IAAI,CAACC,SAAS,CAACF,KAAKC;YACpBD,IAAIG,WAAW,CAAC;YAChBH,IAAII,cAAc;QACpB,GACCC,GAAG,CAAC,YAAY,CAACL,KAAKC;YACrB,IAAI,CAACC,SAAS,CAACF,KAAKC;YACpBD,IAAIM,WAAW,CAAC,gBAAgB;YAChCN,IAAIO,GAAG,CAAC;QACV,GACCC,EAAE,CAAa,QAAQ;YACtBC,wBAAwB;YACxBC,kBAAkB,IAAI,CAACb,OAAO,CAACa,gBAAgB;YAC/CC,SAAS,CAACX,KAAKC,KAAKL;gBAClB,MAAMgB,cAActB,eAAeW;gBAEnC,MAAMY,cACJD,YAAYE,OAAO,CAACT,GAA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,EAAqB,EACrBwC,MAAmB,EACnB;QACA,MAAM,EAAE9B,EAAE,EAAE,GAAGV,GAAGuB,WAAW;QAC7B,MAAM+C,WAAW1F,aAAa4D,QAAQ;QACtC,IAAI,CAACX,QAAQ,CAACiD,aAAa,CAACF,KAAK,CAAClE,IAAI4D;IACxC;AACF"}
|
package/dist/lib/transport.js
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createTransport } from '@nmtjs/protocol/server';
|
|
2
2
|
import { WsTransportServer } from "./server.js";
|
|
3
|
-
export const WsTransport =
|
|
4
|
-
|
|
5
|
-
app.hooks.add(Hook.OnStartup, async ()=>{
|
|
6
|
-
await server.start();
|
|
7
|
-
});
|
|
8
|
-
app.hooks.add(Hook.OnShutdown, async ()=>{
|
|
9
|
-
await server.stop();
|
|
10
|
-
});
|
|
3
|
+
export const WsTransport = createTransport('WsTransport', (context, options)=>{
|
|
4
|
+
return new WsTransportServer(context, options);
|
|
11
5
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../lib/transport.ts"],"sourcesContent":["import { createTransport } from '@nmtjs/protocol/server'\nimport { type WsConnectionData, WsTransportServer } from './server.ts'\nimport type { WsTransportOptions } from './types.ts'\n\nexport const WsTransport = createTransport<\n WsConnectionData,\n WsTransportOptions\n>('WsTransport', (context, options) => {\n return new WsTransportServer(context, options)\n})\n"],"names":["createTransport","WsTransportServer","WsTransport","context","options"],"mappings":"AAAA,SAASA,eAAe,QAAQ,yBAAwB;AACxD,SAAgCC,iBAAiB,QAAQ,cAAa;AAGtE,OAAO,MAAMC,cAAcF,gBAGzB,eAAe,CAACG,SAASC;IACzB,OAAO,IAAIH,kBAAkBE,SAASC;AACxC,GAAE"}
|
package/dist/lib/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../../lib/types.ts"],"sourcesContent":["import type { InteractivePromise } from '@nmtjs/common'\nimport type { Connection, ConnectionContext } from '@nmtjs/protocol/server'\nimport type { AppOptions, WebSocket } from 'uWebSockets.js'\n\nexport type WsUserData = {\n id: Connection['id']\n opening: InteractivePromise<void>\n backpressure: InteractivePromise<void> | null\n request: {\n headers: Map<string, string>\n query: URLSearchParams\n remoteAddress: string\n proxiedRemoteAddress: string\n acceptType: string | null\n contentType: string | null\n }\n context: ConnectionContext\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}\n"],"names":[],"mappings":"AAqBA,WAOC"}
|
package/dist/lib/utils.js
CHANGED
|
@@ -1,18 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ErrorCode, concat, encodeNumber } from '@nmtjs/common';
|
|
3
|
-
|
|
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
|
-
};
|
|
1
|
+
import { createPromise } from '@nmtjs/common';
|
|
2
|
+
import { ErrorCode, concat, encodeNumber } from '@nmtjs/protocol/common';
|
|
3
|
+
import { ProtocolError } from '@nmtjs/protocol/server';
|
|
10
4
|
export const send = (ws, type, ...buffers)=>{
|
|
11
5
|
const data = ws.getUserData();
|
|
12
6
|
try {
|
|
13
|
-
const
|
|
7
|
+
const buffer = concat(encodeNumber(type, 'Uint8'), ...buffers);
|
|
8
|
+
const result = ws.send(buffer, true);
|
|
14
9
|
if (result === 0) {
|
|
15
|
-
data.backpressure =
|
|
10
|
+
data.backpressure = createPromise();
|
|
16
11
|
return false;
|
|
17
12
|
}
|
|
18
13
|
if (result === 2) {
|
|
@@ -23,18 +18,6 @@ export const send = (ws, type, ...buffers)=>{
|
|
|
23
18
|
return null;
|
|
24
19
|
}
|
|
25
20
|
};
|
|
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
21
|
export const toRecord = (input)=>{
|
|
39
22
|
const obj = {};
|
|
40
23
|
input.forEach((value, key)=>{
|
|
@@ -57,7 +40,7 @@ export const getRequestData = (req)=>{
|
|
|
57
40
|
query
|
|
58
41
|
};
|
|
59
42
|
};
|
|
60
|
-
export const InternalError = (message = 'Internal Server Error')=>new
|
|
61
|
-
export const NotFoundError = (message = 'Not Found')=>new
|
|
62
|
-
export const ForbiddenError = (message = 'Forbidden')=>new
|
|
63
|
-
export const RequestTimeoutError = (message = 'Request Timeout')=>new
|
|
43
|
+
export const InternalError = (message = 'Internal Server Error')=>new ProtocolError(ErrorCode.InternalServerError, message);
|
|
44
|
+
export const NotFoundError = (message = 'Not Found')=>new ProtocolError(ErrorCode.NotFound, message);
|
|
45
|
+
export const ForbiddenError = (message = 'Forbidden')=>new ProtocolError(ErrorCode.Forbidden, message);
|
|
46
|
+
export const RequestTimeoutError = (message = 'Request Timeout')=>new ProtocolError(ErrorCode.RequestTimeout, message);
|