@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/build/src/http.js DELETED
@@ -1,562 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.HttpInstrumentation = void 0;
8
- const api_1 = require("@opentelemetry/api");
9
- const core_1 = require("@opentelemetry/core");
10
- const url = require("url");
11
- const version_1 = require("./version");
12
- const instrumentation_1 = require("@opentelemetry/instrumentation");
13
- const events_1 = require("events");
14
- const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
15
- const utils_1 = require("./utils");
16
- const internal_types_1 = require("./internal-types");
17
- /**
18
- * `node:http` and `node:https` instrumentation for OpenTelemetry
19
- */
20
- class HttpInstrumentation extends instrumentation_1.InstrumentationBase {
21
- /** keep track on spans not ended */
22
- _spanNotEnded = new WeakSet();
23
- _headerCapture;
24
- _httpPatched = false;
25
- _httpsPatched = false;
26
- constructor(config = {}) {
27
- super('@opentelemetry/instrumentation-http', version_1.VERSION, config);
28
- this._headerCapture = this._createHeaderCapture();
29
- }
30
- _updateMetricInstruments() {
31
- this._httpServerDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_SERVER_REQUEST_DURATION, {
32
- description: 'Duration of HTTP server requests.',
33
- unit: 's',
34
- valueType: api_1.ValueType.DOUBLE,
35
- advice: {
36
- explicitBucketBoundaries: [
37
- 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,
38
- 7.5, 10,
39
- ],
40
- },
41
- });
42
- this._httpClientDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_CLIENT_REQUEST_DURATION, {
43
- description: 'Duration of HTTP client requests.',
44
- unit: 's',
45
- valueType: api_1.ValueType.DOUBLE,
46
- advice: {
47
- explicitBucketBoundaries: [
48
- 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,
49
- 7.5, 10,
50
- ],
51
- },
52
- });
53
- }
54
- _recordServerDuration(durationMs, attributes) {
55
- // stable histogram is counted in S
56
- this._httpServerDurationHistogram.record(durationMs / 1000, attributes);
57
- }
58
- _recordClientDuration(durationMs, attributes) {
59
- // stable histogram is counted in S
60
- this._httpClientDurationHistogram.record(durationMs / 1000, attributes);
61
- }
62
- setConfig(config = {}) {
63
- super.setConfig(config);
64
- this._headerCapture = this._createHeaderCapture();
65
- }
66
- init() {
67
- return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];
68
- }
69
- _getHttpInstrumentation() {
70
- return new instrumentation_1.InstrumentationNodeModuleDefinition('http', ['*'], (moduleExports) => {
71
- // Guard against double-instrumentation, if loaded by both `require`
72
- // and `import`.
73
- if (this._httpPatched) {
74
- return moduleExports;
75
- }
76
- this._httpPatched = true;
77
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
- const isESM = moduleExports[Symbol.toStringTag] === 'Module';
79
- if (!this.getConfig().disableOutgoingRequestInstrumentation) {
80
- const patchedRequest = this._wrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction('http'));
81
- const patchedGet = this._wrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));
82
- if (isESM) {
83
- // To handle `import http from 'http'`, which returns the default
84
- // export, we need to set `module.default.*`.
85
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
- moduleExports.default.request = patchedRequest;
87
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
- moduleExports.default.get = patchedGet;
89
- }
90
- }
91
- if (!this.getConfig().disableIncomingRequestInstrumentation) {
92
- this._wrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction('http'));
93
- }
94
- return moduleExports;
95
- }, (moduleExports) => {
96
- this._httpPatched = false;
97
- if (moduleExports === undefined)
98
- return;
99
- if (!this.getConfig().disableOutgoingRequestInstrumentation) {
100
- this._unwrap(moduleExports, 'request');
101
- this._unwrap(moduleExports, 'get');
102
- }
103
- if (!this.getConfig().disableIncomingRequestInstrumentation) {
104
- this._unwrap(moduleExports.Server.prototype, 'emit');
105
- }
106
- });
107
- }
108
- _getHttpsInstrumentation() {
109
- return new instrumentation_1.InstrumentationNodeModuleDefinition('https', ['*'], (moduleExports) => {
110
- // Guard against double-instrumentation, if loaded by both `require`
111
- // and `import`.
112
- if (this._httpsPatched) {
113
- return moduleExports;
114
- }
115
- this._httpsPatched = true;
116
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
117
- const isESM = moduleExports[Symbol.toStringTag] === 'Module';
118
- if (!this.getConfig().disableOutgoingRequestInstrumentation) {
119
- const patchedRequest = this._wrap(moduleExports, 'request', this._getPatchHttpsOutgoingRequestFunction('https'));
120
- const patchedGet = this._wrap(moduleExports, 'get', this._getPatchHttpsOutgoingGetFunction(patchedRequest));
121
- if (isESM) {
122
- // To handle `import https from 'https'`, which returns the default
123
- // export, we need to set `module.default.*`.
124
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
125
- moduleExports.default.request = patchedRequest;
126
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
- moduleExports.default.get = patchedGet;
128
- }
129
- }
130
- if (!this.getConfig().disableIncomingRequestInstrumentation) {
131
- this._wrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction('https'));
132
- }
133
- return moduleExports;
134
- }, (moduleExports) => {
135
- this._httpsPatched = false;
136
- if (moduleExports === undefined)
137
- return;
138
- if (!this.getConfig().disableOutgoingRequestInstrumentation) {
139
- this._unwrap(moduleExports, 'request');
140
- this._unwrap(moduleExports, 'get');
141
- }
142
- if (!this.getConfig().disableIncomingRequestInstrumentation) {
143
- this._unwrap(moduleExports.Server.prototype, 'emit');
144
- }
145
- });
146
- }
147
- /**
148
- * Creates spans for incoming requests, restoring spans' context if applied.
149
- */
150
- _getPatchIncomingRequestFunction(component) {
151
- return (original) => {
152
- return this._incomingRequestFunction(component, original);
153
- };
154
- }
155
- /**
156
- * Creates spans for outgoing requests, sending spans' context for distributed
157
- * tracing.
158
- */
159
- _getPatchOutgoingRequestFunction(component) {
160
- return (original) => {
161
- return this._outgoingRequestFunction(component, original);
162
- };
163
- }
164
- _getPatchOutgoingGetFunction(clientRequest) {
165
- return (_original) => {
166
- // Re-implement http.get. This needs to be done (instead of using
167
- // getPatchOutgoingRequestFunction to patch it) because we need to
168
- // set the trace context header before the returned http.ClientRequest is
169
- // ended. The Node.js docs state that the only differences between
170
- // request and get are that (1) get defaults to the HTTP GET method and
171
- // (2) the returned request object is ended immediately. The former is
172
- // already true (at least in supported Node versions up to v10), so we
173
- // simply follow the latter. Ref:
174
- // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback
175
- // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198
176
- return function outgoingGetRequest(options, ...args) {
177
- const req = clientRequest(options, ...args);
178
- req.end();
179
- return req;
180
- };
181
- };
182
- }
183
- /** Patches HTTPS outgoing requests */
184
- _getPatchHttpsOutgoingRequestFunction(component) {
185
- return (original) => {
186
- const instrumentation = this;
187
- return function httpsOutgoingRequest(options, ...args) {
188
- // Makes sure options will have default HTTPS parameters
189
- if (component === 'https' &&
190
- typeof options === 'object' &&
191
- options?.constructor?.name !== 'URL') {
192
- options = Object.assign({}, options);
193
- instrumentation._setDefaultOptions(options);
194
- }
195
- return instrumentation._getPatchOutgoingRequestFunction(component)(original)(options, ...args);
196
- };
197
- };
198
- }
199
- _setDefaultOptions(options) {
200
- options.protocol = options.protocol || 'https:';
201
- options.port = options.port || 443;
202
- }
203
- /** Patches HTTPS outgoing get requests */
204
- _getPatchHttpsOutgoingGetFunction(clientRequest) {
205
- return (original) => {
206
- const instrumentation = this;
207
- return function httpsOutgoingRequest(options, ...args) {
208
- return instrumentation._getPatchOutgoingGetFunction(clientRequest)(original)(options, ...args);
209
- };
210
- };
211
- }
212
- /**
213
- * Attach event listeners to a client request to end span and add span attributes.
214
- *
215
- * @param request The original request object.
216
- * @param span representing the current operation
217
- * @param startTime representing the start time of the request to calculate duration in Metric
218
- * @param metricAttributes metric attributes for the request duration metric
219
- */
220
- _traceClientRequest(request, span, startTime, metricAttributes) {
221
- if (this.getConfig().requestHook) {
222
- this._callRequestHook(span, request);
223
- }
224
- /**
225
- * Determines if the request has errored or the response has ended/errored.
226
- */
227
- let responseFinished = false;
228
- /*
229
- * User 'response' event listeners can be added before our listener,
230
- * force our listener to be the first, so response emitter is bound
231
- * before any user listeners are added to it.
232
- */
233
- request.prependListener('response', (response) => {
234
- this._diag.debug('outgoingRequest on response()');
235
- if (request.listenerCount('response') <= 1) {
236
- response.resume();
237
- }
238
- const responseAttributes = (0, utils_1.getOutgoingRequestAttributesOnResponse)(response);
239
- span.setAttributes(responseAttributes);
240
- metricAttributes = Object.assign(metricAttributes, (0, utils_1.getOutgoingStableRequestMetricAttributesOnResponse)(responseAttributes));
241
- if (this.getConfig().responseHook) {
242
- this._callResponseHook(span, response);
243
- }
244
- span.setAttributes(this._headerCapture.client.captureRequestHeaders(header => request.getHeader(header)));
245
- span.setAttributes(this._headerCapture.client.captureResponseHeaders(header => response.headers[header]));
246
- api_1.context.bind(api_1.context.active(), response);
247
- const endHandler = () => {
248
- this._diag.debug('outgoingRequest on end()');
249
- if (responseFinished) {
250
- return;
251
- }
252
- responseFinished = true;
253
- let status;
254
- if (response.aborted && !response.complete) {
255
- status = { code: api_1.SpanStatusCode.ERROR };
256
- }
257
- else {
258
- // behaves same for new and old semconv
259
- status = {
260
- code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.CLIENT, response.statusCode),
261
- };
262
- }
263
- span.setStatus(status);
264
- if (this.getConfig().applyCustomAttributesOnSpan) {
265
- (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request, response), () => { }, true);
266
- }
267
- this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, metricAttributes);
268
- };
269
- response.on('end', endHandler);
270
- response.on(events_1.errorMonitor, (error) => {
271
- this._diag.debug('outgoingRequest on error()', error);
272
- if (responseFinished) {
273
- return;
274
- }
275
- responseFinished = true;
276
- this._onOutgoingRequestError(span, metricAttributes, startTime, error);
277
- });
278
- });
279
- request.on('close', () => {
280
- this._diag.debug('outgoingRequest on request close()');
281
- if (request.aborted || responseFinished) {
282
- return;
283
- }
284
- responseFinished = true;
285
- this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, metricAttributes);
286
- });
287
- request.on(events_1.errorMonitor, (error) => {
288
- this._diag.debug('outgoingRequest on request error()', error);
289
- if (responseFinished) {
290
- return;
291
- }
292
- responseFinished = true;
293
- this._onOutgoingRequestError(span, metricAttributes, startTime, error);
294
- });
295
- this._diag.debug('http.ClientRequest return request');
296
- return request;
297
- }
298
- _incomingRequestFunction(component, original) {
299
- const instrumentation = this;
300
- return function incomingRequest(event, ...args) {
301
- // Only traces request events
302
- if (event !== 'request') {
303
- return original.apply(this, [event, ...args]);
304
- }
305
- const request = args[0];
306
- const response = args[1];
307
- const method = request.method || 'GET';
308
- instrumentation._diag.debug(`${component} instrumentation incomingRequest`);
309
- if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreIncomingRequestHook?.(request), (e) => {
310
- if (e != null) {
311
- instrumentation._diag.error('caught ignoreIncomingRequestHook error: ', e);
312
- }
313
- }, true)) {
314
- return api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => {
315
- api_1.context.bind(api_1.context.active(), request);
316
- api_1.context.bind(api_1.context.active(), response);
317
- return original.apply(this, [event, ...args]);
318
- });
319
- }
320
- const headers = request.headers;
321
- const spanAttributes = (0, utils_1.getIncomingRequestAttributes)(request, {
322
- component: component,
323
- hookAttributes: instrumentation._callStartSpanHook(request, instrumentation.getConfig().startIncomingSpanHook),
324
- enableSyntheticSourceDetection: instrumentation.getConfig().enableSyntheticSourceDetection || false,
325
- redactedQueryParams: instrumentation.getConfig().redactedQueryParamsServer ??
326
- Array.from(internal_types_1.DEFAULT_QUERY_STRINGS_TO_REDACT),
327
- }, instrumentation._diag);
328
- Object.assign(spanAttributes, instrumentation._headerCapture.server.captureRequestHeaders(header => request.headers[header]));
329
- const spanOptions = {
330
- kind: api_1.SpanKind.SERVER,
331
- attributes: spanAttributes,
332
- };
333
- const startTime = (0, core_1.hrTime)();
334
- // request method and url.scheme are both required span attributes
335
- const metricAttributes = {
336
- [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: spanAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD],
337
- [semantic_conventions_1.ATTR_URL_SCHEME]: spanAttributes[semantic_conventions_1.ATTR_URL_SCHEME],
338
- };
339
- // recommended if and only if one was sent, same as span recommendation
340
- if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
341
- metricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] =
342
- spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
343
- }
344
- const ctx = api_1.propagation.extract(api_1.ROOT_CONTEXT, headers);
345
- const span = instrumentation._startHttpSpan(method, spanOptions, ctx);
346
- const rpcMetadata = {
347
- type: core_1.RPCType.HTTP,
348
- span,
349
- };
350
- return api_1.context.with((0, core_1.setRPCMetadata)(api_1.trace.setSpan(ctx, span), rpcMetadata), () => {
351
- api_1.context.bind(api_1.context.active(), request);
352
- api_1.context.bind(api_1.context.active(), response);
353
- if (instrumentation.getConfig().requestHook) {
354
- instrumentation._callRequestHook(span, request);
355
- }
356
- if (instrumentation.getConfig().responseHook) {
357
- instrumentation._callResponseHook(span, response);
358
- }
359
- // After 'error', no further events other than 'close' should be emitted.
360
- let hasError = false;
361
- response.on('close', () => {
362
- if (hasError) {
363
- return;
364
- }
365
- instrumentation._onServerResponseFinish(request, response, span, metricAttributes, startTime);
366
- });
367
- response.on(events_1.errorMonitor, (err) => {
368
- hasError = true;
369
- instrumentation._onServerResponseError(span, metricAttributes, startTime, err);
370
- });
371
- return (0, instrumentation_1.safeExecuteInTheMiddle)(() => original.apply(this, [event, ...args]), error => {
372
- if (error) {
373
- instrumentation._onServerResponseError(span, metricAttributes, startTime, error);
374
- throw error;
375
- }
376
- });
377
- });
378
- };
379
- }
380
- _outgoingRequestFunction(component, original) {
381
- const instrumentation = this;
382
- return function outgoingRequest(options, ...args) {
383
- if (!(0, utils_1.isValidOptionsType)(options)) {
384
- return original.apply(this, [options, ...args]);
385
- }
386
- const extraOptions = typeof args[0] === 'object' &&
387
- (typeof options === 'string' || options instanceof url.URL)
388
- ? args.shift()
389
- : undefined;
390
- const { method, invalidUrl, optionsParsed } = (0, utils_1.getRequestInfo)(instrumentation._diag, options, extraOptions);
391
- if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation
392
- .getConfig()
393
- .ignoreOutgoingRequestHook?.(optionsParsed), (e) => {
394
- if (e != null) {
395
- instrumentation._diag.error('caught ignoreOutgoingRequestHook error: ', e);
396
- }
397
- }, true)) {
398
- return original.apply(this, [optionsParsed, ...args]);
399
- }
400
- const { hostname, port } = (0, utils_1.extractHostnameAndPort)(optionsParsed);
401
- const attributes = (0, utils_1.getOutgoingRequestAttributes)(optionsParsed, {
402
- component,
403
- port,
404
- hostname,
405
- hookAttributes: instrumentation._callStartSpanHook(optionsParsed, instrumentation.getConfig().startOutgoingSpanHook),
406
- redactedQueryParams: instrumentation.getConfig().redactedQueryParams, // Added config for adding custom query strings
407
- }, instrumentation.getConfig().enableSyntheticSourceDetection || false);
408
- const startTime = (0, core_1.hrTime)();
409
- // request method, server address, and server port are both required span attributes
410
- const metricAttributes = {
411
- [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD],
412
- [semantic_conventions_1.ATTR_SERVER_ADDRESS]: attributes[semantic_conventions_1.ATTR_SERVER_ADDRESS],
413
- [semantic_conventions_1.ATTR_SERVER_PORT]: attributes[semantic_conventions_1.ATTR_SERVER_PORT],
414
- };
415
- // required if and only if one was sent, same as span requirement
416
- if (attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
417
- metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] =
418
- attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
419
- }
420
- // recommended if and only if one was sent, same as span recommendation
421
- if (attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
422
- metricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] =
423
- attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
424
- }
425
- const spanOptions = {
426
- kind: api_1.SpanKind.CLIENT,
427
- attributes,
428
- };
429
- const span = instrumentation._startHttpSpan(method, spanOptions);
430
- const parentContext = api_1.context.active();
431
- const requestContext = api_1.trace.setSpan(parentContext, span);
432
- if (!optionsParsed.headers) {
433
- optionsParsed.headers = {};
434
- }
435
- else {
436
- // Make a copy of the headers object to avoid mutating an object the
437
- // caller might have a reference to.
438
- optionsParsed.headers = Object.assign({}, optionsParsed.headers);
439
- }
440
- api_1.propagation.inject(requestContext, optionsParsed.headers);
441
- return api_1.context.with(requestContext, () => {
442
- /*
443
- * The response callback is registered before ClientRequest is bound,
444
- * thus it is needed to bind it before the function call.
445
- */
446
- const cb = args[args.length - 1];
447
- if (typeof cb === 'function') {
448
- args[args.length - 1] = api_1.context.bind(parentContext, cb);
449
- }
450
- const request = (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
451
- if (invalidUrl) {
452
- // we know that the url is invalid, there's no point in injecting context as it will fail validation.
453
- // Passing in what the user provided will give the user an error that matches what they'd see without
454
- // the instrumentation.
455
- return original.apply(this, [options, ...args]);
456
- }
457
- else {
458
- return original.apply(this, [optionsParsed, ...args]);
459
- }
460
- }, error => {
461
- if (error) {
462
- instrumentation._onOutgoingRequestError(span, metricAttributes, startTime, error);
463
- throw error;
464
- }
465
- });
466
- instrumentation._diag.debug(`${component} instrumentation outgoingRequest`);
467
- api_1.context.bind(parentContext, request);
468
- return instrumentation._traceClientRequest(request, span, startTime, metricAttributes);
469
- });
470
- };
471
- }
472
- _onServerResponseFinish(request, response, span, metricAttributes, startTime) {
473
- const attributes = (0, utils_1.getIncomingRequestAttributesOnResponse)(response);
474
- metricAttributes = Object.assign(metricAttributes, (0, utils_1.getIncomingStableRequestMetricAttributesOnResponse)(attributes));
475
- span.setAttributes(this._headerCapture.server.captureResponseHeaders(header => response.getHeader(header)));
476
- span.setAttributes(attributes).setStatus({
477
- code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.SERVER, response.statusCode),
478
- });
479
- const route = attributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
480
- if (route) {
481
- span.updateName(`${request.method || 'GET'} ${route}`);
482
- }
483
- if (this.getConfig().applyCustomAttributesOnSpan) {
484
- (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request, response), () => { }, true);
485
- }
486
- this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, metricAttributes);
487
- }
488
- _onOutgoingRequestError(span, metricAttributes, startTime, error) {
489
- (0, utils_1.setSpanWithError)(span, error);
490
- metricAttributes[semantic_conventions_1.ATTR_ERROR_TYPE] = error.name;
491
- this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, metricAttributes);
492
- }
493
- _onServerResponseError(span, metricAttributes, startTime, error) {
494
- (0, utils_1.setSpanWithError)(span, error);
495
- metricAttributes[semantic_conventions_1.ATTR_ERROR_TYPE] = error.name;
496
- this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, metricAttributes);
497
- }
498
- _startHttpSpan(name, options, ctx = api_1.context.active()) {
499
- /*
500
- * If a parent is required but not present, we use a `NoopSpan` to still
501
- * propagate context without recording it.
502
- */
503
- const requireParent = options.kind === api_1.SpanKind.CLIENT
504
- ? this.getConfig().requireParentforOutgoingSpans
505
- : this.getConfig().requireParentforIncomingSpans;
506
- let span;
507
- const currentSpan = api_1.trace.getSpan(ctx);
508
- if (requireParent === true &&
509
- (!currentSpan || !api_1.trace.isSpanContextValid(currentSpan.spanContext()))) {
510
- span = api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT);
511
- }
512
- else if (requireParent === true && currentSpan?.spanContext().isRemote) {
513
- span = currentSpan;
514
- }
515
- else {
516
- span = this.tracer.startSpan(name, options, ctx);
517
- }
518
- this._spanNotEnded.add(span);
519
- return span;
520
- }
521
- _closeHttpSpan(span, spanKind, startTime, metricAttributes) {
522
- if (!this._spanNotEnded.has(span)) {
523
- return;
524
- }
525
- span.end();
526
- this._spanNotEnded.delete(span);
527
- // Record metrics
528
- const duration = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)()));
529
- if (spanKind === api_1.SpanKind.SERVER) {
530
- this._recordServerDuration(duration, metricAttributes);
531
- }
532
- else if (spanKind === api_1.SpanKind.CLIENT) {
533
- this._recordClientDuration(duration, metricAttributes);
534
- }
535
- }
536
- _callResponseHook(span, response) {
537
- (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().responseHook(span, response), () => { }, true);
538
- }
539
- _callRequestHook(span, request) {
540
- (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().requestHook(span, request), () => { }, true);
541
- }
542
- _callStartSpanHook(request, hookFunc) {
543
- if (typeof hookFunc === 'function') {
544
- return (0, instrumentation_1.safeExecuteInTheMiddle)(() => hookFunc(request), () => { }, true);
545
- }
546
- }
547
- _createHeaderCapture() {
548
- const config = this.getConfig();
549
- return {
550
- client: {
551
- captureRequestHeaders: (0, utils_1.headerCapture)('request', config.headersToSpanAttributes?.client?.requestHeaders ?? []),
552
- captureResponseHeaders: (0, utils_1.headerCapture)('response', config.headersToSpanAttributes?.client?.responseHeaders ?? []),
553
- },
554
- server: {
555
- captureRequestHeaders: (0, utils_1.headerCapture)('request', config.headersToSpanAttributes?.server?.requestHeaders ?? []),
556
- captureResponseHeaders: (0, utils_1.headerCapture)('response', config.headersToSpanAttributes?.server?.responseHeaders ?? []),
557
- },
558
- };
559
- }
560
- }
561
- exports.HttpInstrumentation = HttpInstrumentation;
562
- //# sourceMappingURL=http.js.map