askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
endpoint_loader.py · 5.2 KB · 199 lines
| 1 | """ |
| 2 | Endpoint Loader |
| 3 | |
| 4 | Loads endpoint Python files as modules and executes their HTTP methods. |
| 5 | |
| 6 | Design principles: |
| 7 | - Endpoints are Python files with GET/POST/PUT/DELETE functions |
| 8 | - Each endpoint is a module that can be imported |
| 9 | - Endpoints are cached for performance |
| 10 | - Errors are caught and wrapped with context |
| 11 | """ |
| 12 | |
| 13 | import importlib.util |
| 14 | import sys |
| 15 | from pathlib import Path |
| 16 | from typing import Any, Dict, Optional |
| 17 | import traceback |
| 18 | |
| 19 | |
| 20 | # Custom exceptions |
| 21 | class EndpointError(Exception): |
| 22 | """Base exception for endpoint-related errors""" |
| 23 | pass |
| 24 | |
| 25 | |
| 26 | class EndpointNotFoundError(EndpointError): |
| 27 | """Raised when endpoint file doesn't exist""" |
| 28 | pass |
| 29 | |
| 30 | |
| 31 | class EndpointLoadError(EndpointError): |
| 32 | """Raised when endpoint file can't be loaded (syntax error, import error)""" |
| 33 | pass |
| 34 | |
| 35 | |
| 36 | class MethodNotSupportedError(EndpointError): |
| 37 | """Raised when HTTP method not supported by endpoint""" |
| 38 | pass |
| 39 | |
| 40 | |
| 41 | class EndpointExecutionError(EndpointError): |
| 42 | """Raised when endpoint execution fails""" |
| 43 | pass |
| 44 | |
| 45 | |
| 46 | # Endpoint cache |
| 47 | _endpoint_cache: Dict[str, Any] = {} |
| 48 | _cache_stats = {'hits': 0, 'misses': 0} |
| 49 | |
| 50 | |
| 51 | def load_endpoint(path: str | Path, reload: bool = False) -> Any: |
| 52 | """ |
| 53 | Load an endpoint Python file as a module. |
| 54 | |
| 55 | Args: |
| 56 | path: Path to the endpoint .py file |
| 57 | reload: If True, bypass cache and reload the module |
| 58 | |
| 59 | Returns: |
| 60 | The loaded module object |
| 61 | |
| 62 | Raises: |
| 63 | EndpointNotFoundError: If file doesn't exist |
| 64 | EndpointLoadError: If file can't be loaded (syntax error, etc.) |
| 65 | """ |
| 66 | # Convert to Path object |
| 67 | path = Path(path) |
| 68 | path_str = str(path.absolute()) |
| 69 | |
| 70 | # Check cache (unless reload=True) |
| 71 | if not reload and path_str in _endpoint_cache: |
| 72 | _cache_stats['hits'] += 1 |
| 73 | return _endpoint_cache[path_str] |
| 74 | |
| 75 | _cache_stats['misses'] += 1 |
| 76 | |
| 77 | # Check if file exists |
| 78 | if not path.exists(): |
| 79 | raise EndpointNotFoundError(f"Endpoint file not found: {path}") |
| 80 | |
| 81 | if not path.is_file(): |
| 82 | raise EndpointNotFoundError(f"Path is not a file: {path}") |
| 83 | |
| 84 | # Load the module |
| 85 | try: |
| 86 | # Create a module spec |
| 87 | module_name = f"endpoint_{path.stem}_{id(path)}" |
| 88 | spec = importlib.util.spec_from_file_location(module_name, path) |
| 89 | |
| 90 | if spec is None or spec.loader is None: |
| 91 | raise EndpointLoadError(f"Could not create module spec for: {path}") |
| 92 | |
| 93 | # Create the module |
| 94 | module = importlib.util.module_from_spec(spec) |
| 95 | |
| 96 | # Add to sys.modules temporarily |
| 97 | sys.modules[module_name] = module |
| 98 | |
| 99 | # Execute the module (loads it) |
| 100 | spec.loader.exec_module(module) |
| 101 | |
| 102 | # Cache it |
| 103 | _endpoint_cache[path_str] = module |
| 104 | |
| 105 | return module |
| 106 | |
| 107 | except SyntaxError as e: |
| 108 | raise EndpointLoadError(f"Syntax error in endpoint {path}: {e}") |
| 109 | except Exception as e: |
| 110 | raise EndpointLoadError(f"Failed to load endpoint {path}: {e}\n{traceback.format_exc()}") |
| 111 | |
| 112 | |
| 113 | def execute_endpoint(endpoint: Any, method: str, request: Dict[str, Any]) -> Dict[str, Any]: |
| 114 | """ |
| 115 | Execute an HTTP method on an endpoint. |
| 116 | |
| 117 | Args: |
| 118 | endpoint: The loaded endpoint module |
| 119 | method: HTTP method name (GET, POST, PUT, DELETE, etc.) |
| 120 | request: Request data dictionary |
| 121 | |
| 122 | Returns: |
| 123 | Response dictionary from the endpoint |
| 124 | |
| 125 | Raises: |
| 126 | MethodNotSupportedError: If method not supported |
| 127 | EndpointExecutionError: If execution fails |
| 128 | """ |
| 129 | # Check if method exists |
| 130 | if not hasattr(endpoint, method): |
| 131 | raise MethodNotSupportedError( |
| 132 | f"Method {method} not supported by endpoint. " |
| 133 | f"Available methods: {_get_available_methods(endpoint)}" |
| 134 | ) |
| 135 | |
| 136 | # Get the method function |
| 137 | method_func = getattr(endpoint, method) |
| 138 | |
| 139 | # Execute it |
| 140 | try: |
| 141 | result = method_func(request) |
| 142 | return result |
| 143 | except Exception as e: |
| 144 | # Wrap the exception with context |
| 145 | raise EndpointExecutionError( |
| 146 | f"Endpoint execution failed for {method}: {type(e).__name__}: {e}\n" |
| 147 | f"{traceback.format_exc()}" |
| 148 | ) |
| 149 | |
| 150 | |
| 151 | def get_endpoint_metadata(endpoint: Any) -> Dict[str, Any]: |
| 152 | """ |
| 153 | Get metadata from an endpoint module. |
| 154 | |
| 155 | Looks for __endpoint__ dict in the module. |
| 156 | |
| 157 | Args: |
| 158 | endpoint: The loaded endpoint module |
| 159 | |
| 160 | Returns: |
| 161 | Metadata dictionary (with defaults if not present) |
| 162 | """ |
| 163 | if hasattr(endpoint, '__endpoint__'): |
| 164 | return getattr(endpoint, '__endpoint__') |
| 165 | |
| 166 | # Return defaults |
| 167 | return { |
| 168 | 'name': getattr(endpoint, '__name__', 'unknown'), |
| 169 | 'version': '0.0.0', |
| 170 | 'description': '', |
| 171 | 'author': 'unknown', |
| 172 | } |
| 173 | |
| 174 | |
| 175 | def clear_cache(): |
| 176 | """Clear the endpoint cache""" |
| 177 | global _endpoint_cache, _cache_stats |
| 178 | _endpoint_cache.clear() |
| 179 | _cache_stats = {'hits': 0, 'misses': 0} |
| 180 | |
| 181 | |
| 182 | def get_cache_stats() -> Dict[str, int]: |
| 183 | """ |
| 184 | Get cache statistics. |
| 185 | |
| 186 | Returns: |
| 187 | Dict with 'hits', 'misses', 'size' |
| 188 | """ |
| 189 | return { |
| 190 | 'hits': _cache_stats['hits'], |
| 191 | 'misses': _cache_stats['misses'], |
| 192 | 'size': len(_endpoint_cache), |
| 193 | } |
| 194 | |
| 195 | |
| 196 | def _get_available_methods(endpoint: Any) -> list[str]: |
| 197 | """Helper: Get list of available HTTP methods on endpoint""" |
| 198 | http_methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] |
| 199 | return [m for m in http_methods if hasattr(endpoint, m)] |