import { env } from "cloudflare:workers";
import { MAX_IN_LIST, all, chunks, first, placeholders, run } from "../db";
import { HttpError } from "../errors";
import { numberVar } from "../limits";
const GIB = 1024 * 1024 * 1024;
const MIB = 1024 * 1024;
const HTTP_INSUFFICIENT_STORAGE = 507;
const HTTP_TOO_MANY = 429;
export type LfsUsage = {
storageBytes: number;
storageLimit: number;
bandwidthBytes: number;
bandwidthLimit: number;
period: string;
};
type UsageRow = { storage_bytes: number; bandwidth_period: string; bandwidth_bytes: number };
export function maxObjectBytes(): number {
return numberVar(env.LFS_MAX_OBJECT_BYTES, 100 * MIB);
}
function storageLimit(): number {
return numberVar(env.LFS_STORAGE_BYTES_PER_OWNER, 10 * GIB);
}
function bandwidthLimit(): number {
return numberVar(env.LFS_BANDWIDTH_BYTES_PER_MONTH, 10 * GIB);
}
/** Bandwidth resets each calendar month (UTC). */
function currentPeriod(now = new Date()): string {
return now.toISOString().slice(0, 7);
}
export async function lfsUsage(ownerId: string): Promise<LfsUsage> {
const row = await first<UsageRow>(
"SELECT storage_bytes, bandwidth_period, bandwidth_bytes FROM lfs_usage WHERE owner_id = ?",