From 4bc9e6afdd0ee1a710a1918e790f373a47ba6ff6 Mon Sep 17 00:00:00 2001 From: Artem Lytvyn Date: Tue, 17 Nov 2026 23:02:58 +0000 Subject: [PATCH 1/2] refactor(sandbox): move Watch onto the shared watcher helpers Fixes #36 Signed-off-by: Artem Lytvyn --- docs/src/api/sandboxes.md | 2 + openshell/v1/sandbox_client.go | 26 ++++----- openshell/v1/sandbox_client_test.go | 91 +++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 13 deletions(-) diff --git a/docs/src/api/sandboxes.md b/docs/src/api/sandboxes.md index 8e66cfc..ff38122 100644 --- a/docs/src/api/sandboxes.md +++ b/docs/src/api/sandboxes.md @@ -227,6 +227,8 @@ Each `Event[T]` carries: - `Type`: one of `EventAdded`, `EventModified`, `EventDeleted`, or `EventError` - `Object`: the `*Sandbox` at that point in time (`nil` for `EventError`) +The channel closes when the server ends the stream, when `StopOnTerminal` sees a terminal phase, when `ctx` is cancelled, or after `Stop`. Cancelling `ctx` or calling `Stop` closes it without an `EventError`, even if nothing is reading: `EventError` reports only a stream failure, such as the gateway becoming unavailable. + ```go watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox") if err != nil { diff --git a/openshell/v1/sandbox_client.go b/openshell/v1/sandbox_client.go index a0a9382..0011abd 100644 --- a/openshell/v1/sandbox_client.go +++ b/openshell/v1/sandbox_client.go @@ -395,6 +395,14 @@ func checkTerminalPhase(sb *Sandbox, name string, target SandboxPhase) (*Sandbox } } +// Watch streams status changes for one sandbox. The first event is +// EventAdded, later ones EventModified, and EventDeleted once the sandbox is +// deleting. +// +// The channel closes when the server ends the stream, when StopOnTerminal +// sees a terminal phase, when ctx is cancelled, or after Stop. Cancelling ctx +// or calling Stop closes it without an EventError: EventError reports only a +// stream failure, such as the gateway becoming unavailable. func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts ...WatchOptions) (WatchInterface[*Sandbox], error) { if name == "" { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"} @@ -444,9 +452,7 @@ func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts } else if sandbox.Status.Phase == SandboxDeleting { eventType = EventDeleted } - select { - case ch <- Event[*Sandbox]{Type: eventType, Object: sandbox}: - case <-w.done: + if !w.emit(streamCtx, Event[*Sandbox]{Type: eventType, Object: sandbox}) { return } if watchOpts.StopOnTerminal && (sandbox.Status.Phase == SandboxReady || sandbox.Status.Phase == SandboxCompleted || sandbox.Status.Phase == SandboxStopped || sandbox.Status.Phase == SandboxError) { @@ -457,16 +463,10 @@ func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts var recvErr error ev, recvErr = stream.Recv() if recvErr != nil { - if recvErr != io.EOF { - select { - case <-w.done: - return - default: - } - select { - case ch <- Event[*Sandbox]{Type: EventError, Err: converter.FromGRPCError(recvErr)}: - case <-w.done: - } + // A cancelled stream after Stop or ctx cancellation is the + // caller's own doing, not a failure to report. + if recvErr != io.EOF && !w.stopped() && streamCtx.Err() == nil { + w.emit(streamCtx, Event[*Sandbox]{Type: EventError, Err: converter.FromGRPCError(recvErr)}) } return } diff --git a/openshell/v1/sandbox_client_test.go b/openshell/v1/sandbox_client_test.go index e77a346..a86d58d 100644 --- a/openshell/v1/sandbox_client_test.go +++ b/openshell/v1/sandbox_client_test.go @@ -1163,6 +1163,97 @@ func TestSandboxWatch_StopCancelsStream(t *testing.T) { } } +// sandboxEvents returns n status snapshots for sb-1, so a test can fill the +// Watch channel. +func sandboxEvents(n int) []*pb.SandboxStreamEvent { + events := make([]*pb.SandboxStreamEvent, n) + for i := range events { + events[i] = &pb.SandboxStreamEvent{Payload: &pb.SandboxStreamEvent_Sandbox{Sandbox: &pb.Sandbox{ + Metadata: &dm.ObjectMeta{Name: "sb-1", Id: "id-1"}, + Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_PROVISIONING}, + }}} + } + return events +} + +// drainSandboxWatch collects events until the channel closes. +func drainSandboxWatch(t *testing.T, w WatchInterface[*Sandbox]) []Event[*Sandbox] { + t.Helper() + var events []Event[*Sandbox] + timeout := time.After(5 * 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 the Watch channel to close") + } + } +} + +func TestSandboxWatch_ContextCancelUnblocksFullChannel(t *testing.T) { + // A consumer that cancels ctx without reading must not leave the producer + // blocked on a full channel: it has to stop sending and close. + const total = 100 + 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_PROVISIONING}, + } + mock.watchEvents = sandboxEvents(total) + 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.Watch(ctx, "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + ch := w.ResultChan() + require.Eventually(t, func() bool { return len(ch) == cap(ch) }, 5*time.Second, 5*time.Millisecond, + "producer never filled the channel") + cancel() + + events := drainSandboxWatch(t, w) + // The buffered events drain, plus at most one send that raced the + // cancellation. A producer that ignored ctx would deliver all of them. + assert.LessOrEqual(t, len(events), cap(ch)+1) + for _, ev := range events { + assert.NotEqual(t, EventError, ev.Type, "cancellation must not surface as an error: %v", ev.Err) + } +} + +func TestSandboxWatch_ContextCancelClosesWithoutError(t *testing.T) { + 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_PROVISIONING}, + } + mock.watchEvents = sandboxEvents(1) + 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.Watch(ctx, "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + ev := <-w.ResultChan() + assert.Equal(t, EventAdded, ev.Type) + + cancel() + assert.Empty(t, drainSandboxWatch(t, w), "cancellation must close the channel without an error event") +} + func TestSandboxWatch_RPCError(t *testing.T) { mock := newMockSandboxServer() mock.sandboxes["watch-err"] = &pb.Sandbox{ From e3f2591172b231c7f93e24e0dcd29ec06ed7e9f1 Mon Sep 17 00:00:00 2001 From: Artem Lytvyn Date: Wed, 25 Nov 2026 12:58:07 +0000 Subject: [PATCH 2/2] test(sandbox): cover Stop and deadline endings of Watch, document contract on the interface Signed-off-by: Artem Lytvyn --- docs/src/api/sandboxes.md | 2 +- openshell/v1/sandbox.go | 10 +++ openshell/v1/sandbox_client.go | 9 +-- openshell/v1/sandbox_client_test.go | 110 ++++++++++++++++++++-------- 4 files changed, 90 insertions(+), 41 deletions(-) diff --git a/docs/src/api/sandboxes.md b/docs/src/api/sandboxes.md index ff38122..164d438 100644 --- a/docs/src/api/sandboxes.md +++ b/docs/src/api/sandboxes.md @@ -227,7 +227,7 @@ Each `Event[T]` carries: - `Type`: one of `EventAdded`, `EventModified`, `EventDeleted`, or `EventError` - `Object`: the `*Sandbox` at that point in time (`nil` for `EventError`) -The channel closes when the server ends the stream, when `StopOnTerminal` sees a terminal phase, when `ctx` is cancelled, or after `Stop`. Cancelling `ctx` or calling `Stop` closes it without an `EventError`, even if nothing is reading: `EventError` reports only a stream failure, such as the gateway becoming unavailable. +The channel closes when the server ends the stream, when `StopOnTerminal` sees a terminal phase, when `ctx` is cancelled or its deadline passes, or after `Stop`. Ending `ctx` or calling `Stop` closes it without an `EventError`, even if nothing is reading: `EventError` reports only a stream failure, such as the gateway becoming unavailable. After the channel closes, check `ctx.Err()` to tell a timeout or cancellation apart from the server ending the stream. ```go watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox") diff --git a/openshell/v1/sandbox.go b/openshell/v1/sandbox.go index 4fb26af..79ebd7e 100644 --- a/openshell/v1/sandbox.go +++ b/openshell/v1/sandbox.go @@ -117,6 +117,16 @@ type SandboxInterface interface { ListAllProviders(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*Provider, error) WaitReady(ctx context.Context, workspace, name string, opts ...WaitOptions) (*Sandbox, error) WaitStopped(ctx context.Context, workspace, name string, opts ...WaitOptions) (*Sandbox, error) + // Watch streams status changes for one sandbox. The first event is + // EventAdded, later ones EventModified, and EventDeleted once the sandbox + // is deleting. + // + // The channel closes when the server ends the stream, when StopOnTerminal + // sees a terminal phase, when ctx is cancelled or its deadline passes, or + // after Stop. Ending ctx or calling Stop closes it without an EventError: + // EventError reports only a stream failure, such as the gateway becoming + // unavailable. After the channel closes, check ctx.Err() to tell a timeout + // or cancellation apart from the server ending the stream. Watch(ctx context.Context, workspace, name string, opts ...WatchOptions) (WatchInterface[*Sandbox], error) GetLogs(ctx context.Context, workspace, sandboxName string, opts ...LogOption) (*LogResult, error) } diff --git a/openshell/v1/sandbox_client.go b/openshell/v1/sandbox_client.go index 0011abd..f39a467 100644 --- a/openshell/v1/sandbox_client.go +++ b/openshell/v1/sandbox_client.go @@ -395,14 +395,7 @@ func checkTerminalPhase(sb *Sandbox, name string, target SandboxPhase) (*Sandbox } } -// Watch streams status changes for one sandbox. The first event is -// EventAdded, later ones EventModified, and EventDeleted once the sandbox is -// deleting. -// -// The channel closes when the server ends the stream, when StopOnTerminal -// sees a terminal phase, when ctx is cancelled, or after Stop. Cancelling ctx -// or calling Stop closes it without an EventError: EventError reports only a -// stream failure, such as the gateway becoming unavailable. +// Watch implements SandboxInterface.Watch. func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts ...WatchOptions) (WatchInterface[*Sandbox], error) { if name == "" { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"} diff --git a/openshell/v1/sandbox_client_test.go b/openshell/v1/sandbox_client_test.go index a86d58d..ae3d31b 100644 --- a/openshell/v1/sandbox_client_test.go +++ b/openshell/v1/sandbox_client_test.go @@ -1194,42 +1194,87 @@ func drainSandboxWatch(t *testing.T, w WatchInterface[*Sandbox]) []Event[*Sandbo } } -func TestSandboxWatch_ContextCancelUnblocksFullChannel(t *testing.T) { - // A consumer that cancels ctx without reading must not leave the producer - // blocked on a full channel: it has to stop sending and close. - const total = 100 - 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_PROVISIONING}, +// watchEnders are the two ways a caller ends a Watch. Both must close the +// channel without an EventError. +var watchEnders = []struct { + name string + end func(cancel context.CancelFunc, w WatchInterface[*Sandbox]) +}{ + {"ContextCancel", func(cancel context.CancelFunc, _ WatchInterface[*Sandbox]) { cancel() }}, + {"Stop", func(_ context.CancelFunc, w WatchInterface[*Sandbox]) { w.Stop() }}, +} + +func TestSandboxWatch_EndUnblocksFullChannel(t *testing.T) { + // A consumer that ends the watch without reading must not leave the + // producer blocked on a full channel: it has to stop sending and close. + for _, tc := range watchEnders { + t.Run(tc.name, func(t *testing.T) { + const total = 100 + 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_PROVISIONING}, + } + mock.watchEvents = sandboxEvents(total) + keepOpen := make(chan struct{}) + defer close(keepOpen) + mock.watchKeepOpen = keepOpen + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w, err := client.Watch(ctx, "default", "sb-1") + require.NoError(t, err) + defer w.Stop() + + ch := w.ResultChan() + require.Eventually(t, func() bool { return len(ch) == cap(ch) }, 5*time.Second, 5*time.Millisecond, + "producer never filled the channel") + tc.end(cancel, w) + + events := drainSandboxWatch(t, w) + // The buffered events drain, plus at most one send that raced + // the end. A producer that ignored it would deliver all of them. + assert.LessOrEqual(t, len(events), cap(ch)+1) + for _, ev := range events { + assert.NotEqual(t, EventError, ev.Type, "ending the watch must not surface as an error: %v", ev.Err) + } + }) } - mock.watchEvents = sandboxEvents(total) - 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.Watch(ctx, "default", "sb-1") - require.NoError(t, err) - defer w.Stop() +func TestSandboxWatch_EndClosesWithoutError(t *testing.T) { + for _, tc := range watchEnders { + t.Run(tc.name, func(t *testing.T) { + 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_PROVISIONING}, + } + mock.watchEvents = sandboxEvents(1) + keepOpen := make(chan struct{}) + defer close(keepOpen) + mock.watchKeepOpen = keepOpen + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() - ch := w.ResultChan() - require.Eventually(t, func() bool { return len(ch) == cap(ch) }, 5*time.Second, 5*time.Millisecond, - "producer never filled the channel") - cancel() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w, err := client.Watch(ctx, "default", "sb-1") + require.NoError(t, err) + defer w.Stop() - events := drainSandboxWatch(t, w) - // The buffered events drain, plus at most one send that raced the - // cancellation. A producer that ignored ctx would deliver all of them. - assert.LessOrEqual(t, len(events), cap(ch)+1) - for _, ev := range events { - assert.NotEqual(t, EventError, ev.Type, "cancellation must not surface as an error: %v", ev.Err) + ev := <-w.ResultChan() + assert.Equal(t, EventAdded, ev.Type) + + tc.end(cancel, w) + assert.Empty(t, drainSandboxWatch(t, w), "ending the watch must close the channel without an error event") + }) } } -func TestSandboxWatch_ContextCancelClosesWithoutError(t *testing.T) { +func TestSandboxWatch_DeadlineClosesWithoutError(t *testing.T) { mock := newMockSandboxServer() mock.sandboxes["sb-1"] = &pb.Sandbox{ Metadata: &dm.ObjectMeta{Id: "id-1", Name: "sb-1"}, @@ -1242,7 +1287,8 @@ func TestSandboxWatch_ContextCancelClosesWithoutError(t *testing.T) { client, cleanup := setupSandboxTest(t, mock) defer cleanup() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() w, err := client.Watch(ctx, "default", "sb-1") require.NoError(t, err) defer w.Stop() @@ -1250,8 +1296,8 @@ func TestSandboxWatch_ContextCancelClosesWithoutError(t *testing.T) { ev := <-w.ResultChan() assert.Equal(t, EventAdded, ev.Type) - cancel() - assert.Empty(t, drainSandboxWatch(t, w), "cancellation must close the channel without an error event") + assert.Empty(t, drainSandboxWatch(t, w), "a passed deadline must close the channel without an error event") + assert.ErrorIs(t, ctx.Err(), context.DeadlineExceeded) } func TestSandboxWatch_RPCError(t *testing.T) {