o
    i;y                     @  s  U d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZmZmZmZmZmZ ddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlmZmZ dd	lmZm Z m!Z! ddl"Z#ddl$Z#ddl%Z#ddl&Z#ddl'Z#ddl(Z#ddl)Z#dd
l'm*Z*m+Z+ ej,-  ej.j/0ej1j2j34 ej5j26 gZ7	 e
e8ej.j9j:f Z;de<d< G dd de#j=j>e#j?j>Z@G dd de#j=jAZBG dd de#j?jCZDG dd deZEG dd de!ZFeddG dd dZGej,HdZIG dd de#j?jJZKG dd de#j?jLZMG d d! d!ZNdS )"z8OpenTelemetry interceptor that creates/propagates spans.    )annotations)contextmanager)	dataclass)
AnyCallableDictIteratorMappingNoReturnOptionalSequenceTypecastN)Context)Status
StatusCode)Protocol	TypeAlias	TypedDict)ApplicationErrorApplicationErrorCategoryr   _CarrierDictc                   @  sv   e Zd ZdZ	d2ddd3ddZd4ddZd5ddZd6ddZd7ddZd8ddZ	e
ddd d9d+d,Zd:d0d1ZdS );TracingInterceptora  Interceptor that supports client and worker OpenTelemetry span creation
    and propagation.

    This should be created and used for ``interceptors`` on the
    :py:meth:`temporalio.client.Client.connect` call to apply to all client
    calls and worker calls using that client. To only apply to workers, set as
    worker creation option instead of in client.

    To customize the header key, text map propagator, or payload converter, a
    subclass of this and :py:class:`TracingWorkflowInboundInterceptor` should be
    created. In addition to customizing those attributes, the subclass of this
    class should return the workflow interceptor subclass from
    :py:meth:`workflow_interceptor_class`. That subclass should also set the
    custom attributes desired.
    NF)always_create_workflow_spanstracer$Optional[opentelemetry.trace.Tracer]r   boolreturnNonec                C  s4   |pt jt| _d| _t| _tj	j
j| _|| _dS )a  Initialize a OpenTelemetry tracing interceptor.

        Args:
            tracer: The tracer to use. Defaults to
                :py:func:`opentelemetry.trace.get_tracer`.
            always_create_workflow_spans: When false, the default, spans are
                only created in workflows when an overarching span from the
                client is present. In cases of starting a workflow elsewhere,
                e.g. CLI or schedules, a client-created span is not present and
                workflow spans will not be created. Setting this to true will
                create spans in workflows no matter what, but there is a risk of
                them being orphans since they may not have a parent span after
                replaying.
        _tracer-dataN)opentelemetrytrace
get_tracer__name__r   
header_keydefault_text_map_propagatortext_map_propagator
temporalio	converterPayloadConverterdefaultpayload_converter_always_create_workflow_spans)selfr   r    r.   f/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/temporalio/contrib/opentelemetry.py__init__M   s
   
zTracingInterceptor.__init__next%temporalio.client.OutboundInterceptorc                 C  
   t || S )z]Implementation of
        :py:meth:`temporalio.client.Interceptor.intercept_client`.
        )!_TracingClientOutboundInterceptorr-   r1   r.   r.   r/   intercept_clientl      
z#TracingInterceptor.intercept_client,temporalio.worker.ActivityInboundInterceptorc                 C  r3   )z_Implementation of
        :py:meth:`temporalio.worker.Interceptor.intercept_activity`.
        )"_TracingActivityInboundInterceptorr5   r.   r.   r/   intercept_activityt   r7   z%TracingInterceptor.intercept_activityinput/temporalio.worker.WorkflowInterceptorClassInput'Type[TracingWorkflowInboundInterceptor]c                 C  s   |j d| ji tS )zgImplementation of
        :py:meth:`temporalio.worker.Interceptor.workflow_interceptor_class`.
        '__temporal_opentelemetry_completed_span)unsafe_extern_functionsupdate_completed_workflow_span!TracingWorkflowInboundInterceptorr-   r;   r.   r.   r/   workflow_interceptor_class|   s
   z-TracingInterceptor.workflow_interceptor_classheaders.Mapping[str, temporalio.api.common.v1.Payload]c                 C  s8   i }| j | |ri || j| j|gd i}|S Nr   )r&   injectr$   r+   to_payloadsr-   rE   carrierr.   r.   r/   _context_to_headers   s   z&TracingInterceptor._context_to_headers/Optional[opentelemetry.context.context.Context]c                 C  sH   | j |vrd S || j }|sd S | j|gd }|sd S | j|S rG   )r$   getr+   from_payloadsr&   extract)r-   rE   header_payloadrK   r.   r.   r/   _context_from_headers   s   
z(TracingInterceptor._context_from_headers)r;   contextnamestr
attributes#opentelemetry.util.types.AttributesOptional[_InputWithHeaders]kindopentelemetry.trace.SpanKindrS   Optional[Context]Iterator[None]c          	      c  s   |r	t j|nd }zj| jj||||ddA}|r!| |j|_zd V  W n* tyP } zt|t	r9|j
tjkrK|ttjt|j d| d  d }~ww W d    n1 s[w   Y  W |rr|t j u rtt j| d S d S d S |r|t j u rt j| w w w )NF)rV   rY   rS   set_status_on_exceptionz: )status_codedescription)r    rS   attachr   start_as_current_spanrL   rE   	Exception
isinstancer   categoryr   BENIGN
set_statusr   r   ERRORtyper#   get_currentdetach)	r-   rT   rV   r;   rY   rS   tokenspanexcr.   r.   r/   _start_as_current_span   sH   

z)TracingInterceptor._start_as_current_spanparams_CompletedWorkflowSpanParamsOptional[_CarrierDict]c                 C  s   |j r| jsd S | j|j}g }|jr.tj| j|j}|tjj	ur.tj
| g}| jj|j||j||j|jd}tj||}|jrN||j |j|jd i }| j|| |S )N)rV   links
start_timerY   )end_time)parent_missingr,   r&   rP   rS   link_contextr    r!   get_current_spanINVALID_SPANLinkget_span_contextr   
start_spanrT   rV   time_nsrY   set_span_in_context	exceptionrecord_exceptionendrH   )r-   ro   rS   rr   	link_spanrl   rK   r.   r.   r/   rA      s2   z+TracingInterceptor._completed_workflow_spanN)r   r   r   r   r   r   )r1   r2   r   r2   )r1   r8   r   r8   )r;   r<   r   r=   rE   rF   r   rF   )rE   rF   r   rM   )rT   rU   rV   rW   r;   rX   rY   rZ   rS   r[   r   r\   )ro   rp   r   rq   )r#   
__module____qualname____doc__r0   r6   r:   rD   rL   rR   r   rn   rA   r.   r.   r.   r/   r   <   s     




&r   c                      sd   e Zd Zd fddZd fddZd fddZd fddZd  fddZd! fddZ  Z	S )"r4   r1   r2   rootr   r   r   c                      t  | || _d S r   superr0   r   r-   r1   r   	__class__r.   r/   r0      s   
z*_TracingClientOutboundInterceptor.__init__r;   $temporalio.client.StartWorkflowInput*temporalio.client.WorkflowHandle[Any, Any]c                   sr   |j sdnd}| jj| d|j d|ji|tjjjd t	 
|I d H W  d    S 1 s2w   Y  d S )NStartWorkflowSignalWithStartWorkflow:temporalWorkflowIDrV   r;   rY   )start_signalr   rn   workflowidr    r!   SpanKindCLIENTr   start_workflow)r-   r;   prefixr   r.   r/   r      s   $z0_TracingClientOutboundInterceptor.start_workflow$temporalio.client.QueryWorkflowInputr   c                   `   | j jd|j d|ji|tjjjd t 	|I d H W  d    S 1 s)w   Y  d S )NzQueryWorkflow:r   r   )
r   rn   queryr   r    r!   r   r   r   query_workflowrC   r   r.   r/   r     s   
$z0_TracingClientOutboundInterceptor.query_workflow%temporalio.client.SignalWorkflowInputc                   r   )NzSignalWorkflow:r   r   )
r   rn   signalr   r    r!   r   r   r   signal_workflowrC   r   r.   r/   r        
$z1_TracingClientOutboundInterceptor.signal_workflow*temporalio.client.StartWorkflowUpdateInput+temporalio.client.WorkflowUpdateHandle[Any]c                   r   )NzStartWorkflowUpdate:r   r   )
r   rn   r@   r   r    r!   r   r   r   start_workflow_updaterC   r   r.   r/   r      r   z7_TracingClientOutboundInterceptor.start_workflow_update3temporalio.client.StartWorkflowUpdateWithStartInputc                   s   d|j ji}|jjd ur|jj|d< | jjd|j j ||j tjj	j
d* |j j| jj}|r@i |jj| jj|i|j_t |I d H W  d    S 1 sSw   Y  d S )Nr   temporalUpdateIDzStartUpdateWithStartWorkflow:r   )start_workflow_inputr   update_workflow_input	update_idr   rn   r   r    r!   r   r   rE   rN   r$   r    start_update_with_start_workflow)r-   r;   attrsotel_headerr   r.   r/   r   +  s(   
$zB_TracingClientOutboundInterceptor.start_update_with_start_workflow)r1   r2   r   r   r   r   )r;   r   r   r   )r;   r   r   r   )r;   r   r   r   )r;   r   r   r   )r;   r   r   r   )
r#   r   r   r0   r   r   r   r   r   __classcell__r.   r.   r   r/   r4      s    	r4   c                      s,   e Zd Zd fddZd fddZ  ZS )r9   r1   r8   r   r   r   r   c                   r   r   r   r   r   r.   r/   r0   E     
z+_TracingActivityInboundInterceptor.__init__r;   &temporalio.worker.ExecuteActivityInputr   c                   s|   t j }| jjd|j | j|j|j|j	|j
dtjjjd t |I d H W  d    S 1 s7w   Y  d S )NzRunActivity:)r   temporalRunIDtemporalActivityID)rS   rV   rY   )r'   activityinfor   rn   activity_typerR   rE   workflow_idworkflow_run_idactivity_idr    r!   r   SERVERr   execute_activity)r-   r;   r   r   r.   r/   r   M  s   


$z3_TracingActivityInboundInterceptor.execute_activity)r1   r8   r   r   r   r   )r;   r   r   r   )r#   r   r   r0   r   r   r.   r.   r   r/   r9   D  s    r9   c                   @     e Zd ZU ded< dS )_InputWithHeadersrF   rE   Nr#   r   r   __annotations__r.   r.   r.   r/   r   ^     
 r   c                   @  r   )_WorkflowExternFunctionsz@Callable[[_CompletedWorkflowSpanParams], Optional[_CarrierDict]]?_WorkflowExternFunctions__temporal_opentelemetry_completed_spanNr   r.   r.   r.   r/   r   b  r   r   T)frozenc                   @  sN   e Zd ZU ded< ded< ded< ded< d	ed
< ded< ded< ded< dS )rp   r   rS   rU   rT   rW   rV   intr|   rq   rv   Optional[Exception]r~   rZ   rY   r   ru   Nr   r.   r.   r.   r/   rp   h  s   
 rp   -__temporal_opentelemetry_workflow_interceptorc                      s   e Zd ZdZedDddZdE fd	d
ZdF fddZdG fddZdH fddZ	dI fddZ
dJ fddZdK fddZdLd d!ZedMd%d&ZdNd)d*ZdOd-d.Zd/d/d0d/d/ejjjd1dPd>d?ZdQdBdCZ  ZS )RrB   zTracing interceptor for workflow calls.

    See :py:class:`TracingInterceptor` docs on why one might want to subclass
    this class.
    r   +Optional[TracingWorkflowInboundInterceptor]c                  C  s"   t jt} | rt| tr| S d S r   )r    rS   	get_value_interceptor_context_keyrc   rB   )retr.   r.   r/   _from_context  s   z/TracingWorkflowInboundInterceptor._from_contextr1   ,temporalio.worker.WorkflowInboundInterceptorr   c                   s@   t  | tttj | _d| _t	| _
tjjj| _d| _dS )z*Initialize a tracing workflow interceptor.r   N)r   r0   r   r   r'   r   extern_functions_extern_functionsr$   r%   r&   r(   r)   r*   r+   _workflow_context_carrierr5   r   r.   r/   r0     s   

z*TracingWorkflowInboundInterceptor.__init__outbound-temporalio.worker.WorkflowOutboundInterceptorc                   s   t  t||  dS )z`Implementation of
        :py:meth:`temporalio.worker.WorkflowInboundInterceptor.init`.
        N)r   init#_TracingWorkflowOutboundInterceptor)r-   r   r   r.   r/   r     s   z&TracingWorkflowInboundInterceptor.initr;   &temporalio.worker.ExecuteWorkflowInputr   c                   sf   | j dd" | jdtj j tjjj	d t
 |I dH W  d   S 1 s,w   Y  dS )zlImplementation of
        :py:meth:`temporalio.worker.WorkflowInboundInterceptor.execute_workflow`.
        Tsuccess_is_completezRunWorkflow:)rY   N)_top_level_workflow_context_completed_spanr'   r   r   workflow_typer    r!   r   r   r   execute_workflowrC   r   r.   r/   r     s   $z2TracingWorkflowInboundInterceptor.execute_workflow#temporalio.worker.HandleSignalInputc                   s   |j | j}d}|r| j|gd }| jdd! | jd|j |tj	j
jd t |I dH  W d   dS 1 s?w   Y  dS )ziImplementation of
        :py:meth:`temporalio.worker.WorkflowInboundInterceptor.handle_signal`.
        Nr   Fr   zHandleSignal:link_context_carrierrY   )rE   rN   r$   r+   rO   r   r   r   r    r!   r   r   r   handle_signalr-   r;   link_context_headerr   r   r.   r/   r     s"   
"z/TracingWorkflowInboundInterceptor.handle_signal"temporalio.worker.HandleQueryInputc              	     s   |j | j}d}|r | j|gd }| j|}|  }ntj	
 }| |}tj	|}z(| jd|j |dtjjjd t |I dH W |tj	 u rXtj	| S S |tj	 u rgtj	| w w )zhImplementation of
        :py:meth:`temporalio.worker.WorkflowInboundInterceptor.handle_query`.
        Nr   zHandleQuery:T)r   new_span_even_on_replayrY   )rE   rN   r$   r+   rO   r&   rP   _load_workflow_context_carrierr    rS   r   _set_on_contextr`   r   r   r!   r   r   r   handle_queryri   rj   )r-   r;   context_headerr   context_carrierrS   rk   r   r.   r/   r     s.   



z.TracingWorkflowInboundInterceptor.handle_query#temporalio.worker.HandleUpdateInputc                   s   |j | j}d}|r| j|gd }| jdd | jd|j |tj	j
jd t | W d   dS 1 s;w   Y  dS )zsImplementation of
        :py:meth:`temporalio.worker.WorkflowInboundInterceptor.handle_update_validator`.
        Nr   Fr   zValidateUpdate:r   )rE   rN   r$   r+   rO   r   r   r@   r    r!   r   r   r   handle_update_validatorr   r   r.   r/   r     s    
"z9TracingWorkflowInboundInterceptor.handle_update_validatorc                   s   |j | j}d}|r| j|gd }| jdd  | jd|j |tj	j
jd t |I dH W  d   S 1 s>w   Y  dS )zqImplementation of
        :py:meth:`temporalio.worker.WorkflowInboundInterceptor.handle_update_handler`.
        Nr   Fr   zHandleUpdate:r   )rE   rN   r$   r+   rO   r   r   r@   r    r!   r   r   r   handle_update_handlerr   r   r.   r/   r     s"   
$z7TracingWorkflowInboundInterceptor.handle_update_handlerrq   c                 C  sB   | j r| j S tj j| j}|sd S | j|gd | _ | j S rG   )	r   r'   r   r   rE   rN   r$   r+   rO   )r-   r   r.   r.   r/   r     s   z@TracingWorkflowInboundInterceptor._load_workflow_context_carrierr   r   r\   c                c  s   |   }|r| j|}ntj }| |}d}d }tj|}zCzd V  d}W n tj	j
y; } z|} d }~ww W |sC|rU|rU| jdtj j |tjjjd |tj u rdtj| d S d S |sl|r~|r~| jdtj j |tjjjd |tj u rtj| w w )NFTzCompleteWorkflow:)r~   rY   )r   r&   rP   r    rS   r   r   r`   r'   
exceptionsFailureErrorr   r   r   r   r!   r   INTERNALri   rj   )r-   r   r   rS   successr~   rk   errr.   r.   r/   r     sH   



z=TracingWorkflowInboundInterceptor._top_level_workflow_contextrE   rF   c                 C  s   i }| j | | ||S r   )r&   rH   _context_carrier_to_headersrJ   r.   r.   r/   rL   F  s   z5TracingWorkflowInboundInterceptor._context_to_headersrK   r   c                 C  s(   |ri || j | j|gd i}|S rG   )r$   r+   rI   )r-   rK   rE   r.   r.   r/   r   M  s   z=TracingWorkflowInboundInterceptor._context_carrier_to_headersNF)r   add_to_outboundr   additional_attributesr~   rY   	span_namerU   r   r   rX   r   r   rW   r~   r   rY   rZ   c                C  s   t jj r
|s
d S i }| j| t j }	|	j|	jd}
|r%|
	| | j
d t|||
t j |||tj tjju d}|rN|rP| ||j|_d S d S d S )N)r   r   r>   )rS   rT   rV   r|   rv   r~   rY   ru   )r'   r   unsafeis_replayingr&   rH   r   r   run_idr@   r   rp   r|   r    r!   rw   rx   r   rE   )r-   r   r   r   r   r   r~   rY   new_context_carrierr   rV   updated_context_carrierr.   r.   r/   r   Y  s>   


z1TracingWorkflowInboundInterceptor._completed_spanrS   opentelemetry.context.Contextc                 C  s   t jt| |S r   )r    rS   	set_valuer   )r-   rS   r.   r.   r/   r     s   z1TracingWorkflowInboundInterceptor._set_on_context)r   r   )r1   r   r   r   )r   r   r   r   )r;   r   r   r   )r;   r   r   r   )r;   r   r   r   )r;   r   r   r   )r;   r   r   r   )r   rq   )r   r   r   r\   r   )rK   r   rE   rF   r   rF   )r   rU   r   rq   r   rX   r   r   r   rW   r~   r   rY   rZ   r   r   )rS   r   r   r   )r#   r   r   r   staticmethodr   r0   r   r   r   r   r   r   r   r   r   rL   r   r    r!   r   r   r   r   r   r.   r.   r   r/   rB   y  s0    )

+
1rB   c                      sr   e Zd Zd fddZd  fddZd! fddZd" fddZd# fddZd$ fddZd% fddZ	  Z
S )&r   r1   r   r   rB   r   r   c                   r   r   r   r   r   r.   r/   r0     r   z,_TracingWorkflowOutboundInterceptor.__init__r;   $temporalio.worker.ContinueAsNewInputr
   c                   s    | j |j|_t | d S r   )r   rL   rE   r   continue_as_newrC   r   r.   r/   r     s   z3_TracingWorkflowOutboundInterceptor.continue_as_new*temporalio.worker.SignalChildWorkflowInputc                   8   | j jd|j |tjjjd t |I d H  d S )NzSignalChildWorkflow:r   rY   )	r   r   r   r    r!   r   r   r   signal_child_workflowrC   r   r.   r/   r       
z9_TracingWorkflowOutboundInterceptor.signal_child_workflow-temporalio.worker.SignalExternalWorkflowInputc                   r   )NzSignalExternalWorkflow:r   )	r   r   r   r    r!   r   r   r   signal_external_workflowrC   r   r.   r/   r    r  z<_TracingWorkflowOutboundInterceptor.signal_external_workflow$temporalio.worker.StartActivityInput"temporalio.workflow.ActivityHandlec                   ,   | j jd|j |tjjjd t |S NzStartActivity:r   )	r   r   r   r    r!   r   r   r   start_activityrC   r   r.   r/   r	       
z2_TracingWorkflowOutboundInterceptor.start_activity)temporalio.worker.StartChildWorkflowInput'temporalio.workflow.ChildWorkflowHandlec                   s4   | j jd|j |tjjjd t |I d H S )NzStartChildWorkflow:r   )	r   r   r   r    r!   r   r   r   start_child_workflowrC   r   r.   r/   r    s   
z8_TracingWorkflowOutboundInterceptor.start_child_workflow)temporalio.worker.StartLocalActivityInputc                   r  r  )	r   r   r   r    r!   r   r   r   start_local_activityrC   r   r.   r/   r    r
  z8_TracingWorkflowOutboundInterceptor.start_local_activity)r1   r   r   rB   r   r   )r;   r   r   r
   )r;   r   r   r   )r;   r  r   r   )r;   r  r   r  )r;   r  r   r  )r;   r  r   r  )r#   r   r   r0   r   r  r  r	  r  r  r   r.   r.   r   r/   r     s    r   c                   @  s0   e Zd ZdZdddZeddddddZdS )r   zContains static methods that are safe to call from within a workflow.

    .. warning::
        Using any other ``opentelemetry`` API could cause non-determinism.
    r   r   c                 C  s   t r   )NotImplementedError)r-   r.   r.   r/   r0     s   zworkflow.__init__N)rV   r~   rT   rU   rV   rW   r~   r   c                C  s$   t  }|r|j| ||d dS dS )a  Create and end an OpenTelemetry span.

        Note, this will only create and record when the workflow is not
        replaying and if there is a current span (meaning the client started a
        span and this interceptor is configured on the worker and the span is on
        the context).

        There is currently no way to create a long-running span or to create a
        span that actually spans other code.

        Args:
            name: Name of the span.
            attributes: Attributes to set on the span if any. Workflow ID and
                run ID are automatically added.
            exception: Optional exception to record on the span.
        )r   r~   N)rB   r   r   )rT   rV   r~   interceptorr.   r.   r/   completed_span  s   
zworkflow.completed_span)r   r   )rT   rU   rV   rW   r~   r   r   r   )r#   r   r   r   r0   r   r  r.   r.   r.   r/   r     s    
r   )Or   
__future__r   
contextlibr   dataclassesr   typingr   r   r   r   r	   r
   r   r   r   r   !opentelemetry.baggage.propagationr    opentelemetry.contextopentelemetry.context.context#opentelemetry.propagators.composite!opentelemetry.propagators.textmapopentelemetry.trace,opentelemetry.trace.propagation.tracecontextopentelemetry.util.typesr   r   r   typing_extensionsr   r   r   temporalio.activityr'   temporalio.api.common.v1temporalio.clienttemporalio.convertertemporalio.exceptionstemporalio.workertemporalio.workflowr   r   rS   ri   propagators	compositeCompositePropagatorr!   propagationtracecontextTraceContextTextMapPropagatorbaggageW3CBaggagePropagatorr%   rU   textmapCarrierValTr   r   clientInterceptorworkerr   OutboundInterceptorr4   ActivityInboundInterceptorr9   r   r   rp   
create_keyr   WorkflowInboundInterceptorrB   WorkflowOutboundInterceptorr   r   r.   r.   r.   r/   <module>   sd    0

 <M  
H