Debian Codegraph @

manager_test.go

raw
1 package proton_test
2
3 import (
4 "context"
5 "crypto/tls"
6 "errors"
7 "net"
8 "net/http"
9 "net/http/httptest"
10 "strconv"
11 "testing"
12 "time"
13
14 "github.com/henrybear327/go-proton-api"
15 "github.com/henrybear327/go-proton-api/server"
16 "github.com/stretchr/testify/require"
17 )
18
19 func TestConnectionReuse(t *testing.T) {
20 s := server.New()
21 defer s.Close()
22
23 ctl := proton.NewNetCtl()
24
25 var dialed int
26
27 ctl.OnDial(func(net.Conn) {
28 dialed++
29 })
30
31 m := proton.New(
32 proton.WithHostURL(s.GetHostURL()),
33 proton.WithTransport(ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true})),
34 )
35
36 // This should succeed; the resulting connection should be reused.
37 require.NoError(t, m.Ping(context.Background()))
38
39 // We should have dialed once.
40 require.Equal(t, 1, dialed)
41
42 // This should succeed; we should not re-dial.
43 require.NoError(t, m.Ping(context.Background()))
44
45 // We should not have re-dialed.
46 require.Equal(t, 1, dialed)
47 }
48
49 func TestAuthRefresh(t *testing.T) {
50 s := server.New()
51 defer s.Close()
52
53 _, _, err := s.CreateUser("user", []byte("pass"))
54 require.NoError(t, err)
55
56 m := proton.New(
57 proton.WithHostURL(s.GetHostURL()),
58 proton.WithTransport(proton.InsecureTransport()),
59 )
60
61 c1, auth, err := m.NewClientWithLogin(context.Background(), "user", []byte("pass"))
62 require.NoError(t, err)
63 defer c1.Close()
64
65 c2, auth, err := m.NewClientWithRefresh(context.Background(), auth.UID, auth.RefreshToken)
66 require.NoError(t, err)
67 defer c2.Close()
68 }
69
70 func TestHandleTooManyRequests(t *testing.T) {
71 // Create a server with a rate limit of 1 request per second.
72 s := server.New(server.WithRateLimit(1, time.Second))
73 defer s.Close()
74
75 var calls []server.Call
76
77 // Watch the calls made.
78 s.AddCallWatcher(func(call server.Call) {
79 calls = append(calls, call)
80 })
81
82 m := proton.New(
83 proton.WithHostURL(s.GetHostURL()),
84 proton.WithTransport(proton.InsecureTransport()),
85 )
86 defer m.Close()
87
88 // Make five calls; they should all succeed, but will be rate limited.
89 for i := 0; i < 5; i++ {
90 require.NoError(t, m.Ping(context.Background()))
91 }
92
93 // After each 429 response, we should wait at least the requested duration before making the next request.
94 for idx, call := range calls {
95 if call.Status == http.StatusTooManyRequests {
96 after, err := strconv.Atoi(call.ResponseHeader.Get("Retry-After"))
97 require.NoError(t, err)
98
99 // The next call should be made after the requested duration.
100 require.True(t, calls[idx+1].Time.After(call.Time.Add(time.Duration(after)*time.Second)))
101 }
102 }
103 }
104
105 func TestHandleTooManyRequests503(t *testing.T) {
106 // Create a server with a rate limit of 1 request per second.
107 s := server.New(server.WithRateLimitAndCustomStatusCode(1, time.Second, http.StatusServiceUnavailable))
108 defer s.Close()
109
110 var calls []server.Call
111
112 // Watch the calls made.
113 s.AddCallWatcher(func(call server.Call) {
114 calls = append(calls, call)
115 })
116
117 m := proton.New(
118 proton.WithHostURL(s.GetHostURL()),
119 proton.WithTransport(proton.InsecureTransport()),
120 )
121 defer m.Close()
122
123 // Make five calls; they should all succeed, but will be rate limited.
124 for i := 0; i < 5; i++ {
125 require.NoError(t, m.Ping(context.Background()))
126 }
127
128 // After each 503 response, we should wait at least the requested duration before making the next request.
129 for idx, call := range calls {
130 if call.Status == http.StatusServiceUnavailable {
131 after, err := strconv.Atoi(call.ResponseHeader.Get("Retry-After"))
132 require.NoError(t, err)
133
134 // The next call should be made after the requested duration.
135 require.True(t, calls[idx+1].Time.After(call.Time.Add(time.Duration(after)*time.Second)))
136 }
137 }
138 }
139
140 func TestHandleTooManyRequests_Malformed(t *testing.T) {
141 var calls []time.Time
142
143 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
144 if len(calls) == 0 {
145 w.Header().Set("Retry-After", "malformed")
146 w.WriteHeader(http.StatusTooManyRequests)
147 }
148
149 calls = append(calls, time.Now())
150 }))
151 defer ts.Close()
152
153 m := proton.New(proton.WithHostURL(ts.URL))
154 defer m.Close()
155
156 require.NoError(t, m.Ping(context.Background()))
157
158 // The first call should fail because the Retry-After header is invalid.
159 // The second call should succeed.
160 require.Len(t, calls, 2)
161
162 // The second call should be made at least 10 seconds after the first call.
163 require.True(t, calls[1].After(calls[0].Add(10*time.Second)))
164 }
165
166 func TestHandleUnprocessableEntity(t *testing.T) {
167 var numCalls int
168
169 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
170 numCalls++
171 w.WriteHeader(http.StatusUnprocessableEntity)
172 }))
173 defer ts.Close()
174
175 m := proton.New(
176 proton.WithHostURL(ts.URL),
177 proton.WithRetryCount(5),
178 )
179
180 // The call should fail because the first call should fail (422s are not retried).
181 c := m.NewClient("", "", "")
182 defer c.Close()
183
184 if _, err := c.GetAddresses(context.Background()); err == nil {
185 t.Fatal("expected error, instead got", err)
186 }
187
188 // The server should be called 1 time.
189 // The first call should return 422.
190 if numCalls != 1 {
191 t.Fatal("expected numCalls to be 1, instead got", numCalls)
192 }
193 }
194
195 func TestHandleDialFailure(t *testing.T) {
196 var numCalls int
197
198 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
199 numCalls++
200 w.WriteHeader(http.StatusOK)
201 }))
202 defer ts.Close()
203
204 m := proton.New(
205 proton.WithHostURL(ts.URL),
206 proton.WithRetryCount(5),
207 proton.WithTransport(newFailingRoundTripper(5)),
208 )
209
210 // The call should succeed because the last retry should succeed (dial errors are retried).
211 c := m.NewClient("", "", "")
212 defer c.Close()
213
214 if _, err := c.GetAddresses(context.Background()); err != nil {
215 t.Fatal("got unexpected error", err)
216 }
217
218 // The server should be called 1 time.
219 // The first 4 attempts don't reach the server.
220 if numCalls != 1 {
221 t.Fatal("expected numCalls to be 1, instead got", numCalls)
222 }
223 }
224
225 func TestHandleTooManyDialFailures(t *testing.T) {
226 var numCalls int
227
228 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
229 numCalls++
230 w.WriteHeader(http.StatusOK)
231 }))
232 defer ts.Close()
233
234 // The failingRoundTripper will fail the first 10 times it is used.
235 // This is more than the number of retries we permit.
236 // Thus, dials will fail.
237 m := proton.New(
238 proton.WithHostURL(ts.URL),
239 proton.WithRetryCount(5),
240 proton.WithTransport(newFailingRoundTripper(10)),
241 )
242
243 // The call should fail because every dial will fail and we'll run out of retries.
244 c := m.NewClient("", "", "")
245 defer c.Close()
246
247 if _, err := c.GetAddresses(context.Background()); err == nil {
248 t.Fatal("expected error, instead got", err)
249 }
250
251 // The server should never be called.
252 if numCalls != 0 {
253 t.Fatal("expected numCalls to be 0, instead got", numCalls)
254 }
255 }
256
257 func TestRetriesWithContextTimeout(t *testing.T) {
258 var numCalls int
259
260 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
261 numCalls++
262
263 if numCalls < 5 {
264 w.WriteHeader(http.StatusTooManyRequests)
265 } else {
266 w.WriteHeader(http.StatusOK)
267 }
268
269 time.Sleep(time.Second)
270 }))
271 defer ts.Close()
272
273 m := proton.New(
274 proton.WithHostURL(ts.URL),
275 proton.WithRetryCount(5),
276 )
277
278 // Timeout after 1s.
279 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
280 defer cancel()
281
282 // Theoretically, this should succeed; on the fifth retry, we'll get StatusOK.
283 // However, that will take at least >5s, and we only allow 1s in the context.
284 // Thus, it will fail.
285 c := m.NewClient("", "", "")
286 defer c.Close()
287
288 if _, err := c.GetAddresses(ctx); err == nil {
289 t.Fatal("expected error, instead got", err)
290 }
291 }
292
293 func TestReturnErrNoConnection(t *testing.T) {
294 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
295 w.WriteHeader(http.StatusOK)
296 }))
297 defer ts.Close()
298
299 // We will fail more times than we retry, so requests should fail with ErrNoConnection.
300 m := proton.New(
301 proton.WithHostURL(ts.URL),
302 proton.WithRetryCount(5),
303 proton.WithTransport(newFailingRoundTripper(10)),
304 )
305
306 // The call should fail because every dial will fail and we'll run out of retries.
307 c := m.NewClient("", "", "")
308 defer c.Close()
309
310 if _, err := c.GetAddresses(context.Background()); err == nil {
311 t.Fatal("expected error, instead got", err)
312 }
313 }
314
315 func TestStatusCallbacks(t *testing.T) {
316 s := server.New()
317 defer s.Close()
318
319 ctl := proton.NewNetCtl()
320
321 m := proton.New(
322 proton.WithHostURL(s.GetHostURL()),
323 proton.WithTransport(ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true})),
324 )
325
326 statusCh := make(chan proton.Status, 1)
327
328 m.AddStatusObserver(func(status proton.Status) {
329 statusCh <- status
330 })
331
332 ctx, cancel := context.WithCancel(context.Background())
333 defer cancel()
334
335 ctl.Disable()
336
337 require.Error(t, m.Ping(ctx))
338 require.Equal(t, proton.StatusDown, <-statusCh)
339
340 ctl.Enable()
341
342 require.NoError(t, m.Ping(ctx))
343 require.Equal(t, proton.StatusUp, <-statusCh)
344
345 ctl.SetReadLimit(1)
346
347 require.Error(t, m.Ping(ctx))
348 require.Equal(t, proton.StatusDown, <-statusCh)
349
350 ctl.SetReadLimit(0)
351
352 require.NoError(t, m.Ping(ctx))
353 require.Equal(t, proton.StatusUp, <-statusCh)
354 }
355
356 func Test503IsReportedAsAPIError(t *testing.T) {
357 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
358 w.WriteHeader(http.StatusServiceUnavailable)
359 }))
360 defer ts.Close()
361
362 m := proton.New(
363 proton.WithHostURL(ts.URL),
364 proton.WithRetryCount(5),
365 )
366
367 c := m.NewClient("", "", "")
368 defer c.Close()
369
370 _, err := c.GetAddresses(context.Background())
371 require.Error(t, err)
372
373 var protonErr *proton.APIError
374 require.True(t, errors.As(err, &protonErr))
375 require.Equal(t, 503, protonErr.Status)
376 }
377
378 type failingRoundTripper struct {
379 http.RoundTripper
380
381 fails, calls int
382 }
383
384 func newFailingRoundTripper(fails int) http.RoundTripper {
385 return &failingRoundTripper{
386 RoundTripper: http.DefaultTransport,
387 fails: fails,
388 }
389 }
390
391 func (rt *failingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
392 rt.calls++
393
394 if rt.calls < rt.fails {
395 return nil, errors.New("simulating network error")
396 }
397
398 return rt.RoundTripper.RoundTrip(req)
399 }