apifrom.performance.optimization ================================ Optimization utilities for APIFromAnything. This module provides tools for analyzing and optimizing API performance, including optimization configuration, recommendation generation, and auto-tuning. .. py:currentmodule:: apifrom.performance.optimization Overview -------- **Classes** * :py:class:`APIProfiler` * :py:class:`BaseMiddleware` * :py:class:`OptimizationAnalyzer` * :py:class:`OptimizationConfig` * :py:class:`OptimizationLevel` * :py:class:`OptimizationRecommendation` * :py:class:`ProfileReport` * :py:class:`Request` * :py:class:`Response` * :py:class:`Web` Classes ------- .. py:class:: APIProfiler(output_dir = None, enabled = True) Profiles API endpoints to measure performance and identify bottlenecks. This class provides tools for profiling API endpoints, measuring response times, memory usage, and CPU usage, and generating profile reports. Initialize an API profiler. :param output_dir: The directory to save profile reports to (defaults to current directory) :param enabled: Whether profiling is enabled .. py:class:: BaseMiddleware(**options):bases: abc.ABC Base middleware class for APIFromAnything. This abstract class defines the interface for middleware components. Middleware components can process requests and responses. .. attribute:: options Options for the middleware. :type: dict Initialize a new BaseMiddleware instance. :param \*\*options: Options for the middleware. .. py:class:: OptimizationAnalyzer(config = None, profiler = None, output_dir = None) Analyzes API performance and generates optimization recommendations. This class provides tools for analyzing API performance, generating optimization recommendations, and applying optimizations. Initialize an optimization analyzer. :param config: The optimization configuration :param profiler: An existing APIProfiler instance :param output_dir: The directory to save optimization data to .. :: _api_stats .. :: _endpoint_stats .. :: _last_optimization .. :: _lock .. :: _system_stats .. :: config :no-index: .. :: output_dir .. :: profiler .. :: recommendations .. method:: _analyze_profile_reports(reports) Analyze profile reports and generate optimization recommendations. :param reports: The profile reports to analyze :returns: A list of optimization recommendations .. method:: _analyze_system_stats() Analyze system statistics and generate optimization recommendations. :returns: A list of optimization recommendations .. method:: _generate_code_specific_recommendations() Generate code-specific optimization recommendations. This method analyzes the codebase to find potential performance issues. :returns: A list of optimization recommendations .. method:: _generate_general_recommendations() Generate general optimization recommendations. :returns: A list of optimization recommendations .. method:: _get_system_stats() Get system statistics. :returns: A dictionary of system statistics .. method:: _save_recommendations() Save optimization recommendations to files. .. method:: analyze() Analyze API performance and generate optimization recommendations. :returns: A list of optimization recommendations .. method:: get_optimization_config() Get the optimization configuration. :returns: The optimization configuration .. method:: get_recommendations() Get optimization recommendations. :returns: A list of optimization recommendations .. method:: print_summary() Print a summary of the optimization analysis to the console. .. method:: set_optimization_config(config) Set the optimization configuration. :param config: The optimization configuration .. py:class:: OptimizationConfig(level = OptimizationLevel.BALANCED, enable_caching = True, enable_connection_pooling = True, enable_profiling = True, enable_request_coalescing = False, enable_request_throttling = False, enable_auto_tuning = True, enable_eager_loading = False, enable_circuit_breaker = False, slow_response_threshold_ms = 500, high_memory_threshold_mb = 500, high_cpu_threshold_percent = 80, high_error_rate_threshold = 0.05, optimization_interval = 3600) Configuration for optimizing APIFromAnything. This class defines the configuration for optimizing the APIFromAnything application for high-load scenarios. Initialize optimization configuration. :param level: The optimization level :param enable_caching: Whether to enable caching :param enable_connection_pooling: Whether to enable connection pooling :param enable_profiling: Whether to enable profiling :param enable_request_coalescing: Whether to enable request coalescing :param enable_request_throttling: Whether to enable request throttling :param enable_auto_tuning: Whether to enable auto-tuning :param enable_eager_loading: Whether to enable eager loading :param enable_circuit_breaker: Whether to enable circuit breaker :param slow_response_threshold_ms: The slow response threshold in milliseconds :param high_memory_threshold_mb: The high memory threshold in megabytes :param high_cpu_threshold_percent: The high CPU threshold in percent :param high_error_rate_threshold: The high error rate threshold (0.0 to 1.0) :param optimization_interval: The interval between optimizations in seconds .. :: enable_auto_tuning .. :: enable_caching .. :: enable_circuit_breaker .. :: enable_connection_pooling .. :: enable_eager_loading .. :: enable_profiling .. :: enable_request_coalescing .. :: enable_request_throttling .. :: high_cpu_threshold_percent .. :: high_error_rate_threshold .. :: high_memory_threshold_mb .. :: level .. :: optimization_interval .. :: slow_response_threshold_ms .. method:: create_aggressive() :classmethod: Create an aggressive optimization configuration. These settings are optimized for maximum performance. :returns: OptimizationConfig instance .. method:: create_balanced() :classmethod: Create a balanced optimization configuration. These settings provide a balance between performance and overhead. :returns: OptimizationConfig instance .. method:: create_minimal() :classmethod: Create a minimal optimization configuration. These settings are optimized for minimal overhead. :returns: OptimizationConfig instance .. method:: load(file_path) :classmethod: Load configuration from a file. :param file_path: The path to load the configuration from :returns: OptimizationConfig instance .. method:: save(file_path) Save the configuration to a file. :param file_path: The path to save the configuration to .. method:: to_dict() Convert the configuration to a dictionary. :returns: A dictionary representation of the configuration .. method:: to_json(pretty = True) Convert the configuration to a JSON string. :param pretty: Whether to format the JSON with indentation :returns: A JSON string representation of the configuration .. py:class:: OptimizationLevel:bases: enum.Enum Optimization level for the APIFromAnything application. This enum defines the level of optimization to apply to the APIFromAnything application. .. :: AGGRESSIVE .. :: BALANCED .. :: CUSTOM .. :: MINIMAL .. :: NONE .. py:class:: OptimizationRecommendation(title, description, action, priority = 3, affected_endpoints = None, affected_components = None, estimated_impact = None, code_examples = None) Represents a performance optimization recommendation. This class provides methods for generating and applying optimization recommendations based on performance data. Initialize an optimization recommendation. :param title: The recommendation title :param description: The recommendation description :param action: The recommended action :param priority: The recommendation priority (1-5, 1 is highest) :param affected_endpoints: The affected API endpoints :param affected_components: The affected components :param estimated_impact: The estimated impact of the recommendation :param code_examples: Code examples illustrating the recommendation .. :: action .. :: affected_components .. :: affected_endpoints .. :: code_examples .. :: created_at .. :: description .. :: estimated_impact .. :: priority .. :: title .. method:: print_summary() Print a summary of the recommendation to the console. .. method:: save(file_path) Save the recommendation to a file. :param file_path: The path to save the recommendation to .. method:: to_dict() Convert the recommendation to a dictionary. :returns: A dictionary representation of the recommendation .. method:: to_json(pretty = True) Convert the recommendation to a JSON string. :param pretty: Whether to format the JSON with indentation :returns: A JSON string representation of the recommendation .. py:class:: ProfileReport(endpoint_name, profile_data) Represents a performance profile report for an API endpoint. This class provides methods for analyzing and visualizing profile data, as well as exporting it to various formats. Initialize a profile report. :param endpoint_name: The name of the endpoint being profiled :param profile_data: The raw profile data .. py:class:: Request(request = None, path_params = None, method = None, path = None, query_params = None, headers = None, body = None, client_ip = None) Request class for APIFromAnything. This class wraps a Starlette request and provides methods for accessing request data in a convenient way. .. attribute:: _request The underlying Starlette request. .. attribute:: path_params Path parameters extracted from the URL. .. attribute:: query_params Query parameters extracted from the URL. .. attribute:: headers HTTP headers. .. attribute:: method HTTP method. .. attribute:: path Request path. .. attribute:: _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. .. py:class:: Response(content = None, status_code = 200, headers = None, content_type = 'application/json') Response class for APIFromAnything. This class represents an HTTP response and provides methods for setting response data, status code, and headers. .. attribute:: content The response content. .. attribute:: status_code The HTTP status code. .. attribute:: headers HTTP headers. .. attribute:: 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. .. py:class:: Web Decorator for optimizing web endpoints. This decorator applies various optimizations to web endpoints, such as caching, profiling, and auto-tuning. .. method:: create_default_web_optimization() :staticmethod: Create a default web optimization decorator. :returns: A default web optimization decorator with balanced settings .. method:: get_optimization_config(func) :staticmethod: Get the optimization configuration for a function. :param func: The function to get the configuration for :returns: The optimization configuration dictionary, or an empty dictionary if not optimized .. method:: is_optimized(func) :staticmethod: Check if a function is optimized. :param func: The function to check :returns: True if the function is optimized, False otherwise .. method:: optimize(cache_ttl = None, profile = True, connection_pool = True, auto_tune = True, request_coalescing = False, coalescing_ttl = 30, batch_processing = False, batch_size = 100, request_throttling = False, eager_loading = False, circuit_breaker = False) :staticmethod: Decorator for optimizing web endpoints. :param cache_ttl: The cache TTL in seconds (None for no caching) :param profile: Whether to profile the endpoint :param connection_pool: Whether to use connection pooling :param auto_tune: Whether to auto-tune the endpoint :param request_coalescing: Whether to coalesce duplicate requests :param coalescing_ttl: The time-to-live for coalesced requests in seconds :param batch_processing: Whether to enable batch processing :param batch_size: The maximum batch size for batch processing :param request_throttling: Whether to throttle excessive requests :param eager_loading: Whether to eagerly load related resources :param circuit_breaker: Whether to use a circuit breaker :returns: A decorated function