Spaces:
Sleeping

File size: 8,209 Bytes
ad10a6c
 
 
 
 
 
 
f9d554a
ad10a6c
 
 
 
 
 
 
 
f9d554a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad10a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d554a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad10a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d554a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad10a6c
 
f9d554a
 
ad10a6c
f9d554a
 
 
 
 
 
 
 
 
 
 
ad10a6c
7ae37d5
f9d554a
 
ad10a6c
f9d554a
ad10a6c
7ae37d5
ad10a6c
 
 
7ae37d5
ad10a6c
 
 
7ae37d5
 
 
 
 
 
ad10a6c
 
7ae37d5
ad10a6c
 
 
7ae37d5
ad10a6c
 
 
7ae37d5
 
 
 
 
 
ad10a6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""Code Sandbox Executor — compiles and runs programming snippets using Piston API.

Supports Python, JavaScript, C++, C, Java, and SQL out of the box with zero local overhead.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any, Optional
import httpx

logger = logging.getLogger(__name__)

PISTON_BASE_URL = "https://emkc.org/api/v2/piston"

# Shared, connection-pooled client for Piston calls — `execute()` runs once
# per test case, and exercise_service.py calls it in a loop for multi-test-case
# submissions, so a fresh TCP+TLS handshake per call compounds fast.
_piston_client: Optional[httpx.AsyncClient] = None
_piston_client_lock = asyncio.Lock()


async def _get_piston_client() -> httpx.AsyncClient:
    global _piston_client
    if _piston_client is None:
        async with _piston_client_lock:
            if _piston_client is None:
                _piston_client = httpx.AsyncClient(
                    limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
                )
    return _piston_client


async def close_piston_client() -> None:
    global _piston_client
    if _piston_client is not None:
        await _piston_client.aclose()
        _piston_client = None

# Shorthand mapping of common file extensions and language nicknames to Piston identifiers
LANGUAGE_MAP = {
    "py": "python",
    "python": "python",
    "js": "javascript",
    "javascript": "javascript",
    "ts": "typescript",
    "typescript": "typescript",
    "cpp": "c++",
    "c++": "c++",
    "c": "c",
    "java": "java",
    "sql": "sqlite3",
    "sqlite": "sqlite3",
    "sqlite3": "sqlite3",
    "go": "go",
    "rust": "rust",
    "rs": "rust",
    "bash": "bash",
    "sh": "bash",
}

# Fallback versions in case dynamic fetching fails
FALLBACK_VERSIONS = {
    "python": "3.10.0",
    "javascript": "18.15.0",
    "typescript": "5.0.3",
    "c++": "10.2.0",
    "c": "10.2.0",
    "java": "15.0.2",
    "sqlite3": "3.36.0",
    "go": "1.16.2",
    "rust": "1.68.2",
    "bash": "5.2.0",
}

class CodeExecutor:
    """Manages secure sandbox execution of code snippets via the Piston API."""

    _runtimes_cache: dict[str, str] = {}  # maps language identifier -> latest version

    @classmethod
    async def _fetch_latest_versions(cls) -> dict[str, str]:
        """Fetch all available runtimes from Piston and cache the latest version for each language."""
        if cls._runtimes_cache:
            return cls._runtimes_cache

        try:
            client = await _get_piston_client()
            resp = await client.get(f"{PISTON_BASE_URL}/runtimes", timeout=5.0)
            if resp.status_code == 200:
                runtimes = resp.json()
                new_cache: dict[str, str] = {}
                for r in runtimes:
                    lang = r.get("language")
                    version = r.get("version")
                    if lang and version:
                        # Keep the highest version if multiple exist
                        if lang not in new_cache or version > new_cache[lang]:
                            new_cache[lang] = version
                cls._runtimes_cache = new_cache
                logger.info("Successfully fetched and cached %d Piston language runtimes.", len(cls._runtimes_cache))
                return cls._runtimes_cache
        except Exception as exc:
            logger.warning("Failed to fetch dynamic Piston runtimes, falling back to static map. Error: %s", exc)

        return FALLBACK_VERSIONS

    @classmethod
    def get_filename(cls, language: str) -> str:
        """Get standard entrypoint filename for the given language."""
        exts = {
            "python": "main.py",
            "javascript": "index.js",
            "typescript": "index.ts",
            "c++": "main.cpp",
            "c": "main.c",
            "java": "Main.java",
            "sqlite3": "query.sql",
            "go": "main.go",
            "rust": "main.rs",
            "bash": "script.sh",
        }
        return exts.get(language, "main.txt")

    @classmethod
    async def execute(
        cls,
        language_or_alias: str,
        code: str,
        stdin: Optional[str] = None,
        args: Optional[list[str]] = None,
    ) -> dict[str, Any]:
        """Send a code snippet to the Piston API and return execution stdout/stderr and status metrics."""
        # Standardize language identifier
        alias = language_or_alias.lower().strip()
        piston_lang = LANGUAGE_MAP.get(alias, alias)

        # Get language version
        runtimes = await cls._fetch_latest_versions()
        version = runtimes.get(piston_lang) or FALLBACK_VERSIONS.get(piston_lang, "*")

        filename = cls.get_filename(piston_lang)

        payload = {
            "language": piston_lang,
            "version": version,
            "files": [
                {
                    "name": filename,
                    "content": code,
                }
            ],
            "stdin": stdin or "",
            "args": args or [],
        }

        try:
            client = await _get_piston_client()
            resp = await client.post(f"{PISTON_BASE_URL}/execute", json=payload, timeout=15.0)
            if resp.status_code == 200:
                res = resp.json()
                run_result = res.get("run", {})
                compile_result = res.get("compile", {})

                # Extract exit code and output
                exit_code = run_result.get("code", 0)
                stdout = run_result.get("stdout", "")
                stderr = run_result.get("stderr", "")
                signal = run_result.get("signal")

                # If compiling failed, prioritize compilation errors
                compile_stderr = compile_result.get("stderr", "")
                if compile_stderr:
                    stderr = compile_stderr + ("\n" + stderr if stderr else "")
                    exit_code = compile_result.get("code", exit_code)

                return {
                    "success": exit_code == 0 and not stderr,
                    "stdout": stdout,
                    "stderr": stderr,
                    "exit_code": exit_code,
                    "language": piston_lang,
                    "version": res.get("version", version),
                    "run": {
                        "stdout": stdout,
                        "stderr": stderr,
                        "code": exit_code,
                        "signal": signal,
                    }
                }
            else:
                err_msg = f"Execution server returned HTTP status {resp.status_code}: {resp.text}"
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": err_msg,
                    "exit_code": -1,
                    "language": piston_lang,
                    "version": version,
                    "run": {
                        "stdout": "",
                        "stderr": err_msg,
                        "code": -1,
                        "signal": None,
                    }
                }
        except httpx.TimeoutException:
            timeout_msg = "Execution timed out (sandbox limit reached)."
            return {
                "success": False,
                "stdout": "",
                "stderr": timeout_msg,
                "exit_code": -2,
                "language": piston_lang,
                "version": version,
                "run": {
                    "stdout": "",
                    "stderr": timeout_msg,
                    "code": -2,
                    "signal": None,
                }
            }
        except Exception as exc:
            fail_msg = f"Failed to execute code: {str(exc)}"
            return {
                "success": False,
                "stdout": "",
                "stderr": fail_msg,
                "exit_code": -3,
                "language": piston_lang,
                "version": version,
                "run": {
                    "stdout": "",
                    "stderr": fail_msg,
                    "code": -3,
                    "signal": None,
                }
            }