Skip to content

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

fix(relay-link): stop waiting for the shared dial when the request's signal aborts

Bugfixer 2316c2aaedccd
diff --git a/src/lib/e2e/relay-link.test.ts b/src/lib/e2e/relay-link.test.ts
index 73c9ed3e00..f69ce915b5 100644
--- a/src/lib/e2e/relay-link.test.ts
+++ b/src/lib/e2e/relay-link.test.ts
@@ -45,4 +45,31 @@ describe("RelayLink", () => {
await expect(link.fetch("/api/auth/session", { signal: AbortSignal.abort(reason) })).rejects.toBe(reason);
expect(dials).toBe(0);
});
+
+ it("stops waiting for the relay with the caller's reason when its signal aborts, and leaves the dial to the others", async () => {
+ const sockets: Array<{ onerror: (() => void) | null; onclose: ((event: { code: number }) => void) | null }> = [];
+ vi.stubGlobal("WebSocket", class {
+ binaryType = "blob";
+ onopen = null;
+ onerror = null;
+ onclose = null;
+ onmessage = null;
+ constructor() {
+ sockets.push(this);
+ }
+ close() {}
+ });
+ const link = new RelayLink(relayRoute({ v: 1, k, h, r: ["relay1.openmausbot.com"] })!, "token");
+ const stop = new AbortController();
+ const cancelled = link.fetch("/api/auth/session", { signal: stop.signal });
+ const other = link.fetch("/api/bots");
+ const reason = new Error("cancelled by the page");
+ stop.abort(reason);
+ await expect(cancelled).rejects.toBe(reason);
+ await vi.waitFor(() => expect(sockets).toHaveLength(1));
+ sockets[0].onclose?.({ code: 1006 });
+ await expect(other).rejects.toThrow();
+ await expect(cancelled).rejects.toBe(reason);
+ link.close();
+ });
});
diff --git a/src/lib/e2e/relay-link.ts b/src/lib/e2e/relay-link.ts
index 1c822c7d97..f08fd16af0 100644
--- a/src/lib/e2e/relay-link.ts
+++ b/src/lib/e2e/relay-link.ts
@@ -97,8 +97,9 @@ export class RelayLink {
}
async fetch(path: string, request: RelayRequest = {}): Promise<Response> {
- request.signal?.throwIfAborted();
- const session = await this.#live();
+ const { signal } = request;
+ signal?.throwIfAborted();
+ const session = await (signal ? untilAborted(this.#live(), signal) : this.#live());
const headers = new Headers(request.headers);
headers.set("authorization", `Bearer ${this.#token}`);
return streamFetch(() => session.open(), { ...request, path, headers });
@@ -123,3 +124,12 @@ export class RelayLink {
return dialing;
}
}
+
+/** `promise`, or `signal`'s reason as soon as it aborts; the promise itself goes on for anyone else waiting on it. */
+function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
+ });
+}