19 lines · 842 B
import { env } from "cloudflare:workers";
import { periodOf, resolveAccount, validate, writeAnalytics } from "./record";
import type { UsageInput } from "./record";

/**
 * `recordUsage` for high-volume, non-blocking meters: the event goes to the account's MeterBuffer and
 * reaches D1 in a batch within seconds. Same idempotency guarantees; returns false for a repeated key.
 */
export async function recordUsageBuffered(input: UsageInput): Promise<boolean> {
  validate(input);
  if (input.quantity === 0) return false;
  const at = input.at ?? Date.now();
  const accountId = await resolveAccount(input.accountId);
  const buffer = env.METER_BUFFER.get(env.METER_BUFFER.idFromName(accountId));
  const inserted = await buffer.add(input, accountId, at);
  if (inserted) writeAnalytics(input, accountId, periodOf(at));
  return inserted;
}