Skip to content

Instantly share code, notes, and snippets.

@dreamorosi
Last active May 2, 2024 17:47
Show Gist options
  • Save dreamorosi/ee40e89a065a8a4c4a334dc83f566ff0 to your computer and use it in GitHub Desktop.
Save dreamorosi/ee40e89a065a8a4c4a334dc83f566ff0 to your computer and use it in GitHub Desktop.
POC that shows how to subscribe to built-in diagnostics_channel events for the http module in Node.js - unfortunately there's no way of subscribing to error events. As of now, if the request fails after having started (i.e. `ECONNREFUSED`) the segment remains opened.
import type { ClientRequest, IncomingMessage } from 'node:http';
import { subscribe } from 'node:diagnostics_channel';
public captureHTTPsGlobal(): void {
const onRequestStart = (message: unknown): void => {
const { request } = message as { request: ClientRequest };
console.log(message);
const parentSubsegment = this.getSegment();
if (parentSubsegment && request.host) {
const subsegment = parentSubsegment.addNewSubsegment(request.host);
subsegment.addAttribute('namespace', 'remote');
(subsegment as HttpSubsegment).http = {
request: {
url: request.host,
method: request.method,
},
};
this.setSegment(subsegment);
}
};
const onResponseFinish = (message: unknown): void => {
const { response } = message as { response: IncomingMessage };
console.log(message);
const subsegment = this.getSegment();
if (isHttpSubsegment(subsegment)) {
const status = response.statusCode || 0; // TODO: when can it be undefined?
const contentLenght = response.headers['content-length'];
subsegment.http = {
...subsegment.http,
response: {
status,
...(contentLenght && {
content_length: parseInt(contentLenght),
}),
},
};
if (status === 429) {
subsegment.addThrottleFlag();
}
if (status >= 400 && status < 500) {
subsegment.addErrorFlag();
} else if (status >= 500 && status < 600) {
subsegment.addFaultFlag();
}
subsegment.close();
this.setSegment(subsegment.parent);
}
};
subscribe('http.client.request.start', onRequestStart);
subscribe('http.client.response.finish', onResponseFinish);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment