Skip to content

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

fix(pages): handle closed responses and resolve unpublish after waiting

Sebastian B576e1e7e7661
diff --git a/server/host/turn-call-signals.test.ts b/server/host/turn-call-signals.test.ts
index c8622e4165..8e9e134f5f 100644
--- a/server/host/turn-call-signals.test.ts
+++ b/server/host/turn-call-signals.test.ts
@@ -35,4 +35,14 @@ describe("turn call signals", () => {
signals.sweep();
expect(signal.aborted).toBe(false);
});
+
+ it.each([false, true])("handles a response closed before registration (writableEnded=%s)", (writableEnded) => {
+ const signals = createTurnCallSignals(() => false);
+ const res = Object.assign(response(), { closed: true, writableEnded });
+ res.emit("close");
+ const signal = signals.signal("turn", res);
+ expect(signal.aborted).toBe(!writableEnded);
+ signals.sweep();
+ expect(signal.aborted).toBe(!writableEnded);
+ });
});
diff --git a/server/host/turn-call-signals.ts b/server/host/turn-call-signals.ts
index 814107f00c..4620f064b3 100644
--- a/server/host/turn-call-signals.ts
+++ b/server/host/turn-call-signals.ts
@@ -8,10 +8,12 @@ export function createTurnCallSignals<Grant>(isActive: (grant: Grant) => boolean
signal(grant: Grant, res: ServerResponse): AbortSignal {
const call = new AbortController();
calls.set(call, grant);
- res.once("close", () => {
+ const onClose = () => {
calls.delete(call);
if (!res.writableEnded) call.abort();
- });
+ };
+ if (res.closed) onClose();
+ else res.once("close", onClose);
return call.signal;
},
/** Called after grants are revoked. */
diff --git a/server/pages/published-pages.test.ts b/server/pages/published-pages.test.ts
index b11f36f54e..668c434b9f 100644
--- a/server/pages/published-pages.test.ts
+++ b/server/pages/published-pages.test.ts
@@ -1,11 +1,12 @@
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PublishedPageCard } from "../../shared/published-page.ts";
import { FAKE_DESKTOP_TOKEN, FAKE_HOME, FAKE_TOKEN_URL, fakePagesService } from "../testing/fake-pages.ts";
import { applyIncludedPagesMessage, pagesHomeSignature } from "./access.ts";
import { PageBundleError, readPageBundle } from "./bundle.ts";
+import * as bundle from "./bundle.ts";
import { PublishedPagesStore } from "./store.ts";
import { createPublishedPages } from "./service.ts";
import { createPagesInternalRoutes, createPublishedPageRoutes, type AppPages } from "../routes/published-pages.ts";
@@ -29,6 +30,12 @@ function writeSite(folder: string, files: Record<string, string> = SITE) {
}
const signIn = () => applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: { url: FAKE_TOKEN_URL, token: FAKE_DESKTOP_TOKEN } });
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
function setup(options: { home?: boolean; quota?: number } = {}) {
const service = fakePagesService({ quota: options.quota });
const work = join(dir, "work"), data = join(dir, "data");
@@ -333,6 +340,61 @@ describe("unpublishing a page", () => {
expect(f.pages.store.get(page!)).toBeNull();
});
+ it.each(["path", "page id"])("unpublishes by %s while a missing page is replaced", async (by) => {
+ const f = setup();
+ signIn();
+ const source = realpathSync(writeSite(join(f.work, "site")));
+ await f.publish({ path: "site" });
+ const [oldId] = [...f.service.pages.keys()];
+ f.service.pages.delete(oldId!);
+ const arrived = deferred(), answered = deferred();
+ const fetch = f.service.fetch;
+ f.service.fetch = async (input, init) => {
+ const response = await fetch(input, init);
+ if (init?.method === "PUT" && response.status === 410) { arrived.resolve(); await answered.promise; }
+ return response;
+ };
+ const update = f.publish({ path: "site" });
+ await arrived.promise;
+ const lookup = vi.spyOn(bundle, "pageSource").mockResolvedValue(source);
+ const unpublished = f.pages.publisher.unpublish(by === "path" ? { path: "site", botId: "bot-1", roots: [f.work] } : { pageId: oldId });
+ await Promise.resolve();
+ lookup.mockRestore();
+ answered.resolve();
+ expect((await update).status).toBe(200);
+ const replacement = f.cards.at(-1)!.card.pageId!;
+ expect(replacement).not.toBe(oldId);
+ expect(await unpublished).toMatchObject({ status: 200, card: { pageId: by === "path" ? replacement : oldId } });
+ expect(f.service.pages.has(replacement)).toBe(by !== "path");
+ expect(f.pages.store.get(replacement) === null).toBe(by === "path");
+ expect(f.cards.at(-1)!.card.state).toBe(by === "path" ? "unpublished" : "live");
+ });
+
+ it("unpublishes by path after the first publish in flight creates its record", async () => {
+ const f = setup();
+ signIn();
+ const source = realpathSync(writeSite(join(f.work, "site")));
+ const arrived = deferred(), answered = deferred();
+ const fetch = f.service.fetch;
+ f.service.fetch = async (input, init) => {
+ const response = await fetch(input, init);
+ if (init?.method === "PUT") { arrived.resolve(); await answered.promise; }
+ return response;
+ };
+ const publish = f.publish({ path: "site" });
+ await arrived.promise;
+ const lookup = vi.spyOn(bundle, "pageSource").mockResolvedValue(source);
+ const unpublished = f.pages.publisher.unpublish({ path: "site", botId: "bot-1", roots: [f.work] });
+ await Promise.resolve();
+ lookup.mockRestore();
+ answered.resolve();
+ expect((await publish).status).toBe(200);
+ expect((await unpublished).status).toBe(200);
+ expect(f.service.pages.size).toBe(0);
+ expect(f.pages.store.list()).toEqual([]);
+ expect(f.cards.map((card) => card.card.state)).toEqual(["unpublished"]);
+ });
+
it.each([["the same folder", false], ["another folder by its page id", true]])("takes a page down after an update from %s already in flight, so the update's late answer leaves no record or live card", async (_case, byId) => {
const f = setup();
signIn();
diff --git a/server/pages/publisher.ts b/server/pages/publisher.ts
index ba89f9fdc9..96b71b44fd 100644
--- a/server/pages/publisher.ts
+++ b/server/pages/publisher.ts
@@ -147,19 +147,27 @@ export function createPagePublisher(deps: {
/** Takes a page down, by its id or the file or folder it came from (with the bot's folders). */
async unpublish(input: { pageId?: string; path?: string; botId?: string; roots?: readonly string[]; call?: PagesCall }): Promise<PageOutcome> {
- let pageId = input.pageId;
+ const pageId = input.pageId;
if (pageId !== undefined && !PAGE_ID.test(pageId)) return { status: 400, text: "page_id must be the id of a page you published, from its link." };
+ const takeDown = (id: string) => serially(pageKey(id), () => unpublishNow(id, input.call));
if (!pageId && input.path && input.botId && input.roots) {
+ const botId = input.botId;
+ const notFound: PageOutcome = { status: 404, text: `No page was published from ${input.path}. Pass the page_id from its link instead.` };
+ let source: string;
try {
- pageId = store.fromSource(input.botId, await pageSource(input.path, input.roots))?.pageId;
+ source = await pageSource(input.path, input.roots);
} catch (error) {
if (!(error instanceof PageBundleError)) throw error;
+ return notFound;
}
- if (!pageId) return { status: 404, text: `No page was published from ${input.path}. Pass the page_id from its link instead.` };
+ return serially(JSON.stringify([botId, source]), async () => {
+ const record = store.fromSource(botId, source);
+ return record ? takeDown(record.pageId) : notFound;
+ });
}
if (!pageId) return { status: 400, text: "Pass the page_id of the page to unpublish, or the path it was published from." };
- const record = store.get(pageId), takeDown = () => serially(pageKey(pageId), () => unpublishNow(pageId, input.call));
- return record ? serially(JSON.stringify([record.botId, record.source]), takeDown) : takeDown();
+ const record = store.get(pageId);
+ return record ? serially(JSON.stringify([record.botId, record.source]), () => takeDown(pageId)) : takeDown(pageId);
},
};
}