Utilities Reference

Complete reference for utility classes and helper functions.

Caching

Cache

class honeyhive.utils.cache.Cache(config=None)[source]

Bases: object

In-memory cache with TTL and size limits.

Parameters:

config (CacheConfig | None)

property cache: Dict[str, CacheEntry]

Get the underlying cache dictionary.

Returns:

Cache dictionary

property hits: int

Get cache hit count.

Returns:

Number of cache hits

property misses: int

Get cache miss count.

Returns:

Number of cache misses

generate_key(*args, **kwargs)[source]

Generate cache key from arguments (public method).

Parameters:
  • *args (Any) – Positional arguments

  • **kwargs (Any) – Keyword arguments

Returns:

Cache key string

Return type:

str

get(key, default=None)[source]

Get value from cache.

Parameters:
  • key (str) – Cache key

  • default (Any) – Default value if key not found

Returns:

Cached value or default

Return type:

Any

set(key, value, ttl=None)[source]

Set value in cache.

Parameters:
  • key (str) – Cache key

  • value (Any) – Value to cache

  • ttl (float | None) – Time to live in seconds (uses default if None)

Return type:

None

delete(key)[source]

Delete key from cache.

Parameters:

key (str) – Cache key to delete

Returns:

True if key was deleted, False if not found

Return type:

bool

exists(key)[source]

Check if key exists in cache.

Parameters:

key (str) – Cache key to check

Returns:

True if key exists and not expired, False otherwise

Return type:

bool

clear()[source]

Clear all entries from cache.

Return type:

None

cleanup_expired()[source]

Clean up expired entries.

Returns:

Number of entries cleaned up

Return type:

int

get_stats()[source]

Get cache statistics.

Returns:

Dictionary with cache statistics

Return type:

Dict[str, Any]

stats()[source]

Get cache statistics.

Returns:

Dictionary with cache statistics

Return type:

Dict[str, Any]

cleanup()[source]

Clean up expired entries and perform maintenance.

Return type:

None

close()[source]

Close cache and cleanup resources.

Return type:

None

FunctionCache

class honeyhive.utils.cache.FunctionCache(cache=None, ttl=None, key_func=None)[source]

Bases: object

Function result cache decorator.

Note: too-few-public-methods disabled - Decorator classes need __init__/__call__.

Parameters:

AsyncFunctionCache

class honeyhive.utils.cache.AsyncFunctionCache(cache=None, ttl=None, key_func=None)[source]

Bases: object

Async function result cache decorator.

Note: too-few-public-methods disabled - Decorator classes need __init__/__call__.

Parameters:

CacheEntry

class honeyhive.utils.cache.CacheEntry(key, value, ttl=300.0)[source]

Bases: object

Cache entry with metadata.

Parameters:
is_expired()[source]

Check if entry is expired.

Returns:

True if expired, False otherwise

Return type:

bool

access()[source]

Mark entry as accessed.

Return type:

None

get_age()[source]

Get age of entry in seconds.

Returns:

Age in seconds

Return type:

float

get_remaining_ttl()[source]

Get remaining TTL in seconds.

Returns:

Remaining TTL in seconds

Return type:

float

property expiry: float

Get expiry timestamp.

Returns:

Timestamp when entry expires

Connection Pooling

ConnectionPool

class honeyhive.utils.connection_pool.ConnectionPool(config=None, *, max_connections=None, max_keepalive=None, max_keepalive_connections=None, keepalive_expiry=None, retries=None, timeout=None, pool_timeout=None)[source]

Bases: object

Connection pool for HTTP clients.

Parameters:
  • config (PoolConfig | None)

  • max_connections (int | None)

  • max_keepalive (int | None)

  • max_keepalive_connections (int | None)

  • keepalive_expiry (float | None)

  • retries (int | None)

  • timeout (float | None)

  • pool_timeout (float | None)

get_client(base_url, headers=None, **kwargs)[source]

Get or create an HTTP client from the pool.

Parameters:
  • base_url (str) – Base URL for the client

  • headers (Dict[str, str] | None) – Default headers

  • **kwargs (Any) – Additional client configuration

Returns:

HTTP client instance

Return type:

Client

get_async_client(base_url, headers=None, **kwargs)[source]

Get or create an async HTTP client from the pool.

Parameters:
  • base_url (str) – Base URL for the client

  • headers (Dict[str, str] | None) – Default headers

  • **kwargs (Any) – Additional client configuration

Returns:

Async HTTP client instance

Return type:

AsyncClient

cleanup_idle_connections(max_idle_time=300.0)[source]

Clean up idle connections.

Parameters:

max_idle_time (float) – Maximum idle time in seconds

Return type:

None

get_stats()[source]

Get pool statistics.

Returns:

Dictionary with pool statistics

Return type:

Dict[str, Any]

property active_connections: int

Get number of active connections.

Returns:

Number of active connections

get_connection(base_url)[source]

Get a connection for a specific base URL.

Parameters:

base_url (str) – Base URL for the connection

Returns:

HTTP client instance or None if not found

Return type:

Client | None

return_connection(base_url, client)[source]

Return a connection to the pool.

Parameters:
  • base_url (str) – Base URL for the connection

  • client (Client) – HTTP client to return

Return type:

None

get_async_connection(base_url)[source]

Get an async connection for a specific base URL.

Parameters:

base_url (str) – Base URL for the connection

Returns:

Async HTTP client instance or None if not found

Return type:

AsyncClient | None

return_async_connection(base_url, client)[source]

Return an async connection to the pool.

Parameters:
  • base_url (str) – Base URL for the connection

  • client (AsyncClient) – Async HTTP client to return

Return type:

None

close_connection(base_url)[source]

Close a specific connection.

Parameters:

base_url (str) – Base URL for the connection

Return type:

None

cleanup()[source]

Clean up expired connections.

Return type:

None

close_all()[source]

Close all connections in the pool.

Return type:

None

reset_stats()[source]

Reset pool statistics.

Return type:

None

close_all_clients()[source]

Close all clients in the pool (alias for close_all).

Return type:

None

async aclose_all_clients()[source]

Close all async clients in the pool.

Return type:

None

PooledHTTPClient

class honeyhive.utils.connection_pool.PooledHTTPClient(pool, **kwargs)[source]

Bases: object

HTTP client that uses connection pooling.

Parameters:
get(url, **kwargs)[source]

Make GET request.

Parameters:
Return type:

Response

post(url, **kwargs)[source]

Make POST request.

Parameters:
Return type:

Response

put(url, **kwargs)[source]

Make PUT request.

Parameters:
Return type:

Response

delete(url, **kwargs)[source]

Make DELETE request.

Parameters:
Return type:

Response

patch(url, **kwargs)[source]

Make PATCH request.

Parameters:
Return type:

Response

PooledAsyncHTTPClient

class honeyhive.utils.connection_pool.PooledAsyncHTTPClient(pool, **kwargs)[source]

Bases: object

Async HTTP client that uses connection pooling.

Parameters:
async get(url, **kwargs)[source]

Make async GET request.

Parameters:
Return type:

Response

async post(url, **kwargs)[source]

Make async POST request.

Parameters:
Return type:

Response

async put(url, **kwargs)[source]

Make async PUT request.

Parameters:
Return type:

Response

async delete(url, **kwargs)[source]

Make async DELETE request.

Parameters:
Return type:

Response

async patch(url, **kwargs)[source]

Make async PATCH request.

Parameters:
Return type:

Response

Data Structures

DotDict

class honeyhive.utils.dotdict.DotDict(*args, **kwargs)[source]

Bases: dict

Dictionary with dot notation access.

Example

>>> d = DotDict({'foo': {'bar': 'baz'}})
>>> d.foo.bar
'baz'
>>> d.foo.bar = 'qux'
>>> d['foo']['bar']
'qux'
Parameters:
get(key, default=None)[source]

Get item with default value, supporting dot notation.

Parameters:
Return type:

Any

setdefault(key, default=None)[source]

Set default value for key, supporting dot notation.

Parameters:
Return type:

Any

update(other=None, /, **kwargs)[source]

Update dictionary with dot notation support.

Parameters:
Return type:

None

to_dict()[source]

Convert dotdict back to regular dictionary.

Return type:

Dict[str, Any]

copy()[source]

Create a shallow copy.

Return type:

DotDict

deepcopy()[source]

Create a deep copy.

Return type:

DotDict

BaggageDict

class honeyhive.utils.baggage_dict.BaggageDict(ctx=None)[source]

Bases: object

Dictionary-like interface for OpenTelemetry baggage.

This class provides a convenient way to work with OpenTelemetry baggage as if it were a regular dictionary, while maintaining proper context propagation.

Parameters:

ctx (Context | None)

property context: Context

Get the current context.

get(key, default=None)[source]

Get a value from baggage.

Parameters:
  • key (str) – Baggage key

  • default (Any) – Default value if key not found

Returns:

Value from baggage or default

Return type:

Any

set(key, value)[source]

Set a value in baggage.

Parameters:
  • key (str) – Baggage key

  • value (Any) – Value to set

Returns:

New BaggageDict with updated context

Return type:

BaggageDict

delete(key)[source]

Delete a key from baggage.

Parameters:

key (str) – Baggage key to delete

Returns:

New BaggageDict with updated context

Return type:

BaggageDict

update(**kwargs)[source]

Update multiple baggage values.

Parameters:

**kwargs (Any) – Key-value pairs to set

Returns:

New BaggageDict with updated context

Return type:

BaggageDict

clear()[source]

Clear all baggage.

Returns:

New BaggageDict with empty baggage

Return type:

BaggageDict

items()[source]

Get all baggage items as a dictionary.

Returns:

Dictionary of baggage key-value pairs

Return type:

Dict[str, str]

keys()[source]

Get all baggage keys.

Return type:

KeysView[str]

values()[source]

Get all baggage values.

Return type:

ValuesView[str]

classmethod from_dict(data, ctx=None)[source]

Create BaggageDict from dictionary.

Parameters:
  • data (Dict[str, Any]) – Dictionary of key-value pairs

  • ctx (Context | None) – Optional OpenTelemetry context

Returns:

New BaggageDict with baggage from dictionary

Return type:

BaggageDict

as_context()[source]

Context manager to temporarily set baggage in current context.

Example

with BaggageDict().set(“user_id”, “123”).as_context():

# baggage is available in this context pass

Return type:

Iterator[None]

Retry Configuration

RetryConfig

class honeyhive.utils.retry.RetryConfig(strategy='exponential', backoff_strategy=None, max_retries=3, retry_on_status_codes=None)[source]

Bases: object

Configuration for retry behavior.

Parameters:
  • strategy (str)

  • backoff_strategy (BackoffStrategy | None)

  • max_retries (int)

  • retry_on_status_codes (set | None)

strategy: str = 'exponential'
backoff_strategy: BackoffStrategy | None = None
max_retries: int = 3
retry_on_status_codes: set | None = None
classmethod default()[source]

Create a default retry configuration.

Return type:

RetryConfig

classmethod exponential(initial_delay=1.0, max_delay=60.0, multiplier=2.0, max_retries=3)[source]

Create an exponential backoff retry configuration.

Parameters:
Return type:

RetryConfig

classmethod linear(delay=1.0, max_retries=3)[source]

Create a linear backoff retry configuration.

Parameters:
Return type:

RetryConfig

classmethod constant(delay=1.0, max_retries=3)[source]

Create a constant delay retry configuration.

Parameters:
Return type:

RetryConfig

should_retry(response)[source]

Determine if a response should be retried.

Parameters:

response (Response)

Return type:

bool

should_retry_exception(exc)[source]

Determine if an exception should be retried.

Parameters:

exc (Exception)

Return type:

bool

Logging

HoneyHiveLogger

class honeyhive.utils.logger.HoneyHiveLogger(name, *, level=None, formatter=None, handler=None, verbose=None)[source]

Bases: object

HoneyHive logger with structured logging.

Provides a structured logging interface with HoneyHive-specific formatting and context data support. Uses per-instance configuration instead of global config for multi-instance architecture.

Parameters:
update_verbose_setting(verbose)[source]

Dynamically update the logger’s verbose setting.

This allows the tracer to update the logger’s level after initialization based on configuration changes.

Parameters:

verbose (bool) – New verbose setting

Return type:

None

debug(message, *args, honeyhive_data=None, **kwargs)[source]

Log debug message with lazy formatting support.

Parameters:
  • message (str) – Debug message format string (supports % formatting)

  • *args (Any) – Arguments for lazy string formatting

  • honeyhive_data (Dict[str, Any] | None) – Additional HoneyHive context data

  • **kwargs (Any) – Additional logging parameters

Return type:

None

info(message, *args, honeyhive_data=None, **kwargs)[source]

Log info message with lazy formatting support.

Parameters:
Return type:

None

warning(message, *args, honeyhive_data=None, **kwargs)[source]

Log warning message with lazy formatting support.

Parameters:
Return type:

None

error(message, *args, honeyhive_data=None, **kwargs)[source]

Log error message with lazy formatting support.

Parameters:
Return type:

None

critical(message, *args, honeyhive_data=None, **kwargs)[source]

Log critical message with lazy formatting support.

Parameters:
Return type:

None

exception(message, *args, honeyhive_data=None, **kwargs)[source]

Log exception message with traceback and lazy formatting support.

Parameters:
Return type:

None

get_logger

honeyhive.utils.logger.get_logger(name, verbose=None, tracer_instance=None, **kwargs)[source]

Get a HoneyHive logger instance with dynamic configuration.

Uses dynamic logic to determine logger configuration based on tracer instance settings or explicit parameters.

Parameters:
  • name (str) – Logger name

  • verbose (bool | None) – Explicit verbose setting

  • tracer_instance (Any | None) – Tracer instance to extract verbose setting from

  • **kwargs (Any) – Additional logger parameters

Returns:

Configured HoneyHive logger instance

Return type:

HoneyHiveLogger

Distributed Tracing (v1.0+)

Context Propagation Functions

These functions enable distributed tracing by propagating trace context across service boundaries via HTTP headers.

inject_context_into_carrier

honeyhive.tracer.processing.context.inject_context_into_carrier(carrier, tracer_instance)[source]

Inject OpenTelemetry context into a carrier dictionary.

This function injects the current OpenTelemetry context (including trace context and baggage) into a carrier dictionary for cross-service or cross-process propagation.

Parameters:
  • carrier (Dict[str, str]) – Dictionary to inject context into

  • tracer_instance (HoneyHiveTracer) – The tracer instance for propagator access

Return type:

None

Example:

headers = {}
inject_context_into_carrier(headers, tracer)
# headers now contains trace context and baggage

# Use headers in HTTP request
response = requests.get(url, headers=headers)

Note:

The carrier dictionary will be modified in-place with context information. This is typically used for HTTP headers or message metadata in distributed systems.

Adds OpenTelemetry trace context (trace ID, span ID, baggage) to a dictionary (typically HTTP headers) for propagation to downstream services.

Example:

from honeyhive.tracer.processing.context import inject_context_into_carrier
import requests

# Inject trace context into HTTP headers
headers = {"Content-Type": "application/json"}
inject_context_into_carrier(headers, tracer)

# Send request with distributed trace context
response = requests.post(
    "http://downstream-service/api/endpoint",
    json=data,
    headers=headers  # Trace context propagates here
)

extract_context_from_carrier

honeyhive.tracer.processing.context.extract_context_from_carrier(carrier, tracer_instance)[source]

Extract OpenTelemetry context from a carrier dictionary.

This function extracts OpenTelemetry context (including trace context and baggage) from a carrier dictionary, typically received from another service or process.

Parameters:
  • carrier (Dict[str, str]) – Dictionary containing context information

  • tracer_instance (HoneyHiveTracer) – The tracer instance for propagator access

Returns:

Extracted OpenTelemetry context or None if extraction fails

Return type:

Optional[Context]

Example:

# Extract context from HTTP headers
extracted_context = extract_context_from_carrier(request.headers, tracer)

# Use extracted context as parent for new spans
with tracer.start_span("operation", context=extracted_context) as span:
    # This span will be a child of the remote span
    pass

Note:

This function is typically used in service endpoints to continue distributed traces from upstream services. The extracted context can be used as a parent context for new spans.

Extracts OpenTelemetry trace context from a dictionary (typically HTTP headers) received from an upstream service.

Example:

from flask import request
from honeyhive.tracer.processing.context import extract_context_from_carrier
from opentelemetry import context

@app.route("/api/endpoint", methods=["POST"])
def endpoint():
    # Extract trace context from incoming headers
    incoming_context = extract_context_from_carrier(dict(request.headers), tracer)

    # Attach context so spans become children of parent trace
    if incoming_context:
        token = context.attach(incoming_context)

    try:
        # Your business logic here
        result = do_work()
        return jsonify(result)
    finally:
        if incoming_context:
            context.detach(token)

See Also