-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathsandbox.py
More file actions
1449 lines (1299 loc) · 54 KB
/
sandbox.py
File metadata and controls
1449 lines (1299 loc) · 54 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Cloudflare sandbox (https://developers.cloudflare.com/sandbox/) implementation.
This module provides a Cloudflare Worker-backed sandbox client/session implementation.
The sandbox communicates with a Cloudflare Worker service over HTTP and WebSocket.
Note: The `aiohttp` dependency is intended to be optional (installed via an extra),
so package-level exports should guard imports of this module. Within this module,
we import aiohttp normally so IDEs can resolve and navigate types.
"""
from __future__ import annotations
import asyncio
import base64
import io
import json
import logging
import os
import shlex
import time
import uuid
from collections import deque
from contextlib import suppress
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
from urllib.parse import quote
import aiohttp
from ....sandbox.errors import (
ConfigurationError,
ErrorCode,
ExecTimeoutError,
ExecTransportError,
ExposedPortUnavailableError,
MountConfigError,
WorkspaceArchiveReadError,
WorkspaceArchiveWriteError,
WorkspaceReadNotFoundError,
WorkspaceStartError,
WorkspaceWriteTypeError,
)
from ....sandbox.manifest import Manifest
from ....sandbox.session import SandboxSession, SandboxSessionState
from ....sandbox.session.base_sandbox_session import BaseSandboxSession
from ....sandbox.session.dependencies import Dependencies
from ....sandbox.session.manager import Instrumentation
from ....sandbox.session.pty_types import (
PTY_PROCESSES_MAX,
PTY_PROCESSES_WARNING,
PtyExecUpdate,
allocate_pty_process_id,
clamp_pty_yield_time_ms,
process_id_to_prune_from_meta,
resolve_pty_write_yield_time_ms,
truncate_text_by_tokens,
)
from ....sandbox.session.runtime_helpers import RESOLVE_WORKSPACE_PATH_HELPER, RuntimeHelperScript
from ....sandbox.session.sandbox_client import BaseSandboxClient, BaseSandboxClientOptions
from ....sandbox.snapshot import SnapshotBase, SnapshotSpec, resolve_snapshot
from ....sandbox.types import ExecResult, ExposedPortEndpoint, User
from ....sandbox.util.retry import (
TRANSIENT_HTTP_STATUS_CODES,
exception_chain_has_status_code,
retry_async,
)
from ....sandbox.util.tar_utils import UnsafeTarMemberError, validate_tar_bytes
_DEFAULT_EXEC_TIMEOUT_S = 30.0
_DEFAULT_REQUEST_TIMEOUT_S = 120.0
logger = logging.getLogger(__name__)
def _is_transient_workspace_error(exc: BaseException) -> bool:
"""Return True if *exc* is a workspace archive error caused by a transient HTTP status."""
if not isinstance(exc, WorkspaceArchiveReadError | WorkspaceArchiveWriteError):
return False
status = exc.context.get("http_status")
return isinstance(status, int) and status in TRANSIENT_HTTP_STATUS_CODES
@dataclass
class _ServerSentEvent:
event: str = "message"
data: str = ""
id: str = ""
retry: int | None = None
class _SSELineDecoder:
_buf: bytes
def __init__(self) -> None:
self._buf = b""
def decode(self, text: str) -> list[str]:
raw = self._buf + text.encode("utf-8")
self._buf = b""
lines: list[str] = []
i = 0
length = len(raw)
while i < length:
cr = raw.find(b"\r", i)
lf = raw.find(b"\n", i)
if cr == -1 and lf == -1:
self._buf = raw[i:]
break
if cr != -1 and (lf == -1 or cr < lf):
line = raw[i:cr]
if cr + 1 < length and raw[cr + 1 : cr + 2] == b"\n":
i = cr + 2
elif cr + 1 == length:
self._buf = b"\r"
lines.append(line.decode("utf-8"))
break
else:
i = cr + 1
lines.append(line.decode("utf-8"))
else:
line = raw[i:lf]
i = lf + 1
lines.append(line.decode("utf-8"))
return lines
def flush(self) -> list[str]:
buf = self._buf
self._buf = b""
if buf == b"\r":
return [""]
if buf:
return [buf.decode("utf-8")]
return []
class _SSEDecoder:
_event: str | None
_data: list[str]
_last_event_id: str | None
_retry: int | None
def __init__(self) -> None:
self._event = None
self._data = []
self._last_event_id = None
self._retry = None
def decode(self, line: str) -> _ServerSentEvent | None:
if not line:
if (
not self._event
and not self._data
and self._last_event_id is None
and self._retry is None
):
return None
sse = _ServerSentEvent(
event=self._event or "message",
data="\n".join(self._data),
id=self._last_event_id or "",
retry=self._retry,
)
self._event = None
self._data = []
self._retry = None
return sse
if line.startswith(":"):
return None
fieldname, _, value = line.partition(":")
if value.startswith(" "):
value = value[1:]
if fieldname == "event":
self._event = value
elif fieldname == "data":
self._data.append(value)
elif fieldname == "id":
if "\0" not in value:
self._last_event_id = value
elif fieldname == "retry":
try:
self._retry = int(value)
except (TypeError, ValueError):
pass
return None
class CloudflareSandboxClientOptions(BaseSandboxClientOptions):
"""Options for ``CloudflareSandboxClient``."""
type: Literal["cloudflare"] = "cloudflare"
worker_url: str
api_key: str | None = None
exposed_ports: tuple[int, ...] = ()
def __init__(
self,
worker_url: str,
api_key: str | None = None,
exposed_ports: tuple[int, ...] = (),
*,
type: Literal["cloudflare"] = "cloudflare",
) -> None:
super().__init__(
type=type,
worker_url=worker_url,
api_key=api_key,
exposed_ports=exposed_ports,
)
class CloudflareSandboxSessionState(SandboxSessionState):
type: Literal["cloudflare"] = "cloudflare"
worker_url: str
sandbox_id: str
@dataclass
class _CloudflarePtyProcessEntry:
"""Per-process state for a Cloudflare WebSocket PTY session."""
ws: aiohttp.ClientWebSocketResponse
tty: bool
last_used: float = field(default_factory=time.monotonic)
output_chunks: deque[bytes] = field(default_factory=deque)
output_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
output_notify: asyncio.Event = field(default_factory=asyncio.Event)
output_closed: asyncio.Event = field(default_factory=asyncio.Event)
pump_task: asyncio.Task[None] | None = None
exit_code: int | None = None
class CloudflareSandboxSession(BaseSandboxSession):
"""``BaseSandboxSession`` backed by a Cloudflare Worker over HTTP."""
state: CloudflareSandboxSessionState
_api_key: str | None
_http: aiohttp.ClientSession | None
_exec_timeout_s: float | None
_request_timeout_s: float | None
_pty_lock: asyncio.Lock
_pty_processes: dict[int, _CloudflarePtyProcessEntry]
_reserved_pty_process_ids: set[int]
# Tracks whether the worker was running when resume began so snapshot restore can
# detach any active ephemeral mounts before hydrating the workspace.
_restore_workspace_was_running: bool
def __init__(
self,
*,
state: CloudflareSandboxSessionState,
http: aiohttp.ClientSession | None = None,
api_key: str | None = None,
exec_timeout_s: float | None = None,
request_timeout_s: float | None = None,
) -> None:
self.state = state
self._api_key = api_key
self._http = http
self._exec_timeout_s = exec_timeout_s
self._request_timeout_s = request_timeout_s
self._pty_lock = asyncio.Lock()
self._pty_processes = {}
self._reserved_pty_process_ids = set()
self._restore_workspace_was_running = False
@classmethod
def from_state(
cls,
state: CloudflareSandboxSessionState,
*,
http: aiohttp.ClientSession | None = None,
exec_timeout_s: float | None = None,
request_timeout_s: float | None = None,
) -> CloudflareSandboxSession:
return cls(
state=state,
http=http,
exec_timeout_s=exec_timeout_s,
request_timeout_s=request_timeout_s,
)
def _session(self) -> aiohttp.ClientSession:
if self._http is None or self._http.closed:
headers: dict[str, str] = {}
if api_key := self._api_key or os.environ.get("CLOUDFLARE_SANDBOX_API_KEY"):
headers["Authorization"] = f"Bearer {api_key}"
self._http = aiohttp.ClientSession(headers=headers)
return self._http
def _url(self, path: str) -> str:
base = self.state.worker_url.rstrip("/")
return f"{base}/v1/sandbox/{self.state.sandbox_id}/{path.lstrip('/')}"
def _ws_pty_url(self, *, cols: int = 80, rows: int = 24) -> str:
base = self.state.worker_url.rstrip("/")
if base.startswith("https://"):
ws_base = f"wss://{base.removeprefix('https://')}"
elif base.startswith("http://"):
ws_base = f"ws://{base.removeprefix('http://')}"
else:
ws_base = base
return f"{ws_base}/v1/sandbox/{self.state.sandbox_id}/pty?cols={cols}&rows={rows}"
def _runtime_helpers(self) -> tuple[RuntimeHelperScript, ...]:
return (RESOLVE_WORKSPACE_PATH_HELPER,)
def _current_runtime_helper_cache_key(self) -> object | None:
return self.state.sandbox_id
async def _validate_path_access(self, path: Path | str, *, for_write: bool = False) -> Path:
return await self._validate_remote_path_access(path, for_write=for_write)
async def _resolve_exposed_port(self, port: int) -> ExposedPortEndpoint:
"""Cloudflare sandboxes do not yet support exposed port resolution."""
raise ExposedPortUnavailableError(
port=port,
exposed_ports=self.state.exposed_ports,
reason="backend_unavailable",
context={
"backend": "cloudflare",
"detail": (
"The Cloudflare sandbox worker does not currently expose "
"a port-resolution endpoint. Exposed port support requires "
"a compatible worker deployment."
),
},
)
async def mount_bucket(
self,
*,
bucket: str,
mount_path: Path | str,
options: dict[str, object],
) -> None:
workspace_path = self.normalize_path(mount_path)
http = self._session()
url = self._url("mount")
payload = {
"bucket": bucket,
"mountPath": str(workspace_path),
"options": options,
}
try:
async with http.post(
url,
json=payload,
timeout=self._request_timeout(),
) as resp:
if resp.status != 200:
body: dict[str, Any] = {}
try:
body = await resp.json(content_type=None)
except Exception:
pass
raise MountConfigError(
message="cloudflare bucket mount failed",
context={
"bucket": bucket,
"mount_path": str(workspace_path),
"http_status": resp.status,
"reason": body.get("error", f"HTTP {resp.status}"),
},
)
except MountConfigError:
raise
except aiohttp.ClientError as e:
raise MountConfigError(
message="cloudflare bucket mount failed",
context={
"bucket": bucket,
"mount_path": str(workspace_path),
"cause_type": type(e).__name__,
"reason": str(e),
},
) from e
async def unmount_bucket(self, mount_path: Path | str) -> None:
workspace_path = self.normalize_path(mount_path)
http = self._session()
url = self._url("unmount")
payload = {"mountPath": str(workspace_path)}
try:
async with http.post(
url,
json=payload,
timeout=self._request_timeout(),
) as resp:
if resp.status != 200:
body: dict[str, Any] = {}
try:
body = await resp.json(content_type=None)
except Exception:
pass
raise MountConfigError(
message="cloudflare bucket unmount failed",
context={
"mount_path": str(workspace_path),
"http_status": resp.status,
"reason": body.get("error", f"HTTP {resp.status}"),
},
)
except MountConfigError:
raise
except aiohttp.ClientError as e:
raise MountConfigError(
message="cloudflare bucket unmount failed",
context={
"mount_path": str(workspace_path),
"cause_type": type(e).__name__,
"reason": str(e),
},
) from e
async def _close_http(self) -> None:
if self._http is not None and not self._http.closed:
await self._http.close()
self._http = None
def _request_timeout(self) -> aiohttp.ClientTimeout:
total = (
self._request_timeout_s
if self._request_timeout_s is not None
else _DEFAULT_REQUEST_TIMEOUT_S
)
return aiohttp.ClientTimeout(total=total)
def _decode_streamed_payload(self, body: bytes) -> bytes:
if not body.startswith(b"data: {"):
return body
try:
text = body.decode("utf-8")
except UnicodeDecodeError:
return body
line_decoder = _SSELineDecoder()
sse_decoder = _SSEDecoder()
is_binary = False
chunks: list[bytes] = []
saw_metadata = False
saw_chunk = False
saw_complete = False
def _handle_event_payload(data: str) -> None:
nonlocal is_binary, saw_complete, saw_chunk, saw_metadata
message = json.loads(data)
msg_type = message.get("type")
if msg_type == "metadata":
is_binary = bool(message.get("isBinary", False))
saw_metadata = True
return
if msg_type == "chunk":
if not saw_metadata:
raise ValueError("chunk event received before metadata")
chunk = message.get("data", "")
if is_binary:
chunks.append(base64.b64decode(chunk))
else:
chunks.append(str(chunk).encode("utf-8"))
saw_chunk = True
return
if msg_type == "complete":
if not saw_metadata:
raise ValueError("complete event received before metadata")
saw_complete = True
return
try:
for line in line_decoder.decode(text):
event = sse_decoder.decode(line)
if event is not None and event.event == "message" and event.data:
_handle_event_payload(event.data)
for line in line_decoder.flush():
event = sse_decoder.decode(line)
if event is not None and event.event == "message" and event.data:
_handle_event_payload(event.data)
except (ValueError, json.JSONDecodeError):
return body
if not saw_metadata or (not saw_chunk and not saw_complete):
return body
if not saw_complete:
raise ValueError("SSE payload ended without complete event")
return b"".join(chunks)
async def _prepare_backend_workspace(self) -> None:
try:
root = Path(self.state.manifest.root)
await self._exec_internal("mkdir", "-p", "--", str(root))
except Exception as e:
raise WorkspaceStartError(path=Path(self.state.manifest.root), cause=e) from e
async def _can_reuse_restorable_snapshot_workspace(self) -> bool:
if not self._workspace_state_preserved_on_start():
self._restore_workspace_was_running = False
return False
is_running = await self.running()
self._restore_workspace_was_running = is_running
if not self._can_reuse_preserved_workspace_on_resume():
return False
return await self._can_skip_snapshot_restore_on_resume(is_running=is_running)
async def _restore_snapshot_into_workspace_on_resume(self) -> None:
root = Path(self.state.manifest.root)
detached_mounts: list[tuple[Any, Path]] = []
if self._restore_workspace_was_running:
for mount_entry, mount_path in self.state.manifest.ephemeral_mount_targets():
try:
await mount_entry.mount_strategy.teardown_for_snapshot(
mount_entry, self, mount_path
)
except Exception as e:
raise WorkspaceStartError(path=root, cause=e) from e
detached_mounts.append((mount_entry, mount_path))
workspace_archive: io.IOBase | None = None
try:
await self._clear_workspace_root_on_resume()
workspace_archive = await self.state.snapshot.restore(dependencies=self.dependencies)
await self._hydrate_workspace_via_http(workspace_archive)
except Exception:
for mount_entry, mount_path in reversed(detached_mounts):
try:
await mount_entry.mount_strategy.restore_after_snapshot(
mount_entry, self, mount_path
)
except Exception:
pass
raise
finally:
if workspace_archive is not None:
try:
workspace_archive.close()
except Exception:
pass
async def _after_stop(self) -> None:
await self._close_http()
async def _shutdown_backend(self) -> None:
try:
http = self._session()
url = self.state.worker_url.rstrip("/") + f"/v1/sandbox/{self.state.sandbox_id}"
async with http.delete(url):
pass
except Exception:
logger.debug("Failed to delete Cloudflare sandbox on shutdown", exc_info=True)
async def _after_shutdown(self) -> None:
await self._close_http()
async def _exec_internal(
self,
*command: str | Path,
timeout: float | None = None,
) -> ExecResult:
argv = [str(c) for c in command]
envs = await self.state.manifest.environment.resolve()
if envs:
argv = ["env", *[f"{key}={value}" for key, value in sorted(envs.items())], *argv]
effective_timeout = (
timeout
if timeout is not None
else (
self._exec_timeout_s
if self._exec_timeout_s is not None
else _DEFAULT_EXEC_TIMEOUT_S
)
)
payload: dict[str, Any] = {"argv": argv}
if effective_timeout is not None:
payload["timeout_ms"] = int(effective_timeout * 1000)
http = self._session()
url = self._url("exec")
try:
request_timeout = aiohttp.ClientTimeout(
total=effective_timeout + 5.0 if effective_timeout is not None else None
)
async with http.post(url, json=payload, timeout=request_timeout) as resp:
if resp.status != 200:
body: dict[str, Any] = {}
try:
body = await resp.json(content_type=None)
except Exception:
pass
msg = body.get("error", f"HTTP {resp.status}")
raise ExecTransportError(command=tuple(argv), cause=Exception(msg))
stdout_parts: list[bytes] = []
stderr_parts: list[bytes] = []
line_decoder = _SSELineDecoder()
sse_decoder = _SSEDecoder()
async for chunk in resp.content.iter_any():
text = chunk.decode("utf-8")
for line in line_decoder.decode(text):
event = sse_decoder.decode(line)
if event is None:
continue
if event.event == "stdout":
stdout_parts.append(base64.b64decode(event.data))
elif event.event == "stderr":
stderr_parts.append(base64.b64decode(event.data))
elif event.event == "exit":
exit_data = json.loads(event.data)
return ExecResult(
stdout=b"".join(stdout_parts),
stderr=b"".join(stderr_parts),
exit_code=int(exit_data["exit_code"]),
)
elif event.event == "error":
err_data = json.loads(event.data)
raise ExecTransportError(
command=tuple(argv),
cause=Exception(err_data.get("error", "unknown error")),
)
for line in line_decoder.flush():
event = sse_decoder.decode(line)
if event is None:
continue
if event.event == "stdout":
stdout_parts.append(base64.b64decode(event.data))
elif event.event == "stderr":
stderr_parts.append(base64.b64decode(event.data))
elif event.event == "exit":
exit_data = json.loads(event.data)
return ExecResult(
stdout=b"".join(stdout_parts),
stderr=b"".join(stderr_parts),
exit_code=int(exit_data["exit_code"]),
)
elif event.event == "error":
err_data = json.loads(event.data)
raise ExecTransportError(
command=tuple(argv),
cause=Exception(err_data.get("error", "unknown error")),
)
raise ExecTransportError(
command=tuple(argv),
cause=Exception("SSE stream ended without exit event"),
)
except asyncio.TimeoutError as e:
raise ExecTimeoutError(command=tuple(argv), timeout_s=effective_timeout, cause=e) from e
except (ExecTimeoutError, ExecTransportError):
raise
except aiohttp.ClientError as e:
raise ExecTransportError(command=tuple(argv), cause=e) from e
except Exception as e:
raise ExecTransportError(command=tuple(argv), cause=e) from e
def supports_pty(self) -> bool:
return True
async def _pump_ws_output(self, entry: _CloudflarePtyProcessEntry) -> None:
try:
while True:
msg = await entry.ws.receive()
if msg.type == aiohttp.WSMsgType.BINARY:
async with entry.output_lock:
entry.output_chunks.append(msg.data)
entry.output_notify.set()
continue
if msg.type == aiohttp.WSMsgType.TEXT:
try:
payload = json.loads(msg.data)
except json.JSONDecodeError:
logger.debug("Ignoring non-JSON PTY text frame: %s", msg.data)
continue
msg_type = payload.get("type")
if msg_type == "ready":
continue
if msg_type == "exit":
code = payload.get("code")
entry.exit_code = code if isinstance(code, int) else None
entry.output_closed.set()
entry.output_notify.set()
break
if msg_type == "error":
logger.warning("Cloudflare PTY error frame: %s", payload.get("message"))
entry.output_closed.set()
entry.output_notify.set()
break
continue
if msg.type in (
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSING,
aiohttp.WSMsgType.CLOSED,
aiohttp.WSMsgType.ERROR,
):
entry.output_closed.set()
entry.output_notify.set()
break
except asyncio.CancelledError:
raise
except Exception:
logger.debug("Cloudflare PTY pump ended with an exception", exc_info=True)
entry.output_closed.set()
entry.output_notify.set()
async def _collect_pty_output(
self,
*,
entry: _CloudflarePtyProcessEntry,
yield_time_ms: int,
max_output_tokens: int | None,
) -> tuple[bytes, int | None]:
deadline = time.monotonic() + (yield_time_ms / 1000)
output = bytearray()
while True:
async with entry.output_lock:
while entry.output_chunks:
output.extend(entry.output_chunks.popleft())
if entry.output_closed.is_set():
async with entry.output_lock:
while entry.output_chunks:
output.extend(entry.output_chunks.popleft())
break
remaining_s = deadline - time.monotonic()
if remaining_s <= 0:
break
try:
await asyncio.wait_for(entry.output_notify.wait(), timeout=remaining_s)
except asyncio.TimeoutError:
break
entry.output_notify.clear()
text = output.decode("utf-8", errors="replace")
truncated_text, original_token_count = truncate_text_by_tokens(text, max_output_tokens)
return truncated_text.encode("utf-8", errors="replace"), original_token_count
async def _finalize_pty_update(
self,
*,
process_id: int,
entry: _CloudflarePtyProcessEntry,
output: bytes,
original_token_count: int | None,
) -> PtyExecUpdate:
exit_code = entry.exit_code if entry.output_closed.is_set() else None
live_process_id: int | None = process_id
if entry.output_closed.is_set():
async with self._pty_lock:
removed = self._pty_processes.pop(process_id, None)
self._reserved_pty_process_ids.discard(process_id)
if removed is not None:
await self._terminate_pty_entry(removed)
live_process_id = None
return PtyExecUpdate(
process_id=live_process_id,
output=output,
exit_code=exit_code,
original_token_count=original_token_count,
)
async def _prune_pty_processes_if_needed(self) -> _CloudflarePtyProcessEntry | None:
if len(self._pty_processes) < PTY_PROCESSES_MAX:
return None
meta = [
(process_id, entry.last_used, entry.output_closed.is_set())
for process_id, entry in self._pty_processes.items()
]
process_id_to_prune = process_id_to_prune_from_meta(meta)
if process_id_to_prune is None:
return None
self._reserved_pty_process_ids.discard(process_id_to_prune)
return self._pty_processes.pop(process_id_to_prune, None)
async def _terminate_pty_entry(self, entry: _CloudflarePtyProcessEntry) -> None:
with suppress(Exception):
await entry.ws.close()
if entry.pump_task is None:
return
entry.pump_task.cancel()
with suppress(asyncio.CancelledError):
await entry.pump_task
async def _cleanup_unregistered_pty(
self,
entry: _CloudflarePtyProcessEntry | None,
ws: aiohttp.ClientWebSocketResponse | None,
registered: bool,
) -> None:
"""Best-effort cleanup of a PTY WebSocket or entry that was never registered."""
if entry is not None and not registered:
await self._terminate_pty_entry(entry)
elif ws is not None and not registered:
with suppress(Exception):
await ws.close()
async def pty_exec_start(
self,
*command: str | Path,
timeout: float | None = None,
shell: bool | list[str] = True,
user: str | User | None = None,
tty: bool = False,
yield_time_s: float | None = None,
max_output_tokens: int | None = None,
) -> PtyExecUpdate:
_ = timeout
sanitized_command = self._prepare_exec_command(*command, shell=shell, user=user)
command_text = shlex.join(str(part) for part in sanitized_command)
ws: aiohttp.ClientWebSocketResponse | None = None
entry: _CloudflarePtyProcessEntry | None = None
registered = False
pruned_entry: _CloudflarePtyProcessEntry | None = None
process_id = 0
process_count = 0
try:
ws = await self._session().ws_connect(self._ws_pty_url())
ready_deadline = time.monotonic() + 30.0
while True:
remaining_s = ready_deadline - time.monotonic()
if remaining_s <= 0:
raise asyncio.TimeoutError()
msg = await asyncio.wait_for(ws.receive(), timeout=remaining_s)
if msg.type == aiohttp.WSMsgType.TEXT:
try:
payload = json.loads(msg.data)
except json.JSONDecodeError:
continue
if payload.get("type") == "ready":
break
elif msg.type == aiohttp.WSMsgType.BINARY:
continue
elif msg.type in (
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSING,
aiohttp.WSMsgType.CLOSED,
aiohttp.WSMsgType.ERROR,
):
raise ExecTransportError(
command=tuple(str(part) for part in command),
cause=Exception("WebSocket closed before PTY ready"),
)
entry = _CloudflarePtyProcessEntry(ws=ws, tty=tty)
entry.pump_task = asyncio.create_task(self._pump_ws_output(entry))
await ws.send_bytes(f"{command_text}\n".encode())
async with self._pty_lock:
process_id = allocate_pty_process_id(self._reserved_pty_process_ids)
self._reserved_pty_process_ids.add(process_id)
pruned_entry = await self._prune_pty_processes_if_needed()
self._pty_processes[process_id] = entry
registered = True
process_count = len(self._pty_processes)
except asyncio.TimeoutError as e:
await self._cleanup_unregistered_pty(entry, ws, registered)
raise ExecTimeoutError(
command=tuple(str(part) for part in command),
timeout_s=30.0,
cause=e,
) from e
except asyncio.CancelledError:
await self._cleanup_unregistered_pty(entry, ws, registered)
raise
except ExecTransportError:
await self._cleanup_unregistered_pty(entry, ws, registered)
raise
except Exception as e:
await self._cleanup_unregistered_pty(entry, ws, registered)
raise ExecTransportError(command=tuple(str(part) for part in command), cause=e) from e
if pruned_entry is not None:
await self._terminate_pty_entry(pruned_entry)
if process_count >= PTY_PROCESSES_WARNING:
logger.warning(
"PTY process count reached warning threshold: %s active sessions",
process_count,
)
yield_time_ms = 10_000 if yield_time_s is None else int(yield_time_s * 1000)
output, original_token_count = await self._collect_pty_output(
entry=entry,
yield_time_ms=clamp_pty_yield_time_ms(yield_time_ms),
max_output_tokens=max_output_tokens,
)
return await self._finalize_pty_update(
process_id=process_id,
entry=entry,
output=output,
original_token_count=original_token_count,
)
async def pty_write_stdin(
self,
*,
session_id: int,
chars: str,
yield_time_s: float | None = None,
max_output_tokens: int | None = None,
) -> PtyExecUpdate:
async with self._pty_lock:
entry = self._resolve_pty_session_entry(
pty_processes=self._pty_processes,
session_id=session_id,
)
if chars:
if not entry.tty:
raise RuntimeError("stdin is not available for this process")
await entry.ws.send_bytes(chars.encode("utf-8"))
await asyncio.sleep(0.1)
yield_time_ms = 250 if yield_time_s is None else int(yield_time_s * 1000)
output, original_token_count = await self._collect_pty_output(
entry=entry,
yield_time_ms=resolve_pty_write_yield_time_ms(
yield_time_ms=yield_time_ms,
input_empty=chars == "",
),
max_output_tokens=max_output_tokens,
)
entry.last_used = time.monotonic()
return await self._finalize_pty_update(
process_id=session_id,
entry=entry,
output=output,
original_token_count=original_token_count,
)
async def pty_terminate_all(self) -> None:
async with self._pty_lock:
entries = list(self._pty_processes.values())
self._pty_processes.clear()
self._reserved_pty_process_ids.clear()
for entry in entries:
await self._terminate_pty_entry(entry)
async def read(self, path: Path | str, *, user: str | User | None = None) -> io.IOBase:
path = Path(path)
if user is not None:
await self._check_read_with_exec(path, user=user)
workspace_path = await self._validate_path_access(path)
http = self._session()
url_path = quote(str(workspace_path).lstrip("/"), safe="/")
url = self._url(f"file/{url_path}")
try:
async with http.get(url, timeout=self._request_timeout()) as resp:
if resp.status == 404:
body: dict[str, Any] = {}
try:
body = await resp.json(content_type=None)
except Exception:
pass
raise WorkspaceReadNotFoundError(
path=workspace_path,
context={"message": body.get("error", "not found")},
)
if resp.status == 403:
body = {}
try:
body = await resp.json(content_type=None)
except Exception:
pass
raise WorkspaceArchiveReadError(
path=workspace_path,
context={
"reason": "path_escape",
"http_status": resp.status,
"message": body.get("error", "path escapes /workspace"),