|
| 1 | +package dispatcher |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "sync/atomic" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | + "github.com/stretchr/testify/require" |
| 13 | +) |
| 14 | + |
| 15 | +func newTestCloudDispatcher(url string) *CloudDispatcher { |
| 16 | + return &CloudDispatcher{ |
| 17 | + Name: "Dozzle Cloud", |
| 18 | + URL: url, |
| 19 | + APIKey: "test-key", |
| 20 | + client: &http.Client{Timeout: 5 * time.Second}, |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +// On a 401/403 the breaker trips and subsequent sends short-circuit without |
| 25 | +// hitting cloud until the breaker is reset. |
| 26 | +func TestCloudDispatcher_AuthFailureTripsBreaker(t *testing.T) { |
| 27 | + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden} { |
| 28 | + var hits atomic.Int32 |
| 29 | + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 30 | + hits.Add(1) |
| 31 | + rw.WriteHeader(status) |
| 32 | + rw.Write([]byte("Invalid API key\n")) |
| 33 | + })) |
| 34 | + |
| 35 | + d := newTestCloudDispatcher(srv.URL) |
| 36 | + |
| 37 | + err := d.Send(context.Background(), newTestNotification("first")) |
| 38 | + require.Error(t, err) |
| 39 | + assert.EqualValues(t, 1, hits.Load(), "first send should reach cloud") |
| 40 | + |
| 41 | + err = d.Send(context.Background(), newTestNotification("second")) |
| 42 | + require.Error(t, err) |
| 43 | + assert.Contains(t, err.Error(), "rate limited") |
| 44 | + assert.EqualValues(t, 1, hits.Load(), "breaker should block second send (status %d)", status) |
| 45 | + |
| 46 | + srv.Close() |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// ResetBreaker clears the circuit so the next send dials cloud again. |
| 51 | +func TestCloudDispatcher_ResetBreaker(t *testing.T) { |
| 52 | + var hits atomic.Int32 |
| 53 | + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 54 | + hits.Add(1) |
| 55 | + rw.WriteHeader(http.StatusUnauthorized) |
| 56 | + })) |
| 57 | + defer srv.Close() |
| 58 | + |
| 59 | + d := newTestCloudDispatcher(srv.URL) |
| 60 | + |
| 61 | + require.Error(t, d.Send(context.Background(), newTestNotification("first"))) |
| 62 | + require.EqualValues(t, 1, hits.Load()) |
| 63 | + |
| 64 | + // Blocked while breaker is open. |
| 65 | + require.Error(t, d.Send(context.Background(), newTestNotification("blocked"))) |
| 66 | + require.EqualValues(t, 1, hits.Load()) |
| 67 | + |
| 68 | + d.ResetBreaker() |
| 69 | + |
| 70 | + require.Error(t, d.Send(context.Background(), newTestNotification("after-reset"))) |
| 71 | + assert.EqualValues(t, 2, hits.Load(), "send after reset should reach cloud again") |
| 72 | +} |
0 commit comments