|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "strings" |
| 10 | + "sync" |
| 11 | + "testing" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/coder/websocket" |
| 15 | + |
| 16 | + "github.com/kristofferrisa/powerctl-cli/internal/models" |
| 17 | +) |
| 18 | + |
| 19 | +// liveServer is a minimal graphql-transport-ws server standing in for Tibber, so |
| 20 | +// the reconnect path can be exercised over a real socket rather than a stub. |
| 21 | +type liveServer struct { |
| 22 | + *httptest.Server |
| 23 | + |
| 24 | + mu sync.Mutex |
| 25 | + conns int |
| 26 | +} |
| 27 | + |
| 28 | +// startLiveServer accepts WebSocket connections and hands each one to session, |
| 29 | +// already past connection_init, with the 1-based connection number. |
| 30 | +func startLiveServer(t *testing.T, session func(ctx context.Context, conn *websocket.Conn, n int)) *liveServer { |
| 31 | + t.Helper() |
| 32 | + |
| 33 | + s := &liveServer{} |
| 34 | + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 35 | + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{ |
| 36 | + Subprotocols: []string{"graphql-transport-ws"}, |
| 37 | + }) |
| 38 | + if err != nil { |
| 39 | + return |
| 40 | + } |
| 41 | + defer conn.CloseNow() |
| 42 | + |
| 43 | + s.mu.Lock() |
| 44 | + s.conns++ |
| 45 | + n := s.conns |
| 46 | + s.mu.Unlock() |
| 47 | + |
| 48 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 49 | + defer cancel() |
| 50 | + |
| 51 | + if _, _, err := conn.Read(ctx); err != nil { // connection_init |
| 52 | + return |
| 53 | + } |
| 54 | + session(ctx, conn, n) |
| 55 | + })) |
| 56 | + t.Cleanup(s.Close) |
| 57 | + return s |
| 58 | +} |
| 59 | + |
| 60 | +func (s *liveServer) connections() int { |
| 61 | + s.mu.Lock() |
| 62 | + defer s.mu.Unlock() |
| 63 | + return s.conns |
| 64 | +} |
| 65 | + |
| 66 | +// client returns a LiveClient pointed at this server. |
| 67 | +func (s *liveServer) client() *LiveClient { |
| 68 | + c := NewLiveClient("test-token", "test-home") |
| 69 | + c.endpoint = "ws" + strings.TrimPrefix(s.URL, "http") |
| 70 | + return c |
| 71 | +} |
| 72 | + |
| 73 | +func send(ctx context.Context, conn *websocket.Conn, msgType string, payload string) error { |
| 74 | + data, err := json.Marshal(wsMessage{Type: msgType, ID: "1", Payload: json.RawMessage(payload)}) |
| 75 | + if err != nil { |
| 76 | + return err |
| 77 | + } |
| 78 | + return conn.Write(ctx, websocket.MessageText, data) |
| 79 | +} |
| 80 | + |
| 81 | +func ackAndAwaitSubscribe(ctx context.Context, conn *websocket.Conn) error { |
| 82 | + if err := send(ctx, conn, "connection_ack", ""); err != nil { |
| 83 | + return err |
| 84 | + } |
| 85 | + _, _, err := conn.Read(ctx) // subscribe |
| 86 | + return err |
| 87 | +} |
| 88 | + |
| 89 | +const measurementPayload = `{"data":{"liveMeasurement":{"timestamp":"2026-01-01T12:00:00Z","power":1234}}}` |
| 90 | + |
| 91 | +// fastPolicy retries almost immediately so the tests do not wait on real backoff. |
| 92 | +func fastPolicy() ReconnectPolicy { |
| 93 | + p := DefaultReconnectPolicy() |
| 94 | + p.BaseDelay = time.Millisecond |
| 95 | + p.MaxDelay = time.Millisecond |
| 96 | + return p |
| 97 | +} |
| 98 | + |
| 99 | +func TestSubscribeWithReconnect_RecoversFromDroppedConnection(t *testing.T) { |
| 100 | + server := startLiveServer(t, func(ctx context.Context, conn *websocket.Conn, n int) { |
| 101 | + if err := ackAndAwaitSubscribe(ctx, conn); err != nil { |
| 102 | + return |
| 103 | + } |
| 104 | + if err := send(ctx, conn, "next", measurementPayload); err != nil { |
| 105 | + return |
| 106 | + } |
| 107 | + if n == 1 { |
| 108 | + conn.CloseNow() // the blip: no close handshake, just a dead socket |
| 109 | + return |
| 110 | + } |
| 111 | + _ = send(ctx, conn, "complete", "") |
| 112 | + }) |
| 113 | + |
| 114 | + var measurements []*models.LiveMeasurement |
| 115 | + err := server.client().SubscribeWithReconnect(context.Background(), fastPolicy(), |
| 116 | + func(m *models.LiveMeasurement) error { |
| 117 | + measurements = append(measurements, m) |
| 118 | + return nil |
| 119 | + }) |
| 120 | + |
| 121 | + if err != nil { |
| 122 | + t.Fatalf("expected the stream to recover, got %v", err) |
| 123 | + } |
| 124 | + if server.connections() != 2 { |
| 125 | + t.Errorf("expected 2 connections, got %d", server.connections()) |
| 126 | + } |
| 127 | + if len(measurements) != 2 { |
| 128 | + t.Fatalf("expected 2 measurements across the reconnect, got %d", len(measurements)) |
| 129 | + } |
| 130 | + for i, m := range measurements { |
| 131 | + if m == nil || m.Power != 1234 { |
| 132 | + t.Errorf("measurement %d: expected 1234 W, got %v", i, m) |
| 133 | + } |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +func TestSubscribeWithReconnect_DoesNotRetryFatalErrors(t *testing.T) { |
| 138 | + tests := []struct { |
| 139 | + name string |
| 140 | + session func(ctx context.Context, conn *websocket.Conn, n int) |
| 141 | + wantErr string |
| 142 | + }{ |
| 143 | + { |
| 144 | + name: "rejected token", |
| 145 | + session: func(ctx context.Context, conn *websocket.Conn, _ int) { |
| 146 | + _ = send(ctx, conn, "connection_error", `{"message":"Invalid token"}`) |
| 147 | + }, |
| 148 | + wantErr: "connection rejected", |
| 149 | + }, |
| 150 | + { |
| 151 | + name: "token refused with close code 4403", |
| 152 | + session: func(_ context.Context, conn *websocket.Conn, _ int) { |
| 153 | + _ = conn.Close(statusInvalidToken, "Invalid token") |
| 154 | + }, |
| 155 | + wantErr: "4403", |
| 156 | + }, |
| 157 | + { |
| 158 | + name: "unknown home ID", |
| 159 | + session: func(ctx context.Context, conn *websocket.Conn, _ int) { |
| 160 | + if err := ackAndAwaitSubscribe(ctx, conn); err != nil { |
| 161 | + return |
| 162 | + } |
| 163 | + _ = send(ctx, conn, "next", `{"errors":[{"message":"home not found"}],"data":{"liveMeasurement":null}}`) |
| 164 | + }, |
| 165 | + wantErr: "invalid or non-existing home ID", |
| 166 | + }, |
| 167 | + { |
| 168 | + name: "subscription error", |
| 169 | + session: func(ctx context.Context, conn *websocket.Conn, _ int) { |
| 170 | + if err := ackAndAwaitSubscribe(ctx, conn); err != nil { |
| 171 | + return |
| 172 | + } |
| 173 | + _ = send(ctx, conn, "error", `[{"message":"query is not valid"}]`) |
| 174 | + }, |
| 175 | + wantErr: "subscription error", |
| 176 | + }, |
| 177 | + } |
| 178 | + |
| 179 | + for _, tt := range tests { |
| 180 | + t.Run(tt.name, func(t *testing.T) { |
| 181 | + server := startLiveServer(t, tt.session) |
| 182 | + |
| 183 | + err := server.client().SubscribeWithReconnect(context.Background(), fastPolicy(), |
| 184 | + func(*models.LiveMeasurement) error { return nil }) |
| 185 | + |
| 186 | + if err == nil { |
| 187 | + t.Fatal("expected an error, got nil") |
| 188 | + } |
| 189 | + if !strings.Contains(err.Error(), tt.wantErr) { |
| 190 | + t.Errorf("expected an error containing %q, got %q", tt.wantErr, err) |
| 191 | + } |
| 192 | + if errors.Is(err, ErrReconnectBudget) { |
| 193 | + t.Error("retried a fatal error until the connection budget ran out") |
| 194 | + } |
| 195 | + if server.connections() != 1 { |
| 196 | + t.Errorf("expected 1 connection attempt, got %d", server.connections()) |
| 197 | + } |
| 198 | + }) |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +func TestSubscribeWithReconnect_StopsWhenCancelled(t *testing.T) { |
| 203 | + ctx, cancel := context.WithCancel(context.Background()) |
| 204 | + defer cancel() |
| 205 | + |
| 206 | + server := startLiveServer(t, func(sctx context.Context, conn *websocket.Conn, _ int) { |
| 207 | + if err := ackAndAwaitSubscribe(sctx, conn); err != nil { |
| 208 | + return |
| 209 | + } |
| 210 | + for { |
| 211 | + if err := send(sctx, conn, "next", measurementPayload); err != nil { |
| 212 | + return |
| 213 | + } |
| 214 | + time.Sleep(time.Millisecond) |
| 215 | + } |
| 216 | + }) |
| 217 | + |
| 218 | + received := 0 |
| 219 | + start := time.Now() |
| 220 | + err := server.client().SubscribeWithReconnect(ctx, fastPolicy(), |
| 221 | + func(*models.LiveMeasurement) error { |
| 222 | + received++ |
| 223 | + if received == 3 { |
| 224 | + cancel() // stand-in for Ctrl+C |
| 225 | + } |
| 226 | + return nil |
| 227 | + }) |
| 228 | + |
| 229 | + // Ctrl+C must not wait on a close handshake the server may never answer. |
| 230 | + if elapsed := time.Since(start); elapsed > 2*time.Second { |
| 231 | + t.Errorf("expected a prompt exit on cancellation, took %v", elapsed) |
| 232 | + } |
| 233 | + if !errors.Is(err, context.Canceled) { |
| 234 | + t.Fatalf("expected context.Canceled, got %v", err) |
| 235 | + } |
| 236 | + if server.connections() != 1 { |
| 237 | + t.Errorf("expected no reconnect after cancellation, got %d connections", server.connections()) |
| 238 | + } |
| 239 | +} |
| 240 | + |
| 241 | +func TestSubscribe_NoReconnectStopsOnFirstError(t *testing.T) { |
| 242 | + server := startLiveServer(t, func(ctx context.Context, conn *websocket.Conn, _ int) { |
| 243 | + if err := ackAndAwaitSubscribe(ctx, conn); err != nil { |
| 244 | + return |
| 245 | + } |
| 246 | + if err := send(ctx, conn, "next", measurementPayload); err != nil { |
| 247 | + return |
| 248 | + } |
| 249 | + conn.CloseNow() |
| 250 | + }) |
| 251 | + |
| 252 | + // What `powerctl live --no-reconnect` does: one connection, then out. |
| 253 | + err := server.client().Subscribe(context.Background(), func(*models.LiveMeasurement) error { return nil }) |
| 254 | + |
| 255 | + if err == nil { |
| 256 | + t.Fatal("expected a read error, got nil") |
| 257 | + } |
| 258 | + if server.connections() != 1 { |
| 259 | + t.Errorf("expected 1 connection, got %d", server.connections()) |
| 260 | + } |
| 261 | +} |
0 commit comments