53 lines
2.0 KiB
TypeScript
53 lines
2.0 KiB
TypeScript
/**
|
|
* Exact credit estimates from a caller-supplied, versioned price book.
|
|
* This is a calculator only: it is not a wallet, reservation or payment proof.
|
|
*/
|
|
export interface CreditPriceLine {
|
|
metric: string;
|
|
/** Maximum chargeable units for this job, established by the server. */
|
|
maxUnits: number;
|
|
/** Integer credits per billing block. */
|
|
creditsPerBlock: number;
|
|
unitsPerBlock: number;
|
|
}
|
|
|
|
export interface CreditQuote {
|
|
priceBookVersion: string;
|
|
maximumCredits: number;
|
|
lines: Array<{ metric: string; maxUnits: number; maximumCredits: number }>;
|
|
}
|
|
|
|
/** Round each metered component up to its configured billing block. */
|
|
export function quoteMaximumCredits(
|
|
priceBookVersion: string,
|
|
lines: readonly CreditPriceLine[],
|
|
): CreditQuote {
|
|
if (!priceBookVersion.trim() || lines.length === 0)
|
|
throw new Error('A versioned price book and at least one line are required');
|
|
const names = new Set<string>();
|
|
let total = BigInt(0);
|
|
const output = lines.map((line) => {
|
|
if (!line.metric.trim() || names.has(line.metric))
|
|
throw new Error('Metric names must be nonempty and unique');
|
|
names.add(line.metric);
|
|
if (
|
|
!Number.isSafeInteger(line.maxUnits) ||
|
|
line.maxUnits < 0 ||
|
|
!Number.isSafeInteger(line.creditsPerBlock) ||
|
|
line.creditsPerBlock < 0 ||
|
|
!Number.isSafeInteger(line.unitsPerBlock) ||
|
|
line.unitsPerBlock <= 0
|
|
) {
|
|
throw new Error('Credit quantities must be nonnegative safe integers and block size must be positive');
|
|
}
|
|
const units = BigInt(line.maxUnits);
|
|
const size = BigInt(line.unitsPerBlock);
|
|
const value = ((units + size - BigInt(1)) / size) * BigInt(line.creditsPerBlock);
|
|
total += value;
|
|
if (value > BigInt(Number.MAX_SAFE_INTEGER) || total > BigInt(Number.MAX_SAFE_INTEGER))
|
|
throw new Error('Credit quote exceeds the supported integer range');
|
|
return { metric: line.metric, maxUnits: line.maxUnits, maximumCredits: Number(value) };
|
|
});
|
|
return { priceBookVersion, maximumCredits: Number(total), lines: output };
|
|
}
|