From 4bc9e6afdd0ee1a710a1918e790f373a47ba6ff6 Mon Sep 17 00:00:00 2001 From: Artem Lytvyn Date: Tue, 17 Nov 2026 23:02:58 +0000 Subject: [PATCH] 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{