// PEP-326: pages of the live site did not refresh by themselves. The web container was started with a // bare `next start` (PEP-222) while pages open a WebSocket to /api/ws that only the web's own server // answers (apps/web/server.ts, PEP-225). The handshake hung until Cloudflare cut it (~125 s), the tab // tried three times and only then went to the SSE fallback: about six minutes of «подключение…» for // every fresh tab. Found on 2026-11-28 while checking «Принять»: the acceptance screen kept saying // «Принимается…» after the server had finished. import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { createServer, type IncomingMessage, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import type { Duplex } from "node:stream"; import { afterEach, beforeEach, describe, mock, test } from "node:test"; import { promisify } from "node:util"; import { createLiveWs, type LiveWs } from "@peppa/runner/live-ws"; const path = (p: string) => new URL(`../../../${p}`, import.meta.url).pathname; const read = (p: string) => readFileSync(path(p), "utf8"); const run = promisify(execFile); describe("PEP-326: сайт в Docker отвечает на постоянное соединение страниц", () => { test("Сценарий: сервис web запускается через свой сервер веба, а не голым next start", () => { const compose = read("infra/docker-compose.yml"); const web = compose.slice(compose.indexOf("\n web:"), compose.indexOf("\n bot:")); assert.match(web, /command: \["sh", "-c", "cd apps\/web && exec node server\.ts -p \$\{PEPPA_WEB_PORT:-3100\}"\]/); assert.doesNotMatch(web.replace(/^\s*#.*$/gm, ""), /next start/, "a bare `next start` leaves /api/ws unanswered"); // The same server the package script starts; it hands /api/ws to the live channel. assert.match(read("apps/web/package.json"), /"start": "node server\.ts -p 3100"/); assert.match(read("apps/web/server.ts"), /req\.url\?\.split\("\?"\)\[0\] === "\/api\/ws"/); }); test("Сценарий: выкатка проверяет постоянное соединение до того, как запомнить версию рабочей", () => { execFileSync("bash", ["-n", path("scripts/platform-deploy.sh")]); execFileSync("bash", ["-n", path("scripts/lib/ws-check.sh")]); const deploy = read("scripts/platform-deploy.sh"); assert.match(deploy, /\. "\$ROOT\/scripts\/lib\/ws-check\.sh"/); const check = deploy.indexOf('ws_answers "$LOCAL_URL" || rollback'); assert.ok(check > 0, "no answer on /api/ws of the container is a failed deploy"); assert.ok(check < deploy.indexOf('echo "$SHORT" >"$PREV_FILE"'), "the check comes before the version is recorded as good"); // The way from outside (Cloudflare, the edge) is not the release's fault: reported, not rolled back. assert.match(deploy, /ws_answers "\$URL" \d+ \|\| say /); }); describe("проверка ws_answers на настоящих соединениях", () => { let server: Server; let live: LiveWs | null = null; let base = ""; const sockets = new Set(); const start = async (onUpgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => void) => { server = createServer((_req, res) => res.writeHead(200).end("ok")); server.on("upgrade", (req, socket, head) => { sockets.add(socket); socket.on("error", () => {}); onUpgrade(req, socket, head); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }; afterEach(async () => { live?.close(); live = null; for (const s of sockets) s.destroy(); sockets.clear(); await new Promise((r) => server.close(() => r())); }); const answers = (url: string, sec: number) => run("bash", ["-c", `. "${path("scripts/lib/ws-check.sh")}"; ws_answers "$1" "$2"`, "ws-check", url, String(sec)]).then( () => true, () => false, ); test("Сценарий: свой сервер веба — настоящий канал страниц принимает запрос проверки (101)", async () => { // The same hand-off as apps/web/server.ts: `upgrade` → the live channel (a tab without a sign-in is let in). const ws = (live = createLiveWs({ db: null as never, authenticate: async () => null, anonymous: true })); await start((req, socket, head) => ws.handleUpgrade(req, socket, head)); assert.equal(await answers(base, 2), true, "the channel refuses a malformed handshake (key, origin) — the check must send a valid one"); assert.equal(await answers(`${base}/`, 2), true, "a trailing slash in the address changes nothing"); }); test("Сценарий: голый next start — запрос соединения висит без ответа — проверка не пройдена за отведённое время", async () => { await start(() => {}); const t0 = Date.now(); assert.equal(await answers(base, 2), false); assert.ok(Date.now() - t0 < 6000, "the check gives up by itself"); }); test("Сценарий: соединение отклонено (503: канал не зарегистрирован) — проверка не пройдена", async () => { await start((_req, socket) => socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n")); assert.equal(await answers(base, 2), false); }); }); }); // ── The tab's client (apps/web/lib/live.ts) with a fake WebSocket and EventSource ────────────────── class FakeWs { static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3; static made: FakeWs[] = []; readyState = 0; sent: string[] = []; closedByClient = false; onopen: (() => void) | null = null; onclose: (() => void) | null = null; onmessage: ((m: { data: string }) => void) | null = null; onerror: (() => void) | null = null; url: string; constructor(url: string) { this.url = url; FakeWs.made.push(this); } send(s: string) { this.sent.push(s); } close() { if (this.readyState === 3) return; this.closedByClient = true; this.fail(); } /** The server accepted the upgrade. */ open() { this.readyState = 1; this.onopen?.(); } /** The handshake was refused or the connection dropped. */ fail() { if (this.readyState === 3) return; this.readyState = 3; this.onclose?.(); } } class FakeEs { static CLOSED = 2; static made: FakeEs[] = []; readyState = 0; closed = false; onerror: (() => void) | null = null; url: string; private listeners = new Map void>>(); constructor(url: string) { this.url = url; FakeEs.made.push(this); } addEventListener(type: string, fn: (e: { data: string }) => void) { this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]); } close() { this.closed = true; } emit(type: string, data = "{}") { for (const fn of this.listeners.get(type) ?? []) fn({ data }); } } const g = globalThis as Record; const { liveClient } = (await import(new URL("../../../apps/web/lib/live.ts", import.meta.url).href)) as typeof import("../../../apps/web/lib/live.ts"); describe("PEP-326: зависшее постоянное соединение — сразу запасной поток", () => { const saved: Record = {}; const NAMES = ["document", "window", "location", "WebSocket", "EventSource"]; beforeEach(() => { FakeWs.made = []; FakeEs.made = []; delete g.__peppaLive; for (const n of NAMES) saved[n] = Object.getOwnPropertyDescriptor(globalThis, n); const set = (n: string, value: unknown) => Object.defineProperty(globalThis, n, { value, configurable: true, writable: true }); set("document", { visibilityState: "visible", addEventListener() {} }); set("window", { addEventListener() {} }); set("location", { protocol: "https:", host: "forge.test" }); set("WebSocket", FakeWs); set("EventSource", FakeEs); mock.timers.enable({ apis: ["setTimeout", "setInterval"] }); }); afterEach(() => { mock.timers.reset(); delete g.__peppaLive; for (const n of NAMES) { if (saved[n]) Object.defineProperty(globalThis, n, saved[n]!); else delete g[n]; } }); test("Сценарий: сервер не отвечает на запрос соединения — через 4 секунды страница на запасном потоке и «в реальном времени»", () => { const live = liveClient(); live.subscribe("home", () => {}); assert.equal(FakeWs.made.length, 1); assert.equal(FakeWs.made[0]!.url, "wss://forge.test/api/ws"); assert.equal(live.mode, "connecting"); mock.timers.tick(3900); assert.equal(FakeEs.made.length, 0, "a slow handshake still has time"); assert.equal(FakeWs.made[0]!.closedByClient, false); mock.timers.tick(200); assert.equal(FakeWs.made[0]!.closedByClient, true, "the hanging handshake is given up"); mock.timers.tick(60); assert.equal(FakeWs.made.length, 1, "no second and third try of two minutes each"); assert.equal(FakeEs.made.length, 1, "the SSE fallback is opened at once"); assert.match(FakeEs.made[0]!.url, /^\/api\/live\?scope=home/); FakeEs.made[0]!.emit("ready"); assert.equal(live.mode, "live"); // The WebSocket is tried again every minute; a try that hangs too is dropped and the page stays live. mock.timers.tick(60_000); assert.equal(FakeWs.made.length, 2); mock.timers.tick(4100); assert.equal(FakeWs.made[1]!.closedByClient, true); assert.equal(live.mode, "live"); assert.equal(FakeEs.made.length, 1); assert.equal(FakeEs.made[0]!.closed, false); }); test("Сценарий: соединение открылось за секунду — его никто не рвёт, запасной поток не нужен", () => { const live = liveClient(); live.subscribe("home", () => {}); mock.timers.tick(1000); FakeWs.made[0]!.open(); assert.equal(live.mode, "live"); assert.deepEqual(FakeWs.made[0]!.sent.map((s) => JSON.parse(s).t), ["sub"]); mock.timers.tick(10_000); assert.equal(FakeWs.made[0]!.closedByClient, false); assert.equal(FakeWs.made.length, 1); assert.equal(FakeEs.made.length, 0); assert.equal(live.mode, "live"); }); test("Сценарий: соединение работало, а после обрыва запрос повис — запасной поток, а не вечное «переподключение…»", () => { const live = liveClient(); live.subscribe("home", () => {}); FakeWs.made[0]!.open(); FakeWs.made[0]!.fail(); assert.equal(live.mode, "reconnecting"); mock.timers.tick(1300); assert.equal(FakeWs.made.length, 2, "the reconnect is tried"); mock.timers.tick(4100); assert.equal(FakeWs.made[1]!.closedByClient, true); mock.timers.tick(60); assert.equal(FakeEs.made.length, 1); FakeEs.made[0]!.emit("ready"); assert.equal(live.mode, "live"); }); test("Сценарий: запрос соединения отклоняют сразу — как раньше, три попытки и запасной поток", () => { const live = liveClient(); live.subscribe("home", () => {}); FakeWs.made[0]!.fail(); assert.equal(FakeEs.made.length, 0); mock.timers.tick(1300); assert.equal(FakeWs.made.length, 2); FakeWs.made[1]!.fail(); mock.timers.tick(2600); assert.equal(FakeWs.made.length, 3); FakeWs.made[2]!.fail(); mock.timers.tick(60); assert.equal(FakeEs.made.length, 1); FakeEs.made[0]!.emit("ready"); assert.equal(live.mode, "live"); }); });