1+ /**
2+ * Local HTTP test-server harness for the RFC 10008 interop regression suite.
3+ *
4+ * Each test spins up a throwaway `node:http` server on an ephemeral port, so
5+ * the suite exercises the real wire — the real HTTP method, real headers, a
6+ * real request body — without mocking `fetch` and without touching any
7+ * external service. Node >= 20 speaks `QUERY` end to end (llhttp accepts the
8+ * method, `undici` sends it verbatim), which is what makes this possible.
9+ */
10+ import { createServer , type ServerResponse } from "node:http" ;
11+ import type { AddressInfo } from "node:net" ;
12+
13+ /** Everything the server observed about a single inbound request. */
14+ export interface RecordedRequest {
15+ /** HTTP method exactly as it arrived on the wire — never normalized. */
16+ method : string ;
17+ /** Raw request target, e.g. `/broker/query?page=2`. */
18+ rawUrl : string ;
19+ /** Request target without the query string. */
20+ path : string ;
21+ /** Raw query string without the leading `?` (empty when there is none). */
22+ search : string ;
23+ /** Inbound headers (Node lower-cases the names). */
24+ headers : Record < string , string | string [ ] | undefined > ;
25+ /** Raw request body as received (empty string when no body was sent). */
26+ rawBody : string ;
27+ /** True once the client hung up before the response was fully written. */
28+ aborted : boolean ;
29+ /** Parse {@link rawBody} as JSON. Throws when the body is not valid JSON. */
30+ json ( ) : unknown ;
31+ /** Decoded query-string pairs in wire order, preserving repeated keys. */
32+ params ( ) : Array < [ string , string ] > ;
33+ }
34+
35+ /** Handler invoked once the full request body has been received. */
36+ export type TestHandler = ( req : RecordedRequest , res : ServerResponse ) => void | Promise < void > ;
37+
38+ /** A running local test server. */
39+ export interface TestServer {
40+ /** Origin to hand to `createClient({ baseUrl })`, e.g. `http://127.0.0.1:51234`. */
41+ url : string ;
42+ /** Every request the server received, in arrival order. */
43+ requests : RecordedRequest [ ] ;
44+ /** Ordered list of HTTP methods the server actually received. */
45+ trace ( ) : string [ ] ;
46+ /** Resolves once the n-th request (1-based) has reached the handler. */
47+ received ( n ?: number ) : Promise < RecordedRequest > ;
48+ /** Shut the server down and drop any held-open connections. */
49+ close ( ) : Promise < void > ;
50+ }
51+
52+ /** Send a JSON response. No-ops when the socket is already gone. */
53+ export function respondJson (
54+ res : ServerResponse ,
55+ status : number ,
56+ body : unknown ,
57+ headers : Record < string , string > = { } ,
58+ ) : void {
59+ if ( res . writableEnded || res . destroyed ) return ;
60+ res . writeHead ( status , { "Content-Type" : "application/json" , ...headers } ) ;
61+ res . end ( JSON . stringify ( body ) ) ;
62+ }
63+
64+ /** Send a bodyless response (e.g. `304 Not Modified`). */
65+ export function respondEmpty ( res : ServerResponse , status : number , headers : Record < string , string > = { } ) : void {
66+ if ( res . writableEnded || res . destroyed ) return ;
67+ res . writeHead ( status , headers ) ;
68+ res . end ( ) ;
69+ }
70+
71+ /** Sleep without keeping the Node event loop (or the vitest worker) alive. */
72+ export function sleep ( ms : number ) : Promise < void > {
73+ return new Promise ( ( resolve ) => {
74+ const timer = setTimeout ( resolve , ms ) ;
75+ timer . unref ?.( ) ;
76+ } ) ;
77+ }
78+
79+ /**
80+ * Poll `predicate` until it turns true. Used for state the client cannot
81+ * observe synchronously — e.g. the server noticing a torn-down socket.
82+ */
83+ export async function waitFor ( predicate : ( ) => boolean , timeoutMs = 2_000 ) : Promise < void > {
84+ const deadline = Date . now ( ) + timeoutMs ;
85+ while ( ! predicate ( ) ) {
86+ if ( Date . now ( ) > deadline ) throw new Error ( `waitFor: condition not met within ${ timeoutMs } ms` ) ;
87+ await sleep ( 5 ) ;
88+ }
89+ }
90+
91+ /** Start a local HTTP server on an ephemeral port and record every request. */
92+ export async function startTestServer ( handler : TestHandler ) : Promise < TestServer > {
93+ const requests : RecordedRequest [ ] = [ ] ;
94+ let waiters : Array < { n : number ; resolve : ( req : RecordedRequest ) => void } > = [ ] ;
95+
96+ const server = createServer ( ( req , res ) => {
97+ let rawBody = "" ;
98+ req . setEncoding ( "utf8" ) ;
99+ req . on ( "data" , ( chunk : string ) => {
100+ rawBody += chunk ;
101+ } ) ;
102+ req . on ( "end" , ( ) => {
103+ const rawUrl = req . url ?? "/" ;
104+ const qIndex = rawUrl . indexOf ( "?" ) ;
105+ const search = qIndex === - 1 ? "" : rawUrl . slice ( qIndex + 1 ) ;
106+
107+ const record : RecordedRequest = {
108+ method : req . method ?? "" ,
109+ rawUrl,
110+ path : qIndex === - 1 ? rawUrl : rawUrl . slice ( 0 , qIndex ) ,
111+ search,
112+ headers : req . headers ,
113+ rawBody,
114+ aborted : false ,
115+ json : ( ) => JSON . parse ( rawBody ) as unknown ,
116+ params : ( ) => [ ...new URLSearchParams ( search ) ] ,
117+ } ;
118+
119+ // A client-side abort (timeout or AbortController) closes the socket
120+ // before the response has finished writing.
121+ res . on ( "close" , ( ) => {
122+ if ( ! res . writableFinished ) record . aborted = true ;
123+ } ) ;
124+
125+ requests . push ( record ) ;
126+ const hit = requests . length ;
127+ waiters = waiters . filter ( ( w ) => {
128+ if ( w . n > hit ) return true ;
129+ w . resolve ( record ) ;
130+ return false ;
131+ } ) ;
132+
133+ void Promise . resolve ( handler ( record , res ) ) . catch ( ( err : unknown ) => {
134+ respondJson ( res , 500 , { error : String ( err ) } ) ;
135+ } ) ;
136+ } ) ;
137+ } ) ;
138+
139+ await new Promise < void > ( ( resolve ) => server . listen ( 0 , "127.0.0.1" , resolve ) ) ;
140+ const { port } = server . address ( ) as AddressInfo ;
141+
142+ return {
143+ url : `http://127.0.0.1:${ port } ` ,
144+ requests,
145+ trace : ( ) => requests . map ( ( r ) => r . method ) ,
146+ received : ( n = 1 ) => {
147+ const existing = requests [ n - 1 ] ;
148+ if ( existing ) return Promise . resolve ( existing ) ;
149+ return new Promise < RecordedRequest > ( ( resolve ) => waiters . push ( { n, resolve } ) ) ;
150+ } ,
151+ close : ( ) =>
152+ new Promise < void > ( ( resolve ) => {
153+ server . closeAllConnections ( ) ;
154+ server . close ( ( ) => resolve ( ) ) ;
155+ } ) ,
156+ } ;
157+ }
0 commit comments