Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions backend/src/services/__tests__/meteredBilling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { describe, expect, it } from 'vitest';
import {
accrue,
isSettlementDue,
newMeter,
rollPeriod,
startUsage,
stopUsage,
takeSettlement,
validatePlan,
type MeterPlan,
} from '../meteredBilling';

const plan: MeterPlan = { ratePerSecond: 10n, freeSeconds: 0, periodCap: null, settlementThreshold: 100n };
const T0 = 1_000_000;

describe('validatePlan', () => {
it('accepts a valid plan and rejects bad fields', () => {
expect(validatePlan(plan)).toBeNull();
expect(validatePlan({ ...plan, ratePerSecond: 0n })).toMatch(/ratePerSecond/);
expect(validatePlan({ ...plan, freeSeconds: -1 })).toMatch(/freeSeconds/);
expect(validatePlan({ ...plan, freeSeconds: 1.5 })).toMatch(/freeSeconds/);
expect(validatePlan({ ...plan, periodCap: -1n })).toMatch(/periodCap/);
expect(validatePlan({ ...plan, settlementThreshold: 0n })).toMatch(/settlementThreshold/);
});
});

describe('accrue', () => {
it('charges per whole second of running usage', () => {
const s = accrue(plan, startUsage(newMeter(T0), T0), T0 + 5_000);
expect(s.usedSeconds).toBe(5);
expect(s.unsettled).toBe(50n);
});

it('carries partial seconds so many ticks equal one long tick', () => {
let many = startUsage(newMeter(T0), T0);
for (let i = 1; i <= 10; i++) many = accrue(plan, many, T0 + i * 700);
const one = accrue(plan, startUsage(newMeter(T0), T0), T0 + 7_000);
expect(many.unsettled).toBe(one.unsettled);
expect(many.usedSeconds).toBe(7);
expect(many.carryMs).toBe(0);
});

it('keeps the leftover milliseconds', () => {
const s = accrue(plan, startUsage(newMeter(T0), T0), T0 + 2_900);
expect(s.usedSeconds).toBe(2);
expect(s.carryMs).toBe(900);
});

it('charges nothing when stopped, or when the clock runs backwards', () => {
const idle = newMeter(T0);
expect(accrue(plan, idle, T0 + 9_000)).toBe(idle);
const running = startUsage(newMeter(T0), T0);
expect(accrue(plan, running, T0 - 5_000)).toBe(running);
});

it('does not charge the free seconds, then charges after them', () => {
const free = { ...plan, freeSeconds: 3 };
const started = startUsage(newMeter(T0), T0);
expect(accrue(free, started, T0 + 2_000).unsettled).toBe(0n);
expect(accrue(free, started, T0 + 3_000).unsettled).toBe(0n);
// 5 seconds used, 3 free: 2 charged.
expect(accrue(free, started, T0 + 5_000).unsettled).toBe(20n);
});

it('charges only the seconds past the free allowance across ticks', () => {
const free = { ...plan, freeSeconds: 3 };
let s = startUsage(newMeter(T0), T0);
s = accrue(free, s, T0 + 2_000);
s = accrue(free, s, T0 + 6_000);
expect(s.usedSeconds).toBe(6);
expect(s.unsettled).toBe(30n);
});

it('never charges past the period cap', () => {
const capped = { ...plan, periodCap: 35n };
const s = accrue(capped, startUsage(newMeter(T0), T0), T0 + 10_000);
expect(s.unsettled).toBe(35n);
expect(s.chargedInPeriod).toBe(35n);
expect(accrue(capped, s, T0 + 20_000).unsettled).toBe(35n);
});
});

describe('start and stop', () => {
it('ignores a second start and stops counting after stop', () => {
const started = startUsage(newMeter(T0), T0);
expect(startUsage(started, T0 + 3_000)).toBe(started);
const stopped = stopUsage(plan, started, T0 + 4_000);
expect(stopped.running).toBe(false);
expect(stopped.unsettled).toBe(40n);
expect(accrue(plan, stopped, T0 + 90_000)).toBe(stopped);
});

it('does not bill the idle gap when usage restarts', () => {
let s = stopUsage(plan, startUsage(newMeter(T0), T0), T0 + 2_000);
s = startUsage(s, T0 + 60_000);
s = accrue(plan, s, T0 + 61_000);
expect(s.unsettled).toBe(30n);
});
});

describe('settlement', () => {
it('is due only at or above the threshold', () => {
const s = accrue(plan, startUsage(newMeter(T0), T0), T0 + 9_000);
expect(isSettlementDue(plan, s)).toBe(false);
expect(takeSettlement(plan, s, 'm1', T0).batch).toBeNull();
expect(isSettlementDue(plan, accrue(plan, s, T0 + 10_000))).toBe(true);
});

it('takes the whole unsettled amount in one batch and clears it', () => {
const s = accrue(plan, startUsage(newMeter(T0), T0), T0 + 12_000);
const { state, batch } = takeSettlement(plan, s, 'm1', T0);
expect(batch).toEqual({ id: `m1:${T0}-${T0 + 12_000}`, amount: 120n, fromMs: T0, toMs: T0 + 12_000 });
expect(state.unsettled).toBe(0n);
expect(takeSettlement(plan, state, 'm1', T0 + 12_000).batch).toBeNull();
});

it('can force a batch below the threshold, but never an empty one', () => {
const s = accrue(plan, startUsage(newMeter(T0), T0), T0 + 2_000);
expect(takeSettlement(plan, s, 'm1', T0, true).batch?.amount).toBe(20n);
expect(takeSettlement(plan, newMeter(T0), 'm1', T0, true).batch).toBeNull();
});

it('gives a retried settlement the same id', () => {
const s = accrue(plan, startUsage(newMeter(T0), T0), T0 + 12_000);
expect(takeSettlement(plan, s, 'm1', T0).batch?.id).toBe(takeSettlement(plan, s, 'm1', T0).batch?.id);
});
});

describe('rollPeriod', () => {
it('resets the period counters but keeps unsettled usage', () => {
const capped = { ...plan, periodCap: 50n };
const s = accrue(capped, startUsage(newMeter(T0), T0), T0 + 10_000);
expect(s.unsettled).toBe(50n);
const next = rollPeriod(s);
expect(next.usedSeconds).toBe(0);
expect(next.chargedInPeriod).toBe(0n);
expect(next.unsettled).toBe(50n);
expect(accrue(capped, next, T0 + 12_000).unsettled).toBe(70n);
});
});
131 changes: 131 additions & 0 deletions backend/src/services/meteredBilling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Usage-metered billing with a per-second settlement accumulator (issue #1330).
//
// Pure functions over plain values: no clock, timers, database or network.
// Callers pass the current time in, so every rule is testable. Amounts are
// bigint in the smallest currency unit (for example stroops) to avoid float
// drift. The accumulator counts whole seconds and carries the leftover
// milliseconds forward, so splitting one usage period into many ticks bills
// exactly the same as one long tick.

export interface MeterPlan {
/** Price of one second of usage, in smallest units. */
ratePerSecond: bigint;
/** Seconds at the start of each billing period that are not charged. */
freeSeconds: number;
/** Most that may be charged in one billing period; null means no cap. */
periodCap: bigint | null;
/** Accrued, unsettled amount at which a settlement batch is due. */
settlementThreshold: bigint;
}

export interface MeterState {
/** Time up to which usage has been counted, in epoch milliseconds. */
accruedUntilMs: number;
/** Milliseconds already counted toward the next whole second. */
carryMs: number;
/** Whole seconds of usage counted in this period (free seconds included). */
usedSeconds: number;
/** Charged but not yet settled. */
unsettled: bigint;
/** Total charged in this period; the cap applies to this. */
chargedInPeriod: bigint;
/** Whether usage is currently running. */
running: boolean;
}

export interface SettlementBatch {
/** Stable id so a retried settlement can be recognised as a duplicate. */
id: string;
amount: bigint;
/** The usage period the batch covers, in epoch milliseconds. */
fromMs: number;
toMs: number;
}

export function validatePlan(plan: MeterPlan): string | null {
if (plan.ratePerSecond <= 0n) return 'ratePerSecond must be positive.';
if (!Number.isInteger(plan.freeSeconds) || plan.freeSeconds < 0) return 'freeSeconds must be a non-negative integer.';
if (plan.periodCap !== null && plan.periodCap < 0n) return 'periodCap must not be negative.';
if (plan.settlementThreshold <= 0n) return 'settlementThreshold must be positive.';
return null;
}

export function newMeter(nowMs: number): MeterState {
return { accruedUntilMs: nowMs, carryMs: 0, usedSeconds: 0, unsettled: 0n, chargedInPeriod: 0n, running: false };
}

/** Starts counting usage from `nowMs`. Starting a running meter changes nothing. */
export function startUsage(state: MeterState, nowMs: number): MeterState {
if (state.running) return state;
return { ...state, running: true, accruedUntilMs: nowMs, carryMs: 0 };
}

/**
* Counts usage up to `nowMs` and charges for the whole seconds that passed.
* A clock that runs backwards, or a stopped meter, charges nothing and leaves
* the state untouched.
*/
export function accrue(plan: MeterPlan, state: MeterState, nowMs: number): MeterState {
if (!state.running || nowMs <= state.accruedUntilMs) return state;

const totalMs = state.carryMs + (nowMs - state.accruedUntilMs);
const wholeSeconds = Math.floor(totalMs / 1000);
const carryMs = totalMs - wholeSeconds * 1000;

const usedSeconds = state.usedSeconds + wholeSeconds;
const chargeableBefore = Math.max(0, state.usedSeconds - plan.freeSeconds);
const chargeableAfter = Math.max(0, usedSeconds - plan.freeSeconds);

let charge = BigInt(chargeableAfter - chargeableBefore) * plan.ratePerSecond;
if (plan.periodCap !== null) {
const room = plan.periodCap - state.chargedInPeriod;
if (charge > room) charge = room > 0n ? room : 0n;
}

return {
...state,
accruedUntilMs: nowMs,
carryMs,
usedSeconds,
unsettled: state.unsettled + charge,
chargedInPeriod: state.chargedInPeriod + charge,
};
}

/** Stops usage after counting everything up to `nowMs`. */
export function stopUsage(plan: MeterPlan, state: MeterState, nowMs: number): MeterState {
const counted = accrue(plan, state, nowMs);
return { ...counted, running: false, carryMs: 0 };
}

export function isSettlementDue(plan: MeterPlan, state: MeterState): boolean {
return state.unsettled >= plan.settlementThreshold;
}

/**
* Takes the unsettled amount out of the meter as one batch. Returns null when
* nothing is due. With `force` the batch is taken even below the threshold
* (used when a period closes). The batch id is derived from the period it
* covers, so a retry of the same settlement carries the same id.
*/
export function takeSettlement(
plan: MeterPlan,
state: MeterState,
meterId: string,
lastSettledMs: number,
force = false,
): { state: MeterState; batch: SettlementBatch | null } {
if (state.unsettled <= 0n || (!force && !isSettlementDue(plan, state))) return { state, batch: null };
const batch: SettlementBatch = {
id: `${meterId}:${lastSettledMs}-${state.accruedUntilMs}`,
amount: state.unsettled,
fromMs: lastSettledMs,
toMs: state.accruedUntilMs,
};
return { state: { ...state, unsettled: 0n }, batch };
}

/** Starts a new billing period: counters reset, unsettled usage is kept. */
export function rollPeriod(state: MeterState): MeterState {
return { ...state, usedSeconds: 0, chargedInPeriod: 0n, carryMs: state.running ? state.carryMs : 0 };
}
Loading