|
53 | 53 | from ....sandbox.manifest import Manifest |
54 | 54 | from ....sandbox.session import SandboxSession, SandboxSessionState |
55 | 55 | from ....sandbox.session.base_sandbox_session import BaseSandboxSession |
| 56 | +from ....sandbox.session.bounded_read import collect_bounded |
56 | 57 | from ....sandbox.session.dependencies import Dependencies |
57 | 58 | from ....sandbox.session.manager import Instrumentation |
58 | 59 | from ....sandbox.session.mount_lifecycle import ( |
@@ -1265,6 +1266,43 @@ async def pty_terminate_all(self) -> None: |
1265 | 1266 | for entry in entries: |
1266 | 1267 | await self._terminate_pty_entry(entry) |
1267 | 1268 |
|
| 1269 | + async def _read_bounded(self, path: Path, *, max_bytes: int) -> bytes: |
| 1270 | + workspace_path = await self._validate_path_access(path) |
| 1271 | + url_path = quote(sandbox_path_str(workspace_path).lstrip("/"), safe="/") |
| 1272 | + async with self._session().get( |
| 1273 | + self._url(f"file/{url_path}"), timeout=self._request_timeout() |
| 1274 | + ) as response: |
| 1275 | + if response.status == 404: |
| 1276 | + raise WorkspaceReadNotFoundError(path=path) |
| 1277 | + if response.status != 200: |
| 1278 | + raise WorkspaceArchiveReadError( |
| 1279 | + path=path, |
| 1280 | + retryable=False |
| 1281 | + if response.status == 403 |
| 1282 | + else _cloudflare_retryability_for_status(response.status), |
| 1283 | + ) |
| 1284 | + # Existing Workers return either bytes or an SSE-encoded file. Bound |
| 1285 | + # the wire representation too, before the existing decoder allocates. |
| 1286 | + try: |
| 1287 | + prefix = await response.content.readexactly(7) |
| 1288 | + except asyncio.IncompleteReadError as error: |
| 1289 | + prefix = error.partial |
| 1290 | + if prefix != b"data: {": |
| 1291 | + if len(prefix) >= max_bytes: |
| 1292 | + return prefix[:max_bytes] |
| 1293 | + return prefix + await collect_bounded( |
| 1294 | + response.content.iter_chunked(65536), max_bytes - len(prefix) |
| 1295 | + ) |
| 1296 | + wire_limit = 8 * max_bytes + 65536 |
| 1297 | + body = prefix + await collect_bounded( |
| 1298 | + response.content.iter_chunked(65536), wire_limit + 1 - len(prefix) |
| 1299 | + ) |
| 1300 | + if len(body) > wire_limit: |
| 1301 | + raise WorkspaceArchiveReadError( |
| 1302 | + path=path, context={"reason": "bounded_read_wire_limit"} |
| 1303 | + ) |
| 1304 | + return self._decode_streamed_payload(body)[:max_bytes] |
| 1305 | + |
1268 | 1306 | async def read(self, path: Path | str, *, user: str | User | None = None) -> io.IOBase: |
1269 | 1307 | if user is not None: |
1270 | 1308 | await self._check_read_with_exec(path, user=user) |
|
0 commit comments