-
-
Notifications
You must be signed in to change notification settings - Fork 133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(MockHttpSocket): handle response stream errors #548
Merged
kettanaito
merged 15 commits into
feat/yet-another-socket-interceptor
from
fix/forward-stream-error
Apr 17, 2024
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
a192a3a
fix(MockHttpSocket): handle response stream errors
kettanaito 3510477
test: ensure response/end are not emitted
kettanaito 69679a7
fix: flush response headers
kettanaito 60f0f27
Merge branch 'feat/yet-another-socket-interceptor' into fix/forward-s…
kettanaito a36b790
Merge branch 'feat/yet-another-socket-interceptor' into fix/forward-s…
kettanaito 8f84796
feat: handle response stream errors as 500 responses
kettanaito 41a661f
Merge branch 'feat/yet-another-socket-interceptor' into fix/forward-s…
kettanaito 07834f1
fix(MockHttpSocket): translate unhandled errors to 500 responses
kettanaito 84fca0e
fix: handle interceptor errors as 500 responses
kettanaito 22dedf5
test: fix miniflare test
kettanaito 194c9c8
fix: allow node-like errors
kettanaito e93cef2
chore: merge with the existing test
kettanaito 9f04c0e
Merge branch 'main' into fix/forward-stream-error
kettanaito 48f3338
fix(MockHttpSocket): treat all response stream errors as 500 responses
kettanaito 700212c
Merge branch 'feat/yet-another-socket-interceptor' into fix/forward-s…
kettanaito File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,7 +14,10 @@ import { isPropertyAccessible } from '../../utils/isPropertyAccessible' | |
import { baseUrlFromConnectionOptions } from '../Socket/utils/baseUrlFromConnectionOptions' | ||
import { parseRawHeaders } from '../Socket/utils/parseRawHeaders' | ||
import { getRawFetchHeaders } from '../../utils/getRawFetchHeaders' | ||
import { RESPONSE_STATUS_CODES_WITHOUT_BODY } from '../../utils/responseUtils' | ||
import { | ||
createServerErrorResponse, | ||
RESPONSE_STATUS_CODES_WITHOUT_BODY, | ||
} from '../../utils/responseUtils' | ||
import { createRequestId } from '../../createRequestId' | ||
|
||
type HttpConnectionOptions = any | ||
|
@@ -248,34 +251,41 @@ export class MockHttpSocket extends MockSocket { | |
} | ||
|
||
if (response.body) { | ||
const reader = response.body.getReader() | ||
|
||
while (true) { | ||
const { done, value } = await reader.read() | ||
|
||
if (done) { | ||
break | ||
} | ||
|
||
// Flush the headers upon the first chunk in the stream. | ||
// This ensures the consumer will start receiving the response | ||
// as it streams in (subsequent chunks are pushed). | ||
if (httpHeaders.length > 0) { | ||
flushHeaders(value) | ||
continue | ||
try { | ||
const reader = response.body.getReader() | ||
|
||
while (true) { | ||
const { done, value } = await reader.read() | ||
|
||
if (done) { | ||
break | ||
} | ||
|
||
// Flush the headers upon the first chunk in the stream. | ||
// This ensures the consumer will start receiving the response | ||
// as it streams in (subsequent chunks are pushed). | ||
if (httpHeaders.length > 0) { | ||
flushHeaders(value) | ||
continue | ||
} | ||
|
||
// Subsequent body chukns are push to the stream. | ||
this.push(value) | ||
} | ||
} catch (error) { | ||
// Coerce response stream errors to 500 responses. | ||
// Don't flush the original response headers because | ||
// unhandled errors translate to 500 error responses forcefully. | ||
this.respondWith(createServerErrorResponse(error)) | ||
|
||
// Subsequent body chukns are push to the stream. | ||
this.push(value) | ||
return | ||
} | ||
} | ||
|
||
// If the headers were not flushed up to this point, | ||
// this means the response either had no body or had | ||
// an empty body stream. Flush the headers. | ||
if (httpHeaders.length > 0) { | ||
flushHeaders() | ||
} | ||
flushHeaders() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's safe to call |
||
|
||
// Close the socket if the connection wasn't marked as keep-alive. | ||
if (!this.shouldKeepAlive) { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
test/modules/http/response/http-response-readable-stream.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
/** | ||
* @vitest-environment node | ||
*/ | ||
import { vi, it, expect, beforeAll, afterEach, afterAll } from 'vitest' | ||
import { performance } from 'node:perf_hooks' | ||
import http from 'node:http' | ||
import https from 'node:https' | ||
import { DeferredPromise } from '@open-draft/deferred-promise' | ||
import { ClientRequestInterceptor } from '../../../../src/interceptors/ClientRequest' | ||
import { sleep, waitForClientRequest } from '../../../helpers' | ||
|
||
type ResponseChunks = Array<{ buffer: Buffer; timestamp: number }> | ||
|
||
const encoder = new TextEncoder() | ||
|
||
const interceptor = new ClientRequestInterceptor() | ||
|
||
beforeAll(async () => { | ||
interceptor.apply() | ||
}) | ||
|
||
afterEach(() => { | ||
interceptor.removeAllListeners() | ||
}) | ||
|
||
afterAll(async () => { | ||
interceptor.dispose() | ||
}) | ||
|
||
it('supports ReadableStream as a mocked response', async () => { | ||
const encoder = new TextEncoder() | ||
interceptor.once('request', ({ request }) => { | ||
const stream = new ReadableStream({ | ||
start(controller) { | ||
controller.enqueue(encoder.encode('hello')) | ||
controller.enqueue(encoder.encode(' ')) | ||
controller.enqueue(encoder.encode('world')) | ||
controller.close() | ||
}, | ||
}) | ||
request.respondWith(new Response(stream)) | ||
}) | ||
|
||
const request = http.get('http://example.com/resource') | ||
const { text } = await waitForClientRequest(request) | ||
expect(await text()).toBe('hello world') | ||
}) | ||
|
||
it('supports delays when enqueuing chunks', async () => { | ||
interceptor.once('request', ({ request }) => { | ||
const stream = new ReadableStream({ | ||
async start(controller) { | ||
controller.enqueue(encoder.encode('first')) | ||
await sleep(200) | ||
|
||
controller.enqueue(encoder.encode('second')) | ||
await sleep(200) | ||
|
||
controller.enqueue(encoder.encode('third')) | ||
await sleep(200) | ||
|
||
controller.close() | ||
}, | ||
}) | ||
|
||
request.respondWith( | ||
new Response(stream, { | ||
headers: { | ||
'Content-Type': 'text/event-stream', | ||
}, | ||
}) | ||
) | ||
}) | ||
|
||
const responseChunksPromise = new DeferredPromise<ResponseChunks>() | ||
|
||
const request = https.get('https://api.example.com/stream', (response) => { | ||
const chunks: ResponseChunks = [] | ||
|
||
response | ||
.on('data', (data) => { | ||
chunks.push({ | ||
buffer: Buffer.from(data), | ||
timestamp: performance.now(), | ||
}) | ||
}) | ||
.on('end', () => { | ||
responseChunksPromise.resolve(chunks) | ||
}) | ||
.on('error', responseChunksPromise.reject) | ||
}) | ||
|
||
request.on('error', responseChunksPromise.reject) | ||
|
||
const responseChunks = await responseChunksPromise | ||
const textChunks = responseChunks.map((chunk) => { | ||
return chunk.buffer.toString('utf8') | ||
}) | ||
expect(textChunks).toEqual(['first', 'second', 'third']) | ||
|
||
// Ensure that the chunks were sent over time, | ||
// respecting the delay set in the mocked stream. | ||
const chunkTimings = responseChunks.map((chunk) => chunk.timestamp) | ||
expect(chunkTimings[1] - chunkTimings[0]).toBeGreaterThanOrEqual(150) | ||
expect(chunkTimings[2] - chunkTimings[1]).toBeGreaterThanOrEqual(150) | ||
}) | ||
|
||
it('forwards ReadableStream errors to the request', async () => { | ||
const requestErrorListener = vi.fn() | ||
const responseErrorListener = vi.fn() | ||
|
||
interceptor.once('request', ({ request }) => { | ||
const stream = new ReadableStream({ | ||
start(controller) { | ||
controller.enqueue(new TextEncoder().encode('original')) | ||
queueMicrotask(() => { | ||
controller.error(new Error('stream error')) | ||
}) | ||
}, | ||
}) | ||
request.respondWith(new Response(stream)) | ||
}) | ||
|
||
const request = http.get('http://localhost/resource') | ||
request.on('error', requestErrorListener) | ||
request.on('response', (response) => { | ||
response.on('error', responseErrorListener) | ||
}) | ||
|
||
const response = await vi.waitFor(() => { | ||
return new Promise<http.IncomingMessage>((resolve) => { | ||
request.on('response', resolve) | ||
}) | ||
}) | ||
|
||
// Response stream errors are translated to unhandled exceptions, | ||
// and then the server decides how to handle them. This is often | ||
// done as returning a 500 response. | ||
expect(response.statusCode).toBe(500) | ||
expect(response.statusMessage).toBe('Unhandled Exception') | ||
|
||
// Response stream errors are not request errors. | ||
expect(requestErrorListener).not.toHaveBeenCalled() | ||
expect(request.destroyed).toBe(false) | ||
}) |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Treating all the response stream errors as 500 error responses! Consistency.