forked from socketio/socket.io-sticky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
210 lines (184 loc) · 5.67 KB
/
index.js
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
const cluster = require("cluster");
const { randomBytes } = require("crypto");
const randomId = () => randomBytes(8).toString("hex");
function destroySocket() {
this.destroy();
}
const setupMaster = (httpServer, opts) => {
if (!cluster.isMaster) {
throw new Error("not master");
}
const options = Object.assign(
{
loadBalancingMethod: "least-connection", // either "random", "round-robin" or "least-connection"
},
opts
);
const sessionIdToWorker = 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]) {
return workerId;
}
}
switch (options.loadBalancingMethod) {
case "random": {
const workerIds = Object.keys(cluster.workers);
return workerIds[Math.floor(Math.random() * workerIds.length)];
}
case "round-robin": {
const workerIds = Object.keys(cluster.workers);
currentIndex++;
if (currentIndex >= workerIds.length) {
currentIndex = 0;
}
return workerIds[currentIndex];
}
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;
}
}
}
leastActiveWorker.clientsCount = (leastActiveWorker.clientsCount || 0) + 100;
setTimeout(() => {
leastActiveWorker.clientsCount -= 100;
}, 1000)
return leastActiveWorker.id;
}
};
httpServer.on("connection", (socket) => {
let workerId, connectionId;
const sendCallback = (err) => {
if (err) {
socket.destroy();
}
};
socket.on("data", (buffer) => {
if (Object.keys(cluster.workers).length === 0) {
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;
}
const data = buffer.toString();
if (workerId && connectionId) {
cluster.workers[workerId].send(
{ type: "sticky:http-chunk", data, connectionId },
sendCallback
);
return;
}
workerId = computeWorkerId(data);
const head = data.substring(0, data.indexOf("\r\n\r\n")).toLowerCase();
const mayHaveMultipleChunks =
head.includes("content-length:") || head.includes("transfer-encoding:");
if (mayHaveMultipleChunks) {
connectionId = randomId();
}
cluster.workers[workerId].send(
{ type: "sticky:connection", data, connectionId },
socket,
{
keepOpen: mayHaveMultipleChunks,
},
sendCallback
);
});
});
// this is needed to properly detect the end of the HTTP request body
httpServer.on("request", (req) => {
req.on("data", () => {});
});
cluster.on("message", (worker, { type, data }) => {
switch (type) {
case "sticky:connection":
sessionIdToWorker.set(data, worker.id);
if (options.loadBalancingMethod === "least-connection") {
worker.clientsCount = (worker.clientsCount || 0) + 1;
}
break;
case "sticky:disconnection":
sessionIdToWorker.delete(data);
if (options.loadBalancingMethod === "least-connection") {
worker.clientsCount--;
}
break;
}
});
cluster.on("exit", (worker) => {
sessionIdToWorker.forEach((value, key) => {
if (value === worker.id) {
sessionIdToWorker.delete(key);
}
});
});
};
const setupWorker = (io) => {
if (!cluster.isWorker) {
throw new Error("not worker");
}
// store connections that may receive multiple chunks
const sockets = new Map();
process.on("message", ({ type, data, connectionId }, socket) => {
switch (type) {
case "sticky:connection":
if (!socket) {
// 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;
}
io.httpServer.emit("connection", socket); // inject connection
socket.emit("data", Buffer.from(data)); // republish first chunk
socket.resume();
if (connectionId) {
sockets.set(connectionId, socket);
socket.on("close", () => {
sockets.delete(connectionId);
});
}
break;
case "sticky:http-chunk": {
const socket = sockets.get(connectionId);
if (socket) {
socket.emit("data", Buffer.from(data));
}
}
}
});
const ignoreError = () => {}; // the next request will fail anyway
io.engine.on("connection", (socket) => {
process.send({ type: "sticky:connection", data: socket.id }, ignoreError);
socket.once("close", () => {
process.send(
{ type: "sticky:disconnection", data: socket.id },
ignoreError
);
});
});
};
module.exports = {
setupMaster,
setupWorker,
};