acapy_agent.utils package
Subpackages
Submodules
acapy_agent.utils.classloader module
The classloader provides utilities to dynamically load classes and modules.
- class acapy_agent.utils.classloader.ClassLoader[source]
Bases:
objectClass used to load classes from modules dynamically.
- classmethod load_class(class_name: str, default_module: str | None = None, package: str | None = None)[source]
Resolve a complete class path (ie. typing.Dict) to the class itself.
- Parameters:
class_name – the class name
default_module – the default module to load, if not part of in the class name
package – the parent package to search for the module
- Returns:
The resolved class
- Raises:
ClassNotFoundError – If the class could not be resolved at path
ModuleLoadError – If there was an error loading the module
- classmethod load_module(mod_path: str, package: str | None = None) ModuleType | None[source]
Load a module by its absolute path.
- Parameters:
mod_path – the absolute or relative module path
package – the parent package to search for the module
- Returns:
The resolved module or None if the module cannot be found
- Raises:
ModuleLoadError – If there was an error loading the module
- classmethod load_subclass_of(base_class: Type, mod_path: str, package: str | None = None)[source]
Resolve an implementation of a base path within a module.
- Parameters:
base_class – the base class being implemented
mod_path – the absolute module path
package – the parent package to search for the module
- Returns:
The resolved class
- Raises:
ClassNotFoundError – If the module or class implementation could not be found
ModuleLoadError – If there was an error loading the module
- exception acapy_agent.utils.classloader.ClassNotFoundError(*args, error_code: str | None = None, **kwargs)[source]
Bases:
BaseErrorClass not found error.
acapy_agent.utils.dependencies module
Dependency related util methods.
acapy_agent.utils.endorsement_setup module
acapy_agent.utils.env module
Environment utility methods.
acapy_agent.utils.extract_validation_error module
Extract validation error messages from nested exceptions.
acapy_agent.utils.general module
Utility functions for the admin server.
acapy_agent.utils.http module
HTTP utility methods.
- exception acapy_agent.utils.http.FetchError(*args, error_code: str | None = None, **kwargs)[source]
Bases:
BaseErrorError raised when an HTTP fetch fails.
- exception acapy_agent.utils.http.PutError(*args, error_code: str | None = None, **kwargs)[source]
Bases:
BaseErrorError raised when an HTTP put fails.
- async acapy_agent.utils.http.fetch(url: str, *, headers: dict | None = None, retry: bool = True, max_attempts: int = 5, interval: float = 1.0, backoff: float = 0.25, request_timeout: float = 10.0, connector: aiohttp.BaseConnector | None = None, session: aiohttp.ClientSession | None = None, json: bool = False)[source]
Fetch from an HTTP server with automatic retries and timeouts.
- Parameters:
url – the address to fetch
headers – an optional dict of headers to send
retry – flag to retry the fetch
max_attempts – the maximum number of attempts to make
interval – the interval between retries, in seconds
backoff – the backoff interval, in seconds
request_timeout – the HTTP request timeout, in seconds
connector – an optional existing BaseConnector
session – a shared ClientSession
json – flag to parse the result as JSON
- async acapy_agent.utils.http.fetch_stream(url: str, *, headers: dict | None = None, retry: bool = True, max_attempts: int = 5, interval: float = 1.0, backoff: float = 0.25, request_timeout: float = 10.0, connector: aiohttp.BaseConnector | None = None, session: aiohttp.ClientSession | None = None)[source]
Fetch from an HTTP server with automatic retries and timeouts.
- Parameters:
url – the address to fetch
headers – an optional dict of headers to send
retry – flag to retry the fetch
max_attempts – the maximum number of attempts to make
interval – the interval between retries, in seconds
backoff – the backoff interval, in seconds
request_timeout – the HTTP request timeout, in seconds
connector – an optional existing BaseConnector
session – a shared ClientSession
json – flag to parse the result as JSON
- async acapy_agent.utils.http.put_file(url: str, file_data: dict, extra_data: dict, *, retry: bool = True, max_attempts: int = 5, interval: float = 1.0, backoff: float = 0.25, request_timeout: float = 10.0, connector: aiohttp.BaseConnector | None = None, session: aiohttp.ClientSession | None = None, json: bool = False)[source]
Put to HTTP server with automatic retries and timeouts.
- Parameters:
url – the address to use
file_data – dict with data key and path of file to upload
extra_data – further content to include in data to put
headers – an optional dict of headers to send
retry – flag to retry the fetch
max_attempts – the maximum number of attempts to make
interval – the interval between retries, in seconds
backoff – the backoff interval, in seconds
request_timeout – the HTTP request timeout, in seconds
connector – an optional existing BaseConnector
session – a shared ClientSession
json – flag to parse the result as JSON
acapy_agent.utils.jwe module
JSON Web Encryption utilities.
- class acapy_agent.utils.jwe.B64Value(*args: Any, **kwargs: Any)[source]
Bases:
StrA marshmallow-compatible wrapper for base64-URL values.
- class acapy_agent.utils.jwe.JweEnvelope(*, protected: dict | None = None, protected_b64: bytes | None = None, unprotected: dict | None = None, ciphertext: bytes | None = None, iv: bytes | None = None, tag: bytes | None = None, aad: bytes | None = None, with_protected_recipients: bool = False, with_flatten_recipients: bool = True)[source]
Bases:
objectJWE envelope instance.
- add_recipient(recip: JweRecipient)[source]
Add a recipient to the JWE envelope.
- property combined_aad: bytes
Accessor for the additional authenticated data.
- classmethod deserialize(message: Mapping[str, Any]) JweEnvelope[source]
Deserialize a JWE envelope from a mapping.
- classmethod from_json(message: bytes | str) JweEnvelope[source]
Decode a JWE envelope from a JSON string or bytes value.
- get_recipient(kid: str) JweRecipient[source]
Find a recipient by key ID.
- property protected_bytes: bytes
Access the protected data encoded as bytes.
This value is used in the additional authenticated data when encrypting.
- property recipient_key_ids: Iterable[JweRecipient]
Accessor for an iterator over the JWE recipient key identifiers.
- property recipients: Iterable[JweRecipient]
Accessor for an iterator over the JWE recipients.
The headers for each recipient include protected and unprotected headers from the outer envelope.
- property recipients_json: List[Dict[str, Any]]
Encode the current recipients for JSON.
- class acapy_agent.utils.jwe.JweRecipient(*, encrypted_key: bytes, header: dict | None = None)[source]
Bases:
objectA single message recipient.
- classmethod deserialize(entry: Mapping[str, Any]) JweRecipient[source]
Deserialize a JWE recipient from a mapping.
- class acapy_agent.utils.jwe.JweRecipientSchema(*args: Any, **kwargs: Any)[source]
Bases:
SchemaJWE recipient schema.
- class acapy_agent.utils.jwe.JweSchema(*args: Any, **kwargs: Any)[source]
Bases:
SchemaJWE envelope schema.
acapy_agent.utils.multi_ledger module
Multiledger related utility methods.
- acapy_agent.utils.multi_ledger.get_write_ledger_config_for_profile(settings: BaseSettings) dict[source]
Return initial/default write ledger config on profile creation.
acapy_agent.utils.outofband module
Utilities for creating out-of-band messages.
- acapy_agent.utils.outofband.serialize_outofband(message: AgentMessage, did: DIDInfo, endpoint: str) str[source]
Serialize the agent message as an out-of-band message.
- Returns:
An OOB message in URL format.
acapy_agent.utils.plugin_installer module
acapy_agent.utils.profiles module
acapy_agent.utils.repeat module
Utils for repeating tasks.
- class acapy_agent.utils.repeat.RepeatAttempt(seq: RepeatSequence, index: int = 1)[source]
Bases:
objectRepresents the current iteration in a repeat sequence.
- property final: bool
Check if this is the last instance in the sequence.
- next() RepeatAttempt[source]
Get the next attempt instance.
- property next_interval: float
Calculate the interval before the next attempt.
- class acapy_agent.utils.repeat.RepeatSequence(limit: int = 0, interval: float = 0.0, backoff: float = 0.0)[source]
Bases:
objectRepresents a repetition sequence.
- start() RepeatAttempt[source]
Get the first attempt in the sequence.
acapy_agent.utils.server module
Utility functions for server operations in an AcaPy agent.
acapy_agent.utils.stats module
Classes for tracking performance and timing.
- class acapy_agent.utils.stats.Collector(*, enabled: bool = True, log_path: str | None = None)[source]
Bases:
objectCollector for a set of statistics.
- property enabled: bool
Accessor for the collector’s enabled property.
- extract(groups: Sequence[str] = None) dict[source]
Extract statistics for a specific set of groups.
- log(name: str, duration: float, start: float | None = None)[source]
Log an entry in the statistics if the collector is enabled.
- property results: dict
Accessor for the current set of collected statistics.
- wrap(obj, prop_name: str | Sequence[str], groups: Sequence[str] = None, *, ignore_missing: bool = False)[source]
Wrap a method on a class or class instance.
acapy_agent.utils.task_queue module
Classes for managing a set of asyncio tasks.
- class acapy_agent.utils.task_queue.CompletedTask(task: Task, exc_info: Tuple, ident: str | None = None, timing: dict | None = None)[source]
Bases:
objectRepresent the result of a queued task.
- class acapy_agent.utils.task_queue.PendingTask(coro: Coroutine, complete_hook: Callable | None = None, ident: str | None = None, task_future: Future = None, queued_time: float | None = None)[source]
Bases:
objectRepresent a task in the queue.
- property cancelled
Accessor for the cancelled property.
- property task: Task
Accessor for the task.
- class acapy_agent.utils.task_queue.TaskQueue(max_active: int = 0, timed: bool = False, trace_fn: Callable | None = None)[source]
Bases:
objectA class for managing a set of asyncio tasks.
- add_active(task: Task, task_complete: Callable | None = None, ident: str | None = None, timing: dict | None = None) Task[source]
Register an active async task with an optional completion callback.
- Parameters:
task – The asyncio task instance
task_complete – An optional callback to run on completion
ident – A string identifier for the task
timing – An optional dictionary of timing information
- add_pending(pending: PendingTask)[source]
Add a task to the pending queue.
- Parameters:
pending – The PendingTask to add to the task queue
- property cancelled: bool
Accessor for the cancelled property of the queue.
- async complete(timeout: float | None = None, cleanup: bool = True)[source]
Cancel any pending tasks and wait for, or cancel active tasks.
- completed_task(task: Task, task_complete: Callable, ident: str, timing: dict | None = None)[source]
Clean up after a task has completed and run callbacks.
- property current_active: int
Accessor for the current number of active tasks in the queue.
- property current_pending: int
Accessor for the current number of pending tasks in the queue.
- property current_size: int
Accessor for the total number of tasks in the queue.
- property max_active: int
Accessor for the maximum number of active tasks in the queue.
- put(coro: Coroutine, task_complete: Callable | None = None, ident: str | None = None) PendingTask[source]
Add a new task to the queue, delaying execution if busy.
- Parameters:
coro – The coroutine to run
task_complete – A callback to run on completion
ident – A string identifier for the task
Returns: a future resolving to the asyncio task instance once queued
- property ready: bool
Accessor for the ready property of the queue.
- run(coro: Coroutine, task_complete: Callable | None = None, ident: str | None = None, timing: dict | None = None) Task[source]
Start executing a coroutine as an async task, bypassing the pending queue.
- Parameters:
coro – The coroutine to run
task_complete – An optional callback to run on completion
ident – A string identifier for the task
timing – An optional dictionary of timing information
Returns: the new asyncio task instance
- acapy_agent.utils.task_queue.coro_ident(coro: Coroutine)[source]
Extract an identifier for a coroutine.
acapy_agent.utils.testing module
acapy_agent.utils.tracing module
Event tracing.
- class acapy_agent.utils.tracing.AdminAPIMessageTracingSchema(*args: Any, **kwargs: Any)[source]
Bases:
OpenAPISchemaRequest/result schema including agent message tracing.
This is to be used as a superclass for aca-py admin input/output messages that need to support tracing.
- acapy_agent.utils.tracing.decode_inbound_message(message)[source]
Return bundled message if appropriate.
- acapy_agent.utils.tracing.trace_event(context, message, handler: str | None = None, outcome: str | None = None, perf_counter: float | None = None, force_trace: bool = False, raise_errors: bool = False) float[source]
Log a trace event to a configured target.
- Parameters:
context – The application context, attributes of interest are: context[“trace.enabled”]: True if we are logging events context[“trace.target”]: Trace target (“log”, “message” or an http endpoint) context[“trace.tag”]: Tag to be included in trace output
message – the current message, can be an AgentMessage, InboundMessage, OutboundMessage or Exchange record
handler (optional) – The handler name for the trace event. If not provided, it defaults to “aca-py.agent”.
outcome (optional) – The outcome of the trace event.
perf_counter (optional) – The performance counter value for the trace event.
force_trace (optional) – If True, forces the trace event to be logged even if tracing is not enabled.
raise_errors (optional) – If True, raises an exception if there is an error logging the trace event.
- Returns:
The value of the performance counter.
- Return type:
float
- Raises:
Exception – If there is an error logging the trace event and raise_errors is True.