import { resolve } from "node:path"; const root = resolve(import.meta.dir, ".."); const lab = (await Bun.file(resolve(root, "lab.json")).json()).number; const base = process.env.BASE_URL ?? "http://127.0.0.1:28203"; const kubernetes = process.env.VP_RUNTIME !== "compose"; if (kubernetes) { const p = Bun.spawn( [ process.execPath, "--no-env-file", resolve(root, "scripts/k3s.ts"), "info", ], { cwd: root, stdout: "pipe", stderr: "pipe" }, ); const [out, err] = await Promise.all([ new Response(p.stdout).text(), new Response(p.stderr).text(), ]); if ((await p.exited) !== 0) throw new Error("Claimed Kubernetes endpoint unavailable"); const info = JSON.parse(out); if (new URL(base).origin !== "http://127.0.0.1:" + info.port) throw new Error("HTTP target differs from the claimed cluster"); } const prefix = `st_${crypto.randomUUID().replaceAll("-", "").slice(0, 16)}`; let assertions = 0; let operation = "initialization"; function check(value: unknown, message: string): asserts value { if (!value) throw new Error(message); assertions++; } async function call( method: string, path: string, status: number, token?: string, body?: unknown, headers: Record = {}, ) { operation = method + " " + path; const response = await fetch(base + path, { method, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...headers, }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(8000), }); const bytes = await response.arrayBuffer(); let json: any; try { json = JSON.parse(new TextDecoder().decode(bytes)); } catch {} check( response.status === status, `${method} ${path}: expected ${status}, got ${response.status}`, ); check(Boolean(response.headers.get("X-Request-Id")), "Missing request ID"); if (status >= 400) check( json?.error?.request_id === response.headers.get("X-Request-Id"), "Error request ID mismatch", ); return { json, response, bytes }; } const password = "synthetic:пароль🙂123"; async function user(suffix: string) { const registration = { username: prefix + suffix, display_name: "Синтетический тест", password, }; const { json } = await call( "POST", "/api/v1/users", 201, undefined, registration, ); const login = await call( "POST", "/api/v1/auth/sessions", 201, undefined, undefined, { Authorization: "Basic " + Buffer.from(registration.username + ":" + password).toString("base64"), }, ); check(!JSON.stringify(json).includes("password"), "Password leaked in User"); check( typeof login.json.token === "string" && login.json.token.length >= 43, "Token entropy/shape", ); return { id: json.id, token: login.json.token, registration }; } async function cleanup() { // No API delete exists. Scope every statement to this run's random username prefix. const sql = `BEGIN; CREATE TEMP TABLE own_users AS SELECT id FROM users WHERE left(username,${prefix.length})='${prefix}'; DO $fixture$ BEGIN IF EXISTS(SELECT 1 FROM chat_members mine JOIN chat_members other ON other.chat_id=mine.chat_id WHERE mine.user_id IN(SELECT id FROM own_users) AND other.user_id NOT IN(SELECT id FROM own_users)) THEN RAISE EXCEPTION 'fixture has foreign memberships';END IF;END $fixture$; CREATE TEMP TABLE own_chats AS SELECT DISTINCT mine.chat_id AS id FROM chat_members mine WHERE mine.user_id IN (SELECT id FROM own_users) AND NOT EXISTS(SELECT 1 FROM chat_members other WHERE other.chat_id=mine.chat_id AND other.user_id NOT IN(SELECT id FROM own_users)); ${lab >= 3 ? "DELETE FROM idempotency WHERE user_id IN (SELECT id FROM own_users);" : ""} DELETE FROM messages WHERE sender_id IN (SELECT id FROM own_users); DELETE FROM sessions WHERE user_id IN (SELECT id FROM own_users); DELETE FROM chat_members WHERE chat_id IN (SELECT id FROM own_chats); DELETE FROM chats WHERE id IN (SELECT id FROM own_chats); DELETE FROM users WHERE id IN (SELECT id FROM own_users); COMMIT; SELECT count(*) FROM users WHERE left(username,${prefix.length})='${prefix}';`; const p = Bun.spawn( kubernetes ? [ resolve(root, "scripts/kube.sh"), "exec", "-i", "deployment/postgres", "--", "psql", "-X", "-qAt", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", ] : [ resolve(root, "scripts/compose.sh"), "exec", "-T", "postgres", "psql", "-X", "-qAt", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", ], { cwd: root, stdin: "pipe", stdout: "pipe", stderr: "pipe" }, ); p.stdin.write(sql); p.stdin.end(); const out = await new Response(p.stdout).text(); const err = await new Response(p.stderr).text(); if ((await p.exited) !== 0) throw new Error( "Fixture cleanup failed: " + err.replace(/password|token/gi, "[redacted]"), ); check( out.trim() === "0", "Fixture users remain after cleanup or SQL stdin was not executed", ); } let primary: unknown; try { const alice = await user("a"), bob = await user("b"), eve = await user("e"); await call("POST", "/api/v1/users", 400, undefined, { username: prefix + "x", display_name: "x", }); await call("POST", "/api/v1/users", 400, undefined, { ...alice.registration, password: "short", }); await call("POST", "/api/v1/users", 400, undefined, { ...alice.registration, extra: 1, }); const race = await Promise.all( [0, 1].map(async () => { const r = await fetch(base + "/api/v1/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...alice.registration, username: prefix + "race", }), }); await r.arrayBuffer(); return r.status; }), ); check( race.sort().join(",") === "201,409", "Registration race must create exactly one user", ); const denied = await call( "GET", "/api/v1/users/me", 401, undefined, undefined, { "X-User-Id": alice.id }, ); check( denied.response.headers.get("WWW-Authenticate") === 'Bearer realm="messenger"', "Bearer challenge", ); const wrong = await call( "POST", "/api/v1/auth/sessions", 401, undefined, undefined, { Authorization: "Basic " + Buffer.from(alice.registration.username + ":wrong-password").toString( "base64", ), }, ); check( wrong.response.headers.get("WWW-Authenticate") === 'Basic realm="messenger", charset="UTF-8"', "Basic challenge", ); const invalidChat = { title: "rollback", member_ids: [alice.id, crypto.randomUUID()], }; await call("POST", "/api/v1/chats", 400, alice.token, invalidChat); let page = (await call("GET", "/api/v1/chats", 200, alice.token)).json; check( page.items.length === 0 && page.next_cursor === null, "Failed composite create left a chat", ); const chat = ( await call("POST", "/api/v1/chats", 201, alice.token, { title: "Пагинация", member_ids: [bob.id, alice.id], }) ).json; const path = "/api/v1/chats/" + chat.id + "/messages"; check( (await call("GET", path, 200, alice.token)).json.items.length === 0, "Empty page", ); for (const limit of ["0", "-1", "101", "1.2", "abc"]) await call("GET", path + "?limit=" + limit, 400, alice.token); await call("GET", path + "?cursor=%%%", 400, alice.token); await call("GET", path, 404, eve.token); const sent = []; for (let i = 0; i < 102; i++) { const h = lab >= 3 ? { "Idempotency-Key": crypto.randomUUID() } : {}; sent.push( ( await call( "POST", path, 201, alice.token, { text: `Сообщение ${i}` }, h, ) ).json, ); } check( (await call("GET", path, 200, bob.token)).json.items.length === 50, "Default bound", ); check( (await call("GET", path + "?limit=100", 200, bob.token)).json.items .length === 100, "Maximum bound", ); const seen = []; let cursor: string | null = null; do { page = ( await call( "GET", path + "?limit=7" + (cursor ? "&cursor=" + encodeURIComponent(cursor) : ""), 200, bob.token, ) ).json; check(page.items.length <= 7, "Page bound"); seen.push(...page.items); cursor = page.next_cursor; } while (cursor); check( JSON.stringify(seen) === JSON.stringify(sent), "Traversal must preserve every item exactly once", ); const other = ( await call("POST", "/api/v1/chats", 201, alice.token, { title: "Другой", member_ids: [alice.id], }) ).json; const first = (await call("GET", path + "?limit=1", 200, alice.token)).json; await call( "GET", "/api/v1/chats/" + other.id + "/messages?cursor=" + encodeURIComponent(first.next_cursor), 400, alice.token, ); if (lab >= 3) { const key = crypto.randomUUID(), headers = { "Idempotency-Key": key }, body = { text: "один конкурентный результат" }; const results = await Promise.all( Array.from({ length: 12 }, () => call("POST", path, 201, alice.token, body, headers), ), ); check( new Set(results.map((r) => r.json.id)).size === 1, "Concurrent retries duplicated a message", ); await call("POST", path, 409, alice.token, { text: "другой" }, headers); await call("POST", path, 400, alice.token, { text: "без ключа" }); const ids = new Set(); for (let i = 0; i < 20; i++) ids.add( ( await call("GET", "/api/v1/users/me", 200, alice.token) ).response.headers.get("X-Instance-Id")!, ); check( ids.size >= 2 && !ids.has(null as any), "One session must reach multiple actual replicas", ); } await call("DELETE", "/api/v1/auth/sessions/current", 204, alice.token); await call("GET", "/api/v1/users/me", 401, alice.token); if (process.env.FAILURES === "1") { async function compose(args: string[], ttl?: string) { const p = Bun.spawn([resolve(root, "scripts/compose.sh"), ...args], { cwd: root, env: { ...process.env, ...(ttl ? { SESSION_TTL_SECONDS: ttl } : {}) }, stdout: "pipe", stderr: "pipe", }); await Promise.all([ new Response(p.stdout).text(), new Response(p.stderr).text(), ]); check((await p.exited) === 0, "Compose failure action failed"); } async function ready() { for (let i = 0; i < 150; i++) { try { const r = await fetch(base + "/health/ready", { signal: AbortSignal.timeout(1500), }); await r.arrayBuffer(); if (r.status === 200) return; } catch {} await Bun.sleep(100); } throw new Error("Readiness did not recover"); } try { await compose(["stop", "valkey"]); await call("GET", "/api/v1/users/me", 200, bob.token); await call("GET", "/api/v1/users/me", 401, undefined, undefined, { "X-User-Id": bob.id, }); } finally { await compose(["start", "valkey"]); } try { await compose(["stop", "postgres"]); await call("GET", "/api/v1/users/me", 503, bob.token); await call("GET", "/health/ready", 503); await call("GET", "/health/live", 200); } finally { await compose(["start", "postgres"]); await ready(); } await call("GET", "/api/v1/users/me", 200, bob.token); if (lab === 2) { try { await compose( ["up", "-d", "--no-deps", "--force-recreate", "api"], "2", ); await ready(); const short = await user("ttl"); await call("GET", "/api/v1/users/me", 200, short.token); await Bun.sleep(2200); await call("GET", "/api/v1/users/me", 401, short.token); } finally { await compose( ["up", "-d", "--no-deps", "--force-recreate", "api"], "3600", ); await ready(); } } } } catch (error) { primary = new Error("Acceptance failed during " + operation, { cause: error, }); } try { await cleanup(); } catch (error) { console.error(String(error)); if (!primary) primary = error; } if (primary) throw primary; console.log( `PASS lab${lab}: ${assertions} HTTP assertions, registration race, rollback, pagination, authentication${lab >= 3 ? ", concurrent idempotency and replica sharing" : ""}; fixture cleanup completed`, );