Exercise Nginx routing, Mongo transaction ordering, history backfills, Undo, Pub/Sub TCP loss, safety polling, resync, and reconnection. Keep fixtures and results isolated from production and git.
61 lines
1.9 KiB
JavaScript
61 lines
1.9 KiB
JavaScript
import { createServer as createTcpServer, connect } from 'node:net';
|
|
import { createServer as createHttpServer } from 'node:http';
|
|
|
|
// Real TCP connections; only connections issuing SUBSCRIBE/PSUBSCRIBE are cut.
|
|
// Redis commands, TIME and PUBLISH continue through the same proxy.
|
|
let blocked = false;
|
|
let dropped = 0;
|
|
const connections = new Set();
|
|
createTcpServer((socket) => {
|
|
const upstream = connect(6379, 'redis');
|
|
const connection = { socket, upstream, subscriber: false, prefix: '' };
|
|
connections.add(connection);
|
|
const close = () => {
|
|
socket.destroy();
|
|
upstream.destroy();
|
|
connections.delete(connection);
|
|
};
|
|
socket.on('error', close);
|
|
upstream.on('error', close);
|
|
socket.on('close', close);
|
|
upstream.on('close', close);
|
|
socket.on('data', (chunk) => {
|
|
connection.prefix = (connection.prefix + chunk.toString('utf8')).slice(
|
|
-4096,
|
|
);
|
|
if (/\r\n(?:p?subscribe|ssubscribe)\r\n/i.test(connection.prefix)) {
|
|
connection.subscriber = true;
|
|
}
|
|
if (blocked && connection.subscriber) {
|
|
dropped += 1;
|
|
close();
|
|
} else upstream.write(chunk);
|
|
});
|
|
upstream.on('data', (chunk) => socket.write(chunk));
|
|
}).listen(6379, '0.0.0.0');
|
|
|
|
createHttpServer((request, response) => {
|
|
if (request.method === 'POST' && request.url === '/block') {
|
|
blocked = true;
|
|
for (const connection of connections) {
|
|
if (!connection.subscriber) continue;
|
|
dropped += 1;
|
|
connection.socket.destroy();
|
|
connection.upstream.destroy();
|
|
}
|
|
} else if (request.method === 'POST' && request.url === '/restore') {
|
|
blocked = false;
|
|
} else if (request.url !== '/status') {
|
|
response.writeHead(404).end();
|
|
return;
|
|
}
|
|
response.setHeader('content-type', 'application/json');
|
|
response.end(
|
|
JSON.stringify({
|
|
blocked,
|
|
dropped,
|
|
subscribers: [...connections].filter((c) => c.subscriber).length,
|
|
}),
|
|
);
|
|
}).listen(8081, '0.0.0.0');
|