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

Pod placement for a child forge: its own namespace, PVC, limits and default-deny egress (from #3687) #3743

Closed opened this
Closed without merging

scout/forge:scout/3702-pod-placement-for-a-child-forge-its-own → main 4 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +811 −4
README.md +33
@@ -1914,3 +1914,36 @@ same rule. A guard installed by hand without the prefix answers `refused`
19141914 until it is re-created with `forge: ` in front of its message.
19151915
19161916 `reach` is a boards source for an admin only (anyone else gets 403, an agent too): `visitors` per day, `lcp_p75` and `inp_p75` per route per day, `server_p50` and `server_p95` per route per day (the beacon's time to first byte, the only per-route server timing the forge keeps), and `accounts_active_1d`, `accounts_active_7d` and `accounts_total` as of now. Filter by `metric`, group by `route` or a time bucket. Percentiles are nearest-rank within one route and day, so a `max` or `avg` over several days is a summary of daily percentiles, not a percentile of the period. Account activity comes from a session's last-seen time, so it is a count as of now, not a history. No dependency was added.
1917
1918 ## Pod placement for a child forge
1919
1920 `placement: "pod"` on `POST /api/v1/forges` (and the MCP `spawn` tool) puts a child
1921 in its own Kubernetes namespace instead of inside this process; `limits`
1922 (`{cpu, memoryGiB, diskGiB}`, whole numbers, default 8 / 16 / 50) are validated by
1923 `parsePodLimits` in the plan. `/forges` (page, terminal, MCP `forges`) shows each pod
1924 child's status, resources and version.
1925
1926 `src/spawn/pod.ts` renders the namespace (`forge-child-<name>`), a ResourceQuota, the
1927 child's own PVC, a Deployment of the parent's release image with no service-account
1928 token and no parent secret, a Service for its public host `<name>--<parent host>`
1929 through the same edge, and NetworkPolicies: default-deny both ways, ingress only from
1930 the edge namespace, egress only DNS and TCP 443 to the addresses it is handed. An
1931 address in 10/8, 100.64/10, 172.16/12, 192.168/16, link-local or loopback is refused,
1932 as is any block that contains one (11.0.0.0/7). IPv4 only: IPv6 is refused as
1933 unparseable. `src/spawn/pod_host.ts` is the placement as configured here, and exists
1934 only in a cluster: `FORGE_POD_IMAGE` (the release image; required),
1935 `FORGE_POD_EGRESS` (comma-separated registry and model-provider hosts; this forge's
1936 own public host is always added), `FORGE_POD_EDGE_NAMESPACE` (default `ingress`),
1937 `FORGE_POD_STORAGE_CLASS`. Without them a pod child is refused plainly.
1938
1939 Assumptions and limits:
1940 - The release image must run as uid 10001 (the pod sets `runAsUser`/`fsGroup` to it).
1941 - Egress hosts are resolved to addresses once, when the child is placed. Nothing
1942 refreshes them afterwards (a spawn retry of an already-placed child does not place
1943 again): a rotated CDN address is blocked (fail closed), not leaked, until the
1944 child is retired and placed anew. A refresher is a follow-up.
1945 - Placing into an existing namespace leaves it and PVC untouched (the child's data), and a
1946 failed placement deletes only a namespace that call created.
1947 - Not done: seeding the pod's volume from the parent's copy (the pod child boots
1948 empty; its claim link is not carried over), choosing a pod in the web "New forge"
1949 form, and counting pod children against `children.max`.
src/actions/spawn.ts +14 −2
@@ -54,6 +54,7 @@ import { loadOrCreateHostKey } from "../ssh/keys.ts";
5454 import { claimLink, hasAdmin, mintClaim, spawnedOrg } from "../spawn/claim.ts";
5555 import { childPublicUrl, parentOrigin, type Placement } from "../spawn/placement.ts";
5656 import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts";
57 import type { PodLimits } from "../spawn/pod.ts";
5758 import { DEFAULT_SIZE, isSize, type Size } from "../spawn/sizes.ts";
5859 import { chainForChild, DEFAULT_MODE, forgeLinkOf, type FollowMode, type Hop } from "../spawn/chain.ts";
5960 import { requireUser } from "./access.ts";
@@ -82,6 +83,8 @@ export type SpawnError =
8283
8384 export interface SpawnDeps {
8485 readonly placement: Placement;
86 /** Where a plan with `podLimits` goes; absent when this forge cannot place pods. */
87 readonly pods?: Placement;
8588 /** The request that asked, for the same-origin check on this mutation. */
8689 readonly request: Request;
8790 readonly url: URL;
@@ -111,6 +114,8 @@ interface Ledger {
111114 readonly createdAt?: string;
112115 /** Absent on a ledger written before sizes; reads as small. */
113116 readonly size?: Size;
117 /** A pod child's limits; absent for a hosted one. */
118 readonly pod?: PodLimits;
114119 /**
115120 * What the parent shows the child to learn its private facts (when anything
116121 * last happened); the child keeps only its hash. Never in an answer.
@@ -242,10 +247,13 @@ async function make(
242247 // A retry of an unfinished child is a new attempt: its failure has a start.
243248 app.bus.append({ kind: "forge.spawn.started", payload: { ...(deps.drill === true ? { drill: 1 } : {}) } });
244249 } else {
245 const placed = await deps.placement.place(plan);
250 const where = plan.podLimits === undefined ? deps.placement : deps.pods;
251 if (where === undefined)
252 return err({ kind: "refused", reason: "unknown", message: "this forge cannot place a child in a pod: it is not running in a cluster" });
253 const placed = await where.place(plan);
246254 if (!placed.ok) return err({ kind: "refused", ...placed.error });
247255 if (!SAFE_ID.test(placed.value.bodyId)) {
248 await deps.placement.retire(placed.value.bodyId);
256 await where.retire(placed.value.bodyId);
249257 return failed(app, deps, "place", "placement returned an unusable body id");
250258 }
251259 ledger = {
@@ -258,6 +266,7 @@ async function make(
258266 apps: plan.apps.map((a) => a.ref),
259267 createdAt: new Date().toISOString(),
260268 size: plan.size ?? DEFAULT_SIZE,
269 ...(plan.podLimits === undefined ? {} : { pod: plan.podLimits }),
261270 statusToken: secret(),
262271 beatKey: secret(),
263272 };
@@ -662,6 +671,8 @@ export interface Child {
662671 /** When it was begun; null on a ledger older than the client list. */
663672 readonly createdAt: string | null;
664673 readonly size: Size;
674 /** The limits of a child that runs in its own pod; absent for a hosted one. */
675 readonly pod?: PodLimits;
665676 }
666677
667678 /** The children this forge has made or begun, from its ledger, by name. */
@@ -681,6 +692,7 @@ export async function listChildren(app: App): Promise<Child[]> {
681692 apps: ledger.apps ?? [],
682693 createdAt: ledger.createdAt ?? null,
683694 size: isSize(ledger.size) ? ledger.size : DEFAULT_SIZE,
695 ...(ledger.pod === undefined ? {} : { pod: ledger.pod }),
684696 });
685697 }
686698 return out;
src/http/mcp.ts +11
@@ -1571,6 +1571,17 @@ const TOOLS: readonly Tool[] = [
15711571 description:
15721572 "How big the child is (optional). Recorded in the plan only: nothing enforces its limits yet.",
15731573 },
1574 placement: {
1575 type: "string",
1576 enum: ["hosted", "pod"],
1577 description:
1578 "Where the child runs: hosted (default, inside this forge) or pod (its own Kubernetes namespace and volume, default-deny egress; only on a forge running in a cluster).",
1579 },
1580 limits: {
1581 type: "object",
1582 properties: { cpu: { type: "integer" }, memoryGiB: { type: "integer" }, diskGiB: { type: "integer" } },
1583 description: "A pod child's limits (placement pod only): cpu, memoryGiB, diskGiB; default 8 / 16 / 50.",
1584 },
15741585 keepAccess: {
15751586 type: "boolean",
15761587 description:
src/spawn/clients.ts +9
@@ -9,6 +9,8 @@
99 * list never waits on, or fails for, one forge that is down.
1010 */
1111
12 import { podHostOf } from "./pod_host.ts";
13 import type { PodView } from "./pod.ts";
1214 import type { App } from "../app.ts";
1315 import { listChildren, statusTokenOf, type Child } from "../actions/spawn.ts";
1416 import { timingSafeEqual } from "node:crypto";
@@ -36,6 +38,8 @@ export interface ClientRow {
3638 readonly lastActivityAt: string | null;
3739 /** The apps this parent runs for the child; null when it runs none here. */
3840 readonly running: ChildAppsSummary | null;
41 /** Status, resources and version of a child in its own pod; absent for a hosted one. */
42 readonly pod?: PodView | null;
3943 }
4044
4145 type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
@@ -153,6 +157,10 @@ export async function clientRows(app: App): Promise<ClientRow[]> {
153157 return last.state;
154158 }),
155159 );
160 const host = podHostOf(app);

Medium: this runs view for every pod child on each /forges render, and through pod_host each view re-resolves every egress host before it calls kube. Call only kube.status (with a short cache) so the page stays fast.

161 const pods = await Promise.all(
162 children.map((c) => (c.pod && host ? host.view(c.name, c.pod).catch(() => null) : null)),
163 );
156164 return children
157165 .map((c, i) => ({
158166 name: c.name,
@@ -164,6 +172,7 @@ export async function clientRows(app: App): Promise<ClientRow[]> {
164172 claimed: states[i]?.claimed ?? null,
165173 lastActivityAt: states[i]?.lastActivityAt ?? null,
166174 running: hostedChildApps(app, c.name) ?? null,
175 pod: pods[i] ?? null,
167176 }))
168177 .sort(
169178 (a, b) =>
src/spawn/door.ts +6 −1
@@ -26,6 +26,7 @@ import {
2626 type Placement,
2727 } from "./placement.ts";
2828 import { dryRun, planSpawn, KEY_BUDGET_NOTE, MAX_APPS, type CatalogApp, type CrewBrief, type SpawnSource } from "./plan.ts";
29 import { podHostOf } from "./pod_host.ts";
2930 import { bootHostedChild } from "./host.ts";
3031 import { ANON_SPAWNS_PER_DAY, checkAnonSpawn, noteAnonSpawn } from "./rate.ts";
3132 import { readdirSync, readFileSync } from "node:fs";
@@ -258,6 +259,8 @@ export async function spawnDoor(
258259 fresh: raw["fresh"],
259260 followMode: raw["followMode"],
260261 size: raw["size"],
262 placement: raw["placement"],

High: placement and limits reach the plan for an anonymous caller too. Refuse them when anon (like modelKey/crew above), and allow pod only for a site admin. Otherwise a stranger can place 64 CPU / 256 GiB / 2 TiB namespaces a few times a day per address.

263 limits: raw["limits"],
261264 ...(anon ? {} : { for: raw["for"] }),
262265 };
263266
@@ -291,6 +294,7 @@ export async function spawnDoor(
291294 const startedAt = Date.now();
292295 const made = await spawnForge(ctx.app, user, input, source, {
293296 placement: placementFor(ctx.app),
297 ...(podHostOf(ctx.app) === undefined ? {} : { pods: podHostOf(ctx.app)!.placement }),
294298 request: ctx.request,
295299 url: ctx.url,
296300 ...(typeof modelKey === "string" ? { modelKey } : {}),
@@ -299,8 +303,9 @@ export async function spawnDoor(
299303 if (!made.ok) return spawnWords(made.error);
300304 if (anon && !made.value.existed) noteAnonSpawn(ctx.app.db, ctx.request);
301305 // Its apps come up now, so the first visit after a claim finds them awake.
306 // A pod child runs in the cluster, not in this process.
302307 if (!made.value.existed) {
303 void bootHostedChild(ctx.app, made.value.name);
308 if (raw["placement"] !== "pod") void bootHostedChild(ctx.app, made.value.name);
304309 startWatch(ctx.app, { name: made.value.name, startedAt, probe: (probes.get(ctx.app) ?? probeOf)(made.value.url) });
305310 }
306311 return {
src/spawn/plan.ts +20
@@ -9,6 +9,7 @@
99
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { DEFAULT_MODE, type FollowMode } from "./chain.ts";
12 import { parsePodLimits, type PodLimits } from "./pod.ts";
1213 import { parseSize, type Size } from "./sizes.ts";
1314
1415 export const MAX_APPS = 50;
@@ -72,6 +73,10 @@ export interface SpawnInput {
7273 readonly followMode?: unknown;
7374 /** How big the child is: `small`, `medium` or `large`; optional. */
7475 readonly size?: unknown;
76 /** Where the child runs: `hosted` (default) or `pod`, its own Kubernetes namespace. */
77 readonly placement?: unknown;
78 /** A pod child's owner-set limits `{cpu, memoryGiB, diskGiB}`; each defaults. */
79 readonly limits?: unknown;
7580 }
7681
7782 /** What the parent has to offer. Extra fields are ignored, never copied. */
@@ -114,6 +119,8 @@ export interface SpawnPlan {
114119 readonly followMode?: FollowMode;
115120 /** The child's size, present only when chosen. */
116121 readonly size?: Size;
122 /** Present only for a pod child: its limits, defaults filled in. */
123 readonly podLimits?: PodLimits;
117124 }
118125
119126 export interface DryRun {
@@ -263,6 +270,18 @@ export function planSpawn(
263270 size = parsed.value;
264271 }
265272
273 let podLimits: PodLimits | undefined;
274 const where = input.placement;
275 if (where !== undefined && where !== null && where !== "" && where !== "hosted" && where !== "pod")
276 return refuse("placement", "must be hosted or pod");
277 if (where === "pod") {
278 const parsed = parsePodLimits(input.limits);
279 if (!parsed.ok) return refuse("limits", parsed.error);
280 podLimits = parsed.value;
281 } else if (input.limits !== undefined && input.limits !== null) {
282 return refuse("limits", "limits are for placement pod");
283 }
284
266285 // `forWhom` only when said, so a plan without it hashes as it always did.
267286 return ok({
268287 name,
@@ -277,6 +296,7 @@ export function planSpawn(
277296 ...(fresh === undefined ? {} : { fresh }),
278297 ...(followMode === undefined ? {} : { followMode }),
279298 ...(size === undefined ? {} : { size }),
299 ...(podLimits === undefined ? {} : { podLimits }),
280300 });
281301 }
282302
src/spawn/pod.ts added +345
@@ -0,0 +1,345 @@
1 /**
2 * Pod placement: a child forge in its own Kubernetes namespace, with its own
3 * volume claim, owner-set limits and an egress policy that denies everything
4 * but DNS and the hosts it is given. Rendering is pure (plain data in, plain
5 * manifests out); `podPlacement` only hands the manifests to a `Kube` client.
6 * The child gets no parent secret, no service account token, no tailnet and
7 * no private range: an address in one is refused before a rule is written.
8 */
9
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { serviceAccount } from "../cluster/jobs.ts";
12 import { CHILD_NAME, childPublicUrl, type Placed, type Placement, type PlacementRefusal } from "./placement.ts";
13 import type { SpawnPlan } from "./plan.ts";
14
15 /** What the owner may set; each field falls back to the default. */
16 export interface PodLimits {
17 readonly cpu: number;
18 readonly memoryGiB: number;
19 readonly diskGiB: number;
20 }
21
22 export const DEFAULT_POD_LIMITS: PodLimits = { cpu: 8, memoryGiB: 16, diskGiB: 50 };
23 const CEILING: PodLimits = { cpu: 64, memoryGiB: 256, diskGiB: 2048 };
24
25 /** Limits from the owner's choice, or the one field and sentence that is wrong. */
26 export function parsePodLimits(v: unknown): Result<PodLimits, string> {
27 if (v === undefined || v === null) return ok(DEFAULT_POD_LIMITS);
28 if (typeof v !== "object" || Array.isArray(v)) return err("limits must be an object");
29 const o = v as Record<string, unknown>;
30 const out = { ...DEFAULT_POD_LIMITS };
31 for (const k of ["cpu", "memoryGiB", "diskGiB"] as const) {
32 if (o[k] === undefined) continue;
33 const n = o[k];
34 if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > CEILING[k])
35 return err(`${k} must be a whole number from 1 to ${CEILING[k]}`);
36 out[k] = n;
37 }
38 return ok(out);
39 }
40
41 /** Ranges a child may never reach: private, tailnet, loopback, link-local. */
42 const DENIED_RANGES = ["10.0.0.0/8", "100.64.0.0/10", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "127.0.0.0/8"];
43
44 const ip4 = (s: string): number | undefined => {
45 const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
46 if (!m || m.slice(1).some((p) => +p > 255)) return undefined;
47 return ((+m[1]! << 24) | (+m[2]! << 16) | (+m[3]! << 8) | +m[4]!) >>> 0;
48 };
49
50 const maskOf = (len: number) => (len === 0 ? 0 : (~0 << (32 - len)) >>> 0);
51
52 /**
53 * Whether an IPv4 address or CIDR block touches a denied range: two blocks
54 * overlap exactly when they agree on the shorter prefix, so a block that
55 * starts outside a range but contains it (11.0.0.0/7) is denied too. IPv4
56 * only: anything that does not parse as IPv4, IPv6 included, is refused.
57 */
58 export function isDeniedAddress(addr: string): boolean {
59 const [a, bits = "32"] = addr.split("/");
60 const n = ip4(a!);
61 if (n === undefined || !/^\d{1,2}$/.test(bits) || +bits > 32) return true;
62 return DENIED_RANGES.some((r) => {
63 const [base, len] = r.split("/");
64 const mask = maskOf(Math.min(+bits, +len!));
65 return ((n & mask) >>> 0) === ((ip4(base!)! & mask) >>> 0);
66 });
67 }
68
69 /** A host a child may reach, with the public addresses the caller resolved for it. */
70 export interface Egress {
71 readonly host: string;
72 readonly addresses: readonly string[];
73 }
74
75 export interface PodOptions {
76 /** The parent forge's public origin (`parentOrigin`). */
77 readonly parent: string;
78 /** The image of the parent's current release. */
79 readonly image: string;
80 /** Hosts the child may reach: registry, model providers, the parent's public URL. */
81 readonly egress: readonly Egress[];
82 /** Namespace of the edge that fronts children; the only ingress. */
83 readonly edgeNamespace?: string;
84 readonly storageClass?: string;
85 }
86
87 const PORT = 3000;
88 export const POD_UID = 10001;
89 const DATA = "/data";
90 const HOST = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;
91
92 export const podNamespace = (name: string) => `forge-child-${name}`;
93
94 export interface PodManifests {
95 readonly namespace: string;
96 readonly objects: readonly object[];
97 }
98
99 /** Every manifest a child pod needs, or the reason one is refused. */
100 export function renderPod(
101 name: string,
102 limits: PodLimits,
103 o: PodOptions,
104 env: Record<string, string> = {},
105 ): Result<PodManifests, string> {
106 if (!CHILD_NAME.test(name)) return err("bad child name");
107 if (typeof o.image !== "string" || !o.image || /\s/.test(o.image)) return err("image is required");
108 const ns = podNamespace(name);
109 const labels = { "app.kubernetes.io/name": "forge-child", "forge/child": name };
110 const publicUrl = childPublicUrl(name, o.parent);
111
112 const cidrs: string[] = [];
113 for (const e of o.egress) {
114 if (!HOST.test(e.host)) return err(`bad egress host ${e.host}`);
115 for (const a of e.addresses) {
116 if (isDeniedAddress(a)) return err(`${e.host} resolves to ${a}, inside a range a child may not reach`);
117 cidrs.push(a.includes("/") ? a : `${a}/32`);
118 }
119 }
120 const envList = Object.entries(env).map(([k, v]) => {
121 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || typeof v !== "string") throw new Error(`bad env ${k}`);
122 return { name: k, value: v };
123 });
124 const meta = (n: string, extra: object = {}) => ({ name: n, namespace: ns, labels, ...extra });
125
126 const objects: object[] = [
127 { apiVersion: "v1", kind: "Namespace", metadata: { name: ns, labels: { ...labels, "pod-security.kubernetes.io/enforce": "restricted" } } },
128 {
129 apiVersion: "v1",
130 kind: "ResourceQuota",
131 metadata: meta("limits"),
132 spec: { hard: { "limits.cpu": String(limits.cpu), "limits.memory": `${limits.memoryGiB}Gi`, "requests.storage": `${limits.diskGiB}Gi`, persistentvolumeclaims: "1" } },
133 },
134 {
135 apiVersion: "v1",
136 kind: "PersistentVolumeClaim",
137 metadata: meta("data"),
138 spec: {
139 accessModes: ["ReadWriteOnce"],
140 ...(o.storageClass ? { storageClassName: o.storageClass } : {}),
141 resources: { requests: { storage: `${limits.diskGiB}Gi` } },
142 },
143 },
144 {
145 apiVersion: "apps/v1",
146 kind: "Deployment",
147 metadata: meta("forge", { annotations: { "forge/image": o.image } }),
148 spec: {
149 replicas: 1,
150 strategy: { type: "Recreate" },
151 selector: { matchLabels: labels },
152 template: {
153 metadata: { labels },
154 spec: {
155 // No kube credential in the child: it is not a client of the cluster.
156 automountServiceAccountToken: false,
157 enableServiceLinks: false,
158 // The release image is assumed to run as this user; fsGroup makes the PVC writable by it.
159 securityContext: { runAsNonRoot: true, runAsUser: POD_UID, runAsGroup: POD_UID, fsGroup: POD_UID, seccompProfile: { type: "RuntimeDefault" } },
160 containers: [
161 {
162 name: "forge",
163 image: o.image,
164 ports: [{ containerPort: PORT }],
165 env: [
166 { name: "FORGE_APP_DATA", value: DATA },
167 { name: "FORGE_URL", value: publicUrl },
168 { name: "PORT", value: String(PORT) },
169 ...envList,
170 ],
171 securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ["ALL"] } },
172 resources: {
173 limits: { cpu: String(limits.cpu), memory: `${limits.memoryGiB}Gi` },
174 requests: { cpu: "100m", memory: "256Mi" },
175 },
176 volumeMounts: [{ name: "data", mountPath: DATA }],
177 },
178 ],
179 volumes: [{ name: "data", persistentVolumeClaim: { claimName: "data" } }],
180 },
181 },
182 },
183 },
184 {
185 apiVersion: "v1",
186 kind: "Service",
187 metadata: meta("forge", { annotations: { "forge/host": new URL(publicUrl).host } }),
188 spec: { selector: labels, ports: [{ port: 80, targetPort: PORT }] },
189 },
190 // Default deny, both ways; the two policies below open only what is named.
191 { apiVersion: "networking.k8s.io/v1", kind: "NetworkPolicy", metadata: meta("default-deny"), spec: { podSelector: {}, policyTypes: ["Ingress", "Egress"] } },
192 {
193 apiVersion: "networking.k8s.io/v1",
194 kind: "NetworkPolicy",
195 metadata: meta("edge-ingress"),
196 spec: {
197 podSelector: { matchLabels: labels },
198 policyTypes: ["Ingress"],
199 ingress: [
200 {
201 from: [{ namespaceSelector: { matchLabels: { "kubernetes.io/metadata.name": o.edgeNamespace ?? "ingress" } } }],
202 ports: [{ protocol: "TCP", port: PORT }],
203 },
204 ],
205 },
206 },
207 {
208 apiVersion: "networking.k8s.io/v1",
209 kind: "NetworkPolicy",
210 metadata: meta("egress"),
211 spec: {
212 podSelector: { matchLabels: labels },
213 policyTypes: ["Egress"],
214 egress: [
215 {
216 to: [{ namespaceSelector: { matchLabels: { "kubernetes.io/metadata.name": "kube-system" } }, podSelector: { matchLabels: { "k8s-app": "kube-dns" } } }],
217 ports: [{ protocol: "UDP", port: 53 }, { protocol: "TCP", port: 53 }],
218 },
219 ...(cidrs.length ? [{ to: cidrs.map((cidr) => ({ ipBlock: { cidr } })), ports: [{ protocol: "TCP", port: 443 }] }] : []),
220 ],
221 },
222 },
223 ];
224 return ok({ namespace: ns, objects });
225 }
226
227 /** The cluster, as far as placement needs it. */
228 export interface Kube {
229 /** Whether the namespace is already there, so a failed placement never deletes a child's data. */
230 exists(namespace: string): Promise<boolean>;
231 apply(objects: readonly object[]): Promise<void>;
232 /** Idempotent: a namespace that is gone is deleted. */
233 deleteNamespace(name: string): Promise<void>;
234 status(namespace: string): Promise<PodStatus>;
235 }
236
237 export interface PodStatus {
238 readonly state: "starting" | "running" | "failed" | "gone";
239 readonly image: string | null;
240 }
241
242 /** What /forges shows of a pod child: status, resources, version. */
243 export interface PodView extends PodStatus {
244 readonly limits: PodLimits;
245 }
246
247 export function podWords(v: PodView): string {
248 const r = `${v.limits.cpu} CPU · ${v.limits.memoryGiB} GiB memory · ${v.limits.diskGiB} GiB disk`;
249 const version = v.image === null ? "" : ` · ${v.image.split("/").pop()}`;
250 return `pod ${v.state} · ${r}${version}`;
251 }
252
253 export interface PodPlacementOptions extends PodOptions {
254 readonly kube: Kube;
255 readonly env?: Record<string, string>;
256 }
257
258 const refusal = (message: string) => err<PlacementRefusal>({ reason: "unknown", message });
259
260 export function podPlacement(opts: PodPlacementOptions): Placement & { view(name: string, limits?: PodLimits): Promise<PodView> } {
261 return {
262 async place(plan: SpawnPlan): Promise<Result<Placed, PlacementRefusal>> {
263 const m = renderPod(plan.name, plan.podLimits ?? DEFAULT_POD_LIMITS, opts, opts.env);
264 if (!m.ok) return refusal(m.error);
265 const ns = m.value.namespace;
266 // Only a namespace this call made is this call's to delete.
267 let existed: boolean;
268 try {
269 existed = await opts.kube.exists(ns);
270 await opts.kube.apply(m.value.objects);
271 } catch (e) {
272 if (existed! === false) await opts.kube.deleteNamespace(ns).catch(() => {});
273 return refusal(`the cluster refused the child: ${e instanceof Error ? e.message : "unknown"}`);
274 }
275 return ok({ url: childPublicUrl(plan.name, opts.parent), bodyId: `pod-${ns}` });
276 },
277 async retire(bodyId) {
278 const ns = /^pod-(forge-child-[a-z0-9-]+)$/.exec(bodyId)?.[1];
279 if (!ns) return ok();
280 try {
281 await opts.kube.deleteNamespace(ns);
282 } catch (e) {
283 return refusal(`could not retire ${ns}: ${e instanceof Error ? e.message : "unknown"}`);
284 }
285 return ok();
286 },
287 async view(name, limits = DEFAULT_POD_LIMITS) {
288 return { ...(await opts.kube.status(podNamespace(name))), limits };
289 },
290 };
291 }
292
293 const PATHS: Record<string, string> = {
294 Namespace: "/api/v1/namespaces",
295 ResourceQuota: "/api/v1/namespaces/{ns}/resourcequotas",
296 PersistentVolumeClaim: "/api/v1/namespaces/{ns}/persistentvolumeclaims",
297 Service: "/api/v1/namespaces/{ns}/services",
298 Deployment: "/apis/apps/v1/namespaces/{ns}/deployments",
299 NetworkPolicy: "/apis/networking.k8s.io/v1/namespaces/{ns}/networkpolicies",
300 };
301
302 /** The kube API over fetch with the service account, as `cluster/jobs.ts` speaks it. */
303 export function kubeApi(f: typeof fetch = fetch, cred = serviceAccount()): Kube {
304 const call = (method: string, path: string, body?: object, type = "application/json") =>
305 f(`${cred.server}${path}`, {
306 method,
307 headers: { authorization: `Bearer ${cred.token}`, accept: "application/json", ...(body ? { "content-type": type } : {}) },
308 body: body ? JSON.stringify(body) : undefined,
309 ...(cred.ca ? { tls: { ca: cred.ca } } : {}),
310 } as RequestInit);
311 return {
312 async apply(objects) {
313 for (const o of objects as { kind: string; metadata: { name: string; namespace?: string } }[]) {
314 const path = PATHS[o.kind]?.replace("{ns}", encodeURIComponent(o.metadata.namespace ?? ""));
315 if (!path) throw new Error(`unknown kind ${o.kind}`);
316 const res = await call("POST", path, o);
317 // The namespace and the claim already exist with the child's data: left as they are.
318 if (res.status === 409 && (o.kind === "Namespace" || o.kind === "PersistentVolumeClaim")) continue;
319 if (res.status === 409) {
320 // Already there: bring it to this spec, so a changed limit lands.
321 const patched = await call("PATCH", `${path}/${encodeURIComponent(o.metadata.name)}`, o, "application/merge-patch+json");
322 if (!patched.ok) throw new Error(`kube PATCH ${o.kind} ${patched.status}`);
323 } else if (!res.ok) throw new Error(`kube POST ${o.kind} ${res.status}`);
324 }
325 },
326 async exists(namespace) {
327 const res = await call("GET", `/api/v1/namespaces/${encodeURIComponent(namespace)}`);
328 if (res.status === 404) return false;
329 if (!res.ok) throw new Error(`kube GET ${res.status}`);
330 return true;
331 },
332 async deleteNamespace(name) {
333 const res = await call("DELETE", `/api/v1/namespaces/${encodeURIComponent(name)}`);
334 if (!res.ok && res.status !== 404) throw new Error(`kube DELETE ${res.status}`);
335 },
336 async status(namespace) {
337 const res = await call("GET", `/apis/apps/v1/namespaces/${encodeURIComponent(namespace)}/deployments/forge`);
338 if (res.status === 404) return { state: "gone", image: null };
339 if (!res.ok) throw new Error(`kube GET ${res.status}`);
340 const d = (await res.json()) as { metadata?: { annotations?: Record<string, string> }; status?: { readyReplicas?: number; conditions?: { type: string; status: string }[] } };
341 const failed = d.status?.conditions?.some((c) => c.type === "Progressing" && c.status === "False");
342 return { state: failed ? "failed" : d.status?.readyReplicas ? "running" : "starting", image: d.metadata?.annotations?.["forge/image"] ?? null };
343 },
344 };
345 }
src/spawn/pod_host.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * The pod placement as this forge is set up to use it: present only inside a
3 * cluster with a release image named, otherwise absent and a pod child is
4 * refused plainly. Its egress hosts (the registry and model providers it is
5 * told, plus this forge's own public host) are resolved to public addresses
6 * each time a child is placed, so placing again refreshes them.
7 */
8
9 import { resolve4 } from "node:dns/promises";
10 import type { App } from "../app.ts";
11 import { kubeApi, podPlacement, type Egress, type Kube, type PodLimits, type PodView } from "./pod.ts";
12 import { parentOrigin, type Placement } from "./placement.ts";
13
14 export interface PodHost {
15 readonly placement: Placement;
16 view(name: string, limits: PodLimits): Promise<PodView>;
17 }
18
19 export interface PodHostOptions {
20 readonly env?: Record<string, string | undefined>;
21 readonly kube?: Kube;
22 readonly resolve?: (host: string) => Promise<string[]>;
23 }
24
25 const hosts = new WeakMap<App, PodHost | null>();
26
27 /** Tests (and a cluster of another shape, one day) swap the pod host. */
28 export function usePodHost(app: App, host: PodHost | null): void {
29 hosts.set(app, host);
30 }
31
32 export function podHostOf(app: App, o: PodHostOptions = {}): PodHost | undefined {
33 const held = hosts.get(app);
34 if (held !== undefined) return held ?? undefined;
35 const env = o.env ?? process.env;
36 const image = env.FORGE_POD_IMAGE;
37 if (!image || (!o.kube && !env.KUBERNETES_SERVICE_HOST)) return undefined;
38 const parent = parentOrigin(app.config);
39 const names = [new URL(parent).hostname, ...(env.FORGE_POD_EGRESS ?? "").split(",").map((h) => h.trim()).filter(Boolean)];
40 const lookup = o.resolve ?? ((h: string) => resolve4(h));
41 const kube = o.kube ?? kubeApi();
42 const build = async () => {
43 const egress: Egress[] = await Promise.all(names.map(async (host) => ({ host, addresses: await lookup(host).catch(() => []) })));
44 return podPlacement({
45 parent,
46 image,
47 egress,
48 kube,
49 ...(env.FORGE_POD_EDGE_NAMESPACE ? { edgeNamespace: env.FORGE_POD_EDGE_NAMESPACE } : {}),
50 ...(env.FORGE_POD_STORAGE_CLASS ? { storageClass: env.FORGE_POD_STORAGE_CLASS } : {}),
51 });
52 };
53 const host: PodHost = {
54 placement: {
55 async place(plan) {
56 return (await build()).place(plan);
57 },
58 async retire(bodyId) {
59 return (await build()).retire(bodyId);
60 },
61 },
62 async view(name, limits) {

view doesn't need the egress addresses: going through build() here adds DNS lookups to every page view. Call kube.status(podNamespace(name)) directly.

63 return (await build()).view(name, limits);
64 },
65 };
66 hosts.set(app, host);
67 return host;
68 }
src/tui/screens/forges.ts +2 −1
@@ -6,6 +6,7 @@
66
77 import type { Ctx, Screen } from "../app/app.ts";
88 import { binding } from "../app/keys.ts";
9 import { podWords } from "../../spawn/pod.ts";
910 import { CLAIM_WORDS, claimState, runningWords, type ClientRow } from "../../spawn/clients.ts";
1011 import { card } from "../ui/widgets.ts";
1112 import { drawFacts } from "./common.ts";
@@ -15,7 +16,7 @@ export function forgeLines(rows: readonly ClientRow[]): [string, string][] {
1516 if (rows.length === 0) return [["", "You have not sent a forge yet"]];
1617 return rows.map((r) => [
1718 r.name,
18 [r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], runningWords(r)]
19 [r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], runningWords(r), r.pod ? podWords(r.pod) : null]
1920 .filter((m): m is string => m !== null)
2021 .join(" · "),
2122 ]);
src/web/pages/forges.ts +7
@@ -16,6 +16,7 @@ import { reissueDoor } from "../../spawn/door.ts";
1616 import { readForm } from "../form.ts";
1717 import { btn, card, empty, time } from "../ui.ts";
1818 import { noRoom } from "../../spawn/door.ts";
19 import { podWords } from "../../spawn/pod.ts";
1920 import { claimLinkBody } from "./new-forge.ts";
2021
2122
@@ -28,12 +29,18 @@ function runningNote(r: ClientRow): Html | null {
2829 >`;
2930 }
3031
32 /** A pod child's status, resources and version. */
33 function podNote(r: ClientRow): Html | null {
34 return r.pod ? html`<span data-pod="${r.pod.state}">${podWords(r.pod)}</span>` : null;
35 }
36
3137 function forgeRow(r: ClientRow): Html {
3238 const state = claimState(r);
3339 const meta = [
3440 r.for === null ? null : html`for ${r.for}`,
3541 r.apps.length === 0 ? null : html`${r.apps.join(", ")}`,
3642 runningNote(r),
43 podNote(r),
3744 r.sentAt === null ? null : html`sent ${time(r.sentAt)}`,
3845 r.lastActivityAt === null
3946 ? null
test/spawn-pod-door.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * A pod child end to end through the door: the plan takes a placement and
3 * limits (validated), spawn places it through the pod host, the ledger
4 * remembers its limits, and /forges and the MCP `forges` tool show its
5 * status, resources and version.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { usePlacement, useProbe } from "../src/spawn/door.ts";
16 import { ok } from "../src/kernel/result.ts";
17 import { planSpawn } from "../src/spawn/plan.ts";
18 import { podPlacement, type Kube } from "../src/spawn/pod.ts";
19 import { podHostOf, usePodHost } from "../src/spawn/pod_host.ts";
20
21 const source = { catalog: [], briefs: [], subscriptions: [] };
22 const base = { name: "kid", org: "kids", apps: [], carryBriefs: false, carrySubscriptions: false };
23
24 describe("plan: placement and limits", () => {
25 test("hosted is the default and a plan without one hashes as before", () => {
26 const r = planSpawn(base, source);
27 if (!r.ok) throw 0;
28 expect("podLimits" in r.value).toBe(false);
29 expect(planSpawn({ ...base, placement: "hosted" }, source)).toEqual(r);
30 });
31 test("pod fills the defaults and follows the owner's choice", () => {
32 const d = planSpawn({ ...base, placement: "pod" }, source);
33 expect(d.ok && d.value.podLimits).toEqual({ cpu: 8, memoryGiB: 16, diskGiB: 50 });
34 const o = planSpawn({ ...base, placement: "pod", limits: { cpu: 2 } }, source);
35 expect(o.ok && o.value.podLimits).toEqual({ cpu: 2, memoryGiB: 16, diskGiB: 50 });
36 });
37 test("bad placement, bad limits, and limits without a pod are refused", () => {
38 expect(planSpawn({ ...base, placement: "moon" }, source)).toMatchObject({ ok: false, error: { field: "placement" } });
39 expect(planSpawn({ ...base, placement: "pod", limits: { cpu: 0 } }, source)).toMatchObject({ ok: false, error: { field: "limits" } });
40 expect(planSpawn({ ...base, limits: { cpu: 2 } }, source)).toMatchObject({ ok: false, error: { field: "limits" } });
41 });
42 });
43
44 describe("a pod child through the door", () => {
45 let dir: string;
46 let app: App;
47 let servers: Servers;
48 let rw: string;
49 const applied: object[][] = [];
50 const kube: Kube = {
51 exists: async () => false,
52 apply: async (o) => void applied.push([...o]),
53 deleteNamespace: async () => {},
54 status: async () => ({ state: "running", image: "registry.example.com/forge:0.7.212" }),
55 };
56 const post = (payload: unknown) =>
57 fetch(`${servers.url}/api/v1/forges`, {
58 method: "POST",
59 headers: { "content-type": "application/json", authorization: `Bearer ${rw}` },
60 body: JSON.stringify(payload),
61 });
62
63 beforeAll(async () => {
64 dir = await mkdtemp(join(tmpdir(), "forge-pod-door-"));
65 app = createApp({ dataDir: dir, port: 0, url: "https://forge.example.com" });
66 servers = await serve(app);
67 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
68 if (!a.ok) throw new Error("user");
69 rw = createToken(app.db, a.value.id, "rw", "admin").token;
70 useProbe(app, () => async () => true);
71 usePlacement(app, { place: async (p) => ok({ url: `https://${p.name}.fake.test`, bodyId: `fake-${p.name}` }), retire: async () => ok() });
72 }, 30_000);
73 afterAll(async () => {
74 servers.stop();
75 app.close();
76 await rm(dir, { recursive: true, force: true });
77 });
78
79 test("without a cluster the door says so, and nothing is made", async () => {
80 expect(podHostOf(app, { env: {} })).toBeUndefined();
81 const res = await post({ name: "nope", placement: "pod", dryRun: false });
82 expect(res.status).toBe(409);
83 expect(((await res.json()) as any).message).toContain("not running in a cluster");
84 });
85
86 test("bad limits are refused at the door", async () => {
87 const res = await post({ name: "bad", placement: "pod", limits: { cpu: -1 } });
88 expect(res.status).toBe(422);
89 });
90
91 test("a pod child is placed with the owner's limits and /forges shows it", async () => {
92 const host = podHostOf(app, { env: { FORGE_POD_IMAGE: "registry.example.com/forge:0.7.212", FORGE_POD_EGRESS: "registry.npmjs.org" }, kube, resolve: async () => ["203.0.113.9"] })!;
93 usePodHost(app, host);
94 const res = await post({ name: "kid", placement: "pod", limits: { cpu: 2, memoryGiB: 4 }, dryRun: false });
95 expect(res.status).toBe(201);
96 expect(((await res.json()) as any).bodyId).toBe("pod-forge-child-kid");
97 const quota = (applied[0] as any[]).find((o) => o.kind === "ResourceQuota");
98 expect(quota.spec.hard["limits.cpu"]).toBe("2");
99 const egress = (applied[0] as any[]).find((o) => o.metadata.name === "egress");
100 expect(JSON.stringify(egress)).toContain("203.0.113.9/32");
101
102 const page = await (await fetch(`${servers.url}/forges`, { headers: { authorization: `Bearer ${rw}` } })).text();
103 expect(page).toContain('data-pod="running"');
104 expect(page).toContain("pod running · 2 CPU · 4 GiB memory · 50 GiB disk · forge:0.7.212");
105
106 const mcp = await fetch(`${servers.url}/mcp`, {
107 method: "POST",
108 headers: { "content-type": "application/json", authorization: `Bearer ${rw}` },
109 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }),
110 });
111 expect(await mcp.text()).toContain("forge:0.7.212");
112 });
113
114 test("a hosted child shows no pod line", async () => {
115 await post({ name: "plain", dryRun: false });
116 const page = await (await fetch(`${servers.url}/forges`, { headers: { authorization: `Bearer ${rw}` } })).text();
117 const row = page.split('data-forge="plain"')[1]!.split("</li>")[0]!;
118 expect(row).not.toContain("data-pod");
119 });
120 });
121
122 test("the terminal's forge line carries a pod child's status", async () => {
123 const { forgeLines } = await import("../src/tui/screens/forges.ts");
124 const row = { name: "kid", url: "u", for: null, apps: [], sentAt: null, made: true, claimed: true, lastActivityAt: null, running: null,
125 pod: { state: "running" as const, image: "r/forge:1", limits: { cpu: 8, memoryGiB: 16, diskGiB: 50 } } };
126 expect(forgeLines([row])[0]![1]).toContain("pod running · 8 CPU · 16 GiB memory · 50 GiB disk · forge:1");
127 });
test/spawn-pod.test.ts added +169
@@ -0,0 +1,169 @@
1 import { describe, expect, test } from "bun:test";
2 import { kubeApi, DEFAULT_POD_LIMITS, isDeniedAddress, parsePodLimits, podPlacement, podWords, renderPod, type Kube } from "../src/spawn/pod.ts";
3 import type { SpawnPlan } from "../src/spawn/plan.ts";
4
5 const plan = (name: string): SpawnPlan => ({ name, org: "o", apps: [], briefs: [], subscriptions: [], direction: "", keepAccess: false, budgetUsd: null });
6 const opts = {
7 parent: "https://forge.example.com",
8 image: "registry.example.com/forge:0.7.212",
9 egress: [
10 { host: "forge.example.com", addresses: ["203.0.113.7"] },
11 { host: "registry.npmjs.org", addresses: ["104.16.0.0/20"] },
12 ],
13 };
14 const render = (limits = DEFAULT_POD_LIMITS) => {
15 const r = renderPod("kid", limits, opts);
16 if (!r.ok) throw new Error(r.error);
17 return r.value;
18 };
19 const find = (kind: string, name?: string) =>
20 render().objects.find((o: any) => o.kind === kind && (!name || o.metadata.name === name)) as any;
21
22 describe("pod manifests", () => {
23 test("own namespace, PVC and the release image", () => {
24 expect(render().namespace).toBe("forge-child-kid");
25 expect(find("PersistentVolumeClaim").spec.resources.requests.storage).toBe("50Gi");
26 expect(find("Deployment").spec.template.spec.containers[0].image).toBe(opts.image);
27 expect(find("Deployment").spec.template.spec.automountServiceAccountToken).toBe(false);
28 expect(find("Service").metadata.annotations["forge/host"]).toBe("kid--forge.example.com");
29 });
30
31 test("limits default to 8 CPU / 16 GiB / 50 GiB and follow the owner", () => {
32 expect(find("ResourceQuota").spec.hard).toMatchObject({ "limits.cpu": "8", "limits.memory": "16Gi", "requests.storage": "50Gi" });
33 const own = parsePodLimits({ cpu: 2, memoryGiB: 4 });
34 expect(own).toEqual({ ok: true, value: { cpu: 2, memoryGiB: 4, diskGiB: 50 } });
35 if (!own.ok) throw 0;
36 const d = (renderPod("kid", own.value, opts) as any).value.objects.find((o: any) => o.kind === "Deployment");
37 expect(d.spec.template.spec.containers[0].resources.limits).toEqual({ cpu: "2", memory: "4Gi" });
38 expect(parsePodLimits(undefined)).toEqual({ ok: true, value: DEFAULT_POD_LIMITS });
39 for (const bad of [{ cpu: 0 }, { cpu: 1.5 }, { memoryGiB: "9" }, { diskGiB: 99999 }, [], 3])
40 expect(parsePodLimits(bad).ok).toBe(false);
41 });
42
43 test("egress: default deny, DNS and the named public hosts only", () => {
44 expect(find("NetworkPolicy", "default-deny").spec).toEqual({ podSelector: {}, policyTypes: ["Ingress", "Egress"] });
45 const rules = find("NetworkPolicy", "egress").spec.egress;
46 expect(rules).toHaveLength(2);
47 const cidrs = rules[1].to.map((t: any) => t.ipBlock.cidr);
48 expect(cidrs).toEqual(["203.0.113.7/32", "104.16.0.0/20"]);
49 const text = JSON.stringify(rules);
50 for (const r of ["10.0.0.0", "100.64.", "192.168.", "0.0.0.0/0"]) expect(text).not.toContain(r);
51 });
52
53 test("a host resolving to 10/8, the tailnet or the parent's service is refused", () => {
54 for (const a of ["11.0.0.0/7", "100.0.0.0/8", "172.0.0.0/8", "8.0.0.0/5", "10.1.2.3", "10.0.0.0/8", "100.64.0.0/10", "100.100.1.1", "172.20.0.1", "192.168.1.1", "169.254.169.254", "0.0.0.0/0", "nonsense"])
55 expect(isDeniedAddress(a)).toBe(true);
56 for (const a of ["203.0.113.7", "104.16.0.0/20"]) expect(isDeniedAddress(a)).toBe(false);
57 const r = renderPod("kid", DEFAULT_POD_LIMITS, { ...opts, egress: [{ host: "forge.internal", addresses: ["10.43.0.12"] }] });
58 expect(r.ok).toBe(false);
59 });
60
61 test("the pod runs as an explicit non-root user that owns the volume", () => {
62 const sc = find("Deployment").spec.template.spec.securityContext;
63 expect(sc).toMatchObject({ runAsNonRoot: true, runAsUser: 10001, fsGroup: 10001 });
64 });
65
66 test("no parent secret reaches the child", () => {
67 const text = JSON.stringify(render());
68 expect(text.replace("automountServiceAccountToken", "")).not.toMatch(/secret|token/i);
69 expect(find("Deployment").spec.template.spec.containers[0].env.map((e: any) => e.name)).toEqual(["FORGE_APP_DATA", "FORGE_URL", "PORT"]);
70 });
71 });
72
73 describe("pod placement", () => {
74 const kube = (): Kube & { applied: object[][]; deleted: string[]; there?: boolean } => {
75 const k: any = { applied: [], deleted: [] };
76 k.apply = async (o: object[]) => void k.applied.push(o);
77 k.exists = async () => k.there ?? false;
78 k.deleteNamespace = async (n: string) => void k.deleted.push(n);
79 k.status = async () => ({ state: "running", image: "registry.example.com/forge:0.7.212" });
80 return k;
81 };
82
83 test("places at the child's public host and retires by deleting the namespace", async () => {
84 const k = kube();
85 const p = podPlacement({ ...opts, kube: k });
86 const r = await p.place(plan("kid"));
87 expect(r).toEqual({ ok: true, value: { url: "https://kid--forge.example.com", bodyId: "pod-forge-child-kid" } });
88 expect(k.applied).toHaveLength(1);
89 expect((await p.retire("pod-forge-child-kid")).ok).toBe(true);
90 expect(k.deleted).toEqual(["forge-child-kid"]);
91 expect((await p.retire("hosted-x")).ok).toBe(true);
92 expect(k.deleted).toHaveLength(1);
93 });
94
95 test("a failed apply cleans up and refuses", async () => {
96 const k = kube();
97 k.apply = async () => { throw new Error("quota"); };
98 const r = await podPlacement({ ...opts, kube: k }).place(plan("kid"));
99 expect(r.ok).toBe(false);
100 expect(k.deleted).toEqual(["forge-child-kid"]);
101 });
102
103 test("a failed apply never deletes a namespace that was already there", async () => {
104 const k = kube();
105 k.there = true;
106 k.apply = async () => { throw new Error("quota"); };
107 expect((await podPlacement({ ...opts, kube: k }).place(plan("kid"))).ok).toBe(false);
108 expect(k.deleted).toEqual([]);
109 });
110
111 test("the plan's limits reach the manifests", async () => {
112 const k = kube();
113 await podPlacement({ ...opts, kube: k }).place({ ...plan("kid"), podLimits: { cpu: 2, memoryGiB: 4, diskGiB: 10 } });
114 const q = (k.applied[0] as any[]).find((o) => o.kind === "ResourceQuota");
115 expect(q.spec.hard).toMatchObject({ "limits.cpu": "2", "limits.memory": "4Gi", "requests.storage": "10Gi" });
116 });
117
118 test("the view says status, resources and version", async () => {
119 const v = await podPlacement({ ...opts, kube: kube() }).view("kid");
120 expect(podWords(v)).toBe("pod running · 8 CPU · 16 GiB memory · 50 GiB disk · forge:0.7.212");
121 });
122 });
123
124 describe("kubeApi", () => {
125 const cred = { server: "https://k", token: "t", namespace: "n" };
126 const fake = (answer: (m: string, u: string) => number) => {
127 const calls: { m: string; u: string; type: string | null }[] = [];
128 const f = (async (u: string, i: RequestInit) => {
129 calls.push({ m: i.method!, u: u.replace("https://k", ""), type: new Headers(i.headers).get("content-type") });
130 return new Response("{}", { status: answer(i.method!, u) });
131 }) as unknown as typeof fetch;
132 return { calls, kube: kubeApi(f, cred) };
133 };
134 const objects = (renderPod("kid", DEFAULT_POD_LIMITS, opts) as any).value.objects as any[];
135
136 test("creates in order, namespace first", async () => {
137 const { calls, kube } = fake(() => 201);
138 await kube.apply(objects);
139 expect(calls.every((c) => c.m === "POST")).toBe(true);
140 expect(calls[0]!.u).toBe("/api/v1/namespaces");
141 expect(calls[1]!.u).toBe("/api/v1/namespaces/forge-child-kid/resourcequotas");
142 expect(calls).toHaveLength(objects.length);
143 });
144
145 test("the namespace and the claim are left alone on a conflict", async () => {
146 const { calls, kube } = fake((m) => (m === "POST" ? 409 : 200));
147 await kube.apply(objects.filter((o) => o.kind === "Namespace" || o.kind === "PersistentVolumeClaim"));
148 expect(calls.map((c) => c.m)).toEqual(["POST", "POST"]);
149 });
150
151 test("a conflict is patched to the new spec, and a refusal fails", async () => {
152 const { calls, kube } = fake((m) => (m === "POST" ? 409 : 200));
153 await kube.apply(objects.filter((o) => o.kind === "ResourceQuota"));
154 expect(calls.map((c) => c.m)).toEqual(["POST", "PATCH"]);
155 expect(calls[1]).toMatchObject({ u: "/api/v1/namespaces/forge-child-kid/resourcequotas/limits", type: "application/merge-patch+json" });
156 await expect(fake((m) => (m === "POST" ? 409 : 422)).kube.apply(objects)).rejects.toThrow("PATCH");
157 await expect(fake(() => 403).kube.apply(objects)).rejects.toThrow("POST");
158 });
159
160 test("exists tells a namespace from a missing one", async () => {
161 expect(await fake(() => 200).kube.exists("n")).toBe(true);
162 expect(await fake(() => 404).kube.exists("n")).toBe(false);
163 });
164
165 test("deleting a namespace that is gone succeeds", async () => {
166 await fake(() => 404).kube.deleteNamespace("forge-child-kid");
167 await expect(fake(() => 500).kube.deleteNamespace("forge-child-kid")).rejects.toThrow();
168 });
169 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs