Spaces:
Sleeping
Sleeping
File size: 2,641 Bytes
27497f4 78120e2 27497f4 78120e2 6572963 78120e2 27497f4 78120e2 27497f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import { NextRequest } from "next/server";
import { promises as fs } from "fs";
import os from "os";
import path from "path";
export const runtime = "nodejs";
async function resolveUsageFilePath() {
if (process.env.USAGE_STATS_PATH) return process.env.USAGE_STATS_PATH;
const candidates = [
process.env.DATA_DIR,
process.env.HF_HOME,
process.env.HOME,
"/tmp",
os.tmpdir(),
process.cwd(),
].filter(Boolean) as string[];
for (const dir of candidates) {
const candidate = path.join(dir, "usage-stats.json");
try {
await fs.access(candidate);
return candidate;
} catch {
// try next
}
}
// Default location if not present yet
return path.join(os.tmpdir(), "usage-stats.json");
}
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || "";
type UsageStats = {
totalRequests: number;
perDay: Record<string, number>;
lastUpdated: string;
};
function isAuthorized(req: NextRequest) {
if (!ADMIN_TOKEN) return true;
const tokenFromHeader = req.headers.get("x-admin-token") || "";
const auth = req.headers.get("authorization") || "";
const tokenFromBearer = auth.toLowerCase().startsWith("bearer ") ? auth.slice(7) : "";
const tokenFromQuery = req.nextUrl.searchParams.get("token") || "";
return tokenFromHeader === ADMIN_TOKEN || tokenFromBearer === ADMIN_TOKEN || tokenFromQuery === ADMIN_TOKEN;
}
async function readUsageStats(): Promise<UsageStats> {
try {
const usageFile = await resolveUsageFilePath();
const raw = await fs.readFile(usageFile, "utf8");
const parsed = JSON.parse(raw) as Partial<UsageStats>;
return {
totalRequests: typeof parsed.totalRequests === "number" ? parsed.totalRequests : 0,
perDay: parsed.perDay && typeof parsed.perDay === "object" ? (parsed.perDay as Record<string, number>) : {},
lastUpdated: typeof parsed.lastUpdated === "string" ? parsed.lastUpdated : new Date(0).toISOString(),
};
} catch {
return {
totalRequests: 0,
perDay: {},
lastUpdated: new Date(0).toISOString(),
};
}
}
export async function GET(req: NextRequest) {
if (!isAuthorized(req)) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
}
const stats = await readUsageStats();
return new Response(JSON.stringify(stats), {
headers: { "Content-Type": "application/json" },
});
}
|