sonda/internal/api/http/discover_busy_test.go
tgiachi 63fee32271 feat(discover): one Discover at a time for each listener, three at once on the server
A cold Discover can make dozens of provider requests, and nothing stopped one
listener, or a client that keeps opening and cancelling requests, from lining up
work for the providers and slowing everyone else's.

- A listener who already has a Discover running gets 429 `discover_busy` with
  Retry-After, at once.
- At most three Discovers run at the same time, whoever asks; the others wait for
  their turn, and one that stops waiting does no work and keeps no place.
- The place and the turn are given back when a Discover fails or ends.
- Spec and README describe it; the fakes of the tests are safe for parallel runs.
2026-11-12 11:52:20 +01:00

35 lines
1 KiB
Go

package httpapi
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/discover"
)
type busyDiscover struct{ err error }
func (b busyDiscover) Discover(context.Context, int64, discover.Query) (discover.Result, error) {
return discover.Result{}, b.err
}
func TestADiscoverThatIsAlreadyRunningIsTurnedAwayWithAWaitAndAKnownCode(t *testing.T) {
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.Discover = busyDiscover{err: discover.ErrBusy} })
admin := registerAndLogin(t, h)
req := httptest.NewRequest("GET", "/api/v1/discover?seed=1", nil)
req.Header.Set("Authorization", "Bearer "+admin)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusTooManyRequests || !strings.Contains(rec.Body.String(), `"discover_busy"`) {
t.Fatalf("%d %s, want 429 discover_busy", rec.Code, rec.Body.String())
}
if rec.Header().Get("Retry-After") == "" {
t.Error("no Retry-After: the client does not know when to ask again")
}
}