Fixed Codex

This commit is contained in:
decolua
2026-02-21 14:36:06 +07:00
parent f2025cc776
commit adf57aa0c9
18 changed files with 1419 additions and 1627 deletions
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { getChartData } from "@/lib/usageDb";
const VALID_PERIODS = new Set(["24h", "7d", "30d", "60d"]);
export async function GET(request) {
try {
const { searchParams } = new URL(request.url);
const period = searchParams.get("period") || "7d";
if (!VALID_PERIODS.has(period)) {
return NextResponse.json({ error: "Invalid period" }, { status: 400 });
}
const data = await getChartData(period);
return NextResponse.json(data);
} catch (error) {
console.error("[API] Failed to get chart data:", error);
return NextResponse.json({ error: "Failed to fetch chart data" }, { status: 500 });
}
}
+58
View File
@@ -0,0 +1,58 @@
import { getUsageStats, statsEmitter } from "@/lib/usageDb";
export const dynamic = "force-dynamic";
export async function GET() {
const encoder = new TextEncoder();
const state = { closed: false, keepalive: null, send: null };
const stream = new ReadableStream({
async start(controller) {
state.send = async () => {
if (state.closed) return;
try {
const stats = await getUsageStats();
if (stats.activeRequests?.length > 0) {
console.log(`[SSE] Push | active=${stats.activeRequests.length} | ${stats.activeRequests.map(r => r.provider).join(",")}`);
}
controller.enqueue(encoder.encode(`data: ${JSON.stringify(stats)}\n\n`));
} catch {
// Controller closed → self-cleanup
state.closed = true;
statsEmitter.off("update", state.send);
clearInterval(state.keepalive);
}
};
await state.send();
console.log(`[SSE] Client connected | listeners=${statsEmitter.listenerCount("update") + 1}`);
statsEmitter.on("update", state.send);
state.keepalive = setInterval(() => {
if (state.closed) { clearInterval(state.keepalive); return; }
try {
controller.enqueue(encoder.encode(": ping\n\n"));
} catch {
state.closed = true;
clearInterval(state.keepalive);
}
}, 25000);
},
cancel() {
state.closed = true;
statsEmitter.off("update", state.send);
clearInterval(state.keepalive);
console.log("[SSE] Client disconnected");
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}