libp2p.tools.anyio_service package
Submodules
libp2p.tools.anyio_service.api module
Public Service API layer with decorators and helper functions.
- class libp2p.tools.anyio_service.api.InternalManagerAPI
Bases:
ManagerAPIInternal interface for service managers with task scheduling capabilities.
This extends ManagerAPI with methods that should only be used internally by the service implementation, not by external callers.
- abstract run_child_service(service: ServiceAPI, daemon: bool = False, name: str | None = None) ManagerAPI
Run a child service in the background.
- abstract run_daemon_child_service(service: ServiceAPI, name: str | None = None) ManagerAPI
Run a daemon child service.
- class libp2p.tools.anyio_service.api.ManagerAPI
Bases:
ABCExternal interface for service managers.
- class libp2p.tools.anyio_service.api.Service
Bases:
ServiceAPIAnyIO-based service implementation.
- get_manager() ManagerAPI
External access to the manager.
- property manager: InternalManagerAPI
Internal access to the manager (for subclasses).
- class libp2p.tools.anyio_service.api.ServiceAPI
Bases:
ABCAbstract base class for services.
- abstract get_manager() ManagerAPI
Get the manager for this service.
- libp2p.tools.anyio_service.api.as_service(service_fn: Callable[[...], Awaitable[Any]]) type[ServiceAPI]
Convert a simple async function into a Service class.
- libp2p.tools.anyio_service.api.external_api(func: TFunc) TFunc
Decorator to protect external API methods.
MEDIUM COMPLEXITY: Ensures methods can only be called while service is running. Uses AnyIO streams and task groups to race the API call against service shutdown.
libp2p.tools.anyio_service.context module
Context managers and aliases for running services.
- class libp2p.tools.anyio_service.context.AnyIOManager(service: ServiceAPI, max_children_per_task: int = 1000, logger: logging.Logger | None = None)
Bases:
InternalManagerAPIAnyIO-based service manager with full lifecycle management.
Implements proper lifecycle with locks, stats tracking, dual nursery architecture, task hierarchy, and ordered cancellation.
- cancel() None
Cancel the service (non-blocking).
HIGH COMPLEXITY: Enhanced validation and state management.
- async run() None
Main run loop with proper lifecycle management.
HIGH COMPLEXITY: - Lock-based lifecycle protection - Dual nursery architecture (system + task) - Cancellation handler - Error collection and propagation - Proper cleanup on exit
- run_child_service(service: ServiceAPI, daemon: bool = False, name: str | None = None) ManagerAPI
Run a child service.
HIGH COMPLEXITY: - Creates ChildServiceTask with full lifecycle - Finds parent using anyio.get_current_task() - Adds to task hierarchy - Returns child manager for external control
- run_daemon_child_service(service: ServiceAPI, name: str | None = None) ManagerAPI
Run a daemon child service.
- run_daemon_task(async_fn: AsyncFn, *args: Any, name: str | None = None) None
Run a daemon task (expected to run indefinitely).
- async classmethod run_service(service: ServiceAPI) None
Class method to run a service.
- run_task(async_fn: AsyncFn, *args: Any, daemon: bool = False, name: str | None = None, _internal: bool = False) None
Run a task in the background.
HIGH COMPLEXITY: - Creates FunctionTask with full lifecycle - Finds parent using anyio.get_current_task() - Adds to task hierarchy - Schedules for execution
- class libp2p.tools.anyio_service.context.TrioManager(service: ServiceAPI, max_children_per_task: int = 1000, logger: logging.Logger | None = None)
Bases:
InternalManagerAPITrio-based service manager with full lifecycle management.
Implements proper lifecycle with locks, stats tracking, dual nursery architecture, task hierarchy, and ordered cancellation.
- cancel() None
Cancel the service (non-blocking).
HIGH COMPLEXITY: Enhanced validation and state management.
- async run() None
Main run loop with proper lifecycle management.
HIGH COMPLEXITY: - Lock-based lifecycle protection - Dual nursery architecture (system + task) - Cancellation handler - Error collection and propagation - Proper cleanup on exit
- run_child_service(service: ServiceAPI, daemon: bool = False, name: str | None = None) ManagerAPI
Run a child service.
HIGH COMPLEXITY: - Creates ChildServiceTask with full lifecycle - Finds parent using trio.lowlevel.current_task() - Adds to task hierarchy - Returns child manager for external control
- run_daemon_child_service(service: ServiceAPI, name: str | None = None) ManagerAPI
Run a daemon child service.
- run_daemon_task(async_fn: AsyncFn, *args: Any, name: str | None = None) None
Run a daemon task (expected to run indefinitely).
- async classmethod run_service(service: ServiceAPI) None
Class method to run a service.
- run_task(async_fn: AsyncFn, *args: Any, daemon: bool = False, name: str | None = None, _internal: bool = False) None
Run a task in the background.
HIGH COMPLEXITY: - Creates FunctionTask with full lifecycle - Finds parent using trio.lowlevel.current_task() - Adds to task hierarchy - Schedules for execution
- libp2p.tools.anyio_service.context.background_anyio_service(service: ServiceAPI) AsyncIterator[ManagerAPI]
Run a service in the background using AnyIO’s structured concurrency.
The service is running within the context block and will be properly cleaned up upon exiting the context block.
This uses AnyIO and can work with either Trio or asyncio backends.
- libp2p.tools.anyio_service.context.background_trio_service(service: ServiceAPI) AsyncIterator[ManagerAPI]
Run a service in the background using Trio’s structured concurrency.
The service is running within the context block and will be properly cleaned up upon exiting the context block.
Note: This uses TrioManager with pure Trio primitives for compatibility with existing Trio-based services (Swarm, PubSub, KadDHT, etc.).
libp2p.tools.anyio_service.exceptions module
Exceptions used by the AnyIO‐based service framework.
- exception libp2p.tools.anyio_service.exceptions.DaemonTaskExit
Bases:
ServiceExceptionException raised when a daemon task exits unexpectedly
- exception libp2p.tools.anyio_service.exceptions.LifecycleError
Bases:
ServiceExceptionError raised when service operations are performed outside of service lifecycle.
- exception libp2p.tools.anyio_service.exceptions.ServiceException
Bases:
ExceptionBase class for Service exceptions
- exception libp2p.tools.anyio_service.exceptions.TooManyChildrenException
Bases:
ServiceExceptionRaised when too many child tasks are spawned
libp2p.tools.anyio_service.manager module
Service manager implementation with lifecycle management.
- class libp2p.tools.anyio_service.manager.AnyIOManager(service: ServiceAPI, max_children_per_task: int = 1000, logger: logging.Logger | None = None)
Bases:
InternalManagerAPIAnyIO-based service manager with full lifecycle management.
Implements proper lifecycle with locks, stats tracking, dual nursery architecture, task hierarchy, and ordered cancellation.
- cancel() None
Cancel the service (non-blocking).
HIGH COMPLEXITY: Enhanced validation and state management.
- async run() None
Main run loop with proper lifecycle management.
HIGH COMPLEXITY: - Lock-based lifecycle protection - Dual nursery architecture (system + task) - Cancellation handler - Error collection and propagation - Proper cleanup on exit
- run_child_service(service: ServiceAPI, daemon: bool = False, name: str | None = None) ManagerAPI
Run a child service.
HIGH COMPLEXITY: - Creates ChildServiceTask with full lifecycle - Finds parent using anyio.get_current_task() - Adds to task hierarchy - Returns child manager for external control
- run_daemon_child_service(service: ServiceAPI, name: str | None = None) ManagerAPI
Run a daemon child service.
- run_daemon_task(async_fn: AsyncFn, *args: Any, name: str | None = None) None
Run a daemon task (expected to run indefinitely).
- async classmethod run_service(service: ServiceAPI) None
Class method to run a service.
- run_task(async_fn: AsyncFn, *args: Any, daemon: bool = False, name: str | None = None, _internal: bool = False) None
Run a task in the background.
HIGH COMPLEXITY: - Creates FunctionTask with full lifecycle - Finds parent using anyio.get_current_task() - Adds to task hierarchy - Schedules for execution
libp2p.tools.anyio_service.stats module
Lightweight statistics dataclasses used by the service framework.
- class libp2p.tools.anyio_service.stats.Stats(tasks: TaskStats)
Bases:
NamedTupleOverall service statistics.
- class libp2p.tools.anyio_service.stats.TaskStats(total_count: int, finished_count: int)
Bases:
NamedTupleStatistics for task execution.
libp2p.tools.anyio_service.tasks module
Task abstractions for the AnyIO service framework.
- class libp2p.tools.anyio_service.tasks.BaseTask(name: str, daemon: bool, parent: TaskWithChildrenAPI | None)
Bases:
TaskAPIBase task implementation with common functionality.
- class libp2p.tools.anyio_service.tasks.BaseTaskWithChildren(name: str, daemon: bool, parent: TaskWithChildrenAPI | None, max_children: int = 1000)
Bases:
BaseTask,TaskWithChildrenAPIBase task that can manage child tasks.
- class libp2p.tools.anyio_service.tasks.ChildServiceTask(name: str, daemon: bool, parent: TaskWithChildrenAPI | None, child_service: ServiceAPI)
Bases:
BaseTaskTask that wraps a child service.
HIGH COMPLEXITY: - Creates a manager for the child service - Integrates with task hierarchy - Proper lifecycle management
- class libp2p.tools.anyio_service.tasks.FunctionTask(name: str, daemon: bool, parent: TaskWithChildrenAPI | None, async_fn: Any, async_fn_args: Sequence[Any], count_in_stats: bool = True, max_children: int = 1000)
Bases:
BaseTaskWithChildrenTask that wraps an async function with full lifecycle management.
HIGH COMPLEXITY: - Tracks the anyio task for parent finding - Has its own cancel scope for ordered cancellation - Waits for children before completing (if not daemon) - Manages lifecycle with events
- property anyio_task: TaskInfo
- async cancel() None
Cancel this task and all children.
HIGH COMPLEXITY: Ordered cancellation (children first)
- property count_in_stats: bool
Return whether this task should be included in user-facing statistics.
- classmethod iterate_tasks(*tasks: TaskAPI) Iterable[FunctionTask]
Iterate over all FunctionTask instances and their children recursively.
- class libp2p.tools.anyio_service.tasks.TaskAPI
Bases:
HashableAbstract base class for tasks in the service framework.
- parent: TaskWithChildrenAPI | None
libp2p.tools.anyio_service.utils module
Utility helpers for the AnyIO service implementation.
Module contents
AnyIO-based service framework (modularized).
This package provides a production-ready service implementation using AnyIO for structured concurrency and cross-platform async compatibility (asyncio + trio).
The implementation is split across multiple modules for clarity: - exceptions: Service-specific exception types - stats: Lightweight statistics dataclasses - utils: Helper functions - tasks: Task abstractions and implementations - manager: AnyIOManager with full lifecycle management - api: Service APIs, decorators, and base classes - context: Context managers for running services
- class libp2p.tools.anyio_service.AnyIOManager(service: ServiceAPI, max_children_per_task: int = 1000, logger: logging.Logger | None = None)
Bases:
InternalManagerAPIAnyIO-based service manager with full lifecycle management.
Implements proper lifecycle with locks, stats tracking, dual nursery architecture, task hierarchy, and ordered cancellation.
- cancel() None
Cancel the service (non-blocking).
HIGH COMPLEXITY: Enhanced validation and state management.
- async run() None
Main run loop with proper lifecycle management.
HIGH COMPLEXITY: - Lock-based lifecycle protection - Dual nursery architecture (system + task) - Cancellation handler - Error collection and propagation - Proper cleanup on exit
- run_child_service(service: ServiceAPI, daemon: bool = False, name: str | None = None) ManagerAPI
Run a child service.
HIGH COMPLEXITY: - Creates ChildServiceTask with full lifecycle - Finds parent using anyio.get_current_task() - Adds to task hierarchy - Returns child manager for external control
- run_daemon_child_service(service: ServiceAPI, name: str | None = None) ManagerAPI
Run a daemon child service.
- run_daemon_task(async_fn: AsyncFn, *args: Any, name: str | None = None) None
Run a daemon task (expected to run indefinitely).
- async classmethod run_service(service: ServiceAPI) None
Class method to run a service.
- run_task(async_fn: AsyncFn, *args: Any, daemon: bool = False, name: str | None = None, _internal: bool = False) None
Run a task in the background.
HIGH COMPLEXITY: - Creates FunctionTask with full lifecycle - Finds parent using anyio.get_current_task() - Adds to task hierarchy - Schedules for execution
- exception libp2p.tools.anyio_service.DaemonTaskExit
Bases:
ServiceExceptionException raised when a daemon task exits unexpectedly
- exception libp2p.tools.anyio_service.LifecycleError
Bases:
ServiceExceptionError raised when service operations are performed outside of service lifecycle.
- class libp2p.tools.anyio_service.Service
Bases:
ServiceAPIAnyIO-based service implementation.
- get_manager() ManagerAPI
External access to the manager.
- property manager: InternalManagerAPI
Internal access to the manager (for subclasses).
- exception libp2p.tools.anyio_service.ServiceException
Bases:
ExceptionBase class for Service exceptions
- class libp2p.tools.anyio_service.Stats(tasks: TaskStats)
Bases:
NamedTupleOverall service statistics.
- class libp2p.tools.anyio_service.TaskStats(total_count: int, finished_count: int)
Bases:
NamedTupleStatistics for task execution.
- class libp2p.tools.anyio_service.TaskType(value)
-
Task type identifiers for internal framework tasks.
Using an enum ensures no collision with user task names and provides a single source of truth for internal task naming.
- INTERNAL_SERVICE_RUN = '_internal:service.run'
- USER = 'user'
- exception libp2p.tools.anyio_service.TooManyChildrenException
Bases:
ServiceExceptionRaised when too many child tasks are spawned
- libp2p.tools.anyio_service.as_service(service_fn: Callable[[...], Awaitable[Any]]) type[ServiceAPI]
Convert a simple async function into a Service class.
- libp2p.tools.anyio_service.background_anyio_service(service: ServiceAPI) AsyncIterator[ManagerAPI]
Run a service in the background using AnyIO’s structured concurrency.
The service is running within the context block and will be properly cleaned up upon exiting the context block.
This uses AnyIO and can work with either Trio or asyncio backends.
- libp2p.tools.anyio_service.background_trio_service(service: ServiceAPI) AsyncIterator[ManagerAPI]
Run a service in the background using Trio’s structured concurrency.
The service is running within the context block and will be properly cleaned up upon exiting the context block.
Note: This uses TrioManager with pure Trio primitives for compatibility with existing Trio-based services (Swarm, PubSub, KadDHT, etc.).
- libp2p.tools.anyio_service.external_api(func: TFunc) TFunc
Decorator to protect external API methods.
MEDIUM COMPLEXITY: Ensures methods can only be called while service is running. Uses AnyIO streams and task groups to race the API call against service shutdown.