Skip to content

Commit a655de0

Browse files
committed
feat(python-sdk): log stream
Signed-off-by: Artem Lytvyn <alytvyn@redhat.com>
1 parent a8f98ec commit a655de0

3 files changed

Lines changed: 459 additions & 4 deletions

File tree

‎python/openshell/errors.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,31 @@ def __getattr__(self, name):
108108
return getattr(self.raw_error, name)
109109

110110

111+
class OutOfRangeError(GatewayError):
112+
"""Resume cursor is gone; events after it are unrecoverable.
113+
114+
This error is raised when the resume_after_cursor passed to watch_logs()
115+
has been trimmed from the server's buffer, making the events after it
116+
unreplayable. The stream is terminal — reconnecting with the same cursor
117+
will fail identically. Start a new watch with an empty resume_after_cursor.
118+
"""
119+
120+
pass
121+
122+
111123
def from_grpc_error(error: grpc.RpcError) -> GatewayError:
112-
"""Decode a raw RPC failure without discarding unrecognized details."""
113-
return error if isinstance(error, GatewayError) else GatewayError(error)
124+
"""Decode a raw RPC failure without discarding unrecognized details.
125+
126+
Returns OutOfRangeError for unrecoverable stream losses (e.g., trimmed cursor).
127+
"""
128+
if isinstance(error, GatewayError):
129+
return error
130+
131+
code = getattr(error, "code", lambda: None)()
132+
if code == grpc.StatusCode.OUT_OF_RANGE:
133+
return OutOfRangeError(error)
134+
135+
return GatewayError(error)
114136

115137

116138
class _ErrorMappingStream:

‎python/openshell/sandbox.py‎

Lines changed: 288 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@
33

44
from __future__ import annotations
55

6+
import asyncio
67
import base64
78
import contextlib
89
import errno
10+
import functools
911
import ipaddress
1012
import json
1113
import math
@@ -17,7 +19,20 @@
1719
import time
1820
from collections import namedtuple
1921
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
2136
from urllib.parse import urlparse
2237

2338
import grpc
@@ -28,7 +43,7 @@
2843
openshell_pb2,
2944
openshell_pb2_grpc,
3045
)
31-
from .errors import _error_mapping_channel
46+
from .errors import OutOfRangeError, _error_mapping_channel, from_grpc_error
3247
from .mutations import DeletionOutcome, DeletionResult
3348

3449
_ClientCallDetailsBase = namedtuple(
@@ -534,6 +549,137 @@ class SandboxError(RuntimeError):
534549
pass
535550

536551

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+
537683
class SandboxSession:
538684
def __init__(self, client: SandboxClient, sandbox: SandboxRef) -> None:
539685
self._client = client
@@ -1264,6 +1410,146 @@ def exec_python(
12641410
timeout_seconds=timeout_seconds,
12651411
)
12661412

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+
12671553

12681554
class SandboxTemplateClient:
12691555
"""gRPC client for reusable sandbox template lifecycle operations."""

0 commit comments

Comments
 (0)