|
| 1 | +"""Deterministic ID generator for OpenTelemetry spans in durable executions.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import os |
| 7 | +import re |
| 8 | +from datetime import datetime, UTC |
| 9 | + |
| 10 | +from opentelemetry.sdk.trace import IdGenerator, RandomIdGenerator |
| 11 | + |
| 12 | +HASH_LENGTH = 16 |
| 13 | +HASHED_ID_PATTERN = re.compile(r"^[0-9a-f]{16}$") |
| 14 | + |
| 15 | + |
| 16 | +def hash_id(input_str: str) -> str: |
| 17 | + """Create an MD5 hash of the input string, truncated to 16 hex chars. |
| 18 | +
|
| 19 | + This matches the JS SDK's hashId function used for operation IDs. |
| 20 | + """ |
| 21 | + return hashlib.md5(input_str.encode()).hexdigest()[:HASH_LENGTH] # noqa: S324 |
| 22 | + |
| 23 | + |
| 24 | +def _parse_xray_root_trace_id(trace_header: str | None) -> str | None: |
| 25 | + """Parse the Root trace ID from an X-Ray trace header string. |
| 26 | +
|
| 27 | + The header format is: |
| 28 | + Root=1-<8 hex>-<24 hex>;Parent=<16 hex>;Sampled=0|1 |
| 29 | +
|
| 30 | + Returns the root value (e.g. "1-5759e988-bd862e3fe1be46a994272793") |
| 31 | + or None if the header is missing or malformed. |
| 32 | + """ |
| 33 | + if not trace_header: |
| 34 | + return None |
| 35 | + match = re.search(r"Root=(1-[0-9a-fA-F]{8}-[0-9a-fA-F]{24})", trace_header) |
| 36 | + return match.group(1) if match else None |
| 37 | + |
| 38 | + |
| 39 | +def _xray_trace_id_to_otel(xray_trace_id: str) -> int: |
| 40 | + """Convert an X-Ray trace ID to the W3C/OpenTelemetry 32-char hex format. |
| 41 | +
|
| 42 | + X-Ray format: "1-<8hex>-<24hex>" (36 chars with prefix and dashes) |
| 43 | + OTel format: "<8hex><24hex>" (32 lowercase hex chars) |
| 44 | + """ |
| 45 | + otel_id = xray_trace_id.replace("1-", "", 1).replace("-", "").lower() |
| 46 | + return int(otel_id, 16) |
| 47 | + |
| 48 | + |
| 49 | +def _to_otel_trace_id(execution_arn: str, start_timestamp: datetime | None) -> int: |
| 50 | + """Build an OTel-compatible trace ID (128 bits) |
| 51 | +
|
| 52 | + First attempts to read the trace ID from the _X_AMZN_TRACE_ID environment |
| 53 | + variable that Lambda populates on each invocation. This ties the durable |
| 54 | + execution spans to the same trace that X-Ray is already tracking. |
| 55 | +
|
| 56 | + Falls back to generating a deterministic trace ID from the execution ARN |
| 57 | + and timestamp when the environment variable is not set (e.g. in tests or |
| 58 | + non-Lambda environments). |
| 59 | + """ |
| 60 | + env_trace_id = _parse_xray_root_trace_id(os.environ.get("_X_AMZN_TRACE_ID")) |
| 61 | + if env_trace_id: |
| 62 | + return _xray_trace_id_to_otel(env_trace_id) |
| 63 | + |
| 64 | + # Fallback: deterministic ID from execution ARN + timestamp |
| 65 | + time_part = format(int((start_timestamp or datetime.now(UTC)).timestamp()), "08x") |
| 66 | + hash_part = hashlib.blake2b(execution_arn.encode()).hexdigest()[:24] # noqa: S324 |
| 67 | + return int(f"{time_part}{hash_part}", 16) |
| 68 | + |
| 69 | + |
| 70 | +def operation_id_to_span_id(operation_id: str) -> int: |
| 71 | + """Derive a deterministic span ID (64 bits) from an operation ID.""" |
| 72 | + hashed_operation_id = hashlib.blake2b(operation_id.encode()).hexdigest()[:16] |
| 73 | + return int(hashed_operation_id, 16) |
| 74 | + |
| 75 | + |
| 76 | +class DeterministicIdGenerator(IdGenerator): |
| 77 | + """An ID generator that produces deterministic span IDs when a pending |
| 78 | + operation ID is set, and random IDs otherwise. |
| 79 | +
|
| 80 | + Trace IDs are deterministic when an execution ARN is set, ensuring all |
| 81 | + invocations of the same durable execution share a single trace. |
| 82 | +
|
| 83 | + Trace IDs embed a real timestamp so they satisfy the X-Ray format |
| 84 | + requirement (first 8 hex chars = Unix epoch seconds). |
| 85 | + """ |
| 86 | + |
| 87 | + def __init__(self) -> None: |
| 88 | + self._next_span_id: int | None = None |
| 89 | + self._execution_trace_id: int | None = None |
| 90 | + self._random_id_generator = RandomIdGenerator() |
| 91 | + |
| 92 | + def set_next_span_id(self, operation_id: str | None) -> None: |
| 93 | + """Set the operation ID to use for the next span's ID. |
| 94 | +
|
| 95 | + After one span is created, it resets to random. |
| 96 | + """ |
| 97 | + self._next_span_id = ( |
| 98 | + operation_id_to_span_id(operation_id) if operation_id else None |
| 99 | + ) |
| 100 | + |
| 101 | + def set_trace_id( |
| 102 | + self, execution_arn: str, start_timestamp: datetime | None |
| 103 | + ) -> None: |
| 104 | + """Compute and cache the deterministic trace ID for this execution. |
| 105 | +
|
| 106 | + Args: |
| 107 | + execution_arn: The durable execution ARN (used for the hash portion). |
| 108 | + start_timestamp: start time of invocation |
| 109 | + """ |
| 110 | + self._execution_trace_id = _to_otel_trace_id(execution_arn, start_timestamp) |
| 111 | + |
| 112 | + def generate_trace_id(self) -> int: |
| 113 | + """Generate a 128-bit trace ID.""" |
| 114 | + if self._execution_trace_id: |
| 115 | + return self._execution_trace_id |
| 116 | + return self._random_id_generator.generate_trace_id() |
| 117 | + |
| 118 | + def generate_span_id(self) -> int: |
| 119 | + """Generate a 64-bit span ID.""" |
| 120 | + if self._next_span_id: |
| 121 | + span_id = self._next_span_id |
| 122 | + self._next_span_id = None |
| 123 | + return span_id |
| 124 | + return self._random_id_generator.generate_span_id() |
0 commit comments