@sentry/opentelemetry 8.0.0-alpha.5 → 8.0.0-alpha.8

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/cjs/index.js CHANGED
@@ -119,7 +119,7 @@ function getRequestSpanData(span) {
119
119
  return data;
120
120
  }
121
121
 
122
- 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; }
122
+ 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; }
123
123
 
124
124
  // Typescript complains if we do not use `...args: any[]` for the mixin, with:
125
125
  // A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
@@ -160,7 +160,7 @@ function wrapClientClass
160
160
  */
161
161
  async flush(timeout) {
162
162
  const provider = this.traceProvider;
163
- const spanProcessor = _optionalChain$8([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
163
+ const spanProcessor = _optionalChain$9([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
164
164
 
165
165
  if (spanProcessor) {
166
166
  await spanProcessor.forceFlush();
@@ -265,6 +265,280 @@ function getContextFromScope(scope) {
265
265
  return SCOPE_CONTEXT_MAP.get(scope);
266
266
  }
267
267
 
268
+ 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; }
269
+
270
+ /**
271
+ * OpenTelemetry only knows about SAMPLED or NONE decision,
272
+ * but for us it is important to differentiate between unset and unsampled.
273
+ *
274
+ * Both of these are identified as `traceFlags === TracegFlags.NONE`,
275
+ * but we additionally look at a special trace state to differentiate between them.
276
+ */
277
+ function getSamplingDecision(spanContext) {
278
+ const { traceFlags, traceState } = spanContext;
279
+
280
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
281
+
282
+ // If trace flag is `SAMPLED`, we interpret this as sampled
283
+ // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
284
+ // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
285
+ // to identify which it is
286
+ if (traceFlags === api.TraceFlags.SAMPLED) {
287
+ return true;
288
+ }
289
+
290
+ if (sampledNotRecording) {
291
+ return false;
292
+ }
293
+
294
+ // Fall back to DSC as a last resort, that may also contain `sampled`...
295
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
296
+ const dsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
297
+
298
+ if (_optionalChain$8([dsc, 'optionalAccess', _ => _.sampled]) === 'true') {
299
+ return true;
300
+ }
301
+ if (_optionalChain$8([dsc, 'optionalAccess', _2 => _2.sampled]) === 'false') {
302
+ return false;
303
+ }
304
+
305
+ return undefined;
306
+ }
307
+
308
+ /**
309
+ * Extract better op/description from an otel span.
310
+ *
311
+ * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
312
+ */
313
+ function parseSpanDescription(span) {
314
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
315
+ const name = spanHasName(span) ? span.name : '<unknown>';
316
+
317
+ // if http.method exists, this is an http request span
318
+ const httpMethod = attributes[semanticConventions.SemanticAttributes.HTTP_METHOD];
319
+ if (httpMethod) {
320
+ return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
321
+ }
322
+
323
+ // If db.type exists then this is a database call span.
324
+ const dbSystem = attributes[semanticConventions.SemanticAttributes.DB_SYSTEM];
325
+ if (dbSystem) {
326
+ return descriptionForDbSystem({ attributes, name });
327
+ }
328
+
329
+ // If rpc.service exists then this is a rpc call span.
330
+ const rpcService = attributes[semanticConventions.SemanticAttributes.RPC_SERVICE];
331
+ if (rpcService) {
332
+ return {
333
+ op: 'rpc',
334
+ description: name,
335
+ source: 'route',
336
+ };
337
+ }
338
+
339
+ // If messaging.system exists then this is a messaging system span.
340
+ const messagingSystem = attributes[semanticConventions.SemanticAttributes.MESSAGING_SYSTEM];
341
+ if (messagingSystem) {
342
+ return {
343
+ op: 'message',
344
+ description: name,
345
+ source: 'route',
346
+ };
347
+ }
348
+
349
+ // If faas.trigger exists then this is a function as a service span.
350
+ const faasTrigger = attributes[semanticConventions.SemanticAttributes.FAAS_TRIGGER];
351
+ if (faasTrigger) {
352
+ return { op: faasTrigger.toString(), description: name, source: 'route' };
353
+ }
354
+
355
+ return { op: undefined, description: name, source: 'custom' };
356
+ }
357
+
358
+ function descriptionForDbSystem({ attributes, name }) {
359
+ // Use DB statement (Ex "SELECT * FROM table") if possible as description.
360
+ const statement = attributes[semanticConventions.SemanticAttributes.DB_STATEMENT];
361
+
362
+ const description = statement ? statement.toString() : name;
363
+
364
+ return { op: 'db', description, source: 'task' };
365
+ }
366
+
367
+ /** Only exported for tests. */
368
+ function descriptionForHttpMethod(
369
+ { name, kind, attributes },
370
+ httpMethod,
371
+ ) {
372
+ const opParts = ['http'];
373
+
374
+ switch (kind) {
375
+ case api.SpanKind.CLIENT:
376
+ opParts.push('client');
377
+ break;
378
+ case api.SpanKind.SERVER:
379
+ opParts.push('server');
380
+ break;
381
+ }
382
+
383
+ const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
384
+
385
+ if (!urlPath) {
386
+ return { op: opParts.join('.'), description: name, source: 'custom' };
387
+ }
388
+
389
+ // Ex. description="GET /api/users".
390
+ const description = `${httpMethod} ${urlPath}`;
391
+
392
+ // If `httpPath` is a root path, then we can categorize the transaction source as route.
393
+ const source = hasRoute || urlPath === '/' ? 'route' : 'url';
394
+
395
+ const data = {};
396
+
397
+ if (url) {
398
+ data.url = url;
399
+ }
400
+ if (query) {
401
+ data['http.query'] = query;
402
+ }
403
+ if (fragment) {
404
+ data['http.fragment'] = fragment;
405
+ }
406
+
407
+ return {
408
+ op: opParts.join('.'),
409
+ description,
410
+ source,
411
+ data,
412
+ };
413
+ }
414
+
415
+ /** Exported for tests only */
416
+ function getSanitizedUrl(
417
+ attributes,
418
+ kind,
419
+ )
420
+
421
+ {
422
+ // This is the relative path of the URL, e.g. /sub
423
+ const httpTarget = attributes[semanticConventions.SemanticAttributes.HTTP_TARGET];
424
+ // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
425
+ const httpUrl = attributes[semanticConventions.SemanticAttributes.HTTP_URL];
426
+ // This is the normalized route name - may not always be available!
427
+ const httpRoute = attributes[semanticConventions.SemanticAttributes.HTTP_ROUTE];
428
+
429
+ const parsedUrl = typeof httpUrl === 'string' ? utils.parseUrl(httpUrl) : undefined;
430
+ const url = parsedUrl ? utils.getSanitizedUrlString(parsedUrl) : undefined;
431
+ const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
432
+ const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
433
+
434
+ if (typeof httpRoute === 'string') {
435
+ return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
436
+ }
437
+
438
+ if (kind === api.SpanKind.SERVER && typeof httpTarget === 'string') {
439
+ return { urlPath: utils.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
440
+ }
441
+
442
+ if (parsedUrl) {
443
+ return { urlPath: url, url, query, fragment, hasRoute: false };
444
+ }
445
+
446
+ // fall back to target even for client spans, if no URL is present
447
+ if (typeof httpTarget === 'string') {
448
+ return { urlPath: utils.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
449
+ }
450
+
451
+ return { urlPath: undefined, url, query, fragment, hasRoute: false };
452
+ }
453
+
454
+ 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; }
455
+ /**
456
+ * Creates a dynamic sampling context from a span (and client and scope)
457
+ *
458
+ * @param span the span from which a few values like the root span name and sample rate are extracted.
459
+ *
460
+ * @returns a dynamic sampling context
461
+ */
462
+ function getDynamicSamplingContextFromSpan(span) {
463
+ const client = core.getClient();
464
+ if (!client) {
465
+ return {};
466
+ }
467
+
468
+ const traceState = span.spanContext().traceState;
469
+ const traceStateDsc = _optionalChain$7([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
470
+
471
+ // If the span has a DSC, we want it to take precedence
472
+ const dscOnSpan = traceStateDsc ? utils.baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
473
+
474
+ if (dscOnSpan) {
475
+ return dscOnSpan;
476
+ }
477
+
478
+ const dsc = core.getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
479
+
480
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
481
+
482
+ const sampleRate = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
483
+ if (sampleRate != null) {
484
+ dsc.sample_rate = `${sampleRate}`;
485
+ }
486
+
487
+ // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
488
+ const source = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
489
+
490
+ // If the span has no name, we assume it is non-recording and want to opt out of using any description
491
+ const { description } = spanHasName(span) ? parseSpanDescription(span) : { description: '' };
492
+
493
+ if (source !== 'url' && description) {
494
+ dsc.transaction = description;
495
+ }
496
+
497
+ const sampled = getSamplingDecision(span.spanContext());
498
+ if (sampled != null) {
499
+ dsc.sampled = String(sampled);
500
+ }
501
+
502
+ client.emit('createDsc', dsc);
503
+
504
+ return dsc;
505
+ }
506
+
507
+ /**
508
+ *
509
+ * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
510
+ * @returns boolean
511
+ */
512
+ function isSentryRequestSpan(span) {
513
+ if (!spanHasAttributes(span)) {
514
+ return false;
515
+ }
516
+
517
+ const { attributes } = span;
518
+
519
+ const httpUrl = attributes[semanticConventions.SemanticAttributes.HTTP_URL];
520
+
521
+ if (!httpUrl) {
522
+ return false;
523
+ }
524
+
525
+ return core.isSentryRequestUrl(httpUrl.toString(), core.getClient());
526
+ }
527
+
528
+ /**
529
+ * Returns the currently active span.
530
+ */
531
+ function getActiveSpan() {
532
+ return api.trace.getActiveSpan();
533
+ }
534
+
535
+ /**
536
+ * 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.
537
+ *
538
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
539
+ */
540
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
541
+
268
542
  const setupElements = new Set();
269
543
 
270
544
  /** Get all the OpenTelemetry elements that have been set up. */
@@ -277,18 +551,25 @@ function setIsSetup(element) {
277
551
  setupElements.add(element);
278
552
  }
279
553
 
280
- 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; }
554
+ 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; }
281
555
 
282
556
  /** Get the Sentry propagation context from a span context. */
283
- function getPropagationContextFromSpanContext(spanContext) {
557
+ function getPropagationContextFromSpan(span) {
558
+ const spanContext = span.spanContext();
284
559
  const { traceId, spanId, traceState } = spanContext;
285
560
 
561
+ // When we have a dsc trace state, it means this came from the incoming trace
562
+ // Then this takes presedence over the root span
286
563
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
287
- const dsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
564
+ const traceStateDsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
565
+
288
566
  const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) : undefined;
289
567
 
290
568
  const sampled = getSamplingDecision(spanContext);
291
569
 
570
+ // No trace state? --> Take DSC from root span
571
+ const dsc = traceStateDsc || getDynamicSamplingContextFromSpan(core.getRootSpan(span));
572
+
292
573
  return {
293
574
  traceId,
294
575
  spanId,
@@ -302,9 +583,14 @@ function getPropagationContextFromSpanContext(spanContext) {
302
583
  * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
303
584
  */
304
585
  class SentryPropagator extends core$1.W3CBaggagePropagator {
586
+ /** A map of URLs that have already been checked for if they match tracePropagationTargets. */
587
+
305
588
  constructor() {
306
589
  super();
307
590
  setIsSetup('SentryPropagator');
591
+
592
+ // We're caching results so we don't have to recompute regexp every time we create a request.
593
+ this._urlMatchesTargetsMap = new utils.LRUMap(100);
308
594
  }
309
595
 
310
596
  /**
@@ -312,13 +598,38 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
312
598
  */
313
599
  inject(context, carrier, setter) {
314
600
  if (core$1.isTracingSuppressed(context)) {
601
+ DEBUG_BUILD && utils.logger.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
315
602
  return;
316
603
  }
317
604
 
605
+ const activeSpan = api.trace.getSpan(context);
606
+ const url = activeSpan && _optionalChain$6([core.spanToJSON, 'call', _ => _(activeSpan), 'access', _2 => _2.data, 'optionalAccess', _3 => _3[semanticConventions.SemanticAttributes.HTTP_URL]]);
607
+ const tracePropagationTargets = _optionalChain$6([core.getClient, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getOptions, 'call', _6 => _6(), 'optionalAccess', _7 => _7.tracePropagationTargets]);
608
+ if (
609
+ typeof url === 'string' &&
610
+ tracePropagationTargets &&
611
+ !this._shouldInjectTraceData(tracePropagationTargets, url)
612
+ ) {
613
+ DEBUG_BUILD &&
614
+ utils.logger.log('[Tracing] Not injecting trace data for url because it does not matchTracePropagationTargets:', url);
615
+ return;
616
+ }
617
+
618
+ const existingBaggageHeader = getExistingBaggage(carrier);
318
619
  let baggage = api.propagation.getBaggage(context) || api.propagation.createBaggage({});
319
620
 
320
621
  const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);
321
622
 
623
+ if (existingBaggageHeader) {
624
+ const baggageEntries = utils.parseBaggageHeader(existingBaggageHeader);
625
+
626
+ if (baggageEntries) {
627
+ Object.entries(baggageEntries).forEach(([key, value]) => {
628
+ baggage = baggage.setEntry(key, { value });
629
+ });
630
+ }
631
+ }
632
+
322
633
  if (dynamicSamplingContext) {
323
634
  baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
324
635
  if (dscValue) {
@@ -368,6 +679,22 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
368
679
  fields() {
369
680
  return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
370
681
  }
682
+
683
+ /** If we want to inject trace data for a given URL. */
684
+ _shouldInjectTraceData(tracePropagationTargets, url) {
685
+ if (tracePropagationTargets === undefined) {
686
+ return true;
687
+ }
688
+
689
+ const cachedDecision = this._urlMatchesTargetsMap.get(url);
690
+ if (cachedDecision !== undefined) {
691
+ return cachedDecision;
692
+ }
693
+
694
+ const decision = utils.stringMatchesSomePattern(url, tracePropagationTargets);
695
+ this._urlMatchesTargetsMap.set(url, decision);
696
+ return decision;
697
+ }
371
698
  }
372
699
 
373
700
  /** Exported for tests. */
@@ -400,12 +727,13 @@ function getInjectionData(context)
400
727
 
401
728
  {
402
729
  const span = api.trace.getSpan(context);
403
- const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2(), 'access', _3 => _3.isRemote]);
730
+ const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _8 => _8.spanContext, 'call', _9 => _9(), 'access', _10 => _10.isRemote]);
404
731
 
405
732
  // If we have a local span, we can just pick everything from it
406
733
  if (span && !spanIsRemote) {
407
734
  const spanContext = span.spanContext();
408
- const propagationContext = getPropagationContextFromSpanContext(spanContext);
735
+
736
+ const propagationContext = getPropagationContextFromSpan(span);
409
737
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
410
738
  return {
411
739
  dynamicSamplingContext,
@@ -416,7 +744,7 @@ function getInjectionData(context)
416
744
  }
417
745
 
418
746
  // Else we try to use the propagation context from the scope
419
- const scope = _optionalChain$7([getScopesFromContext, 'call', _4 => _4(context), 'optionalAccess', _5 => _5.scope]);
747
+ const scope = _optionalChain$6([getScopesFromContext, 'call', _11 => _11(context), 'optionalAccess', _12 => _12.scope]);
420
748
  if (scope) {
421
749
  const propagationContext = scope.getPropagationContext();
422
750
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
@@ -429,9 +757,9 @@ function getInjectionData(context)
429
757
  }
430
758
 
431
759
  // Else, we look at the remote span context
432
- const spanContext = api.trace.getSpanContext(context);
433
- if (spanContext) {
434
- const propagationContext = getPropagationContextFromSpanContext(spanContext);
760
+ if (span) {
761
+ const spanContext = span.spanContext();
762
+ const propagationContext = getPropagationContextFromSpan(span);
435
763
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
436
764
 
437
765
  return {
@@ -458,7 +786,7 @@ function getDynamicSamplingContext(
458
786
  traceId,
459
787
  ) {
460
788
  // If we have a DSC on the propagation context, we just use it
461
- if (_optionalChain$7([propagationContext, 'optionalAccess', _6 => _6.dsc])) {
789
+ if (_optionalChain$6([propagationContext, 'optionalAccess', _13 => _13.dsc])) {
462
790
  return propagationContext.dsc;
463
791
  }
464
792
 
@@ -510,121 +838,14 @@ function continueTraceAsRemoteSpan(
510
838
  return api.context.with(ctxWithSpanContext, callback);
511
839
  }
512
840
 
513
- /**
514
- * OpenTelemetry only knows about SAMPLED or NONE decision,
515
- * but for us it is important to differentiate between unset and unsampled.
516
- *
517
- * Both of these are identified as `traceFlags === TracegFlags.NONE`,
518
- * but we additionally look at a special trace state to differentiate between them.
519
- */
520
- function getSamplingDecision(spanContext) {
521
- const { traceFlags, traceState } = spanContext;
522
-
523
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
524
-
525
- // If trace flag is `SAMPLED`, we interpret this as sampled
526
- // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
527
- // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
528
- // to identify which it is
529
- if (traceFlags === api.TraceFlags.SAMPLED) {
530
- return true;
531
- }
532
-
533
- if (sampledNotRecording) {
534
- return false;
535
- }
536
-
537
- // Fall back to DSC as a last resort, that may also contain `sampled`...
538
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
539
- const dsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
540
-
541
- if (_optionalChain$7([dsc, 'optionalAccess', _7 => _7.sampled]) === 'true') {
542
- return true;
543
- }
544
- if (_optionalChain$7([dsc, 'optionalAccess', _8 => _8.sampled]) === 'false') {
545
- return false;
546
- }
547
-
548
- return undefined;
549
- }
550
-
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; }
552
- /**
553
- * Creates a dynamic sampling context from a span (and client and scope)
554
- *
555
- * @param span the span from which a few values like the root span name and sample rate are extracted.
556
- *
557
- * @returns a dynamic sampling context
558
- */
559
- function getDynamicSamplingContextFromSpan(span) {
560
- const client = core.getClient();
561
- if (!client) {
562
- return {};
563
- }
564
-
565
- const traceState = span.spanContext().traceState;
566
- const traceStateDsc = _optionalChain$6([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
567
-
568
- // If the span has a DSC, we want it to take precedence
569
- const dscOnSpan = traceStateDsc ? utils.baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
570
-
571
- if (dscOnSpan) {
572
- return dscOnSpan;
573
- }
574
-
575
- const dsc = core.getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
576
-
577
- const attributes = spanHasAttributes(span) ? span.attributes : {};
578
-
579
- const sampleRate = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
580
- if (sampleRate != null) {
581
- dsc.sample_rate = `${sampleRate}`;
582
- }
583
-
584
- // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
585
- const source = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
586
- const name = spanHasName(span) ? span.name : '';
587
-
588
- if (source !== 'url' && name) {
589
- dsc.transaction = name;
590
- }
591
-
592
- const sampled = getSamplingDecision(span.spanContext());
593
- if (sampled != null) {
594
- dsc.sampled = String(sampled);
595
- }
596
-
597
- client.emit('createDsc', dsc);
598
-
599
- return dsc;
600
- }
601
-
602
- /**
603
- *
604
- * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
605
- * @returns boolean
606
- */
607
- function isSentryRequestSpan(span) {
608
- if (!spanHasAttributes(span)) {
609
- return false;
610
- }
611
-
612
- const { attributes } = span;
613
-
614
- const httpUrl = attributes[semanticConventions.SemanticAttributes.HTTP_URL];
615
-
616
- if (!httpUrl) {
617
- return false;
841
+ /** Try to get the existing baggage header so we can merge this in. */
842
+ function getExistingBaggage(carrier) {
843
+ try {
844
+ const baggage = (carrier )[SENTRY_BAGGAGE_HEADER];
845
+ return Array.isArray(baggage) ? baggage.join(',') : baggage;
846
+ } catch (e) {
847
+ return undefined;
618
848
  }
619
-
620
- return core.isSentryRequestUrl(httpUrl.toString(), core.getClient());
621
- }
622
-
623
- /**
624
- * Returns the currently active span.
625
- */
626
- function getActiveSpan() {
627
- return api.trace.getActiveSpan();
628
849
  }
629
850
 
630
851
  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; }
@@ -632,11 +853,12 @@ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[
632
853
  /**
633
854
  * Wraps a function with a transaction/span and finishes the span after the function is done.
634
855
  * The created span is the active span and will be used as parent by other spans created inside the function
635
- * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
856
+ * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
636
857
  *
637
858
  * If you want to create a span that is not set as active, use {@link startInactiveSpan}.
638
859
  *
639
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
860
+ * You'll always get a span passed to the callback,
861
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
640
862
  */
641
863
  function startSpan(options, callback) {
642
864
  const tracer = getTracer();
@@ -655,7 +877,10 @@ function startSpan(options, callback) {
655
877
  return core.handleCallbackErrors(
656
878
  () => callback(span),
657
879
  () => {
658
- span.setStatus({ code: api.SpanStatusCode.ERROR });
880
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
881
+ if (core.spanToJSON(span).status === undefined) {
882
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
883
+ }
659
884
  },
660
885
  () => span.end(),
661
886
  );
@@ -669,7 +894,8 @@ function startSpan(options, callback) {
669
894
  * The created span is the active span and will be used as parent by other spans created inside the function
670
895
  * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
671
896
  *
672
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
897
+ * You'll always get a span passed to the callback,
898
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
673
899
  */
674
900
  function startSpanManual(
675
901
  options,
@@ -691,7 +917,10 @@ function startSpanManual(
691
917
  return core.handleCallbackErrors(
692
918
  () => callback(span, () => span.end()),
693
919
  () => {
694
- span.setStatus({ code: api.SpanStatusCode.ERROR });
920
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
921
+ if (core.spanToJSON(span).status === undefined) {
922
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
923
+ }
695
924
  },
696
925
  );
697
926
  });
@@ -699,13 +928,12 @@ function startSpanManual(
699
928
 
700
929
  /**
701
930
  * Creates a span. This span is not set as active, so will not get automatic instrumentation spans
702
- * as children or be able to be accessed via `Sentry.getSpan()`.
931
+ * as children or be able to be accessed via `Sentry.getActiveSpan()`.
703
932
  *
704
933
  * If you want to create a span that is set as active, use {@link startSpan}.
705
934
  *
706
- * Note that if you have not enabled tracing extensions via `addTracingExtensions`
707
- * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
708
- * and the `span` returned from the callback will be undefined.
935
+ * This function will always return a span,
936
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
709
937
  */
710
938
  function startInactiveSpan(options) {
711
939
  const tracer = getTracer();
@@ -730,7 +958,7 @@ function startInactiveSpan(options) {
730
958
  * passed `null` to start an entirely new span tree.
731
959
  *
732
960
  * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
733
- * spans started within the callback will not be attached to a parent span.
961
+ * spans started within the callback will be root spans.
734
962
  * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
735
963
  * @returns the value returned from the provided callback function.
736
964
  */
@@ -782,13 +1010,12 @@ function getContext(scope, forceTransaction) {
782
1010
 
783
1011
  if (actualScope && client) {
784
1012
  const propagationContext = actualScope.getPropagationContext();
785
- const dynamicSamplingContext =
786
- propagationContext.dsc || core.getDynamicSamplingContextFromClient(propagationContext.traceId, client);
787
1013
 
788
1014
  // We store the DSC as OTEL trace state on the span context
789
1015
  const traceState = makeTraceState({
790
1016
  parentSpanId: propagationContext.parentSpanId,
791
- dsc: dynamicSamplingContext,
1017
+ // Not defined yet, we want to pick this up on-demand only
1018
+ dsc: undefined,
792
1019
  sampled: propagationContext.sampled,
793
1020
  });
794
1021
 
@@ -823,6 +1050,8 @@ function getContext(scope, forceTransaction) {
823
1050
  const { spanId, traceId } = parentSpan.spanContext();
824
1051
  const sampled = getSamplingDecision(parentSpan.spanContext());
825
1052
 
1053
+ // In this case, when we are forcing a transaction, we want to treat this like continuing an incoming trace
1054
+ // so we set the traceState according to the root span
826
1055
  const rootSpan = core.getRootSpan(parentSpan);
827
1056
  const dsc = getDynamicSamplingContextFromSpan(rootSpan);
828
1057
 
@@ -890,25 +1119,11 @@ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[
890
1119
  */
891
1120
  function getCurrentHub() {
892
1121
  return {
893
- isOlderThan(_version) {
894
- return false;
895
- },
896
-
897
1122
  bindClient(client) {
898
1123
  const scope = core.getCurrentScope();
899
1124
  scope.setClient(client);
900
1125
  },
901
1126
 
902
- pushScope() {
903
- // TODO: This does not work and is actually deprecated
904
- return core.getCurrentScope();
905
- },
906
-
907
- popScope() {
908
- // TODO: This does not work and is actually deprecated
909
- return false;
910
- },
911
-
912
1127
  withScope: core.withScope,
913
1128
  getClient: () => core.getClient() ,
914
1129
  getScope: core.getCurrentScope,
@@ -946,11 +1161,6 @@ function getCurrentHub() {
946
1161
  // only send the update
947
1162
  _sendSessionUpdate();
948
1163
  },
949
-
950
- shouldSendDefaultPii() {
951
- const client = core.getClient();
952
- return Boolean(client ? client.getOptions().sendDefaultPii : false);
953
- },
954
1164
  };
955
1165
  }
956
1166
 
@@ -1171,18 +1381,11 @@ function wrapContextManagerClass(
1171
1381
  setContextOnScope(newCurrentScope, ctx2);
1172
1382
 
1173
1383
  return super.with(ctx2, fn, thisArg, ...args);
1174
- }
1175
- }
1176
-
1177
- return SentryContextManager ;
1178
- }
1179
-
1180
- /**
1181
- * 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.
1182
- *
1183
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
1184
- */
1185
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
1384
+ }
1385
+ }
1386
+
1387
+ return SentryContextManager ;
1388
+ }
1186
1389
 
1187
1390
  /** If this attribute is true, it means that the parent is a remote span. */
1188
1391
  const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
@@ -1208,14 +1411,19 @@ function groupSpansWithParents(spans) {
1208
1411
  });
1209
1412
  }
1210
1413
 
1211
- function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1414
+ /**
1415
+ * This returns the _local_ parent ID - `parentId` on the span may point to a remote span.
1416
+ */
1417
+ function getLocalParentId(span) {
1212
1418
  const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
1213
-
1214
- const id = span.spanContext().spanId;
1215
-
1216
1419
  // If the parentId is the trace parent ID, we pretend it's undefined
1217
1420
  // As this means the parent exists somewhere else
1218
- const parentId = !parentIsRemote ? span.parentSpanId : undefined;
1421
+ return !parentIsRemote ? span.parentSpanId : undefined;
1422
+ }
1423
+
1424
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1425
+ const id = span.spanContext().spanId;
1426
+ const parentId = getLocalParentId(span);
1219
1427
 
1220
1428
  if (!parentId) {
1221
1429
  createOrUpdateNode(nodeMap, { id, span, children: [] });
@@ -1324,187 +1532,75 @@ function mapStatus(span) {
1324
1532
  }
1325
1533
  }
1326
1534
 
1535
+ 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; }
1536
+
1327
1537
  /**
1328
- * Extract better op/description from an otel span.
1329
- *
1330
- * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
1538
+ * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1331
1539
  */
1332
- function parseSpanDescription(span) {
1333
- const attributes = spanHasAttributes(span) ? span.attributes : {};
1334
- const name = spanHasName(span) ? span.name : '<unknown>';
1335
-
1336
- // if http.method exists, this is an http request span
1337
- const httpMethod = attributes[semanticConventions.SemanticAttributes.HTTP_METHOD];
1338
- if (httpMethod) {
1339
- return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
1340
- }
1341
-
1342
- // If db.type exists then this is a database call span.
1343
- const dbSystem = attributes[semanticConventions.SemanticAttributes.DB_SYSTEM];
1344
- if (dbSystem) {
1345
- return descriptionForDbSystem({ attributes, name });
1346
- }
1347
-
1348
- // If rpc.service exists then this is a rpc call span.
1349
- const rpcService = attributes[semanticConventions.SemanticAttributes.RPC_SERVICE];
1350
- if (rpcService) {
1351
- return {
1352
- op: 'rpc',
1353
- description: name,
1354
- source: 'route',
1355
- };
1356
- }
1357
-
1358
- // If messaging.system exists then this is a messaging system span.
1359
- const messagingSystem = attributes[semanticConventions.SemanticAttributes.MESSAGING_SYSTEM];
1360
- if (messagingSystem) {
1361
- return {
1362
- op: 'message',
1363
- description: name,
1364
- source: 'route',
1365
- };
1366
- }
1367
-
1368
- // If faas.trigger exists then this is a function as a service span.
1369
- const faasTrigger = attributes[semanticConventions.SemanticAttributes.FAAS_TRIGGER];
1370
- if (faasTrigger) {
1371
- return { op: faasTrigger.toString(), description: name, source: 'route' };
1372
- }
1373
-
1374
- return { op: undefined, description: name, source: 'custom' };
1375
- }
1376
-
1377
- function descriptionForDbSystem({ attributes, name }) {
1378
- // Use DB statement (Ex "SELECT * FROM table") if possible as description.
1379
- const statement = attributes[semanticConventions.SemanticAttributes.DB_STATEMENT];
1380
-
1381
- const description = statement ? statement.toString() : name;
1382
-
1383
- return { op: 'db', description, source: 'task' };
1384
- }
1385
-
1386
- /** Only exported for tests. */
1387
- function descriptionForHttpMethod(
1388
- { name, kind, attributes },
1389
- httpMethod,
1390
- ) {
1391
- const opParts = ['http'];
1392
-
1393
- switch (kind) {
1394
- case api.SpanKind.CLIENT:
1395
- opParts.push('client');
1396
- break;
1397
- case api.SpanKind.SERVER:
1398
- opParts.push('server');
1399
- break;
1400
- }
1401
-
1402
- const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
1540
+ class SentrySpanExporter {
1403
1541
 
1404
- if (!urlPath) {
1405
- return { op: opParts.join('.'), description: name, source: 'custom' };
1542
+ constructor() {
1543
+ this._finishedSpans = [];
1406
1544
  }
1407
1545
 
1408
- // Ex. description="GET /api/users".
1409
- const description = `${httpMethod} ${urlPath}`;
1546
+ /** Export a single span. */
1547
+ export(span) {
1548
+ this._finishedSpans.push(span);
1410
1549
 
1411
- // If `httpPath` is a root path, then we can categorize the transaction source as route.
1412
- const source = hasRoute || urlPath === '/' ? 'route' : 'url';
1550
+ // If the span has a local parent ID, we don't need to export anything just yet
1551
+ if (getLocalParentId(span)) {
1552
+ const openSpanCount = this._finishedSpans.length;
1553
+ DEBUG_BUILD && utils.logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1554
+ this._cleanupOldSpans();
1555
+ return;
1556
+ }
1413
1557
 
1414
- const data = {};
1558
+ this._clearTimeout();
1415
1559
 
1416
- if (url) {
1417
- data.url = url;
1418
- }
1419
- if (query) {
1420
- data['http.query'] = query;
1560
+ // If we got a parent span, we try to send the span tree
1561
+ // Wait a tick for this, to ensure we avoid race conditions
1562
+ this._flushTimeout = setTimeout(() => {
1563
+ this.flush();
1564
+ }, 1);
1421
1565
  }
1422
- if (fragment) {
1423
- data['http.fragment'] = fragment;
1424
- }
1425
-
1426
- return {
1427
- op: opParts.join('.'),
1428
- description,
1429
- source,
1430
- data,
1431
- };
1432
- }
1433
-
1434
- /** Exported for tests only */
1435
- function getSanitizedUrl(
1436
- attributes,
1437
- kind,
1438
- )
1439
1566
 
1440
- {
1441
- // This is the relative path of the URL, e.g. /sub
1442
- const httpTarget = attributes[semanticConventions.SemanticAttributes.HTTP_TARGET];
1443
- // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
1444
- const httpUrl = attributes[semanticConventions.SemanticAttributes.HTTP_URL];
1445
- // This is the normalized route name - may not always be available!
1446
- const httpRoute = attributes[semanticConventions.SemanticAttributes.HTTP_ROUTE];
1567
+ /** Try to flush any pending spans immediately. */
1568
+ flush() {
1569
+ this._clearTimeout();
1447
1570
 
1448
- const parsedUrl = typeof httpUrl === 'string' ? utils.parseUrl(httpUrl) : undefined;
1449
- const url = parsedUrl ? utils.getSanitizedUrlString(parsedUrl) : undefined;
1450
- const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
1451
- const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
1571
+ const openSpanCount = this._finishedSpans.length;
1452
1572
 
1453
- if (typeof httpRoute === 'string') {
1454
- return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
1455
- }
1573
+ const remainingSpans = maybeSend(this._finishedSpans);
1456
1574
 
1457
- if (kind === api.SpanKind.SERVER && typeof httpTarget === 'string') {
1458
- return { urlPath: utils.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1459
- }
1575
+ const remainingOpenSpanCount = remainingSpans.length;
1576
+ const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1460
1577
 
1461
- if (parsedUrl) {
1462
- return { urlPath: url, url, query, fragment, hasRoute: false };
1463
- }
1578
+ DEBUG_BUILD &&
1579
+ utils.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1464
1580
 
1465
- // fall back to target even for client spans, if no URL is present
1466
- if (typeof httpTarget === 'string') {
1467
- return { urlPath: utils.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1581
+ this._cleanupOldSpans(remainingSpans);
1468
1582
  }
1469
1583
 
1470
- return { urlPath: undefined, url, query, fragment, hasRoute: false };
1471
- }
1472
-
1473
- 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; }
1474
-
1475
- /**
1476
- * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1477
- */
1478
- class SentrySpanExporter {
1479
-
1480
- constructor() {
1481
- this._stopped = false;
1584
+ /** Clear the exporter. */
1585
+ clear() {
1482
1586
  this._finishedSpans = [];
1587
+ this._clearTimeout();
1483
1588
  }
1484
1589
 
1485
- /** @inheritDoc */
1486
- export(spans, resultCallback) {
1487
- if (this._stopped) {
1488
- return resultCallback({
1489
- code: core$1.ExportResultCode.FAILED,
1490
- error: new Error('Exporter has been stopped'),
1491
- });
1590
+ /** Clear the flush timeout. */
1591
+ _clearTimeout() {
1592
+ if (this._flushTimeout) {
1593
+ clearTimeout(this._flushTimeout);
1594
+ this._flushTimeout = undefined;
1492
1595
  }
1596
+ }
1493
1597
 
1494
- const openSpanCount = this._finishedSpans.length;
1495
- const newSpanCount = spans.length;
1496
-
1497
- this._finishedSpans.push(...spans);
1498
-
1499
- const remainingSpans = maybeSend(this._finishedSpans);
1500
-
1501
- const remainingOpenSpanCount = remainingSpans.length;
1502
- const sentSpanCount = openSpanCount + newSpanCount - remainingOpenSpanCount;
1503
-
1504
- DEBUG_BUILD &&
1505
- utils.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1506
-
1507
- this._finishedSpans = remainingSpans.filter(span => {
1598
+ /**
1599
+ * Remove any span that is older than 5min.
1600
+ * We do this to avoid leaking memory.
1601
+ */
1602
+ _cleanupOldSpans(spans = this._finishedSpans) {
1603
+ this._finishedSpans = spans.filter(span => {
1508
1604
  const shouldDrop = shouldCleanupSpan(span, 5 * 60);
1509
1605
  DEBUG_BUILD &&
1510
1606
  shouldDrop &&
@@ -1515,23 +1611,6 @@ class SentrySpanExporter {
1515
1611
  );
1516
1612
  return !shouldDrop;
1517
1613
  });
1518
-
1519
- resultCallback({ code: core$1.ExportResultCode.SUCCESS });
1520
- }
1521
-
1522
- /** @inheritDoc */
1523
- shutdown() {
1524
- const forceFlush = this.forceFlush();
1525
- this._stopped = true;
1526
- this._finishedSpans = [];
1527
- return forceFlush;
1528
- }
1529
-
1530
- /** @inheritDoc */
1531
- forceFlush() {
1532
- return new Promise(resolve => {
1533
- this.export(this._finishedSpans, () => resolve());
1534
- });
1535
1614
  }
1536
1615
  }
1537
1616
 
@@ -1564,7 +1643,10 @@ function maybeSend(spans) {
1564
1643
 
1565
1644
  transactionEvent.spans = spans;
1566
1645
 
1567
- // TODO Measurements are not yet implemented in OTEL
1646
+ const measurements = core.timedEventsToMeasurements(span.events);
1647
+ if (Object.keys(measurements).length) {
1648
+ transactionEvent.measurements = measurements;
1649
+ }
1568
1650
 
1569
1651
  core.captureEvent(transactionEvent);
1570
1652
  });
@@ -1574,8 +1656,12 @@ function maybeSend(spans) {
1574
1656
  .filter((span) => !!span);
1575
1657
  }
1576
1658
 
1659
+ function nodeIsCompletedRootNode(node) {
1660
+ return !!node.span && !node.parentNode;
1661
+ }
1662
+
1577
1663
  function getCompletedRootNodes(nodes) {
1578
- return nodes.filter((node) => !!node.span && !node.parentNode);
1664
+ return nodes.filter(nodeIsCompletedRootNode);
1579
1665
  }
1580
1666
 
1581
1667
  function shouldCleanupSpan(span, maxStartTimeOffsetSeconds) {
@@ -1620,7 +1706,7 @@ function createTransactionForOtelSpan(span) {
1620
1706
  data: attributes,
1621
1707
  origin,
1622
1708
  op,
1623
- status: core.getStatusMessage(status),
1709
+ status: core.getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1624
1710
  });
1625
1711
 
1626
1712
  const transactionEvent = {
@@ -1694,7 +1780,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1694
1780
  start_timestamp: convertOtelTimeToSeconds(startTime),
1695
1781
  // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1696
1782
  timestamp: convertOtelTimeToSeconds(endTime) || undefined,
1697
- status: core.getStatusMessage(status),
1783
+ status: core.getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1698
1784
  op,
1699
1785
  origin,
1700
1786
  _metrics_summary: core.getMetricSummaryJsonForSpan(span ),
@@ -1801,11 +1887,15 @@ function onSpanStart(span, parentContext) {
1801
1887
  setSpanScopes(span, scopes);
1802
1888
  }
1803
1889
 
1890
+ core.logSpanStart(span);
1891
+
1804
1892
  const client = core.getClient();
1805
1893
  _optionalChain$1([client, 'optionalAccess', _ => _.emit, 'call', _2 => _2('spanStart', span)]);
1806
1894
  }
1807
1895
 
1808
1896
  function onSpanEnd(span) {
1897
+ core.logSpanEnd(span);
1898
+
1809
1899
  const client = core.getClient();
1810
1900
  _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1811
1901
  }
@@ -1814,52 +1904,44 @@ function onSpanEnd(span) {
1814
1904
  * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
1815
1905
  * the Sentry SDK.
1816
1906
  */
1817
- class SentrySpanProcessor extends sdkTraceBase.BatchSpanProcessor {
1818
- constructor() {
1819
- super(new SentrySpanExporter());
1907
+ class SentrySpanProcessor {
1820
1908
 
1909
+ constructor() {
1821
1910
  setIsSetup('SentrySpanProcessor');
1911
+ this._exporter = new SentrySpanExporter();
1822
1912
  }
1823
1913
 
1824
1914
  /**
1825
1915
  * @inheritDoc
1826
1916
  */
1827
- onStart(span, parentContext) {
1828
- onSpanStart(span, parentContext);
1829
-
1830
- // TODO (v8): Trigger client `spanStart` & `spanEnd` in here,
1831
- // once we decoupled opentelemetry from SentrySpan
1917
+ async forceFlush() {
1918
+ this._exporter.flush();
1919
+ }
1832
1920
 
1833
- DEBUG_BUILD && utils.logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1921
+ /**
1922
+ * @inheritDoc
1923
+ */
1924
+ async shutdown() {
1925
+ this._exporter.clear();
1926
+ }
1834
1927
 
1835
- return super.onStart(span, parentContext);
1928
+ /**
1929
+ * @inheritDoc
1930
+ */
1931
+ onStart(span, parentContext) {
1932
+ onSpanStart(span, parentContext);
1836
1933
  }
1837
1934
 
1838
1935
  /** @inheritDoc */
1839
1936
  onEnd(span) {
1840
- DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1841
-
1842
- if (!this._shouldSendSpanToSentry(span)) {
1843
- // Prevent this being called to super.onEnd(), which would pass this to the span exporter
1844
- return;
1845
- }
1846
-
1847
1937
  onSpanEnd(span);
1848
1938
 
1849
- return super.onEnd(span);
1850
- }
1851
-
1852
- /**
1853
- * You can overwrite this in a sub class to implement custom behavior for dropping spans.
1854
- * If you return `false` here, the span will not be passed to the exporter and thus not be sent.
1855
- */
1856
- _shouldSendSpanToSentry(_span) {
1857
- return true;
1939
+ this._exporter.export(span);
1858
1940
  }
1859
1941
  }
1860
1942
 
1861
1943
  /**
1862
- * A custom OTEL sampler that uses Sentry sampling rates to make it's decision
1944
+ * A custom OTEL sampler that uses Sentry sampling rates to make its decision
1863
1945
  */
1864
1946
  class SentrySampler {
1865
1947
 
@@ -1883,16 +1965,17 @@ class SentrySampler {
1883
1965
  return { decision: sdkTraceBase.SamplingDecision.NOT_RECORD };
1884
1966
  }
1885
1967
 
1886
- const parentContext = api.trace.getSpanContext(context);
1887
- const traceState = _optionalChain([parentContext, 'optionalAccess', _ => _.traceState]) || new core$1.TraceState();
1968
+ const parentSpan = api.trace.getSpan(context);
1969
+ const parentContext = _optionalChain([parentSpan, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2()]);
1970
+ const traceState = _optionalChain([parentContext, 'optionalAccess', _3 => _3.traceState]) || new core$1.TraceState();
1888
1971
 
1889
1972
  let parentSampled = undefined;
1890
1973
 
1891
1974
  // Only inherit sample rate if `traceId` is the same
1892
1975
  // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones
1893
- if (parentContext && api.isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1976
+ if (parentSpan && parentContext && api.isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1894
1977
  if (parentContext.isRemote) {
1895
- parentSampled = getParentRemoteSampled(parentContext);
1978
+ parentSampled = getParentRemoteSampled(parentSpan);
1896
1979
  DEBUG_BUILD &&
1897
1980
  utils.logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
1898
1981
  } else {
@@ -1901,7 +1984,7 @@ class SentrySampler {
1901
1984
  }
1902
1985
  }
1903
1986
 
1904
- const sampleRate = getSampleRate(options, {
1987
+ const [sampled, sampleRate] = core.sampleSpan(options, {
1905
1988
  name: spanName,
1906
1989
  attributes: spanAttributes,
1907
1990
  transactionContext: {
@@ -1912,32 +1995,12 @@ class SentrySampler {
1912
1995
  });
1913
1996
 
1914
1997
  const attributes = {
1915
- [core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: Number(sampleRate),
1998
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
1916
1999
  };
1917
2000
 
1918
- // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
1919
- // only valid values are booleans or numbers between 0 and 1.)
1920
- if (!isValidSampleRate(sampleRate)) {
1921
- DEBUG_BUILD && utils.logger.warn('[Tracing] Discarding span because of invalid sample rate.');
1922
-
1923
- return {
1924
- decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
1925
- attributes,
1926
- traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
1927
- };
1928
- }
1929
-
1930
- // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped
1931
- if (!sampleRate) {
1932
- DEBUG_BUILD &&
1933
- utils.logger.log(
1934
- `[Tracing] Discarding span because ${
1935
- typeof options.tracesSampler === 'function'
1936
- ? 'tracesSampler returned 0 or false'
1937
- : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'
1938
- }`,
1939
- );
1940
-
2001
+ const method = `${spanAttributes[semanticConventions.SemanticAttributes.HTTP_METHOD]}`.toUpperCase();
2002
+ if (method === 'OPTIONS' || method === 'HEAD') {
2003
+ DEBUG_BUILD && utils.logger.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
1941
2004
  return {
1942
2005
  decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
1943
2006
  attributes,
@@ -1945,19 +2008,7 @@ class SentrySampler {
1945
2008
  };
1946
2009
  }
1947
2010
 
1948
- // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
1949
- // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
1950
- const isSampled = Math.random() < (sampleRate );
1951
-
1952
- // if we're not going to keep it, we're done
1953
- if (!isSampled) {
1954
- DEBUG_BUILD &&
1955
- utils.logger.log(
1956
- `[Tracing] Discarding span because it's not included in the random sample (sampling rate = ${Number(
1957
- sampleRate,
1958
- )})`,
1959
- );
1960
-
2011
+ if (!sampled) {
1961
2012
  return {
1962
2013
  decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
1963
2014
  attributes,
@@ -1977,57 +2028,9 @@ class SentrySampler {
1977
2028
  }
1978
2029
  }
1979
2030
 
1980
- function getSampleRate(
1981
- options,
1982
- samplingContext,
1983
- ) {
1984
- if (typeof options.tracesSampler === 'function') {
1985
- return options.tracesSampler(samplingContext);
1986
- }
1987
-
1988
- if (samplingContext.parentSampled !== undefined) {
1989
- return samplingContext.parentSampled;
1990
- }
1991
-
1992
- if (typeof options.tracesSampleRate !== 'undefined') {
1993
- return options.tracesSampleRate;
1994
- }
1995
-
1996
- // When `enableTracing === true`, we use a sample rate of 100%
1997
- if (options.enableTracing) {
1998
- return 1;
1999
- }
2000
-
2001
- return 0;
2002
- }
2003
-
2004
- /**
2005
- * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).
2006
- */
2007
- function isValidSampleRate(rate) {
2008
- // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
2009
- if (utils.isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
2010
- DEBUG_BUILD &&
2011
- utils.logger.warn(
2012
- `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
2013
- rate,
2014
- )} of type ${JSON.stringify(typeof rate)}.`,
2015
- );
2016
- return false;
2017
- }
2018
-
2019
- // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
2020
- if (rate < 0 || rate > 1) {
2021
- DEBUG_BUILD &&
2022
- utils.logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
2023
- return false;
2024
- }
2025
- return true;
2026
- }
2027
-
2028
- function getParentRemoteSampled(spanContext) {
2029
- const traceId = spanContext.traceId;
2030
- const traceparentData = getPropagationContextFromSpanContext(spanContext);
2031
+ function getParentRemoteSampled(parentSpan) {
2032
+ const traceId = parentSpan.spanContext().traceId;
2033
+ const traceparentData = getPropagationContextFromSpan(parentSpan);
2031
2034
 
2032
2035
  // Only inherit sampled if `traceId` is the same
2033
2036
  return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;