CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-opentelemetry--core

OpenTelemetry Core provides constants and utilities shared by all OpenTelemetry SDK packages.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

trace-state.mddocs/

Trace State

W3C TraceState specification-compliant key-value store for vendor-specific trace information with immutable operations and serialization support.

Capabilities

TraceState Class

Manages tracestate key-value pairs per W3C specification with immutable operations and proper serialization.

/**
 * TraceState manages key-value pairs for trace vendor information
 * according to W3C Trace Context specification.
 * Operations are immutable - methods return new TraceState instances.
 */
class TraceState implements api.TraceState {
  /**
   * Create a new TraceState instance
   * @param rawTraceState - Optional tracestate header string to parse
   */
  constructor(rawTraceState?: string);

  /**
   * Get value for a specific key
   * @param key - Key to retrieve value for
   * @returns Value for the key, or undefined if not found
   */
  get(key: string): string | undefined;

  /**
   * Set a key-value pair (returns new TraceState instance)
   * Modified keys are moved to the beginning of the list
   * @param key - Key to set
   * @param value - Value to set
   * @returns New TraceState instance with the key-value pair
   */
  set(key: string, value: string): TraceState;

  /**
   * Remove a key-value pair (returns new TraceState instance)
   * @param key - Key to remove
   * @returns New TraceState instance without the key
   */
  unset(key: string): TraceState;

  /**
   * Serialize TraceState to header string format
   * @returns Serialized tracestate string (key1=value1,key2=value2)
   */
  serialize(): string;
}

Usage Examples:

import { TraceState } from "@opentelemetry/core";

// Create TraceState from header string
const traceState = new TraceState("vendor1=value1,vendor2=value2");

// Get values
const vendor1Value = traceState.get("vendor1");
console.log(vendor1Value); // "value1"

// Set new values (immutable - returns new instance)
const updatedState = traceState
  .set("vendor3", "value3")
  .set("vendor1", "newvalue1"); // Updates existing key

// Original traceState is unchanged
console.log(traceState.get("vendor1"));     // "value1"
console.log(updatedState.get("vendor1"));   // "newvalue1"

// Remove keys
const cleanedState = updatedState.unset("vendor2");

// Serialize for HTTP header
const headerValue = cleanedState.serialize();
console.log(headerValue); // "vendor1=newvalue1,vendor3=value3"

// Create empty TraceState and build it up
let state = new TraceState();
state = state.set("tenant", "production");
state = state.set("service", "user-api");
state = state.set("version", "1.2.3");

console.log(state.serialize()); // "version=1.2.3,service=user-api,tenant=production"

Trace Parent Parsing

Function to parse W3C traceparent header values into SpanContext objects.

/**
 * Parse traceparent header value into SpanContext
 * @param traceParent - Traceparent header value in format: version-traceId-spanId-flags
 * @returns SpanContext object or null if parsing fails
 */
function parseTraceParent(traceParent: string): SpanContext | null;

/**
 * Traceparent header name constant
 */
const TRACE_PARENT_HEADER: string;

/**
 * Tracestate header name constant  
 */
const TRACE_STATE_HEADER: string;

Usage Examples:

import { parseTraceParent, TRACE_PARENT_HEADER, TRACE_STATE_HEADER } from "@opentelemetry/core";

// Parse valid traceparent header
const traceParent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
const spanContext = parseTraceParent(traceParent);

if (spanContext) {
  console.log("Trace ID:", spanContext.traceId);     // "4bf92f3577b34da6a3ce929d0e0e4736"
  console.log("Span ID:", spanContext.spanId);       // "00f067aa0ba902b7"
  console.log("Trace Flags:", spanContext.traceFlags); // 1 (sampled)
  console.log("Is Remote:", spanContext.isRemote);    // undefined (set by propagator)
}

// Handle invalid traceparent
const invalidParent = "invalid-format";
const invalidContext = parseTraceParent(invalidParent);
console.log(invalidContext); // null

// Use constants for header names
const headers: Record<string, string> = {};
headers[TRACE_PARENT_HEADER] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
headers[TRACE_STATE_HEADER] = "vendor1=value1,vendor2=value2";

// Process headers
const parsedContext = parseTraceParent(headers[TRACE_PARENT_HEADER]);
const traceState = new TraceState(headers[TRACE_STATE_HEADER]);

if (parsedContext && traceState) {
  // Combine for complete span context
  const completeContext = {
    ...parsedContext,
    traceState: traceState
  };
}

Integration with OpenTelemetry API

TraceState integrates seamlessly with OpenTelemetry API's Context and span management.

Usage Examples:

import { TraceState } from "@opentelemetry/core";
import { trace } from "@opentelemetry/api";

// Get current span and its trace state
const span = trace.getActiveSpan();
const spanContext = span?.spanContext();
const currentTraceState = spanContext?.traceState;

if (currentTraceState instanceof TraceState) {
  // Add vendor-specific information
  const enhancedState = currentTraceState
    .set("my-vendor", "processing-user-request")
    .set("datacenter", "us-west-2")
    .set("canary", "10percent");

  // Create new span context with enhanced trace state
  const newSpanContext = {
    ...spanContext,
    traceState: enhancedState
  };

  // Use in child span creation
  const childSpan = trace.getTracer("my-service").startSpan("child-operation", {
    parent: trace.setSpanContext(trace.context.active(), newSpanContext)
  });
}

// Extract trace state from incoming request headers
function handleIncomingRequest(headers: Record<string, string>) {
  const traceStateValue = headers['tracestate'];
  
  if (traceStateValue) {
    const traceState = new TraceState(traceStateValue);
    
    // Check vendor-specific values
    const canaryPercentage = traceState.get("canary");
    const datacenter = traceState.get("datacenter");
    
    if (canaryPercentage === "10percent") {
      // Route to canary deployment
      console.log("Routing to canary deployment");
    }
    
    if (datacenter === "us-west-2") {
      // Use west coast database
      console.log("Using west coast database");
    }
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-opentelemetry--core

docs

context.md

index.md

platform.md

propagation.md

timing.md

trace-state.md

utilities.md

validation.md

tile.json