| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "sync/atomic" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/sylvinus/agent-vm/internal/remotehost" |
| 16 | ) |
| 17 | |
| 18 | type gatewayLocalFixture struct { |
| 19 | endpoint *httptest.Server |
| 20 | connections, suspended, commands atomic.Int32 |
| 21 | status DesktopLocalStatus |
| 22 | release func(DesktopLocalStatus, bool) error |
| 23 | owned bool |
| 24 | } |
| 25 | |
| 26 | func gatewayFixture(t *testing.T) (*Server, *gatewayLocalFixture) { |
| 27 | t.Helper() |
| 28 | s := testServer(t) |
| 29 | f := &gatewayLocalFixture{status: DesktopLocalStatus{Known: true, Available: true}} |
| 30 | f.endpoint = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 31 | w.Header().Set("Content-Type", "application/json") |
| 32 | switch r.URL.Path { |
| 33 | case "/api/account/suspend": |
| 34 | var input map[string]any |
| 35 | if r.Header.Get("Content-Type") != "application/json" || json.NewDecoder(r.Body).Decode(&input) != nil { |
| 36 | http.Error(w, "invalid account request", 400) |
| 37 | return |
| 38 | } |
| 39 | f.suspended.Add(1) |
| 40 | default: |
| 41 | f.commands.Add(1) |
| 42 | } |
| 43 | _, _ = w.Write([]byte(`{"upstream":"local-controller"}`)) |
| 44 | })) |
| 45 | t.Cleanup(f.endpoint.Close) |
| 46 | s.remote = newDesktopGateway(s.profile, f) |
| 47 | t.Cleanup(s.remote.close) |
| 48 | return s, f |
| 49 | } |
| 50 | |
| 51 | func (f *gatewayLocalFixture) Connect(ctx context.Context) (*remotehost.Session, error) { |
| 52 | f.connections.Add(1) |
| 53 | return &remotehost.Session{Origin: f.endpoint.URL, Client: f.endpoint.Client(), Transport: f.endpoint.Client().Transport, Context: ctx, Manifest: remotehost.PublicManifest{Platform: "linux", InstanceID: strings.Repeat("a", 64)}}, nil |
| 54 | } |
| 55 | func (f *gatewayLocalFixture) Status(context.Context) (DesktopLocalStatus, error) { |
| 56 | return f.status, nil |
| 57 | } |
| 58 | func (f *gatewayLocalFixture) Release(_ context.Context, expected DesktopLocalStatus, stop bool) error { |
| 59 | if f.release == nil { |
| 60 | return errors.New("unexpected release") |
| 61 | } |
| 62 | return f.release(expected, stop) |
| 63 | } |
| 64 | |
| 65 | func (f *gatewayLocalFixture) ReleaseOwnedIdle(context.Context, DesktopLocalStatus) (bool, error) { |
| 66 | return f.owned, nil |
| 67 | } |
| 68 | |
| 69 | func candidateState(t *testing.T, d *desktopGateway, want string) *desktopCandidate { |
| 70 | t.Helper() |
| 71 | deadline := time.Now().Add(time.Second * 5) |
| 72 | for time.Now().Before(deadline) { |
| 73 | c := d.context().Candidate |
| 74 | if c != nil && c.Connection.State == want { |
| 75 | return c |
| 76 | } |
| 77 | time.Sleep(time.Millisecond * 5) |
| 78 | } |
| 79 | t.Fatalf("candidate did not reach %s: %+v", want, d.context().Candidate) |
| 80 | return nil |
| 81 | } |
| 82 | |
| 83 | func gatewayRequest(s *Server, path, generation string) *httptest.ResponseRecorder { |
| 84 | r := httptest.NewRequest("GET", s.origin+path, nil) |
| 85 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 86 | if generation != "" { |
| 87 | r.Header.Set(connectionHeader, generation) |
| 88 | } |
| 89 | w := httptest.NewRecorder() |
| 90 | s.handler().ServeHTTP(w, r) |
| 91 | return w |
| 92 | } |
| 93 | |
| 94 | func chooseLocal(t *testing.T, d *desktopGateway, id string) string { |
| 95 | t.Helper() |
| 96 | c, e := d.prepare(switchRequest{ConnectionID: id, Mode: "local"}) |
| 97 | if e != nil { |
| 98 | t.Fatal(e) |
| 99 | } |
| 100 | candidateState(t, d, "connected") |
| 101 | if e = d.commit(context.Background(), switchRequest{ConnectionID: id, CandidateID: c.ID}); e != nil { |
| 102 | t.Fatal(e) |
| 103 | } |
| 104 | return c.ID |
| 105 | } |
| 106 | |
| 107 | func TestDesktopCandidateFailurePreservesLiveViewAndStaleLocalIDs(t *testing.T) { |
| 108 | s, f := gatewayFixture(t) |
| 109 | d := s.remote.desktop |
| 110 | none := d.context().ConnectionID |
| 111 | if c := d.context(); c.Mode != "none" || c.ConnectionID == "" || f.connections.Load() != 0 { |
| 112 | t.Fatal("cold shell started a local controller", c) |
| 113 | } |
| 114 | if got := gatewayRequest(s, "/api/account", none); got.Code != 409 { |
| 115 | t.Fatal("unselected view exposed a local business API", got.Code) |
| 116 | } |
| 117 | local := chooseLocal(t, d, none) |
| 118 | if got := gatewayRequest(s, "/api/status", local); got.Code != 200 || !strings.Contains(got.Body.String(), "local-controller") { |
| 119 | t.Fatal("selected view did not go to the local controller", got.Code, got.Body.String()) |
| 120 | } |
| 121 | |
| 122 | host, err := s.remote.store.Upsert(remotehost.HostProfile{Name: "fixture", Host: "127.0.0.1", Port: 22, User: "cage", Auth: remotehost.AuthConfig{Kind: "key_file", IdentityFile: filepath.Join(t.TempDir(), "absent")}}) |
| 123 | if err != nil { |
| 124 | t.Fatal(err) |
| 125 | } |
| 126 | remote, err := d.prepare(switchRequest{ConnectionID: local, Mode: "remote", HostID: host.ID}) |
| 127 | if err != nil { |
| 128 | t.Fatal(err) |
| 129 | } |
| 130 | candidateState(t, d, "failed") |
| 131 | if got := gatewayRequest(s, "/api/status", remote.ID); got.Code != 409 { |
| 132 | t.Fatal("uncommitted target dispatched a business API", got.Code) |
| 133 | } |
| 134 | if err = d.commit(context.Background(), switchRequest{ConnectionID: local, CandidateID: remote.ID, LocalAction: "stop"}); err == nil { |
| 135 | t.Fatal("failed candidate could stop or replace the current view") |
| 136 | } |
| 137 | if got := gatewayRequest(s, "/api/status", local); got.Code != 200 || f.commands.Load() != 2 || f.suspended.Load() != 0 { |
| 138 | t.Fatal("candidate failure affected the live view") |
| 139 | } |
| 140 | if err = d.cancelCandidate(switchRequest{ConnectionID: local, CandidateID: remote.ID}); err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | if err = d.disconnect(context.Background(), switchRequest{ConnectionID: local}); err != nil { |
| 144 | t.Fatal(err) |
| 145 | } |
| 146 | second := chooseLocal(t, d, d.context().ConnectionID) |
| 147 | if second == local || f.suspended.Load() != 1 { |
| 148 | t.Fatal("local reconnection reused a generation or failed to suspend the old view") |
| 149 | } |
| 150 | for _, stale := range []string{"", none, "local", local, remote.ID} { |
| 151 | if got := gatewayRequest(s, "/api/status", stale); got.Code != 409 { |
| 152 | t.Fatalf("obsolete ID %q reached local runtime, code %d", stale, got.Code) |
| 153 | } |
| 154 | } |
| 155 | if got := gatewayRequest(s, "/api/status", second); got.Code != 200 { |
| 156 | t.Fatal("current connection rejected", got.Code) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | func TestDesktopRemoteCommitRequiresDecisionBeforeReleasingObservedLocal(t *testing.T) { |
| 161 | s, f := gatewayFixture(t) |
| 162 | d := s.remote.desktop |
| 163 | original := chooseLocal(t, d, d.context().ConnectionID) |
| 164 | f.status = DesktopLocalStatus{Available: true, Known: true, Running: true, ServiceRunning: true, LiveTerminals: 1, ControllerID: "current-controller"} |
| 165 | |
| 166 | |
| 167 | ctx, cancel := context.WithCancel(context.Background()) |
| 168 | session, err := f.Connect(ctx) |
| 169 | if err != nil { |
| 170 | t.Fatal(err) |
| 171 | } |
| 172 | candidate := &desktopTarget{id: "remote-generation", mode: "remote", ctx: ctx, cancel: cancel, session: session} |
| 173 | d.mu.Lock() |
| 174 | d.pending = candidate |
| 175 | d.mu.Unlock() |
| 176 | in := switchRequest{ConnectionID: original, CandidateID: candidate.id, LocalAction: "auto"} |
| 177 | if err := d.commit(context.Background(), in); err == nil { |
| 178 | t.Fatal("auto released a busy local controller") |
| 179 | } |
| 180 | in.LocalAction = "stop" |
| 181 | in.LocalControllerID = "obsolete-controller" |
| 182 | if err := d.commit(context.Background(), in); err == nil { |
| 183 | t.Fatal("obsolete controller ID stopped the replacement") |
| 184 | } |
| 185 | in.LocalControllerID = f.status.ControllerID |
| 186 | f.release = func(observed DesktopLocalStatus, stop bool) error { |
| 187 | if !stop || observed.ControllerID != f.status.ControllerID { |
| 188 | t.Fatal("wrong stop target") |
| 189 | } |
| 190 | if got := gatewayRequest(s, "/api/status", original); got.Code != http.StatusConflict { |
| 191 | t.Fatal("another window admitted a business request while releasing the local controller") |
| 192 | } |
| 193 | return errDesktopLocalLocked |
| 194 | } |
| 195 | if err := d.commit(context.Background(), in); !errors.Is(err, errDesktopLocalLocked) { |
| 196 | t.Fatalf("locked account result %v", err) |
| 197 | } |
| 198 | if d.context().ConnectionID != original || f.suspended.Load() != 0 { |
| 199 | t.Fatal("failed stop changed current selection") |
| 200 | } |
| 201 | if got := gatewayRequest(s, "/api/status", original); got.Code != http.StatusOK { |
| 202 | t.Fatal("failed stop left admission frozen for the retained local view") |
| 203 | } |
| 204 | in.LocalAction = "keep" |
| 205 | if err := d.commit(context.Background(), in); err != nil { |
| 206 | t.Fatal(err) |
| 207 | } |
| 208 | if now := d.context(); now.Mode != "remote" || now.ConnectionID != candidate.id || now.Candidate != nil || f.suspended.Load() != 1 { |
| 209 | t.Fatalf("incorrect committed view or unsuspended previous view: %+v", now) |
| 210 | } |
| 211 | if got := gatewayRequest(s, "/api/status", original); got.Code != 409 { |
| 212 | t.Fatal("old local request reached selected remote") |
| 213 | } |
| 214 | if err := d.disconnect(context.Background(), switchRequest{ConnectionID: original}); err == nil { |
| 215 | t.Fatal("stale disconnect closed remote selection") |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | func TestRemoteToRemoteSwitchHonorsBackgroundLocalDecision(t *testing.T) { |
| 220 | for _, action := range []string{"keep", "stop"} { |
| 221 | t.Run(action, func(t *testing.T) { |
| 222 | s, local := gatewayFixture(t) |
| 223 | d := s.remote.desktop |
| 224 | local.status = DesktopLocalStatus{Known: true, Available: true, ServiceRunning: true, Running: true, LiveTerminals: 1, ControllerID: "background-controller"} |
| 225 | |
| 226 | |
| 227 | remoteView := func(id string) *desktopTarget { |
| 228 | ctx, cancel := context.WithCancel(context.Background()) |
| 229 | session, err := local.Connect(ctx) |
| 230 | if err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | return &desktopTarget{id: id, mode: "remote", ctx: ctx, cancel: cancel, session: session} |
| 234 | } |
| 235 | a, b := remoteView("remote-A"), remoteView("remote-B") |
| 236 | d.mu.Lock() |
| 237 | d.generation, d.active, d.pending = a.id, a, b |
| 238 | d.mu.Unlock() |
| 239 | request := switchRequest{ConnectionID: a.id, CandidateID: b.id, LocalAction: "auto"} |
| 240 | if err := d.commit(context.Background(), request); err == nil { |
| 241 | t.Fatal("background local work did not require an explicit choice") |
| 242 | } |
| 243 | if got := gatewayRequest(s, "/api/status", a.id); got.Code != http.StatusOK { |
| 244 | t.Fatal("A became unavailable while waiting for the local decision") |
| 245 | } |
| 246 | request.LocalAction, request.LocalControllerID = action, local.status.ControllerID |
| 247 | stops := 0 |
| 248 | local.release = func(expected DesktopLocalStatus, stop bool) error { |
| 249 | stops++ |
| 250 | if !stop || expected.ControllerID != local.status.ControllerID { |
| 251 | t.Fatal("stopped the wrong controller") |
| 252 | } |
| 253 | if got := gatewayRequest(s, "/api/status", a.id); got.Code != http.StatusOK { |
| 254 | t.Fatal("A was released before the local stop completed") |
| 255 | } |
| 256 | return nil |
| 257 | } |
| 258 | if err := d.commit(context.Background(), request); err != nil { |
| 259 | t.Fatal(err) |
| 260 | } |
| 261 | if (action == "stop" && stops != 1) || (action == "keep" && stops != 0) || local.suspended.Load() != 0 { |
| 262 | t.Fatalf("incorrect workload action: stop count %d, account suspensions %d", stops, local.suspended.Load()) |
| 263 | } |
| 264 | if d.context().ConnectionID != b.id || a.ctx.Err() == nil { |
| 265 | t.Fatal("successful commit did not switch exclusively to B") |
| 266 | } |
| 267 | }) |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | func TestRemoteAutoReleasesOnlyOwnedLocalService(t *testing.T) { |
| 272 | for _, tc := range []struct { |
| 273 | name string |
| 274 | localView, owned bool |
| 275 | wantSuspend int32 |
| 276 | }{ |
| 277 | {"external-service-with-no-local-view", false, false, 0}, |
| 278 | {"external-service-with-local-view", true, false, 1}, |
| 279 | {"owned-service-with-local-view", true, true, 0}, |
| 280 | } { |
| 281 | t.Run(tc.name, func(t *testing.T) { |
| 282 | s, f := gatewayFixture(t) |
| 283 | d := s.remote.desktop |
| 284 | f.status = DesktopLocalStatus{Known: true, Available: true, ServiceRunning: true, ControllerID: "idle-service"} |
| 285 | f.owned = tc.owned |
| 286 | if tc.localView { |
| 287 | chooseLocal(t, d, d.context().ConnectionID) |
| 288 | } |
| 289 | err := d.leaveLocal(context.Background(), switchRequest{LocalAction: "auto"}, d.active) |
| 290 | if err != nil || f.suspended.Load() != tc.wantSuspend { |
| 291 | t.Fatalf("auto used the wrong owner or directly stopped a controller: err=%v suspensions=%d", err, f.suspended.Load()) |
| 292 | } |
| 293 | }) |
| 294 | } |
| 295 | } |