|
5 | 5 |
|
6 | 6 | import asyncio |
7 | 7 | import base64 |
| 8 | +import concurrent.futures |
8 | 9 | import contextlib |
9 | 10 | import errno |
10 | 11 | import functools |
@@ -549,18 +550,21 @@ class SandboxError(RuntimeError): |
549 | 550 | pass |
550 | 551 |
|
551 | 552 |
|
552 | | -def _timestamp_from_proto(ts) -> datetime: |
553 | | - """Convert protobuf Timestamp to aware UTC datetime. Return current time if unset.""" |
554 | | - if ts is None or ts.seconds == 0: |
555 | | - return datetime.now(UTC) |
556 | | - return ts.ToDatetime(tzinfo=UTC) |
| 553 | +def _timestamp_from_proto(ts) -> datetime | None: |
| 554 | + """Convert protobuf Timestamp to aware UTC datetime. Return None if unset or invalid.""" |
| 555 | + if ts is None or (ts.seconds == 0 and ts.nanos == 0): |
| 556 | + return None |
| 557 | + try: |
| 558 | + return ts.ToDatetime(tzinfo=UTC) |
| 559 | + except (ValueError, OverflowError): |
| 560 | + return None |
557 | 561 |
|
558 | 562 |
|
559 | 563 | @dataclass(frozen=True) |
560 | 564 | class PlatformEvent: |
561 | 565 | """A runtime event observed for a sandbox (e.g., Kubernetes pod event).""" |
562 | 566 |
|
563 | | - timestamp: datetime |
| 567 | + timestamp: datetime | None |
564 | 568 | source: str |
565 | 569 | type: str |
566 | 570 | reason: str |
@@ -590,7 +594,7 @@ class LogLine: |
590 | 594 | """One log entry from a sandbox.""" |
591 | 595 |
|
592 | 596 | sandbox_id: str |
593 | | - timestamp: datetime |
| 597 | + timestamp: datetime | None |
594 | 598 | level: str |
595 | 599 | target: str |
596 | 600 | message: str |
@@ -1465,93 +1469,110 @@ async def watch_logs( |
1465 | 1469 | if not follow_logs and not follow_events: |
1466 | 1470 | follow_logs = True |
1467 | 1471 |
|
1468 | | - # Resolve sandbox name first (fail fast if not found) — blocking call in executor |
| 1472 | + # Every blocking gRPC call for this watch runs on a dedicated thread so a |
| 1473 | + # long-lived stream never holds a slot in the loop's shared default |
| 1474 | + # executor, which would starve unrelated run_in_executor work. |
1469 | 1475 | loop = asyncio.get_running_loop() |
1470 | | - sandbox = await loop.run_in_executor( |
1471 | | - None, functools.partial(self.get, workspace=workspace, name=name) |
| 1476 | + executor = concurrent.futures.ThreadPoolExecutor( |
| 1477 | + max_workers=1, thread_name_prefix="openshell-watch-logs" |
1472 | 1478 | ) |
1473 | | - resolved_name = sandbox.name |
1474 | | - |
1475 | | - # Initialize reconnect state |
1476 | | - cursor = opts.resume_after_cursor |
1477 | | - backoff = 0.1 # 100ms initial |
1478 | | - max_backoff = 2.0 # 2s cap |
1479 | | - consecutive_failures = 0 |
1480 | | - max_retries = 15 # Give up after 15 consecutive UNAVAILABLE |
1481 | | - stream = None |
1482 | | - |
1483 | | - # Reconnect loop |
1484 | | - while True: |
1485 | | - try: |
1486 | | - # Build watch request |
1487 | | - request = openshell_pb2.WatchSandboxRequest( |
1488 | | - sandbox=resolved_name, |
1489 | | - workspace_scope=_workspace_scope(workspace), |
1490 | | - follow_status=False, # Don't want status snapshots |
1491 | | - follow_logs=follow_logs, |
1492 | | - follow_events=follow_events, |
1493 | | - log_tail_lines=opts.log_tail_lines, |
1494 | | - event_tail=opts.event_tail, |
1495 | | - log_sources=list(opts.log_sources), |
1496 | | - log_min_level=opts.log_min_level, |
1497 | | - resume_after_cursor=cursor, # Resume from this cursor |
1498 | | - ) |
| 1479 | + try: |
| 1480 | + # Resolve sandbox name first (fail fast if not found) |
| 1481 | + sandbox = await loop.run_in_executor( |
| 1482 | + executor, functools.partial(self.get, workspace=workspace, name=name) |
| 1483 | + ) |
| 1484 | + resolved_name = sandbox.name |
| 1485 | + |
| 1486 | + # Initialize reconnect state |
| 1487 | + cursor = opts.resume_after_cursor |
| 1488 | + backoff = 0.1 # 100ms initial |
| 1489 | + max_backoff = 2.0 # 2s cap |
| 1490 | + consecutive_failures = 0 |
| 1491 | + max_retries = 15 # Give up after 15 consecutive UNAVAILABLE |
| 1492 | + stream = None |
| 1493 | + |
| 1494 | + # Reconnect loop |
| 1495 | + while True: |
| 1496 | + try: |
| 1497 | + # Build watch request |
| 1498 | + request = openshell_pb2.WatchSandboxRequest( |
| 1499 | + sandbox=resolved_name, |
| 1500 | + workspace_scope=_workspace_scope(workspace), |
| 1501 | + follow_status=False, # Don't want status snapshots |
| 1502 | + follow_logs=follow_logs, |
| 1503 | + follow_events=follow_events, |
| 1504 | + log_tail_lines=opts.log_tail_lines, |
| 1505 | + event_tail=opts.event_tail, |
| 1506 | + log_sources=list(opts.log_sources), |
| 1507 | + log_min_level=opts.log_min_level, |
| 1508 | + resume_after_cursor=cursor, # Resume from this cursor |
| 1509 | + ) |
1499 | 1510 |
|
1500 | | - # Call gRPC stream (blocking, run in executor) |
1501 | | - stream = await loop.run_in_executor( |
1502 | | - None, self._stub.WatchSandbox, request |
1503 | | - ) |
| 1511 | + # Call gRPC stream (blocking, run in executor) |
| 1512 | + stream = await loop.run_in_executor( |
| 1513 | + executor, self._stub.WatchSandbox, request |
| 1514 | + ) |
1504 | 1515 |
|
1505 | | - # Receive events from stream (blocking iteration, run in executor) |
1506 | | - while True: |
1507 | | - pb_event = await loop.run_in_executor(None, next, stream) |
| 1516 | + # Receive events from stream (blocking iteration, run in executor). |
| 1517 | + # Use a None sentinel: a StopIteration raised inside the executor |
| 1518 | + # cannot be set on an asyncio Future and would hang the await. |
| 1519 | + while True: |
| 1520 | + pb_event = await loop.run_in_executor( |
| 1521 | + executor, next, stream, None |
| 1522 | + ) |
| 1523 | + if pb_event is None: |
| 1524 | + # Server closed the stream cleanly; nothing left to resume. |
| 1525 | + return |
| 1526 | + |
| 1527 | + # Convert proto → domain (skip non-resumable) |
| 1528 | + item = _watch_log_event_from_proto(pb_event) |
| 1529 | + if item is None: |
| 1530 | + continue |
| 1531 | + |
| 1532 | + # Reset backoff and failure count only after yielding resumable item |
| 1533 | + backoff = 0.1 |
| 1534 | + consecutive_failures = 0 |
| 1535 | + |
| 1536 | + # Update cursor: high-water mark (max, not last) |
| 1537 | + # Live delivery reads log and event sources independently, |
| 1538 | + # so arrival order ≠ cursor order. Keep max to avoid rewinding. |
| 1539 | + if item.cursor > cursor: |
| 1540 | + cursor = item.cursor |
| 1541 | + |
| 1542 | + # Yield to caller |
| 1543 | + yield item |
| 1544 | + |
| 1545 | + except OutOfRangeError: |
| 1546 | + # Terminal: resume cursor is gone, never retry |
| 1547 | + # Caller gets this exception, knows to start fresh with empty cursor |
| 1548 | + raise |
1508 | 1549 |
|
1509 | | - # Convert proto → domain (skip non-resumable) |
1510 | | - item = _watch_log_event_from_proto(pb_event) |
1511 | | - if item is None: |
| 1550 | + except grpc.RpcError as e: |
| 1551 | + # Check if retryable (Unavailable = connection drop, gateway restart) |
| 1552 | + if e.code() == grpc.StatusCode.UNAVAILABLE: |
| 1553 | + consecutive_failures += 1 |
| 1554 | + if consecutive_failures > max_retries: |
| 1555 | + # Gave up after max retries, raise as GatewayError |
| 1556 | + raise from_grpc_error(e) from e |
| 1557 | + # Sleep with backoff, then reconnect from cursor |
| 1558 | + await asyncio.sleep(backoff) |
| 1559 | + backoff = min(backoff * 2, max_backoff) |
1512 | 1560 | continue |
1513 | | - |
1514 | | - # Reset backoff and failure count only after yielding resumable item |
1515 | | - backoff = 0.1 |
1516 | | - consecutive_failures = 0 |
1517 | | - |
1518 | | - # Update cursor: high-water mark (max, not last) |
1519 | | - # Live delivery reads log and event sources independently, |
1520 | | - # so arrival order ≠ cursor order. Keep max to avoid rewinding. |
1521 | | - if item.cursor > cursor: |
1522 | | - cursor = item.cursor |
1523 | | - |
1524 | | - # Yield to caller |
1525 | | - yield item |
1526 | | - |
1527 | | - except OutOfRangeError: |
1528 | | - # Terminal: resume cursor is gone, never retry |
1529 | | - # Caller gets this exception, knows to start fresh with empty cursor |
1530 | | - raise |
1531 | | - |
1532 | | - except grpc.RpcError as e: |
1533 | | - # Check if retryable (Unavailable = connection drop, gateway restart) |
1534 | | - if e.code() == grpc.StatusCode.UNAVAILABLE: |
1535 | | - consecutive_failures += 1 |
1536 | | - if consecutive_failures > max_retries: |
1537 | | - # Gave up after max retries, raise as GatewayError |
| 1561 | + else: |
| 1562 | + # Other gRPC error (PermissionDenied, NotFound, Internal, etc) |
| 1563 | + # Terminal — raise as GatewayError |
1538 | 1564 | raise from_grpc_error(e) from e |
1539 | | - # Sleep with backoff, then reconnect from cursor |
1540 | | - await asyncio.sleep(backoff) |
1541 | | - backoff = min(backoff * 2, max_backoff) |
1542 | | - continue |
1543 | | - else: |
1544 | | - # Other gRPC error (PermissionDenied, NotFound, Internal, etc) |
1545 | | - # Terminal — raise as GatewayError |
1546 | | - raise from_grpc_error(e) from e |
1547 | | - |
1548 | | - finally: |
1549 | | - if stream is not None: |
1550 | | - await loop.run_in_executor(None, stream.cancel) |
1551 | | - stream = None |
1552 | 1565 |
|
1553 | | - # If we reach here without exception, stream ended cleanly (shouldn't happen) |
1554 | | - break |
| 1566 | + finally: |
| 1567 | + if stream is not None: |
| 1568 | + # cancel() is non-blocking and thread-safe. Call it directly: |
| 1569 | + # the executor's only thread may still be blocked in next() |
| 1570 | + # (e.g. the consumer task was cancelled), and cancelling is |
| 1571 | + # what unblocks it. |
| 1572 | + stream.cancel() |
| 1573 | + stream = None |
| 1574 | + finally: |
| 1575 | + executor.shutdown(wait=False) |
1555 | 1576 |
|
1556 | 1577 |
|
1557 | 1578 | class SandboxTemplateClient: |
|
0 commit comments