@opentelemetry/instrumentation-fetch 0.27.0 → 0.29.1

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.
package/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # OpenTelemetry Fetch Instrumentation for web
2
2
 
3
3
  [![NPM Published Version][npm-img]][npm-url]
4
- [![dependencies][dependencies-image]][dependencies-url]
5
- [![devDependencies][devDependencies-image]][devDependencies-url]
6
4
  [![Apache License][license-image]][license-image]
7
5
 
8
6
  This module provides auto instrumentation for web using fetch.
@@ -81,9 +79,5 @@ Apache 2.0 - See [LICENSE][license-url] for more information.
81
79
  [discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
82
80
  [license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE
83
81
  [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
84
- [dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js.svg?path=packages%2Fopentelemetry-instrumentation-fetch
85
- [dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-fetch
86
- [devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js.svg?path=packages%2Fopentelemetry-instrumentation-fetch&type=dev
87
- [devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-fetch&type=dev
88
82
  [npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-fetch
89
83
  [npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-fetch.svg
@@ -35,6 +35,7 @@ import * as web from '@opentelemetry/sdk-trace-web';
35
35
  import { AttributeNames } from './enums/AttributeNames';
36
36
  import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
37
37
  import { VERSION } from './version';
38
+ import { _globalThis } from '@opentelemetry/core';
38
39
  // how long to wait for observer to collect information about resources
39
40
  // this is needed as event "load" is called before observer
40
41
  // hard to say how long it should really wait, seems like 300ms is
@@ -215,12 +216,12 @@ var FetchInstrumentation = /** @class */ (function (_super) {
215
216
  return function (original) {
216
217
  var plugin = _this;
217
218
  return function patchConstructor() {
218
- var _this = this;
219
219
  var args = [];
220
220
  for (var _i = 0; _i < arguments.length; _i++) {
221
221
  args[_i] = arguments[_i];
222
222
  }
223
- var url = args[0] instanceof Request ? args[0].url : args[0];
223
+ var self = this;
224
+ var url = web.parseUrl(args[0] instanceof Request ? args[0].url : args[0]).href;
224
225
  var options = args[0] instanceof Request ? args[0] : args[1] || {};
225
226
  var createdSpan = plugin._createSpan(url, options);
226
227
  if (!createdSpan) {
@@ -237,16 +238,22 @@ var FetchInstrumentation = /** @class */ (function (_super) {
237
238
  }
238
239
  function endSpanOnSuccess(span, response) {
239
240
  plugin._applyAttributesAfterFetch(span, options, response);
241
+ var spanResponse = {
242
+ status: response.status,
243
+ statusText: response.statusText,
244
+ headers: response.headers,
245
+ url: url
246
+ };
240
247
  if (response.status >= 200 && response.status < 400) {
241
- plugin._endSpan(span, spanData, response);
242
- }
243
- else {
244
- plugin._endSpan(span, spanData, {
245
- status: response.status,
246
- statusText: response.statusText,
247
- url: url,
248
- });
248
+ if (response.url != null && response.url !== '') {
249
+ spanResponse.url = url;
250
+ }
249
251
  }
252
+ plugin._endSpan(span, spanData, {
253
+ status: response.status,
254
+ statusText: response.statusText,
255
+ url: url,
256
+ });
250
257
  }
251
258
  function onSuccess(span, resolve, response) {
252
259
  try {
@@ -291,9 +298,11 @@ var FetchInstrumentation = /** @class */ (function (_super) {
291
298
  return api.context.with(api.trace.setSpan(api.context.active(), createdSpan), function () {
292
299
  plugin._addHeaders(options, url);
293
300
  plugin._tasksCount++;
301
+ // TypeScript complains about arrow function captured a this typed as globalThis
302
+ // ts(7041)
294
303
  return original
295
- .apply(_this, options instanceof Request ? [options] : [url, options])
296
- .then(onSuccess.bind(_this, createdSpan, resolve), onError.bind(_this, createdSpan, reject));
304
+ .apply(self, options instanceof Request ? [options] : [url, options])
305
+ .then(onSuccess.bind(self, createdSpan, resolve), onError.bind(self, createdSpan, reject));
297
306
  });
298
307
  });
299
308
  };
@@ -320,16 +329,14 @@ var FetchInstrumentation = /** @class */ (function (_super) {
320
329
  FetchInstrumentation.prototype._prepareSpanData = function (spanUrl) {
321
330
  var startTime = core.hrTime();
322
331
  var entries = [];
323
- if (typeof window.PerformanceObserver === 'undefined') {
332
+ if (typeof PerformanceObserver !== 'function') {
324
333
  return { entries: entries, startTime: startTime, spanUrl: spanUrl };
325
334
  }
326
335
  var observer = new PerformanceObserver(function (list) {
327
336
  var perfObsEntries = list.getEntries();
328
- var urlNormalizingAnchor = web.getUrlNormalizingAnchor();
329
- urlNormalizingAnchor.href = spanUrl;
330
337
  perfObsEntries.forEach(function (entry) {
331
338
  if (entry.initiatorType === 'fetch' &&
332
- entry.name === urlNormalizingAnchor.href) {
339
+ entry.name === spanUrl) {
333
340
  entries.push(entry);
334
341
  }
335
342
  });
@@ -343,17 +350,17 @@ var FetchInstrumentation = /** @class */ (function (_super) {
343
350
  * implements enable function
344
351
  */
345
352
  FetchInstrumentation.prototype.enable = function () {
346
- if (isWrapped(window.fetch)) {
347
- this._unwrap(window, 'fetch');
353
+ if (isWrapped(fetch)) {
354
+ this._unwrap(_globalThis, 'fetch');
348
355
  this._diag.debug('removing previous patch for constructor');
349
356
  }
350
- this._wrap(window, 'fetch', this._patchConstructor());
357
+ this._wrap(_globalThis, 'fetch', this._patchConstructor());
351
358
  };
352
359
  /**
353
360
  * implements unpatch function
354
361
  */
355
362
  FetchInstrumentation.prototype.disable = function () {
356
- this._unwrap(window, 'fetch');
363
+ this._unwrap(_globalThis, 'fetch');
357
364
  this._usedResources = new WeakSet();
358
365
  };
359
366
  return FetchInstrumentation;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/fetch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,OAAO,K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,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,iBAAiB,EAAE,CAAC,CAAC;IACxD,CAAC;IAED;;OAEG;IACM,sCAAO,GAAhB;QACE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC9B,IAAI,CAAC,cAAc,GAAG,IAAI,OAAO,EAA6B,CAAC;IACjE,CAAC;IACH,2BAAC;AAAD,CAAC,AA1YD,CAA0C,mBAAmB,GA0Y5D","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationConfig,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport * as core from '@opentelemetry/core';\nimport * as web from '@opentelemetry/sdk-trace-web';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { FetchError, FetchResponse, SpanData } from './types';\nimport { VERSION } from './version';\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nexport interface FetchCustomAttributeFunction {\n (\n span: api.Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ): void;\n}\n\n/**\n * FetchPlugin Config\n */\nexport interface FetchInstrumentationConfig extends InstrumentationConfig {\n // the number of timing resources is limited, after the limit\n // (chrome 250, safari 150) the information is not collected anymore\n // the only way to prevent that is to regularly clean the resources\n // whenever it is possible, this is needed only when PerformanceObserver\n // is not available\n clearTimingResources?: boolean;\n // urls which should include trace headers when origin doesn't match\n propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;\n}\n\n/**\n * This class represents a fetch plugin for auto instrumentation\n */\nexport class FetchInstrumentation extends InstrumentationBase<\n Promise<Response>\n> {\n readonly component: string = 'fetch';\n readonly version: string = VERSION;\n moduleName = this.component;\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n private _tasksCount = 0;\n\n constructor(config?: FetchInstrumentationConfig) {\n super(\n '@opentelemetry/instrumentation-fetch',\n VERSION,\n config\n );\n }\n\n init(): void {}\n\n private _getConfig(): FetchInstrumentationConfig {\n return this._config;\n }\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n */\n private _addChildSpan(\n span: api.Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n const childSpan = this.tracer.startSpan(\n 'CORS Preflight',\n {\n startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START],\n },\n api.trace.setSpan(api.context.active(), span)\n );\n web.addSpanNetworkEvents(childSpan, corsPreFlightRequest);\n childSpan.end(\n corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]\n );\n }\n\n /**\n * Adds more attributes to span just before ending it\n * @param span\n * @param response\n */\n private _addFinalSpanAttributes(\n span: api.Span,\n response: FetchResponse\n ): void {\n const parsedUrl = web.parseUrl(response.url);\n span.setAttribute(SemanticAttributes.HTTP_STATUS_CODE, response.status);\n if (response.statusText != null) {\n span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, response.statusText);\n }\n span.setAttribute(SemanticAttributes.HTTP_HOST, parsedUrl.host);\n span.setAttribute(\n SemanticAttributes.HTTP_SCHEME,\n parsedUrl.protocol.replace(':', '')\n );\n span.setAttribute(SemanticAttributes.HTTP_USER_AGENT, navigator.userAgent);\n }\n\n /**\n * Add headers\n * @param options\n * @param spanUrl\n */\n private _addHeaders(options: Request | RequestInit, spanUrl: string): void {\n if (\n !web.shouldPropagateTraceHeaders(\n spanUrl,\n this._getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n\n if (options instanceof Request) {\n api.propagation.inject(api.context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else if(options.headers instanceof Headers) {\n api.propagation.inject(api.context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n options.headers = Object.assign({}, headers, options.headers || {});\n }\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link FetchPluginConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this._getConfig().clearTimingResources) {\n performance.clearResourceTimings();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Creates a new span\n * @param url\n * @param options\n */\n private _createSpan(\n url: string,\n options: Partial<Request | RequestInit> = {}\n ): api.Span | undefined {\n if (core.isUrlIgnored(url, this._getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n const method = (options.method || 'GET').toUpperCase();\n const spanName = `HTTP ${method}`;\n return this.tracer.startSpan(spanName, {\n kind: api.SpanKind.CLIENT,\n attributes: {\n [AttributeNames.COMPONENT]: this.moduleName,\n [SemanticAttributes.HTTP_METHOD]: method,\n [SemanticAttributes.HTTP_URL]: url,\n },\n });\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n * @param resourcesObserver\n * @param endTime\n */\n private _findResourceAndAddNetworkEvents(\n span: api.Span,\n resourcesObserver: SpanData,\n endTime: api.HrTime\n ): void {\n let resources: PerformanceResourceTiming[] = resourcesObserver.entries;\n if (!resources.length) {\n if (!performance.getEntriesByType) {\n return;\n }\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n resources = performance.getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n const resource = web.getResource(\n resourcesObserver.spanUrl,\n resourcesObserver.startTime,\n endTime,\n resources,\n this._usedResources,\n 'fetch'\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n web.addSpanNetworkEvents(span, mainRequest);\n }\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming): void {\n this._usedResources.add(resource);\n }\n\n /**\n * Finish span, add attributes, network events etc.\n * @param span\n * @param spanData\n * @param response\n */\n private _endSpan(\n span: api.Span,\n spanData: SpanData,\n response: FetchResponse\n ) {\n const endTime = core.hrTime();\n this._addFinalSpanAttributes(span, response);\n\n setTimeout(() => {\n spanData.observer?.disconnect();\n this._findResourceAndAddNetworkEvents(span, spanData, endTime);\n this._tasksCount--;\n this._clearResources();\n span.end(endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n /**\n * Patches the constructor of fetch\n */\n private _patchConstructor(): (original: Window['fetch']) => Window['fetch'] {\n return original => {\n const plugin = this;\n return function patchConstructor(\n this: Window,\n ...args: Parameters<Window['fetch']>\n ): Promise<Response> {\n const url = args[0] instanceof Request ? args[0].url : args[0];\n const options = args[0] instanceof Request ? args[0] : args[1] || {};\n const createdSpan = plugin._createSpan(url, options);\n if (!createdSpan) {\n return original.apply(this, args);\n }\n const spanData = plugin._prepareSpanData(url);\n\n function endSpanOnError(span: api.Span, error: FetchError) {\n plugin._applyAttributesAfterFetch(span, options, error);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n statusText: error.message,\n url,\n });\n }\n\n function endSpanOnSuccess(span: api.Span, response: Response) {\n plugin._applyAttributesAfterFetch(span, options, response);\n if (response.status >= 200 && response.status < 400) {\n plugin._endSpan(span, spanData, response);\n } else {\n plugin._endSpan(span, spanData, {\n status: response.status,\n statusText: response.statusText,\n url,\n });\n }\n }\n function onSuccess(\n span: api.Span,\n resolve: (value: Response | PromiseLike<Response>) => void,\n response: Response\n ): void {\n try {\n const resClone = response.clone();\n const resClone4Hook = response.clone();\n const body = resClone.body;\n if (body) {\n const reader = body.getReader();\n const read = (): void => {\n reader.read().then(\n ({ done }) => {\n if (done) {\n endSpanOnSuccess(span, resClone4Hook);\n } else {\n read();\n }\n },\n error => {\n endSpanOnError(span, error);\n }\n );\n };\n read();\n } else {\n // some older browsers don't have .body implemented\n endSpanOnSuccess(span, response);\n }\n } finally {\n resolve(response);\n }\n }\n\n function onError(\n span: api.Span,\n reject: (reason?: unknown) => void,\n error: FetchError\n ) {\n try {\n endSpanOnError(span, error);\n } finally {\n reject(error);\n }\n }\n\n return new Promise((resolve, reject) => {\n return api.context.with(\n api.trace.setSpan(api.context.active(), createdSpan),\n () => {\n plugin._addHeaders(options, url);\n plugin._tasksCount++;\n return original\n .apply(this, options instanceof Request ? [options] : [url, options])\n .then(\n onSuccess.bind(this, createdSpan, resolve),\n onError.bind(this, createdSpan, reject)\n );\n }\n );\n });\n };\n };\n }\n\n private _applyAttributesAfterFetch(\n span: api.Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ) {\n const applyCustomAttributesOnSpan = this._getConfig()\n .applyCustomAttributesOnSpan;\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, request, result),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * Prepares a span data - needed later for matching appropriate network\n * resources\n * @param spanUrl\n */\n private _prepareSpanData(spanUrl: string): SpanData {\n const startTime = core.hrTime();\n const entries: PerformanceResourceTiming[] = [];\n if (typeof window.PerformanceObserver === 'undefined') {\n return { entries, startTime, spanUrl };\n }\n\n const observer: PerformanceObserver = new PerformanceObserver(list => {\n const perfObsEntries = list.getEntries() as PerformanceResourceTiming[];\n const urlNormalizingAnchor = web.getUrlNormalizingAnchor();\n urlNormalizingAnchor.href = spanUrl;\n perfObsEntries.forEach(entry => {\n if (\n entry.initiatorType === 'fetch' &&\n entry.name === urlNormalizingAnchor.href\n ) {\n entries.push(entry);\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n return { entries, observer, startTime, spanUrl };\n }\n\n /**\n * implements enable function\n */\n override enable(): void {\n if (isWrapped(window.fetch)) {\n this._unwrap(window, 'fetch');\n this._diag.debug('removing previous patch for constructor');\n }\n this._wrap(window, 'fetch', this._patchConstructor());\n }\n\n /**\n * implements unpatch function\n */\n override disable(): void {\n this._unwrap(window, 'fetch');\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"]}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/fetch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,SAAS,EACT,mBAAmB,EAEnB,sBAAsB,GACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,IAAI,MAAM,qBAAqB,CAAC;AAC5C,OAAO,KAAK,GAAG,MAAM,8BAA8B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM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AC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,iBAAiB,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED;;OAEG;IACM,sCAAO,GAAhB;QACE,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,cAAc,GAAG,IAAI,OAAO,EAA6B,CAAC;IACjE,CAAC;IACH,2BAAC;AAAD,CAAC,AAlZD,CAA0C,mBAAmB,GAkZ5D","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationConfig,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport * as core from '@opentelemetry/core';\nimport * as web from '@opentelemetry/sdk-trace-web';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { FetchError, FetchResponse, SpanData } from './types';\nimport { VERSION } from './version';\nimport { _globalThis } from '@opentelemetry/core';\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nexport interface FetchCustomAttributeFunction {\n (\n span: api.Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ): void;\n}\n\n/**\n * FetchPlugin Config\n */\nexport interface FetchInstrumentationConfig extends InstrumentationConfig {\n // the number of timing resources is limited, after the limit\n // (chrome 250, safari 150) the information is not collected anymore\n // the only way to prevent that is to regularly clean the resources\n // whenever it is possible, this is needed only when PerformanceObserver\n // is not available\n clearTimingResources?: boolean;\n // urls which should include trace headers when origin doesn't match\n propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;\n}\n\n/**\n * This class represents a fetch plugin for auto instrumentation\n */\nexport class FetchInstrumentation extends InstrumentationBase<Promise<Response>> {\n readonly component: string = 'fetch';\n readonly version: string = VERSION;\n moduleName = this.component;\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n private _tasksCount = 0;\n\n constructor(config?: FetchInstrumentationConfig) {\n super(\n '@opentelemetry/instrumentation-fetch',\n VERSION,\n config\n );\n }\n\n init(): void {}\n\n private _getConfig(): FetchInstrumentationConfig {\n return this._config;\n }\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n */\n private _addChildSpan(\n span: api.Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n const childSpan = this.tracer.startSpan(\n 'CORS Preflight',\n {\n startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START],\n },\n api.trace.setSpan(api.context.active(), span)\n );\n web.addSpanNetworkEvents(childSpan, corsPreFlightRequest);\n childSpan.end(\n corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]\n );\n }\n\n /**\n * Adds more attributes to span just before ending it\n * @param span\n * @param response\n */\n private _addFinalSpanAttributes(\n span: api.Span,\n response: FetchResponse\n ): void {\n const parsedUrl = web.parseUrl(response.url);\n span.setAttribute(SemanticAttributes.HTTP_STATUS_CODE, response.status);\n if (response.statusText != null) {\n span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, response.statusText);\n }\n span.setAttribute(SemanticAttributes.HTTP_HOST, parsedUrl.host);\n span.setAttribute(\n SemanticAttributes.HTTP_SCHEME,\n parsedUrl.protocol.replace(':', '')\n );\n span.setAttribute(SemanticAttributes.HTTP_USER_AGENT, navigator.userAgent);\n }\n\n /**\n * Add headers\n * @param options\n * @param spanUrl\n */\n private _addHeaders(options: Request | RequestInit, spanUrl: string): void {\n if (\n !web.shouldPropagateTraceHeaders(\n spanUrl,\n this._getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n\n if (options instanceof Request) {\n api.propagation.inject(api.context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else if (options.headers instanceof Headers) {\n api.propagation.inject(api.context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n options.headers = Object.assign({}, headers, options.headers || {});\n }\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link FetchPluginConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this._getConfig().clearTimingResources) {\n performance.clearResourceTimings();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Creates a new span\n * @param url\n * @param options\n */\n private _createSpan(\n url: string,\n options: Partial<Request | RequestInit> = {}\n ): api.Span | undefined {\n if (core.isUrlIgnored(url, this._getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n const method = (options.method || 'GET').toUpperCase();\n const spanName = `HTTP ${method}`;\n return this.tracer.startSpan(spanName, {\n kind: api.SpanKind.CLIENT,\n attributes: {\n [AttributeNames.COMPONENT]: this.moduleName,\n [SemanticAttributes.HTTP_METHOD]: method,\n [SemanticAttributes.HTTP_URL]: url,\n },\n });\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n * @param resourcesObserver\n * @param endTime\n */\n private _findResourceAndAddNetworkEvents(\n span: api.Span,\n resourcesObserver: SpanData,\n endTime: api.HrTime\n ): void {\n let resources: PerformanceResourceTiming[] = resourcesObserver.entries;\n if (!resources.length) {\n if (!performance.getEntriesByType) {\n return;\n }\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n resources = performance.getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n const resource = web.getResource(\n resourcesObserver.spanUrl,\n resourcesObserver.startTime,\n endTime,\n resources,\n this._usedResources,\n 'fetch'\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n web.addSpanNetworkEvents(span, mainRequest);\n }\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming): void {\n this._usedResources.add(resource);\n }\n\n /**\n * Finish span, add attributes, network events etc.\n * @param span\n * @param spanData\n * @param response\n */\n private _endSpan(\n span: api.Span,\n spanData: SpanData,\n response: FetchResponse\n ) {\n const endTime = core.hrTime();\n this._addFinalSpanAttributes(span, response);\n\n setTimeout(() => {\n spanData.observer?.disconnect();\n this._findResourceAndAddNetworkEvents(span, spanData, endTime);\n this._tasksCount--;\n this._clearResources();\n span.end(endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n /**\n * Patches the constructor of fetch\n */\n private _patchConstructor(): (original: typeof fetch) => typeof fetch {\n return original => {\n const plugin = this;\n return function patchConstructor(\n this: typeof globalThis,\n ...args: Parameters<typeof fetch>\n ): Promise<Response> {\n const self = this;\n const url = web.parseUrl(args[0] instanceof Request ? args[0].url : args[0]).href;\n\n const options = args[0] instanceof Request ? args[0] : args[1] || {};\n const createdSpan = plugin._createSpan(url, options);\n if (!createdSpan) {\n return original.apply(this, args);\n }\n const spanData = plugin._prepareSpanData(url);\n\n function endSpanOnError(span: api.Span, error: FetchError) {\n plugin._applyAttributesAfterFetch(span, options, error);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n statusText: error.message,\n url,\n });\n }\n\n function endSpanOnSuccess(span: api.Span, response: Response) {\n plugin._applyAttributesAfterFetch(span, options, response);\n const spanResponse = {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n url\n };\n if (response.status >= 200 && response.status < 400) {\n if (response.url != null && response.url !== '') {\n spanResponse.url = url;\n }\n }\n plugin._endSpan(span, spanData, {\n status: response.status,\n statusText: response.statusText,\n url,\n });\n }\n\n function onSuccess(\n span: api.Span,\n resolve: (value: Response | PromiseLike<Response>) => void,\n response: Response\n ): void {\n try {\n const resClone = response.clone();\n const resClone4Hook = response.clone();\n const body = resClone.body;\n if (body) {\n const reader = body.getReader();\n const read = (): void => {\n reader.read().then(\n ({ done }) => {\n if (done) {\n endSpanOnSuccess(span, resClone4Hook);\n } else {\n read();\n }\n },\n error => {\n endSpanOnError(span, error);\n }\n );\n };\n read();\n } else {\n // some older browsers don't have .body implemented\n endSpanOnSuccess(span, response);\n }\n } finally {\n resolve(response);\n }\n }\n\n function onError(\n span: api.Span,\n reject: (reason?: unknown) => void,\n error: FetchError\n ) {\n try {\n endSpanOnError(span, error);\n } finally {\n reject(error);\n }\n }\n\n return new Promise((resolve, reject) => {\n return api.context.with(\n api.trace.setSpan(api.context.active(), createdSpan),\n () => {\n plugin._addHeaders(options, url);\n plugin._tasksCount++;\n // TypeScript complains about arrow function captured a this typed as globalThis\n // ts(7041)\n return original\n .apply(self, options instanceof Request ? [options] : [url, options])\n .then(\n onSuccess.bind(self, createdSpan, resolve),\n onError.bind(self, createdSpan, reject)\n );\n }\n );\n });\n };\n };\n }\n\n private _applyAttributesAfterFetch(\n span: api.Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ) {\n const applyCustomAttributesOnSpan = this._getConfig()\n .applyCustomAttributesOnSpan;\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, request, result),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * Prepares a span data - needed later for matching appropriate network\n * resources\n * @param spanUrl\n */\n private _prepareSpanData(spanUrl: string): SpanData {\n const startTime = core.hrTime();\n const entries: PerformanceResourceTiming[] = [];\n if (typeof PerformanceObserver !== 'function') {\n return { entries, startTime, spanUrl };\n }\n\n const observer = new PerformanceObserver(list => {\n const perfObsEntries = list.getEntries() as PerformanceResourceTiming[];\n perfObsEntries.forEach(entry => {\n if (\n entry.initiatorType === 'fetch' &&\n entry.name === spanUrl\n ) {\n entries.push(entry);\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n return { entries, observer, startTime, spanUrl };\n }\n\n /**\n * implements enable function\n */\n override enable(): void {\n if (isWrapped(fetch)) {\n this._unwrap(_globalThis, 'fetch');\n this._diag.debug('removing previous patch for constructor');\n }\n this._wrap(_globalThis, 'fetch', this._patchConstructor());\n }\n\n /**\n * implements unpatch function\n */\n override disable(): void {\n this._unwrap(_globalThis, 'fetch');\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.27.0";
1
+ export declare const VERSION = "0.29.1";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -14,5 +14,5 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  // this is autogenerated file, see scripts/version-update.js
17
- export var VERSION = '0.27.0';
17
+ export var VERSION = '0.29.1';
18
18
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.27.0';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.29.1';\n"]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md
3
+ */
4
+ export declare enum AttributeNames {
5
+ COMPONENT = "component",
6
+ HTTP_ERROR_NAME = "http.error_name",
7
+ HTTP_STATUS_TEXT = "http.status_text"
8
+ }
9
+ //# sourceMappingURL=AttributeNames.d.ts.map
@@ -0,0 +1,25 @@
1
+ /*
2
+ * Copyright The OpenTelemetry Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md
18
+ */
19
+ export var AttributeNames;
20
+ (function (AttributeNames) {
21
+ AttributeNames["COMPONENT"] = "component";
22
+ AttributeNames["HTTP_ERROR_NAME"] = "http.error_name";
23
+ AttributeNames["HTTP_STATUS_TEXT"] = "http.status_text";
24
+ })(AttributeNames || (AttributeNames = {}));
25
+ //# sourceMappingURL=AttributeNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AttributeNames.js","sourceRoot":"","sources":["../../../src/enums/AttributeNames.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;GAEG;AACH,MAAM,CAAN,IAAY,cAIX;AAJD,WAAY,cAAc;IACxB,yCAAuB,CAAA;IACvB,qDAAmC,CAAA;IACnC,uDAAqC,CAAA;AACvC,CAAC,EAJW,cAAc,KAAd,cAAc,QAIzB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md\n */\nexport enum AttributeNames {\n COMPONENT = 'component',\n HTTP_ERROR_NAME = 'http.error_name',\n HTTP_STATUS_TEXT = 'http.status_text',\n}\n"]}
@@ -0,0 +1,107 @@
1
+ import * as api from '@opentelemetry/api';
2
+ import { InstrumentationBase, InstrumentationConfig } from '@opentelemetry/instrumentation';
3
+ import * as web from '@opentelemetry/sdk-trace-web';
4
+ import { FetchError } from './types';
5
+ export interface FetchCustomAttributeFunction {
6
+ (span: api.Span, request: Request | RequestInit, result: Response | FetchError): void;
7
+ }
8
+ /**
9
+ * FetchPlugin Config
10
+ */
11
+ export interface FetchInstrumentationConfig extends InstrumentationConfig {
12
+ clearTimingResources?: boolean;
13
+ propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;
14
+ /**
15
+ * URLs that partially match any regex in ignoreUrls will not be traced.
16
+ * In addition, URLs that are _exact matches_ of strings in ignoreUrls will
17
+ * also not be traced.
18
+ */
19
+ ignoreUrls?: Array<string | RegExp>;
20
+ /** Function for adding custom attributes on the span */
21
+ applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;
22
+ }
23
+ /**
24
+ * This class represents a fetch plugin for auto instrumentation
25
+ */
26
+ export declare class FetchInstrumentation extends InstrumentationBase<Promise<Response>> {
27
+ readonly component: string;
28
+ readonly version: string;
29
+ moduleName: string;
30
+ private _usedResources;
31
+ private _tasksCount;
32
+ constructor(config?: FetchInstrumentationConfig);
33
+ init(): void;
34
+ private _getConfig;
35
+ /**
36
+ * Add cors pre flight child span
37
+ * @param span
38
+ * @param corsPreFlightRequest
39
+ */
40
+ private _addChildSpan;
41
+ /**
42
+ * Adds more attributes to span just before ending it
43
+ * @param span
44
+ * @param response
45
+ */
46
+ private _addFinalSpanAttributes;
47
+ /**
48
+ * Add headers
49
+ * @param options
50
+ * @param spanUrl
51
+ */
52
+ private _addHeaders;
53
+ /**
54
+ * Clears the resource timings and all resources assigned with spans
55
+ * when {@link FetchPluginConfig.clearTimingResources} is
56
+ * set to true (default false)
57
+ * @private
58
+ */
59
+ private _clearResources;
60
+ /**
61
+ * Creates a new span
62
+ * @param url
63
+ * @param options
64
+ */
65
+ private _createSpan;
66
+ /**
67
+ * Finds appropriate resource and add network events to the span
68
+ * @param span
69
+ * @param resourcesObserver
70
+ * @param endTime
71
+ */
72
+ private _findResourceAndAddNetworkEvents;
73
+ /**
74
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
75
+ * from this is used to add events to span.
76
+ * This is done to avoid reusing the same resource again for next span
77
+ * @param resource
78
+ */
79
+ private _markResourceAsUsed;
80
+ /**
81
+ * Finish span, add attributes, network events etc.
82
+ * @param span
83
+ * @param spanData
84
+ * @param response
85
+ */
86
+ private _endSpan;
87
+ /**
88
+ * Patches the constructor of fetch
89
+ */
90
+ private _patchConstructor;
91
+ private _applyAttributesAfterFetch;
92
+ /**
93
+ * Prepares a span data - needed later for matching appropriate network
94
+ * resources
95
+ * @param spanUrl
96
+ */
97
+ private _prepareSpanData;
98
+ /**
99
+ * implements enable function
100
+ */
101
+ enable(): void;
102
+ /**
103
+ * implements unpatch function
104
+ */
105
+ disable(): void;
106
+ }
107
+ //# sourceMappingURL=fetch.d.ts.map