Files
mtusi2026lab4/student-tests/concurrent-images.ts
T

250 lines
7.2 KiB
TypeScript

import { resolve } from "node:path";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { assertNoGame } from "../scripts/k3s-model";
const root = resolve(import.meta.dir, "..");
if (process.argv.includes("--check")) {
console.log("Parsed Kubernetes concurrent image experiment");
process.exit(0);
}
const base = process.env.BASE_URL ?? "http://127.0.0.1:28204";
const prefix = "st_" + crypto.randomUUID().replaceAll("-", "").slice(0, 16);
async function command(args: string[]) {
const p = Bun.spawn(args, {
cwd: root,
stdout: "pipe",
stderr: "pipe",
signal: AbortSignal.timeout(90000),
});
const [out, err] = await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
if ((await p.exited) !== 0) {
await writeFile(resolve(root, ".local/concurrent-error.txt"), out + err, {
mode: 0o600,
});
throw new Error("Concurrent image operation failed");
}
return out;
}
function stand(args: string[]) {
return command([
process.execPath,
"--no-env-file",
"scripts/k3s.ts",
...args,
]);
}
async function guard() {
const p = Bun.spawn(["game-running"], { stdout: "ignore", stderr: "pipe" });
await new Response(p.stderr).text();
assertNoGame(await p.exited);
}
async function json(
method: string,
path: string,
status: number,
token?: string,
body?: unknown,
headers: Record<string, string> = {},
) {
const r = await fetch(base + path, {
method,
headers: {
...headers,
...(token ? { Authorization: "Bearer " + token } : {}),
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30000),
});
const out = (await r.json()) as any;
if (r.status !== status)
throw new Error("Image experiment HTTP status differs");
return out;
}
const parent = resolve(root, "evidence/k3s/concurrent-images");
await mkdir(parent, { recursive: true });
const evidence = await mkdtemp(resolve(parent, "run-"));
await writeFile(
resolve(evidence, "run.json"),
JSON.stringify({
run_id: prefix,
started_at: new Date().toISOString(),
state: "started",
}) + "\n",
{ flag: "wx" },
);
let finished = false,
touched = false,
primary: unknown,
monitorError: unknown,
result: unknown,
monitor: Promise<void> | undefined;
const cleanupErrors: string[] = [],
samples: any[] = [];
try {
await guard();
const info = JSON.parse(await stand(["info"]));
if (new URL(base).origin !== "http://127.0.0.1:" + info.port)
throw new Error("API URL differs from the claimed Kubernetes endpoint");
const raw = new Uint8Array(
await Bun.file(resolve(root, ".local/concurrent.png")).arrayBuffer(),
);
touched = true;
await command([
resolve(root, "scripts/kube.sh"),
"rollout",
"restart",
"deployment/api",
]);
await stand(["ready"]);
const before = JSON.parse(await stand(["stats"]));
if (before.pods.length !== 2) throw new Error("Expected two API pods");
const user = await json("POST", "/api/v1/users", 201, undefined, {
username: prefix,
display_name: "Synthetic memory experiment",
password: "synthetic-password-123",
});
const session = await json(
"POST",
"/api/v1/auth/sessions",
201,
undefined,
undefined,
{
Authorization:
"Basic " +
Buffer.from(prefix + ":synthetic-password-123").toString("base64"),
},
);
const chat = await json("POST", "/api/v1/chats", 201, session.token, {
title: "Ten concurrent uploads",
member_ids: [user.id],
});
monitor = (async () => {
while (!finished) {
samples.push(JSON.parse(await stand(["stats"])));
await Bun.sleep(100);
}
})().catch((error) => {
monitorError = error;
finished = true;
});
const uploads = Array.from({ length: 10 }, async (_, index) => {
let offset = 0;
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
if (offset === raw.length) {
controller.close();
return;
}
await Bun.sleep(30);
const next = Math.min(raw.length, offset + 65536);
controller.enqueue(raw.slice(offset, next));
offset = next;
},
});
const r = await fetch(
base +
"/api/v1/chats/" +
chat.id +
"/attachments?filename=concurrent-" +
index +
".png",
{
method: "POST",
headers: {
Authorization: "Bearer " + session.token,
"Content-Type": "image/png",
},
body,
signal: AbortSignal.timeout(30000),
},
);
const payload = (await r.json()) as any;
if (r.status !== 201 && r.status !== 503)
throw new Error("Unexpected concurrent upload status");
if (r.status === 201) {
const response = await fetch(
base + "/api/v1/attachments/" + payload.id + "/content",
{
headers: { Authorization: "Bearer " + session.token },
signal: AbortSignal.timeout(10000),
},
);
const bytes = new Uint8Array(await response.arrayBuffer());
if (
response.status !== 200 ||
!Buffer.from(bytes).equals(Buffer.from(raw))
)
throw new Error("Original bytes differ");
}
return r.status;
});
const completed = await Promise.allSettled(uploads);
finished = true;
await monitor;
if (monitorError) throw monitorError;
const statuses: number[] = [];
for (const r of completed) {
if (r.status === "rejected") throw r.reason;
statuses.push(r.value);
}
if (!statuses.includes(201)) throw new Error("No upload succeeded");
const after = JSON.parse(await stand(["stats"]));
if (
after.pods.length !== 2 ||
after.pods.some((p: any) => !before.pods.some((b: any) => b.uid === p.uid))
)
throw new Error("API pod was replaced during memory measurement");
if (
after.pods.some(
(p: any) =>
!Number.isFinite(p.memory_peak_bytes) ||
p.memory_peak_bytes <= 0 ||
p.memory_peak_bytes >= 2 * 1024 ** 3,
)
)
throw new Error("Invalid or excessive cgroup memory peak");
await json("GET", "/health/ready", 200);
await guard();
result = {
attempts: 10,
image_bytes: raw.length,
success: statuses.filter((x) => x === 201).length,
rejected_503: statuses.filter((x) => x === 503).length,
peaks: after.pods,
samples,
originals_verified: true,
};
} catch (error) {
primary = error;
} finally {
finished = true;
if (monitor) await monitor;
if (touched)
try {
await stand(["task", "fixture-cleanup", prefix]);
} catch {
cleanupErrors.push("fixture_cleanup");
}
}
if (primary || cleanupErrors.length) {
await writeFile(
resolve(evidence, "failure.json"),
JSON.stringify({
primary:
primary instanceof Error ? primary.message : primary ? "unknown" : null,
cleanup_errors: cleanupErrors,
}) + "\n",
);
throw new Error("Concurrent image experiment failed");
}
await writeFile(
resolve(evidence, "summary.json"),
JSON.stringify({ complete: true, run_id: prefix, result }, null, 2) + "\n",
{ flag: "wx" },
);
console.log("PASS concurrent Kubernetes uploads: " + evidence);