Compare commits

33 Commits
Author SHA1 Message Date
selimaj-dev d3dac4baeb Merge pull request #21 from orus-dev/bug-patches
Bug patches
2026-02-17 07:04:51 -08:00
selimaj-dev 9290998092 Small thing 2026-02-17 16:03:23 +01:00
selimaj-dev 75c09dfc58 Fixed use server structure on core 2026-02-17 03:39:54 +01:00
selimaj-dev 49ed1a5f36 ping pong 2026-02-17 03:34:30 +01:00
selimaj-dev cbd41d9e37 Refactored /api/run 2026-02-17 03:27:26 +01:00
selimaj-dev abda0b52af Current run management 2026-02-17 02:50:57 +01:00
selimaj-dev 7ec8b9ae4d Max redis clients fix 2026-02-17 02:38:53 +01:00
selimaj-dev de07f634f9 Views fix 2026-02-17 02:23:13 +01:00
selimaj-dev bd54227a98 Sorted live runs 2026-02-17 02:18:22 +01:00
selimaj-dev 0c9c86848e Slight rename in leaderboards 2026-02-17 01:59:54 +01:00
selimaj-dev af464fa3a1 Text stability sync 2026-02-16 01:38:53 +01:00
selimaj-dev d5cc2f47a3 Merge pull request #20 from orus-dev/full-websocket-system
Full websocket system (for running)
2026-02-15 16:11:33 -08:00
selimaj-dev 5a0c83c4c1 Working request id response 2026-02-16 01:01:29 +01:00
selimaj-dev b2ba4fbcc8 Fixed cookie problems 2026-02-16 00:49:10 +01:00
selimaj-dev c914edd025 Fixed cookie problems 2026-02-16 00:44:45 +01:00
selimaj-dev b6e3dd2349 Auth handshake 2026-02-16 00:25:29 +01:00
selimaj-dev 6370219165 Structured 2026-02-15 23:51:57 +01:00
selimaj-dev e552ecb6e2 Websocket moves #19 2026-02-15 23:51:04 +01:00
selimaj-dev 8c7a05efde Moving run to Websocket #19 2026-02-15 23:48:04 +01:00
selimaj-dev d5db0d1352 Fixed redis issues 2026-02-15 00:21:56 +01:00
selimaj-dev ac530ab6cf origin and ws abstractions 2026-02-15 00:04:28 +01:00
selimaj-dev 371186c277 Fixed redirect 2026-02-14 23:39:02 +01:00
selimaj-dev 204f3754f2 Finally fixed origin 2026-02-14 23:25:28 +01:00
selimaj-dev 705d504cd7 Finally fixed origin 2026-02-14 23:15:53 +01:00
selimaj-dev 694652dccd Fixed origin 2026-02-14 23:07:55 +01:00
selimaj-dev 137d263060 Testing redis 2026-02-14 22:45:40 +01:00
selimaj-dev e70191feba Fixed redis issue 2026-02-14 18:42:38 +01:00
selimaj-dev 039ff6687c Simpler dockerfile 2026-02-14 12:50:52 +01:00
selimaj-dev 38d8ca2ca9 renamed dockerfile bc i forgot 2026-02-14 03:37:51 +01:00
selimaj-dev ef7c100a34 renamed dockerfile bc i forgot 2026-02-14 03:37:30 +01:00
selimaj-dev 9a011d6e92 Merge pull request #18 from orus-dev/docker-setup
Dockerfile setup and small package.json improvements
2026-02-14 03:05:53 +01:00
selimaj-dev d8419db0a5 Dockerfile setup and small package.json improvements 2026-02-14 03:04:21 +01:00
selimaj-dev efa7763208 Merge pull request #15 from orus-dev/websocket
Websocket #14
2026-02-09 21:24:57 +01:00
25 changed files with 482 additions and 242 deletions
+18
View File
@@ -0,0 +1,18 @@
FROM node:20-alpine
WORKDIR /app
# Install deps
COPY package.json package-lock.json ./
RUN npm ci
# Copy source
COPY . .
# Build app
RUN npm run build
ENV NODE_ENV=production
EXPOSE 3000
CMD ["npm", "run", "start"]
+42 -24
View File
@@ -7,6 +7,7 @@
"": { "": {
"name": "dev-run", "name": "dev-run",
"version": "0.1.0", "version": "0.1.0",
"hasInstallScript": true,
"dependencies": { "dependencies": {
"@codemirror/lang-go": "^6.0.1", "@codemirror/lang-go": "^6.0.1",
"@codemirror/lang-java": "^6.0.2", "@codemirror/lang-java": "^6.0.2",
@@ -43,7 +44,8 @@
"@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",
"@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",
"axios": "^1.13.5", "axios": "^1.13.5",
@@ -53,6 +55,7 @@
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"ioredis": "^5.9.2", "ioredis": "^5.9.2",
"js-cookie": "^3.0.5",
"lucide-react": "^0.563.0", "lucide-react": "^0.563.0",
"next": "16.1.6", "next": "16.1.6",
"next-ws": "^2.1.16", "next-ws": "^2.1.16",
@@ -3458,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"
@@ -3470,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"
@@ -3482,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"
@@ -3494,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",
@@ -3521,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",
@@ -3534,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"
@@ -3892,6 +3895,12 @@
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/js-cookie": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz",
"integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",
"license": "MIT"
},
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "20.19.32", "version": "20.19.32",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.32.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.32.tgz",
@@ -4927,6 +4936,15 @@
"jiti": "lib/jiti-cli.mjs" "jiti": "lib/jiti-cli.mjs"
} }
}, },
"node_modules/js-cookie": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
"license": "MIT",
"engines": {
"node": ">=14"
}
},
"node_modules/js-tokens": { "node_modules/js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+7 -5
View File
@@ -3,10 +3,10 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev --turbopack", "build": "next build",
"build": "npm run build:lib && next build", "start": "next start",
"postinstall": "npm run ws -- -y", "dev": "next dev",
"ws": "npx --yes next-ws-cli@latest patch" "postinstall": "next-ws patch"
}, },
"dependencies": { "dependencies": {
"@codemirror/lang-go": "^6.0.1", "@codemirror/lang-go": "^6.0.1",
@@ -44,7 +44,8 @@
"@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",
"@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",
"axios": "^1.13.5", "axios": "^1.13.5",
@@ -54,6 +55,7 @@
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"ioredis": "^5.9.2", "ioredis": "^5.9.2",
"js-cookie": "^3.0.5",
"lucide-react": "^0.563.0", "lucide-react": "^0.563.0",
"next": "16.1.6", "next": "16.1.6",
"next-ws": "^2.1.16", "next-ws": "^2.1.16",
+3 -1
View File
@@ -1,9 +1,11 @@
// app/auth/callback/route.ts // app/auth/callback/route.ts
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server"; import { createClient } from "@/lib/supabase/server";
import { getOrigin } from "@/lib/origin/server";
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const code = req.nextUrl.searchParams.get("code"); const code = req.nextUrl.searchParams.get("code");
const { httpOrigin } = await getOrigin();
if (!code) { if (!code) {
return NextResponse.json({ error: "code param required" }, { status: 400 }); return NextResponse.json({ error: "code param required" }, { status: 400 });
@@ -18,5 +20,5 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ error: error.message }, { status: 500 }); return NextResponse.json({ error: error.message }, { status: 500 });
} }
return NextResponse.redirect(new URL("/runs", req.url)); return NextResponse.redirect(`${httpOrigin}/problems`);
} }
-33
View File
@@ -1,33 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import * as Core from "@/modules/live-run/core";
import { getSession } from "@/modules/account/core";
export async function POST(req: NextRequest) {
const { runId, moves, file, language } = await req.json();
if (!runId || !moves || file === undefined || language === undefined)
return NextResponse.json(
{ error: "body requires runId, moves, file and language" },
{ status: 400 },
);
const supabase = await createClient();
const session = await getSession(supabase);
if (!session)
return NextResponse.json({ error: "Invalid session" }, { status: 401 });
const liveRun = await Core.getLiveRun(runId);
if (!liveRun)
return NextResponse.json(
{ error: "Run is not live or does not exist" },
{ status: 401 },
);
const run = await Core.addLiveRunEvent(liveRun.id, file, language, moves);
return NextResponse.json({ ok: true, run });
}
+229 -71
View File
@@ -1,80 +1,238 @@
import { NextRequest, NextResponse } from "next/server"; import { WebSocketServer, WebSocket } from "ws";
import { createClient } from "@/lib/supabase/server";
import * as Core from "@/modules/live-run/core";
import { getSession } from "@/modules/account/core";
import { randomUUID } from "crypto"; import { randomUUID } from "crypto";
import { createClientCookie } from "@/lib/supabase/server";
import { getSession } from "@/modules/account/core";
import * as Core from "@/modules/live-run/core";
import { ClientMessage } from "./types";
import { redis } from "@/lib/redis";
import { User } from "@supabase/supabase-js";
import { UserProfile } from "@/modules/user/types";
import { NextRequest } from "next/server";
export async function PUT(req: NextRequest) { export function UPGRADE(client: WebSocket, server: WebSocketServer) {
const { problem, category } = await req.json(); let authenticated = false;
let session: [User, UserProfile] | null = null;
let currentRun: string | undefined;
if (!problem || !category) // Heartbeat
return NextResponse.json( let isAlive = true;
{ error: "body requires problem and category" }, const heartbeat = setInterval(() => {
{ status: 400 }, 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);
const supabase = await createClient(); client.on("pong", () => {
isAlive = true;
const session = await getSession(supabase);
if (!session)
return NextResponse.json({ error: "Invalid session" }, { status: 401 });
const runId = randomUUID();
await Core.addLiveRun({
problem,
category,
id: runId,
username: session[1].username,
views: 0,
start: new Date().getTime(),
runsCount: 0,
}); });
return NextResponse.json({ ok: true, runId }); const closeClient = (reason?: string) => {
if (reason) console.warn("Closing client:", reason);
try {
client.close();
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;
}
};
client.on("message", async (raw) => {
let requestId: string | undefined;
try {
const msg = JSON.parse(raw.toString());
requestId = msg.requestId;
// AUTHENTICATION
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": {
const { problem, category } = payload as any;
if (!problem || !category)
return client.send(
JSON.stringify({
requestId,
ok: false,
error: "problem and category required",
}),
);
if (currentRun)
return client.send(
JSON.stringify({
requestId,
ok: false,
error:
"Cannot do multiple runs, delete/submit current run first",
}),
);
const runId = randomUUID();
await Core.addLiveRun({
id: runId,
problem,
category,
username: session[1].username,
views: 0,
start: Date.now(),
runsCount: 0,
});
currentRun = runId;
return client.send(
JSON.stringify({
requestId,
ok: true,
type: "create",
data: { runId },
}),
);
}
case "move": {
if (!currentRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "No current run" }),
);
const { moves, file, language } = payload as any;
if (!moves || file === undefined || language === undefined)
return client.send(
JSON.stringify({
requestId,
ok: false,
error: "moves, file, and language required",
}),
);
const liveRun = await Core.getLiveRun(currentRun);
if (!liveRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "Run not live" }),
);
const run = await Core.addLiveRunEvent(
liveRun.id,
file,
language,
moves,
);
return client.send(
JSON.stringify({ requestId, ok: true, type: "move", data: run }),
);
}
case "submit": {
if (!currentRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "No current run" }),
);
const liveRun = await Core.getLiveRun(currentRun);
if (!liveRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "Run not live" }),
);
const run = await Core.submitRun(liveRun, session[0].id);
currentRun = undefined;
return client.send(
JSON.stringify({ requestId, ok: true, type: "submit", data: run }),
);
}
case "delete": {
if (!currentRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "No current run" }),
);
await cleanupRun();
return client.send(
JSON.stringify({
requestId,
ok: true,
type: "delete",
data: { id: currentRun },
}),
);
}
case "getText": {
if (!currentRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "No current run" }),
);
const data = await redis.get(`liveRunText:${currentRun}`);
return client.send(JSON.stringify({ requestId, ok: true, data }));
}
default:
return client.send(
JSON.stringify({
requestId,
ok: false,
error: "Unknown message type",
}),
);
}
} catch (err) {
console.error(err);
if (requestId)
client.send(
JSON.stringify({ requestId, ok: false, error: "Malformed message" }),
);
closeClient("Malformed message");
}
});
client.on("close", async () => {
clearInterval(heartbeat);
await cleanupRun();
});
client.on("error", (err) => {
console.error("WebSocket error:", err);
clearInterval(heartbeat);
closeClient("WebSocket error");
});
} }
export async function POST(req: NextRequest) { export function GET(req: NextRequest) {
const { runId } = await req.json(); const headers = new Headers();
headers.set("Connection", "Upgrade");
if (!runId) headers.set("Upgrade", "websocket");
return NextResponse.json({ error: "body requires runId" }, { status: 400 }); return new Response("Upgrade Required", { status: 426, headers });
const supabase = await createClient();
const session = await getSession(supabase);
if (!session)
return NextResponse.json({ error: "Invalid session" }, { status: 401 });
const liveRun = await Core.getLiveRun(runId);
if (!liveRun)
return NextResponse.json(
{ error: "Run is not live or does not exist" },
{ status: 401 },
);
const run = await Core.submitRun(supabase, liveRun, session[0].id);
return NextResponse.json({ ok: true, run });
}
export async function DELETE(req: NextRequest) {
const runId = req.nextUrl.searchParams.get("runId");
if (!runId)
return NextResponse.json({ error: "missing ?runId=" }, { status: 400 });
const supabase = await createClient();
const session = await getSession(supabase);
if (!session)
return NextResponse.json({ error: "Invalid session" }, { status: 401 });
const run = await Core.removeLiveRun(runId);
return NextResponse.json({ ok: true, run });
} }
+32
View File
@@ -0,0 +1,32 @@
import { LiveRunMove } from "@/modules/live-run/types";
export type ClientMessage = { requestId: string } & (
| {
type: "create";
problem: string;
category: "any%" | "100%";
}
| {
type: "move";
runId: string;
file: string;
language: string;
moves: LiveRunMove[];
}
| {
type: "submit";
runId: string;
}
| {
type: "delete";
runId: string;
}
| {
type: "getText";
runId: string;
}
);
export type ServerMessage =
| { ok: true; type: string; data?: any }
| { ok: false; error: string };
+52 -48
View File
@@ -1,66 +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 { getLiveRun, updateLiveRunViews } from "@/modules/live-run/core"; import { updateLiveRunViews } from "@/modules/live-run/core";
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(); 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 text = await redis.get(`liveRunText:${runId}`);
client.send(
JSON.stringify({ file: null, language: null, moves: [], text }),
);
const sendText = async () => { // Add WebSocket to subscribers
const text = await subscriber.get(`liveRunText:${runId}`); if (!runSubscribers.has(runId)) {
runSubscribers.set(runId, new Set());
if (client.readyState === WebSocket.OPEN) { await redisSubscriber.subscribe(`liveRunEvent:${runId}`);
client.send( }
JSON.stringify({ runSubscribers.get(runId)!.add(client);
file: lastEvent?.file,
language: lastEvent?.language,
moves: [],
text,
}),
);
}
};
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 () => {
if (runId) await subscriber.unsubscribe(`liveRun:${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);
}); });
@@ -68,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>
+2 -2
View File
@@ -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 */}
+2 -1
View File
@@ -9,6 +9,7 @@ import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import useAction from "@/hook/use-action"; import useAction from "@/hook/use-action";
import { getProblems } from "@/modules/problems/actions"; import { getProblems } from "@/modules/problems/actions";
import axios from "axios"; import axios from "axios";
import Cookies from "js-cookie";
export default function Problems() { export default function Problems() {
const [problems] = useAction(getProblems); const [problems] = useAction(getProblems);
@@ -16,7 +17,7 @@ export default function Problems() {
useEffect(() => { useEffect(() => {
(async () => { (async () => {
await axios.post("http://127.0.0.1:63780/auth", { await axios.post("http://127.0.0.1:63780/auth", {
saveCookies: document.cookie, saveCookies: Cookies.get(),
}); });
})().catch(() => {}); })().catch(() => {});
}, []); }, []);
+4 -4
View File
@@ -11,7 +11,7 @@ import { java } from "@codemirror/lang-java";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { LiveRun, LiveRunEvent, LiveRunMove } from "@/modules/live-run/types"; import { LiveRun, LiveRunEvent, LiveRunMove } from "@/modules/live-run/types";
import useAction from "@/hook/use-action"; import useAction from "@/hook/use-action";
import { getOrigin } from "@/modules/getOrigin"; import { getOrigin } from "@/lib/origin/client";
type Language = type Language =
| "javascript" | "javascript"
@@ -56,9 +56,9 @@ export default function Editor({
// WebSocket connection // WebSocket connection
useEffect(() => { useEffect(() => {
if (!run || !origin?.host) return; if (!run || !origin?.wsOrigin) return;
const ws = new WebSocket(`ws://${origin.host}/api/view-run`); const ws = new WebSocket(`${origin.wsOrigin}/api/view-run`);
ws.onopen = () => { ws.onopen = () => {
ws.send(run.id); ws.send(run.id);
@@ -100,7 +100,7 @@ export default function Editor({
}; };
return () => ws.close(); return () => ws.close();
}, [run, ]); }, [run]);
return ( return (
<CodeMirror <CodeMirror
+1 -1
View File
@@ -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
View File
@@ -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>
+7
View File
@@ -0,0 +1,7 @@
"use server";
import * as Core from "./server";
export async function getOrigin() {
return Core.getOrigin();
}
+29
View File
@@ -0,0 +1,29 @@
import "server-only";
import { headers } from "next/headers";
export async function getOrigin(): Promise<{
protocol: string;
host: string;
wsProtocol: string;
httpOrigin: string;
wsOrigin: string;
}> {
const h = await headers();
const host = process.env.ORIGIN || h.get(":authority") || "localhost:3000";
const protocol =
process.env.ORIGIN_PROTO ||
h.get("x-forwarded-proto") ||
h.get(":scheme") ||
"https";
const wsProtocol = protocol === "https" ? "wss" : "ws";
return {
protocol,
host,
wsProtocol,
httpOrigin: `${protocol}://${host}`,
wsOrigin: `${wsProtocol}://${host}`,
};
}
+10
View File
@@ -2,3 +2,13 @@ import "server-only";
import Redis from "ioredis"; 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) => {
console.error("Redis error:", err);
});
redisSubscriber.on("error", (err) => {
console.error("Redis subscriber error:", err);
});
+11 -9
View File
@@ -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();
@@ -27,24 +26,27 @@ export async function createClient() {
); );
} }
export async function createClientApi() { export async function createClientCookie(cookies: Map<string, string>) {
const cookieStore = await cookies();
return createServerClient( return createServerClient(
process.env.SUPABASE_URL!, process.env.SUPABASE_URL!,
process.env.SUPABASE_SECRET_KEY!, process.env.SUPABASE_SECRET_KEY!,
{ {
cookies: { cookies: {
get(name: string) { get(name: string) {
return cookieStore.get(name)?.value; return cookies.get(name) || null;
}, },
set(name: string, value: string, options: CookieOptions) { set(name: string, value: string) {
cookieStore.set(name, value, options); cookies.set(name, value);
}, },
remove(name: string, options: CookieOptions) { remove(name: string, options: CookieOptions) {
cookieStore.set(name, "", options); cookies.delete(name);
}, },
}, },
}, },
); );
} }
export const supabaseApiClient = createSimpleClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SECRET_KEY!,
);
+3 -5
View File
@@ -1,21 +1,19 @@
"use server"; "use server";
import { getOrigin } from "@/lib/origin/server";
import * as Core from "./core"; import * as Core from "./core";
import { createClient } from "@/lib/supabase/server"; import { createClient } from "@/lib/supabase/server";
import { headers } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
export async function signInWithGitHub() { export async function signInWithGitHub() {
const supabase = await createClient(); const supabase = await createClient();
const h = await headers(); const { httpOrigin } = await getOrigin();
const host = h.get("host");
const protocol = h.get("x-forwarded-proto") ?? "https";
const { data, error } = await supabase.auth.signInWithOAuth({ const { data, error } = await supabase.auth.signInWithOAuth({
provider: "github", provider: "github",
options: { options: {
redirectTo: `${protocol}://${host}/api/auth/callback`, redirectTo: `${httpOrigin}/api/auth/callback`,
}, },
}); });
+1 -2
View File
@@ -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) {
-11
View File
@@ -1,11 +0,0 @@
"use server";
import { headers } from "next/headers";
export async function getOrigin(): Promise<{ protocol: string; host: string }> {
const h = await headers();
const host = h.get("host") || "localhost:3000";
const protocol = h.get("x-forwarded-proto") ?? "https";
return { protocol, host };
}
+1 -2
View File
@@ -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(
+6 -13
View File
@@ -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 -------------------- */
@@ -79,8 +78,6 @@ export async function addLiveRunEvent(
language: string, language: string,
moves: LiveRunMove[], moves: LiveRunMove[],
) { ) {
const redis = new Redis();
// Make sure the live run exists // Make sure the live run exists
const runExists = await redis.exists(`liveRun:${runId}`); const runExists = await redis.exists(`liveRun:${runId}`);
if (!runExists) throw "Invalid live run"; if (!runExists) throw "Invalid live run";
@@ -109,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 -2
View File
@@ -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[] = [
-2
View File
@@ -1,3 +1 @@
"use server";
import "server-only"; import "server-only";