22from workflows .transport .middleware import BaseTransportMiddleware
33from collections .abc import Callable
44import functools
5- from opentelemetry .propagate import inject
5+ from opentelemetry .propagate import inject , extract
66
77class OTELTracingMiddleware (BaseTransportMiddleware ):
88 def __init__ (self , tracer : trace .Tracer , service_name : str ):
@@ -14,29 +14,23 @@ def __init__(self, tracer: trace.Tracer, service_name: str):
1414 self .tracer = tracer
1515 self .service_name = service_name
1616
17-
18- def send (self , call_next : Callable , destination , message , ** kwargs ):
19- """
20- Middleware for tracing the `send` operation
21-
22- :param call_next: The next middleware or the original `send` method.
23- :param destination: The destination service to which the message is being sent.
24- :param message: The message being sent.
25- :param kwargs: Additional arguments for the `send` method.
26- """
27-
28- # Start a new span for the `send` operation
29- with self .tracer .start_as_current_span ("transport.send" ) as span :
30- # Attributes we're interested in
31- span .set_attribute ("service_name" , self .service_name )
32- span .set_attribute ("destination" , destination )
33- span .set_attribute ("message" , str (message ))
17+ def subscribe (self , call_next : Callable , channel , callback , ** kwargs ) -> int :
18+ @functools .wraps (callback )
19+ def wrapped_callback (header , message ):
20+ # Extract trace context from message headers
21+ ctx = extract (header ) if header else None
3422
35- # Inject trace context into message headers
36- headers = kwargs .setdefault ("headers" , {})
37- inject (headers )
38- kwargs ["headers" ] = headers
39-
40- # Call the next middleware or the original `send` method
41- return call_next (destination , message , ** kwargs )
42-
23+ # Start a new span with the extracted context
24+ with self .tracer .start_as_current_span (
25+ "transport.subscribe" ,
26+ context = ctx
27+ ) as span :
28+ span .set_attribute ("service_name" , self .service_name )
29+ span .set_attribute ("channel" , channel )
30+
31+
32+ # Call the original callback
33+ return callback (header , message )
34+
35+ # Call the next middleware with the wrapped callback
36+ return call_next (channel , wrapped_callback , ** kwargs )
0 commit comments