Skip to content
239 linesCodeBlameRaw
1import assert from "node:assert/strict";
2import { test } from "node:test";
3
4import type { CostDay, PlatformGuard, SpendCaps } from "@g1t/contracts";
5
6import {
7 count,
8 daySeries,
9 daysBetween,
10 marginOnPrice,
11 marginPercent,
12 marginTone,
13 parseBucket,
14 parseCostSettings,
15 parseMapping,
16 parsePauseLevel,
17 pauseBanner,
18 parseRange,
19 percentLabel,
20 proposalOutcome,
21 spendBanner,
22 spendRows,
23 subscriptionsOver,
24 thresholdShare,
25 unitDollars,
26 versionCells,
27 whoPaid,
28} from "./costs.ts";
29
30const day = (d: string, bucket: string, cf: number, own: number, value: number, cash: number): CostDay => ({
31 day: d,
32 bucket,
33 cfCostMicros: cf,
34 ownCostMicros: own,
35 valueMicros: value,
36 cashMicros: cash,
37});
38
39test("every day of the range is there, even an empty one", () => {
40 assert.deepEqual(daysBetween("2026-09-29", "2026-10-02"), ["2026-09-29", "2026-09-30", "2026-10-01", "2026-10-02"]);
41 assert.deepEqual(daysBetween("2026-10-02", "2026-10-01"), []);
42});
43
44test("all of g1t is money in against every cost; a product is its value against its cost", () => {
45 const rows = [
46 day("2026-10-01", "sandboxes", 2_000_000, 1_900_000, 2_400_000, 1_000_000),
47 day("2026-10-01", "platform", 500_000, 0, 20_000_000, 20_000_000),
48 // Models: no Cloudflare bill, g1t's own cost.
49 day("2026-10-01", "models", 0, 100_000, 120_000, 120_000),
50 ];
51 const all = daySeries(rows, "2026-10-01", "2026-10-02", null);
52 assert.deepEqual(all, [
53 { day: "2026-10-01", revenueMicros: 21_120_000, costMicros: 2_600_000 },
54 { day: "2026-10-02", revenueMicros: 0, costMicros: 0 },
55 ]);
56 const sandboxes = daySeries(rows, "2026-10-01", "2026-10-01", "sandboxes");
57 assert.deepEqual(sandboxes, [{ day: "2026-10-01", revenueMicros: 2_400_000, costMicros: 2_000_000 }]);
58});
59
60test("margins read against the floor", () => {
61 assert.equal(marginPercent(1_200_000, 1_000_000)?.toFixed(2), "16.67");
62 assert.equal(marginPercent(0, 10), null);
63 assert.equal(marginTone(-3, 10), "danger");
64 assert.equal(marginTone(12, 10), "warn");
65 assert.equal(marginTone(16.7, 10), "mint");
66 assert.equal(marginTone(null, 10), undefined);
67 assert.equal(percentLabel(-4), "−4.0%");
68 assert.equal(percentLabel(12.34, { signed: true }), "+12.3%");
69 assert.equal(percentLabel(null), "—");
70});
71
72test("unit costs keep the places they need", () => {
73 assert.equal(unitDollars(150_000), "$0.150");
74 assert.equal(unitDollars(16.44), "$0.0000164");
75 assert.equal(unitDollars(2_500_000), "$2.50");
76 assert.equal(unitDollars(0), "$0");
77});
78
79test("the range and product come from the address, within bounds", () => {
80 assert.equal(parseRange("7"), 7);
81 assert.equal(parseRange("365"), 30);
82 assert.equal(parseRange(null), 30);
83 assert.equal(parseBucket("git", ["git", "sandboxes"]), "git");
84 assert.equal(parseBucket("nope", ["git"]), null);
85});
86
87const form = (entries: Record<string, string>) => {
88 const data = new FormData();
89 for (const [key, value] of Object.entries(entries)) data.set(key, value);
90 return data;
91};
92
93test("the guardrails form is checked", () => {
94 const good = parseCostSettings(
95 form({
96 autoApply: "on",
97 autoApplyPercent: "25",
98 noticeDays: "14",
99 marginFloorPercent: "10",
100 alertDays: "3",
101 anomalyFactor: "1",
102 minDailyCost: "0.10",
103 anomalyFloor: "1",
104 }),
105 );
106 assert.ok(good.ok);
107 assert.equal(good.ok && good.value.minDailyCostMicros, 100_000);
108 assert.equal(good.ok && good.value.autoApply, true);
109 const off = parseCostSettings(form({ autoApplyPercent: "25", noticeDays: "14", marginFloorPercent: "10", alertDays: "3", anomalyFactor: "1", minDailyCost: "0", anomalyFloor: "1" }));
110 assert.ok(off.ok && !off.value.autoApply);
111 assert.equal(parseCostSettings(form({ autoApplyPercent: "250" })).ok, false);
112 assert.equal(parseCostSettings(form({ autoApplyPercent: "25", noticeDays: "1.5" })).ok, false);
113});
114
115test("a mapping names Cloudflare's product and meter and one of g1t's products", () => {
116 const mapped = parseMapping(form({ product: "Artifacts", meter: "", bucket: "git", priceMeter: "git_operations", ownMeter: "git_operations", scaleToOwn: "on", driftPercent: "15" }));
117 assert.deepEqual(mapped, {
118 ok: true,
119 value: { product: "artifacts", meter: "*", bucket: "git", priceMeter: "git_operations", ownMeter: "git_operations", scaleToOwn: true, driftPercent: 15, note: "" },
120 });
121 assert.deepEqual(parseMapping(form({ product: "r2", meter: "class_a", remove: "1" })), { ok: true, value: { product: "r2", meter: "class_a", remove: true } });
122 assert.equal(parseMapping(form({ product: "r2", meter: "x y", bucket: "git" })).ok, false);
123 assert.equal(parseMapping(form({ product: "r2", meter: "*", bucket: "" })).ok, false);
124 assert.equal(parseMapping(form({ product: "r2", meter: "*", bucket: "git", driftPercent: "-1" })).ok, false);
125});
126
127const caps = (over: Partial<SpendCaps> = {}): SpendCaps => ({
128 day: "2026-10-06",
129 month: "2026-10",
130 todayMicros: 20_000_000,
131 dailyCapMicros: 75_000_000,
132 tripped: false,
133 trippedAt: null,
134 liftedBy: null,
135 liftedAt: null,
136 liftNote: null,
137 monthBuckets: [
138 { bucket: "comped", title: "Comped (g1t's own)", micros: 40_000_000 },
139 { bucket: "trial", title: "Trial pool", micros: 5_000_000 },
140 ],
141 comped: [{ account: "ws_flagon-io", name: "flagon-io", usedMicros: 40_000_000, ceilingMicros: 150_000_000, defaultCeiling: true, level: 0 }],
142 freeTierMicros: 1_000_000,
143 fixedMonthlyMicros: 30_000_000,
144 revenueMicros: 0,
145 ...over,
146});
147
148test("the spend bar shows only when a cap stops work", () => {
149 assert.equal(spendBanner(caps()), null);
150 assert.ok((spendBanner(caps({ tripped: true, todayMicros: 80_000_000 })) ?? "").startsWith("The daily breaker is open ($80.00 of $75.00 today)"));
151 const usedUp = caps({ comped: [{ account: "ws_flagon-io", name: "flagon-io", usedMicros: 150_000_000, ceilingMicros: 150_000_000, defaultCeiling: true, level: 100 }] });
152 assert.ok((spendBanner(usedUp) ?? "").startsWith("Flagon-io used its $150.00 monthly budget"));
153 // No budget set to zero is ever "used up".
154 assert.equal(spendBanner(caps({ comped: [{ account: "a", name: "a", usedMicros: 9, ceilingMicros: 0, defaultCeiling: false, level: 0 }] })), null);
155});
156
157test("what g1t paid this month adds every bucket, the free tier and subscriptions", () => {
158 const { rows, totalMicros } = spendRows(caps());
159 assert.deepEqual(rows.map((r) => r.key), ["comped", "trial", "free", "fixed"]);
160 assert.equal(totalMicros, 76_000_000);
161});
162
163test("charged without real money is what it cost g1t, never its price", () => {
164 const { rows } = spendRows(caps({ monthBuckets: [{ bucket: "unpaid", title: "Charged without real money", micros: 7_610_000 }] }));
165 assert.match(rows[0]!.note, /what it cost g1t, not what was charged/);
166});
167
168test("margins are a share of the price: cost plus 20% is 16.7%", () => {
169 assert.equal(percentLabel(marginOnPrice(20)), "16.7%");
170 assert.equal(marginOnPrice(0), 0);
171 // As By product showed it: $2.99 charged for models that cost $2.49.
172 assert.equal(percentLabel(marginPercent(2_988_000, 2_490_000)), "16.7%");
173});
174
175test("who g1t paid is the statement's all-in cost, subscriptions included", () => {
176 const subscriptions = subscriptionsOver(30_000_000, 30);
177 const paid = whoPaid({ costMicros: 2_490_000, cloudflareCostMicros: 0, modelsCostMicros: 2_490_000 }, subscriptions);
178 assert.deepEqual(paid, { totalMicros: 32_490_000, cloudflareMicros: 0, subscriptionsMicros: 30_000_000, modelsMicros: 2_490_000 });
179 assert.equal(subscriptionsOver(30_000_000, 7), 7_000_000);
180 // From older billing, Cloudflare's part is the rest.
181 assert.equal(whoPaid({ costMicros: 3_000_000, modelsCostMicros: 1_000_000 }, 0).cloudflareMicros, 2_000_000);
182});
183
184test("a rate g1t sets shows no cost, and a weight is no money", () => {
185 assert.deepEqual(versionCells({ costMicros: 250_000, priceMicros: 250_000, basis: "rate" }), {
186 cost: "—",
187 price: "$0.250",
188 note: "g1t's own rate: no cost behind it",
189 });
190 assert.equal(versionCells({ costMicros: 100_000, priceMicros: 100_000, basis: "weight" }).price, "×0.1");
191 assert.deepEqual(versionCells({ costMicros: 16.44, priceMicros: 19.73, basis: "cost" }), { cost: unitDollars(16.44), price: unitDollars(19.73), note: null });
192 // Older billing sends no basis: a cost.
193 assert.equal(versionCells({ costMicros: 1_000_000, priceMicros: 1_200_000 }).cost, "$1.00");
194});
195
196test("a rise replaced before its date says so, rather than missing its date", () => {
197 assert.equal(
198 proposalOutcome({ status: "superseded", decidedBy: "guardrail", effectiveAt: null }),
199 "applied by guardrail, then replaced by a later measurement before it took effect; nothing was charged at it",
200 );
201 // From before billing marked them superseded.
202 assert.match(proposalOutcome({ status: "applied", decidedBy: "guardrail", effectiveAt: null }) ?? "", /replaced by a later measurement/);
203 assert.equal(proposalOutcome({ status: "applied", decidedBy: "guardrail", effectiveAt: "2026-10-22T04:18:12.571Z" }), "applied by guardrail");
204 assert.equal(proposalOutcome({ status: "superseded", decidedBy: null, effectiveAt: null }), "replaced by a later measurement");
205 assert.equal(proposalOutcome({ status: "open", decidedBy: null, effectiveAt: null }), null);
206});
207
208test("the pause banner names every paused level, and who paused it when it was not a person", () => {
209 const level = (name: "compute" | "schedules" | "indexing" | "renders", paused: boolean, auto = false) => ({
210 level: name,
211 paused,
212 note: null,
213 set_by: null,
214 set_at: null,
215 auto,
216 });
217 const guard = (levels: ReturnType<typeof level>[]): PlatformGuard => ({
218 levels,
219 hour: null,
220 last_hour: [],
221 month: "2026-10",
222 month_to_date: [],
223 breaches: [],
224 can_read: true,
225 auto_pause: ["schedules", "indexing"],
226 });
227 assert.equal(pauseBanner(guard([level("compute", false), level("renders", false)])), null);
228 assert.equal(pauseBanner(guard([level("schedules", true, true)])), "Paused across g1t: schedules (by the usage watcher).");
229 assert.equal(
230 pauseBanner(guard([level("compute", true), level("schedules", true), level("indexing", true, true)])),
231 "Paused across g1t: compute, schedules and indexing (by the usage watcher).",
232 );
233 assert.equal(parsePauseLevel("renders"), "renders");
234 assert.equal(parsePauseLevel("everything"), null);
235 assert.equal(count(240_000), "240k");
236 assert.equal(count(2_000_000_000), "2.0B");
237 assert.equal(thresholdShare(240_000, 200_000), 120);
238 assert.equal(thresholdShare(5, 0), null);
239});