|
| 1 | +import { Readable, Writable } from 'node:stream' |
| 2 | +import { invariant } from 'outvariant' |
| 3 | +import { Interceptor, INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor' |
| 4 | +import { type HttpRequestEventMap } from '../../glossary' |
| 5 | +import { FetchResponse } from '../../utils/fetchUtils' |
| 6 | +import { SocketInterceptor } from './index' |
| 7 | +import { HttpRequestParser } from './parsers' |
| 8 | +import { baseUrlFromConnectionOptions } from '../Socket/utils/baseUrlFromConnectionOptions' |
| 9 | +import { NetworkConnectionOptions } from './utils/normalize-net-connect-args' |
| 10 | +import { createRequestId } from '../../createRequestId' |
| 11 | +import { emitAsync } from 'src/utils/emitAsync' |
| 12 | +import { RequestController } from '../../RequestController' |
| 13 | +import { handleRequest } from '../../utils/handleRequest' |
| 14 | + |
| 15 | +function toBuffer(data: any, encoding?: BufferEncoding): Buffer { |
| 16 | + return Buffer.isBuffer(data) ? data : Buffer.from(data, encoding) |
| 17 | +} |
| 18 | + |
| 19 | +export class HttpRequestInterceptor extends Interceptor<HttpRequestEventMap> { |
| 20 | + static symbol = Symbol('HttpRequestInterceptor') |
| 21 | + |
| 22 | + constructor() { |
| 23 | + super(HttpRequestInterceptor.symbol) |
| 24 | + } |
| 25 | + |
| 26 | + public setup() { |
| 27 | + /** @fixme Use interceptor as a singleton? */ |
| 28 | + const interceptor = new SocketInterceptor() |
| 29 | + interceptor.apply() |
| 30 | + |
| 31 | + interceptor.on('socket', ({ options, socket }) => { |
| 32 | + socket.once('write', (chunk, encoding) => { |
| 33 | + const firstFrame = chunk.toString() |
| 34 | + |
| 35 | + /** |
| 36 | + * @fixme This is obviously rather naive |
| 37 | + */ |
| 38 | + if (firstFrame.includes('HTTP/1.1')) { |
| 39 | + const method = firstFrame.split(' ')[0] |
| 40 | + |
| 41 | + const requestParser = createHttpRequestParserStream({ |
| 42 | + requestOptions: { |
| 43 | + method, |
| 44 | + ...options, |
| 45 | + }, |
| 46 | + onRequest: async ({ request }) => { |
| 47 | + console.log(1) |
| 48 | + |
| 49 | + const requestId = createRequestId() |
| 50 | + const controller = new RequestController(request) |
| 51 | + |
| 52 | + const isRequestHandled = await handleRequest({ |
| 53 | + request, |
| 54 | + requestId, |
| 55 | + controller, |
| 56 | + emitter: this.emitter, |
| 57 | + onResponse(response) { |
| 58 | + console.log('MOCKED!', response.status) |
| 59 | + }, |
| 60 | + onRequestError(response) { |
| 61 | + // |
| 62 | + }, |
| 63 | + onError(error) {}, |
| 64 | + }) |
| 65 | + |
| 66 | + console.log('REQ! handled?', isRequestHandled) |
| 67 | + |
| 68 | + if (!isRequestHandled) { |
| 69 | + // return socket.passthrough() |
| 70 | + } |
| 71 | + }, |
| 72 | + }) |
| 73 | + requestParser.write(toBuffer(chunk, encoding)) |
| 74 | + socket.pipe(requestParser) |
| 75 | + } |
| 76 | + }) |
| 77 | + }) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +function createHttpRequestParserStream(options: { |
| 82 | + requestOptions: NetworkConnectionOptions & { |
| 83 | + method: string |
| 84 | + } |
| 85 | + onRequest: (args: { request: Request }) => void |
| 86 | +}) { |
| 87 | + const requestRawHeadersBuffer: Array<string> = [] |
| 88 | + const requestWriteBuffer: Array<Buffer> = [] |
| 89 | + let requestBodyStream: Readable | undefined |
| 90 | + |
| 91 | + const parser = new HttpRequestParser({ |
| 92 | + onHeaders(rawHeaders) { |
| 93 | + requestRawHeadersBuffer.push(...rawHeaders) |
| 94 | + }, |
| 95 | + onHeadersComplete( |
| 96 | + versionMajor, |
| 97 | + versionMinor, |
| 98 | + rawHeaders, |
| 99 | + _, |
| 100 | + path, |
| 101 | + __, |
| 102 | + ___, |
| 103 | + ____, |
| 104 | + shouldKeepAlive |
| 105 | + ) { |
| 106 | + const method = options.requestOptions.method?.toUpperCase() || 'GET' |
| 107 | + const baseUrl = baseUrlFromConnectionOptions(options.requestOptions) |
| 108 | + const url = new URL(path || '', baseUrl) |
| 109 | + |
| 110 | + // const headers = FetchResponse.parseRawHeaders([ |
| 111 | + // ...requestRawHeadersBuffer, |
| 112 | + // ...(rawHeaders || []), |
| 113 | + // ]) |
| 114 | + |
| 115 | + const canHaveBody = method !== 'GET' && method !== 'HEAD' |
| 116 | + |
| 117 | + // Translate the basic authorization to request headers. |
| 118 | + // Constructing a Request instance with a URL containing auth is no-op. |
| 119 | + if (url.username || url.password) { |
| 120 | + if (!headers.has('authorization')) { |
| 121 | + headers.set('authorization', `Basic ${url.username}:${url.password}`) |
| 122 | + } |
| 123 | + url.username = '' |
| 124 | + url.password = '' |
| 125 | + } |
| 126 | + |
| 127 | + requestBodyStream = new Readable({ |
| 128 | + /** |
| 129 | + * @note Provide the `read()` method so a `Readable` could be |
| 130 | + * used as the actual request body (the stream calls "read()"). |
| 131 | + */ |
| 132 | + read() { |
| 133 | + // If the user attempts to read the request body, |
| 134 | + // flush the write buffer to trigger the callbacks. |
| 135 | + // This way, if the request stream ends in the write callback, |
| 136 | + // it will indeed end correctly. |
| 137 | + // flushWriteBuffer() |
| 138 | + }, |
| 139 | + }) |
| 140 | + |
| 141 | + const request = new Request(url, { |
| 142 | + method, |
| 143 | + // headers, |
| 144 | + credentials: 'same-origin', |
| 145 | + // @ts-expect-error Undocumented Fetch property. |
| 146 | + duplex: canHaveBody ? 'half' : undefined, |
| 147 | + body: canHaveBody ? (Readable.toWeb(requestBodyStream) as any) : null, |
| 148 | + }) |
| 149 | + |
| 150 | + options.onRequest({ |
| 151 | + request, |
| 152 | + }) |
| 153 | + }, |
| 154 | + onBody(chunk) { |
| 155 | + invariant( |
| 156 | + requestBodyStream, |
| 157 | + 'Failed to write to a request stream: stream does not exist' |
| 158 | + ) |
| 159 | + |
| 160 | + requestBodyStream.push(chunk) |
| 161 | + }, |
| 162 | + onMessageComplete() { |
| 163 | + requestBodyStream?.push(null) |
| 164 | + }, |
| 165 | + }) |
| 166 | + |
| 167 | + const parserStream = new Writable({ |
| 168 | + write(chunk, encoding, callback) { |
| 169 | + const data = toBuffer(chunk, encoding) |
| 170 | + requestWriteBuffer.push(data) |
| 171 | + parser.execute(data) |
| 172 | + callback() |
| 173 | + }, |
| 174 | + }) |
| 175 | + parserStream.once('finish', () => parser.free()) |
| 176 | + |
| 177 | + return parserStream |
| 178 | +} |
0 commit comments