diff --git a/docs/tasks/T-1200/T-1269-instabox-api-update/brief.md b/docs/tasks/T-1200/T-1269-instabox-api-update/brief.md new file mode 100644 index 00000000..e85492e0 --- /dev/null +++ b/docs/tasks/T-1200/T-1269-instabox-api-update/brief.md @@ -0,0 +1,34 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1269 改接口后启动报 400:建机字段和保持唤醒租约按新接口改 + +## 背景 +线上用户点「启动 」报 `HTTP 400: unknown_field`。接口已更新,建机请求体不再接受未知字段。协调者已用不建机的方式核对过当前接口(接口文档即 的 openapi): + +1. `POST /v1/machines` 请求体不再有 `spec`。CPU 和内存是顶层字段:`vcpus`(整数)、`memMiB`(整数,单位 MiB)。`templateId`、`name`、`autoSuspendAfterSeconds`、`metadata` 仍然支持。请求体禁止额外字段。 +2. 活动租约接口改了: + - 旧:`POST /v1/machines/{id}/activity-leases`,body `{ durationSeconds }` 或 `{ leaseId, durationSeconds }`,服务端返回 id。现在这个路由返回 404 route not found。 + - 新:`PUT /v1/machines/{id}/activity-leases/{leaseID}`,body `{ ttlSeconds }`。leaseID 由客户端自己生成;同一个 PUT 既创建也续期,会先唤醒闲置挂起的机器。不需要 Idempotency-Key。 + - `DELETE /v1/machines/{id}/activity-leases/{leaseID}` 释放,幂等,不变。 +3. 其他调用已核对,仍然兼容,不要改:`POST /v1/machines/{id}/desktop` 的 `{ action, width, height }`、`/start` `/resume` `/suspend`、`/exec`、`/files`、`/snapshots` 的 `{ name, description }`、`/restore` 的 `{ snapshotId, desiredState }`。 + +## 要改 +1. server/instabox/machines.ts 建机请求:把 `spec: { vcpus: 4, memoryGiB: 8 }` 换成顶层 `vcpus: 4, memMiB: 8192`。其他字段不变。 +2. server/instabox/computer-tools.ts 活动租约: + - 获取时由客户端生成 leaseID(例如 `crybot-` 加 randomUUID),调用 `PUT /v1/machines/{machineId}/activity-leases/{encodeURIComponent(leaseID)}`,body `{ ttlSeconds: BACKGROUND_MAX_MS / 1000 }`。响应不 ok 时仍按现在的方式视为失败。 + - 续期用同一个 leaseID 再 PUT 一次,body 相同。 + - 释放保持 DELETE 同一路径。 + - 如果 ttlSeconds 有上限,接口文档没写;保持现有时长即可。 +3. 更新相关测试和假接口夹具(server/instabox 下的 machines、computer-tools、wiring-backends-fixture 等)里断言 `spec`、`memoryGiB`、`POST .../activity-leases`、`durationSeconds` 的地方,改成新格式。再加一条回归断言:建机请求体里没有 `spec`,有 `vcpus: 4` 和 `memMiB: 8192`;租约走 PUT 带 ttlSeconds,续期和释放用同一个 leaseID。 +4. 全仓搜一遍 `memoryGiB`、`spec:`、`activity-leases`、`durationSeconds`,确认没有别的 调用遗漏(Boat、VPS 的同名字段不要动)。 + +## 验收 +- `server/instabox/` 下全部测试通过;改动过的其他测试文件通过。 +- `pnpm exec tsc -p tsconfig.server.json` 通过;改动过的文件跑 `oxlint --deny-warnings`。 +- report.md 和 verification.txt 放在本任务文件夹。verification.txt 只写命令和汇总结果(通过数、失败数),不贴原始输出。不写 IP、地址、域名、uuid、任何密钥。文件名不要用反引号单独包住带 md 后缀的写法。 +- 测试临时目录用 os.tmpdir() 下新建的目录。 diff --git a/docs/tasks/T-1200/T-1269-instabox-api-update/report.md b/docs/tasks/T-1200/T-1269-instabox-api-update/report.md new file mode 100644 index 00000000..5480f292 --- /dev/null +++ b/docs/tasks/T-1200/T-1269-instabox-api-update/report.md @@ -0,0 +1,24 @@ +改了什么: + +- docs/tasks/T-1200/T-1269-instabox-api-update/report.md +- docs/tasks/T-1200/T-1269-instabox-api-update/verification.txt +- server/instabox/computer-tools.e2e.test.ts +- server/instabox/computer-tools.ts +- server/instabox/machines.test.ts +- server/instabox/machines.ts +- server/testing/fake-instabox-core.ts +- server/testing/fake-instabox-tools.ts + +建机改为顶层 vcpus: 4、memMiB: 8192;租约由客户端生成 ID,创建与续期共用 PUT 和 ttlSeconds: 7200,释放使用同一 ID 的 DELETE。夹具严格校验新字段;回归覆盖空响应、共用租约、释放与拒绝后重试。 + +为什么:修复建机旧字段导致的 HTTP 400,以及旧租约路由失效导致的保活失败。全仓搜索已核对,旧格式只留在历史任务文档;wiring-backends-fixture 只模拟 Boat/VPS,无需修改。 + +测试命令与结果摘要: + +- 依赖准备脚本:通过。 +- TMPDIR=/tmp pnpm exec vitest run <测试文件> --maxWorkers=1:逐文件运行,16 个文件共 179 项通过、0 失败、0 跳过;8 个 e2e 最终各连续三轮通过,验收合计 401 项次通过。VNC 验证另外设置 CRYBOT_CDP_CHROME=/usr/bin/chromium,已补齐默认路径未配置时跳过的浏览器用例。 +- pnpm exec tsc -p tsconfig.server.json:通过。 +- pnpm exec oxlint --deny-warnings <上述六个 TypeScript 文件>:最终通过,0 警告;初次发现的夹具请求警告已修复。 +- git diff --check:通过。逐文件命令和计数见 [verification.txt](verification.txt)。 + +验证说明文件 docs/verification/README.md 在当前仓库缺失;实际使用现有隔离 HTTP、服务端和浏览器 fixture。测试临时目录通过 os.tmpdir() 新建,设置 TMPDIR=/tmp 以符合模拟远端路径限制。未提交 git。 diff --git a/docs/tasks/T-1200/T-1269-instabox-api-update/verification.txt b/docs/tasks/T-1200/T-1269-instabox-api-update/verification.txt new file mode 100644 index 00000000..388ad259 --- /dev/null +++ b/docs/tasks/T-1200/T-1269-instabox-api-update/verification.txt @@ -0,0 +1,92 @@ +crybot-link-deps +通过 1,失败 0。 + +pnpm exec vitest run server/instabox/machines.test.ts --maxWorkers=1 +初次:通过 25,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/client.test.ts --maxWorkers=1 +第 1 轮:通过 6,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/computer-tools.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 30,失败 0,跳过 0。 +第 2 轮:通过 30,失败 0,跳过 0。 +第 3 轮:通过 30,失败 0,跳过 0。 + +TMPDIR=/tmp CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/computer-tools.e2e.test.ts --maxWorkers=1 +最终第 1 轮:通过 30,失败 0,跳过 0。 +最终第 2 轮:通过 30,失败 0,跳过 0。 +最终第 3 轮:通过 30,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 15,失败 0,跳过 0。 +第 2 轮:通过 15,失败 0,跳过 0。 +第 3 轮:通过 15,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/deletion.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 7,失败 0,跳过 0。 +第 2 轮:通过 7,失败 0,跳过 0。 +第 3 轮:通过 7,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/key.test.ts --maxWorkers=1 +第 1 轮:通过 4,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/machine-records.test.ts --maxWorkers=1 +第 1 轮:通过 16,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/machines.test.ts --maxWorkers=1 +第 1 轮:通过 25,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/persistence.test.ts --maxWorkers=1 +第 1 轮:通过 1,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/power.test.ts --maxWorkers=1 +第 1 轮:通过 10,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/preview.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 3,失败 0,跳过 0。 +第 2 轮:通过 3,失败 0,跳过 0。 +第 3 轮:通过 3,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/snapshot-conflicts.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 10,失败 0,跳过 0。 +第 2 轮:通过 10,失败 0,跳过 0。 +第 3 轮:通过 10,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/snapshot-wiring.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 6,失败 0,跳过 0。 +第 2 轮:通过 6,失败 0,跳过 0。 +第 3 轮:通过 6,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 31,失败 0,跳过 1。 +第 2 轮:通过 31,失败 0,跳过 1。 +第 3 轮:通过 31,失败 0,跳过 1。 + +TMPDIR=/tmp CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 +最终第 1 轮:通过 32,失败 0,跳过 0。 +最终第 2 轮:通过 32,失败 0,跳过 0。 +最终第 3 轮:通过 32,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/vnc.test.ts --maxWorkers=1 +第 1 轮:通过 2,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/wiring.e2e.test.ts --maxWorkers=1 +第 1 轮:通过 8,失败 0,跳过 0。 +第 2 轮:通过 8,失败 0,跳过 0。 +第 3 轮:通过 8,失败 0,跳过 0。 + +TMPDIR=/tmp pnpm exec vitest run server/instabox/wiring.test.ts --maxWorkers=1 +第 1 轮:通过 4,失败 0,跳过 0。 + +pnpm exec tsc -p tsconfig.server.json +检查 3 次:通过 3,失败 0。 + +pnpm exec oxlint --deny-warnings server/instabox/computer-tools.e2e.test.ts server/instabox/computer-tools.ts server/instabox/machines.test.ts server/instabox/machines.ts server/testing/fake-instabox-core.ts server/testing/fake-instabox-tools.ts +初次:通过 0,失败 1,警告 1。 +修复后检查 3 次:通过 3,失败 0,警告 0。 + +rg -n 'memoryGiB|spec:|activity-leases|durationSeconds' . --glob '!pnpm-lock.yaml' +全仓核对:通过 1,失败 0,遗漏的 InstaBox 调用 0。 + +git diff --check +通过 1,失败 0。 diff --git a/server/instabox/computer-tools.e2e.test.ts b/server/instabox/computer-tools.e2e.test.ts index 10c94ba5..a431bf84 100644 --- a/server/instabox/computer-tools.e2e.test.ts +++ b/server/instabox/computer-tools.e2e.test.ts @@ -34,7 +34,7 @@ const inputCalls = async () => (await readFile(join(root, "input"))).toString(). beforeEach(async () => { root = await mkdtemp(join(tmpdir(), "instabox-tools-fixture-")); - remoteRoot = await mkdtemp(join("/tmp", "instabox-tools-remote-")); + remoteRoot = await mkdtemp(join(tmpdir(), "instabox-tools-remote-")); folder = join(root, "working"); bin = join(root, "bin"); await mkdir(folder); await mkdir(bin); await writeFile(join(root, "image.jpg"), jpeg); @@ -277,25 +277,29 @@ describe("InstaBox tools through an isolated HTTP machine fixture", () => { it("keeps a background job awake with an injected lease and releases it on completion", async () => { const started = json(await runInstaboxComputerTool(fixture.machines, machineId, "exec", { command: "true", background: true }, signal(), folder, fixture.request)); - await runInstaboxComputerTool(fixture.machines, machineId, "exec_status", { process_id: started.processId }, signal(), folder, fixture.request); + const path = fixture.leaseRequests[0].path; + expect(path).toMatch(/^\/v1\/machines\/fixture-machine\/activity-leases\/crybot-[0-9a-f-]{36}$/); + expect(fixture.leaseRequests[0]).toMatchObject({ body: { ttlSeconds: 7200 }, idempotencyKey: undefined }); + await runInstaboxComputerTool(fixture.machines, machineId, "exec_status", { process_id: started.processId, wait_seconds: 3 }, signal(), folder, fixture.request); expect(fixture.leaseRequests.map(request => `${request.method} ${request.path}`)).toEqual([ - "POST /v1/machines/fixture-machine/activity-leases", - "DELETE /v1/machines/fixture-machine/activity-leases/fixture-lease", + `PUT ${path}`, + `DELETE ${path}`, ]); }); it("keeps the lease while a background job is still running", async () => { const started = json(await runInstaboxComputerTool(fixture.machines, machineId, "exec", { command: "sleep 0.5", background: true }, signal(), folder, fixture.request)); + const path = fixture.leaseRequests[0].path; const running = json(await runInstaboxComputerTool(fixture.machines, machineId, "exec_status", { process_id: started.processId }, signal(), folder, fixture.request)); expect(running).toMatchObject({ processId: started.processId, status: "running" }); expect(fixture.leaseRequests.map(request => `${request.method} ${request.path}`)).toEqual([ - "POST /v1/machines/fixture-machine/activity-leases", + `PUT ${path}`, ]); const finished = json(await runInstaboxComputerTool(fixture.machines, machineId, "exec_status", { process_id: started.processId, wait_seconds: 3 }, signal(), folder, fixture.request)); expect(finished).toMatchObject({ processId: started.processId, status: "finished" }); expect(fixture.leaseRequests.map(request => `${request.method} ${request.path}`)).toEqual([ - "POST /v1/machines/fixture-machine/activity-leases", - "DELETE /v1/machines/fixture-machine/activity-leases/fixture-lease", + `PUT ${path}`, + `DELETE ${path}`, ]); }); @@ -304,16 +308,28 @@ describe("InstaBox tools through an isolated HTTP machine fixture", () => { const started: CloudComputerResult[] = []; if (concurrent) started.push(...await Promise.all(Array.from({ length: 5 }, start))); else for (let index = 0; index < 5; index++) started.push(await start()); - expect(fixture.leaseRequests.filter(request => request.method === "POST").map(request => request.body)).toEqual([ - { durationSeconds: 7200 }, - ...Array.from({ length: 4 }, () => ({ leaseId: "fixture-lease", durationSeconds: 7200 })), - ]); + const path = fixture.leaseRequests[0].path; + expect(fixture.leaseRequests).toEqual(Array.from({ length: 5 }, () => ({ method: "PUT", path, body: { ttlSeconds: 7200 }, idempotencyKey: undefined }))); for (const [index, result] of started.entries()) { expect(fixture.leaseRequests.filter(request => request.method === "DELETE")).toHaveLength(0); const status = json(await call("exec_status", { process_id: json(result).processId, wait_seconds: 3 })); expect(status.status).toBe("finished"); expect(fixture.leaseRequests.filter(request => request.method === "DELETE")).toHaveLength(index === 4 ? 1 : 0); } + expect(fixture.leaseRequests.at(-1)).toMatchObject({ method: "DELETE", path }); + }); + + it("discards a rejected lease and acquires a fresh ID for the next job", async () => { + const request = vi.fn(fixture.request).mockResolvedValueOnce(new Response(null, { status: 400 })); + const start = () => runInstaboxComputerTool(fixture.machines, machineId, "exec", { command: "true", background: true }, signal(), folder, request); + const first = json(await start()); + await call("exec_status", { process_id: first.processId, wait_seconds: 3 }); + expect(request).toHaveBeenCalledTimes(1); + const second = json(await start()); + await call("exec_status", { process_id: second.processId, wait_seconds: 3 }); + expect(request.mock.calls.map(([method]) => method)).toEqual(["PUT", "PUT", "DELETE"]); + expect(request.mock.calls[1][1]).not.toBe(request.mock.calls[0][1]); + expect(request.mock.calls[2][1]).toBe(request.mock.calls[1][1]); }); it("covers every advertised tool", () => { diff --git a/server/instabox/computer-tools.ts b/server/instabox/computer-tools.ts index 35b2a16a..e821143e 100644 --- a/server/instabox/computer-tools.ts +++ b/server/instabox/computer-tools.ts @@ -1,4 +1,4 @@ -import { randomBytes } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; import { constants, renameSync, rmSync } from "node:fs"; import { open } from "node:fs/promises"; import { basename, join, posix, relative } from "node:path"; @@ -124,11 +124,19 @@ async function copyFile( const BACKGROUND_ROOT = "/tmp/cry-instabox-background"; type ActivityLease = { - request: InstaboxRequest; machineId: string; id?: string; processes: Set; + request: InstaboxRequest; machineId: string; id: string; processes: Set; pending: Promise; renew?: ReturnType; expiry?: ReturnType; }; const activityLeases = new Map(); +const activityLeasePath = (lease: ActivityLease) => `/v1/machines/${lease.machineId}/activity-leases/${encodeURIComponent(lease.id)}`; + +async function putActivityLease(lease: ActivityLease): Promise { + const response = await lease.request("PUT", activityLeasePath(lease), { body: { ttlSeconds: BACKGROUND_MAX_MS / 1000 } }); + await response.body?.cancel(); + if (!response.ok) throw new Error("Activity lease rejected"); +} + async function releaseActivityLease(machineId: string, processId?: string): Promise { const lease = activityLeases.get(machineId); if (!lease) return; @@ -139,18 +147,12 @@ async function releaseActivityLease(machineId: string, processId?: string): Prom activityLeases.delete(machineId); clearInterval(lease.renew); clearTimeout(lease.expiry); - if (!lease.id) return; - const path = `/v1/machines/${machineId}/activity-leases/${encodeURIComponent(lease.id)}`; - await lease.request("DELETE", path).then(response => response.body?.cancel()).catch(() => {}); + await lease.request("DELETE", activityLeasePath(lease)).then(response => response.body?.cancel()).catch(() => {}); } function renewActivityLease(lease: ActivityLease): Promise { lease.pending = lease.pending.then(async () => { - if (!lease.id) return; - const response = await lease.request("POST", `/v1/machines/${lease.machineId}/activity-leases`, { - body: { leaseId: lease.id, durationSeconds: BACKGROUND_MAX_MS / 1000 }, - }); - await response.body?.cancel(); + if (activityLeases.get(lease.machineId) === lease) await putActivityLease(lease); }).catch(() => {}); return lease.pending; } @@ -164,13 +166,10 @@ async function acquireActivityLease(request: InstaboxRequest | undefined, machin await renewActivityLease(existing); return; } - const lease: ActivityLease = { request, machineId, processes: new Set([processId]), pending: Promise.resolve() }; + const lease: ActivityLease = { request, machineId, id: `crybot-${randomUUID()}`, processes: new Set([processId]), pending: Promise.resolve() }; activityLeases.set(machineId, lease); lease.pending = (async () => { - const response = await request("POST", `/v1/machines/${machineId}/activity-leases`, { body: { durationSeconds: BACKGROUND_MAX_MS / 1000 } }); - if (!response.ok) { await response.body?.cancel(); throw new Error("Activity lease rejected"); } - const body = await response.json().catch(() => null) as { id?: unknown; leaseId?: unknown } | null; - lease.id = typeof body?.id === "string" ? body.id : typeof body?.leaseId === "string" ? body.leaseId : undefined; + await putActivityLease(lease); lease.renew = setInterval(() => { void renewActivityLease(lease); }, 30 * 60_000); lease.expiry = setTimeout(() => { void releaseActivityLease(machineId); }, BACKGROUND_MAX_MS); lease.renew.unref?.(); lease.expiry.unref?.(); diff --git a/server/instabox/machines.test.ts b/server/instabox/machines.test.ts index f11378d4..6112f8b3 100644 --- a/server/instabox/machines.test.ts +++ b/server/instabox/machines.test.ts @@ -10,12 +10,14 @@ const botId = "123456789012-more"; beforeEach(async () => { fake = await fakeInstaboxCore(); service = createInstaboxMachines(createInstaboxRequest("fixture-key", fake.url)); }); afterEach(async () => { await fake.close(); }); -it.each(["linux", "android"] as const)("creates %s with the shared naming/spec contract, waits, then starts desktop", async template => { +it.each(["linux", "android"] as const)("creates %s with top-level CPU and memory fields, waits, then starts desktop", async template => { const machine = await service.ensureRunning(botId, { template }); expect(machine).toMatchObject({ name: "crybot-123456789012", state: "running", template }); - expect(fake.calls.find(call => call.method === "POST" && call.path === "/v1/machines")?.body).toEqual({ + const body = fake.calls.find(call => call.method === "POST" && call.path === "/v1/machines")?.body; + expect(body).not.toHaveProperty("spec"); + expect(body).toEqual({ name: "crybot-123456789012", templateId: template === "linux" ? "agent-browser" : "android", - spec: { vcpus: 4, memoryGiB: 8 }, autoSuspendAfterSeconds: 600, metadata: { app: "crybot", botId }, + vcpus: 4, memMiB: 8192, autoSuspendAfterSeconds: 600, metadata: { app: "crybot", botId }, }); expect(fake.calls.at(-1)?.body).toEqual({ action: "start", width: 1280, height: 800 }); expect(fake.calls.filter(call => call.path.includes("operations"))).toHaveLength(2); diff --git a/server/instabox/machines.ts b/server/instabox/machines.ts index 627fd65f..041431fc 100644 --- a/server/instabox/machines.ts +++ b/server/instabox/machines.ts @@ -67,7 +67,7 @@ export function createInstaboxMachines(request: InstaboxRequest, records?: Retur if (!machine || machine.state === "deleted") { const operation = await lifecycle("POST", "/v1/machines", { body: { name: `crybot-${botId.slice(0, 12)}`, templateId: template === "android" ? "android" : "agent-browser", - spec: { vcpus: 4, memoryGiB: 8 }, autoSuspendAfterSeconds: 600, metadata: { app: "crybot", botId }, + vcpus: 4, memMiB: 8192, autoSuspendAfterSeconds: 600, metadata: { app: "crybot", botId }, } }, botId); machine = await read(operation.machineId); } diff --git a/server/testing/fake-instabox-core.ts b/server/testing/fake-instabox-core.ts index eaefc80e..bf2d4298 100644 --- a/server/testing/fake-instabox-core.ts +++ b/server/testing/fake-instabox-core.ts @@ -61,6 +61,9 @@ export async function fakeInstaboxCore() { }; if (url.pathname === "/v1/machines") { if (req.method === "GET") return send(200, { machines: [...machines.values()] }); + const fields = new Set(["name", "templateId", "vcpus", "memMiB", "autoSuspendAfterSeconds", "metadata"]); + if (Object.keys(body).some(field => !fields.has(field))) return send(400, { error: { code: "unknown_field" } }); + if ([body.vcpus, body.memMiB].some(value => value !== undefined && !Number.isInteger(value))) return send(400, { error: { code: "invalid_resources" } }); const id = `machine-${machines.size + 1}`; machines.set(id, { id, name: body.name, state: "creating", templateId: body.templateId, metadata: body.metadata ?? {} }); return finish(id, "running"); diff --git a/server/testing/fake-instabox-tools.ts b/server/testing/fake-instabox-tools.ts index 2b5ac7e2..0c232933 100644 --- a/server/testing/fake-instabox-tools.ts +++ b/server/testing/fake-instabox-tools.ts @@ -1,7 +1,8 @@ import { createServer } from "node:http"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; -import type { InstaboxExecRequest, InstaboxExecResult, InstaboxMachines, InstaboxRequest } from "../instabox/machine.ts"; +import { createInstaboxRequest } from "../instabox/client.ts"; +import type { InstaboxExecRequest, InstaboxExecResult, InstaboxMachines } from "../instabox/machine.ts"; type Request = { method: string; path: string; machineId: string; exec?: InstaboxExecRequest; data?: Uint8Array; mode?: string }; type Options = { @@ -12,7 +13,7 @@ type Options = { export async function fakeInstaboxTools(options: Options = {}) { const requests: Request[] = []; - const leaseRequests: Array<{ method: string; path: string; body?: unknown }> = []; + const leaseRequests: Array<{ method: string; path: string; body?: unknown; idempotencyKey?: string | string[] }> = []; const files = new Map(); const state = { suspended: false, resumes: 0, hold: false }; const server = createServer(async (req, res) => { @@ -22,6 +23,16 @@ export async function fakeInstaboxTools(options: Options = {}) { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(Buffer.from(chunk)); const bytes = Buffer.concat(chunks); + if (parts[4] === "activity-leases") { + const body = bytes.length ? JSON.parse(bytes.toString()) : undefined; + leaseRequests.push({ method: req.method!, path: url.pathname, body, idempotencyKey: req.headers["idempotency-key"] }); + if (!parts[5] || parts.length !== 6 || !["PUT", "DELETE"].includes(req.method!)) { res.writeHead(404); res.end(); return; } + if (req.method === "PUT") { + if (!body || Object.keys(body).length !== 1 || !Number.isInteger(body.ttlSeconds) || body.ttlSeconds <= 0) { res.writeHead(400); res.end(); return; } + state.suspended = false; + } + res.writeHead(204); res.end(); return; + } const request: Request = { method: req.method!, path: url.searchParams.get("path") ?? url.pathname, machineId: parts[3] }; if (parts[4] === "exec") request.exec = JSON.parse(bytes.toString()) as InstaboxExecRequest; if (req.method === "PUT") { request.data = bytes; request.mode = url.searchParams.get("mode") ?? undefined; } @@ -100,10 +111,7 @@ export async function fakeInstaboxTools(options: Options = {}) { }, vncUpstream: async () => ({ url, headers: {} }), }; - const request: InstaboxRequest = async (method, path, opts) => { - leaseRequests.push({ method, path, body: opts?.body }); - return new Response(method === "POST" ? JSON.stringify({ id: "fixture-lease" }) : null, { status: 200 }); - }; + const request = createInstaboxRequest("fixture-key", url); return { machines, request, requests, leaseRequests, files, state, close: async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve()));