| 1 | import type { GuardrailSettings, RunKind } from "@g1t/contracts"; |
| 2 | import { microsOf, money } from "./money.ts"; |
| 3 | |
| 4 | /** A number from a field; empty means inherit. Not a number is kept, to be refused. */ |
| 5 | function amount(value: FormDataEntryValue | null): number | null { |
| 6 | const text = String(value ?? "").trim().replace(/^\$/, ""); |
| 7 | if (!text) return null; |
| 8 | const number = Number(text); |
| 9 | return Number.isFinite(number) ? number : Number.NaN; |
| 10 | } |
| 11 | |
| 12 | /** The kinds of run that still use a sandbox: checks, the merge queue and merge checks. */ |
| 13 | export const SANDBOX_RUN_KINDS = ["checks", "queue", "mergecheck"] as const satisfies readonly RunKind[]; |
| 14 | |
| 15 | /** |
| 16 | * What one level's form says, as the settings that level keeps: a time cap |
| 17 | * for each kind of run it sets, the rest inherited. |
| 18 | */ |
| 19 | export function settingsFromForm(form: FormData, catalog: { kinds: readonly RunKind[] }): GuardrailSettings { |
| 20 | const minutes: Record<string, number> = {}; |
| 21 | for (const kind of catalog.kinds) { |
| 22 | const cap = amount(form.get(`minutes:${kind}`)); |
| 23 | if (cap != null) minutes[kind] = Number.isNaN(cap) ? 0 : Math.trunc(cap); |
| 24 | } |
| 25 | return { minutes }; |
| 26 | } |
| 27 | |
| 28 | /** A cost in dollars, or "no cap". */ |
| 29 | export function formatCap(usd: number | null | undefined): string { |
| 30 | return usd == null ? "no cap" : money(microsOf(usd)); |
| 31 | } |
| 32 | |
| 33 | /** How full a cap is, from 0 to 1, or null with no cap. */ |
| 34 | export function capShare(used: number | null | undefined, cap: number | null | undefined): number | null { |
| 35 | if (cap == null || cap <= 0 || used == null) return null; |
| 36 | return Math.min(1, Math.max(0, used / cap)); |
| 37 | } |