Skip to content

Commit fe129d4

Browse files
committed
feat(go-sdk): WatchLogs
Signed-off-by: Artem Lytvyn <alytvyn@redhat.com>
1 parent 069ae6b commit fe129d4

21 files changed

Lines changed: 1140 additions & 3 deletions

‎sdk/go/docs/src/api/sandboxes.md‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,79 @@ for event := range watcher.ResultChan() {
237237
// Channel closes after Ready or Error
238238
```
239239

240+
## WatchLogs
241+
242+
Streams a sandbox's log lines and platform events with loss-aware resume. Returns a `WatchInterface[*WatchLogEvent]`.
243+
244+
Each delivered item carries an opaque `Cursor`. The watcher tracks the highest cursor it has seen, reconnects transparently when the stream drops, and asks the gateway to replay only what follows that cursor, so a reconnect neither loses nor duplicates events.
245+
246+
Every `Event[*WatchLogEvent]` has `Type` `EventAdded`, except a terminal failure, which arrives as `EventError` with `Err` set and no `Object`. The `Object.Kind` field selects the populated payload:
247+
248+
| Kind | Payload | Meaning |
249+
|------|---------|---------|
250+
| `WatchLogKindLog` | `Log *LogLine` | A log line |
251+
| `WatchLogKindEvent` | `Event *PlatformEvent` | A runtime event from the compute backend |
252+
| `WatchLogKindWarning` | `Warning string` | Recoverable loss — the server skipped ahead after a lag and the stream continues |
253+
254+
**Available options** (`WatchLogsOptions`):
255+
256+
| Field | Description |
257+
|-------|-------------|
258+
| `FollowLogs bool` | Stream log lines. Defaults to true when neither follow flag is set |
259+
| `FollowEvents bool` | Stream platform events |
260+
| `LogSources []string` | Filter log lines by source (e.g. `"gateway"`, `"sandbox"`) |
261+
| `LogMinLevel string` | Minimum log level (e.g. `"WARN"`) |
262+
| `ResumeAfterCursor string` | Replay only what follows a cursor from an earlier watch |
263+
| `LogTailLines uint32` | Bound the initial log backfill. Ignored when resuming from a cursor |
264+
| `EventTail uint32` | Bound the initial event backfill. Ignored when resuming from a cursor |
265+
266+
```go
267+
watcher, err := client.Sandboxes().WatchLogs(ctx, "default", "my-sandbox", v1.WatchLogsOptions{
268+
FollowLogs: true,
269+
FollowEvents: true,
270+
LogTailLines: 100,
271+
})
272+
if err != nil {
273+
log.Fatal(err)
274+
}
275+
defer watcher.Stop()
276+
277+
var cursor string
278+
for event := range watcher.ResultChan() {
279+
if event.Type == v1.EventError {
280+
if v1.IsOutOfRange(event.Err) {
281+
// Unrecoverable gap: events after the resume point are gone.
282+
fmt.Println("log history was trimmed; some events were lost")
283+
}
284+
break
285+
}
286+
switch item := event.Object; item.Kind {
287+
case v1.WatchLogKindLog:
288+
fmt.Printf("[%s] %s\n", item.Log.Level, item.Log.Message)
289+
case v1.WatchLogKindEvent:
290+
fmt.Printf("event %s: %s\n", item.Event.Reason, item.Event.Message)
291+
case v1.WatchLogKindWarning:
292+
fmt.Printf("warning: %s\n", item.Warning)
293+
}
294+
if item := event.Object; item.Cursor > cursor {
295+
cursor = item.Cursor
296+
}
297+
}
298+
```
299+
300+
Loss is never silent. A recoverable gap arrives as a `WatchLogKindWarning` item and the stream continues. An unrecoverable gap ends the stream with an `EventError` carrying `ErrorOutOfRange`: the resume point is gone, so the events after it cannot be replayed. The SDK does not retry that error, because restarting from the tail would hide the loss. To continue anyway, start a new watch with an empty `ResumeAfterCursor`; retrying the same cursor fails identically.
301+
302+
Persist the highest cursor to resume across process restarts:
303+
304+
```go
305+
watcher, err := client.Sandboxes().WatchLogs(ctx, "default", "my-sandbox", v1.WatchLogsOptions{
306+
FollowLogs: true,
307+
ResumeAfterCursor: savedCursor,
308+
})
309+
```
310+
311+
Cursors are opaque. Do not parse or construct one. The only supported operation is comparing two cursors observed on the same stream and keeping the greater one.
312+
240313
## GetLogs
241314

242315
Retrieves log entries from a sandbox. The sandbox is looked up by name (the SDK resolves the name to an internal ID automatically). Use functional options to filter results.

‎sdk/go/docs/src/error-handling.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Use these top-level functions to check error types. They work with wrapped error
4242
| `v1.IsInvalidArgument` | `ErrorInvalidArgument` | Invalid request parameters |
4343
| `v1.IsDeadlineExceeded` | `ErrorDeadlineExceeded` | Operation timed out |
4444
| `v1.IsCancelled` | `ErrorCancelled` | Operation was cancelled (context cancellation) |
45+
| `v1.IsOutOfRange` | `ErrorOutOfRange` | A stream resume cursor is gone and the events after it are unrecoverable |
4546

4647
For `ErrorInternal` (server-side errors), no convenience predicate exists. Match it directly via the `Code` field:
4748

‎sdk/go/openshell/v1/errors.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const (
2323
ErrorUnimplemented = types.ErrorUnimplemented
2424
ErrorConflict = types.ErrorConflict
2525
ErrorUnauthenticated = types.ErrorUnauthenticated
26+
ErrorOutOfRange = types.ErrorOutOfRange
2627
)
2728

2829
// StatusError is the typed error returned by all SDK operations.
@@ -64,3 +65,7 @@ func IsConflict(err error) bool { return types.IsConflict(err) }
6465

6566
// IsUnauthenticated returns true if the error indicates invalid or missing credentials.
6667
func IsUnauthenticated(err error) bool { return types.IsUnauthenticated(err) }
68+
69+
// IsOutOfRange returns true if the error indicates a resume cursor is no longer
70+
// available and the events after it are unrecoverable.
71+
func IsOutOfRange(err error) bool { return types.IsOutOfRange(err) }

‎sdk/go/openshell/v1/errors_test.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ func TestErrorCode_String(t *testing.T) {
120120
{ErrorInternal, "Internal"},
121121
{ErrorUnimplemented, "Unimplemented"},
122122
{ErrorConflict, "Conflict"},
123+
{ErrorUnauthenticated, "Unauthenticated"},
124+
{ErrorOutOfRange, "OutOfRange"},
123125
}
124126
for _, tt := range tests {
125127
assert.Equal(t, tt.want, tt.code.String())

‎sdk/go/openshell/v1/exec_client_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ func (r *stubSandboxResolver) WaitReady(context.Context, string, string, ...Wait
6161
func (r *stubSandboxResolver) Watch(context.Context, string, string, ...WatchOptions) (WatchInterface[*Sandbox], error) {
6262
panic("not implemented")
6363
}
64+
func (r *stubSandboxResolver) WatchLogs(context.Context, string, string, ...WatchLogsOptions) (WatchInterface[*WatchLogEvent], error) {
65+
panic("not implemented")
66+
}
6467
func (r *stubSandboxResolver) GetLogs(context.Context, string, string, ...LogOption) (*LogResult, error) {
6568
panic("not implemented")
6669
}

‎sdk/go/openshell/v1/fake/sandbox.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,15 @@ func (c *fakeSandboxClient) GetLogs(_ context.Context, _, _ string, _ ...v1.LogO
814814
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetLogs not implemented in fake client"}
815815
}
816816

817+
// WatchLogs returns Unimplemented — the fake client has no log or platform
818+
// event stream to replay, so it cannot honor the cursor resume contract.
819+
func (c *fakeSandboxClient) WatchLogs(_ context.Context, _, _ string, _ ...v1.WatchLogsOptions) (types.WatchInterface[*types.WatchLogEvent], error) {
820+
if c.closedFunc() {
821+
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
822+
}
823+
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "WatchLogs not implemented in fake client"}
824+
}
825+
817826
// ListProviders returns stub Provider objects for each provider name
818827
// attached to the sandbox. The returned providers contain only the Name
819828
// field, since the fake client does not maintain a full provider registry

‎sdk/go/openshell/v1/internal/converter/errors.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ var grpcToSDK = map[codes.Code]types.ErrorCode{
2828
codes.Unauthenticated: types.ErrorUnauthenticated,
2929
codes.FailedPrecondition: types.ErrorConflict,
3030
codes.ResourceExhausted: types.ErrorUnavailable,
31-
codes.OutOfRange: types.ErrorInvalidArgument,
31+
codes.OutOfRange: types.ErrorOutOfRange,
3232
}
3333

3434
// FromGRPCError converts a gRPC error to a typed StatusError.

‎sdk/go/openshell/v1/internal/converter/errors_test.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,22 @@ func TestFromGRPCError_Aborted(t *testing.T) {
135135
assert.Equal(t, "version conflict", se.Message)
136136
}
137137

138+
func TestFromGRPCError_OutOfRange(t *testing.T) {
139+
// A trimmed resume cursor is unrecoverable loss, not a malformed request,
140+
// so it must stay distinguishable from InvalidArgument.
141+
grpcErr := status.Error(codes.OutOfRange, "resume cursor was trimmed")
142+
err := FromGRPCError(grpcErr)
143+
require.Error(t, err)
144+
assert.True(t, v1.IsOutOfRange(err))
145+
assert.False(t, v1.IsInvalidArgument(err))
146+
147+
var se *v1.StatusError
148+
require.ErrorAs(t, err, &se)
149+
assert.Equal(t, v1.ErrorOutOfRange, se.Code)
150+
assert.Equal(t, "resume cursor was trimmed", se.Message)
151+
assert.Equal(t, int32(codes.OutOfRange), se.GRPCCode)
152+
}
153+
138154
func TestFromGRPCError_UnmappedCode(t *testing.T) {
139155
grpcErr := status.Error(codes.DataLoss, "data loss")
140156
err := FromGRPCError(grpcErr)
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package converter
5+
6+
import (
7+
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
8+
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
9+
)
10+
11+
// --- PlatformEvent ---
12+
13+
// PlatformEventFromProto converts a proto PlatformEvent to an SDK PlatformEvent.
14+
func PlatformEventFromProto(e *pb.PlatformEvent) *types.PlatformEvent {
15+
if e == nil {
16+
return nil
17+
}
18+
return &types.PlatformEvent{
19+
Timestamp: TimeFromProto(e.GetEventTime()),
20+
Source: e.GetSource(),
21+
Type: e.GetType(),
22+
Reason: e.GetReason(),
23+
Message: e.GetMessage(),
24+
Metadata: CopyStringMap(e.GetMetadata()),
25+
}
26+
}
27+
28+
// --- WatchLogEvent ---
29+
30+
// WatchLogEventFromProto converts a watch stream event into a WatchLogEvent.
31+
//
32+
// Returns nil for payloads that are not part of the log and platform event
33+
// stream (status snapshots, draft policy updates), which callers skip.
34+
func WatchLogEventFromProto(ev *pb.SandboxStreamEvent) *types.WatchLogEvent {
35+
if ev == nil {
36+
return nil
37+
}
38+
switch payload := ev.GetPayload().(type) {
39+
case *pb.SandboxStreamEvent_Log:
40+
line := LogLineFromProto(payload.Log)
41+
if line == nil {
42+
return nil
43+
}
44+
return &types.WatchLogEvent{Kind: types.WatchLogKindLog, Log: line, Cursor: ev.GetCursor()}
45+
case *pb.SandboxStreamEvent_Event:
46+
event := PlatformEventFromProto(payload.Event)
47+
if event == nil {
48+
return nil
49+
}
50+
return &types.WatchLogEvent{Kind: types.WatchLogKindEvent, Event: event, Cursor: ev.GetCursor()}
51+
case *pb.SandboxStreamEvent_Warning:
52+
if payload.Warning == nil {
53+
return nil
54+
}
55+
// Warnings are not resumable and carry no cursor.
56+
return &types.WatchLogEvent{Kind: types.WatchLogKindWarning, Warning: payload.Warning.GetMessage()}
57+
default:
58+
return nil
59+
}
60+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package converter
5+
6+
import (
7+
"testing"
8+
9+
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
10+
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
11+
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
12+
"github.com/stretchr/testify/assert"
13+
"github.com/stretchr/testify/require"
14+
)
15+
16+
// --- PlatformEvent ---
17+
18+
func TestPlatformEventFromProto(t *testing.T) {
19+
event := PlatformEventFromProto(&pb.PlatformEvent{
20+
EventTime: TimestampFromMillis(1700000000000),
21+
Source: "kubernetes",
22+
Type: "Normal",
23+
Reason: "Pulled",
24+
Message: "Container image pulled",
25+
Metadata: map[string]string{"pod": "sb-1"},
26+
})
27+
28+
require.NotNil(t, event)
29+
assert.False(t, event.Timestamp.IsZero())
30+
assert.Equal(t, "kubernetes", event.Source)
31+
assert.Equal(t, "Normal", event.Type)
32+
assert.Equal(t, "Pulled", event.Reason)
33+
assert.Equal(t, "Container image pulled", event.Message)
34+
assert.Equal(t, map[string]string{"pod": "sb-1"}, event.Metadata)
35+
}
36+
37+
func TestPlatformEventFromProtoNil(t *testing.T) {
38+
assert.Nil(t, PlatformEventFromProto(nil))
39+
}
40+
41+
func TestPlatformEventFromProtoCopiesMetadata(t *testing.T) {
42+
metadata := map[string]string{"pod": "sb-1"}
43+
event := PlatformEventFromProto(&pb.PlatformEvent{Metadata: metadata})
44+
require.NotNil(t, event)
45+
46+
metadata["pod"] = "mutated"
47+
assert.Equal(t, "sb-1", event.Metadata["pod"])
48+
}
49+
50+
// --- WatchLogEvent ---
51+
52+
func TestWatchLogEventFromProtoLog(t *testing.T) {
53+
item := WatchLogEventFromProto(&pb.SandboxStreamEvent{
54+
Cursor: "0000000001",
55+
Payload: &pb.SandboxStreamEvent_Log{Log: &pb.SandboxLogLine{Message: "hello"}},
56+
})
57+
58+
require.NotNil(t, item)
59+
assert.Equal(t, types.WatchLogKindLog, item.Kind)
60+
assert.Equal(t, "0000000001", item.Cursor)
61+
require.NotNil(t, item.Log)
62+
assert.Equal(t, "hello", item.Log.Message)
63+
assert.Nil(t, item.Event)
64+
assert.Empty(t, item.Warning)
65+
}
66+
67+
func TestWatchLogEventFromProtoEvent(t *testing.T) {
68+
item := WatchLogEventFromProto(&pb.SandboxStreamEvent{
69+
Cursor: "0000000002",
70+
Payload: &pb.SandboxStreamEvent_Event{Event: &pb.PlatformEvent{Reason: "Started"}},
71+
})
72+
73+
require.NotNil(t, item)
74+
assert.Equal(t, types.WatchLogKindEvent, item.Kind)
75+
assert.Equal(t, "0000000002", item.Cursor)
76+
require.NotNil(t, item.Event)
77+
assert.Equal(t, "Started", item.Event.Reason)
78+
assert.Nil(t, item.Log)
79+
}
80+
81+
func TestWatchLogEventFromProtoWarningHasNoCursor(t *testing.T) {
82+
// The server stamps warnings with an empty cursor because they are not
83+
// resumable; the converter must not invent one either.
84+
item := WatchLogEventFromProto(&pb.SandboxStreamEvent{
85+
Payload: &pb.SandboxStreamEvent_Warning{Warning: &pb.SandboxStreamWarning{Message: "lagged"}},
86+
})
87+
88+
require.NotNil(t, item)
89+
assert.Equal(t, types.WatchLogKindWarning, item.Kind)
90+
assert.Equal(t, "lagged", item.Warning)
91+
assert.Empty(t, item.Cursor)
92+
}
93+
94+
func TestWatchLogEventFromProtoSkipsNonStreamPayloads(t *testing.T) {
95+
tests := map[string]*pb.SandboxStreamEvent{
96+
"nil": nil,
97+
"no payload": {
98+
Cursor: "0000000001",
99+
},
100+
"sandbox snapshot": {
101+
Payload: &pb.SandboxStreamEvent_Sandbox{Sandbox: &pb.Sandbox{
102+
Metadata: &dm.ObjectMeta{Name: "sb-1"},
103+
}},
104+
},
105+
"draft policy update": {
106+
Payload: &pb.SandboxStreamEvent_DraftPolicyUpdate{DraftPolicyUpdate: &pb.DraftPolicyUpdate{}},
107+
},
108+
"empty log payload": {
109+
Payload: &pb.SandboxStreamEvent_Log{},
110+
},
111+
"empty event payload": {
112+
Payload: &pb.SandboxStreamEvent_Event{},
113+
},
114+
"empty warning payload": {
115+
Payload: &pb.SandboxStreamEvent_Warning{},
116+
},
117+
}
118+
119+
for name, event := range tests {
120+
t.Run(name, func(t *testing.T) {
121+
assert.Nil(t, WatchLogEventFromProto(event))
122+
})
123+
}
124+
}

0 commit comments

Comments
 (0)