From d72452d9b655a6bbc8be32983168a745e024dcf8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:04:38 -0500 Subject: [PATCH] =?UTF-8?q?feat(app):=20app.upgrade=20=E2=80=94=20neutral?= =?UTF-8?q?=20WebSocket=20entry=20over=20the=20graph?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/app/index.ts | 45 ++++++++++++++++++++++++++++++ src/app/types.ts | 3 ++ test/app-upgrade.test.ts | 59 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 test/app-upgrade.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 5a80b11..6976798 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -7,6 +7,7 @@ import { runPipeline, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; import { buildFetch } from '../http/web'; +import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '../http/ws-core'; import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; @@ -147,6 +148,13 @@ export function createApp(opts: { fetchOpts, bootAppProviders, ); + const upgradeFn = buildAppUpgrade( + () => booted, + routePlans, + { providedSeed, planSteps, bus, onError: opts.onError }, + streams, + bootAppProviders, + ); const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; @@ -203,6 +211,7 @@ export function createApp(opts: { listen, close, fetch: fetchFn, + upgrade: upgradeFn, inspect, graph, toMermaid: () => toMermaid(graph()), @@ -643,6 +652,42 @@ function buildAppFetch( }; } +/** + * Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so + * Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own + * `server.on('upgrade')` path (see `attachWs`) and never calls this. + * Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so + * `getBooted()` is already `true` and the ws route table builds on the first call; mesh apps defer + * finalize to `listen()`, so this throws until `listen()` finalizes, then works from the next call on. + */ +function buildAppUpgrade( + getBooted: () => boolean, + routePlans: RoutePlan[], + deps: PipelineDeps, + streams: Set<() => void>, + ensureBooted: () => Promise, +): (request: WsRequest, socket: WsSocket) => Promise { + let wsRoutes: WsRouteDef[] | undefined; + + return async (request: WsRequest, socket: WsSocket): Promise => { + if (!wsRoutes) { + if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps'); + wsRoutes = buildWsRoutes(routePlans, deps); + } + + await ensureBooted(); // idempotent: no-op if listen() already booted the providers + const path = request.url.split('?')[0]; + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + socket.close(1008, 'no matching ws route'); + return; + } + + await runWsConnection(socket, request, route, deps.bus, streams); + }; +} + /** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */ function devGraphRoute(graph: () => GraphView): RouteDef { return { diff --git a/src/app/types.ts b/src/app/types.ts index 086146b..50606a1 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -5,6 +5,7 @@ import type { GraphView } from '../graph-viz'; import type { HttpMethod, Transport } from '../metadata'; import type { ArgSpec } from '../params'; import type { OpenApiDoc, OpenApiInfo } from '../openapi'; +import type { WsRequest, WsSocket } from '../http/ws-core'; import { JsonTransformer } from '../transformers'; /** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */ @@ -37,6 +38,8 @@ export interface App { close(): Promise; /** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */ fetch(request: Request): Promise; + /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */ + upgrade(request: WsRequest, socket: WsSocket): Promise; inspect(routePath: string): InspectLine[]; graph(): GraphView; toMermaid(): string; diff --git a/test/app-upgrade.test.ts b/test/app-upgrade.test.ts new file mode 100644 index 0000000..ebad14c --- /dev/null +++ b/test/app-upgrade.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Route, Ws, Module, ctx } from '../src/index'; +import { channel } from '../src/channel'; +import type { WsSocket, WsRequest } from '../src/http/ws-core'; + +@Route('/rt') +class Rt { + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${msg}`; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Rt] }) +class M {} +const app = createApp({ modules: [M] }); + +function fakeSocket() { + const inbound = channel(); + const ac = new AbortController(); + const sent: string[] = []; + const socket: WsSocket = { + inbound, + abort: ac.signal, + isOpen: true, + send: (d) => sent.push(d), + close: () => ac.abort(), + terminate: () => ac.abort(), + }; + return { socket, inbound, sent }; +} + +describe('app.upgrade', () => { + it('routes a matching ws path through the graph', async () => { + const { socket, inbound, sent } = fakeSocket(); + const req: WsRequest = { url: '/rt/echo', headers: {}, protocol: 'http', ip: '' }; + const run = app.upgrade(req, socket); + // let the handler's async generator start subscribing to `inbound` (channel is fan-out: + // push before subscription is lost) before pushing — a macrotask flushes every pending + // microtask in the upgrade/boot chain first, so this is deterministic, not a sleep-and-hope. + await new Promise((resolve) => setTimeout(resolve, 0)); + inbound.push('hi'); + inbound.close(); + await run; + expect(sent).toEqual(['echo:hi']); + }); + + it('closes 1008 on an unknown ws path', async () => { + const { socket } = fakeSocket(); + let closedCode: number | undefined; + socket.close = (c) => { + closedCode = c; + }; + const req: WsRequest = { url: '/rt/nope', headers: {}, protocol: 'http', ip: '' }; + await app.upgrade(req, socket); + expect(closedCode).toBe(1008); + }); +});