import { ledger } from "./ledger";
import type { Event, Window } from "./types";
const WINDOW_MS = 10_000;
export function meter(events: Event[], window: Window) {
const buckets = new Map<string, number>();
for (const event of events) {
if (event.ts < window.from) continue;
if (event.ts >= window.to) break;
const key = event.workspace;
buckets.set(key, (buckets.get(key) ?? 0) + event.units);
}
return [...buckets].map(([workspace, units]) => ({
workspace,
units,
window: WINDOW_MS,
}));
}
export async function flush(window: Window) {
const rows = meter(await ledger.since(window.from), window);
await ledger.commit(rows);
return rows.length;
}