Skip to main content
CodePlanet Docs

Code Execution

Running and testing your code

CodePlanet's code execution system provides secure, reliable, and multi-language programming execution capabilities for learning, practice, and assessment.

🚀 System Architecture

Multi-Provider Architecture

The system uses a fallback chain approach to ensure maximum reliability:

  1. Primary: HackerEarth API
  2. Secondary: OneCompiler API
  3. Tertiary: Paiza.IO API
  4. Local: Docker-based sandbox (development)

Security Sandboxing

  • Isolated Execution: Each code run in separate container
  • Resource Limits: CPU, memory, and time constraints
  • Network Isolation: No external network access
  • File System Restrictions: Read-only file system with temp directories

💻 Supported Languages

Core Languages

  • Python (3.9+)
  • JavaScript (Node.js 18+)
  • Java (OpenJDK 17)
  • C++ (GCC 11+)
  • C (GCC 11+)

Additional Languages

  • Go (1.19+)
  • Rust (1.65+)
  • Ruby (3.1+)
  • PHP (8.1+)
  • Swift (5.7+)

Language-Specific Features

  • Pre-installed standard libraries
  • Package manager integration
  • Version-specific configurations
  • Custom runtime environments

⚙️ Technical Implementation

API Endpoints

# Execute code
POST /api/execute
Content-Type: application/json
 
{
  "code": "print('Hello, World!')",
  "language": "python",
  "input": "optional input data",
  "timeout": 10000
}
 
# Response
{
  "success": true,
  "stdout": "Hello, World!\n",
  "stderr": "",
  "execution_time": 42,
  "memory_used": 12.5,
  "provider": "hackerEarth"
}

Backend Service Structure

class CodeExecutor:
    def __init__(self):
        self.providers = [
            HackerEarthProvider(),
            OneCompilerProvider(), 
            PaizaIOProvider()
        ]
    
    def execute(self, code, language, input_data="", timeout=10000):
        for provider in self.providers:
            try:
                result = provider.execute(code, language, input_data, timeout)
                if result.success:
                    return result
            except Exception as e:
                logger.warning(f"Provider {provider.name} failed: {e}")
                continue
        
        raise ExecutionError("All execution providers failed")

Frontend Integration

// Code execution hook
import { useCodeExecution } from '@/hooks/use-code-execution'
 
function CodeEditor() {
  const { execute, result, loading, error } = useCodeExecution()
  
  const handleRun = async () => {
    const executionResult = await execute({
      code: editor.getValue(),
      language: selectedLanguage,
      input: inputRef.current.value
    })
    
    setResult(executionResult)
  }
  
  return (
    <div className="code-execution-interface">
      <EditorComponent />
      <InputPanel />
      <OutputPanel result={result} loading={loading} />
      <button onClick={handleRun} disabled={loading}>
        {loading ? 'Running...' : 'Run Code'}
      </button>
    </div>
  )
}

🔒 Security Measures

Execution Environment

# Sandbox container configuration
FROM python:3.9-slim
 
# Security hardening
RUN useradd -m executor
USER executor
WORKDIR /home/executor
 
# Resource limits
ulimit -t 10  # 10 seconds CPU time
ulimit -v 131072  # 128MB memory
ulimit -f 1024  # 1MB file size limit
 
# No network access
# Network isolated at container level

Input Sanitization

  • Code Validation: Syntax checking before execution
  • Input Filtering: Remove potentially harmful input
  • Output Sanitization: Clean execution results
  • Size Limits: Maximum code and input size restrictions

Rate Limiting

# Rate limiting configuration
RATE_LIMITS = {
    'anonymous': 10,      # 10 executions per hour
    'user': 100,          # 100 executions per hour
    'pro': 500,           # 500 executions per hour
    'enterprise': 1000    # 1000 executions per hour
}

📊 Performance Monitoring

Execution Metrics

  • Response Time: Average execution response time
  • Success Rate: Percentage of successful executions
  • Resource Usage: CPU and memory consumption
  • Provider Reliability: Individual provider performance

Monitoring Dashboard

// Execution metrics tracking
const executionMetrics = {
  totalExecutions: 0,
  successfulExecutions: 0,
  averageResponseTime: 0,
  providerStats: {
    hackerEarth: { successRate: 0.95, avgTime: 1200 },
    oneCompiler: { successRate: 0.88, avgTime: 1800 },
    paizaIO: { successRate: 0.92, avgTime: 1500 }
  }
}

Error Handling

# Comprehensive error handling
class ExecutionError(Exception):
    def __init__(self, message, error_type, details=None):
        self.message = message
        self.error_type = error_type
        self.details = details or {}
 
# Error types
ERROR_TYPES = {
    'TIMEOUT': 'Execution exceeded time limit',
    'MEMORY_LIMIT': 'Memory usage exceeded limit',
    'COMPILATION_ERROR': 'Code failed to compile',
    'RUNTIME_ERROR': 'Runtime exception occurred',
    'SYNTAX_ERROR': 'Invalid syntax detected'
}

🛠️ Configuration and Setup

Environment Variables

# Execution service configuration
EXECUTION_TIMEOUT=10000
EXECUTION_MEMORY_LIMIT=134217728  # 128MB
EXECUTION_CPU_LIMIT=10  # 10 seconds

# Provider API keys
HACKEREARTH_API_KEY=your-api-key
ONECOMPILER_API_KEY=your-api-key
PAIZAIO_API_KEY=your-api-key

# Rate limiting
RATE_LIMIT_WINDOW=3600  # 1 hour
DEFAULT_QUOTA=100

Provider Configuration

# Provider setup
PROVIDERS = {
    'hackerEarth': {
        'api_url': 'https://api.hackerearth.com/v4/code/run/',
        'api_key': os.getenv('HACKEREARTH_API_KEY'),
        'timeout': 15000,
        'languages': ['python3', 'javascript', 'java', 'cpp17']
    },
    'oneCompiler': {
        'api_url': 'https://onecompiler-apis.p.rapidapi.com/api/v1/run',
        'api_key': os.getenv('ONECOMPILER_API_KEY'),
        'timeout': 20000,
        'languages': ['python', 'javascript', 'java', 'cpp']
    }
}

🎯 Use Cases

Learning and Practice

  • Interactive Coding: Real-time code execution in lessons
  • Problem Solving: Test solutions against test cases
  • Algorithm Practice: Experiment with different approaches
  • Language Learning: Try new programming languages safely

Assessment and Evaluation

  • Coding Tests: Automated code evaluation
  • Interview Preparation: Practice coding interview problems
  • Skill Certification: Verify programming competencies
  • Competitive Programming: Practice contest problems

Development Tools

  • Code Snippets: Test small code fragments
  • Algorithm Testing: Verify algorithm correctness
  • Debugging: Step through code execution
  • Performance Analysis: Measure execution efficiency

🔧 Troubleshooting

Common Issues

  1. Timeout Errors: Code execution taking too long
  2. Memory Limits: Exceeding allocated memory
  3. Compilation Errors: Syntax or dependency issues
  4. Provider Failures: External service unavailability

Debugging Steps

# Check execution logs
tail -f /var/log/code-execution.log
 
# Test individual providers
curl -X POST /api/execute/test-provider/hackerEarth
 
# Monitor resource usage
docker stats code-execution-sandbox
 
# Check rate limits
GET /api/execute/quota

Performance Optimization

  • Caching: Cache frequently used code snippets
  • Pre-compilation: Compile common libraries ahead of time
  • Load Balancing: Distribute execution across multiple instances
  • Result Caching: Store results of identical executions

The code execution system is designed to be reliable, secure, and performant while supporting a wide range of programming languages and use cases for the CodePlanet platform.