diff --git a/README.md b/README.md index 89ed630..98a14e4 100644 --- a/README.md +++ b/README.md @@ -321,6 +321,7 @@ stream completion. | File transfer API (transport capability-gated) | `FileInterface` | [Files](https://ai-openshell.github.io/sdk-go/api/files.html) | | Policy management (draft review, approve, reject, merge, global policy) | `PolicyInterface` | [Policy](https://ai-openshell.github.io/sdk-go/api/policy.html) | | Sandbox logs (streaming retrieval) | `SandboxInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) | +| Resumable log and platform event watch (loss-aware reconnect) | `SandboxLogsWatchInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) | | Workspace management (create, get, list, delete, members) | `WorkspaceInterface` | [Workspaces](https://ai-openshell.github.io/sdk-go/api/workspaces.html) | | Sandbox provider attachment (attach, detach, list) | `SandboxInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) | | Gateway info and current user identity | `HealthInterface` | [Health](https://ai-openshell.github.io/sdk-go/api/health.html) | diff --git a/docs/src/api/sandboxes.md b/docs/src/api/sandboxes.md index 58c46d2..8e66cfc 100644 --- a/docs/src/api/sandboxes.md +++ b/docs/src/api/sandboxes.md @@ -264,6 +264,83 @@ for event := range watcher.ResultChan() { // Channel closes after Ready or Error ``` +## WatchLogs + +Streams a sandbox's log lines and platform events with loss-aware resume. Returns a `WatchInterface[*WatchLogEvent]`. + +`WatchLogs` lives on the optional `SandboxLogsWatchInterface`, reached through `client.SandboxLogsWatch()`, so `SandboxInterface` stays unchanged for existing mocks and wrappers. + +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. The gateway delivers live log and platform events in cursor order across both sources, which is what makes the highest cursor a safe resume point. + +Only gRPC `Unavailable` (a dropped connection or gateway restart) is retried, with exponential backoff from 100ms capped at 2s, and it is retried indefinitely. Nothing is emitted while the watcher reconnects, so a gateway that stays down looks the same as a quiet sandbox. Bound the watch with a context deadline, or call `Stop`, when that matters. This differs from `Watch`, which reports `Unavailable` as an `EventError` immediately. Every other error ends the stream with an `EventError`. + +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: + +| Kind | Payload | Meaning | +|------|---------|---------| +| `WatchLogKindLog` | `Log *LogLine` | A log line | +| `WatchLogKindEvent` | `Event *PlatformEvent` | A runtime event from the compute backend | +| `WatchLogKindWarning` | `Warning string` | Recoverable loss — the server skipped ahead after a lag and the stream continues | + +**Available options** (`WatchLogsOptions`): + +| Field | Description | +|-------|-------------| +| `FollowLogs bool` | Stream log lines. Defaults to true when neither follow flag is set | +| `FollowEvents bool` | Stream platform events | +| `LogSources []string` | Filter log lines by source (e.g. `"gateway"`, `"sandbox"`) | +| `LogMinLevel string` | Minimum log level (e.g. `"WARN"`) | +| `ResumeAfterCursor string` | Replay only what follows a cursor from an earlier watch | +| `LogTailLines uint32` | Bound the initial log backfill. Ignored when resuming from a cursor | +| `EventTail uint32` | Bound the initial event backfill. Ignored when resuming from a cursor | + +```go +watcher, err := client.SandboxLogsWatch().WatchLogs(ctx, "default", "my-sandbox", v1.WatchLogsOptions{ + FollowLogs: true, + FollowEvents: true, + LogTailLines: 100, +}) +if err != nil { + log.Fatal(err) +} +defer watcher.Stop() + +var cursor string +for event := range watcher.ResultChan() { + if event.Type == v1.EventError { + if v1.IsOutOfRange(event.Err) { + // Unrecoverable gap: events after the resume point are gone. + fmt.Println("log history was trimmed; some events were lost") + } + break + } + switch item := event.Object; item.Kind { + case v1.WatchLogKindLog: + fmt.Printf("[%s] %s\n", item.Log.Level, item.Log.Message) + case v1.WatchLogKindEvent: + fmt.Printf("event %s: %s\n", item.Event.Reason, item.Event.Message) + case v1.WatchLogKindWarning: + fmt.Printf("warning: %s\n", item.Warning) + } + if item := event.Object; item.Cursor > cursor { + cursor = item.Cursor + } +} +``` + +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. + +Persist the highest cursor to resume across process restarts: + +```go +watcher, err := client.SandboxLogsWatch().WatchLogs(ctx, "default", "my-sandbox", v1.WatchLogsOptions{ + FollowLogs: true, + ResumeAfterCursor: savedCursor, +}) +``` + +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. + ## GetLogs 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. diff --git a/docs/src/error-handling.md b/docs/src/error-handling.md index 8288126..a72593e 100644 --- a/docs/src/error-handling.md +++ b/docs/src/error-handling.md @@ -42,6 +42,9 @@ Use these top-level functions to check error types. They work with wrapped error | `v1.IsInvalidArgument` | `ErrorInvalidArgument` | Invalid request parameters | | `v1.IsDeadlineExceeded` | `ErrorDeadlineExceeded` | Operation timed out | | `v1.IsCancelled` | `ErrorCancelled` | Operation was cancelled (context cancellation) | +| `v1.IsOutOfRange` | `ErrorOutOfRange` | Operation attempted past a valid range (gRPC `OUT_OF_RANGE`). On `WatchLogs`, the resume cursor is gone and the events after it are unrecoverable | + +gRPC `OUT_OF_RANGE` maps to `ErrorOutOfRange` on every RPC. Earlier releases mapped it to `ErrorInvalidArgument`, so code that matched `IsInvalidArgument` for an out-of-range result should match `IsOutOfRange` instead. For `ErrorInternal` (server-side errors), no convenience predicate exists. Match it directly via the `Code` field: diff --git a/openshell/v1/client.go b/openshell/v1/client.go index e59c3ab..7968d84 100644 --- a/openshell/v1/client.go +++ b/openshell/v1/client.go @@ -22,6 +22,7 @@ type ClientInterface interface { SandboxTemplates() SandboxTemplateInterface CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, opts ...CreateOption) (*Sandbox, error) SandboxSuspendResume() SandboxSuspendResumeInterface + SandboxLogsWatch() SandboxLogsWatchInterface Providers() ProviderInterface Services() ServiceInterface Exec() ExecInterface @@ -55,6 +56,7 @@ type Client struct { sandboxes SandboxInterface templateCreate SandboxTemplateCreateInterface suspendResume SandboxSuspendResumeInterface + logsWatch SandboxLogsWatchInterface templates SandboxTemplateInterface providers ProviderInterface services ServiceInterface @@ -102,6 +104,7 @@ func NewClient(cfg Config) (*Client, error) { c.sandboxes = sandboxes c.templateCreate = sandboxes c.suspendResume = sandboxes + c.logsWatch = sandboxes c.templates = newSandboxTemplateClient(conn) c.providers = newProviderClient(conn) c.services = newServiceClient(conn) @@ -132,6 +135,9 @@ func (c *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name, // SandboxSuspendResume returns the sandbox suspend and resume sub-client. func (c *Client) SandboxSuspendResume() SandboxSuspendResumeInterface { return c.suspendResume } +// SandboxLogsWatch returns the resumable sandbox log and event watch sub-client. +func (c *Client) SandboxLogsWatch() SandboxLogsWatchInterface { return c.logsWatch } + // Providers returns the provider sub-client. func (c *Client) Providers() ProviderInterface { return c.providers } diff --git a/openshell/v1/errors.go b/openshell/v1/errors.go index d8fdfe7..116552a 100644 --- a/openshell/v1/errors.go +++ b/openshell/v1/errors.go @@ -23,6 +23,7 @@ const ( ErrorUnimplemented = types.ErrorUnimplemented ErrorConflict = types.ErrorConflict ErrorUnauthenticated = types.ErrorUnauthenticated + ErrorOutOfRange = types.ErrorOutOfRange ) // StatusError is the typed error returned by all SDK operations. @@ -64,3 +65,7 @@ func IsConflict(err error) bool { return types.IsConflict(err) } // IsUnauthenticated returns true if the error indicates invalid or missing credentials. func IsUnauthenticated(err error) bool { return types.IsUnauthenticated(err) } + +// IsOutOfRange returns true if the error indicates a resume cursor is no longer +// available and the events after it are unrecoverable. +func IsOutOfRange(err error) bool { return types.IsOutOfRange(err) } diff --git a/openshell/v1/errors_test.go b/openshell/v1/errors_test.go index e1ec0d6..0062568 100644 --- a/openshell/v1/errors_test.go +++ b/openshell/v1/errors_test.go @@ -120,6 +120,8 @@ func TestErrorCode_String(t *testing.T) { {ErrorInternal, "Internal"}, {ErrorUnimplemented, "Unimplemented"}, {ErrorConflict, "Conflict"}, + {ErrorUnauthenticated, "Unauthenticated"}, + {ErrorOutOfRange, "OutOfRange"}, } for _, tt := range tests { assert.Equal(t, tt.want, tt.code.String()) diff --git a/openshell/v1/fake/fake.go b/openshell/v1/fake/fake.go index f7f902d..a8bcad5 100644 --- a/openshell/v1/fake/fake.go +++ b/openshell/v1/fake/fake.go @@ -26,6 +26,7 @@ type Client struct { sandboxes v1.SandboxInterface templateCreate v1.SandboxTemplateCreateInterface suspendResume v1.SandboxSuspendResumeInterface + logsWatch v1.SandboxLogsWatchInterface templates v1.SandboxTemplateInterface providers v1.ProviderInterface services v1.ServiceInterface @@ -86,6 +87,7 @@ func NewClient(opts ...ClientOption) *Client { fc.sandboxes = sandboxes fc.templateCreate = sandboxes fc.suspendResume = sandboxes + fc.logsWatch = sandboxes fc.templates = newFakeSandboxTemplateClient(fc.templateStore, fc.isClosed) fc.providers = newFakeProviderClient(fc.providerStore, fc.isClosed) fc.services = newFakeServiceClient(fc.isClosed) @@ -128,6 +130,11 @@ func (fc *Client) SandboxSuspendResume() v1.SandboxSuspendResumeInterface { return fc.suspendResume } +// SandboxLogsWatch returns the resumable sandbox log and event watch sub-client. +func (fc *Client) SandboxLogsWatch() v1.SandboxLogsWatchInterface { + return fc.logsWatch +} + // Providers returns the provider sub-client. func (fc *Client) Providers() v1.ProviderInterface { return fc.providers } diff --git a/openshell/v1/fake/fake_test.go b/openshell/v1/fake/fake_test.go index 2c5aed6..46f5cae 100644 --- a/openshell/v1/fake/fake_test.go +++ b/openshell/v1/fake/fake_test.go @@ -116,6 +116,7 @@ func TestFakeClient_SubClients(t *testing.T) { fc := NewClient() assert.NotNil(t, fc.Sandboxes()) + assert.NotNil(t, fc.SandboxLogsWatch()) assert.NotNil(t, fc.Providers()) assert.NotNil(t, fc.Exec()) assert.NotNil(t, fc.Files()) diff --git a/openshell/v1/fake/sandbox.go b/openshell/v1/fake/sandbox.go index edd888a..0cd3e8e 100644 --- a/openshell/v1/fake/sandbox.go +++ b/openshell/v1/fake/sandbox.go @@ -293,6 +293,7 @@ type fakeSandboxClient struct { var _ v1.SandboxInterface = (*fakeSandboxClient)(nil) var _ v1.SandboxTemplateCreateInterface = (*fakeSandboxClient)(nil) var _ v1.SandboxSuspendResumeInterface = (*fakeSandboxClient)(nil) +var _ v1.SandboxLogsWatchInterface = (*fakeSandboxClient)(nil) // newFakeSandboxClient creates a new fakeSandboxClient. func newFakeSandboxClient( @@ -899,6 +900,15 @@ func (c *fakeSandboxClient) GetLogs(_ context.Context, _, _ string, _ ...v1.LogO return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetLogs not implemented in fake client"} } +// WatchLogs returns Unimplemented — the fake client has no log or platform +// event stream to replay, so it cannot honor the cursor resume contract. +func (c *fakeSandboxClient) WatchLogs(_ context.Context, _, _ string, _ ...v1.WatchLogsOptions) (types.WatchInterface[*types.WatchLogEvent], error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "WatchLogs not implemented in fake client"} +} + // ListProviders returns a pager over stub Provider objects attached to the // sandbox. The returned providers contain only the Name field, since the fake // client does not maintain a full provider registry per sandbox. diff --git a/openshell/v1/fake/sandbox_test.go b/openshell/v1/fake/sandbox_test.go index 16cfd94..939e45a 100644 --- a/openshell/v1/fake/sandbox_test.go +++ b/openshell/v1/fake/sandbox_test.go @@ -1008,6 +1008,25 @@ func TestSandbox_GetLogs_ClosedReturnsUnavailable(t *testing.T) { assert.True(t, types.IsUnavailable(err)) } +func TestSandbox_WatchLogs_ReturnsUnimplemented(t *testing.T) { + sc := newTestSandboxClient() + w, err := sc.WatchLogs(context.Background(), "default", "sb-1") + require.Error(t, err) + assert.Nil(t, w) + assert.True(t, types.IsUnimplemented(err)) +} + +func TestSandbox_WatchLogs_ClosedReturnsUnavailable(t *testing.T) { + store := newobjectStore(sandboxName, copySandbox) + templateStore := newobjectStore(sandboxWorkloadTemplate, copySandboxWorkloadTemplate) + broadcaster := newWatchBroadcaster[*types.Sandbox]() + sc := newFakeSandboxClient(store, templateStore, broadcaster, func() bool { return true }) + w, err := sc.WatchLogs(context.Background(), "default", "sb-1") + require.Error(t, err) + assert.Nil(t, w) + assert.True(t, types.IsUnavailable(err)) +} + func TestSandbox_SuspendAndResume(t *testing.T) { sc := newTestSandboxClient() ctx := context.Background() diff --git a/openshell/v1/internal/converter/errors.go b/openshell/v1/internal/converter/errors.go index 77ac1ae..abc2e7c 100644 --- a/openshell/v1/internal/converter/errors.go +++ b/openshell/v1/internal/converter/errors.go @@ -28,7 +28,7 @@ var grpcToSDK = map[codes.Code]types.ErrorCode{ codes.Unauthenticated: types.ErrorUnauthenticated, codes.FailedPrecondition: types.ErrorConflict, codes.ResourceExhausted: types.ErrorUnavailable, - codes.OutOfRange: types.ErrorInvalidArgument, + codes.OutOfRange: types.ErrorOutOfRange, } // FromGRPCError converts a gRPC error to a typed StatusError. diff --git a/openshell/v1/internal/converter/errors_test.go b/openshell/v1/internal/converter/errors_test.go index 0a0e8ae..826bb42 100644 --- a/openshell/v1/internal/converter/errors_test.go +++ b/openshell/v1/internal/converter/errors_test.go @@ -135,6 +135,22 @@ func TestFromGRPCError_Aborted(t *testing.T) { assert.Equal(t, "version conflict", se.Message) } +func TestFromGRPCError_OutOfRange(t *testing.T) { + // A trimmed resume cursor is unrecoverable loss, not a malformed request, + // so it must stay distinguishable from InvalidArgument. + grpcErr := status.Error(codes.OutOfRange, "resume cursor was trimmed") + err := FromGRPCError(grpcErr) + require.Error(t, err) + assert.True(t, v1.IsOutOfRange(err)) + assert.False(t, v1.IsInvalidArgument(err)) + + var se *v1.StatusError + require.ErrorAs(t, err, &se) + assert.Equal(t, v1.ErrorOutOfRange, se.Code) + assert.Equal(t, "resume cursor was trimmed", se.Message) + assert.Equal(t, int32(codes.OutOfRange), se.GRPCCode) +} + func TestFromGRPCError_UnmappedCode(t *testing.T) { grpcErr := status.Error(codes.DataLoss, "data loss") err := FromGRPCError(grpcErr) diff --git a/openshell/v1/internal/converter/watch_log.go b/openshell/v1/internal/converter/watch_log.go new file mode 100644 index 0000000..0ddb62c --- /dev/null +++ b/openshell/v1/internal/converter/watch_log.go @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package converter + +import ( + "github.com/ai-openshell/sdk-go/openshell/v1/types" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" +) + +// --- PlatformEvent --- + +// PlatformEventFromProto converts a proto PlatformEvent to an SDK PlatformEvent. +func PlatformEventFromProto(e *pb.PlatformEvent) *types.PlatformEvent { + if e == nil { + return nil + } + return &types.PlatformEvent{ + Timestamp: TimeFromProto(e.GetEventTime()), + Source: e.GetSource(), + Type: e.GetType(), + Reason: e.GetReason(), + Message: e.GetMessage(), + Metadata: CopyStringMap(e.GetMetadata()), + } +} + +// --- WatchLogEvent --- + +// WatchLogEventFromProto converts a watch stream event into a WatchLogEvent. +// +// Returns nil for payloads that are not part of the log and platform event +// stream (status snapshots, draft policy updates), which callers skip. +func WatchLogEventFromProto(ev *pb.SandboxStreamEvent) *types.WatchLogEvent { + if ev == nil { + return nil + } + switch payload := ev.GetPayload().(type) { + case *pb.SandboxStreamEvent_Log: + line := LogLineFromProto(payload.Log) + if line == nil { + return nil + } + return &types.WatchLogEvent{Kind: types.WatchLogKindLog, Log: line, Cursor: ev.GetCursor()} + case *pb.SandboxStreamEvent_Event: + event := PlatformEventFromProto(payload.Event) + if event == nil { + return nil + } + return &types.WatchLogEvent{Kind: types.WatchLogKindEvent, Event: event, Cursor: ev.GetCursor()} + case *pb.SandboxStreamEvent_Warning: + if payload.Warning == nil { + return nil + } + // Warnings are not resumable and carry no cursor. + return &types.WatchLogEvent{Kind: types.WatchLogKindWarning, Warning: payload.Warning.GetMessage()} + default: + return nil + } +} diff --git a/openshell/v1/internal/converter/watch_log_test.go b/openshell/v1/internal/converter/watch_log_test.go new file mode 100644 index 0000000..fbb7322 --- /dev/null +++ b/openshell/v1/internal/converter/watch_log_test.go @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package converter + +import ( + "testing" + + "github.com/ai-openshell/sdk-go/openshell/v1/types" + dm "github.com/ai-openshell/sdk-go/proto/datamodelv1" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// --- PlatformEvent --- + +func TestPlatformEventFromProto(t *testing.T) { + event := PlatformEventFromProto(&pb.PlatformEvent{ + EventTime: TimestampFromMillis(1700000000000), + Source: "kubernetes", + Type: "Normal", + Reason: "Pulled", + Message: "Container image pulled", + Metadata: map[string]string{"pod": "sb-1"}, + }) + + require.NotNil(t, event) + assert.False(t, event.Timestamp.IsZero()) + assert.Equal(t, "kubernetes", event.Source) + assert.Equal(t, "Normal", event.Type) + assert.Equal(t, "Pulled", event.Reason) + assert.Equal(t, "Container image pulled", event.Message) + assert.Equal(t, map[string]string{"pod": "sb-1"}, event.Metadata) +} + +func TestPlatformEventFromProtoNil(t *testing.T) { + assert.Nil(t, PlatformEventFromProto(nil)) +} + +func TestPlatformEventFromProtoCopiesMetadata(t *testing.T) { + metadata := map[string]string{"pod": "sb-1"} + event := PlatformEventFromProto(&pb.PlatformEvent{Metadata: metadata}) + require.NotNil(t, event) + + metadata["pod"] = "mutated" + assert.Equal(t, "sb-1", event.Metadata["pod"]) +} + +// --- WatchLogEvent --- + +func TestWatchLogEventFromProtoLog(t *testing.T) { + item := WatchLogEventFromProto(&pb.SandboxStreamEvent{ + Cursor: "0000000001", + Payload: &pb.SandboxStreamEvent_Log{Log: &pb.SandboxLogLine{Message: "hello"}}, + }) + + require.NotNil(t, item) + assert.Equal(t, types.WatchLogKindLog, item.Kind) + assert.Equal(t, "0000000001", item.Cursor) + require.NotNil(t, item.Log) + assert.Equal(t, "hello", item.Log.Message) + assert.Nil(t, item.Event) + assert.Empty(t, item.Warning) +} + +func TestWatchLogEventFromProtoEvent(t *testing.T) { + item := WatchLogEventFromProto(&pb.SandboxStreamEvent{ + Cursor: "0000000002", + Payload: &pb.SandboxStreamEvent_Event{Event: &pb.PlatformEvent{Reason: "Started"}}, + }) + + require.NotNil(t, item) + assert.Equal(t, types.WatchLogKindEvent, item.Kind) + assert.Equal(t, "0000000002", item.Cursor) + require.NotNil(t, item.Event) + assert.Equal(t, "Started", item.Event.Reason) + assert.Nil(t, item.Log) +} + +func TestWatchLogEventFromProtoWarningHasNoCursor(t *testing.T) { + // The server stamps warnings with an empty cursor because they are not + // resumable; the converter must not invent one either. + item := WatchLogEventFromProto(&pb.SandboxStreamEvent{ + Payload: &pb.SandboxStreamEvent_Warning{Warning: &pb.SandboxStreamWarning{Message: "lagged"}}, + }) + + require.NotNil(t, item) + assert.Equal(t, types.WatchLogKindWarning, item.Kind) + assert.Equal(t, "lagged", item.Warning) + assert.Empty(t, item.Cursor) +} + +func TestWatchLogEventFromProtoSkipsNonStreamPayloads(t *testing.T) { + tests := map[string]*pb.SandboxStreamEvent{ + "nil": nil, + "no payload": { + Cursor: "0000000001", + }, + "sandbox snapshot": { + Payload: &pb.SandboxStreamEvent_Sandbox{Sandbox: &pb.Sandbox{ + Metadata: &dm.ObjectMeta{Name: "sb-1"}, + }}, + }, + "draft policy update": { + Payload: &pb.SandboxStreamEvent_DraftPolicyUpdate{DraftPolicyUpdate: &pb.DraftPolicyUpdate{}}, + }, + "empty log payload": { + Payload: &pb.SandboxStreamEvent_Log{}, + }, + "empty event payload": { + Payload: &pb.SandboxStreamEvent_Event{}, + }, + "empty warning payload": { + Payload: &pb.SandboxStreamEvent_Warning{}, + }, + } + + for name, event := range tests { + t.Run(name, func(t *testing.T) { + assert.Nil(t, WatchLogEventFromProto(event)) + }) + } +} diff --git a/openshell/v1/options.go b/openshell/v1/options.go index 5b1ef51..a141dda 100644 --- a/openshell/v1/options.go +++ b/openshell/v1/options.go @@ -27,6 +27,9 @@ type ListOptions = types.ListOptions // WatchOptions configures watch behavior. type WatchOptions = types.WatchOptions +// WatchLogsOptions configures a resumable sandbox log and platform event watch. +type WatchLogsOptions = types.WatchLogsOptions + // WaitOptions configures wait behavior. Use context for timeout control. type WaitOptions = types.WaitOptions diff --git a/openshell/v1/sandbox.go b/openshell/v1/sandbox.go index 0d0ecc1..4fb26af 100644 --- a/openshell/v1/sandbox.go +++ b/openshell/v1/sandbox.go @@ -84,6 +84,22 @@ var WithLogSources = types.WithLogSources // WithLogMinLevel sets the minimum log level to include. var WithLogMinLevel = types.WithLogMinLevel +// PlatformEvent is a runtime event observed for a sandbox. +type PlatformEvent = types.PlatformEvent + +// WatchLogEvent is one item from a resumable sandbox log and platform event stream. +type WatchLogEvent = types.WatchLogEvent + +// WatchLogKind classifies a WatchLogs stream item. +type WatchLogKind = types.WatchLogKind + +// WatchLogKind values. +const ( + WatchLogKindLog = types.WatchLogKindLog + WatchLogKindEvent = types.WatchLogKindEvent + WatchLogKindWarning = types.WatchLogKindWarning +) + // SandboxInterface defines lifecycle operations on sandboxes. type SandboxInterface interface { Create(ctx context.Context, workspace, name string, spec *SandboxSpec, opts ...CreateOption) (*Sandbox, error) @@ -105,6 +121,14 @@ type SandboxInterface interface { GetLogs(ctx context.Context, workspace, sandboxName string, opts ...LogOption) (*LogResult, error) } +// SandboxLogsWatchInterface defines resumable log and platform event watching +// without widening SandboxInterface. +type SandboxLogsWatchInterface interface { + // WatchLogs streams a sandbox's log lines and platform events with + // loss-aware resume. See sandboxClient.WatchLogs for the full contract. + WatchLogs(ctx context.Context, workspace, name string, opts ...WatchLogsOptions) (WatchInterface[*WatchLogEvent], error) +} + // SandboxTemplateCreateInterface defines additive sandbox creation from named // workload templates without widening SandboxInterface. type SandboxTemplateCreateInterface interface { diff --git a/openshell/v1/sandbox_client.go b/openshell/v1/sandbox_client.go index 9d5b73f..a0a9382 100644 --- a/openshell/v1/sandbox_client.go +++ b/openshell/v1/sandbox_client.go @@ -20,11 +20,18 @@ const defaultPollInterval = 500 * time.Millisecond type sandboxClient struct { client pb.OpenShellClient + + // watchLogsWait, when non-nil, replaces the WatchLogs reconnect backoff + // wait. It must return false when the watcher was stopped or ctx ended. + // Tests set it per client to observe or skip the delay; nil uses + // watcher.sleep. + watchLogsWait func(ctx context.Context, w *watcher[*WatchLogEvent], d time.Duration) bool } var _ SandboxInterface = (*sandboxClient)(nil) var _ SandboxTemplateCreateInterface = (*sandboxClient)(nil) var _ SandboxSuspendResumeInterface = (*sandboxClient)(nil) +var _ SandboxLogsWatchInterface = (*sandboxClient)(nil) func newSandboxClient(conn grpc.ClientConnInterface) *sandboxClient { return &sandboxClient{client: pb.NewOpenShellClient(conn)} diff --git a/openshell/v1/sandbox_client_test.go b/openshell/v1/sandbox_client_test.go index 313ca73..e77a346 100644 --- a/openshell/v1/sandbox_client_test.go +++ b/openshell/v1/sandbox_client_test.go @@ -46,8 +46,13 @@ type mockSandboxServer struct { watchEvents []*pb.SandboxStreamEvent watchErr error watchPostEventsErr error - watchKeepOpen chan struct{} // if non-nil, WatchSandbox blocks after sending events until closed - watchRequest *pb.WatchSandboxRequest // recorded request + watchKeepOpen chan struct{} // if non-nil, WatchSandbox blocks after sending events until closed + watchRequest *pb.WatchSandboxRequest // last recorded request + watchRequests []*pb.WatchSandboxRequest // every recorded request, in attempt order + // watchFunc, when set, fully replaces the default WatchSandbox behavior. + // attempt is the zero-based index of this call, letting a test script a + // different response per reconnect. + watchFunc func(attempt int, req *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error // GetLogs fields getLogsResp *pb.GetSandboxLogsResponse @@ -264,7 +269,13 @@ func (s *mockSandboxServer) ListSandboxProviders(_ context.Context, req *pb.List func (s *mockSandboxServer) WatchSandbox(req *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { s.mu.Lock() s.watchRequest = req + s.watchRequests = append(s.watchRequests, proto.Clone(req).(*pb.WatchSandboxRequest)) + attempt := len(s.watchRequests) - 1 + handler := s.watchFunc s.mu.Unlock() + if handler != nil { + return handler(attempt, req, stream) + } if s.watchErr != nil { return s.watchErr } diff --git a/openshell/v1/sandbox_watch_logs.go b/openshell/v1/sandbox_watch_logs.go new file mode 100644 index 0000000..4ae49f5 --- /dev/null +++ b/openshell/v1/sandbox_watch_logs.go @@ -0,0 +1,203 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + "errors" + "io" + "time" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/converter" + "github.com/ai-openshell/sdk-go/openshell/v1/types" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" + "google.golang.org/grpc/codes" +) + +const ( + // watchLogsInitialBackoff is the delay before the first reconnect attempt. + // It is restored after every delivered log, event, or warning, so a + // long-lived stream that drops retries promptly instead of at the capped + // delay. + watchLogsInitialBackoff = 100 * time.Millisecond + // watchLogsMaxBackoff caps the reconnect delay. + watchLogsMaxBackoff = 2 * time.Second + // watchLogsChannelBuffer is the result channel depth. + watchLogsChannelBuffer = 64 +) + +// WatchLogs streams a sandbox's log lines and platform events with loss-aware +// resume. +// +// Each delivered event carries an opaque cursor. The watcher tracks the highest +// cursor it has seen, reconnects transparently on transient stream errors, and +// asks the gateway to replay only what follows that cursor, so a reconnect +// neither loses nor duplicates events. This relies on the gateway delivering +// live log and platform events in cursor order across both sources, which it +// guarantees by merging them and withholding any event above its publication +// watermark. +// +// Only gRPC Unavailable (a dropped connection or gateway restart) is retried, +// with capped exponential backoff, and it is retried indefinitely: no event is +// emitted while the watcher reconnects, so a gateway that stays down looks +// like a quiet sandbox. Bound the watch with a context deadline or call Stop +// when that matters. This differs from Watch, which reports Unavailable as an +// ERROR event immediately. A connection that dies without the transport +// noticing (no keepalive, half-open TCP) stalls until the context ends. +// +// Loss is never silent. A recoverable server-side gap arrives as a +// WatchLogKindWarning event and the stream continues. An unrecoverable gap ends +// the stream with an ERROR event carrying ErrorOutOfRange: the resume point is +// gone, so the events after it cannot be replayed. That error is deliberately +// not retried, because restarting from the tail would hide the loss this API +// exists to surface. A caller that accepts the gap can start a new watch with +// an empty ResumeAfterCursor; retrying the same cursor fails identically. +// +// The returned watcher's channel closes when the server ends the stream, when +// the context is cancelled, or after Stop. Call Stop to release the stream. +func (s *sandboxClient) WatchLogs(ctx context.Context, workspace, name string, opts ...WatchLogsOptions) (WatchInterface[*WatchLogEvent], error) { + if name == "" { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"} + } + + var cfg WatchLogsOptions + if len(opts) > 0 { + cfg = opts[0] + } + if !cfg.FollowLogs && !cfg.FollowEvents { + cfg.FollowLogs = true + } + + // Resolve and confirm the sandbox under this workspace before opening the + // stream, so a bad name fails here rather than inside the reconnect loop. + sb, err := s.Get(ctx, workspace, name) + if err != nil { + return nil, err + } + resolved := name + if sb != nil && sb.Name != "" { + resolved = sb.Name + } + + streamCtx, streamCancel := context.WithCancel(ctx) + ch := make(chan Event[*WatchLogEvent], watchLogsChannelBuffer) + w := newWatcher(ch, streamCancel) + + go s.runWatchLogs(streamCtx, w, workspace, resolved, cfg) + + return w, nil +} + +// runWatchLogs drives the reconnect/resume loop until the stream ends cleanly, +// a terminal error occurs, or the consumer stops watching. +func (s *sandboxClient) runWatchLogs(ctx context.Context, w *watcher[*WatchLogEvent], workspace, name string, cfg WatchLogsOptions) { + defer close(w.result) + defer w.cancel() + + cursor := cfg.ResumeAfterCursor + backoff := watchLogsInitialBackoff + + for { + req := &pb.WatchSandboxRequest{ + Sandbox: name, + WorkspaceScope: namedWorkspaceScope(workspace), + FollowStatus: false, + FollowLogs: cfg.FollowLogs, + FollowEvents: cfg.FollowEvents, + LogTailLines: cfg.LogTailLines, + EventTail: cfg.EventTail, + LogSources: converter.CopyStringSlice(cfg.LogSources), + LogMinLevel: cfg.LogMinLevel, + ResumeAfterCursor: cursor, + } + + stream, err := s.client.WatchSandbox(ctx, req) + if err != nil { + if !s.retryWatchLogs(ctx, w, err, &backoff) { + return + } + continue + } + + reconnect := false + for { + ev, recvErr := stream.Recv() + if recvErr != nil { + if errors.Is(recvErr, io.EOF) { + // Server closed the stream cleanly; nothing left to resume. + return + } + reconnect = s.retryWatchLogs(ctx, w, recvErr, &backoff) + break + } + + item := converter.WatchLogEventFromProto(ev) + if item == nil { + continue + } + // A delivered item means the connection is healthy again. The + // status snapshot the gateway sends at the start of every stream + // is skipped above and must not count: a gateway that accepts the + // stream and then drops it would otherwise be redialed at the + // initial delay forever. + backoff = watchLogsInitialBackoff + // The gateway delivers log and platform events in cursor order + // across both sources: it merges what each source has queued and + // withholds anything above its publication watermark, so a + // higher cursor is never sent ahead of a lower one still in + // flight. Comparing instead of assigning is defensive: the proto + // contract is to keep the greater cursor, and a rewind would + // replay already-delivered events after a reconnect. + if item.Cursor > cursor { + cursor = item.Cursor + } + if !w.emit(ctx, Event[*WatchLogEvent]{Type: EventAdded, Object: item}) { + return + } + } + if !reconnect { + return + } + } +} + +// retryWatchLogs decides what to do with a stream error. It returns true when +// the caller should redial from the tracked cursor, having already waited out +// the backoff and doubled it. Otherwise the error is terminal: it is reported +// as an ERROR event (unless the consumer already stopped) and the watch ends. +func (s *sandboxClient) retryWatchLogs(ctx context.Context, w *watcher[*WatchLogEvent], err error, backoff *time.Duration) bool { + if w.stopped() || ctx.Err() != nil { + return false + } + converted := converter.FromGRPCError(err) + if !isRetryableWatchLogsError(converted) { + // Terminal, including ErrorOutOfRange: the resume point is gone, and + // restarting from the tail here would silently swallow the gap. + w.emit(ctx, Event[*WatchLogEvent]{Type: EventError, Err: converted}) + return false + } + wait := w.sleep + if s.watchLogsWait != nil { + wait = func(ctx context.Context, d time.Duration) bool { return s.watchLogsWait(ctx, w, d) } + } + if !wait(ctx, *backoff) { + return false + } + *backoff = min(*backoff*2, watchLogsMaxBackoff) + return true +} + +// isRetryableWatchLogsError reports whether a converted stream error is a +// transient condition worth reconnecting on. Only gRPC Unavailable (connection +// drop, gateway restart) qualifies. It checks the raw gRPC code, not the SDK +// ErrorCode, because ResourceExhausted also maps to ErrorUnavailable and must +// not be redialed. Every other status is surfaced to the caller instead of +// looping. +func isRetryableWatchLogsError(err error) bool { + var se *types.StatusError + if errors.As(err, &se) { + return se.GRPCCode == int32(codes.Unavailable) + } + return false +} diff --git a/openshell/v1/sandbox_watch_logs_test.go b/openshell/v1/sandbox_watch_logs_test.go new file mode 100644 index 0000000..bb71648 --- /dev/null +++ b/openshell/v1/sandbox_watch_logs_test.go @@ -0,0 +1,660 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + "sync" + "testing" + "time" + + dm "github.com/ai-openshell/sdk-go/proto/datamodelv1" + pb "github.com/ai-openshell/sdk-go/proto/openshellv1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// watchLogsMock returns a mock server with one Ready sandbox registered so +// WatchLogs' name resolution succeeds. +func watchLogsMock() *mockSandboxServer { + mock := newMockSandboxServer() + mock.sandboxes["sb-1"] = &pb.Sandbox{ + Metadata: &dm.ObjectMeta{Id: "id-1", Name: "sb-1"}, + Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_READY}, + } + return mock +} + +func logEvent(cursor, message string) *pb.SandboxStreamEvent { + return &pb.SandboxStreamEvent{ + Cursor: cursor, + Payload: &pb.SandboxStreamEvent_Log{Log: &pb.SandboxLogLine{Message: message, Level: "INFO"}}, + } +} + +func platformEvent(cursor, reason string) *pb.SandboxStreamEvent { + return &pb.SandboxStreamEvent{ + Cursor: cursor, + Payload: &pb.SandboxStreamEvent_Event{Event: &pb.PlatformEvent{ + Reason: reason, + Type: "Normal", + Source: "kubernetes", + }}, + } +} + +func warningEvent(message string) *pb.SandboxStreamEvent { + return &pb.SandboxStreamEvent{ + Payload: &pb.SandboxStreamEvent_Warning{Warning: &pb.SandboxStreamWarning{Message: message}}, + } +} + +// observeWatchLogsBackoff records every reconnect backoff the client requests. +// With wait false the delay is skipped, so a test can drive many retries +// instantly; with wait true the watcher still performs its real, cancellable +// wait. The returned func snapshots the recorded delays. +func observeWatchLogsBackoff(c *sandboxClient, wait bool) func() []time.Duration { + var mu sync.Mutex + var delays []time.Duration + c.watchLogsWait = func(ctx context.Context, w *watcher[*WatchLogEvent], d time.Duration) bool { + mu.Lock() + delays = append(delays, d) + mu.Unlock() + if wait { + return w.sleep(ctx, d) + } + return !w.stopped() && ctx.Err() == nil + } + return func() []time.Duration { + mu.Lock() + defer mu.Unlock() + return append([]time.Duration(nil), delays...) + } +} + +// drainWatchLogs collects every event until the channel closes. +func drainWatchLogs(t *testing.T, w WatchInterface[*WatchLogEvent]) []Event[*WatchLogEvent] { + t.Helper() + var events []Event[*WatchLogEvent] + timeout := time.After(10 * time.Second) + for { + select { + case ev, ok := <-w.ResultChan(): + if !ok { + return events + } + events = append(events, ev) + case <-timeout: + t.Fatal("timed out waiting for WatchLogs channel to close") + } + } +} + +func TestWatchLogs_DeliversLogsEventsAndWarnings(t *testing.T) { + mock := watchLogsMock() + mock.watchEvents = []*pb.SandboxStreamEvent{ + { + Cursor: "0000000001", + Payload: &pb.SandboxStreamEvent_Log{Log: &pb.SandboxLogLine{ + Message: "hello", + Level: "INFO", + Target: "supervisor", + Source: "sandbox", + EventTime: timestamppb.New(time.UnixMilli(1700000000000)), + Fields: map[string]string{"dst_host": "example.test"}, + }}, + }, + platformEvent("0000000002", "Started"), + warningEvent("dropped 3 messages"), + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1", WatchLogsOptions{ + FollowLogs: true, + FollowEvents: true, + }) + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, 3) + + require.Equal(t, EventAdded, events[0].Type) + logItem := events[0].Object + require.NotNil(t, logItem) + assert.Equal(t, WatchLogKindLog, logItem.Kind) + assert.Equal(t, "0000000001", logItem.Cursor) + require.NotNil(t, logItem.Log) + assert.Equal(t, "hello", logItem.Log.Message) + assert.Equal(t, "sandbox", logItem.Log.Source) + assert.Equal(t, map[string]string{"dst_host": "example.test"}, logItem.Log.Fields) + assert.Nil(t, logItem.Event) + + platformItem := events[1].Object + require.NotNil(t, platformItem) + assert.Equal(t, WatchLogKindEvent, platformItem.Kind) + assert.Equal(t, "0000000002", platformItem.Cursor) + require.NotNil(t, platformItem.Event) + assert.Equal(t, "Started", platformItem.Event.Reason) + assert.Nil(t, platformItem.Log) + + warnItem := events[2].Object + require.NotNil(t, warnItem) + assert.Equal(t, WatchLogKindWarning, warnItem.Kind) + assert.Equal(t, "dropped 3 messages", warnItem.Warning) + // Warnings are not resumable, so they carry no cursor. + assert.Empty(t, warnItem.Cursor) +} + +func TestWatchLogs_SkipsNonResumablePayloads(t *testing.T) { + mock := watchLogsMock() + mock.watchEvents = []*pb.SandboxStreamEvent{ + {Payload: &pb.SandboxStreamEvent_Sandbox{Sandbox: &pb.Sandbox{ + Metadata: &dm.ObjectMeta{Name: "sb-1"}, + Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_READY}, + }}}, + logEvent("0000000001", "only this"), + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, 1) + assert.Equal(t, WatchLogKindLog, events[0].Object.Kind) + assert.Equal(t, "only this", events[0].Object.Log.Message) +} + +func TestWatchLogs_RequestFields(t *testing.T) { + mock := watchLogsMock() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1", WatchLogsOptions{ + FollowLogs: true, + FollowEvents: true, + LogSources: []string{"sandbox"}, + LogMinLevel: "WARN", + ResumeAfterCursor: "0000000007", + LogTailLines: 25, + EventTail: 5, + }) + require.NoError(t, err) + defer w.Stop() + + drainWatchLogs(t, w) + + mock.mu.Lock() + req := mock.watchRequest + mock.mu.Unlock() + require.NotNil(t, req) + assert.Equal(t, "sb-1", req.GetSandbox()) + assert.Equal(t, "default", req.GetWorkspaceScope().GetWorkspace()) + assert.False(t, req.GetFollowStatus()) + assert.True(t, req.GetFollowLogs()) + assert.True(t, req.GetFollowEvents()) + assert.Equal(t, []string{"sandbox"}, req.GetLogSources()) + assert.Equal(t, "WARN", req.GetLogMinLevel()) + assert.Equal(t, "0000000007", req.GetResumeAfterCursor()) + assert.Equal(t, uint32(25), req.GetLogTailLines()) + assert.Equal(t, uint32(5), req.GetEventTail()) +} + +func TestWatchLogs_DefaultsToFollowingLogs(t *testing.T) { + mock := watchLogsMock() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + drainWatchLogs(t, w) + + mock.mu.Lock() + req := mock.watchRequest + mock.mu.Unlock() + require.NotNil(t, req) + assert.True(t, req.GetFollowLogs()) + assert.False(t, req.GetFollowEvents()) +} + +func TestWatchLogs_ReconnectResumesFromHighestCursor(t *testing.T) { + mock := watchLogsMock() + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + switch attempt { + case 0: + if err := stream.Send(logEvent("0000000001", "first")); err != nil { + return err + } + if err := stream.Send(platformEvent("0000000003", "Pulled")); err != nil { + return err + } + return status.Error(codes.Unavailable, "connection reset") + default: + return stream.Send(logEvent("0000000004", "after resume")) + } + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1", WatchLogsOptions{ + FollowLogs: true, + FollowEvents: true, + LogSources: []string{"sandbox", "gateway"}, + LogMinLevel: "INFO", + LogTailLines: 10, + EventTail: 3, + }) + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, 3, "reconnect must not drop or duplicate events") + assert.Equal(t, "first", events[0].Object.Log.Message) + assert.Equal(t, "Pulled", events[1].Object.Event.Reason) + assert.Equal(t, "after resume", events[2].Object.Log.Message) + for _, ev := range events { + assert.NotEqual(t, EventError, ev.Type) + } + + mock.mu.Lock() + requests := mock.watchRequests + mock.mu.Unlock() + require.Len(t, requests, 2) + assert.Empty(t, requests[0].GetResumeAfterCursor()) + assert.Equal(t, "0000000003", requests[1].GetResumeAfterCursor()) + + // The redial must rebuild the same request, changing only the cursor. + want := proto.Clone(requests[0]).(*pb.WatchSandboxRequest) + want.ResumeAfterCursor = "0000000003" + assert.True(t, proto.Equal(want, requests[1]), "redial request differs beyond the cursor:\nwant %v\ngot %v", want, requests[1]) +} + +func TestWatchLogs_CursorIsHighWaterMark(t *testing.T) { + // The gateway delivers events in cursor order, but the SDK must still never + // rewind its resume point if a lower cursor arrives after a higher one, as + // the proto contract says to keep the greater cursor. + mock := watchLogsMock() + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + if attempt == 0 { + if err := stream.Send(logEvent("0000000005", "high")); err != nil { + return err + } + if err := stream.Send(platformEvent("0000000002", "Late")); err != nil { + return err + } + return status.Error(codes.Unavailable, "connection reset") + } + return nil + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1", WatchLogsOptions{ + FollowLogs: true, + FollowEvents: true, + }) + require.NoError(t, err) + defer w.Stop() + + drainWatchLogs(t, w) + + mock.mu.Lock() + requests := mock.watchRequests + mock.mu.Unlock() + require.Len(t, requests, 2) + assert.Equal(t, "0000000005", requests[1].GetResumeAfterCursor()) +} + +func TestWatchLogs_WarningDoesNotAdvanceCursor(t *testing.T) { + mock := watchLogsMock() + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + if attempt == 0 { + if err := stream.Send(logEvent("0000000001", "before")); err != nil { + return err + } + if err := stream.Send(warningEvent("dropped 2 messages")); err != nil { + return err + } + return status.Error(codes.Unavailable, "connection reset") + } + return nil + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, 2) + assert.Equal(t, WatchLogKindWarning, events[1].Object.Kind) + + mock.mu.Lock() + requests := mock.watchRequests + mock.mu.Unlock() + require.Len(t, requests, 2) + assert.Equal(t, "0000000001", requests[1].GetResumeAfterCursor()) +} + +func TestWatchLogs_OutOfRangeIsTerminal(t *testing.T) { + mock := watchLogsMock() + mock.watchFunc = func(_ int, _ *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + if err := stream.Send(logEvent("0000000001", "before the gap")); err != nil { + return err + } + return status.Error(codes.OutOfRange, "resume cursor was trimmed") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, 2) + assert.Equal(t, WatchLogKindLog, events[0].Object.Kind) + + last := events[1] + assert.Equal(t, EventError, last.Type) + require.Error(t, last.Err) + assert.True(t, IsOutOfRange(last.Err), "want ErrorOutOfRange, got %v", last.Err) + assert.False(t, IsInvalidArgument(last.Err)) + + mock.mu.Lock() + attempts := len(mock.watchRequests) + mock.mu.Unlock() + assert.Equal(t, 1, attempts, "OUT_OF_RANGE must not be retried") +} + +func TestWatchLogs_NonRetryableErrorIsTerminal(t *testing.T) { + // ResourceExhausted maps to ErrorUnavailable in the SDK, but it must not be + // redialed: the retry decision uses the raw gRPC code. + for _, code := range []codes.Code{ + codes.PermissionDenied, + codes.Unauthenticated, + codes.ResourceExhausted, + codes.Internal, + } { + t.Run(code.String(), func(t *testing.T) { + mock := watchLogsMock() + mock.watchFunc = func(_ int, _ *pb.WatchSandboxRequest, _ grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + return status.Error(code, "nope") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, 1) + assert.Equal(t, EventError, events[0].Type) + var se *StatusError + require.ErrorAs(t, events[0].Err, &se) + assert.Equal(t, int32(code), se.GRPCCode) + + mock.mu.Lock() + attempts := len(mock.watchRequests) + mock.mu.Unlock() + assert.Equal(t, 1, attempts, "%s must not be retried", code) + }) + } +} + +func TestWatchLogs_BackoffResetsAfterDeliveredEvent(t *testing.T) { + // Two drops separated by a delivered event must both request the initial + // backoff, not an escalating one. + const attempts = 3 + mock := watchLogsMock() + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + if attempt >= attempts-1 { + return nil + } + if err := stream.Send(logEvent("000000000"+string(rune('1'+attempt)), "tick")); err != nil { + return err + } + return status.Error(codes.Unavailable, "connection reset") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + backoffs := observeWatchLogsBackoff(client, false) + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + events := drainWatchLogs(t, w) + require.Len(t, events, attempts-1) + + // Both backoff requests should be at the initial delay (reset between drops). + assert.Equal(t, []time.Duration{watchLogsInitialBackoff, watchLogsInitialBackoff}, backoffs()) +} + +func TestWatchLogs_BackoffGrowsWhenOnlySnapshotsArrive(t *testing.T) { + // The gateway opens every stream with a status snapshot. A gateway that + // sends it and then drops has delivered nothing, so the backoff must keep + // growing instead of resetting on each attempt. + const attempts = 4 + mock := watchLogsMock() + + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, stream grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + if attempt >= attempts-1 { + return nil + } + snapshot := &pb.SandboxStreamEvent{Payload: &pb.SandboxStreamEvent_Sandbox{Sandbox: &pb.Sandbox{ + Metadata: &dm.ObjectMeta{Name: "sb-1"}, + Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_READY}, + }}} + if err := stream.Send(snapshot); err != nil { + return err + } + return status.Error(codes.Unavailable, "connection reset") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + backoffs := observeWatchLogsBackoff(client, false) + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + assert.Empty(t, drainWatchLogs(t, w)) + + assert.Equal(t, []time.Duration{ + watchLogsInitialBackoff, + 2 * watchLogsInitialBackoff, + 4 * watchLogsInitialBackoff, + }, backoffs()) +} + +func TestWatchLogs_BackoffCapsAtMax(t *testing.T) { + // A gateway that stays unavailable must be redialed at the capped delay, + // not at an ever-growing one. + const retries = 8 + mock := watchLogsMock() + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, _ grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + if attempt >= retries { + return nil + } + return status.Error(codes.Unavailable, "gateway down") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + backoffs := observeWatchLogsBackoff(client, false) + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + assert.Empty(t, drainWatchLogs(t, w)) + + assert.Equal(t, []time.Duration{ + 100 * time.Millisecond, + 200 * time.Millisecond, + 400 * time.Millisecond, + 800 * time.Millisecond, + 1600 * time.Millisecond, + watchLogsMaxBackoff, + watchLogsMaxBackoff, + watchLogsMaxBackoff, + }, backoffs()) +} + +func TestWatchLogs_BackoffWaitsOncePerRetry(t *testing.T) { + // Each retry must wait the requested backoff once. Three retries from the + // initial delay add up to 100+200+400ms; waiting each delay twice would + // double that. + mock := watchLogsMock() + var mu sync.Mutex + var dials []time.Time + mock.watchFunc = func(attempt int, _ *pb.WatchSandboxRequest, _ grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + mu.Lock() + dials = append(dials, time.Now()) + mu.Unlock() + if attempt >= 3 { + return nil + } + return status.Error(codes.Unavailable, "connection reset") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + drainWatchLogs(t, w) + + mu.Lock() + defer mu.Unlock() + require.Len(t, dials, 4) + const expected = 7 * watchLogsInitialBackoff + elapsed := dials[3].Sub(dials[0]) + assert.GreaterOrEqual(t, elapsed, expected) + assert.Less(t, elapsed, expected+expected/2, "retries waited the backoff more than once") +} + +func TestWatchLogs_StopInterruptsBackoff(t *testing.T) { + // Stop during a reconnect backoff must return promptly instead of waiting + // out the delay, which grows to the 2s cap against a gateway that stays + // unavailable. + const longBackoff = 8 * watchLogsInitialBackoff + mock := watchLogsMock() + mock.watchFunc = func(int, *pb.WatchSandboxRequest, grpc.ServerStreamingServer[pb.SandboxStreamEvent]) error { + return status.Error(codes.Unavailable, "gateway down") + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + // Skip the short delays, then perform the first long one for real so Stop + // has a backoff to interrupt. + inLongBackoff := make(chan struct{}) + var once sync.Once + client.watchLogsWait = func(ctx context.Context, w *watcher[*WatchLogEvent], d time.Duration) bool { + if d < longBackoff { + return !w.stopped() && ctx.Err() == nil + } + once.Do(func() { close(inLongBackoff) }) + return w.sleep(ctx, d) + } + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + + select { + case <-inLongBackoff: + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for a long backoff") + } + + start := time.Now() + w.Stop() + select { + case _, ok := <-w.ResultChan(): + assert.False(t, ok, "channel should close after Stop") + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for channel close after Stop") + } + assert.Less(t, time.Since(start), longBackoff/2, "Stop waited out the backoff") +} + +func TestWatchLogs_StopClosesChannel(t *testing.T) { + mock := watchLogsMock() + keepOpen := make(chan struct{}) + defer close(keepOpen) + mock.watchEvents = []*pb.SandboxStreamEvent{logEvent("0000000001", "hello")} + mock.watchKeepOpen = keepOpen + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + w, err := client.WatchLogs(context.Background(), "default", "sb-1") + require.NoError(t, err) + + ev := <-w.ResultChan() + assert.Equal(t, "hello", ev.Object.Log.Message) + + w.Stop() + // Nothing further is queued, and Stop must not surface the cancelled + // stream as an ERROR event. + for _, ev := range drainWatchLogs(t, w) { + assert.NotEqual(t, EventError, ev.Type, "Stop must not emit an error: %v", ev.Err) + } +} + +func TestWatchLogs_ContextCancelClosesChannel(t *testing.T) { + mock := watchLogsMock() + keepOpen := make(chan struct{}) + defer close(keepOpen) + mock.watchKeepOpen = keepOpen + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + w, err := client.WatchLogs(ctx, "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + cancel() + // The mock sends nothing, and cancellation must not surface the + // cancelled stream as an ERROR event. + assert.Empty(t, drainWatchLogs(t, w)) +} + +func TestWatchLogs_EmptyName(t *testing.T) { + mock := watchLogsMock() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + _, err := client.WatchLogs(context.Background(), "default", "") + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) +} + +func TestWatchLogs_UnknownSandbox(t *testing.T) { + mock := watchLogsMock() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + _, err := client.WatchLogs(context.Background(), "default", "missing") + require.Error(t, err) + assert.True(t, IsNotFound(err)) + + mock.mu.Lock() + attempts := len(mock.watchRequests) + mock.mu.Unlock() + assert.Zero(t, attempts, "resolution failure must not open a stream") +} diff --git a/openshell/v1/types/errors.go b/openshell/v1/types/errors.go index b98fda6..adb86de 100644 --- a/openshell/v1/types/errors.go +++ b/openshell/v1/types/errors.go @@ -25,6 +25,12 @@ const ( ErrorUnimplemented ErrorConflict ErrorUnauthenticated + // ErrorOutOfRange mirrors gRPC OUT_OF_RANGE: the operation was attempted + // past a valid range, such as a read or seek beyond the end of a resource. + // Unlike ErrorInvalidArgument, the request was well formed and may succeed + // against a different state. Each operation documents what the range is; + // for WatchLogs it means the resume cursor is gone. + ErrorOutOfRange ) // String returns the human-readable name of the error code. @@ -52,6 +58,8 @@ func (c ErrorCode) String() string { return "Conflict" case ErrorUnauthenticated: return "Unauthenticated" + case ErrorOutOfRange: + return "OutOfRange" default: return fmt.Sprintf("Unknown(%d)", int(c)) } @@ -144,6 +152,13 @@ func IsUnauthenticated(err error) bool { return hasCode(err, ErrorUnauthenticated) } +// IsOutOfRange returns true if the error indicates an operation was attempted +// past a valid range (gRPC OUT_OF_RANGE). On WatchLogs it means the resume +// cursor is no longer available and the events after it are unrecoverable. +func IsOutOfRange(err error) bool { + return hasCode(err, ErrorOutOfRange) +} + func hasCode(err error, code ErrorCode) bool { if err == nil { return false diff --git a/openshell/v1/types/options.go b/openshell/v1/types/options.go index b2b441d..30cc9f8 100644 --- a/openshell/v1/types/options.go +++ b/openshell/v1/types/options.go @@ -91,6 +91,33 @@ type ResumeOptions struct { RestartIfRestoreFails bool } +// WatchLogsOptions configures a resumable sandbox log and platform event watch. +type WatchLogsOptions struct { + // FollowLogs streams sandbox log lines. + FollowLogs bool + // FollowEvents streams platform events. + FollowEvents bool + // LogSources filters log lines by source (e.g. "gateway", "sandbox"). + LogSources []string + // LogMinLevel sets the minimum log level to include. + LogMinLevel string + // ResumeAfterCursor replays only what follows an opaque cursor taken from a + // WatchLogEvent of an earlier watch on the same sandbox. Empty starts from + // the tail bounded by LogTailLines and EventTail. + // + // If the cursor was already trimmed from the server's buffer, or came from + // a cursor space the gateway no longer has (a restart, or a different + // replica), the watch fails with ErrorOutOfRange rather than silently + // skipping the missing events. + ResumeAfterCursor string + // LogTailLines bounds the initial log backfill. Ignored when + // ResumeAfterCursor is set. + LogTailLines uint32 + // EventTail bounds the initial platform event backfill. Ignored when + // ResumeAfterCursor is set. + EventTail uint32 +} + // WaitOptions configures wait behavior. Use context for timeout control. type WaitOptions struct { PollInterval time.Duration diff --git a/openshell/v1/types/watch_log.go b/openshell/v1/types/watch_log.go new file mode 100644 index 0000000..60c65d9 --- /dev/null +++ b/openshell/v1/types/watch_log.go @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package types + +import "time" + +// PlatformEvent is a runtime event observed for a sandbox, such as a scheduling +// or image-pull event reported by the compute backend. +type PlatformEvent struct { + // Timestamp is when the event occurred. + Timestamp time.Time + // Source is the reporting subsystem (e.g. "kubernetes", "docker", "process"). + Source string + // Type is the event severity (e.g. "Normal", "Warning"). + Type string + // Reason is a short reason code (e.g. "Started", "Pulled", "Failed"). + Reason string + // Message is the human-readable event text. + Message string + // Metadata holds optional key-value pairs. + Metadata map[string]string +} + +// WatchLogKind classifies a WatchLogs stream item. +type WatchLogKind string + +// WatchLogKind values. +const ( + // WatchLogKindLog marks an item carrying a log line. + WatchLogKindLog WatchLogKind = "LOG" + // WatchLogKindEvent marks an item carrying a platform event. + WatchLogKindEvent WatchLogKind = "EVENT" + // WatchLogKindWarning marks a recoverable loss notice. The stream continues. + WatchLogKindWarning WatchLogKind = "WARNING" +) + +// WatchLogEvent is one item from a resumable sandbox log and platform event +// stream. +// +// Exactly one of Log, Event, or Warning is populated, selected by Kind. +type WatchLogEvent struct { + // Kind selects the populated payload. + Kind WatchLogKind + // Log is set when Kind is WatchLogKindLog. + Log *LogLine + // Event is set when Kind is WatchLogKindEvent. + Event *PlatformEvent + // Warning is set when Kind is WatchLogKindWarning. It reports recoverable + // loss: the server skipped ahead after a broadcast lag instead of + // terminating, and the stream keeps running. Because cursors are opaque, + // this is the only signal that events were skipped. + Warning string + // Cursor is the opaque resume position of this item, empty for warnings. + // + // Do not parse or construct a cursor; its encoding is not part of the + // gateway's contract. The only supported operation is comparing two + // non-empty cursors observed on the same stream and keeping the greater + // one, then passing it as WatchLogsOptions.ResumeAfterCursor. + Cursor string +} diff --git a/openshell/v1/watch.go b/openshell/v1/watch.go index 0c30a04..d3c96b1 100644 --- a/openshell/v1/watch.go +++ b/openshell/v1/watch.go @@ -6,6 +6,7 @@ package v1 import ( "context" "sync" + "time" "github.com/ai-openshell/sdk-go/openshell/v1/types" ) @@ -32,6 +33,44 @@ func newWatcher[T any](ch chan Event[T], cancel context.CancelFunc) *watcher[T] } } +// emit delivers an event unless the watcher was stopped or the context ended +// first. Returns false when the caller should stop producing. +func (w *watcher[T]) emit(ctx context.Context, ev Event[T]) bool { + select { + case w.result <- ev: + return true + case <-w.done: + return false + case <-ctx.Done(): + return false + } +} + +// sleep waits for d, returning false if the watcher was stopped or the context +// ended first. +func (w *watcher[T]) sleep(ctx context.Context, d time.Duration) bool { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-timer.C: + return true + case <-w.done: + return false + case <-ctx.Done(): + return false + } +} + +// stopped reports whether the consumer already called Stop. +func (w *watcher[T]) stopped() bool { + select { + case <-w.done: + return true + default: + return false + } +} + func (w *watcher[T]) ResultChan() <-chan Event[T] { return w.result }