feat: token auto-refresh, studio→render wiring, admin panel (nodes + render queue)

Token auto-refresh (middleware):
- Proactively refresh fr_access when < 120s remain — no more silent 15-min kick
- Inlines /v1/auth/refresh call in middleware, stamps new cookies on response
- /admin/* protected: is_admin JWT claim required, else redirect /dashboard
- apiFetch() (src/lib/api/fetch.ts): client-side 401 → auto-refresh → retry;
  de-duplicates concurrent refresh calls; redirects to /auth on failure

Studio → Render V2 wiring:
- scenes[] no longer sent to POST /api/render (V2 render-svc fetches project
  from Studio service via saved_project_id directly)
- renderRequestSchema.scenes is now optional
- RenderModal uses apiFetch for auto-refresh on 401 during polling

Admin panel (/admin/*):
- Admin layout: server-side is_admin guard + top nav (Nodes, Render Queue)
- /admin/nodes: lists all nodes from GET /v1/nodes with status badges,
  heartbeat age, slot usage, tags; Drain (PATCH status=Draining) + Release actions
- /admin/renders: render job table with step filter tabs; progress bars,
  error messages, Retry + Cancel per-row actions; polls GET /v1/renders
- API proxy routes: /api/admin/nodes/:id/drain|release,
  /api/admin/renders/:id/retry|cancel — all validate is_admin in JWT before proxying

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-06-01 13:42:30 +03:30
parent d7743a6fbe
commit 12773e125a
16 changed files with 757 additions and 18 deletions
+44
View File
@@ -0,0 +1,44 @@
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/auth/session";
export const dynamic = "force-dynamic";
export default async function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
const user = await getCurrentUser();
if (!user || !user.is_admin) {
redirect("/dashboard");
}
return (
<div className="min-h-screen bg-[#0c0e1a] text-gray-200">
<nav className="border-b border-[#1e2235] bg-[#0f1120] px-6 py-3">
<div className="mx-auto flex max-w-7xl items-center gap-6">
<span className="text-sm font-semibold text-white">FlatRender Admin</span>
<a
href="/admin/nodes"
className="text-sm text-gray-400 hover:text-white transition-colors"
>
Nodes
</a>
<a
href="/admin/renders"
className="text-sm text-gray-400 hover:text-white transition-colors"
>
Render Queue
</a>
<a
href="/dashboard"
className="ml-auto text-xs text-gray-500 hover:text-gray-300 transition-colors"
>
Back to Dashboard
</a>
</div>
</nav>
<main className="mx-auto max-w-7xl px-6 py-8">{children}</main>
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { adminGet } from "@/lib/api/admin-gateway";
import { NodesTable } from "@/components/admin/NodesTable";
export const dynamic = "force-dynamic";
export const revalidate = 0;
interface V2Node {
id: string;
name: string;
status: "Online" | "Busy" | "Offline" | "Draining";
last_heartbeat: string;
active_job_id: string | null;
slots_total: number;
slots_used: number;
version: string | null;
tags: string[] | null;
}
interface V2NodeList {
items: V2Node[];
total: number;
}
export default async function AdminNodesPage() {
const data = await adminGet<V2NodeList>("/v1/nodes?pageSize=100");
const nodes = data?.items ?? [];
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-white">Render Nodes</h1>
<p className="mt-1 text-sm text-gray-500">
{nodes.length} node{nodes.length !== 1 ? "s" : ""} registered
</p>
</div>
</div>
<NodesTable nodes={nodes} />
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function AdminRootPage() {
redirect("/admin/nodes");
}
+80
View File
@@ -0,0 +1,80 @@
import { adminGet } from "@/lib/api/admin-gateway";
import { RenderQueueTable } from "@/components/admin/RenderQueueTable";
export const dynamic = "force-dynamic";
export const revalidate = 0;
export type V2RenderJob = {
id: string;
saved_project_id: string;
user_id: string;
status: string;
step: string;
progress: number;
quality: string;
resolution: string;
frame_rate: number;
node_id: string | null;
error_message: string | null;
created_at: string;
updated_at: string;
};
interface V2RenderList {
items: V2RenderJob[];
total: number;
}
export default async function AdminRendersPage({
searchParams,
}: {
searchParams: { step?: string };
}) {
const step = searchParams.step ?? "";
const qs = step ? `?step=${step}&pageSize=50` : "?pageSize=50";
const data = await adminGet<V2RenderList>(`/v1/renders${qs}`);
const jobs = data?.items ?? [];
const total = data?.total ?? 0;
const steps = ["Queued", "Preparing", "Rendering", "Uploading", "Done", "Failed", "Cancelled"];
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-white">Render Queue</h1>
<p className="mt-1 text-sm text-gray-500">{total} total jobs</p>
</div>
</div>
{/* Step filter tabs */}
<div className="flex gap-2 flex-wrap">
<a
href="/admin/renders"
className={`rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
!step
? "border-primary-500 bg-primary-600/20 text-white"
: "border-[#1e2235] text-gray-400 hover:text-white hover:border-[#2a3050]"
}`}
>
All
</a>
{steps.map((s) => (
<a
key={s}
href={`/admin/renders?step=${s}`}
className={`rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
step === s
? "border-primary-500 bg-primary-600/20 text-white"
: "border-[#1e2235] text-gray-400 hover:text-white hover:border-[#2a3050]"
}`}
>
{s}
</a>
))}
</div>
<RenderQueueTable jobs={jobs} />
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
/**
* Shared helper for admin action proxy routes.
* Validates the caller is an admin (checks is_admin in the JWT), then
* proxies the action to the V2 gateway.
*/
import { type NextRequest, NextResponse } from "next/server";
import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";
import { decodeJwt } from "@/lib/auth/jwt";
export async function adminProxy(
_req: NextRequest,
gatewayPath: string,
method: string = "POST"
): Promise<NextResponse> {
const token = await getAccessToken();
if (!token) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Quick admin check on the server side before forwarding
const claims = decodeJwt(token);
const isAdmin =
String(claims?.is_admin) === "true" ||
claims?.is_admin === true ||
String(claims?.is_tenant_admin) === "true";
if (!isAdmin) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const res = await fetch(gatewayUrl(gatewayPath), {
method,
cache: "no-store",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
if (!res.ok) {
const err = await res.json().catch(() => null) as { message?: string } | null;
return NextResponse.json(
{ error: err?.message ?? "Gateway error" },
{ status: res.status }
);
}
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,33 @@
// "Drain" sets node status to Draining via PATCH so it finishes its current
// job but won't accept new ones.
import { type NextRequest, NextResponse } from "next/server";
import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";
import { decodeJwt } from "@/lib/auth/jwt";
export const runtime = "nodejs";
interface Ctx { params: { nodeId: string } }
export async function POST(_req: NextRequest, { params }: Ctx) {
const token = await getAccessToken();
if (!token) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const claims = decodeJwt(token);
const isAdmin = String(claims?.is_admin) === "true" || claims?.is_admin === true;
if (!isAdmin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const res = await fetch(gatewayUrl(`/v1/nodes/${params.nodeId}`), {
method: "PATCH",
cache: "no-store",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ status: "Draining" }),
});
if (!res.ok) {
const err = await res.json().catch(() => null) as { message?: string } | null;
return NextResponse.json({ error: err?.message ?? "Gateway error" }, { status: res.status });
}
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,9 @@
import { type NextRequest } from "next/server";
import { adminProxy } from "@/app/api/admin/_adminProxy";
export const runtime = "nodejs";
interface Ctx { params: { nodeId: string } }
export async function POST(req: NextRequest, { params }: Ctx) {
return adminProxy(req, `/v1/nodes/${params.nodeId}/release`);
}
@@ -0,0 +1,9 @@
import { type NextRequest } from "next/server";
import { adminProxy } from "@/app/api/admin/_adminProxy";
export const runtime = "nodejs";
interface Ctx { params: { jobId: string } }
export async function POST(req: NextRequest, { params }: Ctx) {
return adminProxy(req, `/v1/renders/${params.jobId}/cancel`);
}
@@ -0,0 +1,9 @@
import { type NextRequest } from "next/server";
import { adminProxy } from "@/app/api/admin/_adminProxy";
export const runtime = "nodejs";
interface Ctx { params: { jobId: string } }
export async function POST(req: NextRequest, { params }: Ctx) {
return adminProxy(req, `/v1/renders/${params.jobId}/retry`);
}