Skip to content

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

fix(move): serialize conditional publication and accept matching retries

Afloate289da47ec38
diff --git a/server/cloud-send-files.ts b/server/cloud-send-files.ts
index 0d1ad4848c..076f761e7a 100644
--- a/server/cloud-send-files.ts
+++ b/server/cloud-send-files.ts
@@ -87,6 +87,17 @@ function space(dataDir: string): { freeBytes: number; volumeBytes: number } | nu
const staging = (dataDir: string) => join(dataDir, "tmp", "move-files");
const partialPath = (dataDir: string, sha256: string, size: number) => join(staging(dataDir), `${sha256}-${size}.partial`);
+const publications = new Map<string, Promise<void>>();
+
+/** Keeps this receiver's target check and publication together, releasing waiters on failure too. */
+async function publishInOrder<T>(target: string, publish: () => Promise<T>): Promise<T> {
+ const previous = publications.get(target) ?? Promise.resolve();
+ const result = previous.then(publish);
+ const settled = result.then(() => {}, () => {});
+ publications.set(target, settled);
+ try { return await result; }
+ finally { if (publications.get(target) === settled) publications.delete(target); }
+}
/** Partial files a move left more than a day ago. */
async function tidyPartials(dataDir: string, now = Date.now()): Promise<void> {
@@ -167,7 +178,7 @@ async function takePart(deps: MoveFilesDeps, req: IncomingMessage, query: z.infe
}
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;
+ const { path, size, sha256, offset } = 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 } }; }
@@ -181,12 +192,17 @@ async function takePartAt(deps: MoveFilesDeps, req: IncomingMessage, query: z.in
if (received < size) return { status: 200, body: { received } };
if (await sha256Of(partial) !== sha256) { await unlink(partial).catch(() => {}); return { status: 422, body: { error: "the file arrived different from what was sent" } }; }
const target = join(deps.dataDir, path);
- if (!(await realFolders(deps.dataDir, path))) return { status: 409, body: { conflict: true } };
+ return publishInOrder(target, () => publishPart(deps.dataDir, target, partial, query));
+}
+
+/** Publishes a verified part after all earlier publications to this target have finished. */
+async function publishPart(dataDir: string, target: string, partial: string, { path, mode, expect, sha256 }: z.infer<typeof putSchema>): Promise<{ status: number; body: Record<string, unknown> }> {
+ if (!(await realFolders(dataDir, path))) return { status: 409, body: { conflict: true } };
const there = await lstat(target).catch(() => null);
if (there && !there.isFile()) return { status: 409, body: { conflict: true } };
if (there && await sha256Of(target) === sha256) { await unlink(partial).catch(() => {}); return { status: 201, body: { stored: false } }; }
if (mode === "replace" && there && expect && await sha256Of(target) === expect) {
- const placed = join(staging(deps.dataDir), `${randomUUID()}.placing`);
+ const placed = join(staging(dataDir), `${randomUUID()}.placing`);
await link(partial, placed);
await rename(placed, target);
await unlink(partial).catch(() => {});
@@ -195,7 +211,14 @@ async function takePartAt(deps: MoveFilesDeps, req: IncomingMessage, query: z.in
if (there) return { status: 409, body: { conflict: true } };
try { await link(partial, target); }
catch (error) {
- if ((error as NodeJS.ErrnoException).code === "EEXIST") return { status: 409, body: { conflict: true } };
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
+ const current = await lstat(target).catch(() => null);
+ if (current?.isFile() && await sha256Of(target) === sha256) {
+ await unlink(partial).catch(() => {});
+ return { status: 201, body: { stored: false } };
+ }
+ return { status: 409, body: { conflict: true } };
+ }
throw error;
}
await unlink(partial).catch(() => {});
diff --git a/server/cloud-send-publication.test.ts b/server/cloud-send-publication.test.ts
new file mode 100644
index 0000000000..ff86b44fb1
--- /dev/null
+++ b/server/cloud-send-publication.test.ts
@@ -0,0 +1,105 @@
+import { createHash } from "node:crypto";
+import { mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
+import { link, rename } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Readable } from "node:stream";
+import { afterEach, beforeEach, 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");
+const digest = (text: string) => createHash("sha256").update(text).digest("hex");
+
+describe("publishing bot files during a move", () => {
+ let data: string;
+ beforeEach(() => {
+ data = mkdtempSync(join(tmpdir(), "omb-file-publication-"));
+ mkdirSync(join(data, "workspaces/b1"), { recursive: true });
+ });
+ afterEach(async () => {
+ vi.mocked(link).mockRestore();
+ vi.mocked(rename).mockRestore();
+ await removeTempDir(data);
+ });
+
+ async function send(path: string, text: string, expected?: string) {
+ let answer: { status: number; body: unknown } | undefined;
+ const query = { path, size: String(Buffer.byteLength(text)), sha256: digest(text), offset: "0", mode: expected === undefined ? "new" : "replace",
+ ...(expected === undefined ? {} : { expect: digest(expected) }) };
+ const url = new URL(`http://127.0.0.1/api/cloud-send/files?${new URLSearchParams(query)}`);
+ 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.from(text)]) 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;
+ }
+
+ it("accepts an identical file that appears between the existence check and publication", async () => {
+ const path = "workspaces/b1/empty.txt";
+ vi.mocked(link).mockImplementation(async (source, target) => {
+ if (target === join(data, path)) writeFileSync(target, "");
+ return realFs.link(source, target);
+ });
+ expect(await send(path, "")).toEqual({ status: 201, body: { stored: false } });
+ expect(readFileSync(join(data, path))).toHaveLength(0);
+ });
+
+ it.each(["different file", "directory", "symlink"])("keeps a concurrently created %s as a conflict", async (kind) => {
+ const path = "workspaces/b1/occupied.txt";
+ const outside = join(data, "outside.txt");
+ writeFileSync(outside, "");
+ vi.mocked(link).mockImplementation(async (source, target) => {
+ if (target === join(data, path)) {
+ if (kind === "directory") mkdirSync(target);
+ else if (kind === "symlink") symlinkSync(outside, target);
+ else writeFileSync(target, "keep this");
+ }
+ return realFs.link(source, target);
+ });
+ expect(await send(path, "")).toEqual({ status: 409, body: { conflict: true } });
+ });
+
+ it("checks a queued replacement against the version published before it", async () => {
+ const path = "workspaces/b1/current.txt";
+ writeFileSync(join(data, path), "original");
+ let reached!: () => void;
+ let release!: () => void;
+ const waiting = new Promise<void>((resolve) => { reached = resolve; });
+ const allowed = new Promise<void>((resolve) => { release = resolve; });
+ let firstRename = true;
+ vi.mocked(rename).mockImplementation(async (source, target) => {
+ if (target === join(data, path) && firstRename) {
+ firstRename = false;
+ reached();
+ await allowed;
+ }
+ return realFs.rename(source, target);
+ });
+ const first = send(path, "updated", "original");
+ await waiting;
+ const second = send(path, "", "original");
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([second, new Promise<void>((resolve) => { timer = setTimeout(resolve, 1000); })]);
+ } finally {
+ clearTimeout(timer);
+ release();
+ }
+ expect(await first).toEqual({ status: 201, body: { stored: true } });
+ expect(await second).toEqual({ status: 409, body: { conflict: true } });
+ expect(readFileSync(join(data, path), "utf8")).toBe("updated");
+ });
+
+ it("releases a failed publication so a later retry can finish", async () => {
+ const path = "workspaces/b1/retry.txt";
+ vi.mocked(link).mockRejectedValueOnce(new Error("temporary publication failure"));
+ await expect(send(path, "")).rejects.toThrow("temporary publication failure");
+ expect(await send(path, "")).toEqual({ status: 201, body: { stored: true } });
+ expect(readFileSync(join(data, path))).toHaveLength(0);
+ });
+});