"""
This type stub file was generated by pyright.
"""

import asyncio
import contextvars
import logging
import threading
import temporalio.common
import temporalio.converter
from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Callable, Iterator, List, Mapping, MutableMapping, NoReturn, Optional, Sequence, Tuple, Type, Union, overload
from .types import CallableType

"""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.
"""
@overload
def defn(fn: CallableType) -> CallableType:
    ...

@overload
def defn(*, name: Optional[str] = ..., no_thread_cancel_exception: bool = ...) -> Callable[[CallableType], CallableType]:
    ...

@overload
def defn(*, no_thread_cancel_exception: bool = ..., dynamic: bool = ...) -> Callable[[CallableType], CallableType]:
    ...

def defn(fn: Optional[CallableType] = ..., *, name: Optional[str] = ..., no_thread_cancel_exception: bool = ..., dynamic: bool = ...): # -> CallableType@defn | ((fn: CallableType@defn) -> CallableType@defn):
    """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.
    """
    ...

@dataclass(frozen=True)
class Info:
    """Information about the running activity.

    Retrieved inside an activity via :py:func:`info`.
    """
    activity_id: str
    activity_type: str
    attempt: int
    current_attempt_scheduled_time: datetime
    heartbeat_details: Sequence[Any]
    heartbeat_timeout: Optional[timedelta]
    is_local: bool
    schedule_to_close_timeout: Optional[timedelta]
    scheduled_time: datetime
    start_to_close_timeout: Optional[timedelta]
    started_time: datetime
    task_queue: str
    task_token: bytes
    workflow_id: str
    workflow_namespace: str
    workflow_run_id: str
    workflow_type: str
    ...


_current_context: contextvars.ContextVar[_Context] = ...
@dataclass
class _Context:
    info: Callable[[], Info]
    heartbeat: Optional[Callable[..., None]]
    cancelled_event: _CompositeEvent
    worker_shutdown_event: _CompositeEvent
    shield_thread_cancel_exception: Optional[Callable[[], AbstractContextManager]]
    payload_converter_class_or_instance: Union[Type[temporalio.converter.PayloadConverter], temporalio.converter.PayloadConverter,]
    runtime_metric_meter: Optional[temporalio.common.MetricMeter]
    _logger_details: Optional[Mapping[str, Any]] = ...
    _payload_converter: Optional[temporalio.converter.PayloadConverter] = ...
    _metric_meter: Optional[temporalio.common.MetricMeter] = ...
    @staticmethod
    def current() -> _Context:
        ...
    
    @staticmethod
    def set(context: _Context) -> contextvars.Token:
        ...
    
    @staticmethod
    def reset(token: contextvars.Token) -> None:
        ...
    
    @property
    def logger_details(self) -> Mapping[str, Any]:
        ...
    
    @property
    def payload_converter(self) -> temporalio.converter.PayloadConverter:
        ...
    
    @property
    def metric_meter(self) -> temporalio.common.MetricMeter:
        ...
    


@dataclass
class _CompositeEvent:
    thread_event: Optional[threading.Event]
    async_event: Optional[asyncio.Event]
    def set(self) -> None:
        ...
    
    def is_set(self) -> bool:
        ...
    
    async def wait(self) -> None:
        ...
    
    def wait_sync(self, timeout: Optional[float] = ...) -> None:
        ...
    


def in_activity() -> bool:
    """Whether the current code is inside an activity.

    Returns:
        True if in an activity, False otherwise.
    """
    ...

def info() -> Info:
    """Current activity's info.

    Returns:
        Info for the currently running activity.

    Raises:
        RuntimeError: When not in an activity.
    """
    ...

def heartbeat(*details: Any) -> None:
    """Send a heartbeat for the current activity.

    Raises:
        RuntimeError: When not in an activity.
    """
    ...

def is_cancelled() -> bool:
    """Whether 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.
    """
    ...

@contextmanager
def shield_thread_cancel_exception() -> Iterator[None]:
    """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.
    """
    ...

async def wait_for_cancelled() -> None:
    """Asynchronously wait for this activity to get a cancellation request.

    Raises:
        RuntimeError: When not in an async activity.
    """
    ...

def wait_for_cancelled_sync(timeout: Optional[Union[timedelta, float]] = ...) -> None:
    """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.
    """
    ...

def is_worker_shutdown() -> bool:
    """Whether 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.
    """
    ...

async def wait_for_worker_shutdown() -> None:
    """Asynchronously wait for shutdown to be called on the worker.

    Raises:
        RuntimeError: When not in an async activity.
    """
    ...

def wait_for_worker_shutdown_sync(timeout: Optional[Union[timedelta, float]] = ...) -> None:
    """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.
    """
    ...

def raise_complete_async() -> NoReturn:
    """Raise an error that says the activity will be completed
    asynchronously.
    """
    ...

class _CompleteAsyncError(BaseException):
    ...


def payload_converter() -> temporalio.converter.PayloadConverter:
    """Get the payload converter for the current activity.

    This is often used for dynamic activities to convert payloads.
    """
    ...

def metric_meter() -> temporalio.common.MetricMeter:
    """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.
    """
    ...

class LoggerAdapter(logging.LoggerAdapter):
    """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 an ``activity_info`` value
            will be added to the ``extra`` dictionary, making it present on the
            ``LogRecord.__dict__`` for use by others.
    """
    def __init__(self, logger: logging.Logger, extra: Optional[Mapping[str, Any]]) -> None:
        """Create the logger adapter."""
        ...
    
    def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]:
        """Override to add activity details."""
        ...
    
    @property
    def base_logger(self) -> logging.Logger:
        """Underlying logger usable for actions such as adding
        handlers/formatters.
        """
        ...
    


logger = ...
@dataclass(frozen=True)
class _Definition:
    name: Optional[str]
    fn: Callable
    is_async: bool
    no_thread_cancel_exception: bool
    arg_types: Optional[List[Type]] = ...
    ret_type: Optional[Type] = ...
    @staticmethod
    def from_callable(fn: Callable) -> Optional[_Definition]:
        ...
    
    @staticmethod
    def must_from_callable(fn: Callable) -> _Definition:
        ...
    
    def __post_init__(self) -> None:
        ...
    


