|
| 1 | +""" |
| 2 | +Simple Temporal interceptors for threading task_id to enable streaming. |
| 3 | +
|
| 4 | +This module provides minimal interceptors to pass task_id from workflows |
| 5 | +to activities via headers, making it available to the StreamingModel. |
| 6 | +""" |
| 7 | + |
| 8 | +from contextvars import ContextVar |
| 9 | +from typing import Optional, Any, Type |
| 10 | +import logging |
| 11 | + |
| 12 | +from temporalio import workflow |
| 13 | +from temporalio.worker import ( |
| 14 | + Interceptor, |
| 15 | + WorkflowInboundInterceptor, |
| 16 | + WorkflowOutboundInterceptor, |
| 17 | + ActivityInboundInterceptor, |
| 18 | + ExecuteWorkflowInput, |
| 19 | + StartActivityInput, |
| 20 | + ExecuteActivityInput, |
| 21 | +) |
| 22 | +from temporalio.converter import default |
| 23 | + |
| 24 | +# Set up logging |
| 25 | +logger = logging.getLogger("streaming.interceptor") |
| 26 | + |
| 27 | +# Global context variable that StreamingModel will read |
| 28 | +# This is thread-safe and works across async boundaries |
| 29 | +streaming_task_id: ContextVar[Optional[str]] = ContextVar('streaming_task_id', default=None) |
| 30 | +streaming_trace_id: ContextVar[Optional[str]] = ContextVar('streaming_trace_id', default=None) |
| 31 | +streaming_parent_span_id: ContextVar[Optional[str]] = ContextVar('streaming_parent_span_id', default=None) |
| 32 | +# Header key for passing task_id |
| 33 | +TASK_ID_HEADER = "streaming-task-id" |
| 34 | +TRACE_ID_HEADER = "trace-id" |
| 35 | +PARENT_SPAN_ID_HEADER = "parent-span-id" |
| 36 | + |
| 37 | +class StreamingInterceptor(Interceptor): |
| 38 | + """Main interceptor that enables task_id threading.""" |
| 39 | + |
| 40 | + def __init__(self): |
| 41 | + self._payload_converter = default().payload_converter |
| 42 | + logger.info("[StreamingInterceptor] Initialized") |
| 43 | + |
| 44 | + def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor: |
| 45 | + """Create activity interceptor to read task_id from headers.""" |
| 46 | + return StreamingActivityInboundInterceptor(next, self._payload_converter) |
| 47 | + |
| 48 | + def workflow_interceptor_class(self, input: Any) -> Optional[Type[WorkflowInboundInterceptor]]: |
| 49 | + """Return workflow interceptor class.""" |
| 50 | + return StreamingWorkflowInboundInterceptor |
| 51 | + |
| 52 | + |
| 53 | +class StreamingWorkflowInboundInterceptor(WorkflowInboundInterceptor): |
| 54 | + """Workflow interceptor that creates the outbound interceptor.""" |
| 55 | + |
| 56 | + def __init__(self, next: WorkflowInboundInterceptor): |
| 57 | + super().__init__(next) |
| 58 | + self._payload_converter = default().payload_converter |
| 59 | + |
| 60 | + async def execute_workflow(self, input: ExecuteWorkflowInput) -> Any: |
| 61 | + """Execute workflow - just pass through.""" |
| 62 | + return await self.next.execute_workflow(input) |
| 63 | + |
| 64 | + def init(self, outbound: WorkflowOutboundInterceptor) -> None: |
| 65 | + """Initialize with our custom outbound interceptor.""" |
| 66 | + self.next.init(StreamingWorkflowOutboundInterceptor( |
| 67 | + outbound, self._payload_converter |
| 68 | + )) |
| 69 | + |
| 70 | + |
| 71 | +class StreamingWorkflowOutboundInterceptor(WorkflowOutboundInterceptor): |
| 72 | + """Outbound interceptor that adds task_id to activity headers.""" |
| 73 | + |
| 74 | + def __init__(self, next, payload_converter): |
| 75 | + super().__init__(next) |
| 76 | + self._payload_converter = payload_converter |
| 77 | + |
| 78 | + def start_activity(self, input: StartActivityInput) -> workflow.ActivityHandle: |
| 79 | + """Add task_id, trace_id, and parent_span_id to headers when starting model activities.""" |
| 80 | + |
| 81 | + # Only add headers for invoke_model_activity calls |
| 82 | + activity_name = str(input.activity) if hasattr(input, 'activity') else "" |
| 83 | + |
| 84 | + if "invoke_model_activity" in activity_name or "invoke-model-activity" in activity_name: |
| 85 | + # Get task_id, trace_id, and parent_span_id from workflow instance instead of inbound interceptor |
| 86 | + try: |
| 87 | + workflow_instance = workflow.instance() |
| 88 | + task_id = getattr(workflow_instance, '_task_id', None) |
| 89 | + trace_id = getattr(workflow_instance, '_trace_id', None) |
| 90 | + parent_span_id = getattr(workflow_instance, '_parent_span_id', None) |
| 91 | + |
| 92 | + if task_id and trace_id and parent_span_id: |
| 93 | + # Initialize headers if needed |
| 94 | + if not input.headers: |
| 95 | + input.headers = {} |
| 96 | + |
| 97 | + # Add task_id to headers |
| 98 | + input.headers[TASK_ID_HEADER] = self._payload_converter.to_payload(task_id) |
| 99 | + input.headers[TRACE_ID_HEADER] = self._payload_converter.to_payload(trace_id) |
| 100 | + input.headers[PARENT_SPAN_ID_HEADER] = self._payload_converter.to_payload(parent_span_id) |
| 101 | + logger.debug(f"[OutboundInterceptor] Added task_id, trace_id, and parent_span_id to activity headers: {task_id}, {trace_id}, {parent_span_id}") |
| 102 | + else: |
| 103 | + logger.warning("[OutboundInterceptor] No _task_id, _trace_id, or _parent_span_id found in workflow instance") |
| 104 | + except Exception as e: |
| 105 | + logger.error(f"[OutboundInterceptor] Failed to get task_id, trace_id, or parent_span_id from workflow instance: {e}") |
| 106 | + |
| 107 | + return self.next.start_activity(input) |
| 108 | + |
| 109 | + |
| 110 | +class StreamingActivityInboundInterceptor(ActivityInboundInterceptor): |
| 111 | + """Activity interceptor that extracts task_id, trace_id, and parent_span_id from headers and sets context variables.""" |
| 112 | + |
| 113 | + def __init__(self, next, payload_converter): |
| 114 | + super().__init__(next) |
| 115 | + self._payload_converter = payload_converter |
| 116 | + |
| 117 | + async def execute_activity(self, input: ExecuteActivityInput) -> Any: |
| 118 | + """Extract task_id, trace_id, and parent_span_id from headers and set context variables.""" |
| 119 | + |
| 120 | + # Extract task_id from headers if present |
| 121 | + if input.headers and TASK_ID_HEADER in input.headers: |
| 122 | + task_id_value = self._payload_converter.from_payload( |
| 123 | + input.headers[TASK_ID_HEADER], str |
| 124 | + ) |
| 125 | + trace_id_value = self._payload_converter.from_payload( |
| 126 | + input.headers[TRACE_ID_HEADER], str |
| 127 | + ) |
| 128 | + parent_span_id_value = self._payload_converter.from_payload( |
| 129 | + input.headers[PARENT_SPAN_ID_HEADER], str |
| 130 | + ) |
| 131 | + |
| 132 | + # P THIS IS THE KEY PART - Set the context variable! |
| 133 | + # This makes task_id available to StreamingModel.get_response() |
| 134 | + streaming_task_id.set(task_id_value) |
| 135 | + streaming_trace_id.set(trace_id_value) |
| 136 | + streaming_parent_span_id.set(parent_span_id_value) |
| 137 | + logger.info(f"[ActivityInterceptor] Set task_id, trace_id, and parent_span_id in context: {task_id_value}, {trace_id_value}, {parent_span_id_value}") |
| 138 | + else: |
| 139 | + logger.debug("[ActivityInterceptor] No task_id, trace_id, or parent_span_id in headers") |
| 140 | + |
| 141 | + try: |
| 142 | + # Execute the activity |
| 143 | + # The StreamingModel can now read streaming_task_id.get() |
| 144 | + result = await self.next.execute_activity(input) |
| 145 | + return result |
| 146 | + finally: |
| 147 | + # Clean up context after activity |
| 148 | + streaming_task_id.set(None) |
| 149 | + streaming_trace_id.set(None) |
| 150 | + streaming_parent_span_id.set(None) |
| 151 | + logger.debug("[ActivityInterceptor] Cleared task_id, trace_id, and parent_span_id from context") |
| 152 | + |
0 commit comments