So i think you are right but i haven’t figured it out yet. Here’s what i tried:
Server:
const FLY_INSTANCE_ID = process.env.FLY_ALLOC_ID
? process.env.FLY_ALLOC_ID.split(“-”)[0]
: null;
app.get(‘/menue’, (req, res) => {
res.cookie(‘mid’, FLY_INSTANCE_ID, {maxAge: 604800000})
res.render(‘menue’)
})
http.on(“upgrade”, function (req, socket, head) {
// No-op on localhost/non-Fly environments.
if (!FLY_INSTANCE_ID) return;
// No-op on other HTTP upgrades.
if (req.headers[“upgrade”] !== “websocket”) return;
// Get target fly instance via URL pattern matching.
const instanceIdMatches = req.url.match(/fly_instance_id=(.*?)(?:&|$)/);
// No matches, bail.
if (!instanceIdMatches) return;
const TARGET_INSTANCE = instanceIdMatches[1];
if (FLY_INSTANCE_ID === TARGET_INSTANCE) return;
console.log(“Mismatch detected, replaying”,FLY_INSTANCE_ID);
console.log(TARGET_INSTANCE)
// Create a raw HTTP response with the fly-replay header.
// HTTP code 101 must be used to make the response replay correctly.
const headers = [
“HTTP/1.1 101 Switching Protocols”,
fly-replay: instance=${TARGET_INSTANCE}
,
];
// Send new headers and close the socket.
socket.end(headers.concat(“\r\n”).join(“\r\n”));
});
const io = require(‘socket.io’)(http)
Client:
const socket = io({
query: { fly_instance_id: getCookie(“mid”) },
extraHeaders: { “fly-force-instance-id”: getCookie(“mid”) }
});
Sometimes it works, probably when the socket connects to the correct machine but when i get a missmatch the server prints the console log missmatch but it doesn’t work. Any ideas?
Edit: I’m still trying to figure this out, the logs for the tow machines seem strange to me, i try to connect only one client and when i get a mismatch i get a connection on the other machine but the first machine also logs “connected” or in other cases the correct machine gets more than one connections. In both of these cases i get failed connection