Generated
+24
-24
@@ -44,7 +44,7 @@
|
|||||||
"@radix-ui/react-toggle-group": "^1.1.10",
|
"@radix-ui/react-toggle-group": "^1.1.10",
|
||||||
"@radix-ui/react-tooltip": "^1.2.7",
|
"@radix-ui/react-tooltip": "^1.2.7",
|
||||||
"@supabase/ssr": "^0.8.0",
|
"@supabase/ssr": "^0.8.0",
|
||||||
"@supabase/supabase-js": "^2.94.1",
|
"@supabase/supabase-js": "^2.95.3",
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
"@uiw/codemirror-theme-vscode": "^4.25.4",
|
"@uiw/codemirror-theme-vscode": "^4.25.4",
|
||||||
"@uiw/react-codemirror": "^4.25.4",
|
"@uiw/react-codemirror": "^4.25.4",
|
||||||
@@ -3461,9 +3461,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/auth-js": {
|
"node_modules/@supabase/auth-js": {
|
||||||
"version": "2.94.1",
|
"version": "2.95.3",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.94.1.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.95.3.tgz",
|
||||||
"integrity": "sha512-Wt/SdmAtNNiqrcBbPlzWojLcE1bQ9OYb8PTaYF6QccFX5JeXZI0sZ01MLNE+E83UK6cK0lw4YznX0D2g08UQng==",
|
"integrity": "sha512-vD2YoS8E2iKIX0F7EwXTmqhUpaNsmbU6X2R0/NdFcs02oEfnHyNP/3M716f3wVJ2E5XHGiTFXki6lRckhJ0Thg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "2.8.1"
|
"tslib": "2.8.1"
|
||||||
@@ -3473,9 +3473,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/functions-js": {
|
"node_modules/@supabase/functions-js": {
|
||||||
"version": "2.94.1",
|
"version": "2.95.3",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.94.1.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.95.3.tgz",
|
||||||
"integrity": "sha512-A7Bx0gnclDNZ4m8+mnO2IEEzMxtUSg7cpPEBF6Ek1LpjIQkC7vvoidiV/RuntnKX43IiVcWV1f2FsAppMagEmQ==",
|
"integrity": "sha512-uTuOAKzs9R/IovW1krO0ZbUHSJnsnyJElTXIRhjJTqymIVGcHzkAYnBCJqd7468Fs/Foz1BQ7Dv6DCl05lr7ig==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "2.8.1"
|
"tslib": "2.8.1"
|
||||||
@@ -3485,9 +3485,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/postgrest-js": {
|
"node_modules/@supabase/postgrest-js": {
|
||||||
"version": "2.94.1",
|
"version": "2.95.3",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.94.1.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.95.3.tgz",
|
||||||
"integrity": "sha512-N6MTghjHnMZddT48rAj8dIFgedCU97cc1ahQM74Tc+DF4UH7y2+iEfdYV3unJsylpaiWlu92Fy8Lj14Jbrmxog==",
|
"integrity": "sha512-LTrRBqU1gOovxRm1vRXPItSMPBmEFqrfTqdPTRtzOILV4jPSueFz6pES5hpb4LRlkFwCPRmv3nQJ5N625V2Xrg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "2.8.1"
|
"tslib": "2.8.1"
|
||||||
@@ -3497,9 +3497,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/realtime-js": {
|
"node_modules/@supabase/realtime-js": {
|
||||||
"version": "2.94.1",
|
"version": "2.95.3",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.94.1.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.95.3.tgz",
|
||||||
"integrity": "sha512-Wq8olpCAGmN4y2DH2kUdlcakdzNHRCde72BFS8zK5ub46bBeSUoE9DqrfeNFWKaF2gCE/cmK8aTUTorZD9jdtQ==",
|
"integrity": "sha512-D7EAtfU3w6BEUxDACjowWNJo/ZRo7sDIuhuOGKHIm9FHieGeoJV5R6GKTLtga/5l/6fDr2u+WcW/m8I9SYmaIw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/phoenix": "^1.6.6",
|
"@types/phoenix": "^1.6.6",
|
||||||
@@ -3524,9 +3524,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/storage-js": {
|
"node_modules/@supabase/storage-js": {
|
||||||
"version": "2.94.1",
|
"version": "2.95.3",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.94.1.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.95.3.tgz",
|
||||||
"integrity": "sha512-/Mi18LGyrugPwtfqETfAqEGcBQotY/7IMsTGYgEFdqr8cQq280BVQWjN2wI9KibWtshPp0Ryvil5Uzd5YfM7kA==",
|
"integrity": "sha512-4GxkJiXI3HHWjxpC3sDx1BVrV87O0hfX+wvJdqGv67KeCu+g44SPnII8y0LL/Wr677jB7tpjAxKdtVWf+xhc9A==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"iceberg-js": "^0.8.1",
|
"iceberg-js": "^0.8.1",
|
||||||
@@ -3537,16 +3537,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/supabase-js": {
|
"node_modules/@supabase/supabase-js": {
|
||||||
"version": "2.94.1",
|
"version": "2.95.3",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.94.1.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.95.3.tgz",
|
||||||
"integrity": "sha512-87vOY8n3WHB3m+a/KeySj07djOQVuRA5qgX5E7db1eDkaZ1of5M+3t/tv6eYYy4BfqxuHMZuCe5uVrO/oyvoow==",
|
"integrity": "sha512-Fukw1cUTQ6xdLiHDJhKKPu6svEPaCEDvThqCne3OaQyZvuq2qjhJAd91kJu3PXLG18aooCgYBaB6qQz35hhABg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@supabase/auth-js": "2.94.1",
|
"@supabase/auth-js": "2.95.3",
|
||||||
"@supabase/functions-js": "2.94.1",
|
"@supabase/functions-js": "2.95.3",
|
||||||
"@supabase/postgrest-js": "2.94.1",
|
"@supabase/postgrest-js": "2.95.3",
|
||||||
"@supabase/realtime-js": "2.94.1",
|
"@supabase/realtime-js": "2.95.3",
|
||||||
"@supabase/storage-js": "2.94.1"
|
"@supabase/storage-js": "2.95.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.0.0"
|
"node": ">=20.0.0"
|
||||||
|
|||||||
+1
-1
@@ -44,7 +44,7 @@
|
|||||||
"@radix-ui/react-toggle-group": "^1.1.10",
|
"@radix-ui/react-toggle-group": "^1.1.10",
|
||||||
"@radix-ui/react-tooltip": "^1.2.7",
|
"@radix-ui/react-tooltip": "^1.2.7",
|
||||||
"@supabase/ssr": "^0.8.0",
|
"@supabase/ssr": "^0.8.0",
|
||||||
"@supabase/supabase-js": "^2.94.1",
|
"@supabase/supabase-js": "^2.95.3",
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
"@uiw/codemirror-theme-vscode": "^4.25.4",
|
"@uiw/codemirror-theme-vscode": "^4.25.4",
|
||||||
"@uiw/react-codemirror": "^4.25.4",
|
"@uiw/react-codemirror": "^4.25.4",
|
||||||
|
|||||||
+138
-146
@@ -4,65 +4,101 @@ import { createClientCookie } from "@/lib/supabase/server";
|
|||||||
import { getSession } from "@/modules/account/core";
|
import { getSession } from "@/modules/account/core";
|
||||||
import * as Core from "@/modules/live-run/core";
|
import * as Core from "@/modules/live-run/core";
|
||||||
import { ClientMessage } from "./types";
|
import { ClientMessage } from "./types";
|
||||||
import { NextRequest } from "next/server";
|
|
||||||
import { redis } from "@/lib/redis";
|
import { redis } from "@/lib/redis";
|
||||||
|
import { User } from "@supabase/supabase-js";
|
||||||
export function GET(req: NextRequest) {
|
import { UserProfile } from "@/modules/user/types";
|
||||||
const headers = new Headers();
|
import { NextRequest } from "next/server";
|
||||||
headers.set("Connection", "Upgrade");
|
|
||||||
headers.set("Upgrade", "websocket");
|
|
||||||
return new Response("Upgrade Required", { status: 426, headers });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
||||||
client.once("message", async (raw) => {
|
let authenticated = false;
|
||||||
const {
|
let session: [User, UserProfile] | null = null;
|
||||||
cookies,
|
let currentRun: string | undefined;
|
||||||
requestId,
|
|
||||||
}: { cookies: Record<string, string>; requestId: string } = JSON.parse(
|
|
||||||
raw.toString(),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!cookies) {
|
// Heartbeat
|
||||||
client.send(JSON.stringify({ ok: false, error: "Missing cookies" }));
|
let isAlive = true;
|
||||||
|
const heartbeat = setInterval(() => {
|
||||||
|
if (!isAlive) {
|
||||||
|
console.log("Client did not respond to ping, terminating");
|
||||||
|
return closeClient("Heartbeat timeout");
|
||||||
|
}
|
||||||
|
isAlive = false;
|
||||||
|
if (client.readyState === WebSocket.OPEN) client.ping();
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
|
client.on("pong", () => {
|
||||||
|
isAlive = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const closeClient = (reason?: string) => {
|
||||||
|
if (reason) console.warn("Closing client:", reason);
|
||||||
|
try {
|
||||||
client.close();
|
client.close();
|
||||||
return;
|
setTimeout(() => {
|
||||||
|
if (client.readyState !== WebSocket.CLOSED) client.terminate();
|
||||||
|
}, 1000);
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanupRun = async () => {
|
||||||
|
if (currentRun) {
|
||||||
|
try {
|
||||||
|
await Core.removeLiveRun(currentRun);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error cleaning up run:", err);
|
||||||
}
|
}
|
||||||
|
currentRun = undefined;
|
||||||
const supabase = await createClientCookie(new Map(Object.entries(cookies)));
|
|
||||||
const session = await getSession(supabase);
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
client.send(JSON.stringify({ ok: false, error: "Invalid session" }));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
client.send(JSON.stringify({ requestId, ok: true }));
|
|
||||||
|
|
||||||
console.log(`User ${session[1].username} connected to live run`);
|
|
||||||
|
|
||||||
client.on("message", async (raw) => {
|
client.on("message", async (raw) => {
|
||||||
|
let requestId: string | undefined;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { requestId, ...msg }: ClientMessage = JSON.parse(raw.toString());
|
const msg = JSON.parse(raw.toString());
|
||||||
|
requestId = msg.requestId;
|
||||||
|
|
||||||
switch (msg.type) {
|
// AUTHENTICATION
|
||||||
/* ---------------- CREATE ---------------- */
|
if (!authenticated) {
|
||||||
|
const { cookies } = msg as { cookies?: Record<string, string> };
|
||||||
|
if (!cookies) return closeClient("Missing cookies");
|
||||||
|
|
||||||
|
const supabase = await createClientCookie(
|
||||||
|
new Map(Object.entries(cookies)),
|
||||||
|
);
|
||||||
|
session = await getSession(supabase);
|
||||||
|
if (!session) return closeClient("Invalid session");
|
||||||
|
|
||||||
|
authenticated = true;
|
||||||
|
return client.send(JSON.stringify({ requestId, ok: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!session) return closeClient("Session unexpectedly null");
|
||||||
|
|
||||||
|
// POST-AUTH MESSAGE HANDLING
|
||||||
|
const { type, ...payload } = msg as ClientMessage;
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
case "create": {
|
case "create": {
|
||||||
const { problem, category } = msg;
|
const { problem, category } = payload as any;
|
||||||
|
if (!problem || !category)
|
||||||
if (!problem || !category) {
|
return client.send(
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
requestId,
|
requestId,
|
||||||
ok: false,
|
ok: false,
|
||||||
error: "problem and category required",
|
error: "problem and category required",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return;
|
if (currentRun)
|
||||||
}
|
return client.send(
|
||||||
|
JSON.stringify({
|
||||||
|
requestId,
|
||||||
|
ok: false,
|
||||||
|
error:
|
||||||
|
"Cannot do multiple runs, delete/submit current run first",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const runId = randomUUID();
|
const runId = randomUUID();
|
||||||
|
|
||||||
await Core.addLiveRun({
|
await Core.addLiveRun({
|
||||||
id: runId,
|
id: runId,
|
||||||
problem,
|
problem,
|
||||||
@@ -73,7 +109,8 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
|||||||
runsCount: 0,
|
runsCount: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
client.send(
|
currentRun = runId;
|
||||||
|
return client.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
requestId,
|
requestId,
|
||||||
ok: true,
|
ok: true,
|
||||||
@@ -81,41 +118,29 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
|||||||
data: { runId },
|
data: { runId },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------------- DELETE ---------------- */
|
|
||||||
case "move": {
|
case "move": {
|
||||||
const { runId, moves, file, language } = msg;
|
if (!currentRun)
|
||||||
|
return client.send(
|
||||||
|
JSON.stringify({ requestId, ok: false, error: "No current run" }),
|
||||||
|
);
|
||||||
|
|
||||||
if (
|
const { moves, file, language } = payload as any;
|
||||||
!runId ||
|
if (!moves || file === undefined || language === undefined)
|
||||||
!moves ||
|
return client.send(
|
||||||
file === undefined ||
|
|
||||||
language === undefined
|
|
||||||
) {
|
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
requestId,
|
requestId,
|
||||||
ok: false,
|
ok: false,
|
||||||
error: "body requires runId, moves, file and language",
|
error: "moves, file, and language required",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const liveRun = await Core.getLiveRun(runId);
|
const liveRun = await Core.getLiveRun(currentRun);
|
||||||
|
if (!liveRun)
|
||||||
if (!liveRun) {
|
return client.send(
|
||||||
client.send(
|
JSON.stringify({ requestId, ok: false, error: "Run not live" }),
|
||||||
JSON.stringify({
|
|
||||||
requestId,
|
|
||||||
ok: false,
|
|
||||||
error: "Run is not live or does not exist",
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const run = await Core.addLiveRunEvent(
|
const run = await Core.addLiveRunEvent(
|
||||||
liveRun.id,
|
liveRun.id,
|
||||||
@@ -123,103 +148,59 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
|||||||
language,
|
language,
|
||||||
moves,
|
moves,
|
||||||
);
|
);
|
||||||
|
return client.send(
|
||||||
client.send(
|
JSON.stringify({ requestId, ok: true, type: "move", data: run }),
|
||||||
JSON.stringify({
|
|
||||||
requestId,
|
|
||||||
ok: true,
|
|
||||||
type: "move",
|
|
||||||
data: run,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------------- SUBMIT ---------------- */
|
|
||||||
case "submit": {
|
case "submit": {
|
||||||
const { runId } = msg;
|
if (!currentRun)
|
||||||
|
return client.send(
|
||||||
|
JSON.stringify({ requestId, ok: false, error: "No current run" }),
|
||||||
|
);
|
||||||
|
|
||||||
if (!runId) {
|
const liveRun = await Core.getLiveRun(currentRun);
|
||||||
client.send(
|
if (!liveRun)
|
||||||
JSON.stringify({
|
return client.send(
|
||||||
requestId,
|
JSON.stringify({ requestId, ok: false, error: "Run not live" }),
|
||||||
ok: false,
|
);
|
||||||
error: "runId required",
|
|
||||||
}),
|
const run = await Core.submitRun(liveRun, session[0].id);
|
||||||
|
currentRun = undefined;
|
||||||
|
return client.send(
|
||||||
|
JSON.stringify({ requestId, ok: true, type: "submit", data: run }),
|
||||||
);
|
);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const liveRun = await Core.getLiveRun(runId);
|
|
||||||
|
|
||||||
if (!liveRun) {
|
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
|
||||||
requestId,
|
|
||||||
ok: false,
|
|
||||||
error: "Run is not live or does not exist",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const run = await Core.submitRun(supabase, liveRun, session[0].id);
|
|
||||||
|
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
|
||||||
requestId,
|
|
||||||
ok: true,
|
|
||||||
type: "submit",
|
|
||||||
data: run,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------- DELETE ---------------- */
|
|
||||||
case "delete": {
|
case "delete": {
|
||||||
const { runId } = msg;
|
if (!currentRun)
|
||||||
|
return client.send(
|
||||||
if (!runId) {
|
JSON.stringify({ requestId, ok: false, error: "No current run" }),
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
|
||||||
requestId,
|
|
||||||
ok: false,
|
|
||||||
error: "runId required",
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const run = await Core.removeLiveRun(runId);
|
await cleanupRun();
|
||||||
|
return client.send(
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
requestId,
|
requestId,
|
||||||
ok: true,
|
ok: true,
|
||||||
type: "delete",
|
type: "delete",
|
||||||
data: run,
|
data: { id: currentRun },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case "getText":
|
case "getText": {
|
||||||
const { runId } = msg;
|
if (!currentRun)
|
||||||
const data = await redis.get(`liveRunText:${runId}`);
|
return client.send(
|
||||||
|
JSON.stringify({ requestId, ok: false, error: "No current run" }),
|
||||||
client.send(
|
|
||||||
JSON.stringify({
|
|
||||||
requestId,
|
|
||||||
ok: true,
|
|
||||||
data,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
break;
|
|
||||||
|
const data = await redis.get(`liveRunText:${currentRun}`);
|
||||||
|
return client.send(JSON.stringify({ requestId, ok: true, data }));
|
||||||
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
client.send(
|
return client.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
requestId,
|
requestId,
|
||||||
ok: false,
|
ok: false,
|
||||||
@@ -229,18 +210,29 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
if (requestId)
|
||||||
client.send(
|
client.send(
|
||||||
JSON.stringify({
|
JSON.stringify({ requestId, ok: false, error: "Malformed message" }),
|
||||||
requestId,
|
|
||||||
ok: false,
|
|
||||||
error: "Malformed message",
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
closeClient("Malformed message");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
client.on("close", async () => {
|
||||||
|
clearInterval(heartbeat);
|
||||||
|
await cleanupRun();
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on("close", () => {
|
client.on("error", (err) => {
|
||||||
// optional cleanup
|
console.error("WebSocket error:", err);
|
||||||
|
clearInterval(heartbeat);
|
||||||
|
closeClient("WebSocket error");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GET(req: NextRequest) {
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.set("Connection", "Upgrade");
|
||||||
|
headers.set("Upgrade", "websocket");
|
||||||
|
return new Response("Upgrade Required", { status: 426, headers });
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,67 +1,63 @@
|
|||||||
|
// ws/liveRun.ts
|
||||||
import { WebSocketServer, WebSocket } from "ws";
|
import { WebSocketServer, WebSocket } from "ws";
|
||||||
import Redis from "ioredis";
|
import { NextRequest } from "next/server";
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
|
||||||
import { LiveRunEvent } from "@/modules/live-run/types";
|
import { LiveRunEvent } from "@/modules/live-run/types";
|
||||||
import { updateLiveRunViews } from "@/modules/live-run/core";
|
import { updateLiveRunViews } from "@/modules/live-run/core";
|
||||||
import { redis } from "@/lib/redis";
|
import { redis, redisSubscriber } from "@/lib/redis";
|
||||||
|
|
||||||
export function GET(req: NextRequest) {
|
// Map of runId → Set of WebSockets
|
||||||
const headers = new Headers();
|
const runSubscribers: Map<string, Set<WebSocket>> = new Map();
|
||||||
headers.set("Connection", "Upgrade");
|
|
||||||
headers.set("Upgrade", "websocket");
|
|
||||||
return new Response("Upgrade Required", { status: 426, headers });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
// Handle incoming Pub/Sub messages
|
||||||
const subscriber = new Redis(process.env.REDIS_URL!);
|
redisSubscriber.on("message", (channel, message) => {
|
||||||
|
const runId = channel.split(":")[1];
|
||||||
|
const sockets = runSubscribers.get(runId);
|
||||||
|
if (!sockets) return;
|
||||||
|
|
||||||
|
const data: LiveRunEvent = JSON.parse(message);
|
||||||
|
|
||||||
|
sockets.forEach((ws) => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({ ...data, text: null }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
||||||
let runId: string;
|
let runId: string;
|
||||||
|
|
||||||
|
// Receive runId from client
|
||||||
client.once("message", async (message) => {
|
client.once("message", async (message) => {
|
||||||
runId = message.toString();
|
runId = message.toString();
|
||||||
|
|
||||||
|
// Track view count
|
||||||
await updateLiveRunViews(runId, 1);
|
await updateLiveRunViews(runId, 1);
|
||||||
|
|
||||||
let lastEvent: LiveRunEvent | null = null;
|
// Send initial text
|
||||||
|
|
||||||
const sendText = async () => {
|
|
||||||
const text = await redis.get(`liveRunText:${runId}`);
|
const text = await redis.get(`liveRunText:${runId}`);
|
||||||
|
|
||||||
if (client.readyState === WebSocket.OPEN) {
|
|
||||||
client.send(
|
client.send(
|
||||||
JSON.stringify({
|
JSON.stringify({ file: null, language: null, moves: [], text }),
|
||||||
file: lastEvent?.file,
|
|
||||||
language: lastEvent?.language,
|
|
||||||
moves: [],
|
|
||||||
text,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Add WebSocket to subscribers
|
||||||
|
if (!runSubscribers.has(runId)) {
|
||||||
|
runSubscribers.set(runId, new Set());
|
||||||
|
await redisSubscriber.subscribe(`liveRunEvent:${runId}`);
|
||||||
}
|
}
|
||||||
};
|
runSubscribers.get(runId)!.add(client);
|
||||||
|
|
||||||
sendText();
|
|
||||||
|
|
||||||
client.on("message", sendText);
|
|
||||||
|
|
||||||
subscriber.subscribe(`liveRunEvent:${runId}`, (err, count) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Failed to subscribe", err);
|
|
||||||
client.close(1011, "Redis subscription failed");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
subscriber.on("message", (channel, message) => {
|
|
||||||
const data: LiveRunEvent = JSON.parse(message);
|
|
||||||
|
|
||||||
lastEvent = data;
|
|
||||||
if (client.readyState === WebSocket.OPEN) {
|
|
||||||
client.send(JSON.stringify({ ...data, text: null }));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Handle client disconnect
|
||||||
client.once("close", async () => {
|
client.once("close", async () => {
|
||||||
await subscriber.unsubscribe(`liveRunEvent:${runId}`);
|
const set = runSubscribers.get(runId);
|
||||||
subscriber.quit();
|
if (set) {
|
||||||
|
set.delete(client);
|
||||||
|
if (set.size === 0) {
|
||||||
|
await redisSubscriber.unsubscribe(`liveRunEvent:${runId}`);
|
||||||
|
runSubscribers.delete(runId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await updateLiveRunViews(runId, -1);
|
await updateLiveRunViews(runId, -1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -69,3 +65,10 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
|
|||||||
console.error("WebSocket error:", err);
|
console.error("WebSocket error:", err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GET(req: NextRequest) {
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.set("Connection", "Upgrade");
|
||||||
|
headers.set("Upgrade", "websocket");
|
||||||
|
return new Response("Upgrade Required", { status: 426, headers });
|
||||||
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ const LeaderboardRow = ({
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
{/* Wins */}
|
{/* World Records */}
|
||||||
<td className="py-4 px-4 text-center font-mono font-semibold text-primary">
|
<td className="py-4 px-4 text-center font-mono font-semibold text-primary">
|
||||||
{run.wins}
|
{run.wins}
|
||||||
</td>
|
</td>
|
||||||
|
|||||||
@@ -78,9 +78,9 @@ export default function Leaderboard() {
|
|||||||
{/* Runner / Username */}
|
{/* Runner / Username */}
|
||||||
<TableHead className="py-4 px-4 text-left">Runner</TableHead>
|
<TableHead className="py-4 px-4 text-left">Runner</TableHead>
|
||||||
|
|
||||||
{/* Wins */}
|
{/* World Records */}
|
||||||
<TableHead className="py-4 px-4 w-24 text-center">
|
<TableHead className="py-4 px-4 w-24 text-center">
|
||||||
Wins
|
World Records
|
||||||
</TableHead>
|
</TableHead>
|
||||||
|
|
||||||
{/* Podiums */}
|
{/* Podiums */}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export default function LiveRunRow({
|
|||||||
const [problem] = useAction(() => getProblem(run.problem));
|
const [problem] = useAction(() => getProblem(run.problem));
|
||||||
|
|
||||||
const now = new Date().getTime() + 1000;
|
const now = new Date().getTime() + 1000;
|
||||||
const isTop = run.views > 5;
|
const isTop = run.views >= 5;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TableRow
|
<TableRow
|
||||||
|
|||||||
+19
-4
@@ -9,15 +9,30 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
} from "@/components/ui/table";
|
} from "@/components/ui/table";
|
||||||
import LiveRunRow from "./components/LiveRunRow";
|
import LiveRunRow from "./components/LiveRunRow";
|
||||||
import useAction, { useActionInterval } from "@/hook/use-action";
|
import { useActionInterval } from "@/hook/use-action";
|
||||||
import { getLiveRuns } from "@/modules/live-run/actions";
|
import { getLiveRuns } from "@/modules/live-run/actions";
|
||||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||||
|
|
||||||
export default function LiveRuns() {
|
export default function LiveRuns() {
|
||||||
const [liveRuns] = useActionInterval(getLiveRuns, 1500);
|
const [liveRuns] = useActionInterval(getLiveRuns, 1500);
|
||||||
|
|
||||||
// Sort top runners (status === 'pb') to the top
|
const sortedRuns = (liveRuns || []).sort((a, b) => {
|
||||||
const sortedRuns = [...(liveRuns || [])];
|
const aTrending = a.views >= 5;
|
||||||
|
const bTrending = b.views >= 5;
|
||||||
|
|
||||||
|
if (aTrending && bTrending) {
|
||||||
|
// Both trending → sort by views descending, then timestamp descending
|
||||||
|
if (b.views !== a.views) return b.views - a.views;
|
||||||
|
return b.start - a.start;
|
||||||
|
} else if (aTrending) {
|
||||||
|
return -1; // a goes first
|
||||||
|
} else if (bTrending) {
|
||||||
|
return 1; // b goes first
|
||||||
|
} else {
|
||||||
|
// Neither trending → sort by timestamp descending
|
||||||
|
return b.start - a.start;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen pt-24 pb-16">
|
<div className="min-h-screen pt-24 pb-16">
|
||||||
@@ -26,7 +41,7 @@ export default function LiveRuns() {
|
|||||||
<div>
|
<div>
|
||||||
<h1 className="text-4xl font-bold">Live Runs</h1>
|
<h1 className="text-4xl font-bold">Live Runs</h1>
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
42 live runs · Streaming in real time
|
{liveRuns?.length} live runs · Streaming in real time
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,12 @@ import Redis from "ioredis";
|
|||||||
|
|
||||||
export const redis = new Redis(process.env.REDIS_URL!);
|
export const redis = new Redis(process.env.REDIS_URL!);
|
||||||
|
|
||||||
|
export const redisSubscriber = new Redis(process.env.REDIS_URL!);
|
||||||
|
|
||||||
redis.on("error", (err) => {
|
redis.on("error", (err) => {
|
||||||
console.error("Redis error:", err);
|
console.error("Redis error:", err);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
redisSubscriber.on("error", (err) => {
|
||||||
|
console.error("Redis subscriber error:", err);
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
"use server";
|
|
||||||
|
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
import { createServerClient, type CookieOptions } from "@supabase/ssr";
|
import { createServerClient, type CookieOptions } from "@supabase/ssr";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
import { createClient as createSimpleClient } from "@supabase/supabase-js";
|
||||||
|
|
||||||
export async function createClient() {
|
export async function createClient() {
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
@@ -46,3 +45,8 @@ export async function createClientCookie(cookies: Map<string, string>) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const supabaseApiClient = createSimpleClient(
|
||||||
|
process.env.SUPABASE_URL!,
|
||||||
|
process.env.SUPABASE_SECRET_KEY!,
|
||||||
|
);
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use server";
|
import "server-only";
|
||||||
|
|
||||||
import { SupabaseClient, User } from "@supabase/supabase-js";
|
import { SupabaseClient, User } from "@supabase/supabase-js";
|
||||||
import "server-only";
|
|
||||||
import { UserProfile } from "../user/types";
|
import { UserProfile } from "../user/types";
|
||||||
|
|
||||||
export async function signInWithGitHub(supabase: SupabaseClient) {
|
export async function signInWithGitHub(supabase: SupabaseClient) {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use server";
|
import "server-only";
|
||||||
|
|
||||||
import { SupabaseClient } from "@supabase/supabase-js";
|
import { SupabaseClient } from "@supabase/supabase-js";
|
||||||
import "server-only";
|
|
||||||
import { LeaderboardUser } from "./types";
|
import { LeaderboardUser } from "./types";
|
||||||
|
|
||||||
export async function getGlobalLeaderboard(
|
export async function getGlobalLeaderboard(
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
"use server";
|
|
||||||
|
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
import { LiveRun, LiveRunMove } from "./types";
|
import { LiveRun, LiveRunMove } from "./types";
|
||||||
import { SupabaseClient } from "@supabase/supabase-js";
|
|
||||||
import { redis } from "@/lib/redis";
|
import { redis } from "@/lib/redis";
|
||||||
import Redis from "ioredis";
|
|
||||||
import { applyMoves } from "@/lib/move";
|
import { applyMoves } from "@/lib/move";
|
||||||
|
import { supabaseApiClient } from "@/lib/supabase/server";
|
||||||
|
|
||||||
/** -------------------- Live Runs in Redis -------------------- */
|
/** -------------------- Live Runs in Redis -------------------- */
|
||||||
|
|
||||||
@@ -46,6 +44,7 @@ export async function updateLiveRunViews(
|
|||||||
): Promise<number | null> {
|
): Promise<number | null> {
|
||||||
const run = await getLiveRun(id);
|
const run = await getLiveRun(id);
|
||||||
if (!run) return null;
|
if (!run) return null;
|
||||||
|
if (run.views === 0 && increment < 0) return null;
|
||||||
run.views += increment;
|
run.views += increment;
|
||||||
await redis.set(`liveRun:${run.id}`, JSON.stringify(run));
|
await redis.set(`liveRun:${run.id}`, JSON.stringify(run));
|
||||||
return run.views;
|
return run.views;
|
||||||
@@ -65,7 +64,7 @@ export async function getLiveRuns(): Promise<LiveRun[]> {
|
|||||||
* Remove a live run from Redis
|
* Remove a live run from Redis
|
||||||
*/
|
*/
|
||||||
export async function removeLiveRun(id: string) {
|
export async function removeLiveRun(id: string) {
|
||||||
await redis.del(`liveRun:${id}`, `liveRunEvent:${id}`);
|
await redis.del(`liveRun:${id}`, `liveRunEvent:${id}`, `liveRunText:${id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** -------------------- Live Run Moves -------------------- */
|
/** -------------------- Live Run Moves -------------------- */
|
||||||
@@ -107,15 +106,11 @@ export async function addLiveRunEvent(
|
|||||||
* Submit a run to Supabase (persistent storage)
|
* Submit a run to Supabase (persistent storage)
|
||||||
* and remove it from Redis
|
* and remove it from Redis
|
||||||
*/
|
*/
|
||||||
export async function submitRun(
|
export async function submitRun(run: LiveRun, user_id: string) {
|
||||||
supabase: SupabaseClient,
|
|
||||||
run: LiveRun,
|
|
||||||
user_id: string,
|
|
||||||
) {
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const durationMs = now.getTime() - run.start;
|
const durationMs = now.getTime() - run.start;
|
||||||
|
|
||||||
const { data, error } = await supabase
|
const { data, error } = await supabaseApiClient
|
||||||
.from("runs")
|
.from("runs")
|
||||||
.insert([
|
.insert([
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
"use server";
|
|
||||||
|
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
import { Problem, ProblemDefinition } from "./types";
|
import { Problem, ProblemDefinition } from "./types";
|
||||||
|
|
||||||
const problems: ProblemDefinition[] = [
|
const problems: ProblemDefinition[] = [
|
||||||
|
|||||||
@@ -1,3 +1 @@
|
|||||||
"use server";
|
|
||||||
|
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|||||||
Reference in New Issue
Block a user