When build worker returns 404 for >30s or >10 polls, send failed status to client instead of polling forever. Also handled in status API.
89 lines
2.6 KiB
JavaScript
89 lines
2.6 KiB
JavaScript
// Wrapper: starts Next.js standalone, then attaches WebSocket to the same HTTP server
|
|
const http = require("http");
|
|
const { parse } = require("url");
|
|
const { WebSocketServer } = require("ws");
|
|
|
|
const BUILD_WORKER_URL = process.env.BUILD_WORKER_URL || "http://localhost:3001";
|
|
|
|
// Monkey-patch http.createServer to intercept the server Next.js creates
|
|
const origCreateServer = http.createServer;
|
|
let patched = false;
|
|
|
|
http.createServer = function (...args) {
|
|
const server = origCreateServer.apply(this, args);
|
|
|
|
if (!patched) {
|
|
patched = true;
|
|
const wss = new WebSocketServer({ noServer: true });
|
|
|
|
server.on("upgrade", (req, socket, head) => {
|
|
const { pathname } = parse(req.url || "");
|
|
const match = pathname?.match(/^\/ws\/build\/([a-f0-9]{24})$/);
|
|
if (!match) {
|
|
// Not our path — destroy (Next.js doesn't use WS in production)
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
|
|
const buildId = match[1];
|
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
handleBuildWs(ws, buildId);
|
|
});
|
|
});
|
|
|
|
console.log("[ws] WebSocket upgrade handler attached to Next.js server");
|
|
}
|
|
|
|
return server;
|
|
};
|
|
|
|
function handleBuildWs(ws, buildId) {
|
|
let closed = false;
|
|
ws.on("close", () => { closed = true; });
|
|
ws.on("error", () => { closed = true; });
|
|
|
|
let lastJson = "";
|
|
let notFoundCount = 0;
|
|
const startTime = Date.now();
|
|
|
|
const poll = async () => {
|
|
if (closed) return;
|
|
try {
|
|
const res = await fetch(`${BUILD_WORKER_URL}/build/${buildId}/status`);
|
|
if (!res.ok) {
|
|
notFoundCount++;
|
|
// If worker doesn't know this build after 30s, it's orphaned
|
|
if (res.status === 404 && (notFoundCount > 10 || Date.now() - startTime > 30000)) {
|
|
const failMsg = JSON.stringify({ status: "failed", message: "Build was lost during a server restart. Please try again.", progress: 0 });
|
|
try { ws.send(failMsg); } catch {}
|
|
try { ws.close(1000, "failed"); } catch {}
|
|
return;
|
|
}
|
|
if (!closed) setTimeout(poll, 2000);
|
|
return;
|
|
}
|
|
notFoundCount = 0;
|
|
const data = await res.json();
|
|
const json = JSON.stringify(data);
|
|
|
|
if (json !== lastJson) {
|
|
lastJson = json;
|
|
try { ws.send(json); } catch { closed = true; return; }
|
|
}
|
|
|
|
if (data.status === "completed" || data.status === "failed") {
|
|
try { ws.close(1000, data.status); } catch { /* ignore */ }
|
|
return;
|
|
}
|
|
} catch {
|
|
// Worker unreachable — retry
|
|
}
|
|
if (!closed) setTimeout(poll, 1000);
|
|
};
|
|
|
|
poll();
|
|
}
|
|
|
|
// Now load the real Next.js standalone server, which will call http.createServer
|
|
require("./server.js");
|