o
    iS                     @  s  U d Z ddl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	m
Z
mZ ddlmZ ddlmZ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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$m%Z% erydd
l&m'Z' ed\ddZ(edddd]ddZ(edddd^ddZ(	d_ddddd`ddZ(eddG d d! d!Z)e*d"Z+d#e,d$< eG d%d& d&Z-eddG d'd( d(Z.eG d)d* d*Z/eG d+d, d,Z0dad.d/Z1dbd0d1Z2dcd2d3Z3ddd5d6Z4ded:d;Z5dbd<d=Z6edfd?d@Z7dgdAdBZ8d_dhdEdFZ9dbdGdHZ:dgdIdJZ;	d_dhdKdLZ<didNdOZ=G dPdQ dQe>Z?djdSdTZ@dkdVdWZAG dXdY dYejBZBeBeCeDdZE	 eddG dZd[ d[ZFdS )la  Functions that can be called inside of activities.

Most of these functions use :py:mod:`contextvars` to obtain the current activity
in context. This is already set before the start of the activity. Activities
that make calls that do not automatically propagate the context, such as calls
in another thread, should not use the calls herein unless the context is
explicitly propagated.
    )annotationsN)AbstractContextManagercontextmanager)	dataclass)datetime	timedelta)TYPE_CHECKINGAnyCallableIteratorListMappingMutableMappingNoReturnOptionalSequenceTupleTypeUnionoverload   )CallableType)Clientfnr   returnc                 C     d S N r   r   r   Y/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/temporalio/activity.pydefn2   s   r    Fnameno_thread_cancel_exceptionr"   Optional[str]r#   bool&Callable[[CallableType], CallableType]c                 C  r   r   r   r!   r   r   r   r    6      r#   dynamicr)   c                 C  r   r   r   r(   r   r   r   r    <   r'   )r"   r#   r)   Optional[CallableType]c                  s&   d fdd}| dur|| S |S )ae  Decorator for activity functions.

    Activities can be async or non-async.

    Args:
        fn: The function to decorate.
        name: Name to use for the activity. Defaults to function ``__name__``.
            This cannot be set if dynamic is set.
        no_thread_cancel_exception: If set to true, an exception will not be
            raised in synchronous, threaded activities upon cancellation.
        dynamic: If true, this activity will be dynamic. Dynamic activities have
            to accept a single 'Sequence[RawValue]' parameter. This cannot be
            set to true if name is present.
    r   r   r   c                   s"   t j|  s
p	| jnd d | S )N)activity_namer#   )_Definition_apply_to_callable__name__r   r)   r"   r#   r   r   	decoratorX   s    zdefn.<locals>.decoratorNr   r   r   r   r   )r   r"   r#   r)   r0   r   r/   r   r    B   s   	T)frozenc                   @  s   e Zd ZU dZ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ed< 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ed< ded< 	 d#d d!Zd"S )$InfozcInformation about the running activity.

    Retrieved inside an activity via :py:func:`info`.
    stractivity_idactivity_typeintattemptr   current_attempt_scheduled_timezSequence[Any]heartbeat_detailszOptional[timedelta]heartbeat_timeoutr%   is_localschedule_to_close_timeoutscheduled_timestart_to_close_timeoutstarted_time
task_queuebytes
task_tokenworkflow_idworkflow_namespaceworkflow_run_idworkflow_typeztemporalio.common.Prioritypriorityz'Optional[temporalio.common.RetryPolicy]retry_policyr   Mapping[str, Any]c              	   C  s&   | j | j| j| j| j| j| j| jdS )N)r5   r6   r8   	namespacerA   rD   rF   rG   )r5   r6   r8   rE   rA   rD   rF   rG   selfr   r   r   _logger_details   s   zInfo._logger_detailsNr   rJ   )r.   
__module____qualname____doc____annotations__rN   r   r   r   r   r3   f   s.   
 r3   activityz contextvars.ContextVar[_Context]_current_contextc                   @  s   e Zd ZU dZded< dS )"_ActivityCancellationDetailsHolderN%Optional[ActivityCancellationDetails]details)r.   rP   rQ   rX   rS   r   r   r   r   rV      s   
 rV   c                   @  sh   e Zd ZU dZdZded< dZded< dZded< dZded< dZ	ded< dZ
ded	< edddZdS )ActivityCancellationDetailszsProvides the reasons for the activity's cancellation. Cancellation details are set once and do not change once set.Fr%   	not_foundcancel_requestedpausedreset	timed_outworker_shutdownprotoAtemporalio.bridge.proto.activity_task.ActivityCancellationDetailsr   c                 C  s    t | j| j| j| j| j| jdS )N)rZ   r[   r\   r^   r_   r]   )rY   is_not_foundis_cancelled	is_pausedis_timed_outis_worker_shutdownis_reset)r`   r   r   r   _from_proto   s   z'ActivityCancellationDetails._from_protoN)r`   ra   r   rY   )r.   rP   rQ   rR   rZ   rS   r[   r\   r]   r^   r_   staticmethodrh   r   r   r   r   rY      s   
 rY   c                   @  s   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ed< dZded< dZded< dZded< ed,ddZed-ddZ	ed.d!d"Z
ed/d$d%Zed0d'd(Zed1d*d+ZdS )2_ContextzCallable[[], Info]infozOptional[Callable[..., None]]	heartbeat_CompositeEventcancelled_eventworker_shutdown_eventz.Optional[Callable[[], AbstractContextManager]]shield_thread_cancel_exceptionzYUnion[Type[temporalio.converter.PayloadConverter], temporalio.converter.PayloadConverter]#payload_converter_class_or_instancez'Optional[temporalio.common.MetricMeter]runtime_metric_meterzOptional[Client]clientrV   cancellation_detailsNOptional[Mapping[str, Any]]rN   z/Optional[temporalio.converter.PayloadConverter]_payload_converter_metric_meterr   c                  C  s   t d } | std| S )NzNot in activity context)rU   getRuntimeErrorcontextr   r   r   current   s   
z_Context.currentr{   contextvars.Tokenc                 C  s
   t | S r   )rU   setrz   r   r   r   r~      s   
z_Context.settokenNonec                 C  s   t |  d S r   )rU   r]   )r   r   r   r   r]      s   z_Context.resetrJ   c                 C  s   | j d u r|    | _ | j S r   )rN   rk   rL   r   r   r   logger_details   s   
z_Context.logger_details%temporalio.converter.PayloadConverterc                 C  s4   | j st| jtjjr| j| _ | j S |  | _ | j S r   )rv   
isinstancerq   
temporalio	converterPayloadConverterrL   r   r   r   payload_converter   s   
z_Context.payload_convertertemporalio.common.MetricMeterc                 C  s>   | j std| js|  }| j |j|j|jd| _| jS )NzMMetrics meter not available in non-threaded sync activities like mulitprocess)rK   rA   r6   )rr   ry   rw   rk   with_additional_attributesrE   rA   r6   )rM   rk   r   r   r   metric_meter   s   z_Context.metric_meter)r   rj   )r{   rj   r   r}   )r   r}   r   r   rO   r   r   r   r   )r.   rP   rQ   rS   rN   rv   rw   ri   r|   r~   r]   propertyr   r   r   r   r   r   r   rj      s2   
 rj   c                   @  sH   e Zd ZU ded< ded< dddZdd
dZdddZddddZdS )rm   zOptional[threading.Event]thread_eventzOptional[asyncio.Event]async_eventr   r   c                 C  s0   | j std| j   | jr| j  d S d S NzMissing event)r   ry   r~   r   rL   r   r   r   r~   	  s   
z_CompositeEvent.setr%   c                 C  s   | j std| j  S r   )r   ry   is_setrL   r   r   r   r     s   
z_CompositeEvent.is_setc                   s$   | j std| j  I d H  d S )Nznot in async activity)r   ry   waitrL   r   r   r   r     s   z_CompositeEvent.waitNtimeoutOptional[float]c                 C  s   | j std| j | d S r   )r   ry   r   )rM   r   r   r   r   	wait_sync  s   z_CompositeEvent.wait_syncr   r   r   r%   r   )r   r   r   r   )r.   rP   rQ   rS   r~   r   r   r   r   r   r   r   rm     s   
 


rm   r   c                  C  s   t  j} | std| S )a  Return a Temporal Client for use in the current activity.

    The client is only available in `async def` activities.

    In tests it is not available automatically, but you can pass a client when creating a
    :py:class:`temporalio.testing.ActivityEnvironment`.

    Returns:
        :py:class:`temporalio.client.Client` for use in the current activity.

    Raises:
        RuntimeError: When the client is not available.
    zNo client available. The client is only available in `async def` activities; not in `def` activities. In tests you can pass a client when creating ActivityEnvironment.)rj   r|   rs   ry   )rs   r   r   r   rs      s   
rs   c                   C  s   t dduS )zsWhether the current code is inside an activity.

    Returns:
        True if in an activity, False otherwise.
    N)rU   rx   r   r   r   r   in_activity8  s   r   c                   C  s   t   S )zCurrent activity's info.

    Returns:
        Info for the currently running activity.

    Raises:
        RuntimeError: When not in an activity.
    )rj   r|   rk   r   r   r   r   rk   A  s   	rk   rW   c                   C  s   t  jjS )zcCancellation details of the current activity, if any. Once set, cancellation details do not change.)rj   r|   rt   rX   r   r   r   r   rt   M  s   rt   rX   r	   r   c                  G  s"   t  j}|std||   dS )zkSend a heartbeat for the current activity.

    Raises:
        RuntimeError: When not in an activity.
    z1Can only execute heartbeat after interceptor initN)rj   r|   rl   ry   )rX   heartbeat_fnr   r   r   rl   R  s   
rl   c                   C     t  j S )zWhether a cancellation was ever requested on this activity.

    Returns:
        True if the activity has had a cancellation request, False otherwise.

    Raises:
        RuntimeError: When not in an activity.
    )rj   r|   rn   r   r   r   r   r   rc   ^     	rc   Iterator[None]c                  c  sL    t  j} | sdV  dS |   dV  W d   dS 1 sw   Y  dS )a  Context manager for synchronous multithreaded activities to delay
    cancellation exceptions.

    By default, synchronous multithreaded activities have an exception thrown
    inside when cancellation occurs. Code within a "with" block of this context
    manager will delay that throwing until the end. Even if the block returns a
    value or throws its own exception, if a cancellation exception is pending,
    it is thrown instead. Therefore users are encouraged to not throw out of
    this block and can surround this with a try/except if they wish to catch a
    cancellation.

    This properly supports nested calls and will only throw after the last one.

    This just runs the blocks with no extra effects for async activities or
    synchronous multiprocess/other activities.

    Raises:
        temporalio.exceptions.CancelledError: If a cancellation occurs anytime
            during this block and this is not nested in another shield block.
    N)rj   r|   rp   )shield_contextr   r   r   rp   j  s   

"rp   c                        t  j I dH  dS )zAsynchronously wait for this activity to get a cancellation request.

    Raises:
        RuntimeError: When not in an async activity.
    N)rj   r|   rn   r   r   r   r   r   wait_for_cancelled     r   r   !Optional[Union[timedelta, float]]c                 C  ,   t  jt| tr|   dS |  dS )a'  Synchronously block while waiting for a cancellation request on this
    activity.

    This is essentially a wrapper around :py:meth:`threading.Event.wait`.

    Args:
        timeout: Max amount of time to wait for cancellation.

    Raises:
        RuntimeError: When not in an activity.
    N)rj   r|   rn   r   r   r   total_secondsr   r   r   r   wait_for_cancelled_sync  s
   
r   c                   C  r   )zWhether shutdown has been invoked on the worker.

    Returns:
        True if shutdown has been called on the worker, False otherwise.

    Raises:
        RuntimeError: When not in an activity.
    )rj   r|   ro   r   r   r   r   r   rf     r   rf   c                     r   )zAsynchronously wait for shutdown to be called on the worker.

    Raises:
        RuntimeError: When not in an async activity.
    N)rj   r|   ro   r   r   r   r   r   wait_for_worker_shutdown  r   r   c                 C  r   )aF  Synchronously block while waiting for shutdown to be called on the
    worker.

    This is essentially a wrapper around :py:meth:`threading.Event.wait`.

    Args:
        timeout: Max amount of time to wait for shutdown to be called on the
            worker.

    Raises:
        RuntimeError: When not in an activity.
    N)rj   r|   ro   r   r   r   r   r   r   r   r   wait_for_worker_shutdown_sync  s
   
r   r   c                   C  s   t  )zPRaise an error that says the activity will be completed
    asynchronously.
    )_CompleteAsyncErrorr   r   r   r   raise_complete_async  s   r   c                   @  s   e Zd ZdS )r   N)r.   rP   rQ   r   r   r   r   r     s    r   r   c                   C  
   t  jS )zGet the payload converter for the current activity.

    The returned converter has :py:class:`temporalio.converter.ActivitySerializationContext` set.
    This is often used for dynamic activities to convert payloads.
    )rj   r|   r   r   r   r   r   r     s   
r   r   c                   C  r   )a  Get the metric meter for the current activity.

    .. warning::
        This is only available in async or synchronous threaded activities. An
        error is raised on non-thread-based sync activities when trying to
        access this.

    Returns:
        Current metric meter for this activity for recording metrics.

    Raises:
        RuntimeError: When not in an activity or in a non-thread-based
            synchronous activity.
    )rj   r|   r   r   r   r   r   r     s   
r   c                      s:   e Zd ZdZd fdd	ZdddZedddZ  ZS )LoggerAdaptera=  Adapter that adds details to the log about the running activity.

    Attributes:
        activity_info_on_message: Boolean for whether a string representation of
            a dict of some activity info will be appended to each message.
            Default is True.
        activity_info_on_extra: Boolean for whether a ``temporal_activity``
            dictionary value will be added to the ``extra`` dictionary with some
            activity info, making it present on the ``LogRecord.__dict__`` for
            use by others. Default is True.
        full_activity_info_on_extra: Boolean for whether an ``activity_info``
            value will be added to the ``extra`` dictionary with the entire
            activity info, making it present on the ``LogRecord.__dict__`` for
            use by others. Default is False.
    loggerlogging.Loggerextraru   r   r   c                   s(   t  ||pi  d| _d| _d| _dS )zCreate the logger adapter.TFN)super__init__activity_info_on_messageactivity_info_on_extrafull_activity_info_on_extra)rM   r   r   	__class__r   r   r     s   
zLoggerAdapter.__init__msgr	   kwargsMutableMapping[str, Any]$Tuple[Any, MutableMapping[str, Any]]c                 C  s   | j s	| js	| jrEtd}|rE| j r| d|j d}| jr0|ddp&i }|j|d< ||d< | jrE|ddp:i }| |d< ||d< ||fS )z!Override to add activity details.Nz ()r   temporal_activityactivity_info)r   r   r   rU   rx   r   rk   )rM   r   r   r{   r   r   r   r   process  s&   

zLoggerAdapter.processc                 C  s   | j S )zYUnderlying logger usable for actions such as adding
        handlers/formatters.
        )r   rL   r   r   r   base_logger$  s   zLoggerAdapter.base_logger)r   r   r   ru   r   r   )r   r	   r   r   r   r   )r   r   )	r.   rP   rQ   rR   r   r   r   r   __classcell__r   r   r   r   r     s    
	r   c                   @  s   e Zd ZU ded< ded< ded< ded< dZd	ed
< dZded< edddZedddZedddddZ	dddZ
dS )r,   r$   r"   r
   r   r%   is_asyncr#   NzOptional[List[Type]]	arg_typeszOptional[Type]ret_typer   Optional[_Definition]c                 C  s(   t | dd }t|trtj|| d}|S )N__temporal_activity_definitionr   )getattrr   r,   dataclassesreplace)r   r    r   r   r   from_callable:  s   
z_Definition.from_callablec                 C  s.   t | }|r	|S t| dd}td| d)Nr.   z	<unknown>z	Activity z: missing attributes, was it decorated with @activity.defn?)r,   r   r   	TypeError)r   retfn_namer   r   r   must_from_callableE  s   

z_Definition.must_from_callableF)r#   r+   r   c             	   C  s   t | dr	tdt| stdt| }|j D ]}|jtj	j
kr(tdqt| dt|| t| p9t| j|d d S )Nr   z-Function already contains activity definitionzActivity is not callablez+Activity cannot have keyword-only arguments)r"   r   r   r#   )hasattr
ValueErrorcallabler   inspect	signature
parametersvalueskind	ParameterKEYWORD_ONLYsetattrr,   iscoroutinefunction__call__)r   r+   r#   sigparamr   r   r   r-   O  s(   



z_Definition._apply_to_callablec                 C  s   | j d u r@| jd u rB| jd u }tj| j\}}|r0|r,t|dks,|d ttjj	 kr0t
dt| d| t| d| d S d S d S )Nr   r   zJDynamic activity must accept a single Sequence[temporalio.common.RawValue]r   r   )r   r   r"   r   common_type_hints_from_funcr   lenr   RawValuer   object__setattr__)rM   r)   r   r   r   r   r   __post_init__p  s   
z_Definition.__post_init__)r   r
   r   r   )r   r
   r   r,   )r   r
   r+   r$   r#   r%   r   r   r   )r.   rP   rQ   rS   r   r   ri   r   r   r-   r   r   r   r   r   r,   0  s   
 
	 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   r3   )r   rW   )rX   r	   r   r   )r   r   r   )r   r   r   r   )r   r   r   r   )GrR   
__future__r   asynciocontextvarsr   r   logging	threading
contextlibr   r   r   r   r   typingr   r	   r
   r   r   r   r   r   r   r   r   r   r   r   temporalio.bridger   temporalio.bridge.proto%temporalio.bridge.proto.activity_tasktemporalio.commontemporalio.convertertypesr   temporalio.clientr   r    r3   
ContextVarrU   rS   rV   rY   rj   rm   rs   r   rk   rt   rl   rc   rp   r   r   rf   r   r   r   BaseExceptionr   r   r   r   	getLoggerr.   r   r,   r   r   r   r   <module>   s    	@$.K


	



	





	;