Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

113 linesCodeBlameRaw
1import assert from "node:assert/strict";
2import { readFileSync, readdirSync } from "node:fs";
3import { DatabaseSync } from "node:sqlite";
4import { test } from "node:test";
5
6// A month-end source's figure reported after its month was charged or
7// closed: the production SQL of `late_correction` (src/storage.rs).
8const source = (name) => readFileSync(new URL(`../services/billing/src/${name}.rs`, import.meta.url), "utf8");
9const sqlFile = (name) => readFileSync(new URL(`../services/billing/src/${name}.sql`, import.meta.url), "utf8");
10const constant = (file, name) => {
11 const match = source(file).match(new RegExp(`const ${name}: &str = "([\\s\\S]*?)";`));
12 assert.ok(match, `${file}::${name}`);
13 return match[1];
14};
15function database() {
16 const db = new DatabaseSync(":memory:");
17 const dir = new URL("../services/billing/migrations/", import.meta.url);
18 for (const name of readdirSync(dir)
19 .filter((n) => n.endsWith(".sql"))
20 .sort())
21 db.exec(readFileSync(new URL(name, dir), "utf8"));
22 return db;
23}
24function batch(db, writes) {
25 db.exec("BEGIN");
26 try {
27 const rows = writes.map(([sql, args]) => db.prepare(sql).all(...args));
28 db.exec("COMMIT");
29 return rows;
30 } catch (e) {
31 db.exec("ROLLBACK");
32 throw e;
33 }
34}
35const now = "2026-11-03T10:00:00.000Z";
36// One late report, as `late_correction` sends it: the raise, the guarded
37// ledger line, the allocation and the balance, in one batch.
38function late(db, id, workspace, newCost, charge, oldRaw, { plan = 0 } = {}) {
39 const raise = constant("storage", "LATE_RAISE");
40 const ledger = constant("storage", "LATE_LEDGER");
41 const balanceSql = source("storage")
42 .split("pub(crate) fn balance_if_posted(")[1]
43 .match(/\.prepare\(\s*"([\s\S]*?)"\s*,?\s*\)/)[1];
44 const reference = `storage/${workspace}/2026-10/late/${newCost}`;
45 const rows = batch(db, [
46 [raise, [workspace, "storage", "2026-10", newCost, newCost, now, null, oldRaw]],
47 [ledger, [id, workspace, -charge, "Late", "storage", newCost - oldRaw, reference, "2026-10-31T23:59:59Z", null, "2026-10", newCost]],
48 [sqlFile("allocate_usage"), [id, workspace, "2026-10", plan, 0, "", 0, 0, 0]],
49 [constant("allocation", "PLAN"), [id, "2026-10"]],
50 [constant("allocation", "GIFT"), [id, "2026-10"]],
51 [balanceSql, [workspace, now, id]],
52 ]);
53 return rows[1].length === 1;
54}
55function charged(db, workspace, cost) {
56 db.prepare(
57 "INSERT INTO pending_usage (workspace, source, month, charge_micros, cost_micros, updated_at, charged_at) VALUES (?, 'storage', '2026-10', ?, ?, ?, ?)",
58 ).run(workspace, cost, cost, now, now);
59}
60const owed = (db, workspace) => db.prepare("SELECT balance_micros FROM accounts WHERE workspace=?").get(workspace)?.balance_micros ?? 0;
61
62test("a late higher figure charges only what it adds, once", () => {
63 const db = database();
64 charged(db, "acme", 5_000_000);
65 assert.equal(late(db, "a", "acme", 7_000_000, 2_400_000, 5_000_000), true);
66 assert.equal(owed(db, "acme"), -2_400_000);
67 assert.equal(db.prepare("SELECT cost_micros FROM pending_usage WHERE workspace='acme'").get().cost_micros, 7_000_000);
68 // The same report again: worked out from the new figure, nothing changes.
69 assert.equal(late(db, "b", "acme", 7_000_000, 2_400_000, 5_000_000), false);
70 assert.equal(owed(db, "acme"), -2_400_000);
71 assert.equal(db.prepare("SELECT COUNT(*) n FROM ledger").get().n, 1);
72 db.close();
73});
74
75test("of two late reports worked out from the same figure, only one is charged", () => {
76 const db = database();
77 charged(db, "acme", 5_000_000);
78 assert.equal(late(db, "a", "acme", 8_000_000, 3_600_000, 5_000_000), true);
79 // A stale writer that read 5,000,000 before the first moved it.
80 assert.equal(late(db, "b", "acme", 6_000_000, 1_200_000, 5_000_000), false);
81 assert.equal(owed(db, "acme"), -3_600_000);
82 assert.equal(db.prepare("SELECT cost_micros FROM pending_usage WHERE workspace='acme'").get().cost_micros, 8_000_000);
83 db.close();
84});
85
86test("a closed month with no row yet takes the late figure as a charged row", () => {
87 const db = database();
88 db.prepare("INSERT INTO month_closes (workspace, month, status, amount_micros, closed_at) VALUES ('acme', '2026-10', 'charged', 0, ?)").run(now);
89 // The ordinary report is refused for a closed month…
90 db.prepare(constant("storage", "SET_PENDING")).run("acme", "storage", "2026-10", 1, 1, now, null);
91 assert.equal(db.prepare("SELECT COUNT(*) n FROM pending_usage").get().n, 0);
92 // …and the late one charges it, and marks the row charged.
93 assert.equal(late(db, "a", "acme", 4_000_000, 4_800_000, 0), true);
94 assert.equal(owed(db, "acme"), -4_800_000);
95 assert.ok(db.prepare("SELECT charged_at FROM pending_usage WHERE workspace='acme'").get().charged_at.startsWith("late: "));
96 db.close();
97});
98
99test("a late correction draws on that month's allowances first", () => {
100 const db = database();
101 charged(db, "acme", 1_000_000);
102 db.prepare("INSERT INTO allowance_use (kind, scope, month, used) VALUES ('plan_credit', 'acme', '2026-10', 9000000)").run();
103 assert.equal(late(db, "a", "acme", 3_000_000, 2_400_000, 1_000_000, { plan: 10_000_000 }), true);
104 assert.deepEqual({ ...db.prepare("SELECT amount_micros, credit_micros FROM ledger").get() }, { amount_micros: -1_400_000, credit_micros: 1_000_000 });
105 assert.equal(db.prepare("SELECT used FROM allowance_use WHERE kind='plan_credit'").get().used, 10_000_000);
106 db.close();
107});
108
109test("only a raise is charged: a lower late figure changes nothing", () => {
110 const src = source("storage");
111 assert.match(src, /pub\(crate\) fn late_delta\(charged_net: i64, new_net: i64\) -> i64 \{\s*\(new_net - charged_net\)\.max\(0\)/);
112 assert.match(src, /if new_cost < raw_old \{[\s\S]*?return Ok\(true\);/);
113});