@opentelemetry/instrumentation-http 0.222.0-development.0 → 0.300.0-development.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +0 -2
  2. package/dist/_virtual/_rolldown/runtime.mjs +5 -0
  3. package/dist/http.cjs +425 -0
  4. package/dist/http.cjs.map +1 -0
  5. package/dist/http.d.cts +61 -0
  6. package/dist/http.d.cts.map +1 -0
  7. package/dist/http.d.mts +61 -0
  8. package/dist/http.d.mts.map +1 -0
  9. package/dist/http.mjs +425 -0
  10. package/dist/http.mjs.map +1 -0
  11. package/dist/index.cjs +3 -0
  12. package/dist/index.d.cts +3 -0
  13. package/dist/index.d.mts +3 -0
  14. package/dist/index.mjs +2 -0
  15. package/dist/internal-types.cjs +32 -0
  16. package/dist/internal-types.cjs.map +1 -0
  17. package/dist/internal-types.mjs +29 -0
  18. package/dist/internal-types.mjs.map +1 -0
  19. package/dist/semconv.cjs +18 -0
  20. package/dist/semconv.cjs.map +1 -0
  21. package/dist/semconv.mjs +17 -0
  22. package/dist/semconv.mjs.map +1 -0
  23. package/dist/types.d.cts +112 -0
  24. package/dist/types.d.cts.map +1 -0
  25. package/dist/types.d.mts +112 -0
  26. package/dist/types.d.mts.map +1 -0
  27. package/dist/utils.cjs +486 -0
  28. package/dist/utils.cjs.map +1 -0
  29. package/dist/utils.mjs +471 -0
  30. package/dist/utils.mjs.map +1 -0
  31. package/dist/version.cjs +6 -0
  32. package/dist/version.cjs.map +1 -0
  33. package/dist/version.mjs +6 -0
  34. package/dist/version.mjs.map +1 -0
  35. package/package.json +31 -21
  36. package/build/src/http.d.ts +0 -61
  37. package/build/src/http.js +0 -562
  38. package/build/src/http.js.map +0 -1
  39. package/build/src/index.d.ts +0 -3
  40. package/build/src/index.js +0 -10
  41. package/build/src/index.js.map +0 -1
  42. package/build/src/internal-types.d.ts +0 -42
  43. package/build/src/internal-types.js +0 -32
  44. package/build/src/internal-types.js.map +0 -1
  45. package/build/src/semconv.d.ts +0 -17
  46. package/build/src/semconv.js +0 -29
  47. package/build/src/semconv.js.map +0 -1
  48. package/build/src/types.d.ts +0 -115
  49. package/build/src/types.js +0 -3
  50. package/build/src/types.js.map +0 -1
  51. package/build/src/utils.d.ts +0 -105
  52. package/build/src/utils.js +0 -655
  53. package/build/src/utils.js.map +0 -1
  54. package/build/src/version.d.ts +0 -2
  55. package/build/src/version.js +0 -10
  56. package/build/src/version.js.map +0 -1
package/README.md CHANGED
@@ -61,7 +61,6 @@ Options | Type
61
61
  `ignoreOutgoingRequestHook` | `IgnoreOutgoingRequestFunction` | Function for filtering outgoing requests. HTTP instrumentation will not trace outgoing requests for which the function returns `true`.
62
62
  `disableOutgoingRequestInstrumentation` | `boolean` | Set to true to avoid instrumenting outgoing requests at all. This can be helpful when another instrumentation handles outgoing requests.
63
63
  `disableIncomingRequestInstrumentation` | `boolean` | Set to true to avoid instrumenting incoming requests at all. This can be helpful when another instrumentation handles incoming requests.
64
- `serverName` | `string` | **Deprecated.** No longer used. Stable HTTP semantic conventions do not include the `http.server_name` attribute; this option has no effect.
65
64
  `requireParentforOutgoingSpans` | Boolean | Require that is a parent span to create new span for outgoing requests.
66
65
  `requireParentforIncomingSpans` | Boolean | Require that is a parent span to create new span for incoming requests.
67
66
  `redactedQueryParams` | `string[]` | **Experimental.** Query parameter names whose values are redacted on outgoing (client) spans. Replaces the built-in list. See [Query parameter redaction](#query-parameter-redaction).
@@ -136,7 +135,6 @@ v1.23.0 semconv | Short Description
136
135
  (not included) | The size of the uncompressed response payload body after transport decoding. (In semconv v1.23.0 this is defined by `http.response.body.size`, which is experimental and opt-in.)
137
136
  no change | The matched route (path template).
138
137
  `url.scheme` | The URI scheme identifying the used protocol
139
- `server.address` | The primary server name of the matched virtual host
140
138
  `http.response.status_code` | HTTP response status code
141
139
  `url.path` and `url.query` | The URI path and query component
142
140
  `url.full` | Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`
@@ -0,0 +1,5 @@
1
+ import { createRequire } from "node:module";
2
+ //#region \0rolldown/runtime.js
3
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
4
+ //#endregion
5
+ export { __require };
package/dist/http.cjs ADDED
@@ -0,0 +1,425 @@
1
+ const require_version = require("./version.cjs");
2
+ const require_internal_types = require("./internal-types.cjs");
3
+ const require_utils = require("./utils.cjs");
4
+ let _opentelemetry_api = require("@opentelemetry/api");
5
+ let _opentelemetry_core = require("@opentelemetry/core");
6
+ let _opentelemetry_instrumentation = require("@opentelemetry/instrumentation");
7
+ let events = require("events");
8
+ let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
9
+ //#region src/http.ts
10
+ /**
11
+ * `node:http` and `node:https` instrumentation for OpenTelemetry
12
+ */
13
+ var HttpInstrumentation = class extends _opentelemetry_instrumentation.InstrumentationBase {
14
+ /** keep track on spans not ended */
15
+ _spanNotEnded = /* @__PURE__ */ new WeakSet();
16
+ _headerCapture;
17
+ _httpPatched = false;
18
+ _httpsPatched = false;
19
+ constructor(config = {}) {
20
+ super("@opentelemetry/instrumentation-http", require_version.VERSION, config);
21
+ this._headerCapture = this._createHeaderCapture();
22
+ }
23
+ _updateMetricInstruments() {
24
+ this._httpServerDurationHistogram = this.meter.createHistogram(_opentelemetry_semantic_conventions.METRIC_HTTP_SERVER_REQUEST_DURATION, {
25
+ description: "Duration of HTTP server requests.",
26
+ unit: "s",
27
+ valueType: _opentelemetry_api.ValueType.DOUBLE,
28
+ advice: { explicitBucketBoundaries: [
29
+ .005,
30
+ .01,
31
+ .025,
32
+ .05,
33
+ .075,
34
+ .1,
35
+ .25,
36
+ .5,
37
+ .75,
38
+ 1,
39
+ 2.5,
40
+ 5,
41
+ 7.5,
42
+ 10
43
+ ] }
44
+ });
45
+ this._httpClientDurationHistogram = this.meter.createHistogram(_opentelemetry_semantic_conventions.METRIC_HTTP_CLIENT_REQUEST_DURATION, {
46
+ description: "Duration of HTTP client requests.",
47
+ unit: "s",
48
+ valueType: _opentelemetry_api.ValueType.DOUBLE,
49
+ advice: { explicitBucketBoundaries: [
50
+ .005,
51
+ .01,
52
+ .025,
53
+ .05,
54
+ .075,
55
+ .1,
56
+ .25,
57
+ .5,
58
+ .75,
59
+ 1,
60
+ 2.5,
61
+ 5,
62
+ 7.5,
63
+ 10
64
+ ] }
65
+ });
66
+ }
67
+ _recordServerDuration(durationMs, attributes) {
68
+ this._httpServerDurationHistogram.record(durationMs / 1e3, attributes);
69
+ }
70
+ _recordClientDuration(durationMs, attributes) {
71
+ this._httpClientDurationHistogram.record(durationMs / 1e3, attributes);
72
+ }
73
+ setConfig(config = {}) {
74
+ super.setConfig(config);
75
+ this._headerCapture = this._createHeaderCapture();
76
+ }
77
+ init() {
78
+ return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];
79
+ }
80
+ _getHttpInstrumentation() {
81
+ return new _opentelemetry_instrumentation.InstrumentationNodeModuleDefinition("http", ["*"], (moduleExports) => {
82
+ if (this._httpPatched) return moduleExports;
83
+ this._httpPatched = true;
84
+ const isESM = moduleExports[Symbol.toStringTag] === "Module";
85
+ if (!this.getConfig().disableOutgoingRequestInstrumentation) {
86
+ const patchedRequest = this._wrap(moduleExports, "request", this._getPatchOutgoingRequestFunction("http"));
87
+ const patchedGet = this._wrap(moduleExports, "get", this._getPatchOutgoingGetFunction(patchedRequest));
88
+ if (isESM) {
89
+ moduleExports.default.request = patchedRequest;
90
+ moduleExports.default.get = patchedGet;
91
+ }
92
+ }
93
+ if (!this.getConfig().disableIncomingRequestInstrumentation) this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("http"));
94
+ return moduleExports;
95
+ }, (moduleExports) => {
96
+ this._httpPatched = false;
97
+ if (moduleExports === void 0) return;
98
+ if (!this.getConfig().disableOutgoingRequestInstrumentation) {
99
+ this._unwrap(moduleExports, "request");
100
+ this._unwrap(moduleExports, "get");
101
+ }
102
+ if (!this.getConfig().disableIncomingRequestInstrumentation) this._unwrap(moduleExports.Server.prototype, "emit");
103
+ });
104
+ }
105
+ _getHttpsInstrumentation() {
106
+ return new _opentelemetry_instrumentation.InstrumentationNodeModuleDefinition("https", ["*"], (moduleExports) => {
107
+ if (this._httpsPatched) return moduleExports;
108
+ this._httpsPatched = true;
109
+ const isESM = moduleExports[Symbol.toStringTag] === "Module";
110
+ if (!this.getConfig().disableOutgoingRequestInstrumentation) {
111
+ const patchedRequest = this._wrap(moduleExports, "request", this._getPatchHttpsOutgoingRequestFunction("https"));
112
+ const patchedGet = this._wrap(moduleExports, "get", this._getPatchHttpsOutgoingGetFunction(patchedRequest));
113
+ if (isESM) {
114
+ moduleExports.default.request = patchedRequest;
115
+ moduleExports.default.get = patchedGet;
116
+ }
117
+ }
118
+ if (!this.getConfig().disableIncomingRequestInstrumentation) this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("https"));
119
+ return moduleExports;
120
+ }, (moduleExports) => {
121
+ this._httpsPatched = false;
122
+ if (moduleExports === void 0) return;
123
+ if (!this.getConfig().disableOutgoingRequestInstrumentation) {
124
+ this._unwrap(moduleExports, "request");
125
+ this._unwrap(moduleExports, "get");
126
+ }
127
+ if (!this.getConfig().disableIncomingRequestInstrumentation) this._unwrap(moduleExports.Server.prototype, "emit");
128
+ });
129
+ }
130
+ /**
131
+ * Creates spans for incoming requests, restoring spans' context if applied.
132
+ */
133
+ _getPatchIncomingRequestFunction(component) {
134
+ return (original) => {
135
+ return this._incomingRequestFunction(component, original);
136
+ };
137
+ }
138
+ /**
139
+ * Creates spans for outgoing requests, sending spans' context for distributed
140
+ * tracing.
141
+ */
142
+ _getPatchOutgoingRequestFunction(component) {
143
+ return (original) => {
144
+ return this._outgoingRequestFunction(component, original);
145
+ };
146
+ }
147
+ _getPatchOutgoingGetFunction(clientRequest) {
148
+ return (_original) => {
149
+ return function outgoingGetRequest(options, ...args) {
150
+ const req = clientRequest(options, ...args);
151
+ req.end();
152
+ return req;
153
+ };
154
+ };
155
+ }
156
+ /** Patches HTTPS outgoing requests */
157
+ _getPatchHttpsOutgoingRequestFunction(component) {
158
+ return (original) => {
159
+ const instrumentation = this;
160
+ return function httpsOutgoingRequest(options, ...args) {
161
+ if (component === "https" && typeof options === "object" && options?.constructor?.name !== "URL") {
162
+ options = Object.assign({}, options);
163
+ instrumentation._setDefaultOptions(options);
164
+ }
165
+ return instrumentation._getPatchOutgoingRequestFunction(component)(original)(options, ...args);
166
+ };
167
+ };
168
+ }
169
+ _setDefaultOptions(options) {
170
+ options.protocol = options.protocol || "https:";
171
+ options.port = options.port || 443;
172
+ }
173
+ /** Patches HTTPS outgoing get requests */
174
+ _getPatchHttpsOutgoingGetFunction(clientRequest) {
175
+ return (original) => {
176
+ const instrumentation = this;
177
+ return function httpsOutgoingRequest(options, ...args) {
178
+ return instrumentation._getPatchOutgoingGetFunction(clientRequest)(original)(options, ...args);
179
+ };
180
+ };
181
+ }
182
+ /**
183
+ * Attach event listeners to a client request to end span and add span attributes.
184
+ *
185
+ * @param request The original request object.
186
+ * @param span representing the current operation
187
+ * @param startTime representing the start time of the request to calculate duration in Metric
188
+ * @param metricAttributes metric attributes for the request duration metric
189
+ */
190
+ _traceClientRequest(request, span, startTime, metricAttributes) {
191
+ if (this.getConfig().requestHook) this._callRequestHook(span, request);
192
+ /**
193
+ * Determines if the request has errored or the response has ended/errored.
194
+ */
195
+ let responseFinished = false;
196
+ request.prependListener("response", (response) => {
197
+ this._diag.debug("outgoingRequest on response()");
198
+ if (request.listenerCount("response") <= 1) response.resume();
199
+ const responseAttributes = require_utils.getOutgoingRequestAttributesOnResponse(response);
200
+ span.setAttributes(responseAttributes);
201
+ metricAttributes = Object.assign(metricAttributes, require_utils.getOutgoingStableRequestMetricAttributesOnResponse(responseAttributes));
202
+ if (this.getConfig().responseHook) this._callResponseHook(span, response);
203
+ span.setAttributes(this._headerCapture.client.captureRequestHeaders((header) => request.getHeader(header)));
204
+ span.setAttributes(this._headerCapture.client.captureResponseHeaders((header) => response.headers[header]));
205
+ _opentelemetry_api.context.bind(_opentelemetry_api.context.active(), response);
206
+ const endHandler = () => {
207
+ this._diag.debug("outgoingRequest on end()");
208
+ if (responseFinished) return;
209
+ responseFinished = true;
210
+ let status;
211
+ if (response.aborted && !response.complete) status = { code: _opentelemetry_api.SpanStatusCode.ERROR };
212
+ else {
213
+ status = { code: require_utils.parseResponseStatus(_opentelemetry_api.SpanKind.CLIENT, response.statusCode) };
214
+ const errorType = require_utils.parseErrorType(_opentelemetry_api.SpanKind.CLIENT, response.statusCode);
215
+ if (errorType !== void 0) span.setAttribute(_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE, errorType);
216
+ }
217
+ span.setStatus(status);
218
+ if (this.getConfig().applyCustomAttributesOnSpan) (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request, response), () => {}, true);
219
+ this._closeHttpSpan(span, _opentelemetry_api.SpanKind.CLIENT, startTime, metricAttributes);
220
+ };
221
+ response.on("end", endHandler);
222
+ response.on(events.errorMonitor, (error) => {
223
+ this._diag.debug("outgoingRequest on error()", error);
224
+ if (responseFinished) return;
225
+ responseFinished = true;
226
+ this._onOutgoingRequestError(span, metricAttributes, startTime, error);
227
+ });
228
+ });
229
+ request.on("close", () => {
230
+ this._diag.debug("outgoingRequest on request close()");
231
+ if (request.aborted || responseFinished) return;
232
+ responseFinished = true;
233
+ this._closeHttpSpan(span, _opentelemetry_api.SpanKind.CLIENT, startTime, metricAttributes);
234
+ });
235
+ request.on(events.errorMonitor, (error) => {
236
+ this._diag.debug("outgoingRequest on request error()", error);
237
+ if (responseFinished) return;
238
+ responseFinished = true;
239
+ this._onOutgoingRequestError(span, metricAttributes, startTime, error);
240
+ });
241
+ this._diag.debug("http.ClientRequest return request");
242
+ return request;
243
+ }
244
+ _incomingRequestFunction(component, original) {
245
+ const instrumentation = this;
246
+ return function incomingRequest(event, ...args) {
247
+ if (event !== "request") return original.apply(this, [event, ...args]);
248
+ const request = args[0];
249
+ const response = args[1];
250
+ const method = request.method || "GET";
251
+ instrumentation._diag.debug(`${component} instrumentation incomingRequest`);
252
+ if ((0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreIncomingRequestHook?.(request), (e) => {
253
+ if (e != null) instrumentation._diag.error("caught ignoreIncomingRequestHook error: ", e);
254
+ }, true)) return _opentelemetry_api.context.with((0, _opentelemetry_core.suppressTracing)(_opentelemetry_api.context.active()), () => {
255
+ _opentelemetry_api.context.bind(_opentelemetry_api.context.active(), request);
256
+ _opentelemetry_api.context.bind(_opentelemetry_api.context.active(), response);
257
+ return original.apply(this, [event, ...args]);
258
+ });
259
+ const headers = request.headers;
260
+ const spanAttributes = require_utils.getIncomingRequestAttributes(request, {
261
+ component,
262
+ hookAttributes: instrumentation._callStartSpanHook(request, instrumentation.getConfig().startIncomingSpanHook),
263
+ enableSyntheticSourceDetection: instrumentation.getConfig().enableSyntheticSourceDetection || false,
264
+ redactedQueryParams: instrumentation.getConfig().redactedQueryParamsServer ?? Array.from(require_internal_types.DEFAULT_QUERY_STRINGS_TO_REDACT)
265
+ }, instrumentation._diag);
266
+ Object.assign(spanAttributes, instrumentation._headerCapture.server.captureRequestHeaders((header) => request.headers[header]));
267
+ const spanOptions = {
268
+ kind: _opentelemetry_api.SpanKind.SERVER,
269
+ attributes: spanAttributes
270
+ };
271
+ const startTime = (0, _opentelemetry_core.hrTime)();
272
+ const metricAttributes = {
273
+ [_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: spanAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD],
274
+ [_opentelemetry_semantic_conventions.ATTR_URL_SCHEME]: spanAttributes[_opentelemetry_semantic_conventions.ATTR_URL_SCHEME]
275
+ };
276
+ if (spanAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION]) metricAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION];
277
+ const ctx = _opentelemetry_api.propagation.extract(_opentelemetry_api.ROOT_CONTEXT, headers);
278
+ const span = instrumentation._startHttpSpan(method, spanOptions, ctx);
279
+ const rpcMetadata = {
280
+ type: _opentelemetry_core.RPCType.HTTP,
281
+ span
282
+ };
283
+ return _opentelemetry_api.context.with((0, _opentelemetry_core.setRPCMetadata)(_opentelemetry_api.trace.setSpan(ctx, span), rpcMetadata), () => {
284
+ _opentelemetry_api.context.bind(_opentelemetry_api.context.active(), request);
285
+ _opentelemetry_api.context.bind(_opentelemetry_api.context.active(), response);
286
+ if (instrumentation.getConfig().requestHook) instrumentation._callRequestHook(span, request);
287
+ if (instrumentation.getConfig().responseHook) instrumentation._callResponseHook(span, response);
288
+ let hasError = false;
289
+ response.on("close", () => {
290
+ if (hasError) return;
291
+ instrumentation._onServerResponseFinish(request, response, span, metricAttributes, startTime);
292
+ });
293
+ response.on(events.errorMonitor, (err) => {
294
+ hasError = true;
295
+ instrumentation._onServerResponseError(span, metricAttributes, startTime, err);
296
+ });
297
+ return (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => original.apply(this, [event, ...args]), (error) => {
298
+ if (error) {
299
+ instrumentation._onServerResponseError(span, metricAttributes, startTime, error);
300
+ throw error;
301
+ }
302
+ });
303
+ });
304
+ };
305
+ }
306
+ _outgoingRequestFunction(component, original) {
307
+ const instrumentation = this;
308
+ return function outgoingRequest(options, ...args) {
309
+ if (!require_utils.isValidOptionsType(options)) return original.apply(this, [options, ...args]);
310
+ const extraOptions = typeof args[0] === "object" && (typeof options === "string" || require_utils.isURLLike(options)) ? args.shift() : void 0;
311
+ const { method, invalidUrl, optionsParsed } = require_utils.getRequestInfo(instrumentation._diag, options, extraOptions);
312
+ if ((0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreOutgoingRequestHook?.(optionsParsed), (e) => {
313
+ if (e != null) instrumentation._diag.error("caught ignoreOutgoingRequestHook error: ", e);
314
+ }, true)) return original.apply(this, [optionsParsed, ...args]);
315
+ const { hostname, port } = require_utils.extractHostnameAndPort(optionsParsed);
316
+ const attributes = require_utils.getOutgoingRequestAttributes(optionsParsed, {
317
+ component,
318
+ port,
319
+ hostname,
320
+ hookAttributes: instrumentation._callStartSpanHook(optionsParsed, instrumentation.getConfig().startOutgoingSpanHook),
321
+ redactedQueryParams: instrumentation.getConfig().redactedQueryParams
322
+ }, instrumentation.getConfig().enableSyntheticSourceDetection || false);
323
+ const startTime = (0, _opentelemetry_core.hrTime)();
324
+ const metricAttributes = {
325
+ [_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD],
326
+ [_opentelemetry_semantic_conventions.ATTR_SERVER_ADDRESS]: attributes[_opentelemetry_semantic_conventions.ATTR_SERVER_ADDRESS],
327
+ [_opentelemetry_semantic_conventions.ATTR_SERVER_PORT]: attributes[_opentelemetry_semantic_conventions.ATTR_SERVER_PORT]
328
+ };
329
+ if (attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE]) metricAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE] = attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE];
330
+ if (attributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION]) metricAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION] = attributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION];
331
+ const spanOptions = {
332
+ kind: _opentelemetry_api.SpanKind.CLIENT,
333
+ attributes
334
+ };
335
+ const span = instrumentation._startHttpSpan(method, spanOptions);
336
+ const parentContext = _opentelemetry_api.context.active();
337
+ const requestContext = _opentelemetry_api.trace.setSpan(parentContext, span);
338
+ if (!optionsParsed.headers) optionsParsed.headers = {};
339
+ else optionsParsed.headers = Object.assign({}, optionsParsed.headers);
340
+ _opentelemetry_api.propagation.inject(requestContext, optionsParsed.headers);
341
+ return _opentelemetry_api.context.with(requestContext, () => {
342
+ const cb = args[args.length - 1];
343
+ if (typeof cb === "function") args[args.length - 1] = _opentelemetry_api.context.bind(parentContext, cb);
344
+ const request = (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => {
345
+ if (invalidUrl) return original.apply(this, [options, ...args]);
346
+ else return original.apply(this, [optionsParsed, ...args]);
347
+ }, (error) => {
348
+ if (error) {
349
+ instrumentation._onOutgoingRequestError(span, metricAttributes, startTime, error);
350
+ throw error;
351
+ }
352
+ });
353
+ instrumentation._diag.debug(`${component} instrumentation outgoingRequest`);
354
+ _opentelemetry_api.context.bind(parentContext, request);
355
+ return instrumentation._traceClientRequest(request, span, startTime, metricAttributes);
356
+ });
357
+ };
358
+ }
359
+ _onServerResponseFinish(request, response, span, metricAttributes, startTime) {
360
+ const attributes = require_utils.getIncomingRequestAttributesOnResponse(response);
361
+ metricAttributes = Object.assign(metricAttributes, require_utils.getIncomingStableRequestMetricAttributesOnResponse(attributes));
362
+ span.setAttributes(this._headerCapture.server.captureResponseHeaders((header) => response.getHeader(header)));
363
+ span.setAttributes(attributes).setStatus({ code: require_utils.parseResponseStatus(_opentelemetry_api.SpanKind.SERVER, response.statusCode) });
364
+ const errorType = require_utils.parseErrorType(_opentelemetry_api.SpanKind.SERVER, response.statusCode);
365
+ if (errorType !== void 0) span.setAttribute(_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE, errorType);
366
+ const route = attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_ROUTE];
367
+ if (route) span.updateName(`${request.method || "GET"} ${route}`);
368
+ if (this.getConfig().applyCustomAttributesOnSpan) (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request, response), () => {}, true);
369
+ this._closeHttpSpan(span, _opentelemetry_api.SpanKind.SERVER, startTime, metricAttributes);
370
+ }
371
+ _onOutgoingRequestError(span, metricAttributes, startTime, error) {
372
+ require_utils.setSpanWithError(span, error);
373
+ metricAttributes[_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE] = error.name;
374
+ this._closeHttpSpan(span, _opentelemetry_api.SpanKind.CLIENT, startTime, metricAttributes);
375
+ }
376
+ _onServerResponseError(span, metricAttributes, startTime, error) {
377
+ require_utils.setSpanWithError(span, error);
378
+ metricAttributes[_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE] = error.name;
379
+ this._closeHttpSpan(span, _opentelemetry_api.SpanKind.SERVER, startTime, metricAttributes);
380
+ }
381
+ _startHttpSpan(name, options, ctx = _opentelemetry_api.context.active()) {
382
+ const requireParent = options.kind === _opentelemetry_api.SpanKind.CLIENT ? this.getConfig().requireParentforOutgoingSpans : this.getConfig().requireParentforIncomingSpans;
383
+ let span;
384
+ const currentSpan = _opentelemetry_api.trace.getSpan(ctx);
385
+ if (requireParent === true && (!currentSpan || !_opentelemetry_api.trace.isSpanContextValid(currentSpan.spanContext()))) span = _opentelemetry_api.trace.wrapSpanContext(_opentelemetry_api.INVALID_SPAN_CONTEXT);
386
+ else if (requireParent === true && currentSpan?.spanContext().isRemote) span = currentSpan;
387
+ else span = this.tracer.startSpan(name, options, ctx);
388
+ this._spanNotEnded.add(span);
389
+ return span;
390
+ }
391
+ _closeHttpSpan(span, spanKind, startTime, metricAttributes) {
392
+ if (!this._spanNotEnded.has(span)) return;
393
+ span.end();
394
+ this._spanNotEnded.delete(span);
395
+ const duration = (0, _opentelemetry_core.hrTimeToMilliseconds)((0, _opentelemetry_core.hrTimeDuration)(startTime, (0, _opentelemetry_core.hrTime)()));
396
+ if (spanKind === _opentelemetry_api.SpanKind.SERVER) this._recordServerDuration(duration, metricAttributes);
397
+ else if (spanKind === _opentelemetry_api.SpanKind.CLIENT) this._recordClientDuration(duration, metricAttributes);
398
+ }
399
+ _callResponseHook(span, response) {
400
+ (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => this.getConfig().responseHook(span, response), () => {}, true);
401
+ }
402
+ _callRequestHook(span, request) {
403
+ (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => this.getConfig().requestHook(span, request), () => {}, true);
404
+ }
405
+ _callStartSpanHook(request, hookFunc) {
406
+ if (typeof hookFunc === "function") return (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => hookFunc(request), () => {}, true);
407
+ }
408
+ _createHeaderCapture() {
409
+ const config = this.getConfig();
410
+ return {
411
+ client: {
412
+ captureRequestHeaders: require_utils.headerCapture("request", config.headersToSpanAttributes?.client?.requestHeaders ?? []),
413
+ captureResponseHeaders: require_utils.headerCapture("response", config.headersToSpanAttributes?.client?.responseHeaders ?? [])
414
+ },
415
+ server: {
416
+ captureRequestHeaders: require_utils.headerCapture("request", config.headersToSpanAttributes?.server?.requestHeaders ?? []),
417
+ captureResponseHeaders: require_utils.headerCapture("response", config.headersToSpanAttributes?.server?.responseHeaders ?? [])
418
+ }
419
+ };
420
+ }
421
+ };
422
+ //#endregion
423
+ exports.HttpInstrumentation = HttpInstrumentation;
424
+
425
+ //# sourceMappingURL=http.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.cjs","names":["InstrumentationBase","VERSION","METRIC_HTTP_SERVER_REQUEST_DURATION","ValueType","METRIC_HTTP_CLIENT_REQUEST_DURATION","InstrumentationNodeModuleDefinition","getOutgoingRequestAttributesOnResponse","getOutgoingStableRequestMetricAttributesOnResponse","context","SpanStatusCode","parseResponseStatus","SpanKind","parseErrorType","ATTR_ERROR_TYPE","errorMonitor","safeExecuteInTheMiddle","suppressTracing","getIncomingRequestAttributes","DEFAULT_QUERY_STRINGS_TO_REDACT","hrTime","ATTR_HTTP_REQUEST_METHOD","ATTR_URL_SCHEME","ATTR_NETWORK_PROTOCOL_VERSION","propagation","ROOT_CONTEXT","RPCType","setRPCMetadata","trace","isValidOptionsType","isURLLike","getRequestInfo","extractHostnameAndPort","getOutgoingRequestAttributes","ATTR_SERVER_ADDRESS","ATTR_SERVER_PORT","ATTR_HTTP_RESPONSE_STATUS_CODE","getIncomingRequestAttributesOnResponse","getIncomingStableRequestMetricAttributesOnResponse","ATTR_HTTP_ROUTE","INVALID_SPAN_CONTEXT","hrTimeToMilliseconds","hrTimeDuration","headerCapture"],"sources":["../src/http.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n HrTime,\n Span,\n SpanOptions,\n SpanStatus,\n Histogram,\n Attributes,\n} from '@opentelemetry/api';\nimport {\n context,\n INVALID_SPAN_CONTEXT,\n propagation,\n ROOT_CONTEXT,\n SpanKind,\n SpanStatusCode,\n trace,\n ValueType,\n} from '@opentelemetry/api';\nimport type { RPCMetadata } from '@opentelemetry/core';\nimport {\n hrTime,\n hrTimeDuration,\n hrTimeToMilliseconds,\n suppressTracing,\n RPCType,\n setRPCMetadata,\n} from '@opentelemetry/core';\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport type { Socket } from 'net';\nimport type * as url from 'url';\nimport type { HttpInstrumentationConfig } from './types';\nimport { VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { errorMonitor } from 'events';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_NETWORK_PROTOCOL_VERSION,\n ATTR_HTTP_ROUTE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_SCHEME,\n METRIC_HTTP_CLIENT_REQUEST_DURATION,\n METRIC_HTTP_SERVER_REQUEST_DURATION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n extractHostnameAndPort,\n getIncomingRequestAttributes,\n getIncomingRequestAttributesOnResponse,\n getIncomingStableRequestMetricAttributesOnResponse,\n getOutgoingRequestAttributes,\n getOutgoingRequestAttributesOnResponse,\n getOutgoingStableRequestMetricAttributesOnResponse,\n getRequestInfo,\n isURLLike,\n headerCapture,\n isValidOptionsType,\n parseErrorType,\n parseResponseStatus,\n setSpanWithError,\n} from './utils';\nimport type { Err, Func, Http, HttpRequestArgs, Https } from './internal-types';\nimport { DEFAULT_QUERY_STRINGS_TO_REDACT } from './internal-types';\n\n/**\n * `node:http` and `node:https` instrumentation for OpenTelemetry\n */\nexport class HttpInstrumentation extends InstrumentationBase<HttpInstrumentationConfig> {\n /** keep track on spans not ended */\n private readonly _spanNotEnded: WeakSet<Span> = new WeakSet<Span>();\n private _headerCapture;\n private _httpPatched: boolean = false;\n private _httpsPatched: boolean = false;\n declare private _httpServerDurationHistogram: Histogram;\n declare private _httpClientDurationHistogram: Histogram;\n\n constructor(config: HttpInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-http', VERSION, config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n protected override _updateMetricInstruments() {\n this._httpServerDurationHistogram = this.meter.createHistogram(\n METRIC_HTTP_SERVER_REQUEST_DURATION,\n {\n description: 'Duration of HTTP server requests.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n ],\n },\n }\n );\n this._httpClientDurationHistogram = this.meter.createHistogram(\n METRIC_HTTP_CLIENT_REQUEST_DURATION,\n {\n description: 'Duration of HTTP client requests.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n ],\n },\n }\n );\n }\n\n private _recordServerDuration(durationMs: number, attributes: Attributes) {\n // stable histogram is counted in S\n this._httpServerDurationHistogram.record(durationMs / 1000, attributes);\n }\n\n private _recordClientDuration(durationMs: number, attributes: Attributes) {\n // stable histogram is counted in S\n this._httpClientDurationHistogram.record(durationMs / 1000, attributes);\n }\n\n override setConfig(config: HttpInstrumentationConfig = {}): void {\n super.setConfig(config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n init(): [\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleDefinition,\n ] {\n return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];\n }\n\n private _getHttpInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n // Guard against double-instrumentation, if loaded by both `require`\n // and `import`.\n if (this._httpPatched) {\n return moduleExports;\n }\n this._httpPatched = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const isESM = (moduleExports as any)[Symbol.toStringTag] === 'Module';\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n const patchedRequest = this._wrap(\n moduleExports,\n 'request',\n this._getPatchOutgoingRequestFunction('http')\n ) as unknown as Func<http.ClientRequest>;\n const patchedGet = this._wrap(\n moduleExports,\n 'get',\n this._getPatchOutgoingGetFunction(patchedRequest)\n );\n if (isESM) {\n // To handle `import http from 'http'`, which returns the default\n // export, we need to set `module.default.*`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.request = patchedRequest;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.get = patchedGet;\n }\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('http')\n );\n }\n return moduleExports;\n },\n (moduleExports: Http) => {\n this._httpPatched = false;\n if (moduleExports === undefined) return;\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n }\n );\n }\n\n private _getHttpsInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n // Guard against double-instrumentation, if loaded by both `require`\n // and `import`.\n if (this._httpsPatched) {\n return moduleExports;\n }\n this._httpsPatched = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const isESM = (moduleExports as any)[Symbol.toStringTag] === 'Module';\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n const patchedRequest = this._wrap(\n moduleExports,\n 'request',\n this._getPatchHttpsOutgoingRequestFunction('https')\n ) as unknown as Func<http.ClientRequest>;\n const patchedGet = this._wrap(\n moduleExports,\n 'get',\n this._getPatchHttpsOutgoingGetFunction(patchedRequest)\n );\n if (isESM) {\n // To handle `import https from 'https'`, which returns the default\n // export, we need to set `module.default.*`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.request = patchedRequest;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.get = patchedGet;\n }\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('https')\n );\n }\n return moduleExports;\n },\n (moduleExports: Https) => {\n this._httpsPatched = false;\n if (moduleExports === undefined) return;\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n }\n );\n }\n\n /**\n * Creates spans for incoming requests, restoring spans' context if applied.\n */\n private _getPatchIncomingRequestFunction(component: 'http' | 'https') {\n return (\n original: (event: string, ...args: unknown[]) => boolean\n ): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {\n return this._incomingRequestFunction(component, original);\n };\n }\n\n /**\n * Creates spans for outgoing requests, sending spans' context for distributed\n * tracing.\n */\n private _getPatchOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n return this._outgoingRequestFunction(component, original);\n };\n }\n\n private _getPatchOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | url.URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (_original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n // Re-implement http.get. This needs to be done (instead of using\n // getPatchOutgoingRequestFunction to patch it) because we need to\n // set the trace context header before the returned http.ClientRequest is\n // ended. The Node.js docs state that the only differences between\n // request and get are that (1) get defaults to the HTTP GET method and\n // (2) the returned request object is ended immediately. The former is\n // already true (at least in supported Node versions up to v10), so we\n // simply follow the latter. Ref:\n // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback\n // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198\n return function outgoingGetRequest<\n T extends http.RequestOptions | string | url.URL,\n >(options: T, ...args: HttpRequestArgs): http.ClientRequest {\n const req = clientRequest(options, ...args);\n req.end();\n return req;\n };\n };\n }\n\n /** Patches HTTPS outgoing requests */\n private _getPatchHttpsOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n // Makes sure options will have default HTTPS parameters\n if (\n component === 'https' &&\n typeof options === 'object' &&\n options?.constructor?.name !== 'URL'\n ) {\n options = Object.assign({}, options);\n instrumentation._setDefaultOptions(options);\n }\n return instrumentation._getPatchOutgoingRequestFunction(component)(\n original\n )(options, ...args);\n };\n };\n }\n\n private _setDefaultOptions(options: https.RequestOptions) {\n options.protocol = options.protocol || 'https:';\n options.port = options.port || 443;\n }\n\n /** Patches HTTPS outgoing get requests */\n private _getPatchHttpsOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n return instrumentation._getPatchOutgoingGetFunction(clientRequest)(\n original\n )(options, ...args);\n };\n };\n }\n\n /**\n * Attach event listeners to a client request to end span and add span attributes.\n *\n * @param request The original request object.\n * @param span representing the current operation\n * @param startTime representing the start time of the request to calculate duration in Metric\n * @param metricAttributes metric attributes for the request duration metric\n */\n private _traceClientRequest(\n request: http.ClientRequest,\n span: Span,\n startTime: HrTime,\n metricAttributes: Attributes\n ): http.ClientRequest {\n if (this.getConfig().requestHook) {\n this._callRequestHook(span, request);\n }\n\n /**\n * Determines if the request has errored or the response has ended/errored.\n */\n let responseFinished = false;\n\n /*\n * User 'response' event listeners can be added before our listener,\n * force our listener to be the first, so response emitter is bound\n * before any user listeners are added to it.\n */\n request.prependListener(\n 'response',\n (response: http.IncomingMessage & { aborted?: boolean }) => {\n this._diag.debug('outgoingRequest on response()');\n if (request.listenerCount('response') <= 1) {\n response.resume();\n }\n const responseAttributes =\n getOutgoingRequestAttributesOnResponse(response);\n span.setAttributes(responseAttributes);\n metricAttributes = Object.assign(\n metricAttributes,\n getOutgoingStableRequestMetricAttributesOnResponse(responseAttributes)\n );\n\n if (this.getConfig().responseHook) {\n this._callResponseHook(span, response);\n }\n\n span.setAttributes(\n this._headerCapture.client.captureRequestHeaders(header =>\n request.getHeader(header)\n )\n );\n span.setAttributes(\n this._headerCapture.client.captureResponseHeaders(\n header => response.headers[header]\n )\n );\n\n context.bind(context.active(), response);\n\n const endHandler = () => {\n this._diag.debug('outgoingRequest on end()');\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n let status: SpanStatus;\n\n if (response.aborted && !response.complete) {\n status = { code: SpanStatusCode.ERROR };\n } else {\n // behaves same for new and old semconv\n status = {\n code: parseResponseStatus(SpanKind.CLIENT, response.statusCode),\n };\n const errorType = parseErrorType(\n SpanKind.CLIENT,\n response.statusCode\n );\n if (errorType !== undefined) {\n span.setAttribute(ATTR_ERROR_TYPE, errorType);\n }\n }\n\n span.setStatus(status);\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(\n span,\n SpanKind.CLIENT,\n startTime,\n metricAttributes\n );\n };\n\n response.on('end', endHandler);\n response.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n this._onOutgoingRequestError(\n span,\n metricAttributes,\n startTime,\n error\n );\n });\n }\n );\n request.on('close', () => {\n this._diag.debug('outgoingRequest on request close()');\n if (request.aborted || responseFinished) {\n return;\n }\n responseFinished = true;\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n });\n request.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on request error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n this._onOutgoingRequestError(span, metricAttributes, startTime, error);\n });\n\n this._diag.debug('http.ClientRequest return request');\n return request;\n }\n\n private _incomingRequestFunction(\n component: 'http' | 'https',\n original: (event: string, ...args: unknown[]) => boolean\n ) {\n const instrumentation = this;\n return function incomingRequest(\n this: unknown,\n event: string,\n ...args: unknown[]\n ): boolean {\n // Only traces request events\n if (event !== 'request') {\n return original.apply(this, [event, ...args]);\n }\n\n const request = args[0] as http.IncomingMessage;\n const response = args[1] as http.ServerResponse & { socket: Socket };\n const method = request.method || 'GET';\n\n instrumentation._diag.debug(\n `${component} instrumentation incomingRequest`\n );\n\n if (\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().ignoreIncomingRequestHook?.(request),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreIncomingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return context.with(suppressTracing(context.active()), () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n return original.apply(this, [event, ...args]);\n });\n }\n\n const headers = request.headers;\n\n const spanAttributes = getIncomingRequestAttributes(\n request,\n {\n component: component,\n hookAttributes: instrumentation._callStartSpanHook(\n request,\n instrumentation.getConfig().startIncomingSpanHook\n ),\n enableSyntheticSourceDetection:\n instrumentation.getConfig().enableSyntheticSourceDetection || false,\n redactedQueryParams:\n instrumentation.getConfig().redactedQueryParamsServer ??\n Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT),\n },\n instrumentation._diag\n );\n\n Object.assign(\n spanAttributes,\n instrumentation._headerCapture.server.captureRequestHeaders(\n header => request.headers[header]\n )\n );\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.SERVER,\n attributes: spanAttributes,\n };\n\n const startTime = hrTime();\n\n // request method and url.scheme are both required span attributes\n const metricAttributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: spanAttributes[ATTR_HTTP_REQUEST_METHOD],\n [ATTR_URL_SCHEME]: spanAttributes[ATTR_URL_SCHEME],\n };\n\n // recommended if and only if one was sent, same as span recommendation\n if (spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const ctx = propagation.extract(ROOT_CONTEXT, headers);\n const span = instrumentation._startHttpSpan(method, spanOptions, ctx);\n const rpcMetadata: RPCMetadata = {\n type: RPCType.HTTP,\n span,\n };\n\n return context.with(\n setRPCMetadata(trace.setSpan(ctx, span), rpcMetadata),\n () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n\n if (instrumentation.getConfig().requestHook) {\n instrumentation._callRequestHook(span, request);\n }\n if (instrumentation.getConfig().responseHook) {\n instrumentation._callResponseHook(span, response);\n }\n\n // After 'error', no further events other than 'close' should be emitted.\n let hasError = false;\n response.on('close', () => {\n if (hasError) {\n return;\n }\n instrumentation._onServerResponseFinish(\n request,\n response,\n span,\n metricAttributes,\n startTime\n );\n });\n response.on(errorMonitor, (err: Err) => {\n hasError = true;\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n err\n );\n });\n\n return safeExecuteInTheMiddle(\n () => original.apply(this, [event, ...args]),\n error => {\n if (error) {\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n error\n );\n throw error;\n }\n }\n );\n }\n );\n };\n }\n\n private _outgoingRequestFunction(\n component: 'http' | 'https',\n original: Func<http.ClientRequest>\n ): Func<http.ClientRequest> {\n const instrumentation = this;\n return function outgoingRequest(\n this: unknown,\n options: url.URL | http.RequestOptions | string,\n ...args: unknown[]\n ): http.ClientRequest {\n if (!isValidOptionsType(options)) {\n return original.apply(this, [options, ...args]);\n }\n const extraOptions =\n typeof args[0] === 'object' &&\n (typeof options === 'string' || isURLLike(options))\n ? (args.shift() as http.RequestOptions)\n : undefined;\n const { method, invalidUrl, optionsParsed } = getRequestInfo(\n instrumentation._diag,\n options,\n extraOptions\n );\n\n if (\n safeExecuteInTheMiddle(\n () =>\n instrumentation\n .getConfig()\n .ignoreOutgoingRequestHook?.(optionsParsed),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreOutgoingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return original.apply(this, [optionsParsed, ...args]);\n }\n\n const { hostname, port } = extractHostnameAndPort(optionsParsed);\n const attributes = getOutgoingRequestAttributes(\n optionsParsed,\n {\n component,\n port,\n hostname,\n hookAttributes: instrumentation._callStartSpanHook(\n optionsParsed,\n instrumentation.getConfig().startOutgoingSpanHook\n ),\n redactedQueryParams: instrumentation.getConfig().redactedQueryParams, // Added config for adding custom query strings\n },\n instrumentation.getConfig().enableSyntheticSourceDetection || false\n );\n\n const startTime = hrTime();\n\n // request method, server address, and server port are both required span attributes\n const metricAttributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: attributes[ATTR_HTTP_REQUEST_METHOD],\n [ATTR_SERVER_ADDRESS]: attributes[ATTR_SERVER_ADDRESS],\n [ATTR_SERVER_PORT]: attributes[ATTR_SERVER_PORT],\n };\n\n // required if and only if one was sent, same as span requirement\n if (attributes[ATTR_HTTP_RESPONSE_STATUS_CODE]) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] =\n attributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n }\n\n // recommended if and only if one was sent, same as span recommendation\n if (attributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n attributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.CLIENT,\n attributes,\n };\n const span = instrumentation._startHttpSpan(method, spanOptions);\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n if (!optionsParsed.headers) {\n optionsParsed.headers = {};\n } else {\n // Make a copy of the headers object to avoid mutating an object the\n // caller might have a reference to.\n optionsParsed.headers = Object.assign({}, optionsParsed.headers);\n }\n propagation.inject(requestContext, optionsParsed.headers);\n\n return context.with(requestContext, () => {\n /*\n * The response callback is registered before ClientRequest is bound,\n * thus it is needed to bind it before the function call.\n */\n const cb = args[args.length - 1];\n if (typeof cb === 'function') {\n args[args.length - 1] = context.bind(parentContext, cb);\n }\n\n const request: http.ClientRequest = safeExecuteInTheMiddle(\n () => {\n if (invalidUrl) {\n // we know that the url is invalid, there's no point in injecting context as it will fail validation.\n // Passing in what the user provided will give the user an error that matches what they'd see without\n // the instrumentation.\n return original.apply(this, [options, ...args]);\n } else {\n return original.apply(this, [optionsParsed, ...args]);\n }\n },\n error => {\n if (error) {\n instrumentation._onOutgoingRequestError(\n span,\n metricAttributes,\n startTime,\n error\n );\n throw error;\n }\n }\n );\n\n instrumentation._diag.debug(\n `${component} instrumentation outgoingRequest`\n );\n context.bind(parentContext, request);\n return instrumentation._traceClientRequest(\n request,\n span,\n startTime,\n metricAttributes\n );\n });\n };\n }\n\n private _onServerResponseFinish(\n request: http.IncomingMessage,\n response: http.ServerResponse,\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime\n ) {\n const attributes = getIncomingRequestAttributesOnResponse(response);\n metricAttributes = Object.assign(\n metricAttributes,\n getIncomingStableRequestMetricAttributesOnResponse(attributes)\n );\n\n span.setAttributes(\n this._headerCapture.server.captureResponseHeaders(header =>\n response.getHeader(header)\n )\n );\n\n span.setAttributes(attributes).setStatus({\n code: parseResponseStatus(SpanKind.SERVER, response.statusCode),\n });\n\n const errorType = parseErrorType(SpanKind.SERVER, response.statusCode);\n if (errorType !== undefined) {\n span.setAttribute(ATTR_ERROR_TYPE, errorType);\n }\n\n const route = attributes[ATTR_HTTP_ROUTE];\n if (route) {\n span.updateName(`${request.method || 'GET'} ${route}`);\n }\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _onOutgoingRequestError(\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime,\n error: Err\n ) {\n setSpanWithError(span, error);\n metricAttributes[ATTR_ERROR_TYPE] = error.name;\n\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n }\n\n private _onServerResponseError(\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime,\n error: Err\n ) {\n setSpanWithError(span, error);\n metricAttributes[ATTR_ERROR_TYPE] = error.name;\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _startHttpSpan(\n name: string,\n options: SpanOptions,\n ctx = context.active()\n ) {\n /*\n * If a parent is required but not present, we use a `NoopSpan` to still\n * propagate context without recording it.\n */\n const requireParent =\n options.kind === SpanKind.CLIENT\n ? this.getConfig().requireParentforOutgoingSpans\n : this.getConfig().requireParentforIncomingSpans;\n\n let span: Span;\n const currentSpan = trace.getSpan(ctx);\n\n if (\n requireParent === true &&\n (!currentSpan || !trace.isSpanContextValid(currentSpan.spanContext()))\n ) {\n span = trace.wrapSpanContext(INVALID_SPAN_CONTEXT);\n } else if (requireParent === true && currentSpan?.spanContext().isRemote) {\n span = currentSpan;\n } else {\n span = this.tracer.startSpan(name, options, ctx);\n }\n this._spanNotEnded.add(span);\n return span;\n }\n\n private _closeHttpSpan(\n span: Span,\n spanKind: SpanKind,\n startTime: HrTime,\n metricAttributes: Attributes\n ) {\n if (!this._spanNotEnded.has(span)) {\n return;\n }\n\n span.end();\n this._spanNotEnded.delete(span);\n\n // Record metrics\n const duration = hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime()));\n if (spanKind === SpanKind.SERVER) {\n this._recordServerDuration(duration, metricAttributes);\n } else if (spanKind === SpanKind.CLIENT) {\n this._recordClientDuration(duration, metricAttributes);\n }\n }\n\n private _callResponseHook(\n span: Span,\n response: http.IncomingMessage | http.ServerResponse\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().responseHook!(span, response),\n () => {},\n true\n );\n }\n\n private _callRequestHook(\n span: Span,\n request: http.ClientRequest | http.IncomingMessage\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().requestHook!(span, request),\n () => {},\n true\n );\n }\n\n private _callStartSpanHook(\n request: http.IncomingMessage | http.RequestOptions,\n hookFunc: Function | undefined\n ) {\n if (typeof hookFunc === 'function') {\n return safeExecuteInTheMiddle(\n () => hookFunc(request),\n () => {},\n true\n );\n }\n }\n\n private _createHeaderCapture() {\n const config = this.getConfig();\n\n return {\n client: {\n captureRequestHeaders: headerCapture(\n 'request',\n config.headersToSpanAttributes?.client?.requestHeaders ?? []\n ),\n captureResponseHeaders: headerCapture(\n 'response',\n config.headersToSpanAttributes?.client?.responseHeaders ?? []\n ),\n },\n server: {\n captureRequestHeaders: headerCapture(\n 'request',\n config.headersToSpanAttributes?.server?.requestHeaders ?? []\n ),\n captureResponseHeaders: headerCapture(\n 'response',\n config.headersToSpanAttributes?.server?.responseHeaders ?? []\n ),\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AA8EA,IAAa,sBAAb,cAAyCA,+BAAAA,oBAA+C;;CAEtF,gCAAgD,IAAI,QAAc;CAClE;CACA,eAAgC;CAChC,gBAAiC;CAIjC,YAAY,SAAoC,CAAC,GAAG;EAClD,MAAM,uCAAuCC,gBAAAA,SAAS,MAAM;EAC5D,KAAK,iBAAiB,KAAK,qBAAqB;CAClD;CAEA,2BAA8C;EAC5C,KAAK,+BAA+B,KAAK,MAAM,gBAC7CC,oCAAAA,qCACA;GACE,aAAa;GACb,MAAM;GACN,WAAWC,mBAAAA,UAAU;GACrB,QAAQ,EACN,0BAA0B;IACxB;IAAO;IAAM;IAAO;IAAM;IAAO;IAAK;IAAM;IAAK;IAAM;IAAG;IAAK;IAC/D;IAAK;GACP,EACF;EACF,CACF;EACA,KAAK,+BAA+B,KAAK,MAAM,gBAC7CC,oCAAAA,qCACA;GACE,aAAa;GACb,MAAM;GACN,WAAWD,mBAAAA,UAAU;GACrB,QAAQ,EACN,0BAA0B;IACxB;IAAO;IAAM;IAAO;IAAM;IAAO;IAAK;IAAM;IAAK;IAAM;IAAG;IAAK;IAC/D;IAAK;GACP,EACF;EACF,CACF;CACF;CAEA,sBAA8B,YAAoB,YAAwB;EAExE,KAAK,6BAA6B,OAAO,aAAa,KAAM,UAAU;CACxE;CAEA,sBAA8B,YAAoB,YAAwB;EAExE,KAAK,6BAA6B,OAAO,aAAa,KAAM,UAAU;CACxE;CAEA,UAAmB,SAAoC,CAAC,GAAS;EAC/D,MAAM,UAAU,MAAM;EACtB,KAAK,iBAAiB,KAAK,qBAAqB;CAClD;CAEA,OAGE;EACA,OAAO,CAAC,KAAK,yBAAyB,GAAG,KAAK,wBAAwB,CAAC;CACzE;CAEA,0BAAkC;EAChC,OAAO,IAAIE,+BAAAA,oCACT,QACA,CAAC,GAAG,I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gBAAgB;OAChD,IAAI,aAAaA,mBAAAA,SAAS,QAC/B,KAAK,sBAAsB,UAAU,gBAAgB;CAEzD;CAEA,kBACE,MACA,UACA;EACA,CAAA,GAAA,+BAAA,uBAAA,OACQ,KAAK,UAAU,CAAC,CAAC,aAAc,MAAM,QAAQ,SAC7C,CAAC,GACP,IACF;CACF;CAEA,iBACE,MACA,SACA;EACA,CAAA,GAAA,+BAAA,uBAAA,OACQ,KAAK,UAAU,CAAC,CAAC,YAAa,MAAM,OAAO,SAC3C,CAAC,GACP,IACF;CACF;CAEA,mBACE,SACA,UACA;EACA,IAAI,OAAO,aAAa,YACtB,QAAA,GAAOI,+BAAAA,uBAAAA,OACC,SAAS,OAAO,SAChB,CAAC,GACP,IACF;CAEJ;CAEA,uBAA+B;EAC7B,MAAM,SAAS,KAAK,UAAU;EAE9B,OAAO;GACL,QAAQ;IACN,uBAAuB2B,cAAAA,cACrB,WACA,OAAO,yBAAyB,QAAQ,kBAAkB,CAAC,CAC7D;IACA,wBAAwBA,cAAAA,cACtB,YACA,OAAO,yBAAyB,QAAQ,mBAAmB,CAAC,CAC9D;GACF;GACA,QAAQ;IACN,uBAAuBA,cAAAA,cACrB,WACA,OAAO,yBAAyB,QAAQ,kBAAkB,CAAC,CAC7D;IACA,wBAAwBA,cAAAA,cACtB,YACA,OAAO,yBAAyB,QAAQ,mBAAmB,CAAC,CAC9D;GACF;EACF;CACF;AACF"}
@@ -0,0 +1,61 @@
1
+ import { HttpInstrumentationConfig } from "./types.cjs";
2
+ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
3
+ //#region src/http.d.ts
4
+ /**
5
+ * `node:http` and `node:https` instrumentation for OpenTelemetry
6
+ */
7
+ declare class HttpInstrumentation extends InstrumentationBase<HttpInstrumentationConfig> {
8
+ /** keep track on spans not ended */
9
+ private readonly _spanNotEnded;
10
+ private _headerCapture;
11
+ private _httpPatched;
12
+ private _httpsPatched;
13
+ private _httpServerDurationHistogram;
14
+ private _httpClientDurationHistogram;
15
+ constructor(config?: HttpInstrumentationConfig);
16
+ protected _updateMetricInstruments(): void;
17
+ private _recordServerDuration;
18
+ private _recordClientDuration;
19
+ setConfig(config?: HttpInstrumentationConfig): void;
20
+ init(): [InstrumentationNodeModuleDefinition, InstrumentationNodeModuleDefinition];
21
+ private _getHttpInstrumentation;
22
+ private _getHttpsInstrumentation;
23
+ /**
24
+ * Creates spans for incoming requests, restoring spans' context if applied.
25
+ */
26
+ private _getPatchIncomingRequestFunction;
27
+ /**
28
+ * Creates spans for outgoing requests, sending spans' context for distributed
29
+ * tracing.
30
+ */
31
+ private _getPatchOutgoingRequestFunction;
32
+ private _getPatchOutgoingGetFunction;
33
+ /** Patches HTTPS outgoing requests */
34
+ private _getPatchHttpsOutgoingRequestFunction;
35
+ private _setDefaultOptions;
36
+ /** Patches HTTPS outgoing get requests */
37
+ private _getPatchHttpsOutgoingGetFunction;
38
+ /**
39
+ * Attach event listeners to a client request to end span and add span attributes.
40
+ *
41
+ * @param request The original request object.
42
+ * @param span representing the current operation
43
+ * @param startTime representing the start time of the request to calculate duration in Metric
44
+ * @param metricAttributes metric attributes for the request duration metric
45
+ */
46
+ private _traceClientRequest;
47
+ private _incomingRequestFunction;
48
+ private _outgoingRequestFunction;
49
+ private _onServerResponseFinish;
50
+ private _onOutgoingRequestError;
51
+ private _onServerResponseError;
52
+ private _startHttpSpan;
53
+ private _closeHttpSpan;
54
+ private _callResponseHook;
55
+ private _callRequestHook;
56
+ private _callStartSpanHook;
57
+ private _createHeaderCapture;
58
+ }
59
+ //#endregion
60
+ export { HttpInstrumentation };
61
+ //# sourceMappingURL=http.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.cts","names":[],"sources":["../src/http.d.ts"],"mappings":";;;;;;cAKqB,4BAA4B,oBAAoB;;mBAEhD;UACT;UACA;UACA;UACA;UACA;EACR,YAAY,SAAS;YACX;UACF;UACA;EACR,UAAU,SAAS;EACnB,SACI,qCACA;UAEI;UACA;;;;UAIA;;;;;UAKA;UACA;;UAEA;UACA;;UAEA;;;;;;;;;UASA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA"}