-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathmessaging.py
More file actions
394 lines (334 loc) · 13.4 KB
/
messaging.py
File metadata and controls
394 lines (334 loc) · 13.4 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import datetime
import json
import logging
import uuid
import asyncio
import subprocess
from asyncio import Queue
from envs import get_envs
from typing import (
Dict,
Optional,
Union,
)
from pydantic import StrictStr
from websockets.client import WebSocketClientProtocol, connect
from api.models.error import Error
from api.models.logs import Stdout, Stderr
from api.models.result import Result
from api.models.output import (
EndOfExecution,
NumberOfExecutions,
OutputType,
UnexpectedEndOfExecution,
)
from errors import ExecutionError
logger = logging.getLogger(__name__)
compile_typescript_cmd = "/usr/lib/node_modules/@swc/cli/bin/swc.js --config-file /root/.ts.swcrc --filename index.ts"
class Execution:
def __init__(self, in_background: bool = False):
self.queue = Queue[
Union[
Result,
Error,
Stdout,
Stderr,
EndOfExecution,
NumberOfExecutions,
UnexpectedEndOfExecution,
]
]()
self.input_accepted = False
self.errored = False
self.in_background = in_background
class ContextWebSocket:
_ws: Optional[WebSocketClientProtocol] = None
_receive_task: Optional[asyncio.Task] = None
def __init__(
self,
context_id: str,
session_id: str,
language: str,
cwd: str,
):
self.language = language
self.cwd = cwd
self.context_id = context_id
self.url = f"ws://localhost:8888/api/kernels/{context_id}/channels"
self.session_id = session_id
self._executions: Dict[str, Execution] = {}
self._lock = asyncio.Lock()
async def connect(self):
logger.debug(f"WebSocket connecting to {self.url}")
ws_logger = logger.getChild("websockets.client")
ws_logger.setLevel(logging.ERROR)
self._ws = await connect(
self.url,
max_size=None,
max_queue=None,
logger=ws_logger,
)
logger.info(f"WebSocket connected to {self.url}")
self._receive_task = asyncio.create_task(
self._receive_message(),
name="receive_message",
)
def _get_execute_request(
self, msg_id: str, code: Union[str, StrictStr], background: bool
) -> str:
return json.dumps(
{
"header": {
"msg_id": msg_id,
"username": "e2b",
"session": self.session_id,
"msg_type": "execute_request",
"version": "5.3",
"date": datetime.datetime.now(datetime.timezone.utc).isoformat(),
},
"parent_header": {},
"metadata": {
"trusted": True,
"deletedCells": [],
"recordTiming": False,
"cellId": str(uuid.uuid4()),
},
"content": {
"code": code,
"silent": background,
"store_history": True,
"user_expressions": {},
"stop_on_error": True,
"allow_stdin": False,
},
}
)
async def _wait_for_result(self, message_id: str):
queue = self._executions[message_id].queue
while True:
output = await queue.get()
if output.type == OutputType.END_OF_EXECUTION:
break
if output.type == OutputType.UNEXPECTED_END_OF_EXECUTION:
logger.error(f"Unexpected end of execution for code ({message_id})")
yield Error(
name="UnexpectedEndOfExecution",
value="Connection to the execution was closed before the execution was finished",
traceback="",
)
break
yield output.model_dump(exclude_none=True)
async def change_current_directory(
self, path: Union[str, StrictStr], language: str
):
message_id = str(uuid.uuid4())
self._executions[message_id] = Execution(in_background=True)
if language == "python":
request = self._get_execute_request(message_id, f"%cd {path}", True)
elif language == "deno":
request = self._get_execute_request(
message_id, f"Deno.chdir('{path}')", True
)
elif language == "js":
request = self._get_execute_request(
message_id, f"process.chdir('{path}')", True
)
elif language == "r":
request = self._get_execute_request(message_id, f"setwd('{path}')", True)
elif language == "java":
request = self._get_execute_request(
message_id, f"System.setProperty('user.dir', '{path}')", True
)
else:
return
await self._ws.send(request)
async for item in self._wait_for_result(message_id):
if item["type"] == "error":
raise ExecutionError(f"Error during execution: {item}")
async def execute(
self,
code: Union[str, StrictStr],
env_vars: Dict[StrictStr, str] = None,
):
message_id = str(uuid.uuid4())
logger.debug(f"Sending code for the execution ({message_id}): {code}")
self._executions[message_id] = Execution()
if self._ws is None:
raise Exception("WebSocket not connected")
global_env_vars = get_envs()
env_vars = {**global_env_vars, **env_vars} if env_vars else global_env_vars
async with self._lock:
if env_vars:
vars_to_set = {**global_env_vars, **env_vars}
# if there is an indent in the code, we need to add the env vars at the beginning of the code
lines = code.split("\n")
indent = 0
for i, line in enumerate(lines):
if line.strip() != "":
indent = len(line) - len(line.lstrip())
break
if self.language == "python":
code = (
indent * " "
+ f"os.environ.set_envs_for_execution({vars_to_set})\n"
+ code
)
if self.language == "typescript":
logger.info("Compiling TypeScript: %s", code)
# call swc to compile the typescript code
compile_result = subprocess.run(compile_typescript_cmd.split(), input=code.encode(), capture_output=True)
if compile_result.returncode != 0:
logger.error("Error during TypeScript compilation: %s", compile_result.stderr.decode())
yield Error(
name="TypeScriptCompilerError",
value=compile_result.stderr.decode(),
traceback="",
)
return
code = compile_result.stdout.decode()
logger.info(code)
request = self._get_execute_request(message_id, code, False)
# Send the code for execution
await self._ws.send(request)
# Stream the results
async for item in self._wait_for_result(message_id):
yield item
del self._executions[message_id]
async def _receive_message(self):
if not self._ws:
logger.error("No WebSocket connection")
return
try:
async for message in self._ws:
await self._process_message(json.loads(message))
except Exception as e:
logger.error(f"WebSocket received error while receiving messages: {str(e)}")
async def _process_message(self, data: dict):
"""
Process messages from the WebSocket
Message types:
https://jupyter-client.readthedocs.io/en/stable/messaging.html
:param data: The message data
"""
if (
data["msg_type"] == "status"
and data["content"]["execution_state"] == "restarting"
):
logger.error("Context is restarting")
for execution in self._executions.values():
await execution.queue.put(
Error(
name="ContextRestarting",
value="Context was restarted",
traceback="",
)
)
await execution.queue.put(EndOfExecution())
return
parent_msg_ig = data["parent_header"].get("msg_id", None)
if parent_msg_ig is None:
logger.warning("Parent message ID not found. %s", data)
return
execution = self._executions.get(parent_msg_ig)
if not execution:
return
queue = execution.queue
if data["msg_type"] == "error":
logger.debug(
f"Execution {parent_msg_ig} finished execution with error: {data['content']['ename']}: {data['content']['evalue']}"
)
if execution.errored:
return
execution.errored = True
await queue.put(
Error(
name=data["content"]["ename"],
value=data["content"]["evalue"],
traceback="".join(data["content"]["traceback"]),
)
)
elif data["msg_type"] == "stream":
if data["content"]["name"] == "stdout":
logger.debug(f"Execution {parent_msg_ig} received stdout")
await queue.put(
Stdout(
text=data["content"]["text"], timestamp=data["header"]["date"]
)
)
elif data["content"]["name"] == "stderr":
logger.debug(f"Execution {parent_msg_ig} received stderr")
await queue.put(
Stderr(
text=data["content"]["text"], timestamp=data["header"]["date"]
)
)
elif data["msg_type"] in "display_data":
result = Result(is_main_result=False, data=data["content"]["data"])
logger.debug(
f"Execution {parent_msg_ig} received display data with following formats: {result.formats()}"
)
await queue.put(result)
elif data["msg_type"] == "execute_result":
result = Result(is_main_result=True, data=data["content"]["data"])
logger.debug(
f"Execution {parent_msg_ig} received execution result with following formats: {result.formats()}"
)
await queue.put(result)
elif data["msg_type"] == "status":
if data["content"]["execution_state"] == "busy" and execution.in_background:
logger.debug(f"Execution {parent_msg_ig} started execution")
execution.input_accepted = True
if data["content"]["execution_state"] == "idle":
if execution.input_accepted:
logger.debug(f"Execution {parent_msg_ig} finished execution")
await queue.put(EndOfExecution())
elif data["content"]["execution_state"] == "error":
logger.debug(f"Execution {parent_msg_ig} finished execution with error")
await queue.put(
Error(
name=data["content"]["ename"],
value=data["content"]["evalue"],
traceback="".join(data["content"]["traceback"]),
)
)
await queue.put(EndOfExecution())
elif data["msg_type"] == "execute_reply":
if data["content"]["status"] == "error":
logger.debug(f"Execution {parent_msg_ig} finished execution with error")
if execution.errored:
return
execution.errored = True
await queue.put(
Error(
name=data["content"].get("ename", ""),
value=data["content"].get("evalue", ""),
traceback="".join(data["content"].get("traceback", [])),
)
)
elif data["content"]["status"] == "abort":
logger.debug(f"Execution {parent_msg_ig} was aborted")
await queue.put(
Error(
name="ExecutionAborted",
value="Execution was aborted",
traceback="",
)
)
await queue.put(EndOfExecution())
elif data["content"]["status"] == "ok":
pass
elif data["msg_type"] == "execute_input":
logger.debug(f"Input accepted for {parent_msg_ig}")
await queue.put(
NumberOfExecutions(execution_count=data["content"]["execution_count"])
)
execution.input_accepted = True
else:
logger.warning(f"[UNHANDLED MESSAGE TYPE]: {data['msg_type']}")
async def close(self):
logger.debug(f"Closing WebSocket {self.context_id}")
if self._ws is not None:
await self._ws.close()
self._receive_task.cancel()
for execution in self._executions.values():
execution.queue.put_nowait(UnexpectedEndOfExecution())