Refactored /api/run

This commit is contained in:
2026-02-17 03:27:26 +01:00
parent abda0b52af
commit cbd41d9e37
5 changed files with 225 additions and 267 deletions
+24 -24
View File
@@ -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
View File
@@ -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",
+106 -149
View File
@@ -4,70 +4,80 @@ 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";
import { UserProfile } from "@/modules/user/types";
import { NextRequest } from "next/server";
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,
requestId,
}: { cookies: Record<string, string>; requestId: string } = JSON.parse(
raw.toString(),
);
if (!cookies) {
client.send(JSON.stringify({ ok: false, error: "Missing cookies" }));
client.close();
return;
}
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 }));
let currentRun: string | undefined; let currentRun: string | undefined;
client.on("message", async (raw) => { const closeClient = (reason?: string) => {
if (reason) console.warn("Closing client:", reason);
try { try {
const { requestId, ...msg }: ClientMessage = JSON.parse(raw.toString()); client.close();
// force close after 1s if still open
setTimeout(() => {
if (client.readyState !== WebSocket.CLOSED) client.terminate();
}, 1000);
} catch {}
};
switch (msg.type) { client.on("message", async (raw) => {
/* ---------------- CREATE ---------------- */ 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");
// Await the session
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) {
client.send( return 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) { if (currentRun) {
client.send( return client.send(
JSON.stringify({ JSON.stringify({
requestId, requestId,
ok: false, ok: false,
error: error:
"Cannot do multiple runs at a time, please delete or submit the current run", "Cannot do multiple runs, delete/submit current run first",
}), }),
); );
return;
} }
const runId = randomUUID(); const runId = randomUUID();
await Core.addLiveRun({ await Core.addLiveRun({
id: runId, id: runId,
problem, problem,
@@ -78,7 +88,9 @@ 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,
@@ -86,47 +98,29 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
data: { runId }, data: { runId },
}), }),
); );
break;
} }
/* ---------------- DELETE ---------------- */
case "move": { case "move": {
const { moves, file, language } = msg; if (!currentRun)
return client.send(
if (!currentRun) { JSON.stringify({ requestId, ok: false, error: "No current run" }),
client.send(
JSON.stringify({
requestId,
ok: false,
error: "No current run, please create a run first",
}),
); );
return; const { moves, file, language } = payload as any;
}
if (!moves || file === undefined || language === undefined) { if (!moves || file === undefined || language === undefined) {
client.send( return 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(currentRun); 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,
@@ -135,108 +129,63 @@ export function UPGRADE(client: WebSocket, server: WebSocketServer) {
moves, moves,
); );
client.send( return client.send(
JSON.stringify({ JSON.stringify({ requestId, ok: true, type: "move", data: run }),
requestId,
ok: true,
type: "move",
data: run,
}),
); );
break;
} }
/* ---------------- SUBMIT ---------------- */
case "submit": { case "submit": {
if (!currentRun) { if (!currentRun)
client.send( return client.send(
JSON.stringify({ JSON.stringify({ requestId, ok: false, error: "No current run" }),
requestId,
ok: false,
error: "No current run, please create a run first",
}),
); );
return;
}
const liveRun = await Core.getLiveRun(currentRun); const liveRun = await Core.getLiveRun(currentRun);
if (!liveRun)
return client.send(
JSON.stringify({ requestId, ok: false, error: "Run not live" }),
);
if (!liveRun) { const run = await Core.submitRun(liveRun, session[0].id);
client.send( currentRun = undefined;
JSON.stringify({
requestId, return client.send(
ok: false, JSON.stringify({ requestId, ok: true, type: "submit", data: run }),
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": {
if (!currentRun) { if (!currentRun)
client.send( return client.send(
JSON.stringify({ JSON.stringify({ requestId, ok: false, error: "No current run" }),
requestId,
ok: false,
error: "No current run, please create a run first",
}),
); );
return;
}
const run = await Core.removeLiveRun(currentRun); await Core.removeLiveRun(currentRun);
const deletedRun = currentRun;
currentRun = undefined;
client.send( return client.send(
JSON.stringify({ JSON.stringify({
requestId, requestId,
ok: true, ok: true,
type: "delete", type: "delete",
data: run, data: { id: deletedRun },
}), }),
); );
break;
} }
case "getText": case "getText": {
if (!currentRun) { if (!currentRun)
client.send( return client.send(
JSON.stringify({ JSON.stringify({ requestId, ok: false, error: "No current run" }),
requestId,
ok: false,
error: "No current run, please create a run first",
}),
); );
return;
}
const data = await redis.get(`liveRunText:${currentRun}`); const data = await redis.get(`liveRunText:${currentRun}`);
return client.send(JSON.stringify({ requestId, ok: true, data }));
client.send( }
JSON.stringify({
requestId,
ok: true,
data,
}),
);
break;
default: default:
client.send( return client.send(
JSON.stringify({ JSON.stringify({
requestId, requestId,
ok: false, ok: false,
@@ -246,22 +195,30 @@ 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 () => { client.on("close", async () => {
if (!currentRun) return; console.log("WebSocket closed, cleaning up run:", currentRun);
if (currentRun) {
Core.removeLiveRun(currentRun); try {
await redis.del(`liveRunText:${currentRun}`); await Core.removeLiveRun(currentRun);
} catch (err) {
console.error("Error cleaning up run on close:", err);
}
currentRun = undefined;
}
}); });
client.on("error", (err) => {
console.error("WebSocket error:", err);
closeClient("WebSocket error");
}); });
} }
+6 -2
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();
@@ -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!,
);
+4 -7
View File
@@ -6,6 +6,7 @@ import { SupabaseClient } from "@supabase/supabase-js";
import { redis } from "@/lib/redis"; import { redis } from "@/lib/redis";
import Redis from "ioredis"; 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 -------------------- */
@@ -66,7 +67,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 -------------------- */
@@ -108,15 +109,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([
{ {