-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.js
More file actions
463 lines (403 loc) · 11.9 KB
/
Copy pathindex.js
File metadata and controls
463 lines (403 loc) · 11.9 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
const cluster = require("cluster");
const { randomBytes } = require("crypto");
const { Duplex } = require("stream");
const debug = require("debug")("socket.io-sticky");
const randomId = () => randomBytes(8).toString("hex");
function destroySocket() {
this.destroy();
}
const setupMaster = (httpServer, opts) => {
if (!cluster.isPrimary) {
throw new Error("not primary");
}
const options = Object.assign(
{
loadBalancingMethod: "least-connection", // either "random", "round-robin" or "least-connection"
},
opts
);
debug("setting up primary with options %o", options);
const sessionIdToWorker = new Map();
const sockets = new Map();
const sidRegex = /sid=([\w\-]{20})/;
let currentIndex = 0; // for round-robin load balancing
const computeWorkerId = (data) => {
const match = sidRegex.exec(data);
if (match) {
const sid = match[1];
const workerId = sessionIdToWorker.get(sid);
if (workerId && cluster.workers[workerId]) {
debug("sid %s matched to worker %s", sid, workerId);
return workerId;
}
}
switch (options.loadBalancingMethod) {
case "random": {
const workerIds = Object.keys(cluster.workers);
const workerId =
workerIds[Math.floor(Math.random() * workerIds.length)];
debug("randomly selected worker %s", workerId);
return workerId;
}
case "round-robin": {
const workerIds = Object.keys(cluster.workers);
const workerId = workerIds[currentIndex % workerIds.length];
currentIndex = (currentIndex + 1) % workerIds.length;
debug("round-robin selected worker %s", workerId);
return workerId;
}
case "least-connection":
let leastActiveWorker;
for (const id in cluster.workers) {
const worker = cluster.workers[id];
if (leastActiveWorker === undefined) {
leastActiveWorker = worker;
} else {
const c1 = worker.clientsCount || 0;
const c2 = leastActiveWorker.clientsCount || 0;
if (c1 < c2) {
leastActiveWorker = worker;
}
}
}
debug("least-connection selected worker %s", leastActiveWorker.id);
return leastActiveWorker.id;
}
};
httpServer.on("connection", (socket) => {
let workerId, connectionId;
const sendCallback = (err) => {
if (err) {
socket.destroy();
}
};
socket.removeAllListeners("data");
socket.on("data", (chunk) => {
if (Object.keys(cluster.workers).length === 0) {
debug("no workers available, destroying socket");
if (workerId) {
// the socket was already assigned to a worker, so we destroy it directly
socket.destroy();
} else {
socket.on("error", destroySocket);
socket.once("finish", destroySocket);
socket.end(
"HTTP/1.1 503 Service Unavailable\r\n" +
"Connection: close\r\n" +
"Content-Length: 0\r\n" +
"\r\n"
);
}
return;
}
if (workerId && cluster.workers[workerId] && connectionId) {
debug(
"forwarding chunk (chunk length: %d) to worker %s (connectionId: %s)",
chunk.byteLength,
workerId,
connectionId
);
cluster.workers[workerId].send(
{ type: "sticky:http-chunk", data: chunk, connectionId },
sendCallback
);
return;
}
const header = chunk
.subarray(0, chunk.indexOf(Buffer.from("\r\n\r\n")))
.toString();
workerId = computeWorkerId(header);
const lowHeader = header.toLowerCase();
const mayHaveMultipleChunks =
lowHeader.includes("content-length:") ||
lowHeader.includes("transfer-encoding:");
// If the full request is not contained in the first chunk, the primary must
// keep ownership of the real socket and forward next chunks over IPC.
// Sending the socket handle to the worker in that case would let both the
// primary and the worker read from the same stream, so request bytes could be
// split unpredictably between the two processes. Instead, the worker receives
// a FakeSocket whose readable side is fed explicitly by IPC chunks.
if (!mayHaveMultipleChunks) {
debug(
"forwarding connection (chunk length: %d) to worker %s",
chunk.byteLength,
workerId
);
cluster.workers[workerId].send(
{
type: "sticky:connection",
data: chunk,
},
socket,
sendCallback
);
return;
}
connectionId = randomId();
sockets.set(connectionId, socket);
debug(
"forwarding connection (chunk length: %d) to worker %s (connectionId: %s)",
chunk.byteLength,
workerId,
connectionId
);
cluster.workers[workerId].send(
{
type: "sticky:http-chunk-start",
data: chunk,
connectionId,
socketInfo: {
remoteAddress: socket.remoteAddress,
remotePort: socket.remotePort,
localAddress: socket.localAddress,
localPort: socket.localPort,
},
},
sendCallback
);
});
socket.on("close", () => {
if (connectionId && sockets.has(connectionId)) {
sockets.delete(connectionId);
if (workerId && cluster.workers[workerId]) {
cluster.workers[workerId].send({
type: "sticky:abort",
connectionId,
});
}
}
});
});
cluster.on("message", (worker, message) => {
const { type, data } = message;
switch (type) {
case "sticky:http-response": {
const { connectionId } = message;
const socket = sockets.get(connectionId);
if (socket && !socket.destroyed) {
socket.write(data);
}
break;
}
case "sticky:http-response-end": {
const { connectionId } = message;
const socket = sockets.get(connectionId);
if (socket && !socket.destroyed) {
socket.end();
}
sockets.delete(connectionId);
break;
}
case "sticky:http-response-destroy": {
const { connectionId, error } = message;
const socket = sockets.get(connectionId);
if (socket && !socket.destroyed) {
socket.destroy(error ? new Error(error) : undefined);
}
sockets.delete(connectionId);
break;
}
case "sticky:connection":
debug("session %s bound to worker %s", data, worker.id);
sessionIdToWorker.set(data, worker.id);
if (options.loadBalancingMethod === "least-connection") {
worker.clientsCount = (worker.clientsCount || 0) + 1;
}
break;
case "sticky:disconnection":
debug("session %s unbound from worker %s", data, worker.id);
sessionIdToWorker.delete(data);
if (options.loadBalancingMethod === "least-connection") {
worker.clientsCount--;
}
break;
}
});
cluster.on("exit", (worker) => {
debug("worker %s exited, cleaning up sessions", worker.id);
sessionIdToWorker.forEach((value, key) => {
if (value === worker.id) {
sessionIdToWorker.delete(key);
}
});
});
};
class FakeSocket extends Duplex {
constructor(socketInfo, connectionId) {
super({
allowHalfOpen: true,
});
this.connectionId = connectionId;
this.remoteAddress = socketInfo.remoteAddress;
this.remotePort = socketInfo.remotePort;
this.localAddress = socketInfo.localAddress;
this.localPort = socketInfo.localPort;
}
_read(size) {}
_write(chunk, encoding, callback) {
if (!process.connected) {
callback();
return;
}
process.send(
{
type: "sticky:http-response",
data: chunk,
connectionId: this.connectionId,
},
callback
);
}
_final(callback) {
if (!process.connected) {
callback();
return;
}
process.send(
{
type: "sticky:http-response-end",
connectionId: this.connectionId,
},
callback
);
}
_destroy(err, callback) {
if (this._aborted) {
callback();
return;
}
if (!process.connected) {
callback(err);
return;
}
process.send(
{
type: "sticky:http-response-destroy",
connectionId: this.connectionId,
error: err && err.message,
},
() => callback(err)
);
}
addChunk(chunk) {
if (this.destroyed || this.readableEnded) {
return;
}
this.push(chunk);
}
abort() {
this._aborted = true;
this.destroy(new Error("client connection closed"));
}
destroySoon() {
this.end();
}
cork() {
return this;
}
uncork() {
return this;
}
setTimeout(timeout, callback) {
if (callback) {
this.once("timeout", callback);
}
return this;
}
setNoDelay() {
return this;
}
setKeepAlive() {
return this;
}
address() {
return {
family: "IPv4",
address: this.localAddress,
port: this.localPort,
};
}
ref() {
return this;
}
unref() {
return this;
}
}
const setupWorker = (io) => {
if (!cluster.isWorker) {
throw new Error("not worker");
}
io.httpServer.prependListener("request", (req, res) => {
// disable HTTP keep-alive to prevent connection reuse for another session
res.setHeader("Connection", "close");
});
// store connections that may receive multiple chunks
const sockets = new Map();
process.on("message", (message, socket) => {
const { type, data } = message;
switch (type) {
case "sticky:connection":
if (!socket) {
debug(
"ignoring connection from primary because the socket is closed"
);
// might happen if the socket is closed during the transfer to the worker
// see https://nodejs.org/api/child_process.html#child_process_example_sending_a_socket_object
return;
}
debug("received connection from primary");
io.httpServer.emit("connection", socket); // inject connection
socket.unshift(data); // republish first chunk
break;
case "sticky:http-chunk-start": {
const { socketInfo, connectionId } = message;
debug("received first chunk for connection %s", connectionId);
const fakeSocket = new FakeSocket(socketInfo, connectionId);
fakeSocket.once("close", () => {
sockets.delete(connectionId);
});
io.httpServer.emit("connection", fakeSocket); // inject connection
fakeSocket.addChunk(data); // republish first chunk
sockets.set(connectionId, fakeSocket);
break;
}
case "sticky:http-chunk": {
const { connectionId } = message;
const socket = sockets.get(connectionId);
if (socket) {
debug("received chunk for connection %s", connectionId);
socket.addChunk(data);
} else {
debug("received chunk for unknown connection %s", connectionId);
}
break;
}
case "sticky:abort": {
const { connectionId } = message;
const socket = sockets.get(connectionId);
if (socket) {
socket.abort();
}
break;
}
}
});
const ignoreError = () => {}; // the next request will fail anyway
io.engine.on("connection", (socket) => {
debug("new connection %s", socket.id);
process.send({ type: "sticky:connection", data: socket.id }, ignoreError);
socket.once("close", () => {
debug("connection %s closed", socket.id);
process.send(
{ type: "sticky:disconnection", data: socket.id },
ignoreError
);
});
});
};
module.exports = {
setupPrimary: setupMaster,
setupMaster, // kept for backward compatibility
setupWorker,
};