apifrom.performance.connection_poolο
Connection pooling utilities for APIFromAnything.
This module provides tools for efficient connection management in high-load scenarios, including connection pooling, monitoring, and optimization.
Overviewο
Classes
BaseMiddlewareConnectionPoolMiddleware
Classesο
- BaseMiddleware(**options):bases: abc.ABC
Base middleware class for APIFromAnything.
- class apifrom.performance.connection_pool.ConnectionPool(factory, settings=None, validate_func=None, close_func=None, metrics=None)[source]ο
- Parameters:
factory (Callable[[], Any])
settings (Optional[ConnectionPoolSettings])
validate_func (Optional[Callable[[Any], bool]])
close_func (Optional[Callable[[Any], None]])
metrics (Optional[ConnectionPoolMetrics])
A generic connection pool for managing connections to external resources.
This class provides a pool of connections to external resources, such as databases, APIs, or services, and manages their lifecycle.
Initialize a connection pool.
- param factory:
A factory function that creates new connections
- param settings:
The connection pool settings
- param validate_func:
A function that validates connections
- param close_func:
A function that closes connections
- param metrics:
A metrics instance for collecting pool metrics
- apifrom.performance.connection_pool._close_connection(connection)ο
- :async:
Close a connection.
- param connection:
The connection to close
- apifrom.performance.connection_pool._create_connection()ο
- :async:
Create a new connection.
- returns:
A new connection
- apifrom.performance.connection_pool._validate_connection(connection)ο
- :async:
Validate a connection.
- param connection:
The connection to validate
- returns:
True if the connection is valid, False otherwise
- apifrom.performance.connection_pool.acquire()ο
- :async:
Acquire a connection from the pool.
- returns:
A connection from the pool
- raises TimeoutError:
If no connection could be acquired within the timeout
- raises RuntimeError:
If the pool is closed
- apifrom.performance.connection_pool.close()ο
- :async:
Close the connection pool.
This method closes all connections in the pool.
- apifrom.performance.connection_pool.connection()ο
- :async:
Get a connection from the pool as a context manager.
This method acquires a connection from the pool, yields it, and ensures it is released back to the pool when done.
- Yields:
A connection from the pool
- apifrom.performance.connection_pool.get_metrics()ο
Get the connection pool metrics.
- returns:
The connection pool metrics
- apifrom.performance.connection_pool.initialize()ο
- :async:
Initialize the connection pool.
This method creates the minimum number of connections.
- apifrom.performance.connection_pool.release(connection)ο
- :async:
Release a connection back to the pool.
- param connection:
The connection to release
Collects and analyzes connection pool metrics.
This class collects connection pool metrics such as pool size, connection acquisition times, and utilization, and provides tools for analyzing and visualizing this data.
Initialize connection pool metrics.
- apifrom.performance.connection_pool.print_summary()ο
Print a summary of the metrics data to the console.
- apifrom.performance.connection_pool.record_connection_acquire(connection_id, acquisition_time)ο
Record a connection acquisition.
- param connection_id:
The connection ID
- param acquisition_time:
The time it took to acquire the connection in seconds
- apifrom.performance.connection_pool.record_connection_error()ο
Record a connection error.
- apifrom.performance.connection_pool.record_connection_release(connection_id, release_time)ο
Record a connection release.
- param connection_id:
The connection ID
- param release_time:
The time it took to release the connection in seconds
- apifrom.performance.connection_pool.record_connection_request()ο
Record a connection request.
- apifrom.performance.connection_pool.record_connection_timeout()ο
Record a connection timeout.
- apifrom.performance.connection_pool.reset()ο
Reset all metrics data.
- apifrom.performance.connection_pool.save(file_path)ο
Save the metrics data to a file.
- param file_path:
The path to save the data to
- apifrom.performance.connection_pool.to_dict()ο
Convert the metrics data to a dictionary.
- returns:
A dictionary representation of the metrics data
- apifrom.performance.connection_pool.to_json(pretty=True)ο
Convert the metrics data to a JSON string.
- param pretty:
Whether to format the JSON with indentation
- returns:
A JSON string representation of the metrics data
- ConnectionPoolMiddleware(database_url = None, redis_url = None, settings = None, max_connections = 20, connection_timeout = 5.0, pool_recycle = 300, pool_pre_ping = True, **kwargs):bases: apifrom.middleware.base.BaseMiddleware
Middleware for providing connection pooling for API requests.
This middleware initializes connection pools for databases and other external services, and provides them to API requests through the request state.
Initialize the connection pool middleware.
- param database_url:
The database connection URL
- param redis_url:
The Redis connection URL
- param settings:
Connection pool settings
- param max_connections:
Maximum number of connections in the pool
- param connection_timeout:
Connection timeout in seconds
- param pool_recycle:
Connection recycle time in seconds
- param pool_pre_ping:
Whether to ping connections before using them
- param **kwargs:
Additional options
- apifrom.performance.connection_pool._initialize_database_pool()ο
- :async:
Initialize the database connection pool.
- apifrom.performance.connection_pool._initialize_redis_pool()ο
- :async:
Initialize the Redis connection pool.
- apifrom.performance.connection_pool.dispatch(request, call_next)ο
- :async:
Dispatch a request, providing connection pools.
- param request:
The request to process
- param call_next:
The next middleware or route handler
- returns:
The response
- apifrom.performance.connection_pool.get_metrics()ο
Get connection pool metrics.
- returns:
A dictionary of metrics
- apifrom.performance.connection_pool.initialize()ο
- :async:
Initialize the connection pools.
- apifrom.performance.connection_pool.print_metrics()ο
Print connection pool metrics.
- apifrom.performance.connection_pool.process_request(request)ο
- :async:
Process a request (required by BaseMiddleware).
- param request:
The request to process
- returns:
The processed request
- apifrom.performance.connection_pool.process_response(response)ο
- :async:
Process a response (required by BaseMiddleware).
- param response:
The response to process
- returns:
The processed response
- apifrom.performance.connection_pool.shutdown()ο
- :async:
Shutdown all connection pools.
- class apifrom.performance.connection_pool.ConnectionPoolSettings(min_size=1, max_size=10, max_idle=5, max_lifetime=3600, acquire_timeout=10.0, idle_timeout=300.0, retry_limit=3, retry_delay=1.0, validate_on_acquire=True)[source]ο
Settings for a connection pool.
This class defines the settings for a connection pool, such as pool size, timeout, and retry parameters.
Initialize connection pool settings.
- param min_size:
The minimum pool size
- param max_size:
The maximum pool size
- param max_idle:
The maximum number of idle connections
- param max_lifetime:
The maximum connection lifetime in seconds
- param acquire_timeout:
The connection acquisition timeout in seconds
- param idle_timeout:
The idle connection timeout in seconds
- param retry_limit:
The maximum number of connection retries
- param retry_delay:
The delay between connection retries in seconds
- param validate_on_acquire:
Whether to validate connections on acquisition
- apifrom.performance.connection_pool.create_aggressive()ο
- :classmethod:
Create aggressive connection pool settings.
These settings are optimized for high-throughput, low-latency scenarios.
- returns:
ConnectionPoolSettings instance
- apifrom.performance.connection_pool.create_balanced()ο
- :classmethod:
Create balanced connection pool settings.
These settings provide a balance between performance and resource usage.
- returns:
ConnectionPoolSettings instance
- apifrom.performance.connection_pool.create_conservative()ο
- :classmethod:
Create conservative connection pool settings.
These settings are optimized for reliability and resource efficiency.
- returns:
ConnectionPoolSettings instance
Manages multiple connection pools.
This class manages multiple connection pools for different resources, such as databases, APIs, or services.
Initialize a pool manager.
- apifrom.performance.connection_pool.close_all()ο
- :async:
Close all connection pools.
- apifrom.performance.connection_pool.close_pool(name)ο
- :async:
Close a connection pool.
- param name:
The name of the pool
- apifrom.performance.connection_pool.create_pool(name, factory, settings=None, validate_func=None, close_func=None)ο
- :async:
Create a new connection pool.
- param name:
The name of the pool
- param factory:
A factory function that creates new connections
- param settings:
The connection pool settings
- param validate_func:
A function that validates connections
- param close_func:
A function that closes connections
- returns:
The created connection pool
- apifrom.performance.connection_pool.get_metrics()ο
Get metrics for all connection pools.
- returns:
A dictionary mapping pool names to metrics
- apifrom.performance.connection_pool.get_pool(name)ο
- :async:
Get a connection pool by name.
- param name:
The name of the pool
- returns:
The connection pool, or None if not found
- apifrom.performance.connection_pool.print_summary()ο
Print a summary of all connection pools.
- class apifrom.performance.connection_pool.Request(request=None, path_params=None, method=None, path=None, query_params=None, headers=None, body=None, client_ip=None)[source]ο
Request class for APIFromAnything.
This class wraps a Starlette request and provides methods for accessing request data in a convenient way.
- apifrom.performance.connection_pool._requestο
The underlying Starlette request.
- apifrom.performance.connection_pool.path_paramsο
Path parameters extracted from the URL.
- apifrom.performance.connection_pool.query_paramsο
Query parameters extracted from the URL.
- apifrom.performance.connection_pool.headersο
HTTP headers.
- apifrom.performance.connection_pool.methodο
HTTP method.
- apifrom.performance.connection_pool.pathο
Request path.
- apifrom.performance.connection_pool._bodyο
Cached request body.
Initialize a new Request instance.
- param request:
The underlying Starlette request.
- param path_params:
Path parameters extracted from the URL.
- param method:
The HTTP method.
- param path:
The request path.
- param query_params:
Query parameters.
- param headers:
HTTP headers.
- param body:
Request body.
- param client_ip:
Client IP address.
- class apifrom.performance.connection_pool.Response(content=None, status_code=200, headers=None, content_type='application/json')[source]ο
Response class for APIFromAnything.
This class represents an HTTP response and provides methods for setting response data, status code, and headers.
- apifrom.performance.connection_pool.contentο
The response content.
- apifrom.performance.connection_pool.status_codeο
The HTTP status code.
- apifrom.performance.connection_pool.headersο
HTTP headers.
- apifrom.performance.connection_pool.content_typeο
The content type of the response.
Initialize a new Response instance.
- param content:
The response content.
- param status_code:
The HTTP status code.
- param headers:
HTTP headers.
- param content_type:
The content type of the response.