All files / src/core TracingManager.ts

86.86% Statements 172/198
80% Branches 28/35
78.57% Functions 11/14
86.86% Lines 172/198

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 1991x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 29x 29x 29x 29x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 2x 2x 2x 2x 2x 2x 2x 2x           17x 19x 19x 2x   19x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 8x 8x 1x 1x               1x 1x 16x 16x 1x 1x 2x 1x 1x 1x 1x 1x 1x 2x 1x 1x 8x 8x 8x 1x 1x 1x 7x 7x 7x 8x 6x 8x 1x 1x 1x 1x 1x 1x           1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 8x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x     1x 1x     1x 1x 31x 17x 17x 17x 17x     17x 31x 31x 31x 1x  
import type { LightConfig, SpanContext, TransactionContext, Span, Transaction, LightClient, SamplingContext } from '../types';
import { Span as SpanImpl, Transaction as TransactionImpl } from '../utils/tracing';
import { logDebug } from '../utils/logger';
 
export class TracingManager {
  private config: LightConfig;
  private _client?: LightClient;
  private currentTransaction: Transaction | null = null;
  private spanStack: Span[] = [];
  private dsnPublicKey?: string;
 
  constructor(config: LightConfig, client?: LightClient, dsnPublicKey?: string) {
    this.config = config;
    this._client = client;
    this.dsnPublicKey = dsnPublicKey;
  }
 
  updateConfig(config: LightConfig): void {
    this.config = config;
    if (this.currentTransaction) {
      const txImpl = this.currentTransaction as unknown as TransactionImpl;
      txImpl.setUserBaggage(config.user?.id, (config.user as { segment?: string } | undefined)?.segment);
    }
  }
 
  private shouldSample(context: TransactionContext, parentSampled?: boolean): boolean {
    const sampler = this.config.tracesSampler;
    if (sampler) {
      const samplingContext: SamplingContext = {
        ...context,
        parentSampled,
      };
      const result = sampler(samplingContext);
      if (typeof result === 'boolean') {
        return result;
      }
      const clampedRate = Math.max(0, Math.min(1, result));
      if (clampedRate === 0) return false;
      if (clampedRate === 1) return true;
      return Math.random() < clampedRate;
    }
 
    const rate = this.config.tracesSampleRate ?? 0;
    if (rate >= 1) return true;
    if (rate <= 0) return false;
    return Math.random() < rate;
  }
 
  startTransaction(context: TransactionContext): Transaction | null {
    const parentTx = this.currentTransaction;
    const parentSampled = parentTx ? parentTx.sampled : undefined;
 
    const sampled = context.sampled ?? this.shouldSample(context, parentSampled);
 
    const transaction = new TransactionImpl(
      {
        ...context,
        sampled,
      },
      this._client,
      this.dsnPublicKey,
      this.config.release,
      this.config.environment
    ) as unknown as Transaction;
 
    this.currentTransaction = transaction;
    this.spanStack = [transaction];
 
    logDebug('TracingManager', 'Transaction started', {
      name: transaction.name,
      traceId: transaction.traceId,
      spanId: transaction.spanId,
      sampled,
      op: transaction.op,
    });
 
    return transaction;
  }
 
  getCurrentTransaction(): Transaction | null {
    return this.currentTransaction;
  }
 
  setCurrentTransaction(transaction: Transaction | null): void {
    this.currentTransaction = transaction;
    if (!transaction) {
      this.spanStack = [];
    } else {
      this.spanStack = [transaction];
    }
  }
 
  getCurrentSpan(): Span | null {
    return this.spanStack.length > 0 ? this.spanStack[this.spanStack.length - 1] : null;
  }
 
  setCurrentSpan(span: Span | null): void {
    if (span === null) {
      if (this.spanStack.length > 1) {
        this.spanStack.pop();
      }
    } else {
      this.spanStack.push(span);
    }
  }
 
  startSpan(context: SpanContext): Span | null {
    const parentSpan = this.getCurrentSpan();
 
    if (!parentSpan && !context.traceId) {
      logDebug('TracingManager', 'startSpan skipped: no active span and no traceId');
      return null;
    }
 
    let span: Span;
 
    if (parentSpan) {
      span = (parentSpan as SpanImpl).startChild(context);
    } else {
      span = new SpanImpl({
        ...context,
        parentSpanId: context.parentSpanId,
      }) as unknown as Span;
 
      if (this.currentTransaction) {
        if (this.currentTransaction.sampled !== false) {
          (this.currentTransaction as unknown as TransactionImpl)._addSpan(span as unknown as SpanImpl);
        }
        (span as SpanImpl & { transaction: Transaction }).transaction = this.currentTransaction;
      }
    }
 
    this.spanStack.push(span);
 
    logDebug('TracingManager', 'Span started', {
      op: span.op,
      description: span.description,
      spanId: span.spanId,
      parentSpanId: span.parentSpanId,
      stackDepth: this.spanStack.length,
    });
 
    return span;
  }
 
  onSpanFinished(span: Span): void {
    const idx = this.spanStack.lastIndexOf(span);
    if (idx !== -1) {
      this.spanStack.splice(idx, 1);
    }
 
    if (this.spanStack.length === 0 && this.currentTransaction) {
      this.spanStack = [this.currentTransaction];
    }
 
    logDebug('TracingManager', 'Span finished', {
      op: span.op,
      description: span.description,
      spanId: span.spanId,
      stackDepth: this.spanStack.length,
    });
  }
 
  onTransactionFinished(transaction: Transaction): void {
    if (this.currentTransaction === transaction) {
      this.currentTransaction = null;
      this.spanStack = [];
    }
 
    logDebug('TracingManager', 'Transaction finished', {
      name: transaction.name,
      traceId: transaction.traceId,
      spanCount: transaction.spans.length,
      sampled: transaction.sampled,
    });
  }
 
  finishSpan(span: Span): void {
    span.finish();
  }
 
  finishTransaction(transaction: Transaction): void {
    transaction.finish();
  }
 
  destroy(): void {
    if (this.currentTransaction) {
      try {
        this.currentTransaction.setStatus('aborted');
        this.currentTransaction.finish();
      } catch {
        // ignore
      }
    }
    this.currentTransaction = null;
    this.spanStack = [];
  }
}