Skip to content

task

Class info

Classes

Name Children Inherits
RpcTask
aclientp.task
An incoming request or notification waiting to be handled.

    Re-exported classes

    Class Module Description
    DebugEntry aclientp.task.debug Structured debug entry for ACP message tracking.
    DebuggingMessageStateStore aclientp.task.debug Enhanced message state store with structured debugging output.
    DefaultMessageDispatcher aclientp.task.dispatcher Background worker that consumes RPC tasks from a broker.
    InMemoryMessageQueue aclientp.task.queue Simple in-memory broker for RPC task dispatch.
    InMemoryMessageStateStore aclientp.task.state In-memory implementation of MessageStateStore.
    MessageDispatcher aclientp.task.dispatcher Protocol for message dispatchers.
    MessageQueue aclientp.task.queue Protocol for message queues used in RPC task dispatch.
    MessageSender aclientp.task.sender Serialize JSON-RPC messages as NDJSON frames onto a byte stream.
    MessageStateStore aclientp.task.state Protocol for managing message states.
    TaskSupervisor aclientp.task.supervisor Track background tasks and provide graceful shutdown semantics.

    🛈 DocStrings

    Task package.

    RequestRunner module-attribute

    RequestRunner = Callable[['RpcTask'], Awaitable[dict[str, Any]]]
    

    Handles a request and returns the JSON-RPC response payload that was sent.

    DebugEntry dataclass

    Structured debug entry for ACP message tracking.

    Source code in src/aclientp/task/debug.py
    @dataclass(kw_only=True)
    class DebugEntry:
        """Structured debug entry for ACP message tracking."""
    
        timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
        direction: Literal["outgoing", "incoming"]
        event: Literal["register", "resolve", "reject", "begin", "complete", "fail"]
        request_id: int | None
        method: str
        params: Any = None
        result: Any = None
        error: str | None = None
        status: Literal["pending", "completed", "failed"] | None = None
        duration_ms: float | None = None
    

    DebuggingMessageStateStore

    Bases: InMemoryMessageStateStore

    Enhanced message state store with structured debugging output.

    Provides much richer debugging information than raw JSON logging: - Request/response correlation - Timing information - Status tracking - Structured data output - Error details

    Source code in src/aclientp/task/debug.py
    class DebuggingMessageStateStore(InMemoryMessageStateStore):
        """Enhanced message state store with structured debugging output.
    
        Provides much richer debugging information than raw JSON logging:
        - Request/response correlation
        - Timing information
        - Status tracking
        - Structured data output
        - Error details
        """
    
        def __init__(self, debug_file: str | Path | None = None) -> None:
            super().__init__()
            self._debug_file = Path(debug_file) if debug_file else None
            self._request_start_times: dict[int, datetime] = {}
    
        def register_outgoing(self, request_id: int, method: str) -> asyncio.Future[Any]:
            """Register outgoing request with debug logging."""
            future = super().register_outgoing(request_id, method)
            # Track start time for duration calculation
            self._request_start_times[request_id] = datetime.now()
            entry = DebugEntry(
                direction="outgoing",
                event="register",
                request_id=request_id,
                method=method,
            )
            self._log_debug(entry)
            return future
    
        def resolve_outgoing(self, request_id: int, result: Any) -> None:
            """Resolve outgoing request with debug logging."""
            duration = self._calculate_duration(request_id)
            super().resolve_outgoing(request_id, result)
            entry = DebugEntry(
                direction="outgoing",
                event="resolve",
                request_id=request_id,
                method=self._get_method_for_request(request_id),
                result=result,
                duration_ms=duration,
            )
            self._log_debug(entry)
            self._cleanup_request_timing(request_id)
    
        def reject_outgoing(self, request_id: int, error: RequestError) -> None:
            """Reject outgoing request with debug logging."""
            duration = self._calculate_duration(request_id)
            super().reject_outgoing(request_id, error)
            entry = DebugEntry(
                direction="outgoing",
                event="reject",
                request_id=request_id,
                method=self._get_method_for_request(request_id),
                error=str(error),
                duration_ms=duration,
            )
            self._log_debug(entry)
            self._cleanup_request_timing(request_id)
    
        def reject_all_outgoing(self, error: BaseException) -> None:
            """Reject all outgoing requests with debug logging."""
            # Log for each pending request
            for request_id in list(self._outgoing.keys()):
                duration = self._calculate_duration(request_id)
                entry = DebugEntry(
                    direction="outgoing",
                    event="reject",
                    request_id=request_id,
                    method=self._get_method_for_request(request_id),
                    error=f"Connection error: {error}",
                    duration_ms=duration,
                )
                self._log_debug(entry)
    
            super().reject_all_outgoing(error)
            self._request_start_times.clear()
    
        def begin_incoming(self, method: str, params: Any) -> IncomingMessage:
            """Begin processing incoming request with debug logging."""
            record = super().begin_incoming(method, params)
            entry = DebugEntry(
                direction="incoming",
                event="begin",
                request_id=None,
                method=method,
                params=params,
                status="pending",
            )
            self._log_debug(entry)
            return record
    
        def complete_incoming(self, record: IncomingMessage, result: Any) -> None:
            """Complete incoming request with debug logging."""
            super().complete_incoming(record, result)
            entry = DebugEntry(
                direction="incoming",
                event="complete",
                request_id=None,
                method=record.method,
                result=result,
                status="completed",
            )
            self._log_debug(entry)
    
        def fail_incoming(self, record: IncomingMessage, error: Exception) -> None:
            """Fail incoming request with debug logging."""
            super().fail_incoming(record, error)
            entry = DebugEntry(
                direction="incoming",
                event="fail",
                request_id=None,
                method=record.method,
                error=str(error),
                status="failed",
            )
            self._log_debug(entry)
    
        def _log_debug(self, entry: DebugEntry) -> None:
            """Write debug entry to file if configured."""
            if not self._debug_file:
                return
            # Convert to dict and filter out None values for cleaner output
            data = {k: v for k, v in asdict(entry).items() if v is not None}
            try:
                # Write as JSONL (one JSON object per line)
                with self._debug_file.open("a", encoding="utf-8") as f:
                    f.write(anyenv.dump_json(data) + "\n")
            except Exception:
                # Don't let debug logging break the connection
                logger.exception("Failed to write debug entry")
    
        def _calculate_duration(self, request_id: int) -> float | None:
            """Calculate request duration in milliseconds."""
            if start_time := self._request_start_times.get(request_id):
                return (datetime.now() - start_time).total_seconds() * 1000
            return None
    
        def _cleanup_request_timing(self, request_id: int) -> None:
            """Clean up timing tracking for completed request."""
            self._request_start_times.pop(request_id, None)
    
        def _get_method_for_request(self, request_id: int) -> str:
            """Get method name for outgoing request."""
            record = self._outgoing.get(request_id)
            return record.method if record else "unknown"
    

    begin_incoming

    begin_incoming(method: str, params: Any) -> IncomingMessage
    

    Begin processing incoming request with debug logging.

    Source code in src/aclientp/task/debug.py
    def begin_incoming(self, method: str, params: Any) -> IncomingMessage:
        """Begin processing incoming request with debug logging."""
        record = super().begin_incoming(method, params)
        entry = DebugEntry(
            direction="incoming",
            event="begin",
            request_id=None,
            method=method,
            params=params,
            status="pending",
        )
        self._log_debug(entry)
        return record
    

    complete_incoming

    complete_incoming(record: IncomingMessage, result: Any) -> None
    

    Complete incoming request with debug logging.

    Source code in src/aclientp/task/debug.py
    def complete_incoming(self, record: IncomingMessage, result: Any) -> None:
        """Complete incoming request with debug logging."""
        super().complete_incoming(record, result)
        entry = DebugEntry(
            direction="incoming",
            event="complete",
            request_id=None,
            method=record.method,
            result=result,
            status="completed",
        )
        self._log_debug(entry)
    

    fail_incoming

    fail_incoming(record: IncomingMessage, error: Exception) -> None
    

    Fail incoming request with debug logging.

    Source code in src/aclientp/task/debug.py
    def fail_incoming(self, record: IncomingMessage, error: Exception) -> None:
        """Fail incoming request with debug logging."""
        super().fail_incoming(record, error)
        entry = DebugEntry(
            direction="incoming",
            event="fail",
            request_id=None,
            method=record.method,
            error=str(error),
            status="failed",
        )
        self._log_debug(entry)
    

    register_outgoing

    register_outgoing(request_id: int, method: str) -> Future[Any]
    

    Register outgoing request with debug logging.

    Source code in src/aclientp/task/debug.py
    def register_outgoing(self, request_id: int, method: str) -> asyncio.Future[Any]:
        """Register outgoing request with debug logging."""
        future = super().register_outgoing(request_id, method)
        # Track start time for duration calculation
        self._request_start_times[request_id] = datetime.now()
        entry = DebugEntry(
            direction="outgoing",
            event="register",
            request_id=request_id,
            method=method,
        )
        self._log_debug(entry)
        return future
    

    reject_all_outgoing

    reject_all_outgoing(error: BaseException) -> None
    

    Reject all outgoing requests with debug logging.

    Source code in src/aclientp/task/debug.py
    def reject_all_outgoing(self, error: BaseException) -> None:
        """Reject all outgoing requests with debug logging."""
        # Log for each pending request
        for request_id in list(self._outgoing.keys()):
            duration = self._calculate_duration(request_id)
            entry = DebugEntry(
                direction="outgoing",
                event="reject",
                request_id=request_id,
                method=self._get_method_for_request(request_id),
                error=f"Connection error: {error}",
                duration_ms=duration,
            )
            self._log_debug(entry)
    
        super().reject_all_outgoing(error)
        self._request_start_times.clear()
    

    reject_outgoing

    reject_outgoing(request_id: int, error: RequestError) -> None
    

    Reject outgoing request with debug logging.

    Source code in src/aclientp/task/debug.py
    def reject_outgoing(self, request_id: int, error: RequestError) -> None:
        """Reject outgoing request with debug logging."""
        duration = self._calculate_duration(request_id)
        super().reject_outgoing(request_id, error)
        entry = DebugEntry(
            direction="outgoing",
            event="reject",
            request_id=request_id,
            method=self._get_method_for_request(request_id),
            error=str(error),
            duration_ms=duration,
        )
        self._log_debug(entry)
        self._cleanup_request_timing(request_id)
    

    resolve_outgoing

    resolve_outgoing(request_id: int, result: Any) -> None
    

    Resolve outgoing request with debug logging.

    Source code in src/aclientp/task/debug.py
    def resolve_outgoing(self, request_id: int, result: Any) -> None:
        """Resolve outgoing request with debug logging."""
        duration = self._calculate_duration(request_id)
        super().resolve_outgoing(request_id, result)
        entry = DebugEntry(
            direction="outgoing",
            event="resolve",
            request_id=request_id,
            method=self._get_method_for_request(request_id),
            result=result,
            duration_ms=duration,
        )
        self._log_debug(entry)
        self._cleanup_request_timing(request_id)
    

    DefaultMessageDispatcher dataclass

    Bases: MessageDispatcher

    Background worker that consumes RPC tasks from a broker.

    Every message is handled in its own task, so a slow handler never blocks the others; tasks are started in the order the messages were received.

    Source code in src/aclientp/task/dispatcher.py
    @dataclass(kw_only=True)
    class DefaultMessageDispatcher(MessageDispatcher):
        """Background worker that consumes RPC tasks from a broker.
    
        Every message is handled in its own task, so a slow handler never blocks the
        others; tasks are started in the order the messages were received.
        """
    
        supervisor: TaskSupervisor
        request_runner: RequestRunner
        notification_runner: NotificationRunner
        queue: MessageQueue = field(default_factory=InMemoryMessageQueue)
        store: MessageStateStore = field(default_factory=InMemoryMessageStateStore)
    
        def __post_init__(self) -> None:
            self._task: asyncio.Task[None] | None = None
    
        def start(self) -> None:
            if self._task is not None:
                raise RuntimeError("dispatcher already started")
            self._task = self.supervisor.create(self._run(), name="acp.Dispatcher.loop")
    
        async def _run(self) -> None:
            try:
                async for task in self.queue:
                    try:
                        if self.supervisor.closed:
                            continue  # Connection is shutting down, drain without handling
                        if task.kind == "request":
                            self._dispatch_request(task)
                        else:
                            self._dispatch_notification(task)
                    finally:
                        self.queue.task_done()
            except asyncio.CancelledError:
                return
    
        async def stop(self) -> None:
            await self.queue.close()
            if self._task is not None:
                with suppress(asyncio.CancelledError):
                    await self._task
                self._task = None
    
        def _dispatch_request(self, task: RpcTask) -> None:
            msg = task.message
            record = self.store.begin_incoming(msg.get("method", ""), msg.get("params"))
    
            async def runner() -> None:
                response = await self.request_runner(task)
                if "error" in response:
                    self.store.fail_incoming(record, RequestError.from_error_obj(response["error"]))
                else:
                    self.store.complete_incoming(record, response.get("result"))
    
            self.supervisor.create(runner(), name="acp.Dispatcher.request")
    
        def _dispatch_notification(self, task: RpcTask) -> None:
            async def runner() -> None:
                await self.notification_runner(task)
    
            self.supervisor.create(runner(), name="acp.Dispatcher.notification")
    

    InMemoryMessageQueue

    Simple in-memory broker for RPC task dispatch.

    Source code in src/aclientp/task/queue.py
    class InMemoryMessageQueue:
        """Simple in-memory broker for RPC task dispatch."""
    
        def __init__(self, *, maxsize: int = 0) -> None:
            self._queue: asyncio.Queue[RpcTask | None] = asyncio.Queue(maxsize=maxsize)
            self._closed = False
    
        async def publish(self, task: RpcTask) -> None:
            if self._closed:
                raise RuntimeError("mssage queue already closed")
            await self._queue.put(task)
    
        async def close(self) -> None:
            if self._closed:
                return
            self._closed = True
            await self._queue.put(None)
    
        async def join(self) -> None:
            await self._queue.join()
    
        def task_done(self) -> None:
            with suppress(ValueError):
                self._queue.task_done()
    
        def __aiter__(self) -> AsyncIterator[RpcTask]:
            return _QueueIterator(self)
    

    InMemoryMessageStateStore

    Bases: MessageStateStore

    In-memory implementation of MessageStateStore.

    Source code in src/aclientp/task/state.py
    class InMemoryMessageStateStore(MessageStateStore):
        """In-memory implementation of MessageStateStore."""
    
        def __init__(self) -> None:
            self._outgoing: dict[int, OutgoingMessage] = {}
            self._incoming: list[IncomingMessage] = []
    
        def register_outgoing(self, request_id: int, method: str) -> asyncio.Future[Any]:
            future: asyncio.Future[Any] = asyncio.get_running_loop().create_future()
            self._outgoing[request_id] = OutgoingMessage(request_id, method, future)
            return future
    
        def resolve_outgoing(self, request_id: int, result: Any) -> None:
            record = self._outgoing.pop(request_id, None)
            if record and not record.future.done():
                record.future.set_result(result)
    
        def reject_outgoing(self, request_id: int, error: RequestError) -> None:
            record = self._outgoing.pop(request_id, None)
            if record and not record.future.done():
                record.future.set_exception(error)
    
        def reject_all_outgoing(self, error: BaseException) -> None:
            for record in self._outgoing.values():
                if not record.future.done():
                    record.future.set_exception(error)
            self._outgoing.clear()
    
        def begin_incoming(self, method: str, params: Any) -> IncomingMessage:
            record = IncomingMessage(method=method, params=params)
            self._incoming.append(record)
            return record
    
        def complete_incoming(self, record: IncomingMessage, result: Any) -> None:
            record.status = "completed"
            record.result = result
    
        def fail_incoming(self, record: IncomingMessage, error: Exception) -> None:
            record.status = "failed"
            record.error = error
    

    MessageDispatcher

    Bases: Protocol

    Protocol for message dispatchers.

    Source code in src/aclientp/task/dispatcher.py
    class MessageDispatcher(Protocol):
        """Protocol for message dispatchers."""
    
        def __init__(
            self,
            *,
            queue: MessageQueue,
            supervisor: TaskSupervisor,
            store: MessageStateStore,
            request_runner: RequestRunner,
            notification_runner: NotificationRunner,
        ) -> None: ...
    
        def start(self) -> None: ...
    
        async def stop(self) -> None: ...
    

    MessageQueue

    Bases: Protocol

    Protocol for message queues used in RPC task dispatch.

    Source code in src/aclientp/task/queue.py
    class MessageQueue(Protocol):
        """Protocol for message queues used in RPC task dispatch."""
    
        async def publish(self, task: RpcTask) -> None: ...
    
        async def close(self) -> None: ...
    
        def task_done(self) -> None: ...
    
        async def join(self) -> None: ...
    
        def __aiter__(self) -> AsyncIterator[RpcTask]: ...
    

    MessageSender

    Serialize JSON-RPC messages as NDJSON frames onto a byte stream.

    Frames are written by a single writer task, in the order they were enqueued. Writing outside the caller's task keeps frames intact: cancelling a caller can never leave a half-written frame on the stream (anyio byte streams may write in several steps).

    Once the stream fails or the sender is closed, every queued and every later send fails with :class:ConnectionError instead of waiting forever.

    Source code in src/aclientp/task/sender.py
    class MessageSender:
        """Serialize JSON-RPC messages as NDJSON frames onto a byte stream.
    
        Frames are written by a single writer task, in the order they were enqueued. Writing
        outside the caller's task keeps frames intact: cancelling a caller can never leave a
        half-written frame on the stream (anyio byte streams may write in several steps).
    
        Once the stream fails or the sender is closed, every queued and every later send
        fails with :class:`ConnectionError` instead of waiting forever.
        """
    
        def __init__(
            self,
            writer: ByteSendStream,
            supervisor: TaskSupervisor,
            *,
            flush_timeout: float = 5.0,
        ) -> None:
            """Start the writer task.
    
            Args:
                writer: Byte stream the frames are written to.
                supervisor: Supervisor owning the writer task.
                flush_timeout: How long ``close()`` waits for queued frames to be written.
            """
            self._writer = writer
            self._flush_timeout = flush_timeout
            self._queue: asyncio.Queue[_PendingSend | None] = asyncio.Queue()
            self._closed = False
            self._failure: ConnectionError | None = None
            self._task = supervisor.create(self._loop(), name="acp.Sender.loop")
    
        @property
        def closed(self) -> bool:
            """Whether the sender stopped accepting messages."""
            return self._closed
    
        def send_nowait(self, payload: dict[str, Any]) -> asyncio.Future[None]:
            """Enqueue a message without waiting for it to be written.
    
            The message is committed to the stream as soon as this returns, so it is written
            even if the caller is cancelled right after (it is flushed by ``close()`` too).
    
            Returns:
                A future that completes once the frame was written, or fails with
                ``ConnectionError`` if it could not be.
    
            Raises:
                ConnectionError: The sender is closed or the stream failed earlier.
                TypeError: The payload is not JSON-serializable.
            """
            if self._closed:
                raise ConnectionError("Sender closed") from self._failure
            data = self._encode(payload)
            future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
            self._queue.put_nowait(_PendingSend(data, future))
            return future
    
        async def send(self, payload: dict[str, Any]) -> None:
            """Write a message and wait until it is on the stream.
    
            Raises:
                ConnectionError: The sender is closed or the stream failed.
                TypeError: The payload is not JSON-serializable.
            """
            await self.send_nowait(payload)
    
        async def close(self) -> None:
            """Stop accepting messages and flush the ones already queued.
    
            Queued frames get up to ``flush_timeout`` seconds to be written; whatever is
            still pending afterwards fails with ``ConnectionError``.
            """
            if self._closed:
                return
            self._closed = True
            self._queue.put_nowait(None)
            await asyncio.wait({self._task}, timeout=self._flush_timeout)
            if not self._task.done():
                self._task.cancel()
                await asyncio.wait({self._task})
    
        def _encode(self, payload: dict[str, Any]) -> bytes:
            try:
                return (anyenv.dump_json(payload) + "\n").encode()
            except TypeError:
                offenders = "\n".join(
                    f"  {path}: {type(value).__name__} = {value!r:.200s}"
                    for path, value in _find_non_serializable(payload)
                )
                logger.exception(
                    "Failed to JSON-serialize message payload",
                    non_serializable=offenders,
                    payload=repr(payload)[:2000],
                )
                raise
    
        async def _loop(self) -> None:
            current: _PendingSend | None = None
            try:
                while (current := await self._queue.get()) is not None:
                    try:
                        await self._writer.send(current.payload)
                    except Exception as exc:
                        error = ConnectionError(f"Failed to write message: {exc!r}")
                        error.__cause__ = exc
                        self._failure = error
                        logger.debug("Writing to the stream failed", exc_info=exc)
                        return
                    if not current.future.done():
                        current.future.set_result(None)
            finally:
                # Reached on stream failure, on close() and when the writer task is cancelled.
                self._closed = True
                error = self._failure or ConnectionError("Sender closed")
                if current is not None and not current.future.done():
                    current.future.set_exception(error)
                while not self._queue.empty():
                    item = self._queue.get_nowait()
                    if item is not None and not item.future.done():
                        item.future.set_exception(error)
    

    closed property

    closed: bool
    

    Whether the sender stopped accepting messages.

    __init__

    __init__(writer: ByteSendStream, supervisor: TaskSupervisor, *, flush_timeout: float = 5.0) -> None
    

    Start the writer task.

    Parameters:

    Name Type Description Default
    writer ByteSendStream

    Byte stream the frames are written to.

    required
    supervisor TaskSupervisor

    Supervisor owning the writer task.

    required
    flush_timeout float

    How long close() waits for queued frames to be written.

    5.0
    Source code in src/aclientp/task/sender.py
    def __init__(
        self,
        writer: ByteSendStream,
        supervisor: TaskSupervisor,
        *,
        flush_timeout: float = 5.0,
    ) -> None:
        """Start the writer task.
    
        Args:
            writer: Byte stream the frames are written to.
            supervisor: Supervisor owning the writer task.
            flush_timeout: How long ``close()`` waits for queued frames to be written.
        """
        self._writer = writer
        self._flush_timeout = flush_timeout
        self._queue: asyncio.Queue[_PendingSend | None] = asyncio.Queue()
        self._closed = False
        self._failure: ConnectionError | None = None
        self._task = supervisor.create(self._loop(), name="acp.Sender.loop")
    

    close async

    close() -> None
    

    Stop accepting messages and flush the ones already queued.

    Queued frames get up to flush_timeout seconds to be written; whatever is still pending afterwards fails with ConnectionError.

    Source code in src/aclientp/task/sender.py
    async def close(self) -> None:
        """Stop accepting messages and flush the ones already queued.
    
        Queued frames get up to ``flush_timeout`` seconds to be written; whatever is
        still pending afterwards fails with ``ConnectionError``.
        """
        if self._closed:
            return
        self._closed = True
        self._queue.put_nowait(None)
        await asyncio.wait({self._task}, timeout=self._flush_timeout)
        if not self._task.done():
            self._task.cancel()
            await asyncio.wait({self._task})
    

    send async

    send(payload: dict[str, Any]) -> None
    

    Write a message and wait until it is on the stream.

    Raises:

    Type Description
    ConnectionError

    The sender is closed or the stream failed.

    TypeError

    The payload is not JSON-serializable.

    Source code in src/aclientp/task/sender.py
    async def send(self, payload: dict[str, Any]) -> None:
        """Write a message and wait until it is on the stream.
    
        Raises:
            ConnectionError: The sender is closed or the stream failed.
            TypeError: The payload is not JSON-serializable.
        """
        await self.send_nowait(payload)
    

    send_nowait

    send_nowait(payload: dict[str, Any]) -> Future[None]
    

    Enqueue a message without waiting for it to be written.

    The message is committed to the stream as soon as this returns, so it is written even if the caller is cancelled right after (it is flushed by close() too).

    Returns:

    Type Description
    Future[None]

    A future that completes once the frame was written, or fails with

    Future[None]

    ConnectionError if it could not be.

    Raises:

    Type Description
    ConnectionError

    The sender is closed or the stream failed earlier.

    TypeError

    The payload is not JSON-serializable.

    Source code in src/aclientp/task/sender.py
    def send_nowait(self, payload: dict[str, Any]) -> asyncio.Future[None]:
        """Enqueue a message without waiting for it to be written.
    
        The message is committed to the stream as soon as this returns, so it is written
        even if the caller is cancelled right after (it is flushed by ``close()`` too).
    
        Returns:
            A future that completes once the frame was written, or fails with
            ``ConnectionError`` if it could not be.
    
        Raises:
            ConnectionError: The sender is closed or the stream failed earlier.
            TypeError: The payload is not JSON-serializable.
        """
        if self._closed:
            raise ConnectionError("Sender closed") from self._failure
        data = self._encode(payload)
        future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
        self._queue.put_nowait(_PendingSend(data, future))
        return future
    

    MessageStateStore

    Bases: Protocol

    Protocol for managing message states.

    Source code in src/aclientp/task/state.py
    class MessageStateStore(Protocol):
        """Protocol for managing message states."""
    
        def register_outgoing(self, request_id: int, method: str) -> asyncio.Future[Any]: ...
    
        def resolve_outgoing(self, request_id: int, result: Any) -> None: ...
    
        def reject_outgoing(self, request_id: int, error: RequestError) -> None: ...
    
        def reject_all_outgoing(self, error: BaseException) -> None: ...
    
        def begin_incoming(self, method: str, params: Any) -> IncomingMessage: ...
    
        def complete_incoming(self, record: IncomingMessage, result: Any) -> None: ...
    
        def fail_incoming(self, record: IncomingMessage, error: Exception) -> None: ...
    

    RpcTask dataclass

    An incoming request or notification waiting to be handled.

    Attributes:

    Name Type Description
    kind RpcTaskKind

    Whether the message is a request or a notification.

    message dict[str, Any]

    The raw JSON-RPC message.

    done Future[None] | None

    Resolved once the message has been handled. Set for notifications, so the connection can wait for notifications received before a given response.

    Source code in src/aclientp/task/__init__.py
    @dataclass(slots=True)
    class RpcTask:
        """An incoming request or notification waiting to be handled.
    
        Attributes:
            kind: Whether the message is a request or a notification.
            message: The raw JSON-RPC message.
            done: Resolved once the message has been handled. Set for notifications, so the
                connection can wait for notifications received before a given response.
        """
    
        kind: RpcTaskKind
        message: dict[str, Any]
        done: asyncio.Future[None] | None = None
    

    TaskSupervisor

    Track background tasks and provide graceful shutdown semantics.

    Inspired by fasta2a's task manager, this supervisor keeps a registry of asyncio tasks created for request handling so they can be cancelled and awaited reliably when the connection closes.

    Source code in src/aclientp/task/supervisor.py
    class TaskSupervisor:
        """Track background tasks and provide graceful shutdown semantics.
    
        Inspired by fasta2a's task manager, this supervisor keeps a registry of
        asyncio tasks created for request handling so they can be cancelled and
        awaited reliably when the connection closes.
        """
    
        def __init__(self, *, source: str, error_handlers: list[ErrorHandler] | None = None) -> None:
            self._source = source
            self._tasks: set[asyncio.Task[Any]] = set()
            self._closed = False
            self._error_handlers = error_handlers or []
    
        @property
        def closed(self) -> bool:
            """Whether the supervisor stopped accepting new tasks."""
            return self._closed
    
        def add_error_handler(self, handler: ErrorHandler) -> None:
            self._error_handlers.append(handler)
    
        def create(
            self,
            coroutine: Coroutine[Any, Any, Any],
            *,
            name: str | None = None,
            on_error: ErrorHandler | None = None,
        ) -> asyncio.Task[Any]:
            if self._closed:
                coroutine.close()  # Avoid a "coroutine was never awaited" warning
                raise RuntimeError(f"TaskSupervisor for {self._source} already closed")
            task = asyncio.create_task(coroutine, name=name)
            self._tasks.add(task)
            task.add_done_callback(lambda t: self._on_done(t, on_error))
            return task
    
        def _on_done(self, task: asyncio.Task[Any], on_error: ErrorHandler | None) -> None:
            self._tasks.discard(task)
            if task.cancelled():
                return
            try:
                task.result()
            except Exception as exc:
                handled = False
                if on_error is not None:
                    try:
                        on_error(task, exc)
                        handled = True
                    except Exception:
                        logger.exception("Error in task-specific error handler", source=self._source)
                if not handled:
                    for handler in self._error_handlers:
                        try:
                            handler(task, exc)
                            handled = True
                        except Exception:
                            logger.exception("Error in supervisor error handler", source=self._source)
                if not handled:
                    logger.exception("Unhandled error in task", source=self._source)
    
        async def shutdown(self) -> None:
            """Cancel all tracked tasks and wait for them to finish.
    
            The calling task is left alone: a handler may close its own connection, and
            cancelling and awaiting itself would end in a self-await cancellation cycle.
            """
            self._closed = True
            current = asyncio.current_task()
            tasks = [task for task in self._tasks if task is not current]
            if not tasks:
                return
            for task in tasks:
                task.cancel()
            # Failures were already routed to the error handlers by `_on_done`.
            await asyncio.gather(*tasks, return_exceptions=True)
            self._tasks.difference_update(tasks)
    

    closed property

    closed: bool
    

    Whether the supervisor stopped accepting new tasks.

    shutdown async

    shutdown() -> None
    

    Cancel all tracked tasks and wait for them to finish.

    The calling task is left alone: a handler may close its own connection, and cancelling and awaiting itself would end in a self-await cancellation cycle.

    Source code in src/aclientp/task/supervisor.py
    async def shutdown(self) -> None:
        """Cancel all tracked tasks and wait for them to finish.
    
        The calling task is left alone: a handler may close its own connection, and
        cancelling and awaiting itself would end in a self-await cancellation cycle.
        """
        self._closed = True
        current = asyncio.current_task()
        tasks = [task for task in self._tasks if task is not current]
        if not tasks:
            return
        for task in tasks:
            task.cancel()
        # Failures were already routed to the error handlers by `_on_done`.
        await asyncio.gather(*tasks, return_exceptions=True)
        self._tasks.difference_update(tasks)