-
-
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
feat(wip): async hooks interceptor #495
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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 |
---|---|---|
@@ -0,0 +1,149 @@ | ||
import type { ClientRequest, OutgoingHttpHeaders } from 'node:http' | ||
import { createHook } from 'node:async_hooks' | ||
import { HttpRequestEventMap, Interceptor } from '../..' | ||
import { uuidv4 } from '../../utils/uuid' | ||
import { toInteractiveRequest } from '../../utils/toInteractiveRequest' | ||
|
||
export class AsyncHooksInterceptor extends Interceptor<HttpRequestEventMap> { | ||
static symbol = Symbol('AsyncHooksInterceptor') | ||
|
||
constructor() { | ||
super(AsyncHooksInterceptor.symbol) | ||
} | ||
|
||
protected setup(): void { | ||
const hook = createHook({ | ||
init: ( | ||
asyncId, | ||
type, | ||
triggerAsyncId, | ||
resource: { type: string; req: ClientRequest } | ||
) => { | ||
// process.stdout.write(type + '\n') | ||
|
||
if (type === 'HTTPCLIENTREQUEST') { | ||
const clientRequest = resource.req | ||
|
||
// console.log( | ||
// clientRequest.method, | ||
// clientRequest.host, | ||
// clientRequest.path | ||
// ) | ||
|
||
const requestId = uuidv4() | ||
const request = hastilyWrittenClientRequestToRequest(clientRequest) | ||
const { interactiveRequest, requestController } = | ||
toInteractiveRequest(request) | ||
|
||
this.emitter.emit('request', { | ||
requestId, | ||
request: interactiveRequest, | ||
}) | ||
} | ||
}, | ||
}) | ||
|
||
hook.enable() | ||
|
||
this.subscriptions.push(() => { | ||
hook.disable() | ||
}) | ||
} | ||
} | ||
|
||
function hastilyWrittenClientRequestToRequest(message: ClientRequest): Request { | ||
const url = urlFromClientRequest(message) | ||
|
||
/** | ||
* @fixme How to know the "credentials" value when using XHR? | ||
* ClientRequest doesn't have that. | ||
*/ | ||
const request = new Request(url, { | ||
method: message.method, | ||
headers: toHeaders(message.getHeaders()), | ||
duplex: 'half', | ||
body: | ||
message.method === 'HEAD' || message.method === 'GET' | ||
? null | ||
: new ReadableStream({ | ||
start(controller) { | ||
/** | ||
* @fixme Relying on Node.js internals is not nice. | ||
*/ | ||
// First, flush all request body chunks written before | ||
// the async_hooks emitted its event. | ||
const [, ...bodyWrites] = message.outputData | ||
|
||
for (const bodyWrite of bodyWrites) { | ||
/** | ||
* @note fetch request with a body writes | ||
* an empty line on body finish but empty | ||
* chunks cannot be queued to ReadableStream. | ||
*/ | ||
if (bodyWrite.data !== '') { | ||
controller.enqueue(bodyWrite.data) | ||
} | ||
} | ||
|
||
// Keep writing to the request body stream | ||
// in case the body stream is still open. | ||
message._write = (chunk, encoding, callback) => { | ||
/** | ||
* @fixme It's likely a good idea to coerce all | ||
* chunks to a Buffer and check its size. | ||
* You can technically write an empty line as | ||
* a Buffer to announce the stream end. | ||
*/ | ||
if (chunk !== '') { | ||
controller.enqueue(chunk) | ||
} | ||
|
||
callback() | ||
} | ||
|
||
message.once('finish', () => { | ||
controller.close() | ||
}) | ||
}, | ||
}), | ||
}) | ||
|
||
return request | ||
} | ||
|
||
function urlFromClientRequest(request: ClientRequest): URL { | ||
const url = new URL(`${request.protocol}//${request.host}${request.path}`) | ||
|
||
/** | ||
* ClientRequest doesn't expose the "port" anywhere. | ||
* It does contain the port in the "Host" request header. | ||
* See if that one was set, and infer the host from there. | ||
*/ | ||
const host = request.getHeader('host') | ||
|
||
if (host) { | ||
url.host = host.toString() | ||
} | ||
|
||
return url | ||
} | ||
|
||
function toHeaders(outgoingHeaders: OutgoingHttpHeaders): Headers { | ||
const headers = new Headers() | ||
|
||
for (const headerName in outgoingHeaders) { | ||
const headerValue = outgoingHeaders[headerName] | ||
|
||
if (headerValue === 'undefined') { | ||
continue | ||
} | ||
|
||
const headerValuesList = Array.prototype.concat([], headerValue) | ||
|
||
for (const value of headerValuesList) { | ||
headers.append(headerName, value.toString()) | ||
} | ||
} | ||
|
||
return headers | ||
} |
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.
Reading request body is a pain.