|
3 | 3 |
|
4 | 4 | from __future__ import annotations |
5 | 5 |
|
| 6 | +import asyncio |
6 | 7 | import base64 |
7 | 8 | import contextlib |
8 | 9 | import errno |
| 10 | +import functools |
9 | 11 | import ipaddress |
10 | 12 | import json |
11 | 13 | import math |
|
17 | 19 | import time |
18 | 20 | from collections import namedtuple |
19 | 21 | from dataclasses import dataclass, field |
20 | | -from typing import TYPE_CHECKING, Any, Generic, Never, SupportsIndex, TypeVar, cast |
| 22 | +from datetime import UTC, datetime |
| 23 | +from enum import Enum |
| 24 | +from typing import ( |
| 25 | + TYPE_CHECKING, |
| 26 | + Any, |
| 27 | + Generic, |
| 28 | + Never, |
| 29 | + SupportsIndex, |
| 30 | + TypeVar, |
| 31 | + cast, |
| 32 | +) |
| 33 | + |
| 34 | +if TYPE_CHECKING: |
| 35 | + from collections.abc import AsyncIterator |
21 | 36 | from urllib.parse import urlparse |
22 | 37 |
|
23 | 38 | import grpc |
|
28 | 43 | openshell_pb2, |
29 | 44 | openshell_pb2_grpc, |
30 | 45 | ) |
31 | | -from .errors import _error_mapping_channel |
| 46 | +from .errors import OutOfRangeError, _error_mapping_channel, from_grpc_error |
32 | 47 | from .mutations import DeletionOutcome, DeletionResult |
33 | 48 |
|
34 | 49 | _ClientCallDetailsBase = namedtuple( |
@@ -534,6 +549,137 @@ class SandboxError(RuntimeError): |
534 | 549 | pass |
535 | 550 |
|
536 | 551 |
|
| 552 | +def _timestamp_from_proto(ts) -> datetime: |
| 553 | + if ts is None or ts.seconds == 0: |
| 554 | + return datetime.now(UTC) |
| 555 | + return ts.ToDatetime(tzinfo=UTC) |
| 556 | + |
| 557 | + |
| 558 | +@dataclass(frozen=True) |
| 559 | +class PlatformEvent: |
| 560 | + """A runtime event observed for a sandbox (e.g., Kubernetes pod event).""" |
| 561 | + |
| 562 | + timestamp: datetime |
| 563 | + source: str |
| 564 | + type: str |
| 565 | + reason: str |
| 566 | + message: str |
| 567 | + metadata: dict[str, str] |
| 568 | + |
| 569 | + |
| 570 | +def _platform_event_from_proto( |
| 571 | + pb_event: openshell_pb2.PlatformEvent, |
| 572 | +) -> PlatformEvent | None: |
| 573 | + if pb_event is None: |
| 574 | + return None |
| 575 | + |
| 576 | + return PlatformEvent( |
| 577 | + timestamp=_timestamp_from_proto(pb_event.event_time), |
| 578 | + source=pb_event.source, |
| 579 | + type=pb_event.type, |
| 580 | + reason=pb_event.reason, |
| 581 | + message=pb_event.message, |
| 582 | + metadata=dict(pb_event.metadata), |
| 583 | + ) |
| 584 | + |
| 585 | + |
| 586 | +@dataclass(frozen=True) |
| 587 | +class LogLine: |
| 588 | + """One log entry from a sandbox.""" |
| 589 | + |
| 590 | + sandbox_id: str |
| 591 | + timestamp: datetime |
| 592 | + level: str |
| 593 | + target: str |
| 594 | + message: str |
| 595 | + source: str |
| 596 | + fields: dict[str, str] |
| 597 | + |
| 598 | + |
| 599 | +class WatchLogKind(Enum): |
| 600 | + """Classifies items from watch_logs stream.""" |
| 601 | + |
| 602 | + LOG = "log" |
| 603 | + EVENT = "event" |
| 604 | + WARNING = "warning" |
| 605 | + |
| 606 | + |
| 607 | +@dataclass(frozen=True) |
| 608 | +class WatchLogEvent: |
| 609 | + """One item from sandbox log/event stream with resume cursor.""" |
| 610 | + |
| 611 | + kind: WatchLogKind |
| 612 | + log: LogLine | None |
| 613 | + event: PlatformEvent | None |
| 614 | + warning: str | None |
| 615 | + cursor: str |
| 616 | + |
| 617 | + |
| 618 | +def _watch_log_event_from_proto( |
| 619 | + pb_event: openshell_pb2.SandboxStreamEvent, |
| 620 | +) -> WatchLogEvent | None: |
| 621 | + if pb_event is None: |
| 622 | + return None |
| 623 | + |
| 624 | + if pb_event.HasField("log"): |
| 625 | + log_line = LogLine( |
| 626 | + sandbox_id=pb_event.log.sandbox_id, |
| 627 | + timestamp=_timestamp_from_proto(pb_event.log.event_time), |
| 628 | + level=pb_event.log.level, |
| 629 | + target=pb_event.log.target, |
| 630 | + message=pb_event.log.message, |
| 631 | + source=pb_event.log.source, |
| 632 | + fields=dict(pb_event.log.fields), |
| 633 | + ) |
| 634 | + |
| 635 | + return WatchLogEvent( |
| 636 | + kind=WatchLogKind.LOG, |
| 637 | + log=log_line, |
| 638 | + event=None, |
| 639 | + warning=None, |
| 640 | + cursor=pb_event.cursor, |
| 641 | + ) |
| 642 | + |
| 643 | + if pb_event.HasField("event"): |
| 644 | + # Convert event (handles None case: returns None) |
| 645 | + event = _platform_event_from_proto(pb_event.event) |
| 646 | + if event is None: |
| 647 | + return None |
| 648 | + |
| 649 | + return WatchLogEvent( |
| 650 | + kind=WatchLogKind.EVENT, |
| 651 | + log=None, |
| 652 | + event=event, |
| 653 | + warning=None, |
| 654 | + cursor=pb_event.cursor, |
| 655 | + ) |
| 656 | + |
| 657 | + if pb_event.HasField("warning"): |
| 658 | + # Warning has no cursor, thus not resumable |
| 659 | + return WatchLogEvent( |
| 660 | + kind=WatchLogKind.WARNING, |
| 661 | + log=None, |
| 662 | + event=None, |
| 663 | + warning=pb_event.warning.message, |
| 664 | + cursor="", |
| 665 | + ) |
| 666 | + |
| 667 | + return None |
| 668 | + |
| 669 | + |
| 670 | +@dataclass(frozen=True) |
| 671 | +class WatchLogsOptions: |
| 672 | + """Configuration for watch_logs stream.""" |
| 673 | + |
| 674 | + follow_logs: bool = True |
| 675 | + follow_events: bool = False |
| 676 | + log_sources: tuple[str, ...] = () |
| 677 | + log_min_level: str = "" |
| 678 | + resume_after_cursor: str = "" |
| 679 | + log_tail_lines: int = 0 |
| 680 | + event_tail: int = 0 |
| 681 | + |
| 682 | + |
537 | 683 | class SandboxSession: |
538 | 684 | def __init__(self, client: SandboxClient, sandbox: SandboxRef) -> None: |
539 | 685 | self._client = client |
@@ -1264,6 +1410,146 @@ def exec_python( |
1264 | 1410 | timeout_seconds=timeout_seconds, |
1265 | 1411 | ) |
1266 | 1412 |
|
| 1413 | + async def watch_logs( |
| 1414 | + self, |
| 1415 | + *, |
| 1416 | + workspace: str, |
| 1417 | + name: str, |
| 1418 | + opts: WatchLogsOptions | None = None, |
| 1419 | + ) -> AsyncIterator[WatchLogEvent]: |
| 1420 | + """Stream a sandbox's log lines and platform events with loss-aware resume. |
| 1421 | +
|
| 1422 | + Each delivered event carries an opaque cursor. The stream tracks the highest |
| 1423 | + cursor it has seen, reconnects transparently on transient errors, and asks |
| 1424 | + the gateway to replay only what follows that cursor — neither losing nor |
| 1425 | + duplicating events. |
| 1426 | +
|
| 1427 | + Loss is never silent: |
| 1428 | + - Recoverable loss (server lag): arrives as WatchLogKind.WARNING, stream continues |
| 1429 | + - Unrecoverable loss (cursor trimmed): raises OutOfRangeError, terminal |
| 1430 | +
|
| 1431 | + Args: |
| 1432 | + workspace: workspace name |
| 1433 | + name: sandbox name |
| 1434 | + opts: WatchLogsOptions (follow_logs, follow_events, resume_after_cursor, etc) |
| 1435 | + Defaults to following logs only, from tail |
| 1436 | +
|
| 1437 | + Yields: |
| 1438 | + WatchLogEvent items (log, event, or warning) |
| 1439 | +
|
| 1440 | + Raises: |
| 1441 | + OutOfRangeError: unrecoverable gap, resume_after_cursor is gone |
| 1442 | + GatewayError: other gRPC errors |
| 1443 | + SandboxError: sandbox not found, invalid args |
| 1444 | +
|
| 1445 | + Example: |
| 1446 | + async for event in client.watch_logs(workspace="default", name="sb-1"): |
| 1447 | + if event.kind == WatchLogKind.LOG: |
| 1448 | + print(f"[{event.log.level}] {event.log.message}") |
| 1449 | + elif event.kind == WatchLogKind.EVENT: |
| 1450 | + print(f"Event: {event.event.reason}") |
| 1451 | + elif event.kind == WatchLogKind.WARNING: |
| 1452 | + print(f"Warning: {event.warning}") |
| 1453 | + """ |
| 1454 | + |
| 1455 | + # Normalize options |
| 1456 | + if opts is None: |
| 1457 | + opts = WatchLogsOptions() |
| 1458 | + |
| 1459 | + # Default to following logs if neither flag set |
| 1460 | + follow_logs = opts.follow_logs |
| 1461 | + follow_events = opts.follow_events |
| 1462 | + if not follow_logs and not follow_events: |
| 1463 | + follow_logs = True |
| 1464 | + |
| 1465 | + # Resolve sandbox name first (fail fast if not found) — blocking call in executor |
| 1466 | + loop = asyncio.get_running_loop() |
| 1467 | + sandbox = await loop.run_in_executor( |
| 1468 | + None, functools.partial(self.get, workspace=workspace, name=name) |
| 1469 | + ) |
| 1470 | + resolved_name = sandbox.name |
| 1471 | + |
| 1472 | + # Initialize reconnect state |
| 1473 | + cursor = opts.resume_after_cursor |
| 1474 | + backoff = 0.1 # 100ms initial |
| 1475 | + max_backoff = 2.0 # 2s cap |
| 1476 | + consecutive_failures = 0 |
| 1477 | + max_retries = 15 # Give up after 15 consecutive UNAVAILABLE |
| 1478 | + stream = None |
| 1479 | + |
| 1480 | + # Reconnect loop |
| 1481 | + while True: |
| 1482 | + try: |
| 1483 | + # Build watch request |
| 1484 | + request = openshell_pb2.WatchSandboxRequest( |
| 1485 | + sandbox=resolved_name, |
| 1486 | + workspace_scope=_workspace_scope(workspace), |
| 1487 | + follow_status=False, # Don't want status snapshots |
| 1488 | + follow_logs=follow_logs, |
| 1489 | + follow_events=follow_events, |
| 1490 | + log_tail_lines=opts.log_tail_lines, |
| 1491 | + event_tail=opts.event_tail, |
| 1492 | + log_sources=list(opts.log_sources), |
| 1493 | + log_min_level=opts.log_min_level, |
| 1494 | + resume_after_cursor=cursor, # Resume from this cursor |
| 1495 | + ) |
| 1496 | + |
| 1497 | + # Call gRPC stream (blocking, run in executor) |
| 1498 | + stream = await loop.run_in_executor( |
| 1499 | + None, self._stub.WatchSandbox, request |
| 1500 | + ) |
| 1501 | + |
| 1502 | + # Receive events from stream (blocking iteration, run in executor) |
| 1503 | + while True: |
| 1504 | + pb_event = await loop.run_in_executor(None, next, stream) |
| 1505 | + |
| 1506 | + # Reset backoff and failure count on successful deliver |
| 1507 | + backoff = 0.1 |
| 1508 | + consecutive_failures = 0 |
| 1509 | + |
| 1510 | + # Convert proto → domain (skip non-resumable) |
| 1511 | + item = _watch_log_event_from_proto(pb_event) |
| 1512 | + if item is None: |
| 1513 | + continue |
| 1514 | + |
| 1515 | + # Update cursor: high-water mark (max, not last) |
| 1516 | + # Live delivery reads log and event sources independently, |
| 1517 | + # so arrival order ≠ cursor order. Keep max to avoid rewinding. |
| 1518 | + if item.cursor > cursor: |
| 1519 | + cursor = item.cursor |
| 1520 | + |
| 1521 | + # Yield to caller |
| 1522 | + yield item |
| 1523 | + |
| 1524 | + except OutOfRangeError: |
| 1525 | + # Terminal: resume cursor is gone, never retry |
| 1526 | + # Caller gets this exception, knows to start fresh with empty cursor |
| 1527 | + raise |
| 1528 | + |
| 1529 | + except grpc.RpcError as e: |
| 1530 | + # Check if retryable (Unavailable = connection drop, gateway restart) |
| 1531 | + if e.code() == grpc.StatusCode.UNAVAILABLE: |
| 1532 | + consecutive_failures += 1 |
| 1533 | + if consecutive_failures > max_retries: |
| 1534 | + # Gave up after max retries, raise as GatewayError |
| 1535 | + raise from_grpc_error(e) from e |
| 1536 | + # Sleep with backoff, then reconnect from cursor |
| 1537 | + await asyncio.sleep(backoff) |
| 1538 | + backoff = min(backoff * 2, max_backoff) |
| 1539 | + continue |
| 1540 | + else: |
| 1541 | + # Other gRPC error (PermissionDenied, NotFound, Internal, etc) |
| 1542 | + # Terminal — raise as GatewayError |
| 1543 | + raise from_grpc_error(e) from e |
| 1544 | + |
| 1545 | + finally: |
| 1546 | + if stream is not None: |
| 1547 | + await loop.run_in_executor(None, stream.cancel) |
| 1548 | + stream = None |
| 1549 | + |
| 1550 | + # If we reach here without exception, stream ended cleanly (shouldn't happen) |
| 1551 | + break |
| 1552 | + |
1267 | 1553 |
|
1268 | 1554 | class SandboxTemplateClient: |
1269 | 1555 | """gRPC client for reusable sandbox template lifecycle operations.""" |
|
0 commit comments