콘텐츠로 이동

spakky-tracing

분산 트레이싱 추상화 — TraceContext, ITracePropagator, W3C Propagator

컨텍스트

spakky.tracing.context

TraceContext — contextvars-based distributed trace context.

TraceContext

W3C Trace Context Level 2 compatible trace context.

Attributes:

Name Type Description
trace_id str

32-character hex string (128-bit).

span_id str

16-character hex string (64-bit).

parent_span_id str | None

Parent span ID, or None for root spans.

trace_flags int

Trace flags (0x01 = sampled).

generate_trace_id() classmethod

Generate a new random 128-bit trace ID as 32-character hex.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def generate_trace_id(cls) -> str:
    """Generate a new random 128-bit trace ID as 32-character hex."""
    return token_hex(cls._TRACE_ID_BYTES)

generate_span_id() classmethod

Generate a new random 64-bit span ID as 16-character hex.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def generate_span_id(cls) -> str:
    """Generate a new random 64-bit span ID as 16-character hex."""
    return token_hex(cls._SPAN_ID_BYTES)

to_traceparent()

Serialize to W3C traceparent header format.

Returns:

Type Description
str

Traceparent string: 00-{trace_id}-{span_id}-{flags:02x}.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
def to_traceparent(self) -> str:
    """Serialize to W3C traceparent header format.

    Returns:
        Traceparent string: ``00-{trace_id}-{span_id}-{flags:02x}``.
    """
    return f"00-{self.trace_id}-{self.span_id}-{self.trace_flags:02x}"

from_traceparent(header) classmethod

Parse a W3C traceparent header.

Format: {version}-{trace_id}-{span_id}-{trace_flags} Example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01

Parameters:

Name Type Description Default
header str

The traceparent header value.

required

Returns:

Type Description
Self

Parsed TraceContext.

Raises:

Type Description
InvalidTraceparentError

If the header format is invalid.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def from_traceparent(cls, header: str) -> Self:
    """Parse a W3C traceparent header.

    Format: ``{version}-{trace_id}-{span_id}-{trace_flags}``
    Example: ``00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01``

    Args:
        header: The traceparent header value.

    Returns:
        Parsed TraceContext.

    Raises:
        InvalidTraceparentError: If the header format is invalid.
    """
    match = cls._TRACEPARENT_PATTERN.match(header.strip())
    if match is None:
        raise InvalidTraceparentError()
    _version, trace_id, span_id, flags_hex = match.groups()
    return cls(
        trace_id=trace_id,
        span_id=span_id,
        trace_flags=int(flags_hex, cls._HEX_BASE),
    )

new_root() classmethod

Create a new root trace (generates trace_id and span_id).

Returns:

Type Description
Self

A new TraceContext with fresh IDs.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def new_root(cls) -> Self:
    """Create a new root trace (generates trace_id and span_id).

    Returns:
        A new TraceContext with fresh IDs.
    """
    return cls(
        trace_id=cls.generate_trace_id(),
        span_id=cls.generate_span_id(),
    )

child()

Create a child span under this context.

Returns:

Type Description
Self

A new TraceContext sharing the same trace_id, with a new span_id

Self

and parent_span_id set to the current span_id.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
def child(self) -> Self:
    """Create a child span under this context.

    Returns:
        A new TraceContext sharing the same trace_id, with a new span_id
        and parent_span_id set to the current span_id.
    """
    return TraceContext(
        trace_id=self.trace_id,
        span_id=self.generate_span_id(),
        parent_span_id=self.span_id,
        trace_flags=self.trace_flags,
    )

get() classmethod

Get the current execution context's TraceContext.

Returns:

Type Description
Self | None

The current TraceContext, or None if not set.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def get(cls) -> Self | None:
    """Get the current execution context's TraceContext.

    Returns:
        The current TraceContext, or None if not set.
    """
    return _trace_context.get()

set(ctx) classmethod

Set the TraceContext for the current execution context.

Parameters:

Name Type Description Default
ctx Self

The TraceContext to set.

required
Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def set(cls, ctx: Self) -> None:
    """Set the TraceContext for the current execution context.

    Args:
        ctx: The TraceContext to set.
    """
    _trace_context.set(ctx)

clear() classmethod

Clear the TraceContext from the current execution context.

Source code in core/spakky-tracing/src/spakky/tracing/context.py
@classmethod
def clear(cls) -> None:
    """Clear the TraceContext from the current execution context."""
    _trace_context.set(None)

options: show_root_heading: false

Propagator 인터페이스

spakky.tracing.propagator

ITracePropagator — trace context propagation interface.

ITracePropagator

Bases: ABC

Interface for trace context propagation across service boundaries.

Implementations read/write the ambient TraceContext (stored in contextvars) from/to carrier dictionaries such as HTTP headers or message metadata.

Terminology follows the OpenTelemetry TextMapPropagator convention:

  • inject — read the ambient TraceContext and write it into an outbound carrier. Does not create a new trace; it serializes whatever context is currently active. If no context is active the carrier is left unchanged.
  • extract — read an inbound carrier and reconstruct a TraceContext. The caller is responsible for activating it via TraceContext.set().

inject(carrier) abstractmethod

Read the ambient TraceContext and write it into the carrier.

This is an upsert on the carrier: if a context is active its header fields are added (or overwritten); if no context is active the carrier is left untouched.

Parameters:

Name Type Description Default
carrier dict[str, str]

Mutable header dictionary. After the call, keys such as traceparent may be present.

required
Source code in core/spakky-tracing/src/spakky/tracing/propagator.py
@abstractmethod
def inject(self, carrier: dict[str, str]) -> None:
    """Read the ambient TraceContext and write it into the carrier.

    This is an **upsert** on the carrier: if a context is active its
    header fields are added (or overwritten); if no context is active
    the carrier is left untouched.

    Args:
        carrier: Mutable header dictionary.  After the call, keys such
            as ``traceparent`` may be present.
    """
    ...

extract(carrier) abstractmethod

Reconstruct a TraceContext from the carrier.

The returned context is not automatically activated. Call TraceContext.set() to make it the ambient context.

Parameters:

Name Type Description Default
carrier dict[str, str]

Read-only header dictionary.

required

Returns:

Type Description
TraceContext | None

The restored TraceContext, or None if the required headers are

TraceContext | None

missing or malformed.

Source code in core/spakky-tracing/src/spakky/tracing/propagator.py
@abstractmethod
def extract(self, carrier: dict[str, str]) -> TraceContext | None:
    """Reconstruct a TraceContext from the carrier.

    The returned context is **not** automatically activated.  Call
    ``TraceContext.set()`` to make it the ambient context.

    Args:
        carrier: Read-only header dictionary.

    Returns:
        The restored TraceContext, or None if the required headers are
        missing or malformed.
    """
    ...

fields() abstractmethod

Return the header field names used by this propagator.

Returns:

Type Description
list[str]

List of header names, e.g., ["traceparent", "tracestate"].

Source code in core/spakky-tracing/src/spakky/tracing/propagator.py
@abstractmethod
def fields(self) -> list[str]:
    """Return the header field names used by this propagator.

    Returns:
        List of header names, e.g., ``["traceparent", "tracestate"]``.
    """
    ...

options: show_root_heading: false

W3C Propagator

spakky.tracing.w3c_propagator

W3CTracePropagator — W3C Trace Context Level 2 propagator.

W3CTracePropagator

Bases: ITracePropagator

W3C Trace Context Level 2 standard propagator.

Pure Python implementation with no external dependencies. traceparent format: {version:2}-{trace_id:32}-{span_id:16}-{trace_flags:2}

inject(carrier)

Write the current TraceContext as a traceparent header into the carrier.

Parameters:

Name Type Description Default
carrier dict[str, str]

Mutable header dictionary.

required
Source code in core/spakky-tracing/src/spakky/tracing/w3c_propagator.py
@override
def inject(self, carrier: dict[str, str]) -> None:
    """Write the current TraceContext as a traceparent header into the carrier.

    Args:
        carrier: Mutable header dictionary.
    """
    ctx = TraceContext.get()
    if ctx is not None:
        carrier[TRACEPARENT_HEADER] = ctx.to_traceparent()

extract(carrier)

Restore a TraceContext from the traceparent header in the carrier.

Parameters:

Name Type Description Default
carrier dict[str, str]

Read-only header dictionary.

required

Returns:

Type Description
TraceContext | None

The restored TraceContext, or None if the header is missing or invalid.

Source code in core/spakky-tracing/src/spakky/tracing/w3c_propagator.py
@override
def extract(self, carrier: dict[str, str]) -> TraceContext | None:
    """Restore a TraceContext from the traceparent header in the carrier.

    Args:
        carrier: Read-only header dictionary.

    Returns:
        The restored TraceContext, or None if the header is missing or invalid.
    """
    header = carrier.get(TRACEPARENT_HEADER)
    if header is None:
        return None
    try:
        return TraceContext.from_traceparent(header)
    except Exception:  # pragma: no branch - InvalidTraceparentError 외 방어
        return None

fields()

Return the header field names used by this propagator.

Returns:

Type Description
list[str]

["traceparent"]

Source code in core/spakky-tracing/src/spakky/tracing/w3c_propagator.py
@override
def fields(self) -> list[str]:
    """Return the header field names used by this propagator.

    Returns:
        ``["traceparent"]``
    """
    return [TRACEPARENT_HEADER]

options: show_root_heading: false

에러

spakky.tracing.error

Error classes for the spakky-tracing package.

AbstractSpakkyTracingError

Bases: AbstractSpakkyFrameworkError, ABC

Base class for all tracing-related errors.

InvalidTraceparentError

Bases: AbstractSpakkyTracingError

Raised when a traceparent header has an invalid format.

options: show_root_heading: false