diff --git a/apps/t3/src/runtimeApiServer.test.ts b/apps/t3/src/runtimeApiServer.test.ts index 746e2b19cd..0c4cd25588 100644 --- a/apps/t3/src/runtimeApiServer.test.ts +++ b/apps/t3/src/runtimeApiServer.test.ts @@ -166,6 +166,19 @@ describe("runtimeApiServer", () => { await expect(server.close()).resolves.toBeUndefined(); }); + it("allows concurrent runtime server close calls", async () => { + const server = await startRuntimeApiServer({ + port: 0, + launchCwd: process.cwd(), + }); + + await expect(Promise.all([server.close(), server.close(), server.close()])).resolves.toEqual([ + undefined, + undefined, + undefined, + ]); + }); + it("rejects empty auth token configuration", async () => { await expect( startRuntimeApiServer({ diff --git a/apps/t3/src/runtimeApiServer.ts b/apps/t3/src/runtimeApiServer.ts index 68c5aca149..8277b21ae5 100644 --- a/apps/t3/src/runtimeApiServer.ts +++ b/apps/t3/src/runtimeApiServer.ts @@ -656,19 +656,28 @@ export async function startRuntimeApiServer( const wsUrl = authToken ? `${wsBaseUrl}?token=${encodeURIComponent(authToken)}` : wsBaseUrl; + let closePromise: Promise | null = null; return { wsUrl, - async close() { - processManager.killAll(); - providerManager.stopAll(); - providerManager.dispose(); - for (const client of wss.clients) { - client.terminate(); + close() { + if (closePromise) { + return closePromise; } - await new Promise((resolve) => { - wss.close(() => resolve()); - }); + + closePromise = (async () => { + processManager.killAll(); + providerManager.stopAll(); + providerManager.dispose(); + for (const client of wss.clients) { + client.terminate(); + } + await new Promise((resolve) => { + wss.close(() => resolve()); + }); + })(); + + return closePromise; }, }; }