Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/interceptors/ClientRequest/MockHttpSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export class MockHttpSocket extends MockSocket {
private request?: Request
private requestParser: HTTPParser<0>
private requestStream?: Readable
private httpVersionMajor?: number
private httpVersionMinor?: number
private shouldKeepAlive?: boolean

private socketState: 'unknown' | 'mock' | 'passthrough' = 'unknown'
Expand Down Expand Up @@ -340,7 +342,20 @@ export class MockHttpSocket extends MockSocket {

// Create a `ServerResponse` instance to delegate HTTP message parsing,
// Transfer-Encoding, and other things to Node.js internals.
const serverResponse = new ServerResponse(new IncomingMessage(this))
const incomingMessage = new IncomingMessage(this)

// Set the HTTP version on the IncomingMessage.
// This is critical for Node.js to correctly allow keep alive.
// By default, nodejs sets keepalive to false if the HttpVersion is not at least
// 1.1: https://github.com/nodejs/node/blob/70f6b58ac655234435a99d72b857dd7b316d34bf/lib/_http_server.js#L211C1-L211C34
// The version should normally already have been set by the onRequestStart method
if(this.httpVersionMajor != null && this.httpVersionMinor != null) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, this is interesting! From what I gathered, this IncomingMessage was purely internal to help us handle the mock response and shouldn't influence the user-facing behaviors in any way. So you say it does?

This might be an indicator that we should consider migrating from this.

All ServerResponse does here is help us parse out the response. User-facing ClientRequest constructs its own instances, including IncomingMessage, and ours never leaks or affects the user-facing data in any way. At least, that is the intention.

incomingMessage.httpVersion = `${this.httpVersionMajor}.${this.httpVersionMinor}`
incomingMessage.httpVersionMajor = this.httpVersionMajor
incomingMessage.httpVersionMinor = this.httpVersionMinor
}

const serverResponse = new ServerResponse(incomingMessage)

/**
* Assign a mock socket instance to the server response to
Expand Down Expand Up @@ -521,6 +536,8 @@ export class MockHttpSocket extends MockSocket {
____,
shouldKeepAlive
) => {
this.httpVersionMajor = versionMajor

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A single socket instance might be reused across different requests (decided by the agent). If we decide to go with this approach, we need to reset these properties at some point (e.g. at new request start).

this.httpVersionMinor = versionMinor
this.shouldKeepAlive = shouldKeepAlive

const url = new URL(path || '', this.baseUrl)
Expand Down Expand Up @@ -641,6 +658,7 @@ export class MockHttpSocket extends MockSocket {
status,
statusText
) => {

const headers = FetchResponse.parseRawHeaders([
...this.responseRawHeadersBuffer,
...(rawHeaders || []),
Expand Down Expand Up @@ -708,4 +726,4 @@ export class MockHttpSocket extends MockSocket {
this.responseStream.push(null)
}
}
}
}
214 changes: 214 additions & 0 deletions test/modules/http/response/http-response-connection-headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/**
* @vitest-environment node
*/
import { it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import http from 'http'
import https from 'https'
import { HttpServer } from '@open-draft/test-server/http'
import { ClientRequestInterceptor } from '../../../../src/interceptors/ClientRequest'
import { waitForClientRequest } from '../../../helpers'

const httpServer = new HttpServer((app) => {
app.get('/', (_req, res) => {
res.status(200).send('response with keep-alive')
})

app.get('/stream', (_req, res) => {
res.write('chunk1')
setTimeout(() => {
res.write('chunk2')
res.end()
}, 10)
})
})

const interceptor = new ClientRequestInterceptor()

beforeAll(async () => {
interceptor.apply()
await httpServer.listen()
})

afterEach(() => {
interceptor.removeAllListeners()
})

afterAll(async () => {
interceptor.dispose()
await httpServer.close()
})

it('responds to an HTTP request with connection: keep-alive header', async () => {
interceptor.on('request', ({ controller }) => {
controller.respondWith(
new Response('mock response', {
status: 200,
headers: {
Connection: 'keep-alive',
'Content-Type': 'text/plain',
},
})
)
})

const request = http.get('http://localhost/', {
headers: {
Connection: 'keep-alive',
},
})

const { res, text } = await waitForClientRequest(request)

expect(res.statusCode).toBe(200)
expect(res.headers.connection).toBe('keep-alive')
expect(await text()).toBe('mock response')
})

it('responds to an HTTP request with connection: close header', async () => {
interceptor.on('request', ({ controller }) => {
controller.respondWith(
new Response('mock response', {
status: 200,
headers: {
Connection: 'close',
'Content-Type': 'text/plain',
},
})
)
})

const request = http.get('http://localhost/', {
headers: {
Connection: 'close',
},
})

const { res, text } = await waitForClientRequest(request)

expect(res.statusCode).toBe(200)
expect(res.headers.connection).toBe('close')
expect(await text()).toBe('mock response')
})

it('responds to an HTTP request without connection header', async () => {
interceptor.on('request', ({ controller }) => {
controller.respondWith(
new Response('mock response', {
status: 200,
headers: {
'Content-Type': 'text/plain',
},
})
)
})

const request = http.get('http://localhost/')

const { res, text } = await waitForClientRequest(request)

expect(res.statusCode).toBe(200)
expect(await text()).toBe('mock response')
})

it('responds to an HTTPS request with connection: keep-alive header', async () => {
interceptor.on('request', ({ controller }) => {
controller.respondWith(
new Response('mock response https', {
status: 200,
headers: {
Connection: 'keep-alive',
'Content-Type': 'text/plain',
},
})
)
})

const request = https.get('https://localhost/', {
headers: {
Connection: 'keep-alive',
},
})

const { res, text } = await waitForClientRequest(request)

expect(res.statusCode).toBe(200)
expect(res.headers.connection).toBe('keep-alive')
expect(await text()).toBe('mock response https')
})

it('responds to a streaming request with connection: keep-alive header', async () => {
interceptor.on('request', ({ controller }) => {
const encoder = new TextEncoder()
const stream = new ReadableStream({
start(streamController) {
streamController.enqueue(encoder.encode('chunk1'))
setTimeout(() => {
streamController.enqueue(encoder.encode('chunk2'))
streamController.close()
}, 10)
},
})

controller.respondWith(
new Response(stream, {
status: 200,
headers: {
Connection: 'keep-alive',
'Content-Type': 'text/plain',
},
})
)
})

const request = http.get('http://localhost/', {
headers: {
Connection: 'keep-alive',
},
})

const { res, text } = await waitForClientRequest(request)

expect(res.statusCode).toBe(200)
expect(res.headers.connection).toBe('keep-alive')
expect(await text()).toBe('chunk1chunk2')
})

it('handles multiple sequential requests with keep-alive', async () => {
interceptor.on('request', ({ controller }) => {
controller.respondWith(
new Response('mock response sequential', {
status: 200,
headers: {
Connection: 'keep-alive',
'Content-Type': 'text/plain',
},
})
)
})

// First request
const request1 = http.get('http://localhost/', {
headers: {
Connection: 'keep-alive',
},
})

const { res: res1, text: text1 } = await waitForClientRequest(request1)

expect(res1.statusCode).toBe(200)
expect(res1.headers.connection).toBe('keep-alive')
expect(await text1()).toBe('mock response sequential')

// Second request
const request2 = http.get('http://localhost/', {
headers: {
Connection: 'keep-alive',
},
})

const { res: res2, text: text2 } = await waitForClientRequest(request2)

expect(res2.statusCode).toBe(200)
expect(res2.headers.connection).toBe('keep-alive')
expect(await text2()).toBe('mock response sequential')
})