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