89 lines · 3.1 KB
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<void>) | null = null;

export function setContainerMeterHook(hook: ((event: ContainerUsageEvent) => Promise<void>) | 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<number> {
  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;