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


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:

Returns:
CodeExecutionResult object containing:

Implementation Details:

  1. Logging: Logs receipt of the /run request.

  2. Concurrency Control: Uses a semaphore keyed by the requested language to limit simultaneous executions, preventing resource exhaustion.

  3. Code Decoding: Decodes the base64-encoded code to a UTF-8 string.

  4. NodeJS Special Handling: If the language is NodeJS, appends an export statement (module.exports = { main };) to allow proper module execution.

  5. Security Analysis: Uses analyze_code_security to scan the code for unsafe patterns or vulnerabilities. If unsafe, returns immediately with an error result including line numbers and issues.

  6. Execution: Calls the async execute_code service to run the code and returns its result.

  7. 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


Interaction with Other System Components


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.


End of Documentation for handlers.py