Files
orca/cloud/apps/billing/src/usage.ts
T
Neil ec8cfe5dac feat(cloud): ENTITLEMENTS-A plans catalog, entitlement grants and resolver in billing D1 (shadow on dev)
- migration 0008: plans, immutable plan_versions, plan_prices (Stripe mirror), entitlement_grants,
  entitlement_audit, entitlement_shadow_diffs, stripe_sync_state; subscriptions.seat_price_id
- catalog/catalog.json (catalog-as-code: Team, Enterprise, Trial; no prices) + scripts/catalog-apply.ts
- typed entitlement registry (entitlement-keys.ts) with sum/max/union/or aggregation
- grants.ts: idempotent projection of each subscription (Stripe mirror) and trial into grants,
  hold/release/revoke, out-of-order guard, terminal revocation, audit; manual/promo grants
- entitlements.ts: one builder fed by legacy terms or grant terms; ENTITLEMENTS_MODE off|shadow|on;
  shadow records every disagreement; lazy re-projection; cron backfill
- trial hours come from the catalog's trial plan when on (granted trials keep their hours)
- the whole suite runs in legacy, shadow (zero diffs enforced) and on modes
2026-11-11 22:11:18 -08:00

135 lines
4.9 KiB
TypeScript

// Sandbox usage ingestion (control plane -> billing) and the Stripe meter outbox.
// Only overage reaches Stripe, and only for accounts that opted in, up to their monthly spend cap:
// included hours are tracked here (pooled across seats, monthly even on annual plans, which tiered
// Stripe prices cannot express); the overage price is a flat per-hour rate billed by the minute: a
// metered per-minute price on a "standard seconds" meter with transform_quantity divide_by=60.
// Metering stays in seconds (exact per segment); Stripe rounds the period total up to a minute.
import { z } from 'zod'
import type { Env } from './env'
import { MACHINE_SIZE_WEIGHT, MACHINE_SIZES, capSeconds } from './plans'
import { accountTerms, subscriptionWindow } from './entitlements'
import type { StripeClient } from './stripe'
import {
accountSettings,
currentSubscription,
customerFor,
insertUsage,
markMeterReport,
pendingMeterReports,
usageOverage
} from './store'
import { refreshTrialUsage } from './trial'
// One segment is at most a day: the control plane settles running sandboxes periodically.
const MAX_SEGMENT_MS = 24 * 3600 * 1000
// Stripe accepts meter events up to 35 days old and 5 minutes in the future.
const MAX_AGE_MS = 30 * 24 * 3600 * 1000
const FUTURE_SKEW_MS = 5 * 60 * 1000
export const MAX_METER_ATTEMPTS = 10
const ID = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/)
export const UsageReportSchema = z
.object({
usageId: ID,
accountId: ID,
sandboxId: ID,
machineSize: z.enum(MACHINE_SIZES),
startedAt: z.number().int().positive(),
endedAt: z.number().int().positive(),
// The member who started the sandbox (attribution and per-member caps).
userId: ID.optional()
})
.strict()
export type UsageReport = z.infer<typeof UsageReportSchema>
export function validateSegment(report: UsageReport, now: number): string | null {
if (report.endedAt <= report.startedAt) {
return 'empty_segment'
}
if (report.endedAt - report.startedAt > MAX_SEGMENT_MS) {
return 'segment_too_long'
}
if (report.endedAt > now + FUTURE_SKEW_MS) {
return 'segment_in_future'
}
if (report.endedAt < now - MAX_AGE_MS) {
return 'segment_too_old'
}
return null
}
export async function recordUsage(
env: Env,
report: UsageReport,
now: number
): Promise<{ recorded: boolean; weightedSeconds: number; overageSeconds: number }> {
const db = env.BILLING_DB
const [subscription, settings, terms] = await Promise.all([
currentSubscription(db, report.accountId),
accountSettings(db, report.accountId),
accountTerms(env, report.accountId, now)
])
const wallSeconds = Math.ceil((report.endedAt - report.startedAt) / 1000)
const weightedSeconds = wallSeconds * MACHINE_SIZE_WEIGHT[report.machineSize]
// A segment counts in the allowance window it ended in.
const window = subscription ? subscriptionWindow(subscription, report.endedAt) : null
const billable =
subscription !== null && settings.overage_opt_in === 1 && subscription.overage_item_id !== null && terms.overageAllowed
const customer = billable ? await customerFor(db, report.accountId) : null
const recorded = await insertUsage(db, {
usageId: report.usageId,
accountId: report.accountId,
sandboxId: report.sandboxId,
machineSize: report.machineSize,
startedAt: report.startedAt,
endedAt: report.endedAt,
weightedSeconds,
periodStart: window?.start ?? null,
includedSeconds: subscription ? terms.includedSeconds : 0,
now,
userId: report.userId ?? null,
meterCustomer: customer,
meterCapSeconds: capSeconds(terms, settings.spend_cap_cents ?? terms.defaultSpendCapCents)
})
if (!subscription) {
// No plan: the segment counts against the one-time trial, if any (never overage).
await refreshTrialUsage(db, report.accountId, now)
}
return { recorded, weightedSeconds, overageSeconds: await usageOverage(db, report.usageId) }
}
/** Sends pending meter reports (one usage id, or the oldest batch for the cron). */
export async function flushMeterReports(
env: Env,
stripe: StripeClient,
now: number,
options: { usageId?: string; limit?: number } = {}
): Promise<{ sent: number; failed: number }> {
const pending = await pendingMeterReports(env.BILLING_DB, options.limit ?? 100, options.usageId)
let sent = 0
let failed = 0
for (const report of pending) {
try {
await stripe.createMeterEvent({
eventName: env.STRIPE_METER_EVENT_NAME,
customer: report.stripe_customer_id,
value: report.seconds,
identifier: report.usage_id,
timestamp: report.event_timestamp
})
await markMeterReport(env.BILLING_DB, report.usage_id, { sent: true, now })
sent++
} catch (error) {
failed++
await markMeterReport(env.BILLING_DB, report.usage_id, {
sent: false,
error: error instanceof Error ? error.message : 'unknown',
giveUp: report.attempts + 1 >= MAX_METER_ATTEMPTS
})
}
}
return { sent, failed }
}