Public: anyone can read this; the crew can change it.

test/apps-ws.test.ts fails 5 of 8 in the full gate run, passes alone #1186

Closed opened this
Closed without merging

scout/forge:scout/1073-test-apps-ws-test-ts-fails-5-of-8-in-the → main 5 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +96 −83
scripts/gate.ts +2 −1
@@ -58,6 +58,7 @@ export const GATE: readonly string[] = [
5858 "test/crew-direction-autonomy.test.ts",
5959 "test/crew-guard.test.ts",
6060 "test/review-waits.test.ts",
61 "test/review-from-check.test.ts",
6162 "test/scale.test.ts",
6263 "test/sealed-private-work.test.ts",
6364 "test/settings.test.ts",
@@ -212,6 +213,7 @@ export const GATE: readonly string[] = [
212213 "test/reports.test.ts",
213214 "test/report-discovery.test.ts",
214215 "test/apps-report.test.ts",
216 "test/apps-ws.test.ts",
215217 "test/private-app.test.ts",
216218 "test/actions.test.ts",
217219 "test/app-env.test.ts",
@@ -239,7 +241,6 @@ export const EXCLUDED: readonly Exclusion[] = [
239241 issue: 261,
240242 },
241243 { file: "test/apps-sleep.test.ts", reason: "not yet admitted", issue: 261 },
242 { file: "test/apps-ws.test.ts", reason: "not yet admitted", issue: 261 },
243244 { file: "test/audit.test.ts", reason: "not yet admitted", issue: 261 },
244245 {
245246 file: "test/board-windows.test.ts",
src/app.ts +2
@@ -98,6 +98,8 @@ export interface ForgeConfig {
9898 trustedProxies?: readonly string[];
9999 /** A header a trusted edge sets to the client's address (\`FORGE_CLIENT_IP_HEADER\`). */
100100 clientIpHeader?: string;
101 /** The most one proxied websocket frame may carry; absent, 16 MiB. Tests lower it. */
102 wsMaxMessage?: number;
101103 /**
102104 * How often this process holds what it has open against each account's
103105 * standing in the database (\`http/caller.ts\`), so a suspension made by
src/apps/proxy.ts +81 −73
@@ -334,7 +334,10 @@ const HOP_BY_HOP = [
334334 * a sealed report's fix, which only those who may see the report may open,
335335 * on a public app as on a private one.
336336 */
337 function sealedPull(runtime: AppsRuntime, target: AppTarget): Issue | undefined {
337 function sealedPull(
338 runtime: AppsRuntime,
339 target: AppTarget,
340 ): Issue | undefined {
338341 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
339342 if (number === undefined) return undefined;
340343 const pull = getIssue(runtime.app.db, target.app.repoId, Number(number));
@@ -464,8 +467,8 @@ const isHtml = (headers: Headers): boolean =>
464467
465468 /**
466469 * Serve a request addressed to an app. `undefined` means the request became
467 * a websocket: the response was the handshake, and `appWebSocket` now owns
468 * the connection.
470 * a websocket: the response was the handshake, and the handler `serve`
471 * builds with `appWebSocketWith` now owns the connection.
469472 */
470473 export async function proxyApp(
471474 runtime: AppsRuntime,
@@ -812,81 +815,86 @@ function closeBoth(
812815 /**
813816 * The forge's `websocket` handler: frames through, both ways, and the
814817 * close of one side carried to the other. Text stays text and binary
815 * stays binary; the forge reads neither.
818 * stays binary; the forge reads neither. The frame limit is
819 * `WS_MAX_MESSAGE` unless the app's config chooses another.
816820 */
817 export const appWebSocket: Bun.WebSocketHandler<AppSocket> = {
818 maxPayloadLength: WS_MAX_MESSAGE,
819 backpressureLimit: WS_MAX_MESSAGE,
820 closeOnBackpressureLimit: true,
821 idleTimeout: WS_IDLE_SECONDS,
821 export function appWebSocketWith(max = WS_MAX_MESSAGE): Bun.WebSocketHandler<AppSocket> {
822 return {
823 maxPayloadLength: max,
824 backpressureLimit: max,
825 closeOnBackpressureLimit: true,
826 idleTimeout: WS_IDLE_SECONDS,
822827
823 open(ws) {
824 const { upstream, userId, db } = ws.data;
825 if (userId !== undefined)
826 heldSockets.set(
827 ws,
828 holdOpen(db, userId, undefined, () => {
829 if (ws.readyState === WebSocket.OPEN)
830 closeBoth(ws, 1008, "this account was suspended");
831 }),
832 );
833 // No frame from the app can get here first. Its `open` event resolved
834 // `connectUpstream`, and the microtask checkpoint after that callback
835 // runs `proxyWebSocket` to completion — `server.upgrade` calls this
836 // handler synchronously — before the loop dispatches the next event,
837 // so a greeting the app sent the moment its socket opened, even one
838 // corked into the same write as its 101, still finds this listener.
839 // test/apps-ws.test.ts holds the app to exactly that.
840 upstream.addEventListener("message", (event: MessageEvent) => {
841 const data: unknown = event.data;
842 const size =
843 typeof data === "string"
844 ? Buffer.byteLength(data)
845 : (data as ArrayBuffer).byteLength;
846 if (size > WS_MAX_MESSAGE) {
847 closeBoth(ws, 1009, "message too big");
848 return;
828 open(ws) {
829 const { upstream, userId, db } = ws.data;
830 if (userId !== undefined)
831 heldSockets.set(
832 ws,
833 holdOpen(db, userId, undefined, () => {
834 if (ws.readyState === WebSocket.OPEN)
835 closeBoth(ws, 1008, "this account was suspended");
836 }),
837 );
838 // No frame from the app can get here first. Its `open` event resolved
839 // `connectUpstream`, and the microtask checkpoint after that callback
840 // runs `proxyWebSocket` to completion — `server.upgrade` calls this
841 // handler synchronously — before the loop dispatches the next event,
842 // so a greeting the app sent the moment its socket opened, even one
843 // corked into the same write as its 101, still finds this listener.
844 // test/apps-ws.test.ts holds the app to exactly that.
845 upstream.addEventListener("message", (event: MessageEvent) => {
846 const data: unknown = event.data;
847 const size =
848 typeof data === "string"
849 ? Buffer.byteLength(data)
850 : (data as ArrayBuffer).byteLength;
851 if (size > max) {
852 closeBoth(ws, 1009, "message too big");
853 return;
854 }
855 if (ws.readyState !== WebSocket.OPEN) return;
856 const sent =
857 typeof data === "string"
858 ? ws.send(data)
859 : ws.send(data as ArrayBuffer);
860 // 0 is a frame Bun dropped, because more than the limit was already
861 // waiting on a browser that is not reading. A stream with a hole in
862 // it is not a stream; end it rather than let the app keep talking.
863 if (sent === 0 && ws.readyState === WebSocket.OPEN) {
864 closeBoth(ws, 1008, "not reading");
865 }
866 });
867 upstream.addEventListener("close", (event: CloseEvent) => {
868 if (ws.readyState !== WebSocket.OPEN) return;
869 // The app went away without a word: a crash, a redeploy, a stop.
870 if (event.code === 1006) ws.close(1001, "the app stopped answering");
871 else ws.close(sendable(event.code) ? event.code : 1000, event.reason);
872 });
873 // Opened a moment ago, and nothing has run since — but a socket that
874 // is somehow already shut would otherwise leave this one hanging.
875 if (upstream.readyState !== WebSocket.OPEN) {
876 ws.close(1001, "the app stopped answering");
849877 }
850 if (ws.readyState !== WebSocket.OPEN) return;
851 const sent =
852 typeof data === "string" ? ws.send(data) : ws.send(data as ArrayBuffer);
853 // 0 is a frame Bun dropped, because more than the limit was already
854 // waiting on a browser that is not reading. A stream with a hole in
855 // it is not a stream; end it rather than let the app keep talking.
856 if (sent === 0 && ws.readyState === WebSocket.OPEN) {
857 closeBoth(ws, 1008, "not reading");
858 }
859 });
860 upstream.addEventListener("close", (event: CloseEvent) => {
861 if (ws.readyState !== WebSocket.OPEN) return;
862 // The app went away without a word: a crash, a redeploy, a stop.
863 if (event.code === 1006) ws.close(1001, "the app stopped answering");
864 else ws.close(sendable(event.code) ? event.code : 1000, event.reason);
865 });
866 // Opened a moment ago, and nothing has run since — but a socket that
867 // is somehow already shut would otherwise leave this one hanging.
868 if (upstream.readyState !== WebSocket.OPEN) {
869 ws.close(1001, "the app stopped answering");
870 }
871 },
878 },
872879
873 message(ws, message) {
874 const { upstream } = ws.data;
875 // A closing app has its close on the way to the browser already.
876 if (upstream.readyState !== WebSocket.OPEN) return;
877 upstream.send(message);
878 },
880 message(ws, message) {
881 const { upstream } = ws.data;
882 // A closing app has its close on the way to the browser already.
883 if (upstream.readyState !== WebSocket.OPEN) return;
884 upstream.send(message);
885 },
879886
880 close(ws, code, reason) {
881 const { upstream } = ws.data;
882 heldSockets.get(ws)?.();
883 heldSockets.delete(ws);
884 if (upstream.readyState === WebSocket.CLOSED) return;
885 // 1006 here is the browser gone without a close frame.
886 if (code === 1006) upstream.close(1001, "the browser went away");
887 else upstream.close(sendable(code) ? code : 1000, reason);
888 },
889 };
887 close(ws, code, reason) {
888 const { upstream } = ws.data;
889 heldSockets.get(ws)?.();
890 heldSockets.delete(ws);
891 if (upstream.readyState === WebSocket.CLOSED) return;
892 // 1006 here is the browser gone without a close frame.
893 if (code === 1006) upstream.close(1001, "the browser went away");
894 else upstream.close(sendable(code) ? code : 1000, reason);
895 },
896 };
897 }
890898
891899 function grant(
892900 runtime: AppsRuntime,
src/http/server.ts +2 −2
@@ -403,7 +403,7 @@ import { Router } from "./router.ts";
403403 import { getUserById } from "../core/users.ts";
404404 import { appsRuntime } from "../apps/runtime.ts";
405405 import {
406 appWebSocket,
406 appWebSocketWith,
407407 proxyApp,
408408 resolveAppHost,
409409 } from "../apps/proxy.ts";
@@ -1670,7 +1670,7 @@ export async function serve(app: App): Promise<Servers> {
16701670 maxRequestBodySize: REQUEST_MAX,
16711671 // The only sockets the forge holds are an app's, carried through the
16721672 // proxy; its own live surfaces are SSE (`sse.ts`) and stay so.
1673 websocket: appWebSocket,
1673 websocket: appWebSocketWith(app.config.wsMaxMessage),
16741674 async fetch(request, server) {
16751675 // An app's hostname is answered before any route: `hello.<domain>` is
16761676 // the app, whatever its path, and the forge's own routes never apply.
test/apps-ws.test.ts +9 −7
@@ -27,6 +27,8 @@ import { createUser, type User } from "../src/core/users.ts";
2727 import { serve, type Servers } from "../src/http/server.ts";
2828
2929 const MIB = 1024 * 1024;
30 /** The forge's frame limit for this file: the real one is 16 MiB, and moving that much three times took the test 30 s under load. */
31 const LIMIT = 2 * MIB;
3032
3133 /**
3234 * The app under test: `/ws` echoes what it is sent, text as text and
@@ -209,7 +211,7 @@ describe("apps: websockets through the proxy", () => {
209211
210212 beforeAll(async () => {
211213 dataDir = await mkdtemp(join(tmpdir(), "forge-apps-ws-"));
212 app = createApp({ dataDir, port: 0 });
214 app = createApp({ dataDir, port: 0, wsMaxMessage: LIMIT });
213215 servers = await serve(app);
214216 runtime = new AppsRuntime(app, {
215217 domain: DOMAIN,
@@ -357,14 +359,14 @@ describe("apps: websockets through the proxy", () => {
357359 const inbound = connect("/ws");
358360 expect(await inbound.opened).toBe(true);
359361 await seenBy(inbound.next);
360 inbound.ws.send(new Uint8Array(16 * MIB + 1));
362 inbound.ws.send(new Uint8Array(LIMIT + 1));
361363 expect((await inbound.closed).code).not.toBe(1000);
362364
363365 // From the app: the forge will not carry it.
364366 const outbound = connect("/ws");
365367 expect(await outbound.opened).toBe(true);
366368 await seenBy(outbound.next);
367 outbound.ws.send(`big:${16 * MIB + 1}`);
369 outbound.ws.send(`big:${LIMIT + 1}`);
368370 expect(await outbound.closed).toEqual({
369371 code: 1009,
370372 reason: "message too big",
@@ -375,10 +377,10 @@ describe("apps: websockets through the proxy", () => {
375377 const atLimit = connect("/ws");
376378 expect(await atLimit.opened).toBe(true);
377379 await seenBy(atLimit.next);
378 atLimit.ws.send(`big:${16 * MIB}`);
379 expect(bytes(await atLimit.next()).length).toBe(16 * MIB);
380 atLimit.ws.send(new Uint8Array(16 * MIB));
381 expect(bytes(await atLimit.next()).length).toBe(16 * MIB);
380 atLimit.ws.send(`big:${LIMIT}`);
381 expect(bytes(await atLimit.next()).length).toBe(LIMIT);
382 atLimit.ws.send(new Uint8Array(LIMIT));
383 expect(bytes(await atLimit.next()).length).toBe(LIMIT);
382384 atLimit.ws.close();
383385 }, 30_000);
384386

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs