docfast/src/middleware/usage.ts

98 lines
2.8 KiB
TypeScript

import { isProKey } from "../services/keys.js";
import fs from "fs/promises";
import path from "path";
const USAGE_FILE = "/app/data/usage.json";
let usage = new Map<string, { count: number; monthKey: string }>();
const FREE_TIER_LIMIT = 100;
function getMonthKey(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
// Load usage data from file on startup
async function loadUsageData(): Promise<void> {
try {
const data = await fs.readFile(USAGE_FILE, "utf8");
const usageObj = JSON.parse(data);
usage = new Map();
for (const [key, record] of Object.entries(usageObj)) {
usage.set(key, record as { count: number; monthKey: string });
}
console.log(`Loaded usage data for ${usage.size} keys`);
} catch (error) {
// File doesn't exist or invalid JSON - start fresh
console.log("No existing usage data found, starting fresh");
usage = new Map();
}
}
// Save usage data to file
async function saveUsageData(): Promise<void> {
try {
const usageObj: Record<string, { count: number; monthKey: string }> = {};
for (const [key, record] of usage) {
usageObj[key] = record;
}
// Ensure directory exists
await fs.mkdir(path.dirname(USAGE_FILE), { recursive: true });
await fs.writeFile(USAGE_FILE, JSON.stringify(usageObj, null, 2));
} catch (error) {
console.error("Failed to save usage data:", error);
}
}
// Initialize usage data loading
loadUsageData().catch(console.error);
export function usageMiddleware(req: any, res: any, next: any): void {
const key = req.headers.authorization?.slice(7) || "unknown";
const monthKey = getMonthKey();
// Pro keys have no limit
if (isProKey(key)) {
trackUsage(key, monthKey);
next();
return;
}
// Free tier limit check
const record = usage.get(key);
if (record && record.monthKey === monthKey && record.count >= FREE_TIER_LIMIT) {
res.status(429).json({
error: "Free tier limit reached",
limit: FREE_TIER_LIMIT,
used: record.count,
upgrade: "Upgrade to Pro for unlimited conversions: https://docfast.dev/pricing",
});
return;
}
trackUsage(key, monthKey);
next();
}
function trackUsage(key: string, monthKey: string): void {
const record = usage.get(key);
if (!record || record.monthKey !== monthKey) {
usage.set(key, { count: 1, monthKey });
} else {
record.count++;
}
// Save to file after each update (simple approach)
saveUsageData().catch(console.error);
}
export function getUsageStats(): Record<string, { count: number; month: string }> {
const stats: Record<string, { count: number; month: string }> = {};
for (const [key, record] of usage) {
const masked = key.slice(0, 8) + "...";
stats[masked] = { count: record.count, month: record.monthKey };
}
return stats;
}