Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/tasks/T-1200/T-1269-instabox-api-update/brief.md
Original file line number Diff line number Diff line change
@@ -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() 下新建的目录。
24 changes: 24 additions & 0 deletions docs/tasks/T-1200/T-1269-instabox-api-update/report.md
Original file line number Diff line number Diff line change
@@ -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。
92 changes: 92 additions & 0 deletions docs/tasks/T-1200/T-1269-instabox-api-update/verification.txt
Original file line number Diff line number Diff line change
@@ -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。
38 changes: 27 additions & 11 deletions server/instabox/computer-tools.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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}`,
]);
});

Expand All @@ -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", () => {
Expand Down
29 changes: 14 additions & 15 deletions server/instabox/computer-tools.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -124,11 +124,19 @@ async function copyFile(

const BACKGROUND_ROOT = "/tmp/cry-instabox-background";
type ActivityLease = {
request: InstaboxRequest; machineId: string; id?: string; processes: Set<string>;
request: InstaboxRequest; machineId: string; id: string; processes: Set<string>;
pending: Promise<void>; renew?: ReturnType<typeof setInterval>; expiry?: ReturnType<typeof setTimeout>;
};
const activityLeases = new Map<string, ActivityLease>();

const activityLeasePath = (lease: ActivityLease) => `/v1/machines/${lease.machineId}/activity-leases/${encodeURIComponent(lease.id)}`;

async function putActivityLease(lease: ActivityLease): Promise<void> {
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<void> {
const lease = activityLeases.get(machineId);
if (!lease) return;
Expand All @@ -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<void> {
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;
}
Expand All @@ -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?.();
Expand Down
Loading
Loading