-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
uWebSockets.ts
219 lines (200 loc) · 6.82 KB
/
uWebSockets.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import type * as uWS from 'uWebSockets.js';
import type http from 'http';
import { makeServer, ServerOptions } from '../server';
import { CloseCode } from '../common';
/**
* The extra that will be put in the `Context`.
*
* @category Server/uWebSockets
*/
export interface Extra extends UpgradeData {
/**
* The actual socket connection between the server and the client
* with the upgrade data.
*/
readonly socket: uWS.WebSocket & UpgradeData;
}
/**
* Data acquired during the HTTP upgrade callback from uWS.
*
* @category Server/uWebSockets
*/
export interface UpgradeData {
/**
* The initial HTTP upgrade request before the actual
* socket and connection is established.
*
* uWS's request is stack allocated and cannot be accessed
* from outside of the internal upgrade; therefore, the persisted
* request holds the relevant values extracted from the uWS's request
* while it is accessible.
*/
readonly persistedRequest: PersistedRequest;
}
/**
* The initial HTTP upgrade request before the actual
* socket and connection is established.
*
* uWS's request is stack allocated and cannot be accessed
* from outside of the internal upgrade; therefore, the persisted
* request holds relevant values extracted from the uWS's request
* while it is accessible.
*
* @category Server/uWebSockets
*/
export interface PersistedRequest {
method: string;
url: string;
/** The raw query string (after the `?` sign) or empty string. */
query: string;
headers: http.IncomingHttpHeaders;
}
interface Client {
pingInterval: NodeJS.Timeout | null;
pongWaitTimeout: NodeJS.Timeout | null;
handleMessage: (data: string) => Promise<void>;
closed: (code: number, reason: string) => Promise<void>;
}
/**
* Make the behaviour for using a [uWebSockets.js](https://github.com/uNetworking/uWebSockets.js) WebSocket server.
* This is a basic starter, feel free to copy the code over and adjust it to your needs
*
* @category Server/uWebSockets
*/
export function makeBehavior<
E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>,
>(
options: ServerOptions<Extra & Partial<E>>,
behavior: uWS.WebSocketBehavior = {},
/**
* The timout between dispatched keep-alive messages. Internally uses the [ws Ping and Pongs]((https://developer.mozilla.org/en-US/docs/Web/API/wss_API/Writing_ws_servers#Pings_and_Pongs_The_Heartbeat_of_wss))
* to check that the link between the clients and the server is operating and to prevent the link
* from being broken due to idling.
*
* @default 12_000 // 12 seconds
*/
keepAlive = 12_000,
): uWS.WebSocketBehavior {
const isProd = process.env.NODE_ENV === 'production';
const server = makeServer(options);
const clients = new Map<uWS.WebSocket, Client>();
let onDrain = () => {
// gets called when backpressure drains
};
return {
...behavior,
pong(...args) {
behavior.pong?.(...args);
const [socket] = args;
const client = clients.get(socket);
if (!client) throw new Error('Pong received for a missing client');
if (client.pongWaitTimeout) {
clearTimeout(client.pongWaitTimeout);
client.pongWaitTimeout = null;
}
},
upgrade(...args) {
behavior.upgrade?.(...args);
const [res, req, context] = args;
const headers: http.IncomingHttpHeaders = {};
req.forEach((key, value) => {
headers[key] = value;
});
res.upgrade<UpgradeData>(
{
persistedRequest: {
method: req.getMethod(),
url: req.getUrl(),
query: req.getQuery(),
headers,
},
},
req.getHeader('sec-websocket-key'),
req.getHeader('sec-websocket-protocol'),
req.getHeader('sec-websocket-extensions'),
context,
);
},
open(...args) {
behavior.open?.(...args);
const socket = args[0] as uWS.WebSocket & UpgradeData;
const persistedRequest = socket.persistedRequest;
// prepare client object
const client: Client = {
pingInterval: null,
pongWaitTimeout: null,
handleMessage: () => {
throw new Error('Message received before handler was registered');
},
closed: () => {
throw new Error('Closed before handler was registered');
},
};
client.closed = server.opened(
{
protocol: persistedRequest.headers['sec-websocket-protocol'] ?? '',
send: async (message) => {
// the socket might have been destroyed in the meantime
if (!clients.has(socket)) return;
if (!socket.send(message))
// if backpressure is built up wait for drain
await new Promise<void>((resolve) => (onDrain = resolve));
},
close: (code, reason) => {
// end socket in next tick making sure the client is registered
setImmediate(() => {
// the socket might have been destroyed before issuing a close
if (clients.has(socket)) socket.end(code, reason);
});
},
onMessage: (cb) => (client.handleMessage = cb),
},
{ socket, persistedRequest } as Extra & Partial<E>,
);
if (keepAlive > 0 && isFinite(keepAlive)) {
client.pingInterval = setInterval(() => {
// terminate the connection after pong wait has passed because the client is idle
client.pongWaitTimeout = setTimeout(() => socket.close(), keepAlive);
socket.ping();
}, keepAlive);
}
clients.set(socket, client);
},
drain(...args) {
behavior.drain?.(...args);
onDrain();
},
async message(...args) {
behavior.message?.(...args);
const [socket, message] = args;
const client = clients.get(socket);
if (!client) throw new Error('Message received for a missing client');
try {
await client.handleMessage(Buffer.from(message).toString());
} catch (err) {
console.error(
'Internal error occurred during message handling. ' +
'Please check your implementation.',
err,
);
socket.end(
CloseCode.InternalServerError,
// close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
isProd || err.message.length > 123
? 'Internal server error'
: err.message,
);
}
},
close(...args) {
behavior.close?.(...args);
const [socket, code, message] = args;
const client = clients.get(socket);
if (!client) throw new Error('Closing a missing client');
if (client.pongWaitTimeout) clearTimeout(client.pongWaitTimeout);
if (client.pingInterval) clearTimeout(client.pingInterval);
client.closed(code, Buffer.from(message).toString());
clients.delete(socket);
},
};
}