http.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { _optionalChain } from '@sentry/utils';
  2. import { defineIntegration, getClient, isSentryRequestUrl, getCurrentScope, getIsolationScope, getActiveSpan, spanToTraceHeader, getDynamicSamplingContextFromSpan, getDynamicSamplingContextFromClient, setHttpStatus, spanToJSON, hasTracingEnabled, getCurrentHub, addBreadcrumb } from '@sentry/core';
  3. import { dropUndefinedKeys, logger, fill, LRUMap, generateSentryTraceHeader, dynamicSamplingContextToSentryBaggageHeader, stringMatchesSomePattern } from '@sentry/utils';
  4. import { DEBUG_BUILD } from '../debug-build.js';
  5. import { NODE_VERSION } from '../nodeVersion.js';
  6. import { normalizeRequestArgs, extractRawUrl, extractUrl, cleanSpanDescription } from './utils/http.js';
  7. const _httpIntegration = ((options = {}) => {
  8. const { breadcrumbs, tracing, shouldCreateSpanForRequest } = options;
  9. const convertedOptions = {
  10. breadcrumbs,
  11. tracing:
  12. tracing === false
  13. ? false
  14. : dropUndefinedKeys({
  15. // If tracing is forced to `true`, we don't want to set `enableIfHasTracingEnabled`
  16. enableIfHasTracingEnabled: tracing === true ? undefined : true,
  17. shouldCreateSpanForRequest,
  18. }),
  19. };
  20. // eslint-disable-next-line deprecation/deprecation
  21. return new Http(convertedOptions) ;
  22. }) ;
  23. /**
  24. * The http module integration instruments Node's internal http module. It creates breadcrumbs, spans for outgoing
  25. * http requests, and attaches trace data when tracing is enabled via its `tracing` option.
  26. *
  27. * By default, this will always create breadcrumbs, and will create spans if tracing is enabled.
  28. */
  29. const httpIntegration = defineIntegration(_httpIntegration);
  30. /**
  31. * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing
  32. * http requests and attaches trace data when tracing is enabled via its `tracing` option.
  33. *
  34. * @deprecated Use `httpIntegration()` instead.
  35. */
  36. class Http {
  37. /**
  38. * @inheritDoc
  39. */
  40. static __initStatic() {this.id = 'Http';}
  41. /**
  42. * @inheritDoc
  43. */
  44. // eslint-disable-next-line deprecation/deprecation
  45. __init() {this.name = Http.id;}
  46. /**
  47. * @inheritDoc
  48. */
  49. constructor(options = {}) {Http.prototype.__init.call(this);
  50. this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;
  51. this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing;
  52. }
  53. /**
  54. * @inheritDoc
  55. */
  56. setupOnce(
  57. _addGlobalEventProcessor,
  58. setupOnceGetCurrentHub,
  59. ) {
  60. // eslint-disable-next-line deprecation/deprecation
  61. const clientOptions = _optionalChain([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);
  62. // If `tracing` is not explicitly set, we default this based on whether or not tracing is enabled.
  63. // But for compatibility, we only do that if `enableIfHasTracingEnabled` is set.
  64. const shouldCreateSpans = _shouldCreateSpans(this._tracing, clientOptions);
  65. // No need to instrument if we don't want to track anything
  66. if (!this._breadcrumbs && !shouldCreateSpans) {
  67. return;
  68. }
  69. // Do not auto-instrument for other instrumenter
  70. if (clientOptions && clientOptions.instrumenter !== 'sentry') {
  71. DEBUG_BUILD && logger.log('HTTP Integration is skipped because of instrumenter configuration.');
  72. return;
  73. }
  74. const shouldCreateSpanForRequest = _getShouldCreateSpanForRequest(shouldCreateSpans, this._tracing, clientOptions);
  75. // eslint-disable-next-line deprecation/deprecation
  76. const tracePropagationTargets = _optionalChain([clientOptions, 'optionalAccess', _6 => _6.tracePropagationTargets]) || _optionalChain([this, 'access', _7 => _7._tracing, 'optionalAccess', _8 => _8.tracePropagationTargets]);
  77. // eslint-disable-next-line @typescript-eslint/no-var-requires
  78. const httpModule = require('http');
  79. const wrappedHttpHandlerMaker = _createWrappedRequestMethodFactory(
  80. httpModule,
  81. this._breadcrumbs,
  82. shouldCreateSpanForRequest,
  83. tracePropagationTargets,
  84. );
  85. fill(httpModule, 'get', wrappedHttpHandlerMaker);
  86. fill(httpModule, 'request', wrappedHttpHandlerMaker);
  87. // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.
  88. // If we do, we'd get double breadcrumbs and double spans for `https` calls.
  89. // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately.
  90. if (NODE_VERSION.major > 8) {
  91. // eslint-disable-next-line @typescript-eslint/no-var-requires
  92. const httpsModule = require('https');
  93. const wrappedHttpsHandlerMaker = _createWrappedRequestMethodFactory(
  94. httpsModule,
  95. this._breadcrumbs,
  96. shouldCreateSpanForRequest,
  97. tracePropagationTargets,
  98. );
  99. fill(httpsModule, 'get', wrappedHttpsHandlerMaker);
  100. fill(httpsModule, 'request', wrappedHttpsHandlerMaker);
  101. }
  102. }
  103. }Http.__initStatic();
  104. // for ease of reading below
  105. /**
  106. * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http`
  107. * and `https` modules. (NB: Not a typo - this is a creator^2!)
  108. *
  109. * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs
  110. * @param tracingEnabled Whether or not to record outgoing requests as tracing spans
  111. *
  112. * @returns A function which accepts the exiting handler and returns a wrapped handler
  113. */
  114. function _createWrappedRequestMethodFactory(
  115. httpModule,
  116. breadcrumbsEnabled,
  117. shouldCreateSpanForRequest,
  118. tracePropagationTargets,
  119. ) {
  120. // We're caching results so we don't have to recompute regexp every time we create a request.
  121. const createSpanUrlMap = new LRUMap(100);
  122. const headersUrlMap = new LRUMap(100);
  123. const shouldCreateSpan = (url) => {
  124. if (shouldCreateSpanForRequest === undefined) {
  125. return true;
  126. }
  127. const cachedDecision = createSpanUrlMap.get(url);
  128. if (cachedDecision !== undefined) {
  129. return cachedDecision;
  130. }
  131. const decision = shouldCreateSpanForRequest(url);
  132. createSpanUrlMap.set(url, decision);
  133. return decision;
  134. };
  135. const shouldAttachTraceData = (url) => {
  136. if (tracePropagationTargets === undefined) {
  137. return true;
  138. }
  139. const cachedDecision = headersUrlMap.get(url);
  140. if (cachedDecision !== undefined) {
  141. return cachedDecision;
  142. }
  143. const decision = stringMatchesSomePattern(url, tracePropagationTargets);
  144. headersUrlMap.set(url, decision);
  145. return decision;
  146. };
  147. /**
  148. * Captures Breadcrumb based on provided request/response pair
  149. */
  150. function addRequestBreadcrumb(
  151. event,
  152. requestSpanData,
  153. req,
  154. res,
  155. ) {
  156. // eslint-disable-next-line deprecation/deprecation
  157. if (!getCurrentHub().getIntegration(Http)) {
  158. return;
  159. }
  160. addBreadcrumb(
  161. {
  162. category: 'http',
  163. data: {
  164. status_code: res && res.statusCode,
  165. ...requestSpanData,
  166. },
  167. type: 'http',
  168. },
  169. {
  170. event,
  171. request: req,
  172. response: res,
  173. },
  174. );
  175. }
  176. return function wrappedRequestMethodFactory(originalRequestMethod) {
  177. return function wrappedMethod( ...args) {
  178. const requestArgs = normalizeRequestArgs(httpModule, args);
  179. const requestOptions = requestArgs[0];
  180. // eslint-disable-next-line deprecation/deprecation
  181. const rawRequestUrl = extractRawUrl(requestOptions);
  182. const requestUrl = extractUrl(requestOptions);
  183. const client = getClient();
  184. // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method
  185. if (isSentryRequestUrl(requestUrl, client)) {
  186. return originalRequestMethod.apply(httpModule, requestArgs);
  187. }
  188. const scope = getCurrentScope();
  189. const isolationScope = getIsolationScope();
  190. const parentSpan = getActiveSpan();
  191. const data = getRequestSpanData(requestUrl, requestOptions);
  192. const requestSpan = shouldCreateSpan(rawRequestUrl)
  193. ? // eslint-disable-next-line deprecation/deprecation
  194. _optionalChain([parentSpan, 'optionalAccess', _9 => _9.startChild, 'call', _10 => _10({
  195. op: 'http.client',
  196. origin: 'auto.http.node.http',
  197. description: `${data['http.method']} ${data.url}`,
  198. data,
  199. })])
  200. : undefined;
  201. if (client && shouldAttachTraceData(rawRequestUrl)) {
  202. const { traceId, spanId, sampled, dsc } = {
  203. ...isolationScope.getPropagationContext(),
  204. ...scope.getPropagationContext(),
  205. };
  206. const sentryTraceHeader = requestSpan
  207. ? spanToTraceHeader(requestSpan)
  208. : generateSentryTraceHeader(traceId, spanId, sampled);
  209. const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(
  210. dsc ||
  211. (requestSpan
  212. ? getDynamicSamplingContextFromSpan(requestSpan)
  213. : getDynamicSamplingContextFromClient(traceId, client, scope)),
  214. );
  215. addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, sentryBaggageHeader);
  216. } else {
  217. DEBUG_BUILD &&
  218. logger.log(
  219. `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`,
  220. );
  221. }
  222. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  223. return originalRequestMethod
  224. .apply(httpModule, requestArgs)
  225. .once('response', function ( res) {
  226. // eslint-disable-next-line @typescript-eslint/no-this-alias
  227. const req = this;
  228. if (breadcrumbsEnabled) {
  229. addRequestBreadcrumb('response', data, req, res);
  230. }
  231. if (requestSpan) {
  232. if (res.statusCode) {
  233. setHttpStatus(requestSpan, res.statusCode);
  234. }
  235. requestSpan.updateName(
  236. cleanSpanDescription(spanToJSON(requestSpan).description || '', requestOptions, req) || '',
  237. );
  238. requestSpan.end();
  239. }
  240. })
  241. .once('error', function () {
  242. // eslint-disable-next-line @typescript-eslint/no-this-alias
  243. const req = this;
  244. if (breadcrumbsEnabled) {
  245. addRequestBreadcrumb('error', data, req);
  246. }
  247. if (requestSpan) {
  248. setHttpStatus(requestSpan, 500);
  249. requestSpan.updateName(
  250. cleanSpanDescription(spanToJSON(requestSpan).description || '', requestOptions, req) || '',
  251. );
  252. requestSpan.end();
  253. }
  254. });
  255. };
  256. };
  257. }
  258. function addHeadersToRequestOptions(
  259. requestOptions,
  260. requestUrl,
  261. sentryTraceHeader,
  262. sentryBaggageHeader,
  263. ) {
  264. // Don't overwrite sentry-trace and baggage header if it's already set.
  265. const headers = requestOptions.headers || {};
  266. if (headers['sentry-trace']) {
  267. return;
  268. }
  269. DEBUG_BUILD &&
  270. logger.log(`[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `);
  271. requestOptions.headers = {
  272. ...requestOptions.headers,
  273. 'sentry-trace': sentryTraceHeader,
  274. // Setting a header to `undefined` will crash in node so we only set the baggage header when it's defined
  275. ...(sentryBaggageHeader &&
  276. sentryBaggageHeader.length > 0 && { baggage: normalizeBaggageHeader(requestOptions, sentryBaggageHeader) }),
  277. };
  278. }
  279. function getRequestSpanData(requestUrl, requestOptions) {
  280. const method = requestOptions.method || 'GET';
  281. const data = {
  282. url: requestUrl,
  283. 'http.method': method,
  284. };
  285. if (requestOptions.hash) {
  286. // strip leading "#"
  287. data['http.fragment'] = requestOptions.hash.substring(1);
  288. }
  289. if (requestOptions.search) {
  290. // strip leading "?"
  291. data['http.query'] = requestOptions.search.substring(1);
  292. }
  293. return data;
  294. }
  295. function normalizeBaggageHeader(
  296. requestOptions,
  297. sentryBaggageHeader,
  298. ) {
  299. if (!requestOptions.headers || !requestOptions.headers.baggage) {
  300. return sentryBaggageHeader;
  301. } else if (!sentryBaggageHeader) {
  302. return requestOptions.headers.baggage ;
  303. } else if (Array.isArray(requestOptions.headers.baggage)) {
  304. return [...requestOptions.headers.baggage, sentryBaggageHeader];
  305. }
  306. // Type-cast explanation:
  307. // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity
  308. // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this.
  309. return [requestOptions.headers.baggage, sentryBaggageHeader] ;
  310. }
  311. /** Exported for tests only. */
  312. function _shouldCreateSpans(
  313. tracingOptions,
  314. clientOptions,
  315. ) {
  316. return tracingOptions === undefined
  317. ? false
  318. : tracingOptions.enableIfHasTracingEnabled
  319. ? hasTracingEnabled(clientOptions)
  320. : true;
  321. }
  322. /** Exported for tests only. */
  323. function _getShouldCreateSpanForRequest(
  324. shouldCreateSpans,
  325. tracingOptions,
  326. clientOptions,
  327. ) {
  328. const handler = shouldCreateSpans
  329. ? // eslint-disable-next-line deprecation/deprecation
  330. _optionalChain([tracingOptions, 'optionalAccess', _11 => _11.shouldCreateSpanForRequest]) || _optionalChain([clientOptions, 'optionalAccess', _12 => _12.shouldCreateSpanForRequest])
  331. : () => false;
  332. return handler;
  333. }
  334. export { Http, _getShouldCreateSpanForRequest, _shouldCreateSpans, httpIntegration };
  335. //# sourceMappingURL=http.js.map