import { all, first, run } from "../db"; import { randomId } from "../crypto"; export const EDITOR_INSTANCE_TYPE = "standard-1"; const MINUTE_MS = 60 * 1000; const MAX_OPEN_SESSIONS = 20; export type ContainerUsageEvent = { kind: "editor.container.minutes"; accountId: string; repoId: string; sessionId: string; instanceType: string; minutes: number; startedAt: number; stoppedAt: number; }; /** Usage-metering integration point: the metering workstream registers its recorder here. */ let meterHook: ((event: ContainerUsageEvent) => Promise) | null = null; export function setContainerMeterHook(hook: ((event: ContainerUsageEvent) => Promise) | null): void { meterHook = hook; } function monthStart(now = new Date()): number { return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1); } /** Minutes used this calendar month, counting running sessions up to now (rounded up per session). */ export async function containerMinutesThisMonth(accountId: string): Promise { const now = Date.now(); const start = monthStart(); const rows = await all<{ started_at: number; stopped_at: number | null }>( `SELECT started_at, stopped_at FROM editor_container_sessions WHERE account_id = ? AND (stopped_at IS NULL OR stopped_at >= ?) LIMIT 1000`, accountId, start, ); let minutes = 0; for (const row of rows) minutes += Math.ceil(((row.stopped_at ?? now) - Math.max(row.started_at, start)) / MINUTE_MS); return minutes; } export async function openContainerSession(accountId: string, repoId: string, branch: string): Promise { const open = await first<{ count: number }>( "SELECT COUNT(*) AS count FROM editor_container_sessions WHERE account_id = ? AND stopped_at IS NULL", accountId, ); if ((open?.count ?? 0) >= MAX_OPEN_SESSIONS) throw new Error("Too many running containers for this account"); const id = randomId(); await run( `INSERT INTO editor_container_sessions (id, account_id, repo_id, branch, instance_type, started_at) VALUES (?, ?, ?, ?, ?, ?)`, id, accountId, repoId, branch, EDITOR_INSTANCE_TYPE, Date.now(), ); return id; } /** Closes a session row with its billed minutes (rounded up, at least one) and reports it once. */ export async function closeContainerSession(sessionId: string, reason: string): Promise { const now = Date.now(); const row = await first<{ account_id: string; repo_id: string; started_at: number; minutes: number }>( `UPDATE editor_container_sessions SET stopped_at = ?1, minutes = MAX(1, (?1 - started_at + ${MINUTE_MS - 1}) / ${MINUTE_MS}), stop_reason = ?2 WHERE id = ?3 AND stopped_at IS NULL RETURNING account_id, repo_id, started_at, minutes`, now, reason, sessionId, ); if (!row) return 0; await meterHook?.({ kind: "editor.container.minutes", accountId: row.account_id, repoId: row.repo_id, sessionId, instanceType: EDITOR_INSTANCE_TYPE, minutes: row.minutes, startedAt: row.started_at, stoppedAt: now, }).catch((error: unknown) => console.error("container metering hook failed", error)); return row.minutes; }