feat: 用 SSE 替代 SWR 轮询,实现房间状态实时推送

SSE 断连时自动降级为 2s 轮询,重连后切回 SSE。
This commit is contained in:
2026-02-24 19:51:30 +08:00
parent f6949a062f
commit 8c0d89af6d
9 changed files with 223 additions and 71 deletions
+76
View File
@@ -0,0 +1,76 @@
import { buildRoomStatus } from "@/lib/buildRoomStatus";
import { subscribe } from "@/lib/roomEvents";
export const dynamic = "force-dynamic";
export async function GET(
req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params;
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
const send = (obj: object) => {
try {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify(obj)}\n\n`),
);
} catch {
/* controller already closed */
}
};
let alive = true;
(async () => {
const status = await buildRoomStatus(id);
if (!status) {
send({ error: "room_not_found" });
controller.close();
return;
}
if (alive) send(status);
})();
const unsubscribe = subscribe(id, async () => {
if (!alive) return;
try {
const status = await buildRoomStatus(id);
if (status && alive) send(status);
} catch {
/* ignore transient read errors */
}
});
const heartbeat = setInterval(() => {
try {
controller.enqueue(encoder.encode(": heartbeat\n\n"));
} catch {
clearInterval(heartbeat);
}
}, 30_000);
req.signal.addEventListener("abort", () => {
alive = false;
unsubscribe();
clearInterval(heartbeat);
try {
controller.close();
} catch {
/* already closed */
}
});
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
});
}