handlers.py
Overview
The handlers.py file defines asynchronous HTTP request handlers for the InfiniFlow application, primarily focused on code execution services. It provides endpoints to check service health and to securely execute user-submitted code snippets in supported programming languages. This file integrates with core concurrency controls, security analysis, rate limiting, and code execution services to ensure safe and efficient handling of code execution requests.
Detailed Descriptions
Imports and Dependencies
base64: For encoding and decoding user-submitted code.
core.container._CONTAINER_EXECUTION_SEMAPHORES: Semaphore objects to limit concurrent execution per language.
core.logger.logger: Logger for recording events and debugging information.
fastapi.Request: Represents HTTP request context in FastAPI.
models.enums.ResultStatus, SupportLanguage: Enumerations defining execution result statuses and supported programming languages.
models.schemas.CodeExecutionRequest, CodeExecutionResult: Data models for input requests and output results of code execution.
services.execution.execute_code: Core asynchronous function that runs the submitted code.
services.limiter.limiter: Rate limiter to prevent abuse of the execution endpoint.
services.security.analyze_code_security: Static code analyzer to detect unsafe code patterns.
Functions
async def healthz_handler() -> dict
Purpose:
Health check endpoint that responds with a simple status message indicating the service is operational.
Parameters:
None
Returns:dict with a single key "status" and value "ok".
Usage Example:
response = await healthz_handler()
print(response) # Output: {'status': 'ok'}
@limiter.limit("5/second")
async def run_code_handler(req: CodeExecutionRequest, request: Request) -> CodeExecutionResult
Purpose:
Handles requests to execute user-submitted code snippets. It enforces rate limiting (max 5 requests per second), concurrency control per language, performs security analysis on the submitted code, and executes it if safe.
Parameters:
req(CodeExecutionRequest): The request payload containing the base64-encoded code and language information.request(fastapi.Request): The HTTP request context (not used directly in the function but available for middleware or logging purposes).
Returns:CodeExecutionResult object containing:
status(ResultStatus): The result status of the execution (success, error, etc.).stdout(str): Captured standard output from the executed code.stderr(str): Captured standard error or error messages.exit_code(int): Exit code of the execution process.detail(str): Additional detail or error context.
Implementation Details:
Logging: Logs receipt of the
/runrequest.Concurrency Control: Uses a semaphore keyed by the requested language to limit simultaneous executions, preventing resource exhaustion.
Code Decoding: Decodes the base64-encoded code to a UTF-8 string.
NodeJS Special Handling: If the language is NodeJS, appends an export statement (
module.exports = { main };) to allow proper module execution.Security Analysis: Uses
analyze_code_securityto scan the code for unsafe patterns or vulnerabilities. If unsafe, returns immediately with an error result including line numbers and issues.Execution: Calls the async
execute_codeservice to run the code and returns its result.Exception Handling: Catches and reports unhandled exceptions as a program runner error with exit code
-999.
Usage Example:
from models.schemas import CodeExecutionRequest
from models.enums import SupportLanguage
import base64
code = "print('Hello, World!')"
encoded_code = base64.b64encode(code.encode('utf-8')).decode('utf-8')
req = CodeExecutionRequest(code_b64=encoded_code, language=SupportLanguage.PYTHON)
result = await run_code_handler(req, request=None)
print(result.stdout) # Expected: Hello, World!
Important Implementation Details and Algorithms
Concurrency Semaphores:
The_CONTAINER_EXECUTION_SEMAPHORESdictionary holds async semaphores for each supported language. This ensures that only a limited number of code executions per language occur simultaneously, preventing overloading the underlying container or runtime environment.Security Analysis:
Theanalyze_code_securityfunction performs static analysis on the decoded code to detect potentially harmful or insecure code fragments before execution. This is critical in a public code execution environment to prevent code injection, resource abuse, or system compromise.NodeJS Code Adjustment:
Since NodeJS expects modules to export functions for invocation, the handler appendsmodule.exports = { main };to the user code if the language is NodeJS. This ensures the execution environment can properly call the entry point.Comprehensive Error Handling:
The handler returns structured error responses with detailed information, making debugging and client-side error handling easier.Rate Limiting:
The decorator@limiter.limit("5/second")prevents abuse by limiting the number of requests to the/runendpoint to 5 per second per client or globally depending on the limiter configuration.
Interaction with Other System Components
core.container:
Provides synchronization primitives (semaphores) to control concurrent execution in isolated containers or sandboxes.core.logger:
Used for logging key events such as request receipt and errors.models:
Defines data models for request and response payloads, ensuring consistent API contracts.services.execution:
Contains the execution engine that runs code safely in isolated environments.services.limiter:
Implements request rate limiting to protect the system from overload and abuse.services.security:
Performs static code analysis to maintain security and integrity of the execution environment.FastAPI Framework:
This file’s handlers are designed to be wired into FastAPI routes, serving as the backend logic for web endpoints.
Diagram: Class and Function Structure in handlers.py
classDiagram
class handlers.py {
+async healthz_handler() dict
+async run_code_handler(req: CodeExecutionRequest, request: Request) CodeExecutionResult
}
%% External dependencies
class CodeExecutionRequest
class CodeExecutionResult
class ResultStatus
class SupportLanguage
%% Relationships
handlers.py ..> CodeExecutionRequest : uses
handlers.py ..> CodeExecutionResult : returns
handlers.py ..> ResultStatus : reads
handlers.py ..> SupportLanguage : reads
Summary
The handlers.py file is a critical component of the InfiniFlow backend service, providing robust, secure, and efficient APIs for running user-submitted code snippets. It carefully balances concurrency, security, and usability by employing semaphores, static code analysis, and rate limiting. This file integrates tightly with the execution and security services, forming the core of the code execution workflow.