-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfactory.py
More file actions
197 lines (168 loc) · 6.62 KB
/
Copy pathfactory.py
File metadata and controls
197 lines (168 loc) · 6.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""Factory for creating UiPath runtime instances."""
from typing import (
Any,
AsyncGenerator,
Callable,
Generic,
List,
Optional,
Type,
TypeVar,
)
from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
from opentelemetry.sdk.trace.export import SpanExporter
from opentelemetry.trace import Tracer
from uipath.core.tracing import UiPathTracingManager
from uipath.runtime.base import UiPathBaseRuntime
from uipath.runtime.context import UiPathRuntimeContext
from uipath.runtime.events import UiPathRuntimeEvent
from uipath.runtime.result import UiPathRuntimeResult
from uipath.runtime.tracing import (
UiPathExecutionBatchTraceProcessor,
UiPathExecutionSimpleTraceProcessor,
UiPathRuntimeExecutionSpanExporter,
)
T = TypeVar("T", bound="UiPathBaseRuntime")
class UiPathRuntimeFactory(Generic[T]):
"""Generic factory for UiPath runtime classes."""
def __init__(
self,
runtime_class: Type[T],
runtime_generator: Optional[Callable[[UiPathRuntimeContext], T]] = None,
):
"""Initialize the UiPathRuntimeFactory."""
if not issubclass(runtime_class, UiPathBaseRuntime):
raise TypeError(
f"runtime_class {runtime_class.__name__} must inherit from UiPathBaseRuntime"
)
self.runtime_class = runtime_class
self.runtime_generator = runtime_generator
def new_runtime(self, **kwargs) -> T:
"""Create a new runtime instance."""
context = UiPathRuntimeContext(**kwargs)
return self.from_context(context)
def from_context(self, context: UiPathRuntimeContext) -> T:
"""Create runtime instance from context."""
if self.runtime_generator:
return self.runtime_generator(context)
return self.runtime_class(context)
class UiPathRuntimeExecutor:
"""Handles runtime execution with tracing/telemetry."""
def __init__(self):
"""Initialize the executor."""
self.tracer_provider: TracerProvider = TracerProvider()
trace.set_tracer_provider(self.tracer_provider)
self.tracer_span_processors: List[SpanProcessor] = []
self.execution_span_exporter = UiPathRuntimeExecutionSpanExporter()
self.add_span_exporter(self.execution_span_exporter)
def add_span_exporter(
self,
span_exporter: SpanExporter,
batch: bool = True,
) -> "UiPathRuntimeExecutor":
"""Add a span processor to the tracer provider."""
span_processor: SpanProcessor
if batch:
span_processor = UiPathExecutionBatchTraceProcessor(span_exporter)
else:
span_processor = UiPathExecutionSimpleTraceProcessor(span_exporter)
self.tracer_span_processors.append(span_processor)
self.tracer_provider.add_span_processor(span_processor)
return self
def add_instrumentor(
self,
instrumentor_class: Type[BaseInstrumentor],
get_current_span_func: Callable[[], Any],
) -> "UiPathRuntimeExecutor":
"""Add and instrument immediately."""
instrumentor_class().instrument(tracer_provider=self.tracer_provider)
UiPathTracingManager.register_current_span_provider(get_current_span_func)
return self
async def execute(self, runtime: UiPathBaseRuntime) -> UiPathRuntimeResult:
"""Execute runtime with context."""
try:
return await runtime.execute()
finally:
self._flush_spans()
async def stream(
self, runtime: UiPathBaseRuntime
) -> AsyncGenerator[UiPathRuntimeEvent, None]:
"""Stream runtime execution with context.
Args:
runtime: The runtime instance
context: The runtime context
Yields:
UiPathRuntimeEvent instances during execution and final UiPathRuntimeResult
Raises:
UiPathRuntimeStreamNotSupportedError: If the runtime doesn't support streaming
"""
try:
async for event in runtime.stream():
yield event
finally:
self._flush_spans()
async def execute_in_root_span(
self,
runtime: UiPathBaseRuntime,
root_span: str = "root",
attributes: Optional[dict[str, str]] = None,
) -> UiPathRuntimeResult:
"""Execute runtime with context in a root span."""
try:
tracer: Tracer = trace.get_tracer("uipath-runtime")
span_attributes = {}
if runtime.context.execution_id:
span_attributes["execution.id"] = runtime.context.execution_id
if attributes:
span_attributes.update(attributes)
with tracer.start_as_current_span(
root_span,
attributes=span_attributes,
):
return await runtime.execute()
finally:
self._flush_spans()
async def stream_in_root_span(
self,
runtime: UiPathBaseRuntime,
root_span: str = "root",
attributes: Optional[dict[str, str]] = None,
) -> AsyncGenerator[UiPathRuntimeEvent, None]:
"""Stream runtime execution with context in a root span.
Args:
runtime: The runtime instance
context: The runtime context
root_span: Name of the root span
attributes: Optional attributes to add to the span
Yields:
UiPathRuntimeEvent instances during execution and final UiPathRuntimeResult
Raises:
UiPathRuntimeStreamNotSupportedError: If the runtime doesn't support streaming
"""
try:
tracer: Tracer = trace.get_tracer("uipath-runtime")
span_attributes = {}
if runtime.context.execution_id:
span_attributes["execution.id"] = runtime.context.execution_id
if attributes:
span_attributes.update(attributes)
with tracer.start_as_current_span(
root_span,
attributes=span_attributes,
):
async for event in runtime.stream():
yield event
finally:
self._flush_spans()
def get_execution_spans(
self,
execution_id: str,
) -> List[ReadableSpan]:
"""Retrieve spans for a given execution id."""
return self.execution_span_exporter.get_spans(execution_id)
def _flush_spans(self) -> None:
"""Flush all span processors."""
for span_processor in self.tracer_span_processors:
span_processor.force_flush()