Public: anyone can read this; the crew can change it.

The forge watches its cloud accounts hourly and says at once when a provider… #16529

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16329-the-forge-watches-its-cloud-accounts-hou → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/16329-the-forge-watches-its-cloud-accounts-hou was merged into main as 1a27c7d.

Review

Sign in to review this change.
23 files changed +858 −9
docs/features/cloud.md +14
@@ -60,3 +60,17 @@ A prepared machine already booted and waiting, unclaimed and with no name, answe
6060 - Set it with the MCP `cloud_account` verb `set_warm` (`place`, `count` 0 to 10, admin scope); it is recorded as `cloud.warm_target`.
6161
6262 Not done: making and refilling the machines themselves, and a form on the page and a key in the terminal to set the count; this lands the policy, the setting, the counting and the display.
63
64 ## The hourly watch (#16329)
65
66 The ceiling counts only what the forge's own rows say it made. The `cloud-watch` duty (`src/maintain/duties/cloud_watch.ts`, `src/cloud/watch.ts`) looks at the provider itself once an hour for each DigitalOcean or Hetzner account that allows writes: read-only GETs of droplets or servers and volumes, recorded like the other cloud calls (`maintain:cloud-watch`).
67
68 - A thing named `forge-<name>` or `forge-<name>-data` with no live pinned row is an **orphan**. A thing not named so, and not acknowledged, is **outside**. Each is priced from the Places catalog beside the forge's own reckoning and the ceiling.
69 - An orphan, an outside thing, real cost over the ceiling, or a provider that could not be read raises a card in `/health` `needs`, one notification to admins and one issue (`Cloud account <provider>/<account> shows more than the forge made`). Each sentence names the thing, its age, its monthly cost and the one action that resolves it.
70 - While an orphan stands, a create on that account is refused with that sentence.
71 - **Acknowledge as not the forge's** (Settings → Cloud accounts, `o` in the terminal screen, `src/tui/screens/cloud.ts`) records everything standing as not the forge's; later readings are quiet about it, and a new one is not.
72 - Quiet when all is as expected: one line on the account says when the watch last looked and what it found.
73
74 Not done: adopting an orphan into a pinned row (retire it in the provider's console, or acknowledge it), and a read of the provider's actual bill.
75
76 The watch keeps when the standing problems began, so a standing orphan is one notification and one /health card, not one an hour. A forge-named thing made in the last two hours, or named for a live pinned row, is a deploy in flight and not an orphan. A create stays refused until the next hourly reading even after an orphan is retired in the provider's console; the refusal says so.
src/actions/cloud_ceiling.ts +14
@@ -7,6 +7,7 @@
77 import type { App } from "../app.ts";
88 import { getCloudAccount, setCeilingDollars, setProjectName } from "../core/cloud_account.ts";
99 import type { User } from "../core/users.ts";
10 import { ackWatch } from "../cloud/watch.ts";
1011 import { MAX_WARM, setWarmTarget, warmTargets } from "../cloud/warm_pool.ts";
1112 import { err, ok, type Result } from "../kernel/result.ts";
1213
@@ -35,6 +36,19 @@ export function setWarm(app: App, actor: User | undefined, provider: string, nam
3536 return ok(count === 0 ? `no machine is kept warm at ${place}` : `up to ${count} machine${count === 1 ? "" : "s"} kept warm at ${place}, as purchases and the ceiling allow`);
3637 }
3738
39 /**
40 * Say that what the hourly watch shows at an account and the forge did not make is not the forge's
41 * (#16329).
42 */
43 export function acknowledgeWatch(app: App, actor: User | undefined, provider: string, name: string): Result<string, string> {
44 if (actor?.isAdmin !== true) return err("not_found");
45 if (!getCloudAccount(app.db, provider, name)) return err("No such credential.");
46 const n = ackWatch(app.db, provider, name, actor.id);
47 if (n === 0) return err("The watch shows nothing there that needs acknowledging.");
48 app.bus.append({ kind: "cloud.watch_acknowledged", actorId: actor.id, payload: { provider, name, count: n } });
49 return ok(`${n} thing${n === 1 ? "" : "s"} at ${provider}/${name} acknowledged as not the forge's`);
50 }
51
3852 const PROJECT = /^[A-Za-z0-9][A-Za-z0-9 ._:-]{0,99}$/;
3953
4054 /** The words where a Hetzner account would name its project: its token already belongs to one. */
src/cloud/ceiling.ts +5
@@ -24,6 +24,7 @@ import { DO_VOLUME_USD_PER_GIB, VOLUME_GIB } from "./places.ts";
2424 import { keptPlaces } from "./places_read.ts";
2525 import { dollars, toUsd, type Rate } from "./prices.ts";
2626 import { keptRate } from "./rates.ts";
27 import { orphanRefusal } from "./watch_read.ts";
2728
2829 export const DEFAULT_CEILING_DOLLARS = 50;
2930
@@ -171,6 +172,10 @@ export function refusalAt(
171172 /** What orders in flight will cost, not yet in any row. */
172173 held = 0,
173174 ): string | undefined {
175 // The hourly watch saw something at the provider the forge cannot account for: nothing more is
176 // made.
177 const orphan = orphanRefusal(app.db, provider, account);
178 if (orphan !== undefined) return orphan;

A forge-named thing whose pinned row has not yet recorded its remote or volume (deploy in flight) reads as an orphan and refuses every create. Allow a grace for young things, or match against non-retired rows by name. A retired-in-console orphan also blocks until the next hourly read; say so or re-read before refusing.

174179 const who = `${provider}/${account}`;
175180 const id = place.id;
176181 const price = prices.forge(id);
src/cloud/overview.ts +4
@@ -12,6 +12,7 @@ import { listCloudAccounts, recentCloudReads } from "../core/cloud_account.ts";
1212 import type { User } from "../core/users.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
1414 import { usedFor, type VendorUse } from "./declared.ts";
15 import { watchLine } from "./watch.ts";
1516 import { spendOf } from "./ceiling.ts";
1617 import { warmOf, type WarmPlace } from "./warm_pool.ts";
1718 import { VENDOR_OF, type Provider } from "./providers.ts";
@@ -37,6 +38,8 @@ export interface AccountRow {
3738 * in monthlyCents). Empty by default.
3839 */
3940 readonly warm: WarmPlace[];
41 /** When the hourly watch last looked at the provider and what it found (`watch.ts`). */
42 readonly watch: string;
4043 }
4144
4245 export interface CloudOverview {
@@ -64,6 +67,7 @@ export function cloudOverview(
6467 callsToday: today.filter((r) => r.provider === a.provider && r.account === a.name).length,
6568 ...spendOf(app.db, a.provider, a.name),
6669 warm: warmOf(app.db, a.provider, a.name),
70 watch: watchLine(app.db, a.provider, a.name),
6771 }));
6872 return ok({ accounts, today });
6973 }
src/cloud/watch.ts added +204
@@ -0,0 +1,204 @@
1 /**
2 * The hourly watch of a cloud account (#16329). The ceiling (`ceiling.ts`) counts only what the
3 * forge's own rows say it made; this reads what the provider shows (DigitalOcean droplets and
4 * volumes, Hetzner servers and volumes: read-only GETs), sorts each thing as the forge's, an
5 * orphan, outside or acknowledged, and prices what is there from the Places catalog beside the
6 * forge's own reckoning and the ceiling.
7 *
8 * - forge's: its id is on a live pinned row (a machine of a row not retired; a volume of any row).
9 * - orphan: named as the forge names things (`forge-<name>`, `forge-<name>-data`) with no live row.
10 * - outside: not named so, and not acknowledged by an admin as not the forge's.
11 * - acknowledged: an admin said so (`ackWatch`); it is priced but raises nothing.
12 *
13 * A standing orphan refuses every create on the account (`orphanRefusal`, asked by `refusalAt`).
14 * Prices are list prices; the provider's bill is the truth.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import { listPinned } from "../core/pinned.ts";
19 import { getCloudAccount } from "../core/cloud_account.ts";
20 import { accountCents, priced, type Priced } from "./ceiling.ts";
21 import { VOLUME_GIB } from "./places.ts";
22 import { dollars } from "./prices.ts";
23 import type { Fetch } from "./providers.ts";
24 import { CLOUD_PAGE, allReadings, ageOf, describe, lastReading, type Judged, type Reading, type Seen, type Verdict } from "./watch_read.ts";
25
26 export const WATCHED = ["digitalocean", "hetzner"] as const;
27 const PER_PAGE: Record<string, number> = { digitalocean: 200, hetzner: 50 };
28 const MAX_PAGES = 10;
29 const FORGE_NAMED = /^forge-[a-z][a-z0-9-]{0,39}(-data)?$/;
30 /** A forge-named thing younger than this is a deploy in flight: its row has not yet kept its id. */
31 export const GRACE_MS = 2 * 3_600_000;
32
33 /**
34 * What the provider calls a thing is a stranger's text: it goes into sentences that reach an issue
35 * body (markdown) and a notification, so only plain characters stay and the rest becomes `?`.
36 */
37 export const plain = (s: string, max = 120): string => s.slice(0, max).replace(/[^A-Za-z0-9 ._:/()+-]/g, "?");
38 const text = (v: unknown, max = 120): string => (typeof v === "string" || typeof v === "number" ? plain(String(v), max) : "");
39
40 async function pages(f: Fetch, token: string, base: string, key: string, per: number): Promise<any[]> {
41 const out: any[] = [];
42 for (let page = 1; page <= MAX_PAGES; page++) {
43 const res = await f(`${base}${base.includes("?") ? "&" : "?"}per_page=${per}&page=${page}`, { headers: { authorization: `Bearer ${token}` } });
44 if (!res.ok) throw new Error(`${new URL(res.url || base).host || "the provider"} answered ${res.status} to ${key}`);
45 const body: any = await res.json();
46 const list: unknown = body?.[key];
47 if (!Array.isArray(list)) throw new Error(`the provider's answer to ${key} was not a list`);
48 out.push(...list.filter((x) => typeof x === "object" && x !== null));
49 if (list.length < per) return out;
50 }
51 throw new Error(`more than ${MAX_PAGES * per} ${key}: not read whole`);
52 }
53
54 /** Every machine and volume the account shows. Throws when any read fails: nothing is guessed. */
55 export async function readLive(provider: string, f: Fetch, token: string): Promise<Seen[]> {
56 const per = PER_PAGE[provider];
57 if (per === undefined) throw new Error(`${provider} is not watched`);
58 if (provider === "digitalocean") {
59 const api = "https://api.digitalocean.com/v2";
60 const [d, v] = [await pages(f, token, `${api}/droplets`, "droplets", per), await pages(f, token, `${api}/volumes`, "volumes", per)];
61 return [
62 ...d.map((x): Seen => ({ kind: "machine", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: text(x.region?.slug), size: text(x.size_slug), gib: 0 })),
63 ...v.map((x): Seen => ({ kind: "volume", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: text(x.region?.slug), size: "", gib: Number(x.size_gigabytes) || VOLUME_GIB })),
64 ];
65 }
66 const api = "https://api.hetzner.cloud/v1";
67 const [s, v] = [await pages(f, token, `${api}/servers`, "servers", per), await pages(f, token, `${api}/volumes`, "volumes", per)];
68 return [
69 ...s.map((x): Seen => ({ kind: "machine", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: text(x.datacenter?.location?.name), size: text(x.server_type?.name), gib: 0 })),
70 ...v.map((x): Seen => ({ kind: "volume", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: text(x.location?.name), size: "", gib: Number(x.size) || VOLUME_GIB })),
71 ].filter((x) => x.id !== "");
72 }
73
74 /** What a thing costs a month at list price, cents rounded up; null when the catalog has none. */
75 export function priceOf(provider: string, s: Seen, prices: Priced): number | null {
76 if (s.kind === "volume") {
77 const per = prices.volume(provider);
78 return per === undefined ? null : Math.ceil((per * s.gib) / VOLUME_GIB);
79 }
80 // The catalog prices a place whole (machine, its volume and address); the volume is taken off.
81 const whole = prices.forge(`${provider}:${s.datacenter}:${s.size}`) ?? prices.sameSize(provider, s.size);
82 if (whole === undefined) return null;
83 return Math.max(0, whole - (prices.volume(provider) ?? 0));
84 }
85
86 export const ackedIds = (db: Database, provider: string, account: string): Set<string> =>
87 new Set(
88 db
89 .query<{ kind: string; remote: string }, [string, string]>("SELECT kind, remote FROM cloud_watch_ack WHERE provider = ?1 AND account = ?2")
90 .all(provider, account)
91 .map((r) => `${r.kind}:${r.remote}`),
92 );
93
94 /** Sort what the provider shows against the forge's live rows and the admin's acknowledgements. */
95 export function judge(db: Database, provider: string, account: string, seen: readonly Seen[], prices: Priced = priced(db), now = Date.now()): Judged[] {
96 const rows = listPinned(db).filter((p) => p.target === provider && p.account === account);
97 const machines = new Set(rows.filter((p) => p.state !== "retired" && p.remote !== "").map((p) => p.remote));
98 const volumes = new Set(rows.filter((p) => p.volume !== "").map((p) => p.volume));
99 // A deploy in flight has its machine at the provider before its row holds the id: a forge-named
100 // thing of a row not retired, or one made within the grace, is the forge's own.
101 const named = new Set(rows.filter((p) => p.state !== "retired").flatMap((p) => [`forge-${p.name}`, `forge-${p.name}-data`]));
102 const young = (s: Seen): boolean => {
103 const made = Date.parse(s.createdAt);
104 return Number.isFinite(made) && now - made < GRACE_MS && made <= now + GRACE_MS;
105 };
106 const acked = ackedIds(db, provider, account);
107 return seen.map((s) => {
108 const mine = (s.kind === "machine" ? machines.has(s.id) : volumes.has(s.id)) || (FORGE_NAMED.test(s.name) && (named.has(s.name) || young(s)));
109 const verdict: Verdict = mine ? "forge" : acked.has(`${s.kind}:${s.id}`) ? "acknowledged" : FORGE_NAMED.test(s.name) ? "orphan" : "outside";
110 return { ...s, verdict, cents: priceOf(provider, s, prices) };
111 });
112 }
113
114 /** Read the provider and keep what was found (or why it could not be read). Never throws. */
115 export async function watchAccount(db: Database, provider: string, account: string, f: Fetch, token: string, now: Date): Promise<Reading> {
116 const prices = priced(db);
117 const base = { provider, account, at: now.toISOString(), ceilingCents: (getCloudAccount(db, provider, account)?.ceilingDollars ?? 0) * 100, forgeCents: accountCents(db, provider, account, prices) };
118 const before = lastReading(db, provider, account);
119 let reading: Reading;
120 try {
121 const resources = judge(db, provider, account, await readLive(provider, f, token), prices, now.getTime());
122 reading = { ...base, since: "", error: "", resources, actualCents: resources.reduce((n, r) => n + (r.cents ?? 0), 0) };
123 } catch (e) {
124 reading = { ...base, since: "", error: plain(e instanceof Error ? e.message : "failed", 200), resources: [], actualCents: 0 };
125 }
126 // The problems stand from when this set of them began, not from the last look.
127 const key = problemKey(reading);
128 const standing = key !== "" && before !== undefined && problemKey(before) === key && before.since !== "";
129 reading = { ...reading, since: key === "" ? "" : standing ? before!.since : reading.at };
130 db.query(
131 `INSERT INTO cloud_watch (provider, account, at, error, resources, actual_cents, forge_cents, ceiling_cents, since, problem_key) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)
132 ON CONFLICT(provider, account) DO UPDATE SET at = excluded.at, error = excluded.error, resources = excluded.resources,
133 actual_cents = excluded.actual_cents, forge_cents = excluded.forge_cents, ceiling_cents = excluded.ceiling_cents,
134 since = excluded.since, problem_key = excluded.problem_key`,
135 ).run(provider, account, reading.at, reading.error, JSON.stringify(reading.resources), reading.actualCents, reading.forgeCents, reading.ceilingCents, reading.since, key);
136 return reading;
137 }
138
139 /** What is wrong, by identity and not by age: the same set of things reads the same key. */
140 export function problemKey(r: Reading): string {
141 if (r.error !== "") return "error";
142 const ids = r.resources.filter((x) => x.verdict === "orphan" || x.verdict === "outside").map((x) => `${x.verdict}:${x.kind}:${x.id}`).sort();
143 if (r.ceilingCents > 0 && r.actualCents > r.ceilingCents) ids.push("over");
144 return ids.join(",");
145 }
146
147 /**
148 * What an account's last reading says is wrong, one sentence each, each naming the thing, its age,
149 * its monthly cost and the one action that resolves it. Empty when all is as expected.
150 */
151 export function problems(r: Reading, now: number): string[] {
152 const who = `${r.provider}/${r.account}`;
153 if (r.error !== "") return [`The forge could not read ${who} to check it for stray machines (${r.error}); it is not known to be clean. It looks again within the hour.`];
154 const out = r.resources
155 .filter((x) => x.verdict === "orphan")
156 .map((x) => `${who} shows an orphan: ${describe(x, now)}, named as the forge names things with no live forge. Retire it in the provider's console, or acknowledge it as not the forge's at ${CLOUD_PAGE}. Creates on ${who} are refused until then.`);
157 for (const x of r.resources.filter((y) => y.verdict === "outside"))
158 out.push(`${who} shows something the forge did not make: ${describe(x, now)}. Acknowledge it as not the forge's at ${CLOUD_PAGE}, or delete it in the provider's console.`);
159 if (r.ceilingCents > 0 && r.actualCents > r.ceilingCents)
160 out.push(`${who} shows ${dollars(r.actualCents)} a month at list price, over its $${r.ceilingCents / 100} ceiling (the forge's own reckoning is ${dollars(r.forgeCents)}). Retire what is not needed, or raise the ceiling at ${CLOUD_PAGE}.`);
161 return out;
162 }
163
164 /** The sentences standing against every watched account now, for `/health` and the notifier. */
165 export function watchNeeds(db: Database, now = Date.now()): { cause: string; sentence: string; since: string }[] {
166 const out: { cause: string; sentence: string; since: string }[] = [];
167 for (const r of allReadings(db)) {
168 const found = problems(r, now);
169 if (found.length > 0) out.push({ cause: `cloud-watch:${r.provider}/${r.account}`, sentence: found.join(" "), since: r.since || r.at });
170 }
171 return out;
172 }
173
174 /**
175 * The line the cloud accounts page and the terminal show: when it last looked, and what it found.
176 */
177 export function watchLine(db: Database, provider: string, account: string, now = Date.now()): string {
178 if (!(WATCHED as readonly string[]).includes(provider)) return "";
179 const r = lastReading(db, provider, account);
180 if (r === undefined) return "not watched yet";
181 const when = `watched ${ageOf(r.at, now).replace(" old", " ago")}`;
182 if (r.error !== "") return `${when}: could not read the provider (${r.error})`;
183 const found = problems(r, now).length;
184 const seen = `${r.resources.length} thing${r.resources.length === 1 ? "" : "s"} there, ${dollars(r.actualCents)} a month at list price`;
185 return found === 0 ? `${when}: ${seen}, all as expected` : `${when}: ${seen}; ${found} to look at`;
186 }
187
188 /**
189 * Say that everything standing now is not the forge's (an admin's word); the next reading is quiet.
190 */
191 export function ackWatch(db: Database, provider: string, account: string, by: string, now = new Date()): number {
192 const r = lastReading(db, provider, account);
193 const open = r?.resources.filter((x) => x.verdict === "orphan" || x.verdict === "outside") ?? [];
194 for (const x of open)
195 db.query("INSERT OR IGNORE INTO cloud_watch_ack (provider, account, kind, remote, at, by) VALUES (?1,?2,?3,?4,?5,?6)").run(provider, account, x.kind, x.id, now.toISOString(), by);
196 if (r !== undefined && open.length > 0) {
197 const set = new Set(open.map((x) => `${x.kind}:${x.id}`));
198 const resources = r.resources.map((x) => (set.has(`${x.kind}:${x.id}`) ? { ...x, verdict: "acknowledged" as Verdict } : x));
199 const after = { ...r, resources };
200 const key = problemKey(after);
201 db.query("UPDATE cloud_watch SET resources = ?3, problem_key = ?4, since = CASE WHEN ?4 = '' THEN '' ELSE since END WHERE provider = ?1 AND account = ?2").run(provider, account, JSON.stringify(resources), key);
202 }
203 return open.length;
204 }
src/cloud/watch_read.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * What the hourly watch last read of a cloud account (#16329, `watch.ts`), and the refusal it
3 * stands behind: kept apart from the reader so the ceiling can ask without importing it.
4 */
5
6 import type { Database } from "bun:sqlite";
7 import { dollars } from "./prices.ts";
8
9 export const CLOUD_PAGE = "/settings/cloud";
10
11 export type Verdict = "forge" | "orphan" | "outside" | "acknowledged";
12
13 /** One machine or volume as the provider shows it. */
14 export interface Seen {
15 readonly kind: "machine" | "volume";
16 readonly id: string;
17 readonly name: string;
18 readonly createdAt: string;
19 /** Datacenter, and the machine size or the volume's GiB. */
20 readonly datacenter: string;
21 readonly size: string;
22 readonly gib: number;
23 }
24
25 export interface Judged extends Seen {
26 readonly verdict: Verdict;
27 /** US cents a month at list price; null when the catalog holds no price for it. */
28 readonly cents: number | null;
29 }
30
31 export interface Reading {
32 readonly provider: string;
33 readonly account: string;
34 readonly at: string;
35 /** Why the provider could not be read; empty when it was. */
36 readonly error: string;
37 readonly resources: readonly Judged[];
38 readonly actualCents: number;
39 readonly forgeCents: number;
40 readonly ceilingCents: number;
41 /** When the standing set of problems began (not the last look); empty when none stands. */
42 readonly since: string;
43 }
44
45 interface Stored {
46 provider: string;
47 account: string;
48 at: string;
49 error: string;
50 resources: string;
51 actual_cents: number;
52 forge_cents: number;
53 ceiling_cents: number;
54 since: string;
55 problem_key: string;
56 }
57
58 function toReading(r: Stored): Reading {
59 let resources: Judged[] = [];
60 try {
61 resources = JSON.parse(r.resources) as Judged[];
62 } catch {
63 // an unreadable row reads as nothing seen; the next hour replaces it
64 }
65 return { provider: r.provider, account: r.account, at: r.at, error: r.error, resources, actualCents: r.actual_cents, forgeCents: r.forge_cents, ceilingCents: r.ceiling_cents, since: r.since };
66 }
67
68 /** The last reading kept for an account; undefined before the first. */
69 export function lastReading(db: Database, provider: string, account: string): Reading | undefined {
70 const r = db.query<Stored, [string, string]>("SELECT * FROM cloud_watch WHERE provider = ?1 AND account = ?2").get(provider, account);
71 return r === null ? undefined : toReading(r);
72 }
73
74 /** The last reading of every watched account, one query. */
75 export const allReadings = (db: Database): Reading[] => db.query<Stored, []>("SELECT * FROM cloud_watch ORDER BY provider, account").all().map(toReading);
76
77 export const ageOf = (createdAt: string, now: number): string => {
78 const ms = now - Date.parse(createdAt);
79 if (!Number.isFinite(ms) || ms < 0) return "of unknown age";
80 const h = Math.floor(ms / 3_600_000);
81 return h < 48 ? `${h} hour${h === 1 ? "" : "s"} old` : `${Math.floor(h / 24)} days old`;
82 };
83
84 export const describe = (r: Judged, now: number): string =>
85 `${r.kind} ${r.name || "(unnamed)"} (id ${r.id}, ${r.datacenter || "?"}), ${ageOf(r.createdAt, now)}, ${r.cents === null ? "no list price" : `${dollars(r.cents)} a month`}`;
86
87 /** The refusal of a create while an orphan stands on the account; undefined when none does. */
88 export function orphanRefusal(db: Database, provider: string, account: string, now = Date.now()): string | undefined {
89 const r = lastReading(db, provider, account);
90 const orphans = r?.resources.filter((x) => x.verdict === "orphan") ?? [];
91 if (orphans.length === 0) return undefined;
92 return `${provider}/${account} shows ${orphans.length === 1 ? "an orphan" : `${orphans.length} orphans`} the forge did not account for: ${orphans.map((x) => describe(x, now)).join("; ")}; nothing was made. ` +
93 `Retire ${orphans.length === 1 ? "it" : "them"} in the provider's console, or acknowledge ${orphans.length === 1 ? "it" : "them"} as not the forge's at ${CLOUD_PAGE}. The watch reads the provider again within the hour, so a create stays refused until then even after it is gone.`;
94 }
95
src/core/account_purge.ts +1
@@ -51,6 +51,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5151 "access_link.user_id": DELETE,
5252 "access_link.created_by": FORMER,
5353 "account_ceiling.set_by": FORMER,
54 "cloud_watch_ack.by": FORMER,
5455 "account_notice.user_id": DELETE,
5556 "account_request.decided_by": FORMER,
5657 "admin_ask.user_id": DELETE,
src/core/event_audience.ts +2
@@ -307,6 +307,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
307307 kind === "forge.updates_taken" ||
308308 kind === "cloud.write_allowed" ||
309309 kind === "cloud.ceiling" ||
310 // An admin acknowledging a resource as not the forge's (`cloud/watch.ts`, #16329).
311 kind === "cloud.watch_acknowledged" ||
310312 kind === "cloud.project" ||
311313 // How many prepared machines a plan keeps waiting is a spend choice (`cloud/warm_pool.ts`,
312314 // #16362).
src/core/migration-pins/20261127100000-cloud-watch.pin added +1
@@ -0,0 +1,1 @@
1 1900e7e53e6d4004ce2326aa42a2b9f91afd4bd336283de58247aa677ba55733
src/core/migrations/20261127100000-cloud-watch.ts added +27
@@ -0,0 +1,27 @@
1 // The hourly watch of a cloud account (cloud/watch.ts, #16329): the last reading of what the
2 // provider shows, one row an account and replaced each hour, and the resources an admin
3 // acknowledged as not the forge's. Additive.
4 export default `
5 CREATE TABLE IF NOT EXISTS cloud_watch (
6 provider TEXT NOT NULL,
7 account TEXT NOT NULL,
8 at TEXT NOT NULL,
9 error TEXT NOT NULL DEFAULT '',
10 resources TEXT NOT NULL DEFAULT '[]',
11 actual_cents INTEGER NOT NULL DEFAULT 0,
12 forge_cents INTEGER NOT NULL DEFAULT 0,
13 ceiling_cents INTEGER NOT NULL DEFAULT 0,
14 since TEXT NOT NULL DEFAULT '',
15 problem_key TEXT NOT NULL DEFAULT '',
16 PRIMARY KEY (provider, account)
17 );
18 CREATE TABLE IF NOT EXISTS cloud_watch_ack (
19 provider TEXT NOT NULL,
20 account TEXT NOT NULL,
21 kind TEXT NOT NULL,
22 remote TEXT NOT NULL,
23 at TEXT NOT NULL,
24 by TEXT NOT NULL,
25 PRIMARY KEY (provider, account, kind, remote)
26 );
27 `;
src/crew/notify.ts +19
@@ -20,6 +20,7 @@
2020 * settings, is never logged, and the account page shows its host only.
2121 */
2222
23 import { watchNeeds } from "../cloud/watch.ts";
2324 import { blockedLines } from "../actions/egress_refused.ts";
2425 import { scheduleLines } from "../actions/schedules.ts";
2526 import { newAccountLines } from "../actions/accounts.ts";
@@ -255,6 +256,23 @@ export function domainDrillLines(
255256 });
256257 }
257258
259 /**
260 * The admin hears once of what a cloud account shows that the forge did not make, or could not be
261 * read (#16329); the id is the cause and the reading it began at, so a standing one is not news
262 * every tick and a new one is.
263 */
264 export function cloudWatchLines(
265 app: App,
266 user: User,
267 now = Date.now(),
268 ): { id: string; line: string; items: readonly string[]; link: string }[] {
269 if (!user.isAdmin || user.kind !== "user") return [];
270 return watchNeeds(app.db, now).map((n) => {

n.since is the reading's at, rewritten hourly, so this id changes every hour and a standing orphan notifies every hour. Key it on when the problem set began, not on the last look.

271 const id = `${n.cause}@${n.since}`;
272 return { id, line: n.sentence, items: [id], link: "/settings/cloud" };
273 });
274 }
275
258276 /** The admin hears of a snapshot that did not land off the box, or a stale mirror, once per cause. */
259277 export function mirrorLines(
260278 app: App,
@@ -527,6 +545,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
527545 ...drillLines(app, user, now()),
528546 ...domainDrillLines(app, user, now(), options.forgeUrl),
529547 ...mirrorLines(app, user, now()),
548 ...cloudWatchLines(app, user, now()),
530549 ...redLines(app, user, now()),
531550 ...alarmLines(app, user, now(), options.alarms?.()),
532551 ...clogLines(app, user),
src/http/marks/settings.json +1
@@ -62,6 +62,7 @@
6262 "/settings/cloud/verify": "admin",
6363 "/settings/cloud/write": "admin",
6464 "/settings/cloud/ceiling": "admin",
65 "/settings/cloud/watch-ack": "admin",
6566 "/settings/cloud/project": "admin",
6667 "/settings/cloud/audit": "admin",
6768 "/settings/cloud/rotate": "admin",
src/http/settings_routes.ts +2
@@ -69,6 +69,7 @@ import {
6969 cloudAudit,
7070 cloudAuditPage,
7171 cloudCeiling,
72 cloudWatchAck,
7273 cloudProject,
7374 cloudRename,
7475 cloudRotate,
@@ -238,6 +239,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
238239 router.add("POST", "/settings/cloud/verify", cloudVerify);
239240 router.add("POST", "/settings/cloud/write", cloudWrite);
240241 router.add("POST", "/settings/cloud/ceiling", cloudCeiling);
242 router.add("POST", "/settings/cloud/watch-ack", cloudWatchAck);
241243 router.add("POST", "/settings/cloud/project", cloudProject);
242244 router.add("POST", "/settings/cloud/audit", cloudAudit);
243245 router.add("GET", "/settings/cloud/audit", cloudAuditPage);
src/kernel/vitals.ts +5
@@ -50,6 +50,7 @@ import { limitValue } from "../settings/limits.ts";
5050 import { unwrittenFor, SILENT_AFTER_S } from "../http/access_log.ts";
5151 import { DOMAINS } from "./domains.ts";
5252 import { domainDrillNeeds } from "./domain_drill.ts";
53 import { watchNeeds } from "../cloud/watch.ts";
5354 import { freeChecks, heldChecks, redHref, redSentence } from "../checks/red_main.ts";
5455 import { diskRedSentence, diskReds } from "../checks/disk_red.ts";
5556 import { flakeList, type FlakeRow } from "../checks/flake.ts";
@@ -690,6 +691,10 @@ export function vitals(input: VitalsInput): Vitals {
690691 ))
691692 need("todo", owed.cause, owed.sentence, owed.since, "/");
692693
694 // What a cloud account shows that the forge did not make, or a provider it could not read
695 // (#16329).
696 for (const w of watchNeeds(input.db, now)) need("todo", w.cause, w.sentence, w.since, "/settings/cloud");
697
693698 // A snapshot that failed is a card from that morning until one lands.
694699 const failing = snapshotNeed(lastSnapshotOutcome(input.dataDir));
695700 if (failing !== undefined) need("todo", "snapshot-failed", failing.sentence, failing.since, "/settings/backups");
src/maintain/duties/cloud_watch.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * Cloud watch (#16329): once an hour, for each cloud account with writes allowed, read what the
3 * provider shows (`cloud/watch.ts`), keep it for /health, the notifier and the cloud accounts page,
4 * and file one issue naming each orphan or unexplained resource, its age, its monthly cost and the
5 * one action that resolves it. A provider that cannot be read is a finding too, never a pass. Quiet
6 * when all is as expected: no finding, no issue, and the page's line says when it last looked.
7 */
8
9 import { fileIssueOnce } from "../../checks/flake.ts";
10 import { net } from "../../actions/pinned.ts";
11 import { gatedFetch } from "../../cloud/gate.ts";
12 import { problems, watchAccount, WATCHED } from "../../cloud/watch.ts";
13 import { listCloudAccounts, secretNameOf } from "../../core/cloud_account.ts";
14 import { getRepo } from "../../core/repos.ts";
15 import { resolveSecrets } from "../../core/secret_store.ts";
16 import { ownRepoPath } from "../../kernel/own_repo.ts";
17 import type { Duty, Finding } from "../duty.ts";
18
19 export const titleOf = (provider: string, account: string): string => `Cloud account ${provider}/${account} shows more than the forge made`;
20
21 export const duty: Duty = {
22 name: "cloud-watch",
23 intervalMs: 3_600_000,
24 budget: { runsPerDay: 30, dollarsPerDay: 1, reason: "hourly is 24 a day; the rest is room for a catch-up, and it makes only read calls that cost no money" },
25 async run({ db, bus, now, app }) {
26 if (app === undefined) return { findings: [], actions: [] };
27 const findings: Finding[] = [];
28 const actions: string[] = [];
29 for (const a of listCloudAccounts(db)) {
30 if (!a.writeAllowed || !(WATCHED as readonly string[]).includes(a.provider)) continue;
31 const secret = secretNameOf(a.provider, a.name);
32 const token = resolveSecrets(db, app.config.dataDir, bus, [secret], { run: "maintain:cloud-watch" })[secret];
33 const who = `${a.provider}/${a.name}`;
34 if (token === undefined) {
35 findings.push({ summary: `${who}: its credential could not be opened, so it was not watched`, probe: { kind: "measurement", what: "accounts not watched", number: 1, at: now.toISOString() } });
36 continue;
37 }
38 const reading = await watchAccount(db, a.provider, a.name, gatedFetch(db, { provider: a.provider, account: a.name }, "maintain:cloud-watch", net.fetch), token, now);
39 const found = problems(reading, now.getTime());
40 if (found.length === 0) continue;
41 findings.push(...found.map((summary) => ({ summary, probe: { kind: "measurement" as const, what: `things at ${who} that need a look`, number: found.length, at: reading.at } })));
42 const [owner = "", name = ""] = ownRepoPath().split("/");
43 const repo = getRepo(db, owner, name);
44 if (repo === undefined) continue;
45 const filed = fileIssueOnce(db, bus, repo, {
46 title: titleOf(a.provider, a.name),
47 body: `_Filed by the cloud watch duty from the provider's own list, not written by a person._\n\n${found.map((s) => `- ${s}`).join("\n")}\n\nThe forge's reckoning comes from list prices; the provider's bill is the truth.`,
48 });
49 if (filed.opened) actions.push(`filed cloud watch issue #${filed.number} for ${who}`);
50 }
51 return { findings, actions };
52 },
53 };
src/tui/screens/cloud.ts +7 −2
@@ -7,6 +7,7 @@
77 * is never drawn, kept or put in a note. Anyone else sees nothing and does nothing.
88 */
99
10 import { acknowledgeWatch } from "../../actions/cloud_ceiling.ts";
1011 import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../actions/cloud.ts";
1112 import { setProject } from "../../actions/cloud_ceiling.ts";
1213 import { usesByVendor, type VendorUse } from "../../cloud/declared.ts";
@@ -88,7 +89,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
8889 accounts().map((a) => ({
8990 title: `${a.provider}/${a.name}`,
9091 secondary: `verified ${day(a.verifiedAt)} · used ${day(a.lastUsedAt)} · ${a.callsToday} call${a.callsToday === 1 ? "" : "s"} today`,
91 meta: `${a.writeAllowed ? "writes allowed" : "read-only"}${a.warm.length === 0 ? "" : ` · warm ${a.warm.map((w) => `${w.held}/${w.configured} ${w.place} ${dollars(w.cents)} a month`).join(", ")}`}`,
92 meta: `${a.writeAllowed ? "writes allowed" : "read-only"}${a.warm.length === 0 ? "" : ` · warm ${a.warm.map((w) => `${w.held}/${w.configured} ${w.place} ${dollars(w.cents)} a month`).join(", ")}`}${a.watch === "" ? "" : ` · ${a.watch}`}`,
9293 }));
9394
9495 const attach = (parent: Screen): Screen =>
@@ -124,6 +125,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
124125 binding(["P"], "project for its forges"),
125126 binding(["A"], "audit"),
126127 binding(["c"], "calls today"),
128 binding(["o"], "acknowledge"),
127129 ],
128130 render(area, s) {
129131 const c = ctx.theme.c;
@@ -207,7 +209,10 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
207209 },
208210 }),
209211 );
210 else if (e.key === "x")
212 else if (e.key === "o") {
213 const r = acknowledgeWatch(f.app, f.user, provider, name);
214 say(r.ok ? r.value : r.error);
215 } else if (e.key === "x")
211216 ctx.push(
212217 promptScreen(ctx, screen, {
213218 title: `Remove ${provider}/${name}`,
src/web/pages/cloud.ts +28 −2
@@ -19,6 +19,8 @@ import {
1919 } from "../../actions/cloud.ts";
2020 import { LABEL, PROVIDERS, VENDOR_OF, isProvider, shape } from "../../cloud/providers.ts";
2121 import { HOME, usedFor, usesByVendor, type VendorUse } from "../../cloud/declared.ts";
22 import { watchLine } from "../../cloud/watch.ts";
23 import { lastReading } from "../../cloud/watch_read.ts";
2224 import { spendOf } from "../../cloud/ceiling.ts";
2325 import { warmOf } from "../../cloud/warm_pool.ts";
2426 import { dollars } from "../../cloud/prices.ts";
@@ -33,7 +35,7 @@ import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from
3335 import type { Ctx } from "../../http/context.ts";
3436 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
3537 import { field, readForm } from "../form.ts";
36 import { setCeiling, setProject } from "../../actions/cloud_ceiling.ts";
38 import { acknowledgeWatch, setCeiling, setProject } from "../../actions/cloud_ceiling.ts";
3739 import { html, type Html } from "../html.ts";
3840 import { flashTo, page } from "../layout.ts";
3941 import { btn, confirmAction, icon, row, time } from "../ui.ts";
@@ -66,6 +68,15 @@ function warmFacts(db: Database, a: CloudAccount): { label: string; value: strin
6668 }));
6769 }
6870
71 /**
72 * What the hourly watch last saw of the account, a fact with its own label (none for a kind it does
73 * not watch).
74 */
75 function watchFacts(db: Database, a: CloudAccount): { label: string; value: string }[] {
76 const line = watchLine(db, a.provider, a.name);
77 return line === "" ? [] : [{ label: "Hourly watch", value: line }];
78 }
79
6980 function ceilingLine(db: Database, a: CloudAccount): string {
7081 const s = spendOf(db, a.provider, a.name);
7182 return `ceiling $${s.ceilingDollars} a month · the forge reckons ${dollars(s.monthlyCents)} now · ${s.leftCents >= 0 ? `${dollars(s.leftCents)} left` : `${dollars(-s.leftCents)} over`}`;
@@ -80,7 +91,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
8091 meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} ·
8192 ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} ·
8293 ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`,
83 facts: warmFacts(db, a),
94 facts: [...watchFacts(db, a), ...warmFacts(db, a)],
8495 trail: html`<div class="row-fields">
8596 <form method="post" action="/settings/cloud/verify">
8697 ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })}
@@ -96,6 +107,11 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
96107 aria-label="Monthly ceiling in US dollars for ${a.name}" required />
97108 ${btn("Set ceiling", { size: "sm", label: `Set the ceiling of ${a.name}` })}
98109 </form>
110 ${(lastReading(db, a.provider, a.name)?.resources ?? []).some((r) => r.verdict === "orphan" || r.verdict === "outside")
111 ? html`<form method="post" action="/settings/cloud/watch-ack">
112 ${hidden(a.provider, a.name)}${btn("Acknowledge as not the forge's", { size: "sm", label: `Acknowledge what the watch shows at ${a.name} as not the forge's` })}
113 </form>`
114 : ""}
99115 ${a.provider === "digitalocean"
100116 ? html`<form method="post" action="/settings/cloud/project" class="row-fields">
101117 ${hidden(a.provider, a.name)}
@@ -244,6 +260,16 @@ export async function cloudCeiling(ctx: Ctx): Promise<Response> {
244260 return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error });
245261 }
246262
263 // POST /settings/cloud/watch-ack: what the hourly watch shows there is not the forge's (#16329).
264 export async function cloudWatchAck(ctx: Ctx): Promise<Response> {
265 const denied = requireAdmin(ctx);
266 if (denied) return denied;
267 const form = await readForm(ctx, "admin");
268 if (form instanceof Response) return form;
269 const r = acknowledgeWatch(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"));
270 return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error });
271 }
272
247273 // POST /settings/cloud/project: the cloud project an account's forges are filed in.
248274 export async function cloudProject(ctx: Ctx): Promise<Response> {
249275 const denied = requireAdmin(ctx);
test/api-forge-view.test.ts +4 −3
@@ -159,9 +159,10 @@ describe("the forge view over the API", () => {
159159 expect(view.apps.length).toBeLessThanOrEqual(VIEW_APPS);
160160 expect(view.runs.filter((r) => r.run !== null).length).toBeLessThanOrEqual(50);
161161 // 120 apps, 960 runs. `mayReadRuns` (shared with /crew/now) reads two
162 // rows per app today, 20 fixed reads before the crew sentences and 3 for them (running work,
163 // queued runs, open pulls); anything beyond that, or a read per run, fails.
164 expect(selects.length).toBeLessThanOrEqual(2 * APPS + 23);
162 // rows per app today, 21 fixed reads (one is the cloud watch, #16329) before the crew sentences
163 // and 3 for them (running work, queued runs, open pulls); anything beyond that, or a read per
164 // run, fails.
165 expect(selects.length).toBeLessThanOrEqual(2 * APPS + 24);
165166 });
166167
167168 test("foundry has a door only for an app an admin or an admin's org owns", async () => {
test/cloud-watch-doors.test.ts added +96
@@ -0,0 +1,96 @@
1 /**
2 * The doors to acknowledging what the watch shows (#16329): POST /settings/cloud/watch-ack and the
3 * terminal's `o`. An admin acknowledges; a non-admin, a cross-origin post and a guest do nothing.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser, getUserByName } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15 import { settleApp } from "./helpers/tui.ts";
16
17 quietLogs();
18
19 describe("acknowledging what the watch shows", () => {
20 let dataDir = "";
21 let app: App;
22 let servers: Servers;
23 const acked = () => (app.db.query("SELECT COUNT(*) AS n FROM cloud_watch_ack").get() as { n: number }).n;
24 const reseed = () => {
25 app.db.run("DELETE FROM cloud_watch_ack");
26 const orphan = { kind: "machine", id: "9", name: "forge-ghost", createdAt: "2026-11-01T00:00:00Z", datacenter: "nyc3", size: "s", gib: 0, verdict: "orphan", cents: 1200 };
27 app.db.run("INSERT OR REPLACE INTO cloud_watch (provider, account, at, resources) VALUES ('digitalocean', 'main', ?1, ?2)", [new Date().toISOString(), JSON.stringify([orphan])]);
28 };
29
30 beforeAll(async () => {
31 dataDir = await mkdtemp(join(tmpdir(), "forge-watch-doors-"));
32 app = createApp({ dataDir, port: 0 });
33 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
34 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
35 if (!made.ok) throw new Error(made.error);
36 }
37 app.db.run("INSERT INTO cloud_account (provider, name, summary) VALUES ('digitalocean', 'main', 'x')");
38 servers = await serve(app);
39 });
40 afterAll(async () => {
41 servers.stop();
42 app.close();
43 await rm(dataDir, { recursive: true, force: true });
44 });
45
46 const login = async (username: string) =>
47 ((await fetch(`${servers.url}/signin`, { method: "POST", redirect: "manual", headers: { origin: servers.url }, body: new URLSearchParams({ username, password: "a-good-passphrase" }) })).headers.get("set-cookie") ?? "").split(";")[0] ?? "";
48 const post = (cookie: string, origin: string) =>
49 fetch(`${servers.url}/settings/cloud/watch-ack`, {
50 method: "POST",
51 redirect: "manual",
52 headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" },
53 body: new URLSearchParams({ provider: "digitalocean", name: "main" }),
54 });
55
56 test("the page offers the button only when something stands, and a post acknowledges it", async () => {
57 reseed();
58 const alice = await login("alice");
59 expect(await (await fetch(`${servers.url}/settings/cloud`, { headers: { cookie: alice } })).text()).toContain("Acknowledge as not the forge");
60 expect((await post(alice, servers.url)).status).toBe(303);
61 expect(acked()).toBe(1);
62 const page = await (await fetch(`${servers.url}/settings/cloud`, { headers: { cookie: alice } })).text();
63 expect(page).not.toContain("Acknowledge as not the forge");
64 expect(page).toContain("Hourly watch");
65 });
66
67 test("a non-admin and a cross-origin post are refused and acknowledge nothing", async () => {
68 reseed();
69 expect((await post(await login("bob"), servers.url)).status).toBe(403);
70 expect((await post(await login("alice"), "https://evil.example")).status).toBe(403);
71 expect(acked()).toBe(0);
72 });
73
74 const press = async (username: string) => {
75 const { app: tui } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(app.db, username)! }, { terminal: headlessTerminal(160, 32), exitHooks: false });
76 tui.start();
77 const key = (k: string, ctrl = false) => tui.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
78 key("k", true);
79 await settleApp(tui);
80 for (const ch of "Cloud accounts") key(ch);
81 await settleApp(tui);
82 key("enter");
83 await settleApp(tui);
84 key("o");
85 await settleApp(tui);
86 tui.stop();
87 };
88
89 test("the terminal's o acknowledges for an admin and does nothing for anyone else", async () => {
90 reseed();
91 await press("bob");
92 expect(acked()).toBe(0);
93 await press("alice");
94 expect(acked()).toBe(1);
95 });
96 });
test/cloud-watch-read.test.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * What the hourly watch asks of each provider (#16329, `readLive`): DigitalOcean and Hetzner
3 * shapes, the page size each is asked for, paging to the end, and the refusal to guess when a
4 * list is too long to read whole.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { plain, readLive } from "../src/cloud/watch.ts";
8
9 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
10
11 describe("reading Hetzner", () => {
12 test("servers and volumes are read with per_page 50, location and created kept", async () => {
13 const urls: string[] = [];
14 const seen = await readLive(
15 "hetzner",
16 async (url, init) => {
17 urls.push(url);
18 expect((init?.headers as Record<string, string>).authorization).toBe("Bearer tok");
19 const u = new URL(url);
20 return u.pathname === "/v1/servers"
21 ? json({ servers: [{ id: 11, name: "forge-a", created: "2026-11-01T00:00:00Z", server_type: { name: "cx22" }, datacenter: { location: { name: "fsn1" } } }] })
22 : json({ volumes: [{ id: 22, name: "forge-a-data", size: 25, created: "2026-11-01T00:00:00Z", location: { name: "fsn1" } }] });
23 },
24 "tok",
25 );
26 expect(urls).toEqual(["https://api.hetzner.cloud/v1/servers?per_page=50&page=1", "https://api.hetzner.cloud/v1/volumes?per_page=50&page=1"]);
27 expect(seen).toEqual([
28 { kind: "machine", id: "11", name: "forge-a", createdAt: "2026-11-01T00:00:00Z", datacenter: "fsn1", size: "cx22", gib: 0 },
29 { kind: "volume", id: "22", name: "forge-a-data", createdAt: "2026-11-01T00:00:00Z", datacenter: "fsn1", size: "", gib: 25 },
30 ]);
31 });
32 });
33
34 describe("paging", () => {
35 const droplet = (i: number) => ({ id: i, name: `d${i}`, size_slug: "s", region: { slug: "nyc3" }, created_at: "2026-11-01T00:00:00Z" });
36 test("a full page asks for the next, and a short one ends the read", async () => {
37 const pages: string[] = [];
38 const seen = await readLive(
39 "digitalocean",
40 async (url) => {
41 const u = new URL(url);
42 if (u.pathname === "/v2/volumes") return json({ volumes: [] });
43 pages.push(`${u.searchParams.get("per_page")}/${u.searchParams.get("page")}`);
44 return json({ droplets: u.searchParams.get("page") === "1" ? Array.from({ length: 200 }, (_, i) => droplet(i + 1)) : [droplet(999)] });
45 },
46 "tok",
47 );
48 expect(pages).toEqual(["200/1", "200/2"]);
49 expect(seen).toHaveLength(201);
50 });
51
52 test("a list that never ends fails as not read whole, never a partial pass", async () => {
53 let n = 0;
54 const read = readLive("hetzner", async (url) => {
55 n++;
56 const key = new URL(url).pathname.endsWith("servers") ? "servers" : "volumes";
57 return json({ [key]: Array.from({ length: 50 }, (_, i) => ({ id: n * 100 + i, name: "x" })) });
58 }, "tok");
59 await expect(read).rejects.toThrow("more than 500 servers: not read whole");
60 expect(n).toBe(10);
61 });
62
63 test("a provider's strange text is made plain before it reaches a sentence", () => {
64 expect(plain("a`b\n[x](http://e)<i>")).toBe("a?b??x?(http://e)?i?");
65 });
66 });
test/cloud-watch.test.ts added +206
@@ -0,0 +1,206 @@
1 /**
2 * The hourly watch of a cloud account (#16329): an orphan machine, an orphan volume, an outside
3 * resource an admin acknowledged, a provider that cannot be read, and the refusal of a create while
4 * an orphan stands. The provider is a recorded fetch.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
12 import { acknowledgeWatch, setCeiling } from "../src/actions/cloud_ceiling.ts";
13 import { deployPinned, net } from "../src/actions/pinned.ts";
14 import { cloudOverview } from "../src/cloud/overview.ts";
15 import { watchNeeds, watchLine, watchAccount, GRACE_MS } from "../src/cloud/watch.ts";
16 import { getPinned } from "../src/core/pinned.ts";
17 import { createUser, getUserByName } from "../src/core/users.ts";
18 import { duty } from "../src/maintain/duties/cloud_watch.ts";
19 import { duties } from "../src/maintain/registry.ts";
20 import { cloudWatchLines } from "../src/crew/notify.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { seedPlaces } from "./helpers/places-fixture.ts";
23
24 quietLogs();
25
26 const NOW = new Date("2026-11-27T12:00:00Z");
27 const DAY = 86_400_000;
28 const ago = (days: number) => new Date(NOW.getTime() - days * DAY).toISOString();
29
30 describe("cloud watch", () => {
31 let dir = "";
32 let app: App;
33 let seq = 1000;
34 const calls: string[] = [];
35 // What the provider shows besides the forge's own machine, and whether it answers.
36 let extraDroplets: object[] = [];
37 let extraVolumes: object[] = [];
38 let down = false;
39 const admin = () => getUserByName(app.db, "alice")!;
40 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
41 const input = (name: string) => ({ name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: {} });
42 const shown = async (url: string): Promise<Response> => {
43 const u = new URL(url);
44 if (down) return json({ message: "boom" }, 500);
45 const mine = getPinned(app.db, "shop");
46 if (u.pathname === "/v2/droplets") return json({ droplets: [...(mine ? [{ id: Number(mine.remote), name: "forge-shop", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(5) }] : []), ...extraDroplets] });
47 return json({ volumes: [...(mine ? [{ id: mine.volume, name: "forge-shop-data", size_gigabytes: 10, region: { slug: "nyc3" }, created_at: ago(5) }] : []), ...extraVolumes] });
48 };
49 const watch = () => watchAccount(app.db, "digitalocean", "main", shown, "tok", NOW);
50
51 beforeAll(async () => {
52 dir = await mkdtemp(join(tmpdir(), "forge-watch-"));
53 app = createApp({ dataDir: dir, port: 0 });
54 await seedPlaces(app.db);
55 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
56 if (!made.ok) throw new Error(made.error);
57 cloudNet.fetch = async () => json({ account: { email: "[email protected]", status: "active" } });
58 const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
59 if (!added.ok) throw new Error(String(added.error));
60 allowWrite(app, admin(), "digitalocean", "main", true);
61 setCeiling(app, admin(), "digitalocean", "main", 500);
62 net.fetch = async (url, init) => {
63 const u = new URL(url);
64 calls.push(`${init?.method ?? "GET"} ${u.pathname}`);
65 if ((init?.method ?? "GET") === "GET" && (u.pathname === "/v2/volumes" || u.pathname === "/v2/droplets")) return shown(url);
66 if (u.pathname === "/v2/volumes") return json({ volume: { id: ++seq } }, 201);
67 if (u.pathname === "/v2/account/keys") return json({ ssh_key: { id: 4242 } }, 201);
68 if ((init?.method ?? "GET") === "DELETE") return new Response(null, { status: 204 });
69 return json({ droplet: { id: ++seq } }, 202);
70 };
71 expect((await deployPinned(app, admin(), input("shop"))).ok).toBe(true);
72 }, 30_000);
73
74 afterAll(async () => {
75 app.close();
76 await rm(dir, { recursive: true, force: true });
77 });
78
79 test("the duty is on the roster", () => {
80 expect(duties.map((d) => d.name)).toContain("cloud-watch");
81 });
82
83 test("the forge's own machine and volume are quiet, and the page says when it looked", async () => {
84 const r = await watch();
85 expect(r.error).toBe("");
86 expect(r.resources.map((x) => x.verdict)).toEqual(["forge", "forge"]);
87 expect(watchNeeds(app.db, NOW.getTime())).toEqual([]);
88 expect(watchLine(app.db, "digitalocean", "main", NOW.getTime())).toBe("watched 0 hours ago: 2 things there, $13.00 a month at list price, all as expected");
89 const o = cloudOverview(app, admin());
90 expect(o.ok && o.value.accounts[0]?.watch).toContain("all as expected");
91 });
92
93 test("an orphan machine is named with its age and monthly cost, raised as a need and a notification", async () => {
94 extraDroplets = [{ id: 9001, name: "forge-ghost", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(3) }];
95 const r = await watch();
96 expect(r.resources.find((x) => x.id === "9001")).toMatchObject({ verdict: "orphan", cents: 1200 });
97 const [need] = watchNeeds(app.db, NOW.getTime());
98 expect(need?.cause).toBe("cloud-watch:digitalocean/main");
99 expect(need?.sentence).toContain("orphan: machine forge-ghost (id 9001, nyc3), 3 days old, $12.00 a month");
100 expect(need?.sentence).toContain("Retire it in the provider's console, or acknowledge it as not the forge's");
101 expect(cloudWatchLines(app, admin(), NOW.getTime()).map((l) => l.line)).toEqual([need!.sentence]);
102 const ran = await duty.run({ db: app.db, bus: app.bus, app, now: NOW });
103 expect(ran.findings.map((f) => f.summary)).toEqual([need!.sentence]);
104 });
105
106 test("a create on the account is refused, with that sentence, while an orphan stands", async () => {
107 calls.length = 0;
108 const r = await deployPinned(app, admin(), input("second"));
109 expect(r).toMatchObject({ ok: false });
110 expect((r as { error: string }).error).toContain("digitalocean/main shows an orphan the forge did not account for: machine forge-ghost (id 9001");
111 expect((r as { error: string }).error).toContain("nothing was made");
112 expect(calls.filter((c) => c.startsWith("POST"))).toEqual([]);
113 });
114
115 test("an orphan volume is named too, and acknowledging both as not the forge's is quiet", async () => {
116 extraVolumes = [{ id: "v-77", name: "forge-ghost-data", size_gigabytes: 20, region: { slug: "nyc3" }, created_at: ago(9) }];
117 await watch();
118 const sentence = watchNeeds(app.db, NOW.getTime())[0]!.sentence;
119 expect(sentence).toContain("orphan: volume forge-ghost-data (id v-77, nyc3), 9 days old, $2.00 a month");
120 expect(acknowledgeWatch(app, admin(), "digitalocean", "main")).toMatchObject({ ok: true });
121 expect(watchNeeds(app.db, NOW.getTime())).toEqual([]);
122 // The next hour reads them again, still there, still acknowledged.
123 await watch();
124 expect(watchNeeds(app.db, NOW.getTime())).toEqual([]);
125 expect(watchLine(app.db, "digitalocean", "main", NOW.getTime())).toContain("all as expected");
126 // Nothing is left to acknowledge.
127 expect(acknowledgeWatch(app, admin(), "digitalocean", "main")).toMatchObject({ ok: false });
128 // The create is let through again.
129 expect((await deployPinned(app, admin(), input("second"))).ok).toBe(true);
130 });
131
132 test("something outside the forge's naming is raised until acknowledged, and a stranger may not acknowledge", async () => {
133 extraDroplets = [{ id: 5, name: "my-blog", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(40) }];
134 await watch();
135 expect(watchNeeds(app.db, NOW.getTime())[0]!.sentence).toContain("something the forge did not make: machine my-blog (id 5, nyc3), 40 days old, $12.00 a month");
136 const stranger = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
137 expect(stranger.ok && acknowledgeWatch(app, stranger.value, "digitalocean", "main")).toMatchObject({ ok: false, error: "not_found" });
138 expect(acknowledgeWatch(app, admin(), "digitalocean", "main")).toMatchObject({ ok: true });
139 await watch();
140 expect(watchNeeds(app.db, NOW.getTime())).toEqual([]);
141 });
142
143 test("real cost over the ceiling is raised beside the forge's own reckoning", async () => {
144 expect(setCeiling(app, admin(), "digitalocean", "main", 20).ok).toBe(true);
145 await watch();
146 expect(watchNeeds(app.db, NOW.getTime())[0]!.sentence).toContain("over its $20 ceiling (the forge's own reckoning is $26.00)");
147 setCeiling(app, admin(), "digitalocean", "main", 500);
148 });
149
150 test("a provider read that fails says so, and is not a pass", async () => {
151 down = true;
152 const r = await watch();
153 expect(r.error).toContain("answered 500");
154 const [need] = watchNeeds(app.db, NOW.getTime());
155 expect(need?.sentence).toContain("could not read digitalocean/main");
156 expect(need?.sentence).toContain("not known to be clean");
157 expect(watchLine(app.db, "digitalocean", "main", NOW.getTime())).toContain("could not read the provider");
158 down = false;
159 await watch();
160 expect(watchNeeds(app.db, NOW.getTime())).toEqual([]);
161 });
162
163 test("a standing orphan is one notification, not one an hour; a new one is another", async () => {
164 const at = (h: number) => new Date(NOW.getTime() + h * 3_600_000);
165 const ghost = { id: 9101, name: "forge-ghost", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(3) };
166 extraDroplets = [ghost];
167 await watchAccount(app.db, "digitalocean", "main", shown, "tok", at(0));
168 const first = cloudWatchLines(app, admin(), at(0).getTime());
169 await watchAccount(app.db, "digitalocean", "main", shown, "tok", at(1));
170 await watchAccount(app.db, "digitalocean", "main", shown, "tok", at(2));
171 const later = cloudWatchLines(app, admin(), at(2).getTime());
172 expect(first).toHaveLength(1);
173 expect(later.map((l) => l.id)).toEqual(first.map((l) => l.id));
174 expect(watchNeeds(app.db, at(2).getTime())[0]!.since).toBe(at(0).toISOString());
175 extraDroplets = [ghost, { ...ghost, id: 9102, name: "forge-ghost2" }];
176 await watchAccount(app.db, "digitalocean", "main", shown, "tok", at(3));
177 expect(cloudWatchLines(app, admin(), at(3).getTime())[0]!.id).not.toBe(first[0]!.id);
178 extraDroplets = [];
179 await watchAccount(app.db, "digitalocean", "main", shown, "tok", at(4));
180 expect(cloudWatchLines(app, admin(), at(4).getTime())).toEqual([]);
181 });
182
183 test("a forge-named thing made moments ago, or named for a live row, is a deploy in flight, not an orphan", async () => {
184 extraDroplets = [
185 { id: 7001, name: "forge-fresh", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: new Date(NOW.getTime() - GRACE_MS / 4).toISOString() },
186 { id: 7002, name: "forge-shop", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(1) },
187 { id: 7003, name: "forge-old", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(1) },
188 ];
189 const r = await watch();
190 const verdict = (id: string) => r.resources.find((x) => x.id === id)?.verdict;
191 expect(verdict("7001")).toBe("forge");
192 expect(verdict("7002")).toBe("forge");
193 expect(verdict("7003")).toBe("orphan");
194 extraDroplets = [];
195 await watch();
196 });
197
198 test("a provider's markup in a name cannot reach the sentence", async () => {
199 extraDroplets = [{ id: 8, name: "x`](http://evil)\n# h", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(40) }];
200 await watch();
201 const sentence = watchNeeds(app.db, NOW.getTime())[0]!.sentence;
202 expect(sentence).not.toMatch(/[`\[\]\n#]/);
203 extraDroplets = [];
204 await watch();
205 });
206 });
test/kernel-boundary.test.ts +1
@@ -27,6 +27,7 @@ const CROSSINGS: Readonly<Record<string, string>> = {
2727 "preflight.ts -> ../settings/signup.ts": "preflight checks the signup setting read from the env",
2828 "worker_ask.ts -> ../perf/memory_watch.ts": "a worker's answer carries its memory reading",
2929 "vitals.ts -> ../perf/memory_watch.ts": "the standing says when memory grew",
30 "vitals.ts -> ../cloud/watch.ts": "the standing raises what a cloud account shows that the forge did not make",
3031 "vitals.ts -> ../spawn/disk_floor.ts": "the standing holds the disk to the spawn floor",
3132 "vitals.ts -> ../core/runs.ts": "the standing counts the queue, leases and budget failures",
3233 "vitals.ts -> ../runs/held.ts": "the standing names held runs",
test/vitals.test.ts +3 −2
@@ -180,8 +180,9 @@ test("the number of queries does not grow with runs", () => {
180180 // finished checks, the red mains holding pulls' checks, the tests red on many pulls, (the checks
181181 // red on a full disk only while the disk is full), and the newest drill of every domain, the
182182 // checks no red main holds, the week's flake list, and the database's daily size readings
183 // (#12010, at most 60 rows), and the memory floor the forge keeps for itself (#12300).
184 expect(before).toBe(12);
183 // (#12010, at most 60 rows), the memory floor the forge keeps for itself (#12300), and the
184 // hourly cloud watch's readings, one row an account (#16329).
185 expect(before).toBe(13);
185186 });
186187
187188 test("errors are counted, bounded, redacted, and a burst is said", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs