Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Stop a hung exercise catalog from freezing every search (#220)
Carter59d041bc9731
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.goindex dcb845d..e7e42e6 100644--- a/backend/stores/exercise.go+++ b/backend/stores/exercise.go@@ -7,6 +7,7 @@ import ("errors""fmt""log"+ "net""sort""strings""sync"@@ -30,9 +31,17 @@ type ExerciseStore struct {// status is how recent passes went. syncing above stays the one running flag.statusMu sync.Mutexstatus models.ExerciseCacheStatus+ // searchDownUntil (unix nanos, 0 = up) is when Search may next ask the catalog. See+ // searchAllowed.+ searchDownUntil atomic.Int64+ // searchTimeout bounds one live search call. A healthy catalog answers in well under+ // a second; a picker that hangs is worse than one that falls back.+ searchTimeout time.Duration}-func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db} }+func NewExerciseStore(db *sql.DB) *ExerciseStore {+ return &ExerciseStore{db: db, searchTimeout: defaultSearchTimeout}+}// ExerciseFilter holds the optional list filters (empty string = no filter).type ExerciseFilter struct {@@ -430,9 +439,47 @@ func replaceTranslation(tx *sql.Tx, it oedb.Exercise, locale string, nameEN, des// exercises. Nothing in Lyftr requires the network to work.func (s *ExerciseStore) UseCatalog(c *oedb.Client) { s.catalog = c }+const (+ defaultSearchTimeout = 3 * time.Second+ // searchBackoff is how long Search stops asking a catalog that did not answer, so+ // one dead upstream costs one slow request, not one per keystroke.+ searchBackoff = time.Minute+)++// searchAllowed reports whether this search may call the catalog. After a failed call+// the answer is no until searchBackoff has passed. The first caller after that claims+// the retry, holding the rest off for as long as its own call can take, so a catalog+// that is still down is probed once, not by every request that arrives meanwhile.+func (s *ExerciseStore) searchAllowed() bool {+ until := s.searchDownUntil.Load()+ if until == 0 {+ return true+ }+ now := time.Now()+ if now.UnixNano() < until {+ return false+ }+ return s.searchDownUntil.CompareAndSwap(until, now.Add(s.searchTimeout+time.Second).UnixNano())+}++// searchFailed backs Search off the catalog when it gave no answer: a timeout or a+// connection that never completed. An answer that says no (a 4xx for one bad query,+// a 5xx) arrives fast, costs nothing to repeat and says nothing about the next query,+// and a caller that gave up on its own request says nothing about the catalog.+func (s *ExerciseStore) searchFailed(ctx context.Context, err error) {+ var netErr net.Error+ if ctx.Err() != nil || !(errors.Is(err, context.DeadlineExceeded) || errors.As(err, &netErr)) {+ s.searchDownUntil.Store(0)+ return+ }+ s.searchDownUntil.Store(time.Now().Add(searchBackoff).UnixNano())+ log.Printf("exercises: catalog is not answering, serving the local copy for %s: %v", searchBackoff, err)+}+// Search answers an exercise query from the upstream catalog, recording what it// returns locally, and falls back to the local table when the catalog cannot be-// reached.+// reached. A catalog that does not answer is left alone for searchBackoff, so the+// fallback is immediate rather than a timeout on every request.//// The fallback is not a nicety. oedb being down, slow, or rate-limiting must// never stop someone logging a workout, and the local table already holds every@@ -443,16 +490,23 @@ func (s *ExerciseStore) Search(ctx context.Context, f ExerciseFilter) ([]models.return s.List(f)}+ if !s.searchAllowed() {+ return s.List(f)+ }+items, err := s.fetchCatalog(ctx, f)if err != nil {+ s.searchFailed(ctx, err)log.Printf("exercises: catalog query failed, serving local snapshot: %v", err)return s.List(f)}if err := s.ensureEnglishBase(ctx, items); err != nil {+ s.searchFailed(ctx, err)log.Printf("exercises: could not fetch English base rows, serving local snapshot: %v", err)return s.List(f)}+ s.searchDownUntil.Store(0)out, err := s.Materialize(items, s.catalog.BaseURL(), f.Locale)if err != nil {@@ -485,7 +539,7 @@ func (s *ExerciseStore) ensureEnglishBase(ctx context.Context, items []oedb.Exerreturn nil}- ctx, cancel := context.WithTimeout(ctx, 8*time.Second)+ ctx, cancel := context.WithTimeout(ctx, s.searchTimeout)defer cancel()for len(missing) > 0 {batch := missing[:min(len(missing), 100)]@@ -538,7 +592,7 @@ func (s *ExerciseStore) fetchCatalog(ctx context.Context, f ExerciseFilter) ([]o// An interactive search gets a short deadline: a picker that hangs is worse// than one that falls back to the local snapshot immediately.- ctx, cancel := context.WithTimeout(ctx, 8*time.Second)+ ctx, cancel := context.WithTimeout(ctx, s.searchTimeout)defer cancel()// A filtered request for more than one page walks the pages. oedb capsdiff --git a/backend/stores/exercise_search_breaker_test.go b/backend/stores/exercise_search_breaker_test.gonew file mode 100644index 0000000..305acb8--- /dev/null+++ b/backend/stores/exercise_search_breaker_test.go@@ -0,0 +1,160 @@+package stores++import (+ "context"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+ "time"++ "github.com/Cawlumm/lyftr-backend/oedb"+)++// breakerCatalog is an oedb stand-in whose behaviour the test switches: hung accepts the+// connection and never answers (a stopped server would refuse instantly, which hides the+// whole class of bug), status answers that code at once, and otherwise it returns an+// empty page.+type breakerCatalog struct {+ hits atomic.Int32+ hung atomic.Bool+ status atomic.Int32+ srv *httptest.Server+}++func newBreakerCatalog(t *testing.T) *breakerCatalog {+ t.Helper()+ c := &breakerCatalog{}+ c.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ c.hits.Add(1)+ if c.hung.Load() {+ <-r.Context().Done()+ return+ }+ if code := int(c.status.Load()); code != 0 {+ w.WriteHeader(code)+ return+ }+ w.Write([]byte(`{"exercises":[],"total":0,"page":1,"per_page":25}`))+ }))+ t.Cleanup(c.srv.Close)+ return c+}++func breakerStore(t *testing.T, c *breakerCatalog) *ExerciseStore {+ t.Helper()+ s := NewExerciseStore(testDB(t))+ s.UseCatalog(oedb.New(c.srv.URL, "test"))+ s.searchTimeout = 150 * time.Millisecond+ return s+}++// One dead catalog must cost one slow request, not one per keystroke. Before this, every+// search against a hung catalog waited out the whole timeout before falling back.+func TestSearch_HungCatalogIsAskedOnce(t *testing.T) {+ c := newBreakerCatalog(t)+ c.hung.Store(true)+ s := breakerStore(t, c)+ f := ExerciseFilter{Query: "squat", Limit: 25}++ start := time.Now()+ if _, err := s.Search(context.Background(), f); err != nil {+ t.Fatalf("first search: %v", err)+ }+ if took := time.Since(start); took < s.searchTimeout {+ t.Fatalf("first search took %v, expected to wait out the %v timeout", took, s.searchTimeout)+ }+ first := c.hits.Load()++ start = time.Now()+ for i := 0; i < 5; i++ {+ if _, err := s.Search(context.Background(), f); err != nil {+ t.Fatalf("later search: %v", err)+ }+ }+ if took := time.Since(start); took > s.searchTimeout/2 {+ t.Errorf("five searches while the catalog is down took %v, want them served locally at once", took)+ }+ if n := c.hits.Load(); n != first {+ t.Errorf("catalog was asked %d more times while backed off, want 0", n-first)+ }+}++// After the backoff the catalog is tried again, and one good answer ends it.+func TestSearch_RetriesAfterBackoffAndRecovers(t *testing.T) {+ c := newBreakerCatalog(t)+ c.hung.Store(true)+ s := breakerStore(t, c)+ f := ExerciseFilter{Query: "squat", Limit: 25}++ s.Search(context.Background(), f)+ if s.searchDownUntil.Load() == 0 {+ t.Fatal("a hung catalog did not back searches off")+ }++ c.hung.Store(false)+ s.searchDownUntil.Store(time.Now().Add(-time.Second).UnixNano())+ before := c.hits.Load()+ if _, err := s.Search(context.Background(), f); err != nil {+ t.Fatalf("search after backoff: %v", err)+ }+ if c.hits.Load() == before {+ t.Error("catalog was not asked again once the backoff had passed")+ }+ if s.searchDownUntil.Load() != 0 {+ t.Error("a good answer did not end the backoff")+ }+}++// Once the backoff has passed, one request probes the catalog and the rest keep to the+// local copy meanwhile, so a catalog that is still down is not hit by a crowd.+func TestSearchAllowed_OnlyOneCallerProbesAfterBackoff(t *testing.T) {+ s := NewExerciseStore(testDB(t))+ if !s.searchAllowed() {+ t.Fatal("a store that never failed must allow live search")+ }+ s.searchDownUntil.Store(time.Now().Add(time.Minute).UnixNano())+ if s.searchAllowed() {+ t.Fatal("live search was allowed inside the backoff")+ }+ s.searchDownUntil.Store(time.Now().Add(-time.Second).UnixNano())+ if !s.searchAllowed() {+ t.Fatal("the first caller after the backoff must be allowed to probe")+ }+ if s.searchAllowed() {+ t.Error("a second caller probed while the first was still trying")+ }+}++// A caller that gives up says nothing about the catalog, and neither does a fast "no":+// the next search must still reach it.+func TestSearch_OnlyANonAnswerBacksOff(t *testing.T) {+ t.Run("caller cancelled", func(t *testing.T) {+ c := newBreakerCatalog(t)+ c.hung.Store(true)+ s := breakerStore(t, c)+ ctx, cancel := context.WithCancel(context.Background())+ go func() { time.Sleep(30 * time.Millisecond); cancel() }()+ s.Search(ctx, ExerciseFilter{Query: "squat", Limit: 25})+ if s.searchDownUntil.Load() != 0 {+ t.Error("a client abandoning its own request backed everyone else off")+ }+ })++ for _, code := range []int{http.StatusUnprocessableEntity, http.StatusBadGateway} {+ t.Run(http.StatusText(code), func(t *testing.T) {+ c := newBreakerCatalog(t)+ c.status.Store(int32(code))+ s := breakerStore(t, c)+ f := ExerciseFilter{Query: "squat", Limit: 25}+ s.Search(context.Background(), f)+ s.Search(context.Background(), f)+ if s.searchDownUntil.Load() != 0 {+ t.Errorf("an immediate %d backed searches off", code)+ }+ if n := c.hits.Load(); n != 2 {+ t.Errorf("catalog asked %d times for two searches, want 2", n)+ }+ })+ }+}