73 lines
2.5 KiB
TypeScript
73 lines
2.5 KiB
TypeScript
import { PDF_STREAM_HARD_ROW_LIMIT, XLSX_STREAM_HARD_ROW_LIMIT } from "./format-caps.js";
|
|
|
|
/**
|
|
* Tenant plan tier used to resolve export row caps. Matches the
|
|
* billing-plan vocabulary used elsewhere in the repo. Callers that
|
|
* encounter an unknown plan should fall back to "free" — the most
|
|
* conservative cap — rather than throwing, because the row cap is a
|
|
* safety net, not an authorisation primitive.
|
|
*/
|
|
export type TenantPlanTier = "free" | "pro" | "enterprise";
|
|
|
|
export type ExportFormat = "csv" | "json" | "xlsx" | "pdf";
|
|
|
|
/**
|
|
* Plan-based soft caps applied on top of the per-format hard caps. The
|
|
* plan cap protects shared worker capacity from a single noisy tenant; the
|
|
* format cap protects against format-specific failure modes.
|
|
*/
|
|
export const EXPORT_PLAN_ROW_CAPS: Record<TenantPlanTier, number> = {
|
|
free: 10_000,
|
|
pro: 100_000,
|
|
enterprise: Number.POSITIVE_INFINITY,
|
|
};
|
|
|
|
const FORMAT_HARD_CAPS: Record<ExportFormat, number> = {
|
|
csv: Number.POSITIVE_INFINITY,
|
|
json: Number.POSITIVE_INFINITY,
|
|
xlsx: XLSX_STREAM_HARD_ROW_LIMIT,
|
|
pdf: PDF_STREAM_HARD_ROW_LIMIT,
|
|
};
|
|
|
|
export class ExportRowCapExceededError extends Error {
|
|
readonly code = "EXPORT_ROW_LIMIT_PLAN";
|
|
constructor(
|
|
readonly requestedRowCount: number,
|
|
readonly effectiveCap: number,
|
|
readonly plan: TenantPlanTier,
|
|
readonly format: ExportFormat,
|
|
) {
|
|
super(
|
|
`Export request of ${requestedRowCount} rows exceeds the ${plan} plan / ${format} format cap of ${Number.isFinite(effectiveCap) ? effectiveCap : "unlimited"}.`,
|
|
);
|
|
this.name = "ExportRowCapExceededError";
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolves the effective row cap for a given plan and format. Returns
|
|
* `Infinity` only when both the plan and the format are unbounded; in
|
|
* practice all PDF and XLSX exports still hit a finite ceiling.
|
|
*/
|
|
export function resolveExportRowCap(plan: TenantPlanTier, format: ExportFormat): number {
|
|
const planCap = EXPORT_PLAN_ROW_CAPS[plan] ?? EXPORT_PLAN_ROW_CAPS.free;
|
|
const formatCap = FORMAT_HARD_CAPS[format] ?? Number.POSITIVE_INFINITY;
|
|
return Math.min(planCap, formatCap);
|
|
}
|
|
|
|
/**
|
|
* Convenience guard: throws {@link ExportRowCapExceededError} when the
|
|
* caller knows the row count up front. Streamers also enforce caps
|
|
* mid-stream so this is a fast-path check, not the sole guard.
|
|
*/
|
|
export function assertExportRowCap(
|
|
rowCount: number,
|
|
plan: TenantPlanTier,
|
|
format: ExportFormat,
|
|
): void {
|
|
const cap = resolveExportRowCap(plan, format);
|
|
if (rowCount > cap) {
|
|
throw new ExportRowCapExceededError(rowCount, cap, plan, format);
|
|
}
|
|
}
|