|
| 1 | +""" |
| 2 | +Distributed Tracing Simulation. |
| 3 | +Demonstrates: |
| 4 | +1. Simulating a microservices architecture (Service A calling Service B). |
| 5 | +2. Propagating the Trace ID across service boundaries (e.g., via HTTP headers). |
| 6 | +3. Linking distributed logs into a single coherent Mermaid diagram. |
| 7 | +""" |
| 8 | + |
| 9 | +import time |
| 10 | +import uuid |
| 11 | +from typing import Dict, Any |
| 12 | +from mermaid_trace import trace, configure_flow |
| 13 | +from mermaid_trace.core.context import LogContext |
| 14 | + |
| 15 | +# Setup tracing to a single file to see the full picture |
| 16 | +configure_flow("mermaid_diagrams/examples/distributed_trace.mmd") |
| 17 | + |
| 18 | + |
| 19 | +# --- Simulated Network Layer --- |
| 20 | + |
| 21 | + |
| 22 | +class NetworkClient: |
| 23 | + """ |
| 24 | + Simulates an HTTP client that automatically injects the current Trace ID header. |
| 25 | + """ |
| 26 | + |
| 27 | + @trace(source="ServiceA", target="Network", action="HTTP POST") |
| 28 | + def post(self, url: str, data: Dict[str, Any]) -> Dict[str, Any]: |
| 29 | + # 1. Get current trace ID |
| 30 | + current_trace_id = LogContext.current_trace_id() |
| 31 | + |
| 32 | + # 2. Inject into headers (simulation) |
| 33 | + headers = {"X-Trace-ID": current_trace_id} |
| 34 | + print(f"[Network] Sending request to {url} with Trace ID: {current_trace_id}") |
| 35 | + |
| 36 | + # 3. Simulate network call to Service B |
| 37 | + if url == "http://service-b/api/process": |
| 38 | + return service_b_entrypoint(headers, data) |
| 39 | + return {"error": "404 Not Found"} |
| 40 | + |
| 41 | + |
| 42 | +# --- Service B (The Called Service) --- |
| 43 | + |
| 44 | + |
| 45 | +@trace(source="Network", target="ServiceB", action="Handle Request") |
| 46 | +def service_b_entrypoint( |
| 47 | + headers: Dict[str, str], payload: Dict[str, Any] |
| 48 | +) -> Dict[str, Any]: |
| 49 | + """ |
| 50 | + Simulates the entry point (e.g., FastAPI middleware) of Service B. |
| 51 | + It extracts the Trace ID and restores the context. |
| 52 | + """ |
| 53 | + # 1. Extract Trace ID from headers |
| 54 | + incoming_trace_id = headers.get("X-Trace-ID") |
| 55 | + |
| 56 | + if incoming_trace_id: |
| 57 | + # 2. RESTORE CONTEXT: Important! |
| 58 | + # This links Service B's actions to the original trace started in Service A. |
| 59 | + LogContext.set_trace_id(incoming_trace_id) |
| 60 | + print(f"[ServiceB] Resumed context with Trace ID: {incoming_trace_id}") |
| 61 | + else: |
| 62 | + # Fallback: Start a new trace if no ID provided |
| 63 | + new_id = str(uuid.uuid4()) |
| 64 | + LogContext.set_trace_id(new_id) |
| 65 | + print(f"[ServiceB] No Trace ID found, started new: {new_id}") |
| 66 | + |
| 67 | + # 3. Call internal business logic |
| 68 | + return process_data(payload) |
| 69 | + |
| 70 | + |
| 71 | +@trace(target="ServiceB.Logic") |
| 72 | +def process_data(data: Dict[str, Any]) -> Dict[str, Any]: |
| 73 | + time.sleep(0.1) |
| 74 | + return {"status": "processed", "result": f"Processed {data['item']}"} |
| 75 | + |
| 76 | + |
| 77 | +# --- Service A (The Caller Service) --- |
| 78 | + |
| 79 | + |
| 80 | +@trace(source="Client", target="ServiceA", action="Start Job") |
| 81 | +def run_job() -> None: |
| 82 | + client = NetworkClient() |
| 83 | + |
| 84 | + print("[ServiceA] Starting job...") |
| 85 | + item = {"item": "Order-123", "amount": 99.9} |
| 86 | + |
| 87 | + # This call will propagate the trace ID internally via our simulated client |
| 88 | + response = client.post("http://service-b/api/process", item) |
| 89 | + |
| 90 | + print(f"[ServiceA] Got response: {response}") |
| 91 | + |
| 92 | + |
| 93 | +if __name__ == "__main__": |
| 94 | + print("Simulating distributed tracing between Service A and Service B...") |
| 95 | + run_job() |
| 96 | + print("\nCheck 'mermaid_diagrams/examples/distributed_trace.mmd'.") |
| 97 | + print("You should see a continuous flow from Client -> ServiceA -> ServiceB.") |
0 commit comments