@sentry/opentelemetry 8.0.0-alpha.7 → 8.0.0-alpha.9

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/esm/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { _optionalChain } from '@sentry/utils';
2
2
  import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
3
- import { parseUrl, getSanitizedUrlString, LRUMap, logger, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, stringMatchesSomePattern, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, dropUndefinedKeys, stripUrlQueryAndFragment, isNaN } from '@sentry/utils';
3
+ import { parseUrl, getSanitizedUrlString, baggageHeaderToDynamicSamplingContext, stripUrlQueryAndFragment, LRUMap, logger, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, stringMatchesSomePattern, dynamicSamplingContextToSentryBaggageHeader, dropUndefinedKeys } from '@sentry/utils';
4
4
  import * as api from '@opentelemetry/api';
5
- import { trace, SpanKind, createContextKey, propagation, TraceFlags, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
6
- import { SDK_VERSION, getCurrentScope, getIsolationScope, getClient, getDynamicSamplingContextFromClient, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isSentryRequestUrl, handleCallbackErrors, SEMANTIC_ATTRIBUTE_SENTRY_OP, getRootSpan, continueTrace as continueTrace$1, withScope, captureEvent, addBreadcrumb, setUser, setTags, setTag, setExtra, setExtras, setContext, startSession, endSession, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getStatusMessage, getMetricSummaryJsonForSpan, addChildSpanToSpan, hasTracingEnabled } from '@sentry/core';
5
+ import { trace, SpanKind, createContextKey, TraceFlags, propagation, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
6
+ import { SDK_VERSION, getClient, getDynamicSamplingContextFromClient, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isSentryRequestUrl, getCurrentScope, getIsolationScope, getRootSpan, spanToJSON, handleCallbackErrors, SEMANTIC_ATTRIBUTE_SENTRY_OP, continueTrace as continueTrace$1, withScope, captureEvent, addBreadcrumb, setUser, setTags, setTag, setExtra, setExtras, setContext, startSession, endSession, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, timedEventsToMeasurements, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getStatusMessage, getMetricSummaryJsonForSpan, addChildSpanToSpan, logSpanStart, logSpanEnd, hasTracingEnabled, sampleSpan } from '@sentry/core';
7
7
  export { getClient } from '@sentry/core';
8
8
  import { W3CBaggagePropagator, isTracingSuppressed, TraceState, suppressTracing } from '@opentelemetry/core';
9
9
  import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
@@ -116,7 +116,7 @@ function getRequestSpanData(span) {
116
116
  return data;
117
117
  }
118
118
 
119
- function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
119
+ function _optionalChain$9(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
120
120
 
121
121
  // Typescript complains if we do not use `...args: any[]` for the mixin, with:
122
122
  // A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
@@ -157,7 +157,7 @@ function wrapClientClass
157
157
  */
158
158
  async flush(timeout) {
159
159
  const provider = this.traceProvider;
160
- const spanProcessor = _optionalChain$8([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
160
+ const spanProcessor = _optionalChain$9([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
161
161
 
162
162
  if (spanProcessor) {
163
163
  await spanProcessor.forceFlush();
@@ -262,6 +262,273 @@ function getContextFromScope(scope) {
262
262
  return SCOPE_CONTEXT_MAP.get(scope);
263
263
  }
264
264
 
265
+ function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
266
+
267
+ /**
268
+ * OpenTelemetry only knows about SAMPLED or NONE decision,
269
+ * but for us it is important to differentiate between unset and unsampled.
270
+ *
271
+ * Both of these are identified as `traceFlags === TracegFlags.NONE`,
272
+ * but we additionally look at a special trace state to differentiate between them.
273
+ */
274
+ function getSamplingDecision(spanContext) {
275
+ const { traceFlags, traceState } = spanContext;
276
+
277
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
278
+
279
+ // If trace flag is `SAMPLED`, we interpret this as sampled
280
+ // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
281
+ // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
282
+ // to identify which it is
283
+ if (traceFlags === TraceFlags.SAMPLED) {
284
+ return true;
285
+ }
286
+
287
+ if (sampledNotRecording) {
288
+ return false;
289
+ }
290
+
291
+ // Fall back to DSC as a last resort, that may also contain `sampled`...
292
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
293
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
294
+
295
+ if (_optionalChain$8([dsc, 'optionalAccess', _ => _.sampled]) === 'true') {
296
+ return true;
297
+ }
298
+ if (_optionalChain$8([dsc, 'optionalAccess', _2 => _2.sampled]) === 'false') {
299
+ return false;
300
+ }
301
+
302
+ return undefined;
303
+ }
304
+
305
+ /**
306
+ * Extract better op/description from an otel span.
307
+ *
308
+ * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
309
+ */
310
+ function parseSpanDescription(span) {
311
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
312
+ const name = spanHasName(span) ? span.name : '<unknown>';
313
+
314
+ // if http.method exists, this is an http request span
315
+ const httpMethod = attributes[SemanticAttributes.HTTP_METHOD];
316
+ if (httpMethod) {
317
+ return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
318
+ }
319
+
320
+ // If db.type exists then this is a database call span.
321
+ const dbSystem = attributes[SemanticAttributes.DB_SYSTEM];
322
+ if (dbSystem) {
323
+ return descriptionForDbSystem({ attributes, name });
324
+ }
325
+
326
+ // If rpc.service exists then this is a rpc call span.
327
+ const rpcService = attributes[SemanticAttributes.RPC_SERVICE];
328
+ if (rpcService) {
329
+ return {
330
+ op: 'rpc',
331
+ description: name,
332
+ source: 'route',
333
+ };
334
+ }
335
+
336
+ // If messaging.system exists then this is a messaging system span.
337
+ const messagingSystem = attributes[SemanticAttributes.MESSAGING_SYSTEM];
338
+ if (messagingSystem) {
339
+ return {
340
+ op: 'message',
341
+ description: name,
342
+ source: 'route',
343
+ };
344
+ }
345
+
346
+ // If faas.trigger exists then this is a function as a service span.
347
+ const faasTrigger = attributes[SemanticAttributes.FAAS_TRIGGER];
348
+ if (faasTrigger) {
349
+ return { op: faasTrigger.toString(), description: name, source: 'route' };
350
+ }
351
+
352
+ return { op: undefined, description: name, source: 'custom' };
353
+ }
354
+
355
+ function descriptionForDbSystem({ attributes, name }) {
356
+ // Use DB statement (Ex "SELECT * FROM table") if possible as description.
357
+ const statement = attributes[SemanticAttributes.DB_STATEMENT];
358
+
359
+ const description = statement ? statement.toString() : name;
360
+
361
+ return { op: 'db', description, source: 'task' };
362
+ }
363
+
364
+ /** Only exported for tests. */
365
+ function descriptionForHttpMethod(
366
+ { name, kind, attributes },
367
+ httpMethod,
368
+ ) {
369
+ const opParts = ['http'];
370
+
371
+ switch (kind) {
372
+ case SpanKind.CLIENT:
373
+ opParts.push('client');
374
+ break;
375
+ case SpanKind.SERVER:
376
+ opParts.push('server');
377
+ break;
378
+ }
379
+
380
+ const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
381
+
382
+ if (!urlPath) {
383
+ return { op: opParts.join('.'), description: name, source: 'custom' };
384
+ }
385
+
386
+ // Ex. description="GET /api/users".
387
+ const description = `${httpMethod} ${urlPath}`;
388
+
389
+ // If `httpPath` is a root path, then we can categorize the transaction source as route.
390
+ const source = hasRoute || urlPath === '/' ? 'route' : 'url';
391
+
392
+ const data = {};
393
+
394
+ if (url) {
395
+ data.url = url;
396
+ }
397
+ if (query) {
398
+ data['http.query'] = query;
399
+ }
400
+ if (fragment) {
401
+ data['http.fragment'] = fragment;
402
+ }
403
+
404
+ return {
405
+ op: opParts.join('.'),
406
+ description,
407
+ source,
408
+ data,
409
+ };
410
+ }
411
+
412
+ /** Exported for tests only */
413
+ function getSanitizedUrl(
414
+ attributes,
415
+ kind,
416
+ )
417
+
418
+ {
419
+ // This is the relative path of the URL, e.g. /sub
420
+ const httpTarget = attributes[SemanticAttributes.HTTP_TARGET];
421
+ // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
422
+ const httpUrl = attributes[SemanticAttributes.HTTP_URL];
423
+ // This is the normalized route name - may not always be available!
424
+ const httpRoute = attributes[SemanticAttributes.HTTP_ROUTE];
425
+
426
+ const parsedUrl = typeof httpUrl === 'string' ? parseUrl(httpUrl) : undefined;
427
+ const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : undefined;
428
+ const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
429
+ const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
430
+
431
+ if (typeof httpRoute === 'string') {
432
+ return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
433
+ }
434
+
435
+ if (kind === SpanKind.SERVER && typeof httpTarget === 'string') {
436
+ return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
437
+ }
438
+
439
+ if (parsedUrl) {
440
+ return { urlPath: url, url, query, fragment, hasRoute: false };
441
+ }
442
+
443
+ // fall back to target even for client spans, if no URL is present
444
+ if (typeof httpTarget === 'string') {
445
+ return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
446
+ }
447
+
448
+ return { urlPath: undefined, url, query, fragment, hasRoute: false };
449
+ }
450
+
451
+ function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
452
+ /**
453
+ * Creates a dynamic sampling context from a span (and client and scope)
454
+ *
455
+ * @param span the span from which a few values like the root span name and sample rate are extracted.
456
+ *
457
+ * @returns a dynamic sampling context
458
+ */
459
+ function getDynamicSamplingContextFromSpan(span) {
460
+ const client = getClient();
461
+ if (!client) {
462
+ return {};
463
+ }
464
+
465
+ const traceState = span.spanContext().traceState;
466
+ const traceStateDsc = _optionalChain$7([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
467
+
468
+ // If the span has a DSC, we want it to take precedence
469
+ const dscOnSpan = traceStateDsc ? baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
470
+
471
+ if (dscOnSpan) {
472
+ return dscOnSpan;
473
+ }
474
+
475
+ const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
476
+
477
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
478
+
479
+ const sampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
480
+ if (sampleRate != null) {
481
+ dsc.sample_rate = `${sampleRate}`;
482
+ }
483
+
484
+ // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
485
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
486
+
487
+ // If the span has no name, we assume it is non-recording and want to opt out of using any description
488
+ const { description } = spanHasName(span) ? parseSpanDescription(span) : { description: '' };
489
+
490
+ if (source !== 'url' && description) {
491
+ dsc.transaction = description;
492
+ }
493
+
494
+ const sampled = getSamplingDecision(span.spanContext());
495
+ if (sampled != null) {
496
+ dsc.sampled = String(sampled);
497
+ }
498
+
499
+ client.emit('createDsc', dsc);
500
+
501
+ return dsc;
502
+ }
503
+
504
+ /**
505
+ *
506
+ * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
507
+ * @returns boolean
508
+ */
509
+ function isSentryRequestSpan(span) {
510
+ if (!spanHasAttributes(span)) {
511
+ return false;
512
+ }
513
+
514
+ const { attributes } = span;
515
+
516
+ const httpUrl = attributes[SemanticAttributes.HTTP_URL];
517
+
518
+ if (!httpUrl) {
519
+ return false;
520
+ }
521
+
522
+ return isSentryRequestUrl(httpUrl.toString(), getClient());
523
+ }
524
+
525
+ /**
526
+ * Returns the currently active span.
527
+ */
528
+ function getActiveSpan() {
529
+ return trace.getActiveSpan();
530
+ }
531
+
265
532
  /**
266
533
  * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
267
534
  *
@@ -281,18 +548,25 @@ function setIsSetup(element) {
281
548
  setupElements.add(element);
282
549
  }
283
550
 
284
- function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
551
+ function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
285
552
 
286
553
  /** Get the Sentry propagation context from a span context. */
287
- function getPropagationContextFromSpanContext(spanContext) {
554
+ function getPropagationContextFromSpan(span) {
555
+ const spanContext = span.spanContext();
288
556
  const { traceId, spanId, traceState } = spanContext;
289
557
 
558
+ // When we have a dsc trace state, it means this came from the incoming trace
559
+ // Then this takes presedence over the root span
290
560
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
291
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
561
+ const traceStateDsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
562
+
292
563
  const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) : undefined;
293
564
 
294
565
  const sampled = getSamplingDecision(spanContext);
295
566
 
567
+ // No trace state? --> Take DSC from root span
568
+ const dsc = traceStateDsc || getDynamicSamplingContextFromSpan(getRootSpan(span));
569
+
296
570
  return {
297
571
  traceId,
298
572
  spanId,
@@ -326,8 +600,8 @@ class SentryPropagator extends W3CBaggagePropagator {
326
600
  }
327
601
 
328
602
  const activeSpan = trace.getSpan(context);
329
- const url = activeSpan && _optionalChain$7([spanToJSON, 'call', _ => _(activeSpan), 'access', _2 => _2.data, 'optionalAccess', _3 => _3[SemanticAttributes.HTTP_URL]]);
330
- const tracePropagationTargets = _optionalChain$7([getClient, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getOptions, 'call', _6 => _6(), 'optionalAccess', _7 => _7.tracePropagationTargets]);
603
+ const url = activeSpan && _optionalChain$6([spanToJSON, 'call', _ => _(activeSpan), 'access', _2 => _2.data, 'optionalAccess', _3 => _3[SemanticAttributes.HTTP_URL]]);
604
+ const tracePropagationTargets = _optionalChain$6([getClient, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getOptions, 'call', _6 => _6(), 'optionalAccess', _7 => _7.tracePropagationTargets]);
331
605
  if (
332
606
  typeof url === 'string' &&
333
607
  tracePropagationTargets &&
@@ -338,10 +612,21 @@ class SentryPropagator extends W3CBaggagePropagator {
338
612
  return;
339
613
  }
340
614
 
615
+ const existingBaggageHeader = getExistingBaggage(carrier);
341
616
  let baggage = propagation.getBaggage(context) || propagation.createBaggage({});
342
617
 
343
618
  const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);
344
619
 
620
+ if (existingBaggageHeader) {
621
+ const baggageEntries = parseBaggageHeader(existingBaggageHeader);
622
+
623
+ if (baggageEntries) {
624
+ Object.entries(baggageEntries).forEach(([key, value]) => {
625
+ baggage = baggage.setEntry(key, { value });
626
+ });
627
+ }
628
+ }
629
+
345
630
  if (dynamicSamplingContext) {
346
631
  baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
347
632
  if (dscValue) {
@@ -439,12 +724,13 @@ function getInjectionData(context)
439
724
 
440
725
  {
441
726
  const span = trace.getSpan(context);
442
- const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _8 => _8.spanContext, 'call', _9 => _9(), 'access', _10 => _10.isRemote]);
727
+ const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _8 => _8.spanContext, 'call', _9 => _9(), 'access', _10 => _10.isRemote]);
443
728
 
444
729
  // If we have a local span, we can just pick everything from it
445
730
  if (span && !spanIsRemote) {
446
731
  const spanContext = span.spanContext();
447
- const propagationContext = getPropagationContextFromSpanContext(spanContext);
732
+
733
+ const propagationContext = getPropagationContextFromSpan(span);
448
734
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
449
735
  return {
450
736
  dynamicSamplingContext,
@@ -455,7 +741,7 @@ function getInjectionData(context)
455
741
  }
456
742
 
457
743
  // Else we try to use the propagation context from the scope
458
- const scope = _optionalChain$7([getScopesFromContext, 'call', _11 => _11(context), 'optionalAccess', _12 => _12.scope]);
744
+ const scope = _optionalChain$6([getScopesFromContext, 'call', _11 => _11(context), 'optionalAccess', _12 => _12.scope]);
459
745
  if (scope) {
460
746
  const propagationContext = scope.getPropagationContext();
461
747
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
@@ -468,9 +754,9 @@ function getInjectionData(context)
468
754
  }
469
755
 
470
756
  // Else, we look at the remote span context
471
- const spanContext = trace.getSpanContext(context);
472
- if (spanContext) {
473
- const propagationContext = getPropagationContextFromSpanContext(spanContext);
757
+ if (span) {
758
+ const spanContext = span.spanContext();
759
+ const propagationContext = getPropagationContextFromSpan(span);
474
760
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
475
761
 
476
762
  return {
@@ -497,173 +783,66 @@ function getDynamicSamplingContext(
497
783
  traceId,
498
784
  ) {
499
785
  // If we have a DSC on the propagation context, we just use it
500
- if (_optionalChain$7([propagationContext, 'optionalAccess', _13 => _13.dsc])) {
786
+ if (_optionalChain$6([propagationContext, 'optionalAccess', _13 => _13.dsc])) {
501
787
  return propagationContext.dsc;
502
788
  }
503
-
504
- // Else, we try to generate a new one
505
- const client = getClient();
506
-
507
- if (client) {
508
- return getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);
509
- }
510
-
511
- return undefined;
512
- }
513
-
514
- function getContextWithRemoteActiveSpan(
515
- ctx,
516
- { sentryTrace, baggage },
517
- ) {
518
- const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
519
-
520
- // We store the DSC as OTEL trace state on the span context
521
- const traceState = makeTraceState({
522
- parentSpanId: propagationContext.parentSpanId,
523
- dsc: propagationContext.dsc,
524
- sampled: propagationContext.sampled,
525
- });
526
-
527
- const spanContext = {
528
- traceId: propagationContext.traceId,
529
- spanId: propagationContext.parentSpanId || '',
530
- isRemote: true,
531
- traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
532
- traceState,
533
- };
534
-
535
- return trace.setSpanContext(ctx, spanContext);
536
- }
537
-
538
- /**
539
- * Takes trace strings and propagates them as a remote active span.
540
- * This should be used in addition to `continueTrace` in OTEL-powered environments.
541
- */
542
- function continueTraceAsRemoteSpan(
543
- ctx,
544
- options,
545
- callback,
546
- ) {
547
- const ctxWithSpanContext = getContextWithRemoteActiveSpan(ctx, options);
548
-
549
- return context.with(ctxWithSpanContext, callback);
550
- }
551
-
552
- /**
553
- * OpenTelemetry only knows about SAMPLED or NONE decision,
554
- * but for us it is important to differentiate between unset and unsampled.
555
- *
556
- * Both of these are identified as `traceFlags === TracegFlags.NONE`,
557
- * but we additionally look at a special trace state to differentiate between them.
558
- */
559
- function getSamplingDecision(spanContext) {
560
- const { traceFlags, traceState } = spanContext;
561
-
562
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
563
-
564
- // If trace flag is `SAMPLED`, we interpret this as sampled
565
- // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
566
- // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
567
- // to identify which it is
568
- if (traceFlags === TraceFlags.SAMPLED) {
569
- return true;
570
- }
571
-
572
- if (sampledNotRecording) {
573
- return false;
574
- }
575
-
576
- // Fall back to DSC as a last resort, that may also contain `sampled`...
577
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
578
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
579
-
580
- if (_optionalChain$7([dsc, 'optionalAccess', _14 => _14.sampled]) === 'true') {
581
- return true;
582
- }
583
- if (_optionalChain$7([dsc, 'optionalAccess', _15 => _15.sampled]) === 'false') {
584
- return false;
585
- }
586
-
587
- return undefined;
588
- }
589
-
590
- function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
591
- /**
592
- * Creates a dynamic sampling context from a span (and client and scope)
593
- *
594
- * @param span the span from which a few values like the root span name and sample rate are extracted.
595
- *
596
- * @returns a dynamic sampling context
597
- */
598
- function getDynamicSamplingContextFromSpan(span) {
599
- const client = getClient();
600
- if (!client) {
601
- return {};
602
- }
603
-
604
- const traceState = span.spanContext().traceState;
605
- const traceStateDsc = _optionalChain$6([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
606
-
607
- // If the span has a DSC, we want it to take precedence
608
- const dscOnSpan = traceStateDsc ? baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
609
-
610
- if (dscOnSpan) {
611
- return dscOnSpan;
612
- }
613
-
614
- const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
615
-
616
- const attributes = spanHasAttributes(span) ? span.attributes : {};
617
-
618
- const sampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
619
- if (sampleRate != null) {
620
- dsc.sample_rate = `${sampleRate}`;
621
- }
622
-
623
- // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
624
- const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
625
- const name = spanHasName(span) ? span.name : '';
626
-
627
- if (source !== 'url' && name) {
628
- dsc.transaction = name;
629
- }
630
-
631
- const sampled = getSamplingDecision(span.spanContext());
632
- if (sampled != null) {
633
- dsc.sampled = String(sampled);
634
- }
635
-
636
- client.emit('createDsc', dsc);
637
-
638
- return dsc;
639
- }
640
-
641
- /**
642
- *
643
- * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
644
- * @returns boolean
645
- */
646
- function isSentryRequestSpan(span) {
647
- if (!spanHasAttributes(span)) {
648
- return false;
789
+
790
+ // Else, we try to generate a new one
791
+ const client = getClient();
792
+
793
+ if (client) {
794
+ return getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);
649
795
  }
650
796
 
651
- const { attributes } = span;
797
+ return undefined;
798
+ }
652
799
 
653
- const httpUrl = attributes[SemanticAttributes.HTTP_URL];
800
+ function getContextWithRemoteActiveSpan(
801
+ ctx,
802
+ { sentryTrace, baggage },
803
+ ) {
804
+ const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
654
805
 
655
- if (!httpUrl) {
656
- return false;
657
- }
806
+ // We store the DSC as OTEL trace state on the span context
807
+ const traceState = makeTraceState({
808
+ parentSpanId: propagationContext.parentSpanId,
809
+ dsc: propagationContext.dsc,
810
+ sampled: propagationContext.sampled,
811
+ });
658
812
 
659
- return isSentryRequestUrl(httpUrl.toString(), getClient());
813
+ const spanContext = {
814
+ traceId: propagationContext.traceId,
815
+ spanId: propagationContext.parentSpanId || '',
816
+ isRemote: true,
817
+ traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
818
+ traceState,
819
+ };
820
+
821
+ return trace.setSpanContext(ctx, spanContext);
660
822
  }
661
823
 
662
824
  /**
663
- * Returns the currently active span.
825
+ * Takes trace strings and propagates them as a remote active span.
826
+ * This should be used in addition to `continueTrace` in OTEL-powered environments.
664
827
  */
665
- function getActiveSpan() {
666
- return trace.getActiveSpan();
828
+ function continueTraceAsRemoteSpan(
829
+ ctx,
830
+ options,
831
+ callback,
832
+ ) {
833
+ const ctxWithSpanContext = getContextWithRemoteActiveSpan(ctx, options);
834
+
835
+ return context.with(ctxWithSpanContext, callback);
836
+ }
837
+
838
+ /** Try to get the existing baggage header so we can merge this in. */
839
+ function getExistingBaggage(carrier) {
840
+ try {
841
+ const baggage = (carrier )[SENTRY_BAGGAGE_HEADER];
842
+ return Array.isArray(baggage) ? baggage.join(',') : baggage;
843
+ } catch (e) {
844
+ return undefined;
845
+ }
667
846
  }
668
847
 
669
848
  function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
@@ -828,13 +1007,12 @@ function getContext(scope, forceTransaction) {
828
1007
 
829
1008
  if (actualScope && client) {
830
1009
  const propagationContext = actualScope.getPropagationContext();
831
- const dynamicSamplingContext =
832
- propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
833
1010
 
834
1011
  // We store the DSC as OTEL trace state on the span context
835
1012
  const traceState = makeTraceState({
836
1013
  parentSpanId: propagationContext.parentSpanId,
837
- dsc: dynamicSamplingContext,
1014
+ // Not defined yet, we want to pick this up on-demand only
1015
+ dsc: undefined,
838
1016
  sampled: propagationContext.sampled,
839
1017
  });
840
1018
 
@@ -869,6 +1047,8 @@ function getContext(scope, forceTransaction) {
869
1047
  const { spanId, traceId } = parentSpan.spanContext();
870
1048
  const sampled = getSamplingDecision(parentSpan.spanContext());
871
1049
 
1050
+ // In this case, when we are forcing a transaction, we want to treat this like continuing an incoming trace
1051
+ // so we set the traceState according to the root span
872
1052
  const rootSpan = getRootSpan(parentSpan);
873
1053
  const dsc = getDynamicSamplingContextFromSpan(rootSpan);
874
1054
 
@@ -936,25 +1116,11 @@ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[
936
1116
  */
937
1117
  function getCurrentHub() {
938
1118
  return {
939
- isOlderThan(_version) {
940
- return false;
941
- },
942
-
943
1119
  bindClient(client) {
944
1120
  const scope = getCurrentScope();
945
1121
  scope.setClient(client);
946
1122
  },
947
1123
 
948
- pushScope() {
949
- // TODO: This does not work and is actually deprecated
950
- return getCurrentScope();
951
- },
952
-
953
- popScope() {
954
- // TODO: This does not work and is actually deprecated
955
- return false;
956
- },
957
-
958
1124
  withScope,
959
1125
  getClient: () => getClient() ,
960
1126
  getScope: getCurrentScope,
@@ -992,11 +1158,6 @@ function getCurrentHub() {
992
1158
  // only send the update
993
1159
  _sendSessionUpdate();
994
1160
  },
995
-
996
- shouldSendDefaultPii() {
997
- const client = getClient();
998
- return Boolean(client ? client.getOptions().sendDefaultPii : false);
999
- },
1000
1161
  };
1001
1162
  }
1002
1163
 
@@ -1368,152 +1529,6 @@ function mapStatus(span) {
1368
1529
  }
1369
1530
  }
1370
1531
 
1371
- /**
1372
- * Extract better op/description from an otel span.
1373
- *
1374
- * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
1375
- */
1376
- function parseSpanDescription(span) {
1377
- const attributes = spanHasAttributes(span) ? span.attributes : {};
1378
- const name = spanHasName(span) ? span.name : '<unknown>';
1379
-
1380
- // if http.method exists, this is an http request span
1381
- const httpMethod = attributes[SemanticAttributes.HTTP_METHOD];
1382
- if (httpMethod) {
1383
- return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
1384
- }
1385
-
1386
- // If db.type exists then this is a database call span.
1387
- const dbSystem = attributes[SemanticAttributes.DB_SYSTEM];
1388
- if (dbSystem) {
1389
- return descriptionForDbSystem({ attributes, name });
1390
- }
1391
-
1392
- // If rpc.service exists then this is a rpc call span.
1393
- const rpcService = attributes[SemanticAttributes.RPC_SERVICE];
1394
- if (rpcService) {
1395
- return {
1396
- op: 'rpc',
1397
- description: name,
1398
- source: 'route',
1399
- };
1400
- }
1401
-
1402
- // If messaging.system exists then this is a messaging system span.
1403
- const messagingSystem = attributes[SemanticAttributes.MESSAGING_SYSTEM];
1404
- if (messagingSystem) {
1405
- return {
1406
- op: 'message',
1407
- description: name,
1408
- source: 'route',
1409
- };
1410
- }
1411
-
1412
- // If faas.trigger exists then this is a function as a service span.
1413
- const faasTrigger = attributes[SemanticAttributes.FAAS_TRIGGER];
1414
- if (faasTrigger) {
1415
- return { op: faasTrigger.toString(), description: name, source: 'route' };
1416
- }
1417
-
1418
- return { op: undefined, description: name, source: 'custom' };
1419
- }
1420
-
1421
- function descriptionForDbSystem({ attributes, name }) {
1422
- // Use DB statement (Ex "SELECT * FROM table") if possible as description.
1423
- const statement = attributes[SemanticAttributes.DB_STATEMENT];
1424
-
1425
- const description = statement ? statement.toString() : name;
1426
-
1427
- return { op: 'db', description, source: 'task' };
1428
- }
1429
-
1430
- /** Only exported for tests. */
1431
- function descriptionForHttpMethod(
1432
- { name, kind, attributes },
1433
- httpMethod,
1434
- ) {
1435
- const opParts = ['http'];
1436
-
1437
- switch (kind) {
1438
- case SpanKind.CLIENT:
1439
- opParts.push('client');
1440
- break;
1441
- case SpanKind.SERVER:
1442
- opParts.push('server');
1443
- break;
1444
- }
1445
-
1446
- const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
1447
-
1448
- if (!urlPath) {
1449
- return { op: opParts.join('.'), description: name, source: 'custom' };
1450
- }
1451
-
1452
- // Ex. description="GET /api/users".
1453
- const description = `${httpMethod} ${urlPath}`;
1454
-
1455
- // If `httpPath` is a root path, then we can categorize the transaction source as route.
1456
- const source = hasRoute || urlPath === '/' ? 'route' : 'url';
1457
-
1458
- const data = {};
1459
-
1460
- if (url) {
1461
- data.url = url;
1462
- }
1463
- if (query) {
1464
- data['http.query'] = query;
1465
- }
1466
- if (fragment) {
1467
- data['http.fragment'] = fragment;
1468
- }
1469
-
1470
- return {
1471
- op: opParts.join('.'),
1472
- description,
1473
- source,
1474
- data,
1475
- };
1476
- }
1477
-
1478
- /** Exported for tests only */
1479
- function getSanitizedUrl(
1480
- attributes,
1481
- kind,
1482
- )
1483
-
1484
- {
1485
- // This is the relative path of the URL, e.g. /sub
1486
- const httpTarget = attributes[SemanticAttributes.HTTP_TARGET];
1487
- // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
1488
- const httpUrl = attributes[SemanticAttributes.HTTP_URL];
1489
- // This is the normalized route name - may not always be available!
1490
- const httpRoute = attributes[SemanticAttributes.HTTP_ROUTE];
1491
-
1492
- const parsedUrl = typeof httpUrl === 'string' ? parseUrl(httpUrl) : undefined;
1493
- const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : undefined;
1494
- const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
1495
- const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
1496
-
1497
- if (typeof httpRoute === 'string') {
1498
- return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
1499
- }
1500
-
1501
- if (kind === SpanKind.SERVER && typeof httpTarget === 'string') {
1502
- return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1503
- }
1504
-
1505
- if (parsedUrl) {
1506
- return { urlPath: url, url, query, fragment, hasRoute: false };
1507
- }
1508
-
1509
- // fall back to target even for client spans, if no URL is present
1510
- if (typeof httpTarget === 'string') {
1511
- return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1512
- }
1513
-
1514
- return { urlPath: undefined, url, query, fragment, hasRoute: false };
1515
- }
1516
-
1517
1532
  function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1518
1533
 
1519
1534
  /**
@@ -1625,7 +1640,10 @@ function maybeSend(spans) {
1625
1640
 
1626
1641
  transactionEvent.spans = spans;
1627
1642
 
1628
- // TODO Measurements are not yet implemented in OTEL
1643
+ const measurements = timedEventsToMeasurements(span.events);
1644
+ if (Object.keys(measurements).length) {
1645
+ transactionEvent.measurements = measurements;
1646
+ }
1629
1647
 
1630
1648
  captureEvent(transactionEvent);
1631
1649
  });
@@ -1866,13 +1884,17 @@ function onSpanStart(span, parentContext) {
1866
1884
  setSpanScopes(span, scopes);
1867
1885
  }
1868
1886
 
1887
+ logSpanStart(span);
1888
+
1869
1889
  const client = getClient();
1870
1890
  _optionalChain$1([client, 'optionalAccess', _ => _.emit, 'call', _2 => _2('spanStart', span)]);
1871
1891
  }
1872
1892
 
1873
1893
  function onSpanEnd(span) {
1894
+ logSpanEnd(span);
1895
+
1874
1896
  const client = getClient();
1875
- _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span )]);
1897
+ _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1876
1898
  }
1877
1899
 
1878
1900
  /**
@@ -1905,22 +1927,10 @@ class SentrySpanProcessor {
1905
1927
  */
1906
1928
  onStart(span, parentContext) {
1907
1929
  onSpanStart(span, parentContext);
1908
-
1909
- // TODO (v8): Trigger client `spanStart` & `spanEnd` in here,
1910
- // once we decoupled opentelemetry from SentrySpan
1911
-
1912
- DEBUG_BUILD && logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1913
1930
  }
1914
1931
 
1915
1932
  /** @inheritDoc */
1916
1933
  onEnd(span) {
1917
- if (span.spanContext().traceFlags !== TraceFlags.SAMPLED) {
1918
- DEBUG_BUILD && logger.log(`[Tracing] Finishing unsampled span "${span.name}" (${span.spanContext().spanId})`);
1919
- return;
1920
- }
1921
-
1922
- DEBUG_BUILD && logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1923
-
1924
1934
  onSpanEnd(span);
1925
1935
 
1926
1936
  this._exporter.export(span);
@@ -1928,7 +1938,7 @@ class SentrySpanProcessor {
1928
1938
  }
1929
1939
 
1930
1940
  /**
1931
- * A custom OTEL sampler that uses Sentry sampling rates to make it's decision
1941
+ * A custom OTEL sampler that uses Sentry sampling rates to make its decision
1932
1942
  */
1933
1943
  class SentrySampler {
1934
1944
 
@@ -1952,16 +1962,17 @@ class SentrySampler {
1952
1962
  return { decision: SamplingDecision.NOT_RECORD };
1953
1963
  }
1954
1964
 
1955
- const parentContext = trace.getSpanContext(context);
1956
- const traceState = _optionalChain([parentContext, 'optionalAccess', _ => _.traceState]) || new TraceState();
1965
+ const parentSpan = trace.getSpan(context);
1966
+ const parentContext = _optionalChain([parentSpan, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2()]);
1967
+ const traceState = _optionalChain([parentContext, 'optionalAccess', _3 => _3.traceState]) || new TraceState();
1957
1968
 
1958
1969
  let parentSampled = undefined;
1959
1970
 
1960
1971
  // Only inherit sample rate if `traceId` is the same
1961
1972
  // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones
1962
- if (parentContext && isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1973
+ if (parentSpan && parentContext && isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1963
1974
  if (parentContext.isRemote) {
1964
- parentSampled = getParentRemoteSampled(parentContext);
1975
+ parentSampled = getParentRemoteSampled(parentSpan);
1965
1976
  DEBUG_BUILD &&
1966
1977
  logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
1967
1978
  } else {
@@ -1970,7 +1981,7 @@ class SentrySampler {
1970
1981
  }
1971
1982
  }
1972
1983
 
1973
- const sampleRate = getSampleRate(options, {
1984
+ const [sampled, sampleRate] = sampleSpan(options, {
1974
1985
  name: spanName,
1975
1986
  attributes: spanAttributes,
1976
1987
  transactionContext: {
@@ -1981,32 +1992,12 @@ class SentrySampler {
1981
1992
  });
1982
1993
 
1983
1994
  const attributes = {
1984
- [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: Number(sampleRate),
1995
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
1985
1996
  };
1986
1997
 
1987
- // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
1988
- // only valid values are booleans or numbers between 0 and 1.)
1989
- if (!isValidSampleRate(sampleRate)) {
1990
- DEBUG_BUILD && logger.warn('[Tracing] Discarding span because of invalid sample rate.');
1991
-
1992
- return {
1993
- decision: SamplingDecision.NOT_RECORD,
1994
- attributes,
1995
- traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
1996
- };
1997
- }
1998
-
1999
- // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped
2000
- if (!sampleRate) {
2001
- DEBUG_BUILD &&
2002
- logger.log(
2003
- `[Tracing] Discarding span because ${
2004
- typeof options.tracesSampler === 'function'
2005
- ? 'tracesSampler returned 0 or false'
2006
- : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'
2007
- }`,
2008
- );
2009
-
1998
+ const method = `${spanAttributes[SemanticAttributes.HTTP_METHOD]}`.toUpperCase();
1999
+ if (method === 'OPTIONS' || method === 'HEAD') {
2000
+ DEBUG_BUILD && logger.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
2010
2001
  return {
2011
2002
  decision: SamplingDecision.NOT_RECORD,
2012
2003
  attributes,
@@ -2014,19 +2005,7 @@ class SentrySampler {
2014
2005
  };
2015
2006
  }
2016
2007
 
2017
- // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
2018
- // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
2019
- const isSampled = Math.random() < (sampleRate );
2020
-
2021
- // if we're not going to keep it, we're done
2022
- if (!isSampled) {
2023
- DEBUG_BUILD &&
2024
- logger.log(
2025
- `[Tracing] Discarding span because it's not included in the random sample (sampling rate = ${Number(
2026
- sampleRate,
2027
- )})`,
2028
- );
2029
-
2008
+ if (!sampled) {
2030
2009
  return {
2031
2010
  decision: SamplingDecision.NOT_RECORD,
2032
2011
  attributes,
@@ -2046,57 +2025,9 @@ class SentrySampler {
2046
2025
  }
2047
2026
  }
2048
2027
 
2049
- function getSampleRate(
2050
- options,
2051
- samplingContext,
2052
- ) {
2053
- if (typeof options.tracesSampler === 'function') {
2054
- return options.tracesSampler(samplingContext);
2055
- }
2056
-
2057
- if (samplingContext.parentSampled !== undefined) {
2058
- return samplingContext.parentSampled;
2059
- }
2060
-
2061
- if (typeof options.tracesSampleRate !== 'undefined') {
2062
- return options.tracesSampleRate;
2063
- }
2064
-
2065
- // When `enableTracing === true`, we use a sample rate of 100%
2066
- if (options.enableTracing) {
2067
- return 1;
2068
- }
2069
-
2070
- return 0;
2071
- }
2072
-
2073
- /**
2074
- * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).
2075
- */
2076
- function isValidSampleRate(rate) {
2077
- // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
2078
- if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
2079
- DEBUG_BUILD &&
2080
- logger.warn(
2081
- `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
2082
- rate,
2083
- )} of type ${JSON.stringify(typeof rate)}.`,
2084
- );
2085
- return false;
2086
- }
2087
-
2088
- // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
2089
- if (rate < 0 || rate > 1) {
2090
- DEBUG_BUILD &&
2091
- logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
2092
- return false;
2093
- }
2094
- return true;
2095
- }
2096
-
2097
- function getParentRemoteSampled(spanContext) {
2098
- const traceId = spanContext.traceId;
2099
- const traceparentData = getPropagationContextFromSpanContext(spanContext);
2028
+ function getParentRemoteSampled(parentSpan) {
2029
+ const traceId = parentSpan.spanContext().traceId;
2030
+ const traceparentData = getPropagationContextFromSpan(parentSpan);
2100
2031
 
2101
2032
  // Only inherit sampled if `traceId` is the same
2102
2033
  return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;