- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/fake-server.ts?format=json
781 linesFirst import 94% · pinch 4% · candidates 2% · review 1% · rename 1% · whytrail 1%Last change pinch in version 280, 10 versions changed it
1// A local stand-in for the avcs Worker, for testing the client. The project
2// logic is the real engine (worker/project/project.ts, in memory) with the
3// Worker's own blame, why and where; only the HTTP routing (as in
4// worker/project/http.ts) and the box are local. `run` unpacks the folder into a
5// temp folder and runs the command there.
6//
7// Run it on its own to point a real folder at it:
8// node client/test/fake-server.ts [port]
10import { spawn, spawnSync } from "node:child_process";
11import { createHash } from "node:crypto";
12import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
14import type { AddressInfo } from "node:net";
15import { tmpdir } from "node:os";
16import { dirname, join } from "node:path";
17import { gunzipSync } from "node:zlib";
18import { blame, why } from "../../worker/project/blame.ts";
19import { readerAnswer, statusWithReaders } from "../../worker/project/http.ts";
20import { MemoryStore, Project } from "../../worker/project/project.ts";
21import { type Candidate, type CheckResult, queueRound } from "../../worker/project/queue-driver.ts";
22import { where } from "../../worker/project/where.ts";
23import { globTest } from "../src/at.ts";
24import { tarGz } from "../src/tar.ts";
26/** Exit codes from 0xC0000000 up are Windows exceptions (0xC0000005: an access violation): the process crashed. */
27const WINDOWS_CRASH = 0xc0000000;
29interface Hosted {
30 readonly project: Project;
31 readonly store: MemoryStore;
32 /** Every edit and record body, by agent, for tests. */
33 readonly calls: Map<string, { action: string; body: unknown }[]>;
34 box: string | undefined;
35 /** Runs by id: their output so far, the exit line once known, and who is listening. */
36 readonly runs: Map<string, Run>;
37 /** Binary files' bytes by sha256, as the Worker's blob store keeps them. */
38 readonly blobs: Map<string, Buffer>;
39 /** Agents that read and never record (#37), kept outside the log as the Worker keeps them. */
40 readers?: Set<string>;
41 /** CI (#39), as a test sets it: status's ci, each shared version's log mark, and the jobs GET /ci?version=N answers. */
42 ci?: FakeCi;
43 /** The merge queue (#39): the last round, and whether one is running. */
44 queueLast?: Record<string, unknown> | null;
45 queueBusy?: boolean;
46}
48export interface FakeCi {
49 status: Record<string, unknown>;
50 marks: Map<number, string>;
51 jobs: Map<number, Record<string, unknown>>;
52}
54interface Run {
55 /** The output so far; `at` offsets count its bytes, as the Worker's do. */
56 out: Buffer;
57 /** The stderr so far, when the run keeps it apart (?stderr=split); `errAt` counts its bytes. */
58 err: Buffer;
59 readonly split: boolean;
60 end: string | undefined;
61 readonly listeners: Set<(line: string) => void>;
62}
64export interface Fake {
65 readonly url: string;
66 readonly projects: Map<string, Hosted>;
67 /** The token every request must carry, as the Worker's AVCS_TOKEN. */
68 readonly token: string;
69 /** Added to every answer, to stand in for the network. */
70 delayMs: number;
71 /** How many of the next run streams (the POST or a reattach) to cut after their first output line, as a dropped connection. */
72 cutRunStreams: number;
73 /** How a cut stream ends: dropped, or with the Worker's {"error", "retry": true} (as a deploy ends one). */
74 cutRunAs: "drop" | "retry";
75 /** How many of the next run POSTs to drop before answering (ECONNRESET / "other side closed"); no run starts. */
76 dropRunStarts: number;
77 /** How the dropped ones end: the connection cut, or a 502 with no run id (as Cloudflare answers when the Worker fails). */
78 dropRunAs: "reset" | 502;
79 /**
80 * Paths the next sync answer carries on top of the engine's, as a server
81 * that lets anything through would (the engine refuses them since 03a44da).
82 */
83 injectSync:
84 | { files?: Record<string, string | null>; modes?: Record<string, { exec?: boolean; link?: string | null }> }
85 | undefined;
86 /** Entries box-files adds to its answer, as a box holding hostile paths or links would. */
87 boxExtra: { path: string; data: Uint8Array; link?: string }[] | undefined;
88 /** While true, the merge queue runs no rounds (a test holds a publish in the queue). */
89 queueHold: boolean;
90 /** The next publish: commit it and answer 500 ('after'), or answer 500 without it ('before'), as a storage reset does. */
91 failPublish: "after" | "before" | undefined;
92 /** How many of the next pulls to carry out and then cut before answering, as an answer that never arrives (abso-core 26). */
93 loseSyncAnswers: number;
94 /** Run the merge queue's rounds now (after queueHold is let go). */
95 kickQueue(name: string): Promise<void>;
96 /** Each run POST's X-Abso-Run-Key, and whether a run started for it. */
97 runStarts: { key: string | undefined; started: boolean; cmd: string; kind?: string }[];
98 close(): Promise<void>;
99}
101const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
103function isLocal(path: string): boolean {
104 return [".abso", ".avcs"].some((d) => path === d || path.startsWith(`${d}/`) || path.startsWith(`./${d}/`));
105}
107async function readBody(req: IncomingMessage): Promise<Buffer> {
108 const chunks: Buffer[] = [];
109 for await (const chunk of req) chunks.push(chunk as Buffer);
110 return Buffer.concat(chunks);
111}
113function send(res: ServerResponse, status: number, body: unknown): void {
114 res.writeHead(status, { "content-type": "application/json" });
115 res.end(JSON.stringify(body));
116}
118/** Read a ustar archive (with pax path records) into path -> bytes. */
119export function untar(data: Uint8Array): Map<string, Uint8Array> {
120 const out = new Map<string, Uint8Array>();
121 const text = (from: number, len: number): string =>
122 new TextDecoder().decode(data.subarray(from, from + len)).replace(/\0.*$/s, "");
123 let at = 0;
124 let paxPath: string | undefined;
125 while (at + 512 <= data.length) {
126 if (data.subarray(at, at + 512).every((b) => b === 0)) break;
127 const name = text(at, 100);
128 const size = parseInt(text(at + 124, 12).trim() || "0", 8);
129 const type = text(at + 156, 1);
130 const prefix = text(at + 345, 155);
131 const body = data.subarray(at + 512, at + 512 + size);
132 at += 512 + Math.ceil(size / 512) * 512;
133 if (type === "x") {
134 const m = /\d+ path=([^\n]*)\n/.exec(new TextDecoder().decode(body));
135 paxPath = m?.[1];
136 continue;
137 }
138 if (type === "0" || type === "") out.set(paxPath ?? (prefix ? `${prefix}/${name}` : name), body);
139 paxPath = undefined;
140 }
141 return out;
142}
144export async function startFake(port = 0, token = "fake-token"): Promise<Fake> {
145 const projects = new Map<string, Hosted>();
146 const fake: Fake = {
147 url: "",
148 projects,
149 token,
150 delayMs: 0,
151 cutRunStreams: 0,
152 cutRunAs: "drop",
153 dropRunStarts: 0,
154 dropRunAs: "reset",
155 runStarts: [],
156 injectSync: undefined,
157 boxExtra: undefined,
158 queueHold: false,
159 failPublish: undefined,
160 loseSyncAnswers: 0,
161 kickQueue: async () => {},
162 close: async () => {},
163 };
165 /** The queue's check, as the Worker's CI box runs it: the candidate's avcs.json build and check, in a folder of its files. */
166 const queueCheck = async (c: Candidate): Promise<CheckResult> => {
167 const dir = mkdtempSync(join(tmpdir(), "avcs-fake-queue-"));
168 try {
169 for (const [path, text] of Object.entries(c.files)) {
170 mkdirSync(dirname(join(dir, path)), { recursive: true });
171 writeFileSync(join(dir, path), text);
172 }
173 const cfg = JSON.parse(c.files["avcs.json"] ?? "{}") as { build?: string; check?: string };
174 const cmd = [cfg.build, cfg.check].filter((s) => typeof s === "string" && s !== "").join(" && ");
175 if (cmd === "") return { kind: "fail", output: "the merge queue needs a check (or a build) in avcs.json" };
176 let r = spawnSync(cmd, { cwd: dir, shell: true, encoding: "utf8" });
177 // As for box runs: a Windows crash at start, with nothing printed, runs once more.
178 if ((r.status ?? 0) >= WINDOWS_CRASH && `${r.stdout ?? ""}${r.stderr ?? ""}` === "")
179 r = spawnSync(cmd, { cwd: dir, shell: true, encoding: "utf8" });
180 return r.status === 0 ? { kind: "pass" } : { kind: "fail", output: `${r.stdout ?? ""}${r.stderr ?? ""}` };
181 } finally {
182 rmSync(dir, { recursive: true, force: true });
183 }
184 };
185 /** Rounds until the queue is empty, one at a time, as the Worker's object runs them. */
186 fake.kickQueue = async (name: string): Promise<void> => {
187 const hosted = projects.get(name);
188 if (!hosted || hosted.queueBusy || fake.queueHold) return;
189 hosted.queueBusy = true;
190 try {
191 while (hosted.project.queue().items.length > 0 && !fake.queueHold) {
192 const round = await queueRound(hosted.project, { check: queueCheck });
193 hosted.queueLast = { ...round, at: new Date().toISOString() };
194 if (round.kind !== "landed" && round.kind !== "pulled") break;
195 }
196 } finally {
197 hosted.queueBusy = false;
198 }
199 };
200 const queueState = (hosted: Hosted) => ({
201 items: hosted.project.queue().items,
202 checking: hosted.queueBusy ?? false,
203 paused: null,
204 last: hosted.queueLast ?? null,
205 });
206 let runs = 0;
207 // Blobs come before init (init names them), so they wait here until the project exists.
208 const waiting = new Map<string, Map<string, Buffer>>();
209 const pendingBlobs = (name: string): Map<string, Buffer> => {
210 let m = waiting.get(name);
211 if (!m) waiting.set(name, (m = new Map()));
212 return m;
213 };
215 const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
216 const url = new URL(req.url ?? "/", "http://fake");
217 if (req.headers.authorization !== `Bearer ${token}`) return send(res, 401, { error: "missing or wrong token" });
218 const blob = /^\/p\/([^/]+)\/blobs\/([0-9a-f]{64})$/.exec(url.pathname);
219 if (blob) {
220 const store = projects.get(decodeURIComponent(blob[1]!))?.blobs ?? pendingBlobs(decodeURIComponent(blob[1]!));
221 const sha = blob[2]!;
222 if (req.method === "PUT") {
223 const bytes = await readBody(req);
224 if (createHash("sha256").update(bytes).digest("hex") !== sha)
225 return send(res, 400, { error: "the bytes do not match the hash" });
226 const stored = !store.has(sha);
227 store.set(sha, bytes);
228 return send(res, 200, { sha, stored });
229 }
230 const bytes = store.get(sha);
231 if (!bytes) return send(res, 404, { error: "no such blob" });
232 res.writeHead(200, { "content-type": "application/octet-stream" });
233 res.end(bytes);
234 return;
235 }
236 const boxFiles = /^\/p\/([^/]+)\/a\/([^/]+)\/box-files$/.exec(url.pathname);
237 if (boxFiles) {
238 // As the Worker answers it, from the fake box: a tar.gz of the matching files under it.
239 const box = projects.get(decodeURIComponent(boxFiles[1]!))?.box;
240 const glob = url.searchParams.get("glob") ?? "";
241 if (glob.split("/").includes("..") || glob.startsWith("/"))
242 return send(res, 400, { error: "no .. or absolute paths" });
243 const pick = globTest(glob);
244 const list = (dir: string, prefix: string): string[] =>
245 readdirSync(join(box!, dir), { withFileTypes: true }).flatMap((e) => {
246 const rel = prefix === "" ? e.name : `${prefix}/${e.name}`;
247 return e.isDirectory() ? list(join(dir, e.name), rel) : [rel];
248 });
249 const files = box === undefined ? [] : list("", "").filter(pick);
250 if (files.length === 0) return send(res, 404, { error: `nothing in the box matches ${glob}` });
251 const extra = fake.boxExtra ?? [];
252 const gz = tarGz([
253 ...files.map((rel) => ({ path: rel, data: readFileSync(join(box!, ...rel.split("/"))) })),
254 ...extra,
255 ]);
256 res.writeHead(200, { "content-type": "application/gzip", "x-abso-files": String(files.length) });
257 res.end(Buffer.from(gz));
258 return;
259 }
260 const reattach = /^\/p\/([^/]+)\/a\/([^/]+)\/run\/([^/]+)$/.exec(url.pathname);
261 if (reattach) {
262 const run = projects.get(decodeURIComponent(reattach[1]!))?.runs.get(decodeURIComponent(reattach[3]!));
263 if (!run) return send(res, 404, { error: "no such run; it ended long ago, or another run replaced it" });
264 res.writeHead(200, { "content-type": "application/x-ndjson" });
265 const from = Number(url.searchParams.get("from") ?? 0);
266 const errFrom = Number(url.searchParams.get("errFrom") ?? 0);
267 res.write(`${JSON.stringify({ run: reattach[3], ...(run.split ? { stderr: "split" } : {}) })}\n`);
268 const listen = streamRun(res, run);
269 if (run.out.length > from)
270 listen(`${JSON.stringify({ out: run.out.subarray(from).toString("utf8"), at: run.out.length })}\n`);
271 if (run.split && run.err.length > errFrom)
272 listen(`${JSON.stringify({ err: run.err.subarray(errFrom).toString("utf8"), errAt: run.err.length })}\n`);
273 if (run.end !== undefined) listen(run.end);
274 return;
275 }
276 const m =
277 /^\/p\/([^/]+)\/(init|status|queue|change\/\d+|changes|notes|ci\/revoke|ci|blame|why|where|labels|files|diff|log|show|file|compare|without|a\/([^/]+)\/(edit|record|publish|sync|run|draft|land|draft-sync|diff|restore|announce|news|starting|reader|drop|pluck|amend|label|files|unqueue|note|note-close|move))$/.exec(
278 url.pathname,
279 );
280 if (!m) return send(res, 404, { error: "no such route; see docs/v2-slice1.md" });
281 const name = decodeURIComponent(m[1]!);
282 const agent = m[3] === undefined ? undefined : decodeURIComponent(m[3]);
283 const op = m[4] ?? m[2]!;
284 const raw = await readBody(req);
285 if (fake.delayMs > 0) await new Promise((r) => setTimeout(r, fake.delayMs));
287 let hosted = projects.get(name);
288 if (op === "init") {
289 const {
290 files,
291 modes,
292 blobs: initBlobs,
293 } = JSON.parse(raw.toString("utf8") || "{}") as {
294 files?: Record<string, string>;
295 modes?: Parameters<Project["init"]>[2];
296 blobs?: Record<string, string>;
297 };
298 if (!files || typeof files !== "object") return send(res, 400, { error: "init needs {files: {path: text}}" });
299 if (hosted) return send(res, 409, { error: "the project already exists" });
300 const bad = Object.keys(files).find(isLocal);
301 if (bad) return send(res, 400, { error: `${bad} is under .abso/, which stays in the agent's folder` });
302 const store = new MemoryStore();
303 const blobs = pendingBlobs(name);
304 waiting.delete(name);
305 // Files kept whole (#46) go to the blob store, as the Worker's do.
306 const whole = {
307 keep: (text: string): string => {
308 const bytes = Buffer.from(text, "utf8");
309 const sha = createHash("sha256").update(bytes).digest("hex");
310 blobs.set(sha, bytes);
311 return sha;
312 },
313 read: (sha: string): string | null => blobs.get(sha)?.toString("utf8") ?? null,
314 };
315 hosted = {
316 project: new Project(store, { hasBlob: (sha) => blobs.has(sha), whole }),
317 store,
318 calls: new Map(),
319 box: undefined,
320 runs: new Map(),
321 blobs,
322 };
323 // As the Worker with a checker: "queue": true in avcs.json turns the merge queue on (#39).
324 hosted.project.checkerReady = true;
325 projects.set(name, hosted);
326 return send(res, 200, hosted.project.init(files, Date.now(), modes, initBlobs ?? {}));
327 }
328 if (!hosted) return send(res, 404, { error: "no such project; run init first" });
329 // Readers (#37), with the Worker's rules; like the Worker, kept outside the log.
330 const readerList = (hosted.readers ??= new Set<string>());
331 const readers = {
332 has: (a: string) => readerList.has(a),
333 set: (a: string, on: boolean) => void (on ? readerList.add(a) : readerList.delete(a)),
334 list: () => [...readerList].sort(),
335 };
336 if (op === "status") {
337 const queue = hosted.project.queue().items.length > 0 ? { queue: queueState(hosted) } : {};
338 return send(res, 200, {
339 ...(statusWithReaders(hosted.project.status(), readers) as object),
340 ...(hosted.ci ? { ci: hosted.ci.status } : {}),
341 ...queue,
342 });
343 }
344 if (op === "queue") return send(res, 200, queueState(hosted));
345 // Changes and notes (#44), as the Worker routes them.
346 if (op === "changes" || op.startsWith("change/") || op === "notes") {
347 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
348 try {
349 if (op === "changes")
350 return send(
351 res,
352 200,
353 hosted.project.changes(
354 q.since ? Number(q.since) : 0,
355 q.limit ? Number(q.limit) : 50,
356 q.before ? Number(q.before) : undefined,
357 ),
358 );
359 if (op === "notes")
360 return send(
361 res,
362 200,
363 hosted.project.notes({
364 ...(q.file ? { file: q.file } : {}),
365 ...(q.change ? { change: Number(q.change) } : {}),
366 ...(q.open ? { open: true } : {}),
367 }),
368 );
369 return send(res, 200, hosted.project.change(Number(op.slice("change/".length))));
370 } catch (e) {
371 const code = (e as { code?: string }).code;
372 return send(res, code === "not-found" ? 404 : 400, { error: e instanceof Error ? e.message : String(e) });
373 }
374 }
375 if (op === "ci" || op === "ci/revoke") {
376 if (!hosted.ci) return send(res, 404, { error: "no such route; see docs/v2-slice1.md" });
377 if (op === "ci/revoke") {
378 const latest = hosted.ci.status.latest as { version: number; url?: string } | null;
379 if (latest?.url)
380 hosted.ci.status = {
381 ...hosted.ci.status,
382 latest: { ...latest, url: `${latest.url.replace(/\/g\d+\/$/, "")}/g${Date.now()}/` },
383 };
384 return send(res, 200, hosted.ci.status);
385 }
386 const v = url.searchParams.get("version");
387 if (v === null) return send(res, 200, hosted.ci.status);
388 // As the Worker: a version without a job of its own is running, waiting, or not checked.
389 const mark = hosted.ci.marks.get(Number(v));
390 return send(
391 res,
392 200,
393 hosted.ci.jobs.get(Number(v)) ?? {
394 version: Number(v),
395 result: mark === "running" || mark === "waiting" ? mark : "not checked",
396 },
397 );
398 }
399 if (agent !== undefined) {
400 const gated = readerAnswer(
401 hosted.project,
402 op,
403 agent,
404 op === "reader" ? JSON.parse(raw.toString("utf8") || "{}") : undefined,
405 readers,
406 );
407 if (gated) return send(res, gated.status, gated.body);
408 }
409 if (op === "where") return send(res, 200, where(hosted.project));
410 if (op === "labels") return send(res, 200, hosted.project.labels());
411 if (op === "diff" && agent === undefined) {
412 // Another agent's draft, read only (abso diff --agent), as the Worker answers GET /p/:project/diff?agent=.
413 const of = url.searchParams.get("agent");
414 if (!of) return send(res, 400, { error: "diff needs ?agent=<name>" });
415 try {
416 return send(res, 200, hosted.project.diffOf(of));
417 } catch (e) {
418 const code = (e as { code?: string }).code;
419 return send(res, code === "not-found" ? 404 : 500, { error: e instanceof Error ? e.message : String(e) });
420 }
421 }
422 if (op === "files" && agent === undefined) {
423 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
424 try {
425 return send(res, 200, hosted.project.pathsAt(q.version ? Number(q.version) : undefined, q.draft || null));
426 } catch (e) {
427 return send(res, 400, { error: e instanceof Error ? e.message : String(e) });
428 }
429 }
430 if (op === "blame" || op === "why") {
431 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
432 if (!q.file) return send(res, 400, { error: `${op} needs ?file=<path>` });
433 const num = (s: string | undefined) => (s === undefined || s === "" ? undefined : Number(s));
434 try {
435 const view = { draft: q.draft || undefined, agent: q.agent || undefined };
436 if (op === "blame")
437 return send(res, 200, blame(hosted.project, q.file, num(q.from), num(q.to), num(q.version), view));
438 const line = num(q.line);
439 if (!line || !Number.isInteger(line)) return send(res, 400, { error: "why needs ?line=<number>" });
440 return send(res, 200, why(hosted.project, q.file, line, { ...view, version: num(q.version) }));
441 } catch (e) {
442 const code = (e as { code?: string }).code;
443 return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
444 }
445 }
446 if (op === "without") {
447 // GET ?version=<n>&versions=<n,n>, as worker/project/http.ts routes it.
448 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
449 try {
450 return send(
451 res,
452 200,
453 hosted.project.without(Number(q.version), (q.versions ?? "").split(",").filter(Boolean).map(Number)),
454 );
455 } catch (e) {
456 const code = (e as { code?: string }).code;
457 return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
458 }
459 }
460 if (op === "log" || op === "show" || op === "file" || op === "compare") {
461 // As the Worker routes them: ?draft=<name>, shared when absent.
462 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
463 const draft = q.draft ? q.draft : null;
464 const agentSpace = q.agent ? { agent: q.agent } : {};
465 const int = (s: string | undefined): number | undefined =>
466 s !== undefined && s !== "" && Number.isInteger(Number(s)) ? Number(s) : undefined;
467 try {
468 if (op === "log") {
469 const log = hosted.project.log({ draft, ...agentSpace, limit: int(q.limit), path: q.path || undefined });
470 // Shared's versions only, by what the answer is (an agent may be in a named draft).
471 const ci = hosted.ci;
472 if (!ci || log.draft !== null) return send(res, 200, log);
473 return send(res, 200, {
474 ...log,
475 versions: log.versions.map((v) => ({ ...v, ci: ci.marks.get(v.version) ?? "not checked" })),
476 });
477 }
478 if (op === "file") {
479 const version = int(q.version);
480 if (!q.path || version === undefined)
481 return send(res, 400, { error: "file needs ?path=<path>&version=<number>" });
482 return send(res, 200, hosted.project.fileAt(q.path, version, { draft, ...agentSpace }));
483 }
484 if (op === "compare") {
485 const from = int(q.from);
486 const to = int(q.to);
487 if (from === undefined || to === undefined)
488 return send(res, 400, { error: "compare needs ?from=<number>&to=<number>" });
489 return send(res, 200, hosted.project.compare(from, to, { draft, ...agentSpace }));
490 }
491 const version = int(q.version);
492 if (version === undefined) return send(res, 400, { error: "show needs ?version=<number>" });
493 return send(res, 200, hosted.project.show(version, { draft, ...agentSpace }));
494 } catch (e) {
495 const code = (e as { code?: string }).code;
496 return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
497 }
498 }
499 if (agent === undefined || !NAME.test(agent))
500 return send(res, 400, { error: "agent names use letters, digits, '.', '_' and '-'" });
501 if (op === "run") {
502 const key = req.headers["x-abso-run-key"];
503 const dropped = fake.dropRunStarts > 0;
504 fake.runStarts.push({
505 key: typeof key === "string" ? key : undefined,
506 started: !dropped,
507 cmd: url.searchParams.get("cmd") ?? "",
508 kind: String(req.headers["x-abso-kind"] ?? ""),
509 });
510 if (dropped) {
511 fake.dropRunStarts--;
512 if (fake.dropRunAs === 502) return send(res, 502, { error: "bad gateway" });
513 res.socket?.destroy();
514 return;
515 }
516 return runInBox(hosted, url.searchParams.get("cmd") ?? "", raw, res, url.searchParams.get("stderr") === "split");
517 }
519 const body = JSON.parse(raw.toString("utf8") || "{}") as Record<string, unknown>;
520 const calls = hosted.calls.get(agent) ?? [];
521 hosted.calls.set(agent, calls);
522 calls.push({ action: op, body });
523 const project = hosted.project;
524 try {
525 if (op === "edit") {
526 if (typeof body.file !== "string")
527 return send(res, 400, { error: "edit needs {file, old, new}, {file, content} or {file, edits}" });
528 if (isLocal(body.file))
529 return send(res, 400, { error: `${body.file} is under .abso/, which stays in the agent's folder` });
530 return send(res, 200, project.edit(agent, body as unknown as Parameters<Project["edit"]>[1], Date.now()));
531 }
532 if (op === "record") {
533 const files = body.files as Record<string, string | null> | undefined;
534 if (!files || typeof files !== "object")
535 return send(res, 400, { error: "record needs {files: {path: text or null}}" });
536 const bad = Object.keys(files).find(isLocal);
537 if (bad) return send(res, 400, { error: `${bad} is under .abso/, which stays in the agent's folder` });
538 const meta = {
539 ...(typeof body.session === "string" ? { session: body.session } : {}),
540 ...(typeof body.subagent === "string" ? { subagent: body.subagent } : {}),
541 };
542 return send(
543 res,
544 200,
545 project.record(
546 agent,
547 files,
548 Date.now(),
549 body.modes as Parameters<Project["record"]>[3],
550 body.blobs as Record<string, string> | undefined,
551 meta,
552 ),
553 );
554 }
555 if (op === "publish") {
556 const message = body.message;
557 if (typeof message !== "string" || !message.trim())
558 return send(res, 400, { error: "push needs {message} saying why" });
559 const fail = fake.failPublish;
560 fake.failPublish = undefined;
561 const storageReset = { error: "Internal error in Durable Object storage caused object to be reset." };
562 if (fail === "before") return send(res, 500, storageReset);
563 const answer = project.publish(agent, message, Date.now(), { asIs: body.asIs === true });
564 if (fail === "after") return send(res, 500, storageReset);
565 // A queued publish wakes the queue, as the Worker's object does.
566 if ((answer as { queued?: number }).queued !== undefined) setTimeout(() => void fake.kickQueue(name), 0);
567 return send(res, 200, answer);
568 }
569 if (op === "note") return send(res, 200, project.note(agent, body, Date.now()));
570 if (op === "move") return send(res, 200, project.move(agent, body.from as string, body.to as string, Date.now()));
571 if (op === "note-close") return send(res, 200, project.closeNote(agent, body.id as number, body.how, Date.now()));
572 if (op === "unqueue") {
573 return send(res, 200, project.unqueue(agent, Date.now()));
574 }
575 if (op === "draft") {
576 const name = body.name;
577 if (name !== null && typeof name !== "string")
578 return send(res, 400, { error: "draft needs {name}, or {name: null} for shared" });
579 return send(res, 200, project.switchTo(agent, name, Date.now(), { carry: body.carry === true }));
580 }
581 if (op === "land") {
582 const message = body.message;
583 if (typeof message !== "string" || !message.trim())
584 return send(res, 400, { error: "land needs {message} saying why" });
585 return send(res, 200, project.land(agent, message, Date.now()));
586 }
587 if (op === "draft-sync") return send(res, 200, project.syncDraft(agent, Date.now()));
588 if (op === "files") return send(res, 200, project.agentPaths(agent));
589 if (op === "diff") return send(res, 200, project.diff(agent));
590 if (op === "starting")
591 return send(
592 res,
593 200,
594 project.starting(agent, body.text as string | null, body.files as string[] | undefined, Date.now()),
595 );
596 if (op === "announce")
597 return send(
598 res,
599 200,
600 project.announce(agent, body.text as string, body.to as string[] | undefined, Date.now()),
601 );
602 if (op === "news") return send(res, 200, project.news(agent));
603 if (op === "restore") {
604 if (body.all === true) return send(res, 200, project.restore(agent, null, Date.now()));
605 if (!Array.isArray(body.files) || !body.files.every((f) => typeof f === "string"))
606 return send(res, 400, { error: "restore needs {files: [path]} or {all: true}" });
607 return send(res, 200, project.restore(agent, body.files as string[], Date.now()));
608 }
609 if (op === "drop")
610 return send(
611 res,
612 200,
613 project.drop(agent, body.versions as number[], body.message as string, Date.now(), {
614 withDependents: body.withDependents === true,
615 }),
616 );
617 if (op === "pluck")
618 return send(
619 res,
620 200,
621 project.pluck(agent, body.draft as string, body.versions as number[], body.message as string, Date.now(), {
622 withDependencies: body.withDependencies === true,
623 }),
624 );
625 if (op === "amend") return send(res, 200, project.amend(agent, body.message as string, Date.now()));
626 if (op === "label")
627 return send(
628 res,
629 200,
630 project.label(agent, body.name as string, body.version as number | undefined, Date.now(), {
631 remove: body.remove === true,
632 }),
633 );
634 const synced = project.sync(agent, {
635 ...(typeof body.label === "string" ? { label: body.label } : {}),
636 ...(body.full === true ? { full: true } : {}),
637 });
638 if (fake.loseSyncAnswers > 0) {
639 fake.loseSyncAnswers--;
640 res.destroy();
641 return;
642 }
643 const extra = fake.injectSync;
644 fake.injectSync = undefined;
645 if (extra === undefined) return send(res, 200, synced);
646 return send(res, 200, {
647 ...synced,
648 files: { ...synced.files, ...extra.files },
649 modes: { ...synced.modes, ...extra.modes },
650 });
651 } catch (e) {
652 const code = (e as { code?: string }).code;
653 const status =
654 code === "not-initialized" || code === "not-found"
655 ? 404
656 : code === "already-initialized" || code === "conflict"
657 ? 409
658 : code === "bad-request" || code === "bad-agent"
659 ? 400
660 : 500;
661 return send(res, status, { error: e instanceof Error ? e.message : String(e) });
662 }
663 };
665 /** Unpack the folder into a temp box (keeping node_modules), run the command, stream ndjson. */
666 const runInBox = (hosted: Hosted, cmd: string, raw: Buffer, res: ServerResponse, split: boolean): void => {
667 if (hosted.box === undefined) hosted.box = mkdtempSync(join(tmpdir(), "avcs-fake-box-"));
668 const box = hosted.box;
669 for (const entry of readdirSync(box))
670 if (entry !== "node_modules") rmSync(join(box, entry), { recursive: true, force: true });
671 for (const [path, data] of untar(gunzipSync(raw))) {
672 const full = join(box, ...path.split("/"));
673 mkdirSync(dirname(full), { recursive: true });
674 writeFileSync(full, data);
675 }
676 // The run lives on without its connection; a reattach streams from where the client got to.
677 const id = `run${++runs}`;
678 const run: Run = { out: Buffer.alloc(0), err: Buffer.alloc(0), split, end: undefined, listeners: new Set() };
679 hosted.runs.clear();
680 hosted.runs.set(id, run);
681 res.writeHead(200, { "content-type": "application/x-ndjson", "x-abso-box": "warm", "x-abso-run": id });
682 res.write(`${JSON.stringify({ run: id, ...(split ? { stderr: "split" } : {}) })}\n`);
683 streamRun(res, run);
684 const emit = (line: string): void => {
685 for (const listen of [...run.listeners]) listen(line);
686 };
687 const out = (chunk: Buffer): void => {
688 run.out = Buffer.concat([run.out, chunk]);
689 emit(`${JSON.stringify({ out: chunk.toString("utf8"), at: run.out.length })}\n`);
690 };
691 const err = (chunk: Buffer): void => {
692 if (!split) return out(chunk);
693 run.err = Buffer.concat([run.err, chunk]);
694 emit(`${JSON.stringify({ err: chunk.toString("utf8"), errAt: run.err.length })}\n`);
695 };
696 child(cmd, box, out, err, (end) => {
697 run.end = end;
698 emit(end);
699 });
700 };
702 const child = (
703 cmd: string,
704 box: string,
705 out: (chunk: Buffer) => void,
706 err: (chunk: Buffer) => void,
707 done: (end: string) => void,
708 ): void => {
709 // The box's sh reads `export A='x'; command`; the shell here may be cmd.exe, so take the stamp into the environment.
710 const stamped = /^export ((?:[A-Z_]+='[^']*' ?)+); ([\s\S]*)$/.exec(cmd);
711 const env = { ...process.env };
712 if (stamped) for (const [, k, v] of stamped[1]!.matchAll(/([A-Z_]+)='([^']*)'/g)) env[k!] = v!;
713 // Node on Windows sometimes crashes as it starts (0xC0000005, about 1 start in 200 on the dev machine,
714 // more when many start at once), which made the box tests flaky. The real box is Linux; a run that
715 // crashed before printing anything is started once more, as a fresh box would run it.
716 const start = (tries: number): void => {
717 let printed = false;
718 const p = spawn(stamped ? stamped[2]! : cmd, { cwd: box, shell: true, env });
719 p.stdout.on("data", (chunk: Buffer) => ((printed = true), out(chunk)));
720 p.stderr.on("data", (chunk: Buffer) => ((printed = true), err(chunk)));
721 p.on("error", (e) => done(`${JSON.stringify({ error: e.message })}\n`));
722 p.on("close", (code) => {
723 if (code !== null && code >= WINDOWS_CRASH && !printed && tries < 2) return start(tries + 1);
724 done(`${JSON.stringify({ exit: code ?? 1 })}\n`);
725 });
726 };
727 start(0);
728 };
730 /** Send a run's lines to one connection until its end line; cut it after its first output when the test asks. */
731 const streamRun = (res: ServerResponse, run: Run): ((line: string) => void) => {
732 const cut = fake.cutRunStreams > 0;
733 if (cut) fake.cutRunStreams--;
734 const listen = (line: string): void => {
735 if (res.destroyed) return;
736 if (line.startsWith('{"out"') || line.startsWith('{"err"')) {
737 if (cut) {
738 // Drop the connection once this line has gone out, as a network that breaks mid-run.
739 run.listeners.delete(listen);
740 if (fake.cutRunAs === "retry")
741 res.end(`${line}${JSON.stringify({ error: "the Worker is restarting (a deploy)", retry: true })}\n`);
742 else res.write(line, () => res.destroy());
743 return;
744 }
745 res.write(line);
746 return;
747 }
748 run.listeners.delete(listen);
749 res.end(line);
750 };
751 run.listeners.add(listen);
752 res.on("close", () => run.listeners.delete(listen));
753 return listen;
754 };
756 const server: Server = createServer((req, res) => {
757 handle(req, res).catch((err: Error) => {
758 if (!res.headersSent) send(res, 500, { error: err.message });
759 else res.end();
760 });
761 });
762 // Never close an idle kept-alive connection: on Windows, under load, the client could reuse one in the moment
763 // the server closed it, and the next call failed with ECONNRESET. close() below drops every connection.
764 server.keepAliveTimeout = 0;
765 await new Promise<void>((ok) => server.listen(port, "127.0.0.1", ok));
766 const address = server.address() as AddressInfo;
767 return Object.assign(fake, {
768 url: `http://127.0.0.1:${address.port}`,
769 close: () =>
770 new Promise<void>((ok) => {
771 server.closeAllConnections();
772 server.close(() => ok());
773 for (const p of projects.values()) if (p.box) rmSync(p.box, { recursive: true, force: true, maxRetries: 5 });
774 }),
775 });
776}
778if (import.meta.main) {
779 const fake = await startFake(Number(process.argv[2] ?? 0), process.env.AVCS_TOKEN ?? "fake-token");
780 console.log(`fake abso server at ${fake.url} (the real engine in memory; token from AVCS_TOKEN, else "fake-token")`);
781}