Skip to content

Commit ef78738

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

3 files changed

Lines changed: 443 additions & 4 deletions

File tree

‎python/openshell/errors.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,31 @@ def __getattr__(self, name):
109109

110110

111111
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)
112+
"""Decode a raw RPC failure without discarding unrecognized details.
113+
114+
Raises OutOfRangeError for unrecoverable stream losses (e.g., trimmed cursor).
115+
"""
116+
if isinstance(error, GatewayError):
117+
return error
118+
119+
# OUT_OF_RANGE, resume cursor is gone
120+
if error.code() == grpc.StatusCode.OUT_OF_RANGE:
121+
raise OutOfRangeError(error.details())
122+
123+
return GatewayError(error)
124+
125+
126+
# TODO: remove it later, in case we use SandboxError
127+
class OutOfRangeError(RuntimeError):
128+
"""Resume cursor is gone; events after it are unrecoverable.
129+
130+
This error is raised when the resume_after_cursor passed to watch_logs()
131+
has been trimmed from the server's buffer, making the events after it
132+
unreplayable. The stream is terminal — reconnecting with the same cursor
133+
will fail identically. Start a new watch with an empty resume_after_cursor.
134+
"""
135+
136+
pass
114137

115138

116139
class _ErrorMappingStream:

‎python/openshell/sandbox.py‎

Lines changed: 274 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from __future__ import annotations
55

6+
import asyncio
67
import base64
78
import contextlib
89
import errno
@@ -17,7 +18,20 @@
1718
import time
1819
from collections import namedtuple
1920
from dataclasses import dataclass, field
20-
from typing import TYPE_CHECKING, Any, Generic, Never, SupportsIndex, TypeVar, cast
21+
from datetime import datetime
22+
from enum import Enum
23+
from typing import (
24+
TYPE_CHECKING,
25+
Any,
26+
Generic,
27+
Never,
28+
SupportsIndex,
29+
TypeVar,
30+
cast,
31+
)
32+
33+
if TYPE_CHECKING:
34+
from collections.abc import AsyncIterator
2135
from urllib.parse import urlparse
2236

2337
import grpc
@@ -28,7 +42,7 @@
2842
openshell_pb2,
2943
openshell_pb2_grpc,
3044
)
31-
from .errors import _error_mapping_channel
45+
from .errors import OutOfRangeError, _error_mapping_channel, from_grpc_error
3246
from .mutations import DeletionOutcome, DeletionResult
3347

3448
_ClientCallDetailsBase = namedtuple(
@@ -534,6 +548,139 @@ class SandboxError(RuntimeError):
534548
pass
535549

536550

551+
def _timestamp_from_proto(ts) -> datetime:
552+
# If None or no timestamp set, return current time
553+
if ts is None:
554+
return datetime.utcnow()
555+
seconds_since_epoch = ts.seconds + (ts.nanos / 1_000_000_000)
556+
return datetime.utcfromtimestamp(seconds_since_epoch)
557+
558+
559+
@dataclass(frozen=True)
560+
class PlatformEvent:
561+
"""A runtime event observed for a sandbox (e.g., Kubernetes pod event)."""
562+
563+
timestamp: datetime
564+
source: str
565+
type: str
566+
reason: str
567+
message: str
568+
metadata: dict[str, str]
569+
570+
571+
def _platform_event_from_proto(
572+
pb_event: openshell_pb2.PlatformEvent,
573+
) -> PlatformEvent | None:
574+
if pb_event is None:
575+
return None
576+
577+
return PlatformEvent(
578+
timestamp=_timestamp_from_proto(pb_event.event_time),
579+
source=pb_event.source,
580+
type=pb_event.type,
581+
reason=pb_event.reason,
582+
message=pb_event.message,
583+
metadata=dict(pb_event.metadata),
584+
)
585+
586+
587+
@dataclass(frozen=True)
588+
class LogLine:
589+
"""One log entry from a sandbox."""
590+
591+
sandbox_id: str
592+
timestamp: datetime
593+
level: str
594+
target: str
595+
message: str
596+
source: str
597+
fields: dict[str, str]
598+
599+
600+
class WatchLogKind(Enum):
601+
"""Classifies items from watch_logs stream."""
602+
603+
LOG = "log"
604+
EVENT = "event"
605+
WARNING = "warning"
606+
607+
608+
@dataclass(frozen=True)
609+
class WatchLogEvent:
610+
"""One item from sandbox log/event stream with resume cursor."""
611+
612+
kind: WatchLogKind
613+
log: LogLine | None
614+
event: PlatformEvent | None
615+
warning: str | None
616+
cursor: str
617+
618+
619+
def _watch_log_event_from_proto(
620+
pb_event: openshell_pb2.SandboxStreamEvent,
621+
) -> WatchLogEvent | None:
622+
if pb_event is None:
623+
return None
624+
625+
if pb_event.HasField("log"):
626+
log_line = LogLine(
627+
sandbox_id=pb_event.log.sandbox_id,
628+
timestamp=_timestamp_from_proto(pb_event.log.event_time),
629+
level=pb_event.log.level,
630+
target=pb_event.log.target,
631+
message=pb_event.log.message,
632+
source=pb_event.log.source,
633+
fields=dict(pb_event.log.fields),
634+
)
635+
636+
return WatchLogEvent(
637+
kind=WatchLogKind.LOG,
638+
log=log_line,
639+
event=None,
640+
warning=None,
641+
cursor=pb_event.cursor,
642+
)
643+
644+
if pb_event.HasField("event"):
645+
# Convert event (handles None case: returns None)
646+
event = _platform_event_from_proto(pb_event.event)
647+
if event is None:
648+
return None
649+
650+
return WatchLogEvent(
651+
kind=WatchLogKind.EVENT,
652+
log=None,
653+
event=event,
654+
warning=None,
655+
cursor=pb_event.cursor,
656+
)
657+
658+
if pb_event.HasField("warning"):
659+
# Warning has no cursor, thus not resumable
660+
return WatchLogEvent(
661+
kind=WatchLogKind.WARNING,
662+
log=None,
663+
event=None,
664+
warning=pb_event.warning.message,
665+
cursor="",
666+
)
667+
668+
return None
669+
670+
671+
@dataclass(frozen=True)
672+
class WatchLogsOptions:
673+
"""Configuration for watch_logs stream."""
674+
675+
follow_logs: bool = True
676+
follow_events: bool = False
677+
log_sources: tuple[str, ...] = ()
678+
log_min_level: str = ""
679+
resume_after_cursor: str = ""
680+
log_tail_lines: int = 0
681+
event_tail: int = 0
682+
683+
537684
class SandboxSession:
538685
def __init__(self, client: SandboxClient, sandbox: SandboxRef) -> None:
539686
self._client = client
@@ -1264,6 +1411,131 @@ def exec_python(
12641411
timeout_seconds=timeout_seconds,
12651412
)
12661413

1414+
async def watch_logs(
1415+
self,
1416+
*,
1417+
workspace: str,
1418+
name: str,
1419+
opts: WatchLogsOptions | None = None,
1420+
) -> AsyncIterator[WatchLogEvent]:
1421+
"""Stream a sandbox's log lines and platform events with loss-aware resume.
1422+
1423+
Each delivered event carries an opaque cursor. The stream tracks the highest
1424+
cursor it has seen, reconnects transparently on transient errors, and asks
1425+
the gateway to replay only what follows that cursor — neither losing nor
1426+
duplicating events.
1427+
1428+
Loss is never silent:
1429+
- Recoverable loss (server lag): arrives as WatchLogKind.WARNING, stream continues
1430+
- Unrecoverable loss (cursor trimmed): raises OutOfRangeError, terminal
1431+
1432+
Args:
1433+
workspace: workspace name
1434+
name: sandbox name
1435+
opts: WatchLogsOptions (follow_logs, follow_events, resume_after_cursor, etc)
1436+
Defaults to following logs only, from tail
1437+
1438+
Yields:
1439+
WatchLogEvent items (log, event, or warning)
1440+
1441+
Raises:
1442+
OutOfRangeError: unrecoverable gap, resume_after_cursor is gone
1443+
GatewayError: other gRPC errors
1444+
SandboxError: sandbox not found, invalid args
1445+
1446+
Example:
1447+
async for event in client.watch_logs(workspace="default", name="sb-1"):
1448+
if event.kind == WatchLogKind.LOG:
1449+
print(f"[{event.log.level}] {event.log.message}")
1450+
elif event.kind == WatchLogKind.EVENT:
1451+
print(f"Event: {event.event.reason}")
1452+
elif event.kind == WatchLogKind.WARNING:
1453+
print(f"Warning: {event.warning}")
1454+
"""
1455+
1456+
# Normalize options
1457+
if opts is None:
1458+
opts = WatchLogsOptions()
1459+
1460+
# Default to following logs if neither flag set
1461+
follow_logs = opts.follow_logs
1462+
follow_events = opts.follow_events
1463+
if not follow_logs and not follow_events:
1464+
follow_logs = True
1465+
1466+
# Resolve sandbox name first (fail fast if not found)
1467+
sandbox = self.get(workspace=workspace, name=name)
1468+
resolved_name = sandbox.name
1469+
1470+
# Initialize reconnect state
1471+
cursor = opts.resume_after_cursor
1472+
backoff = 0.1 # 100ms initial
1473+
max_backoff = 2.0 # 2s cap
1474+
1475+
# Reconnect loop
1476+
while True:
1477+
try:
1478+
# Build watch request
1479+
request = openshell_pb2.WatchSandboxRequest(
1480+
sandbox=resolved_name,
1481+
workspace_scope=_workspace_scope(workspace),
1482+
follow_status=False, # Don't want status snapshots
1483+
follow_logs=follow_logs,
1484+
follow_events=follow_events,
1485+
log_tail_lines=opts.log_tail_lines,
1486+
event_tail=opts.event_tail,
1487+
log_sources=list(opts.log_sources),
1488+
log_min_level=opts.log_min_level,
1489+
resume_after_cursor=cursor, # Resume from this cursor
1490+
)
1491+
1492+
# Call gRPC stream
1493+
stream = self._stub.WatchSandbox(request, timeout=self._timeout)
1494+
1495+
# Receive events from stream
1496+
async for pb_event in stream:
1497+
# Reset backoff on successful deliver
1498+
backoff = 0.1
1499+
1500+
# Convert proto → domain (skip non-resumable)
1501+
item = _watch_log_event_from_proto(pb_event)
1502+
if item is None:
1503+
continue
1504+
1505+
# Update cursor: high-water mark (max, not last)
1506+
# Live delivery reads log and event sources independently,
1507+
# so arrival order ≠ cursor order. Keep max to avoid rewinding.
1508+
if item.cursor > cursor:
1509+
cursor = item.cursor
1510+
1511+
# Yield to caller
1512+
yield item
1513+
1514+
except OutOfRangeError:
1515+
# Terminal: resume cursor is gone, never retry
1516+
# Caller gets this exception, knows to start fresh with empty cursor
1517+
raise
1518+
1519+
except grpc.RpcError as e:
1520+
# Check if retryable (Unavailable = connection drop, gateway restart)
1521+
if e.code() == grpc.StatusCode.UNAVAILABLE:
1522+
# Sleep with backoff, then reconnect from cursor
1523+
await asyncio.sleep(backoff)
1524+
backoff = min(backoff * 2, max_backoff)
1525+
continue
1526+
else:
1527+
# Other gRPC error (PermissionDenied, NotFound, Internal, etc)
1528+
# Terminal — raise as GatewayError
1529+
raise from_grpc_error(e) from e
1530+
1531+
except Exception:
1532+
# Any other error (asyncio.CancelledError, timeout, etc) — terminal
1533+
raise
1534+
1535+
# If we reach here without exception, stream ended cleanly
1536+
# (shouldn't happen unless server closes normally, which is EOF)
1537+
break
1538+
12671539

12681540
class SandboxTemplateClient:
12691541
"""gRPC client for reusable sandbox template lifecycle operations."""

0 commit comments

Comments
 (0)