File tree Expand file tree Collapse file tree 5 files changed +75
-13
lines changed Expand file tree Collapse file tree 5 files changed +75
-13
lines changed Original file line number Diff line number Diff line change @@ -213,6 +213,42 @@ To add Node.js dependencies:
213
213
214
214
---
215
215
216
+
217
+ ## Usage
218
+
219
+ ### 🐍 A Python example
220
+
221
+ ``` python
222
+ def main (arg1 : str , arg2 : str ) -> str :
223
+ return f " result: { arg1 + arg2} "
224
+ ```
225
+
226
+ ### 🟨 JavaScript examples
227
+
228
+ A simple sync function
229
+
230
+ ``` javascript
231
+ function main ({arg1, arg2}) {
232
+ return arg1+ arg2
233
+ }
234
+ ```
235
+
236
+ Async funcion with aioxs
237
+
238
+ ``` javascript
239
+ const axios = require (' axios' );
240
+ async function main () {
241
+ try {
242
+ const response = await axios .get (' https://github.com/infiniflow/ragflow' );
243
+ return ' Body:' + response .data ;
244
+ } catch (error) {
245
+ return ' Error:' + error .message ;
246
+ }
247
+ }
248
+ ```
249
+
250
+ ---
251
+
216
252
## 📋 FAQ
217
253
218
254
### ❓Sandbox Not Working?
Original file line number Diff line number Diff line change 15
15
#
16
16
import base64
17
17
18
+ from core .container import _CONTAINER_EXECUTION_SEMAPHORES
18
19
from core .logger import logger
19
20
from fastapi import Request
20
- from models .enums import ResultStatus
21
+ from models .enums import ResultStatus , SupportLanguage
21
22
from models .schemas import CodeExecutionRequest , CodeExecutionResult
22
23
from services .execution import execute_code
23
24
from services .limiter import limiter
24
25
from services .security import analyze_code_security
25
- from core . container import _CONTAINER_EXECUTION_SEMAPHORES
26
+
26
27
27
28
async def healthz_handler ():
28
29
return {"status" : "ok" }
29
30
31
+
30
32
@limiter .limit ("5/second" )
31
33
async def run_code_handler (req : CodeExecutionRequest , request : Request ):
32
34
logger .info ("🟢 Received /run request" )
33
35
34
36
async with _CONTAINER_EXECUTION_SEMAPHORES [req .language ]:
35
37
code = base64 .b64decode (req .code_b64 ).decode ("utf-8" )
38
+ if req .language == SupportLanguage .NODEJS :
39
+ code += "\n \n module.exports = { main };"
40
+ req .code_b64 = base64 .b64encode (code .encode ("utf-8" )).decode ("utf-8" )
36
41
is_safe , issues = analyze_code_security (code , language = req .language )
37
42
if not is_safe :
38
43
issue_details = "\n " .join ([f"Line { lineno } : { issue } " for issue , lineno in issues ])
Original file line number Diff line number Diff line change 20
20
router = APIRouter ()
21
21
22
22
router .get ("/healthz" )(healthz_handler )
23
- router .post ("/run" )(run_code_handler )
23
+ router .post ("/run" )(run_code_handler )
24
+
Original file line number Diff line number Diff line change 26
26
27
27
_CONTAINER_QUEUES : dict [SupportLanguage , Queue ] = {}
28
28
_CONTAINER_LOCK : asyncio .Lock = asyncio .Lock ()
29
- _CONTAINER_EXECUTION_SEMAPHORES :dict [SupportLanguage ,asyncio .Semaphore ] = {}
29
+ _CONTAINER_EXECUTION_SEMAPHORES : dict [SupportLanguage , asyncio .Semaphore ] = {}
30
30
31
31
32
32
async def init_containers (size : int ) -> tuple [int , int ]:
@@ -38,7 +38,7 @@ async def init_containers(size: int) -> tuple[int, int]:
38
38
_CONTAINER_QUEUES [SupportLanguage .PYTHON ].get_nowait ()
39
39
while not _CONTAINER_QUEUES [SupportLanguage .NODEJS ].empty ():
40
40
_CONTAINER_QUEUES [SupportLanguage .NODEJS ].get_nowait ()
41
-
41
+
42
42
for language in SupportLanguage :
43
43
_CONTAINER_EXECUTION_SEMAPHORES [language ] = asyncio .Semaphore (size )
44
44
Original file line number Diff line number Diff line change @@ -82,20 +82,40 @@ async def execute_code(req: CodeExecutionRequest):
82
82
const path = require('path');
83
83
84
84
const args = JSON.parse(process.argv[2]);
85
-
86
85
const mainPath = path.join(__dirname, 'main.js');
87
86
87
+ function isPromise(value) {
88
+ return Boolean(value && typeof value.then === 'function');
89
+ }
90
+
88
91
if (fs.existsSync(mainPath)) {
89
- const { main } = require(mainPath);
92
+ const mod = require(mainPath);
93
+ const main = typeof mod === 'function' ? mod : mod.main;
94
+
95
+ if (typeof main !== 'function') {
96
+ console.error('Error: main is not a function');
97
+ process.exit(1);
98
+ }
90
99
91
100
if (typeof args === 'object' && args !== null) {
92
- main(args).then(result => {
93
- if (result !== null) {
94
- console.log(result);
101
+ try {
102
+ const result = main(args);
103
+ if (isPromise(result)) {
104
+ result.then(output => {
105
+ if (output !== null) {
106
+ console.log(output);
107
+ }
108
+ }).catch(err => {
109
+ console.error('Error in async main function:', err);
110
+ });
111
+ } else {
112
+ if (result !== null) {
113
+ console.log(result);
114
+ }
95
115
}
96
- }). catch(err => {
97
- console.error('Error in main function :', err);
98
- });
116
+ } catch (err) {
117
+ console.error('Error when executing main :', err);
118
+ }
99
119
} else {
100
120
console.error('Error: args is not a valid object:', args);
101
121
}
You can’t perform that action at this time.
0 commit comments