Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
57 changes: 37 additions & 20 deletions packages/http-transport/src/runtimes/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const statusResponseBuffer = await statusResponse.arrayBuffer()

type UwsResponse = Parameters<
Parameters<ReturnType<typeof App>['any']>[1]
>[0] & { aborted?: boolean }
>[0] & { aborted?: boolean; wakeWritable?: () => void }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function adapterFactory(params: HttpAdapterParams<'node'>): HttpAdapterServer {
const server = params.tls
Expand Down Expand Up @@ -51,6 +51,7 @@ function adapterFactory(params: HttpAdapterParams<'node'>): HttpAdapterServer {
res.onAborted(() => {
aborted = true
uwsRes.aborted = true
uwsRes.wakeWritable?.()
requestController.abort()

try {
Expand All @@ -65,8 +66,14 @@ function adapterFactory(params: HttpAdapterParams<'node'>): HttpAdapterServer {
req.forEach((k, v) => headers.append(k, v))

const host = headers.get('host') || 'localhost'
const proto =
headers.get('x-forwarded-proto') || params.tls ? 'https' : 'http'
const forwardedProto = headers.get('x-forwarded-proto')
const proto = forwardedProto
? forwardedProto === 'https'
? 'https'
: 'http'
: params.tls
? 'https'
: 'http'
const url = new URL(req.getUrl(), `${proto}://${host}`)
url.search = req.getQuery() ? `?${req.getQuery()}` : ''
try {
Expand Down Expand Up @@ -202,19 +209,43 @@ async function handleFixedLengthStream(
}
}

async function handleChunkedStream(
// exported for tests: the waiter dispatch is timing-sensitive and needs
// deterministic coverage against a controlled response double
export async function handleChunkedStream(
res: UwsResponse,
body: ReadableStream<Uint8Array>,
): Promise<void> {
const reader = body.getReader()
// uWS honors only the first onWritable registration per response, so a
// single handler dispatches drain (and abort) events to the pending waiter
let writableHandlerRegistered = false
const waitWritable = () =>
new Promise<void>((resolve, reject) => {
if (!writableHandlerRegistered) {
writableHandlerRegistered = true
res.onWritable(() => {
res.wakeWritable?.()
return true
})
}
res.wakeWritable = () => {
res.wakeWritable = undefined
if (res.aborted) reject(new Error('Response aborted'))
else resolve()
}
})
try {
while (!res.aborted) {
const { done, value } = await reader.read()
if (done) break
if (value.byteLength === 0) continue

const ok = res.cork(() => res.write(value))
if (!ok) await waitWritable(res)
// cork() returns the response object, not write()'s backpressure flag
let ok = true
res.cork(() => {
ok = res.write(value)
})
if (!ok) await waitWritable()
}

if (!res.aborted) res.cork(() => res.end())
Expand Down Expand Up @@ -260,20 +291,6 @@ function handleFixedChunk(
})
}

function waitWritable(res: UwsResponse): Promise<void> {
return new Promise((resolve, reject) => {
res.onWritable(() => {
if (res.aborted) {
reject(new Error('Response aborted'))
return false
}

resolve()
return true
})
})
}

function getContentLength(headers: Headers): number | undefined {
const raw = headers.get('content-length')
if (!raw) return undefined
Expand Down
15 changes: 13 additions & 2 deletions packages/http-transport/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,16 @@ export class HttpTransportServer implements TransportWorker<
const isBlob = request.headers.get(NEEMATA_BLOB_HEADER) === 'true'
const contentType = request.headers.get('content-type')
const accept = request.headers.get('accept') || '*/*'
// GET endpoints are reachable via browser navigation, which sends HTML
// Accept headers; fall back to the default format only when the client's
// Accept can't be negotiated
const negotiableAccept =
canHaveBody || this.params.formats.supportsEncoder(accept)
? accept
: '*/*'

await using connection = await this.params.onConnect({
accept: canHaveBody ? accept : '*/*',
accept: negotiableAccept,
contentType: isBlob || !contentType ? '*/*' : contentType,
data: request,
protocolVersion: ProtocolVersion.v1,
Expand Down Expand Up @@ -178,7 +185,11 @@ export class HttpTransportServer implements TransportWorker<
} else {
const querystring = url.searchParams.get('payload')
if (querystring) {
payload = JSON.parse(querystring)
try {
payload = JSON.parse(querystring)
} catch {
throw new ProtocolError(ErrorCode.BadRequest, 'Invalid payload')
}
}
}

Expand Down
263 changes: 263 additions & 0 deletions packages/http-transport/tests/node-runtime.spec.ts
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 })
})
})
})
Loading
Loading