Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(move): isolate empty uploads through file publication

Afloatdb9cab8a935d
diff --git a/server/cloud-send-empty-overlap.test.ts b/server/cloud-send-empty-overlap.test.ts
new file mode 100644
index 0000000000..2510ea4f35
--- /dev/null
+++ b/server/cloud-send-empty-overlap.test.ts
@@ -0,0 +1,56 @@
+import { createHash } from "node:crypto";
+import { mkdtempSync, readFileSync } from "node:fs";
+import { link } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Readable } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+vi.mock("node:fs/promises", { spy: true });
+vi.resetModules();
+const { moveFilesRoute } = await import("./cloud-send-files.ts");
+const realFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
+
+describe("overlapping empty bot file uploads", () => {
+ const data = mkdtempSync(join(tmpdir(), "omb-empty-overlap-"));
+ afterEach(async () => {
+ vi.mocked(link).mockRestore();
+ await removeTempDir(data);
+ });
+
+ it("keeps a verified empty upload available while another empty file finishes", async () => {
+ const firstPath = "workspaces/b1/first.txt";
+ const secondPath = "workspaces/b1/second.txt";
+ const digest = createHash("sha256").update("").digest("hex");
+ let reached!: () => void;
+ let release!: () => void;
+ const waiting = new Promise<void>((resolve) => { reached = resolve; });
+ const allowed = new Promise<void>((resolve) => { release = resolve; });
+ vi.mocked(link).mockImplementation(async (existing, target) => {
+ if (target === join(data, firstPath)) { reached(); await allowed; }
+ return realFs.link(existing, target);
+ });
+ const send = async (path: string) => {
+ let answer: { status: number; body: unknown } | undefined;
+ const url = new URL(`http://127.0.0.1/api/cloud-send/files?${new URLSearchParams({ path, size: "0", sha256: digest, offset: "0", mode: "new" })}`);
+ await moveFilesRoute({ dataDir: data, bots: () => [{ id: "b1" }], owner: () => ({ person: "p_owner", name: "Owner" }) }, {
+ path: "/api/cloud-send/files", method: "POST", url, auth: {} as never,
+ req: Readable.from([Buffer.alloc(0)]) as never, res: { setHeader() {} } as never,
+ json: ((_res: unknown, status: number, body: unknown) => { answer = { status, body }; }) as never,
+ readBody: (async () => null) as never,
+ });
+ return answer;
+ };
+ const first = send(firstPath).catch((error: unknown) => ({ error }));
+ try {
+ await waiting;
+ expect(await send(secondPath)).toEqual({ status: 201, body: { stored: true } });
+ } finally {
+ release();
+ }
+ expect(await first).toEqual({ status: 201, body: { stored: true } });
+ expect(readFileSync(join(data, firstPath))).toHaveLength(0);
+ expect(readFileSync(join(data, secondPath))).toHaveLength(0);
+ });
+});
diff --git a/server/cloud-send-files.ts b/server/cloud-send-files.ts
index ede593cc5d..0d1ad4848c 100644
--- a/server/cloud-send-files.ts
+++ b/server/cloud-send-files.ts
@@ -154,11 +154,20 @@ async function readPart(dataDir: string, { path, offset, length }: z.infer<typeo
/** One part of a file: 200 `{ received }` until the last, then 201 `{ stored }`, or 409 `{ conflict }` when the path holds a
* file the move may not replace; 409 `{ received }` when the part does not start where My Cloud's copy ends. */
async function takePart(deps: MoveFilesDeps, req: IncomingMessage, query: z.infer<typeof putSchema>): Promise<{ status: number; body: Record<string, unknown> }> {
- const { path, size, sha256, offset, mode, expect } = query;
+ const { path, size, sha256 } = query;
const botId = /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path)?.[1];
if (!movedFilePath(path) || !botId) return { status: 400, body: { error: "not a bot file a move carries" } };
if (!deps.bots().some((bot) => bot.id === botId)) return { status: 409, body: { error: "This file's bot is not on My Cloud yet." } };
- const partial = partialPath(deps.dataDir, sha256, size);
+ if (size === 0) {
+ const partial = join(staging(deps.dataDir), `${randomUUID()}.partial`);
+ try { return await takePartAt(deps, req, query, partial); }
+ finally { await unlink(partial).catch(() => {}); }
+ }
+ return takePartAt(deps, req, query, partialPath(deps.dataDir, sha256, size));
+}
+
+async function takePartAt(deps: MoveFilesDeps, req: IncomingMessage, query: z.infer<typeof putSchema>, partial: string): Promise<{ status: number; body: Record<string, unknown> }> {
+ const { path, size, sha256, offset, mode, expect } = query;
await mkdir(staging(deps.dataDir), { recursive: true, mode: 0o700 });
const held = (await stat(partial).catch(() => null))?.size ?? 0;
if (offset !== held) { await rawBody(req, 0); return { status: 409, body: { received: held } }; }