@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/esm/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { _optionalChain } from '@sentry/utils';
2
2
  import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
3
- import { parseUrl, getSanitizedUrlString, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, dropUndefinedKeys, stripUrlQueryAndFragment, logger, 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, 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
- import { W3CBaggagePropagator, isTracingSuppressed, TraceState, suppressTracing, ExportResultCode } from '@opentelemetry/core';
9
- import { BatchSpanProcessor, SamplingDecision } from '@opentelemetry/sdk-trace-base';
8
+ import { W3CBaggagePropagator, isTracingSuppressed, TraceState, suppressTracing } from '@opentelemetry/core';
9
+ import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
10
10
 
11
11
  /**
12
12
  * Check if a given span has attributes.
@@ -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,280 @@ 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
+
532
+ /**
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.
534
+ *
535
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
536
+ */
537
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
538
+
265
539
  const setupElements = new Set();
266
540
 
267
541
  /** Get all the OpenTelemetry elements that have been set up. */
@@ -274,18 +548,25 @@ function setIsSetup(element) {
274
548
  setupElements.add(element);
275
549
  }
276
550
 
277
- 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; }
278
552
 
279
553
  /** Get the Sentry propagation context from a span context. */
280
- function getPropagationContextFromSpanContext(spanContext) {
554
+ function getPropagationContextFromSpan(span) {
555
+ const spanContext = span.spanContext();
281
556
  const { traceId, spanId, traceState } = spanContext;
282
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
283
560
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
284
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
561
+ const traceStateDsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
562
+
285
563
  const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) : undefined;
286
564
 
287
565
  const sampled = getSamplingDecision(spanContext);
288
566
 
567
+ // No trace state? --> Take DSC from root span
568
+ const dsc = traceStateDsc || getDynamicSamplingContextFromSpan(getRootSpan(span));
569
+
289
570
  return {
290
571
  traceId,
291
572
  spanId,
@@ -299,9 +580,14 @@ function getPropagationContextFromSpanContext(spanContext) {
299
580
  * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
300
581
  */
301
582
  class SentryPropagator extends W3CBaggagePropagator {
583
+ /** A map of URLs that have already been checked for if they match tracePropagationTargets. */
584
+
302
585
  constructor() {
303
586
  super();
304
587
  setIsSetup('SentryPropagator');
588
+
589
+ // We're caching results so we don't have to recompute regexp every time we create a request.
590
+ this._urlMatchesTargetsMap = new LRUMap(100);
305
591
  }
306
592
 
307
593
  /**
@@ -309,13 +595,38 @@ class SentryPropagator extends W3CBaggagePropagator {
309
595
  */
310
596
  inject(context, carrier, setter) {
311
597
  if (isTracingSuppressed(context)) {
598
+ DEBUG_BUILD && logger.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
312
599
  return;
313
600
  }
314
601
 
602
+ const activeSpan = trace.getSpan(context);
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]);
605
+ if (
606
+ typeof url === 'string' &&
607
+ tracePropagationTargets &&
608
+ !this._shouldInjectTraceData(tracePropagationTargets, url)
609
+ ) {
610
+ DEBUG_BUILD &&
611
+ logger.log('[Tracing] Not injecting trace data for url because it does not matchTracePropagationTargets:', url);
612
+ return;
613
+ }
614
+
615
+ const existingBaggageHeader = getExistingBaggage(carrier);
315
616
  let baggage = propagation.getBaggage(context) || propagation.createBaggage({});
316
617
 
317
618
  const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);
318
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
+
319
630
  if (dynamicSamplingContext) {
320
631
  baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
321
632
  if (dscValue) {
@@ -365,6 +676,22 @@ class SentryPropagator extends W3CBaggagePropagator {
365
676
  fields() {
366
677
  return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
367
678
  }
679
+
680
+ /** If we want to inject trace data for a given URL. */
681
+ _shouldInjectTraceData(tracePropagationTargets, url) {
682
+ if (tracePropagationTargets === undefined) {
683
+ return true;
684
+ }
685
+
686
+ const cachedDecision = this._urlMatchesTargetsMap.get(url);
687
+ if (cachedDecision !== undefined) {
688
+ return cachedDecision;
689
+ }
690
+
691
+ const decision = stringMatchesSomePattern(url, tracePropagationTargets);
692
+ this._urlMatchesTargetsMap.set(url, decision);
693
+ return decision;
694
+ }
368
695
  }
369
696
 
370
697
  /** Exported for tests. */
@@ -397,12 +724,13 @@ function getInjectionData(context)
397
724
 
398
725
  {
399
726
  const span = trace.getSpan(context);
400
- const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2(), 'access', _3 => _3.isRemote]);
727
+ const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _8 => _8.spanContext, 'call', _9 => _9(), 'access', _10 => _10.isRemote]);
401
728
 
402
729
  // If we have a local span, we can just pick everything from it
403
730
  if (span && !spanIsRemote) {
404
731
  const spanContext = span.spanContext();
405
- const propagationContext = getPropagationContextFromSpanContext(spanContext);
732
+
733
+ const propagationContext = getPropagationContextFromSpan(span);
406
734
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
407
735
  return {
408
736
  dynamicSamplingContext,
@@ -413,7 +741,7 @@ function getInjectionData(context)
413
741
  }
414
742
 
415
743
  // Else we try to use the propagation context from the scope
416
- const scope = _optionalChain$7([getScopesFromContext, 'call', _4 => _4(context), 'optionalAccess', _5 => _5.scope]);
744
+ const scope = _optionalChain$6([getScopesFromContext, 'call', _11 => _11(context), 'optionalAccess', _12 => _12.scope]);
417
745
  if (scope) {
418
746
  const propagationContext = scope.getPropagationContext();
419
747
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
@@ -426,9 +754,9 @@ function getInjectionData(context)
426
754
  }
427
755
 
428
756
  // Else, we look at the remote span context
429
- const spanContext = trace.getSpanContext(context);
430
- if (spanContext) {
431
- const propagationContext = getPropagationContextFromSpanContext(spanContext);
757
+ if (span) {
758
+ const spanContext = span.spanContext();
759
+ const propagationContext = getPropagationContextFromSpan(span);
432
760
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
433
761
 
434
762
  return {
@@ -455,7 +783,7 @@ function getDynamicSamplingContext(
455
783
  traceId,
456
784
  ) {
457
785
  // If we have a DSC on the propagation context, we just use it
458
- if (_optionalChain$7([propagationContext, 'optionalAccess', _6 => _6.dsc])) {
786
+ if (_optionalChain$6([propagationContext, 'optionalAccess', _13 => _13.dsc])) {
459
787
  return propagationContext.dsc;
460
788
  }
461
789
 
@@ -507,121 +835,14 @@ function continueTraceAsRemoteSpan(
507
835
  return context.with(ctxWithSpanContext, callback);
508
836
  }
509
837
 
510
- /**
511
- * OpenTelemetry only knows about SAMPLED or NONE decision,
512
- * but for us it is important to differentiate between unset and unsampled.
513
- *
514
- * Both of these are identified as `traceFlags === TracegFlags.NONE`,
515
- * but we additionally look at a special trace state to differentiate between them.
516
- */
517
- function getSamplingDecision(spanContext) {
518
- const { traceFlags, traceState } = spanContext;
519
-
520
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
521
-
522
- // If trace flag is `SAMPLED`, we interpret this as sampled
523
- // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
524
- // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
525
- // to identify which it is
526
- if (traceFlags === TraceFlags.SAMPLED) {
527
- return true;
528
- }
529
-
530
- if (sampledNotRecording) {
531
- return false;
532
- }
533
-
534
- // Fall back to DSC as a last resort, that may also contain `sampled`...
535
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
536
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
537
-
538
- if (_optionalChain$7([dsc, 'optionalAccess', _7 => _7.sampled]) === 'true') {
539
- return true;
540
- }
541
- if (_optionalChain$7([dsc, 'optionalAccess', _8 => _8.sampled]) === 'false') {
542
- return false;
543
- }
544
-
545
- return undefined;
546
- }
547
-
548
- 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; }
549
- /**
550
- * Creates a dynamic sampling context from a span (and client and scope)
551
- *
552
- * @param span the span from which a few values like the root span name and sample rate are extracted.
553
- *
554
- * @returns a dynamic sampling context
555
- */
556
- function getDynamicSamplingContextFromSpan(span) {
557
- const client = getClient();
558
- if (!client) {
559
- return {};
560
- }
561
-
562
- const traceState = span.spanContext().traceState;
563
- const traceStateDsc = _optionalChain$6([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
564
-
565
- // If the span has a DSC, we want it to take precedence
566
- const dscOnSpan = traceStateDsc ? baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
567
-
568
- if (dscOnSpan) {
569
- return dscOnSpan;
570
- }
571
-
572
- const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
573
-
574
- const attributes = spanHasAttributes(span) ? span.attributes : {};
575
-
576
- const sampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
577
- if (sampleRate != null) {
578
- dsc.sample_rate = `${sampleRate}`;
579
- }
580
-
581
- // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
582
- const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
583
- const name = spanHasName(span) ? span.name : '';
584
-
585
- if (source !== 'url' && name) {
586
- dsc.transaction = name;
587
- }
588
-
589
- const sampled = getSamplingDecision(span.spanContext());
590
- if (sampled != null) {
591
- dsc.sampled = String(sampled);
592
- }
593
-
594
- client.emit('createDsc', dsc);
595
-
596
- return dsc;
597
- }
598
-
599
- /**
600
- *
601
- * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
602
- * @returns boolean
603
- */
604
- function isSentryRequestSpan(span) {
605
- if (!spanHasAttributes(span)) {
606
- return false;
607
- }
608
-
609
- const { attributes } = span;
610
-
611
- const httpUrl = attributes[SemanticAttributes.HTTP_URL];
612
-
613
- if (!httpUrl) {
614
- return false;
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;
615
845
  }
616
-
617
- return isSentryRequestUrl(httpUrl.toString(), getClient());
618
- }
619
-
620
- /**
621
- * Returns the currently active span.
622
- */
623
- function getActiveSpan() {
624
- return trace.getActiveSpan();
625
846
  }
626
847
 
627
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; }
@@ -629,11 +850,12 @@ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[
629
850
  /**
630
851
  * Wraps a function with a transaction/span and finishes the span after the function is done.
631
852
  * The created span is the active span and will be used as parent by other spans created inside the function
632
- * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
853
+ * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
633
854
  *
634
855
  * If you want to create a span that is not set as active, use {@link startInactiveSpan}.
635
856
  *
636
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
857
+ * You'll always get a span passed to the callback,
858
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
637
859
  */
638
860
  function startSpan(options, callback) {
639
861
  const tracer = getTracer();
@@ -652,7 +874,10 @@ function startSpan(options, callback) {
652
874
  return handleCallbackErrors(
653
875
  () => callback(span),
654
876
  () => {
655
- span.setStatus({ code: SpanStatusCode.ERROR });
877
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
878
+ if (spanToJSON(span).status === undefined) {
879
+ span.setStatus({ code: SpanStatusCode.ERROR });
880
+ }
656
881
  },
657
882
  () => span.end(),
658
883
  );
@@ -666,7 +891,8 @@ function startSpan(options, callback) {
666
891
  * The created span is the active span and will be used as parent by other spans created inside the function
667
892
  * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
668
893
  *
669
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
894
+ * You'll always get a span passed to the callback,
895
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
670
896
  */
671
897
  function startSpanManual(
672
898
  options,
@@ -688,7 +914,10 @@ function startSpanManual(
688
914
  return handleCallbackErrors(
689
915
  () => callback(span, () => span.end()),
690
916
  () => {
691
- span.setStatus({ code: SpanStatusCode.ERROR });
917
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
918
+ if (spanToJSON(span).status === undefined) {
919
+ span.setStatus({ code: SpanStatusCode.ERROR });
920
+ }
692
921
  },
693
922
  );
694
923
  });
@@ -696,13 +925,12 @@ function startSpanManual(
696
925
 
697
926
  /**
698
927
  * Creates a span. This span is not set as active, so will not get automatic instrumentation spans
699
- * as children or be able to be accessed via `Sentry.getSpan()`.
928
+ * as children or be able to be accessed via `Sentry.getActiveSpan()`.
700
929
  *
701
930
  * If you want to create a span that is set as active, use {@link startSpan}.
702
931
  *
703
- * Note that if you have not enabled tracing extensions via `addTracingExtensions`
704
- * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
705
- * and the `span` returned from the callback will be undefined.
932
+ * This function will always return a span,
933
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
706
934
  */
707
935
  function startInactiveSpan(options) {
708
936
  const tracer = getTracer();
@@ -727,7 +955,7 @@ function startInactiveSpan(options) {
727
955
  * passed `null` to start an entirely new span tree.
728
956
  *
729
957
  * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
730
- * spans started within the callback will not be attached to a parent span.
958
+ * spans started within the callback will be root spans.
731
959
  * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
732
960
  * @returns the value returned from the provided callback function.
733
961
  */
@@ -779,13 +1007,12 @@ function getContext(scope, forceTransaction) {
779
1007
 
780
1008
  if (actualScope && client) {
781
1009
  const propagationContext = actualScope.getPropagationContext();
782
- const dynamicSamplingContext =
783
- propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
784
1010
 
785
1011
  // We store the DSC as OTEL trace state on the span context
786
1012
  const traceState = makeTraceState({
787
1013
  parentSpanId: propagationContext.parentSpanId,
788
- dsc: dynamicSamplingContext,
1014
+ // Not defined yet, we want to pick this up on-demand only
1015
+ dsc: undefined,
789
1016
  sampled: propagationContext.sampled,
790
1017
  });
791
1018
 
@@ -820,6 +1047,8 @@ function getContext(scope, forceTransaction) {
820
1047
  const { spanId, traceId } = parentSpan.spanContext();
821
1048
  const sampled = getSamplingDecision(parentSpan.spanContext());
822
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
823
1052
  const rootSpan = getRootSpan(parentSpan);
824
1053
  const dsc = getDynamicSamplingContextFromSpan(rootSpan);
825
1054
 
@@ -887,25 +1116,11 @@ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[
887
1116
  */
888
1117
  function getCurrentHub() {
889
1118
  return {
890
- isOlderThan(_version) {
891
- return false;
892
- },
893
-
894
1119
  bindClient(client) {
895
1120
  const scope = getCurrentScope();
896
1121
  scope.setClient(client);
897
1122
  },
898
1123
 
899
- pushScope() {
900
- // TODO: This does not work and is actually deprecated
901
- return getCurrentScope();
902
- },
903
-
904
- popScope() {
905
- // TODO: This does not work and is actually deprecated
906
- return false;
907
- },
908
-
909
1124
  withScope,
910
1125
  getClient: () => getClient() ,
911
1126
  getScope: getCurrentScope,
@@ -943,11 +1158,6 @@ function getCurrentHub() {
943
1158
  // only send the update
944
1159
  _sendSessionUpdate();
945
1160
  },
946
-
947
- shouldSendDefaultPii() {
948
- const client = getClient();
949
- return Boolean(client ? client.getOptions().sendDefaultPii : false);
950
- },
951
1161
  };
952
1162
  }
953
1163
 
@@ -1168,18 +1378,11 @@ function wrapContextManagerClass(
1168
1378
  setContextOnScope(newCurrentScope, ctx2);
1169
1379
 
1170
1380
  return super.with(ctx2, fn, thisArg, ...args);
1171
- }
1172
- }
1173
-
1174
- return SentryContextManager ;
1175
- }
1176
-
1177
- /**
1178
- * 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.
1179
- *
1180
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
1181
- */
1182
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
1381
+ }
1382
+ }
1383
+
1384
+ return SentryContextManager ;
1385
+ }
1183
1386
 
1184
1387
  /** If this attribute is true, it means that the parent is a remote span. */
1185
1388
  const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
@@ -1205,14 +1408,19 @@ function groupSpansWithParents(spans) {
1205
1408
  });
1206
1409
  }
1207
1410
 
1208
- function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1411
+ /**
1412
+ * This returns the _local_ parent ID - `parentId` on the span may point to a remote span.
1413
+ */
1414
+ function getLocalParentId(span) {
1209
1415
  const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
1210
-
1211
- const id = span.spanContext().spanId;
1212
-
1213
1416
  // If the parentId is the trace parent ID, we pretend it's undefined
1214
1417
  // As this means the parent exists somewhere else
1215
- const parentId = !parentIsRemote ? span.parentSpanId : undefined;
1418
+ return !parentIsRemote ? span.parentSpanId : undefined;
1419
+ }
1420
+
1421
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1422
+ const id = span.spanContext().spanId;
1423
+ const parentId = getLocalParentId(span);
1216
1424
 
1217
1425
  if (!parentId) {
1218
1426
  createOrUpdateNode(nodeMap, { id, span, children: [] });
@@ -1321,187 +1529,75 @@ function mapStatus(span) {
1321
1529
  }
1322
1530
  }
1323
1531
 
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; }
1533
+
1324
1534
  /**
1325
- * Extract better op/description from an otel span.
1326
- *
1327
- * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
1535
+ * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1328
1536
  */
1329
- function parseSpanDescription(span) {
1330
- const attributes = spanHasAttributes(span) ? span.attributes : {};
1331
- const name = spanHasName(span) ? span.name : '<unknown>';
1332
-
1333
- // if http.method exists, this is an http request span
1334
- const httpMethod = attributes[SemanticAttributes.HTTP_METHOD];
1335
- if (httpMethod) {
1336
- return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
1337
- }
1338
-
1339
- // If db.type exists then this is a database call span.
1340
- const dbSystem = attributes[SemanticAttributes.DB_SYSTEM];
1341
- if (dbSystem) {
1342
- return descriptionForDbSystem({ attributes, name });
1343
- }
1344
-
1345
- // If rpc.service exists then this is a rpc call span.
1346
- const rpcService = attributes[SemanticAttributes.RPC_SERVICE];
1347
- if (rpcService) {
1348
- return {
1349
- op: 'rpc',
1350
- description: name,
1351
- source: 'route',
1352
- };
1353
- }
1354
-
1355
- // If messaging.system exists then this is a messaging system span.
1356
- const messagingSystem = attributes[SemanticAttributes.MESSAGING_SYSTEM];
1357
- if (messagingSystem) {
1358
- return {
1359
- op: 'message',
1360
- description: name,
1361
- source: 'route',
1362
- };
1363
- }
1364
-
1365
- // If faas.trigger exists then this is a function as a service span.
1366
- const faasTrigger = attributes[SemanticAttributes.FAAS_TRIGGER];
1367
- if (faasTrigger) {
1368
- return { op: faasTrigger.toString(), description: name, source: 'route' };
1369
- }
1370
-
1371
- return { op: undefined, description: name, source: 'custom' };
1372
- }
1373
-
1374
- function descriptionForDbSystem({ attributes, name }) {
1375
- // Use DB statement (Ex "SELECT * FROM table") if possible as description.
1376
- const statement = attributes[SemanticAttributes.DB_STATEMENT];
1377
-
1378
- const description = statement ? statement.toString() : name;
1379
-
1380
- return { op: 'db', description, source: 'task' };
1381
- }
1382
-
1383
- /** Only exported for tests. */
1384
- function descriptionForHttpMethod(
1385
- { name, kind, attributes },
1386
- httpMethod,
1387
- ) {
1388
- const opParts = ['http'];
1389
-
1390
- switch (kind) {
1391
- case SpanKind.CLIENT:
1392
- opParts.push('client');
1393
- break;
1394
- case SpanKind.SERVER:
1395
- opParts.push('server');
1396
- break;
1397
- }
1398
-
1399
- const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
1537
+ class SentrySpanExporter {
1400
1538
 
1401
- if (!urlPath) {
1402
- return { op: opParts.join('.'), description: name, source: 'custom' };
1539
+ constructor() {
1540
+ this._finishedSpans = [];
1403
1541
  }
1404
1542
 
1405
- // Ex. description="GET /api/users".
1406
- const description = `${httpMethod} ${urlPath}`;
1543
+ /** Export a single span. */
1544
+ export(span) {
1545
+ this._finishedSpans.push(span);
1407
1546
 
1408
- // If `httpPath` is a root path, then we can categorize the transaction source as route.
1409
- const source = hasRoute || urlPath === '/' ? 'route' : 'url';
1547
+ // If the span has a local parent ID, we don't need to export anything just yet
1548
+ if (getLocalParentId(span)) {
1549
+ const openSpanCount = this._finishedSpans.length;
1550
+ DEBUG_BUILD && logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1551
+ this._cleanupOldSpans();
1552
+ return;
1553
+ }
1410
1554
 
1411
- const data = {};
1555
+ this._clearTimeout();
1412
1556
 
1413
- if (url) {
1414
- data.url = url;
1415
- }
1416
- if (query) {
1417
- data['http.query'] = query;
1557
+ // If we got a parent span, we try to send the span tree
1558
+ // Wait a tick for this, to ensure we avoid race conditions
1559
+ this._flushTimeout = setTimeout(() => {
1560
+ this.flush();
1561
+ }, 1);
1418
1562
  }
1419
- if (fragment) {
1420
- data['http.fragment'] = fragment;
1421
- }
1422
-
1423
- return {
1424
- op: opParts.join('.'),
1425
- description,
1426
- source,
1427
- data,
1428
- };
1429
- }
1430
-
1431
- /** Exported for tests only */
1432
- function getSanitizedUrl(
1433
- attributes,
1434
- kind,
1435
- )
1436
1563
 
1437
- {
1438
- // This is the relative path of the URL, e.g. /sub
1439
- const httpTarget = attributes[SemanticAttributes.HTTP_TARGET];
1440
- // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
1441
- const httpUrl = attributes[SemanticAttributes.HTTP_URL];
1442
- // This is the normalized route name - may not always be available!
1443
- const httpRoute = attributes[SemanticAttributes.HTTP_ROUTE];
1564
+ /** Try to flush any pending spans immediately. */
1565
+ flush() {
1566
+ this._clearTimeout();
1444
1567
 
1445
- const parsedUrl = typeof httpUrl === 'string' ? parseUrl(httpUrl) : undefined;
1446
- const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : undefined;
1447
- const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
1448
- const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
1568
+ const openSpanCount = this._finishedSpans.length;
1449
1569
 
1450
- if (typeof httpRoute === 'string') {
1451
- return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
1452
- }
1570
+ const remainingSpans = maybeSend(this._finishedSpans);
1453
1571
 
1454
- if (kind === SpanKind.SERVER && typeof httpTarget === 'string') {
1455
- return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1456
- }
1572
+ const remainingOpenSpanCount = remainingSpans.length;
1573
+ const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1457
1574
 
1458
- if (parsedUrl) {
1459
- return { urlPath: url, url, query, fragment, hasRoute: false };
1460
- }
1575
+ DEBUG_BUILD &&
1576
+ logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1461
1577
 
1462
- // fall back to target even for client spans, if no URL is present
1463
- if (typeof httpTarget === 'string') {
1464
- return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1578
+ this._cleanupOldSpans(remainingSpans);
1465
1579
  }
1466
1580
 
1467
- return { urlPath: undefined, url, query, fragment, hasRoute: false };
1468
- }
1469
-
1470
- 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; }
1471
-
1472
- /**
1473
- * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1474
- */
1475
- class SentrySpanExporter {
1476
-
1477
- constructor() {
1478
- this._stopped = false;
1581
+ /** Clear the exporter. */
1582
+ clear() {
1479
1583
  this._finishedSpans = [];
1584
+ this._clearTimeout();
1480
1585
  }
1481
1586
 
1482
- /** @inheritDoc */
1483
- export(spans, resultCallback) {
1484
- if (this._stopped) {
1485
- return resultCallback({
1486
- code: ExportResultCode.FAILED,
1487
- error: new Error('Exporter has been stopped'),
1488
- });
1587
+ /** Clear the flush timeout. */
1588
+ _clearTimeout() {
1589
+ if (this._flushTimeout) {
1590
+ clearTimeout(this._flushTimeout);
1591
+ this._flushTimeout = undefined;
1489
1592
  }
1593
+ }
1490
1594
 
1491
- const openSpanCount = this._finishedSpans.length;
1492
- const newSpanCount = spans.length;
1493
-
1494
- this._finishedSpans.push(...spans);
1495
-
1496
- const remainingSpans = maybeSend(this._finishedSpans);
1497
-
1498
- const remainingOpenSpanCount = remainingSpans.length;
1499
- const sentSpanCount = openSpanCount + newSpanCount - remainingOpenSpanCount;
1500
-
1501
- DEBUG_BUILD &&
1502
- logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1503
-
1504
- this._finishedSpans = remainingSpans.filter(span => {
1595
+ /**
1596
+ * Remove any span that is older than 5min.
1597
+ * We do this to avoid leaking memory.
1598
+ */
1599
+ _cleanupOldSpans(spans = this._finishedSpans) {
1600
+ this._finishedSpans = spans.filter(span => {
1505
1601
  const shouldDrop = shouldCleanupSpan(span, 5 * 60);
1506
1602
  DEBUG_BUILD &&
1507
1603
  shouldDrop &&
@@ -1512,23 +1608,6 @@ class SentrySpanExporter {
1512
1608
  );
1513
1609
  return !shouldDrop;
1514
1610
  });
1515
-
1516
- resultCallback({ code: ExportResultCode.SUCCESS });
1517
- }
1518
-
1519
- /** @inheritDoc */
1520
- shutdown() {
1521
- const forceFlush = this.forceFlush();
1522
- this._stopped = true;
1523
- this._finishedSpans = [];
1524
- return forceFlush;
1525
- }
1526
-
1527
- /** @inheritDoc */
1528
- forceFlush() {
1529
- return new Promise(resolve => {
1530
- this.export(this._finishedSpans, () => resolve());
1531
- });
1532
1611
  }
1533
1612
  }
1534
1613
 
@@ -1561,7 +1640,10 @@ function maybeSend(spans) {
1561
1640
 
1562
1641
  transactionEvent.spans = spans;
1563
1642
 
1564
- // 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
+ }
1565
1647
 
1566
1648
  captureEvent(transactionEvent);
1567
1649
  });
@@ -1571,8 +1653,12 @@ function maybeSend(spans) {
1571
1653
  .filter((span) => !!span);
1572
1654
  }
1573
1655
 
1656
+ function nodeIsCompletedRootNode(node) {
1657
+ return !!node.span && !node.parentNode;
1658
+ }
1659
+
1574
1660
  function getCompletedRootNodes(nodes) {
1575
- return nodes.filter((node) => !!node.span && !node.parentNode);
1661
+ return nodes.filter(nodeIsCompletedRootNode);
1576
1662
  }
1577
1663
 
1578
1664
  function shouldCleanupSpan(span, maxStartTimeOffsetSeconds) {
@@ -1617,7 +1703,7 @@ function createTransactionForOtelSpan(span) {
1617
1703
  data: attributes,
1618
1704
  origin,
1619
1705
  op,
1620
- status: getStatusMessage(status),
1706
+ status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1621
1707
  });
1622
1708
 
1623
1709
  const transactionEvent = {
@@ -1691,7 +1777,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1691
1777
  start_timestamp: convertOtelTimeToSeconds(startTime),
1692
1778
  // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1693
1779
  timestamp: convertOtelTimeToSeconds(endTime) || undefined,
1694
- status: getStatusMessage(status),
1780
+ status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1695
1781
  op,
1696
1782
  origin,
1697
1783
  _metrics_summary: getMetricSummaryJsonForSpan(span ),
@@ -1798,11 +1884,15 @@ function onSpanStart(span, parentContext) {
1798
1884
  setSpanScopes(span, scopes);
1799
1885
  }
1800
1886
 
1887
+ logSpanStart(span);
1888
+
1801
1889
  const client = getClient();
1802
1890
  _optionalChain$1([client, 'optionalAccess', _ => _.emit, 'call', _2 => _2('spanStart', span)]);
1803
1891
  }
1804
1892
 
1805
1893
  function onSpanEnd(span) {
1894
+ logSpanEnd(span);
1895
+
1806
1896
  const client = getClient();
1807
1897
  _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1808
1898
  }
@@ -1811,52 +1901,44 @@ function onSpanEnd(span) {
1811
1901
  * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
1812
1902
  * the Sentry SDK.
1813
1903
  */
1814
- class SentrySpanProcessor extends BatchSpanProcessor {
1815
- constructor() {
1816
- super(new SentrySpanExporter());
1904
+ class SentrySpanProcessor {
1817
1905
 
1906
+ constructor() {
1818
1907
  setIsSetup('SentrySpanProcessor');
1908
+ this._exporter = new SentrySpanExporter();
1819
1909
  }
1820
1910
 
1821
1911
  /**
1822
1912
  * @inheritDoc
1823
1913
  */
1824
- onStart(span, parentContext) {
1825
- onSpanStart(span, parentContext);
1826
-
1827
- // TODO (v8): Trigger client `spanStart` & `spanEnd` in here,
1828
- // once we decoupled opentelemetry from SentrySpan
1914
+ async forceFlush() {
1915
+ this._exporter.flush();
1916
+ }
1829
1917
 
1830
- DEBUG_BUILD && logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1918
+ /**
1919
+ * @inheritDoc
1920
+ */
1921
+ async shutdown() {
1922
+ this._exporter.clear();
1923
+ }
1831
1924
 
1832
- return super.onStart(span, parentContext);
1925
+ /**
1926
+ * @inheritDoc
1927
+ */
1928
+ onStart(span, parentContext) {
1929
+ onSpanStart(span, parentContext);
1833
1930
  }
1834
1931
 
1835
1932
  /** @inheritDoc */
1836
1933
  onEnd(span) {
1837
- DEBUG_BUILD && logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1838
-
1839
- if (!this._shouldSendSpanToSentry(span)) {
1840
- // Prevent this being called to super.onEnd(), which would pass this to the span exporter
1841
- return;
1842
- }
1843
-
1844
1934
  onSpanEnd(span);
1845
1935
 
1846
- return super.onEnd(span);
1847
- }
1848
-
1849
- /**
1850
- * You can overwrite this in a sub class to implement custom behavior for dropping spans.
1851
- * If you return `false` here, the span will not be passed to the exporter and thus not be sent.
1852
- */
1853
- _shouldSendSpanToSentry(_span) {
1854
- return true;
1936
+ this._exporter.export(span);
1855
1937
  }
1856
1938
  }
1857
1939
 
1858
1940
  /**
1859
- * 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
1860
1942
  */
1861
1943
  class SentrySampler {
1862
1944
 
@@ -1880,16 +1962,17 @@ class SentrySampler {
1880
1962
  return { decision: SamplingDecision.NOT_RECORD };
1881
1963
  }
1882
1964
 
1883
- const parentContext = trace.getSpanContext(context);
1884
- 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();
1885
1968
 
1886
1969
  let parentSampled = undefined;
1887
1970
 
1888
1971
  // Only inherit sample rate if `traceId` is the same
1889
1972
  // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones
1890
- if (parentContext && isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1973
+ if (parentSpan && parentContext && isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1891
1974
  if (parentContext.isRemote) {
1892
- parentSampled = getParentRemoteSampled(parentContext);
1975
+ parentSampled = getParentRemoteSampled(parentSpan);
1893
1976
  DEBUG_BUILD &&
1894
1977
  logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
1895
1978
  } else {
@@ -1898,7 +1981,7 @@ class SentrySampler {
1898
1981
  }
1899
1982
  }
1900
1983
 
1901
- const sampleRate = getSampleRate(options, {
1984
+ const [sampled, sampleRate] = sampleSpan(options, {
1902
1985
  name: spanName,
1903
1986
  attributes: spanAttributes,
1904
1987
  transactionContext: {
@@ -1909,32 +1992,12 @@ class SentrySampler {
1909
1992
  });
1910
1993
 
1911
1994
  const attributes = {
1912
- [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: Number(sampleRate),
1995
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
1913
1996
  };
1914
1997
 
1915
- // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
1916
- // only valid values are booleans or numbers between 0 and 1.)
1917
- if (!isValidSampleRate(sampleRate)) {
1918
- DEBUG_BUILD && logger.warn('[Tracing] Discarding span because of invalid sample rate.');
1919
-
1920
- return {
1921
- decision: SamplingDecision.NOT_RECORD,
1922
- attributes,
1923
- traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
1924
- };
1925
- }
1926
-
1927
- // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped
1928
- if (!sampleRate) {
1929
- DEBUG_BUILD &&
1930
- logger.log(
1931
- `[Tracing] Discarding span because ${
1932
- typeof options.tracesSampler === 'function'
1933
- ? 'tracesSampler returned 0 or false'
1934
- : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'
1935
- }`,
1936
- );
1937
-
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}`);
1938
2001
  return {
1939
2002
  decision: SamplingDecision.NOT_RECORD,
1940
2003
  attributes,
@@ -1942,19 +2005,7 @@ class SentrySampler {
1942
2005
  };
1943
2006
  }
1944
2007
 
1945
- // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
1946
- // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
1947
- const isSampled = Math.random() < (sampleRate );
1948
-
1949
- // if we're not going to keep it, we're done
1950
- if (!isSampled) {
1951
- DEBUG_BUILD &&
1952
- logger.log(
1953
- `[Tracing] Discarding span because it's not included in the random sample (sampling rate = ${Number(
1954
- sampleRate,
1955
- )})`,
1956
- );
1957
-
2008
+ if (!sampled) {
1958
2009
  return {
1959
2010
  decision: SamplingDecision.NOT_RECORD,
1960
2011
  attributes,
@@ -1974,57 +2025,9 @@ class SentrySampler {
1974
2025
  }
1975
2026
  }
1976
2027
 
1977
- function getSampleRate(
1978
- options,
1979
- samplingContext,
1980
- ) {
1981
- if (typeof options.tracesSampler === 'function') {
1982
- return options.tracesSampler(samplingContext);
1983
- }
1984
-
1985
- if (samplingContext.parentSampled !== undefined) {
1986
- return samplingContext.parentSampled;
1987
- }
1988
-
1989
- if (typeof options.tracesSampleRate !== 'undefined') {
1990
- return options.tracesSampleRate;
1991
- }
1992
-
1993
- // When `enableTracing === true`, we use a sample rate of 100%
1994
- if (options.enableTracing) {
1995
- return 1;
1996
- }
1997
-
1998
- return 0;
1999
- }
2000
-
2001
- /**
2002
- * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).
2003
- */
2004
- function isValidSampleRate(rate) {
2005
- // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
2006
- if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
2007
- DEBUG_BUILD &&
2008
- logger.warn(
2009
- `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
2010
- rate,
2011
- )} of type ${JSON.stringify(typeof rate)}.`,
2012
- );
2013
- return false;
2014
- }
2015
-
2016
- // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
2017
- if (rate < 0 || rate > 1) {
2018
- DEBUG_BUILD &&
2019
- logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
2020
- return false;
2021
- }
2022
- return true;
2023
- }
2024
-
2025
- function getParentRemoteSampled(spanContext) {
2026
- const traceId = spanContext.traceId;
2027
- const traceparentData = getPropagationContextFromSpanContext(spanContext);
2028
+ function getParentRemoteSampled(parentSpan) {
2029
+ const traceId = parentSpan.spanContext().traceId;
2030
+ const traceparentData = getPropagationContextFromSpan(parentSpan);
2028
2031
 
2029
2032
  // Only inherit sampled if `traceId` is the same
2030
2033
  return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;