Repository navigation
http-transport: cork backpressure, x-forwarded-proto precedence, payload 400, GET Accept #267
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
90856f7
http-transport: fix cork backpressure, x-forwarded-proto precedence, …
denny-il 7ddbb19
http-transport: deterministic unit tests for chunked-stream writable …
denny-il 2a2e9b2
http-transport: cancel pending body read on client abort in chunked s…
denny-il 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 hidden or 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 hidden or 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 hidden or 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,263 @@ | ||
| import { setTimeout as delay } from 'node:timers/promises' | ||
|
|
||
| import { BaseServerFormat, ProtocolFormats } from '@nmtjs/protocol/server' | ||
| import { describe, expect, it, vi } from 'vitest' | ||
|
|
||
| import type { HttpTransportServerRequest } from '../src/types.ts' | ||
| import { handleChunkedStream, HttpTransport } from '../src/runtimes/node.ts' | ||
|
|
||
| class TestJsonFormat extends BaseServerFormat { | ||
| accept = ['application/json'] | ||
| contentType = 'application/json' | ||
|
|
||
| encode(data: unknown): ArrayBufferView { | ||
| return new TextEncoder().encode(JSON.stringify(data)) | ||
| } | ||
|
|
||
| encodeRPC(data: unknown): ArrayBufferView { | ||
| return this.encode(data) | ||
| } | ||
|
|
||
| encodeBlob(): unknown { | ||
| return null | ||
| } | ||
|
|
||
| decode(buffer: ArrayBufferView): any { | ||
| return JSON.parse( | ||
| new TextDecoder().decode( | ||
| new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength), | ||
| ), | ||
| ) | ||
| } | ||
|
|
||
| decodeRPC(buffer: ArrayBufferView): any { | ||
| return this.decode(buffer) | ||
| } | ||
| } | ||
|
|
||
| async function startServer(onRpc?: (...args: any[]) => Promise<unknown>) { | ||
| const format = new TestJsonFormat() | ||
| const connection = { | ||
| encoder: format, | ||
| decoder: format, | ||
| [Symbol.asyncDispose]: () => Promise.resolve(), | ||
| } | ||
| const requests: HttpTransportServerRequest[] = [] | ||
| const params = { | ||
| formats: new ProtocolFormats([format]), | ||
| onConnect: vi.fn(async (options: { data: unknown }) => { | ||
| requests.push(options.data as HttpTransportServerRequest) | ||
| return connection | ||
| }), | ||
| resolve: async () => ({ meta: { get: () => ['get', 'post'] } }), | ||
| onRpc: onRpc ?? (async () => ({ ok: true })), | ||
| onDisconnect: async () => {}, | ||
| onMessage: async () => {}, | ||
| } | ||
|
|
||
| const worker = await HttpTransport.factory({ | ||
| listen: { port: 0, hostname: '127.0.0.1' }, | ||
| }) | ||
| const url = await worker.start(params as any) | ||
|
|
||
| return { | ||
| url, | ||
| requests, | ||
| stop: () => worker.stop(params as any), | ||
| } | ||
| } | ||
|
|
||
| describe('node runtime adapter', () => { | ||
| describe('x-forwarded-proto', () => { | ||
| it('uses http when the header says http', async () => { | ||
| const { url, requests, stop } = await startServer() | ||
| try { | ||
| const response = await fetch(`${url}/test`, { | ||
| headers: { 'x-forwarded-proto': 'http' }, | ||
| }) | ||
| expect(response.status).toBe(200) | ||
| expect(requests[0]?.url.protocol).toBe('http:') | ||
| } finally { | ||
| await stop() | ||
| } | ||
| }) | ||
|
|
||
| it('uses https when the header says https', async () => { | ||
| const { url, requests, stop } = await startServer() | ||
| try { | ||
| const response = await fetch(`${url}/test`, { | ||
| headers: { 'x-forwarded-proto': 'https' }, | ||
| }) | ||
| expect(response.status).toBe(200) | ||
| expect(requests[0]?.url.protocol).toBe('https:') | ||
| } finally { | ||
| await stop() | ||
| } | ||
| }) | ||
|
|
||
| it('falls back to the listener protocol without the header', async () => { | ||
| const { url, requests, stop } = await startServer() | ||
| try { | ||
| const response = await fetch(`${url}/test`) | ||
| expect(response.status).toBe(200) | ||
| expect(requests[0]?.url.protocol).toBe('http:') | ||
| } finally { | ||
| await stop() | ||
| } | ||
| }) | ||
| }) | ||
|
|
||
| describe('chunked stream backpressure', () => { | ||
| it('pauses reading the source stream when the client does not consume', async () => { | ||
| const chunkSize = 256 * 1024 | ||
| const totalChunks = 100 | ||
| const chunk = new Uint8Array(chunkSize).fill(97) | ||
| let pulled = 0 | ||
|
|
||
| const { url, stop } = await startServer(async () => { | ||
| // no content-length header -> exercises the chunked write path | ||
| const stream = new ReadableStream<Uint8Array>({ | ||
| pull(controller) { | ||
| pulled++ | ||
| controller.enqueue(chunk) | ||
| if (pulled >= totalChunks) controller.close() | ||
| }, | ||
| }) | ||
| return new Response(stream) | ||
| }) | ||
|
|
||
| try { | ||
| const response = await fetch(`${url}/test`) | ||
| expect(response.status).toBe(200) | ||
|
|
||
| // give the server time to push as much as buffers allow while the | ||
| // client is not reading the body yet | ||
| await delay(500) | ||
| expect(pulled).toBeLessThan(totalChunks) | ||
|
|
||
| const body = new Uint8Array(await response.arrayBuffer()) | ||
| expect(pulled).toBe(totalChunks) | ||
| expect(body.byteLength).toBe(chunkSize * totalChunks) | ||
| } finally { | ||
| await stop() | ||
| } | ||
| }) | ||
| }) | ||
|
|
||
| describe('handleChunkedStream writable dispatcher', () => { | ||
| // scripted stand-in for uWS HttpResponse: only the first onWritable | ||
| // registration takes effect, matching real uWS behavior | ||
| function createResDouble(writeResults: boolean[]) { | ||
| const results = [...writeResults] | ||
| let writes = 0 | ||
| let ends = 0 | ||
| let registrations = 0 | ||
| let handler: ((offset: number) => boolean) | undefined | ||
| const res: any = { | ||
| aborted: false, | ||
| wakeWritable: undefined, | ||
| cork(cb: () => void) { | ||
| cb() | ||
| return res | ||
| }, | ||
| write() { | ||
| writes++ | ||
| return results.length > 0 ? (results.shift() as boolean) : true | ||
| }, | ||
| end() { | ||
| ends++ | ||
| return res | ||
| }, | ||
| onWritable(h: (offset: number) => boolean) { | ||
| registrations++ | ||
| handler ??= h | ||
| return res | ||
| }, | ||
| } | ||
| return { | ||
| res, | ||
| fireWritable: () => handler!(0), | ||
| counts: () => ({ writes, ends, registrations }), | ||
| abort: () => { | ||
| res.aborted = true | ||
| res.wakeWritable?.() | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| const chunks = (n: number) => | ||
| new ReadableStream<Uint8Array>({ | ||
| start(controller) { | ||
| for (let i = 0; i < n; i++) controller.enqueue(new Uint8Array(8)) | ||
| controller.close() | ||
| }, | ||
| }) | ||
|
|
||
| const tick = () => new Promise((resolve) => setImmediate(resolve)) | ||
|
|
||
| it('resumes exactly one pending waiter per drain across cycles', async () => { | ||
| const double = createResDouble([false, true, false, true]) | ||
| const pump = handleChunkedStream(double.res, chunks(4)) | ||
|
|
||
| await tick() | ||
| expect(double.counts()).toEqual({ writes: 1, ends: 0, registrations: 1 }) | ||
|
|
||
| double.fireWritable() | ||
| await tick() | ||
| // resumed once: write 2 succeeded, write 3 hit backpressure again and | ||
| // parked a second waiter without re-registering the handler | ||
| expect(double.counts()).toEqual({ writes: 3, ends: 0, registrations: 1 }) | ||
|
|
||
| double.fireWritable() | ||
| await tick() | ||
| await pump | ||
| expect(double.counts()).toEqual({ writes: 4, ends: 1, registrations: 1 }) | ||
| }) | ||
|
|
||
| it('writable callback without a pending waiter is a no-op returning true', async () => { | ||
| const double = createResDouble([false]) | ||
| const pump = handleChunkedStream(double.res, chunks(1)) | ||
|
|
||
| await tick() | ||
| expect(double.fireWritable()).toBe(true) | ||
| await tick() | ||
| await pump | ||
|
|
||
| // stream is finished; a late drain event finds no waiter | ||
| expect(() => double.fireWritable()).not.toThrow() | ||
| expect(double.fireWritable()).toBe(true) | ||
| }) | ||
|
|
||
| it('abort while a waiter is pending settles the wait and exits the pump', async () => { | ||
| const double = createResDouble([false]) | ||
| const body = chunks(2) | ||
| const pump = handleChunkedStream(double.res, body) | ||
|
|
||
| await tick() | ||
| expect(double.counts().writes).toBe(1) | ||
|
|
||
| double.abort() | ||
| await expect(pump).rejects.toThrow('Response aborted') | ||
| expect(double.counts()).toEqual({ writes: 1, ends: 0, registrations: 1 }) | ||
| // reader lock is released on exit | ||
| expect(() => body.getReader()).not.toThrow() | ||
| }) | ||
|
|
||
| it('handles a drain cycle followed by an abort', async () => { | ||
| const double = createResDouble([false, false]) | ||
| const pump = handleChunkedStream(double.res, chunks(3)) | ||
|
|
||
| await tick() | ||
| expect(double.counts().writes).toBe(1) | ||
|
|
||
| double.fireWritable() | ||
| await tick() | ||
| // resumed and immediately backpressured again | ||
| expect(double.counts().writes).toBe(2) | ||
|
|
||
| double.abort() | ||
| await expect(pump).rejects.toThrow('Response aborted') | ||
| expect(double.counts()).toEqual({ writes: 2, ends: 0, registrations: 1 }) | ||
| }) | ||
| }) | ||
| }) |
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.
Uh oh!
There was an error while loading. Please reload this page.