Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Report an unreachable exercise catalog as 503, not a bad request (#207)

Carter33a54ab22336
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.go
index ddb0363..0ffa2c9 100644
--- a/backend/controllers/exercises.go
+++ b/backend/controllers/exercises.go
@@ -3,6 +3,7 @@ package controllers
import (
"database/sql"
"errors"
+ "log"
"strconv"
"github.com/Cawlumm/lyftr-backend/middleware"
@@ -112,8 +113,12 @@ func (h *Handler) RefreshExerciseCache(c *gin.Context) {
utils.Fail(c, utils.CodeNoExerciseCatalog, nil)
return
}
- if err != nil {
- utils.BindError(c, err)
+ if errors.Is(err, stores.ErrCatalogUnreachable) {
+ log.Printf("exercises: refresh could not reach the catalog: %v", err)
+ utils.Fail(c, utils.CodeCatalogUnreachable, nil)
+ return
+ }
+ if utils.DBError(c, err) {
return
}
utils.OK(c, gin.H{"refreshed": n})
diff --git a/backend/controllers/food_codes_test.go b/backend/controllers/food_codes_test.go
index 0438f90..59fd296 100644
--- a/backend/controllers/food_codes_test.go
+++ b/backend/controllers/food_codes_test.go
@@ -8,6 +8,9 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/oedb"
)
// These pin the code, the status and the sentence of every error the food-database and
@@ -157,3 +160,61 @@ func TestRefreshExerciseCache_withoutCatalogCode(t *testing.T) {
wantCode(t, w, http.StatusBadRequest, "NO_EXERCISE_CATALOG", "This server has no exercise catalog configured.")
}
+
+func refreshWithCatalog(t *testing.T, baseURL string) *httptest.ResponseRecorder {
+ t.Helper()
+ setupTestDB(t)
+ uid := createTestUser(t)
+ if _, err := db.DB.Exec("INSERT INTO exercises (name, oedb_id) VALUES ('Held', 'uuid-1')"); err != nil {
+ t.Fatal(err)
+ }
+ th.s.Exercise.UseCatalog(oedb.New(baseURL, "test"))
+
+ c, w := newContext(uid, http.MethodPost, "/api/v1/admin/sync-exercises", nil)
+ th.RefreshExerciseCache(c)
+ return w
+}
+
+func TestRefreshExerciseCache_catalogFailureCodes(t *testing.T) {
+ const sentence = "Couldn't reach the exercise catalog."
+
+ t.Run("upstream 5xx", func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer srv.Close()
+ w := refreshWithCatalog(t, srv.URL)
+ wantCode(t, w, http.StatusServiceUnavailable, "EXERCISE_CATALOG_UNREACHABLE", sentence)
+ if got := w.Header().Get("Retry-After"); got != "2" {
+ t.Fatalf("Retry-After = %q, want 2", got)
+ }
+ })
+
+ t.Run("unreachable", func(t *testing.T) {
+ w := refreshWithCatalog(t, "http://127.0.0.1:1")
+ wantCode(t, w, http.StatusServiceUnavailable, "EXERCISE_CATALOG_UNREACHABLE", sentence)
+ })
+
+ t.Run("malformed body", func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("{not json"))
+ }))
+ defer srv.Close()
+ w := refreshWithCatalog(t, srv.URL)
+ wantCode(t, w, http.StatusServiceUnavailable, "EXERCISE_CATALOG_UNREACHABLE", sentence)
+ })
+}
+
+func TestRefreshExerciseCache_success(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"exercises":[{"id":"uuid-1","slug":"held","muscle_group":"chest","translation":{"name":"Held Renamed","instructions":[]}}],"total":1}`))
+ }))
+ defer srv.Close()
+ w := refreshWithCatalog(t, srv.URL)
+
+ body := decodeResponse(t, w)
+ data, _ := body["data"].(map[string]any)
+ if w.Code != http.StatusOK || data["refreshed"] != float64(1) || body["code"] != nil {
+ t.Fatalf("got %d %v, want 200 refreshed 1", w.Code, body)
+ }
+}
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.go
index 62b665a..a5bdfe1 100644
--- a/backend/stores/exercise.go
+++ b/backend/stores/exercise.go
@@ -531,6 +531,10 @@ var errNoCatalog = errors.New("This server has no exercise catalog configured.")
// no upstream configured.
var ErrNoCatalog = errors.New("This server has no exercise catalog configured.")
+// ErrCatalogUnreachable marks a refresh that failed reading the upstream catalog, so a
+// caller can tell an oedb outage from a local database failure.
+var ErrCatalogUnreachable = errors.New("exercise catalog unreachable")
+
// CachedCount reports how many catalog rows this instance currently holds.
//
// Lyftr does not maintain a copy of the catalog, so this is not "how big is the
@@ -579,7 +583,7 @@ func (s *ExerciseStore) refresh(ctx context.Context, locale string) (int, error)
if servedInEnglish(locale) {
items, err := cat.Export(ctx)
if err != nil {
- return 0, err
+ return 0, fmt.Errorf("%w: %w", ErrCatalogUnreachable, err)
}
keep := items[:0]
for _, it := range items {
@@ -602,7 +606,7 @@ func (s *ExerciseStore) refresh(ctx context.Context, locale string) (int, error)
end := min(start+oedb.MaxPerPage, len(ids))
res, err := cat.List(ctx, oedb.ListParams{IDs: ids[start:end], Locale: locale, PerPage: oedb.MaxPerPage})
if err != nil {
- return done, err
+ return done, fmt.Errorf("%w: %w", ErrCatalogUnreachable, err)
}
out, err := s.Materialize(res.Exercises, s.catalog.BaseURL(), locale)
if err != nil {
diff --git a/backend/utils/codes.go b/backend/utils/codes.go
index bc7cfdd..e89e148 100644
--- a/backend/utils/codes.go
+++ b/backend/utils/codes.go
@@ -114,6 +114,7 @@ var (
CodeFoodSearchUnavailable = define("FOOD_SEARCH_UNAVAILABLE", 503, "Food search is temporarily unavailable.")
CodeBarcodeLookupUnavailable = define("BARCODE_LOOKUP_UNAVAILABLE", 503, "Barcode lookup is temporarily unavailable.")
CodeNoExerciseCatalog = define("NO_EXERCISE_CATALOG", 400, "This server has no exercise catalog configured.")
+ CodeCatalogUnreachable = define("EXERCISE_CATALOG_UNREACHABLE", 503, "Couldn't reach the exercise catalog.")
CodeDisplayNameControlChars = define("DISPLAY_NAME_CONTROL_CHARS", 400, "A name can't contain line breaks or other control characters.")
CodeTimezoneEmpty = define("TIMEZONE_EMPTY", 400, "Timezone can't be empty.")
CodeUnknownTimezone = define("UNKNOWN_TIMEZONE", 400, "Unknown timezone: {{timezone}}.")
diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.md
index fa1120b..22f297f 100644
--- a/docs/API_CHANGES.md
+++ b/docs/API_CHANGES.md
@@ -21,7 +21,7 @@ ignores `code`. Every error body is now `{"error": "...", "code": "UPPER_SNAKE"}
optional `params` object when the sentence has variables. The first-party clients key their
own (localized) wording on `code` and fall back to `error`.
-Codes (70). Every error has its own code with a fixed status; there is no generic
+Codes (71). Every error has its own code with a fixed status; there is no generic
`BAD_REQUEST`, `NOT_FOUND` or `SERVICE_UNAVAILABLE`.
- Sign-in and session: `INVALID_CREDENTIALS`, `EMAIL_TAKEN`, `REGISTRATION_CLOSED`,
@@ -40,7 +40,7 @@ Codes (70). Every error has its own code with a fixed status; there is no generi
- Resources: `INVALID_ID`, `INVALID_EXERCISE_ID`, `INVALID_PROGRAM_ID`, `INVALID_WORKOUT_ID`
(`400`); `ENTRY_NOT_FOUND`, `SAVED_FOOD_NOT_FOUND`, `EXERCISE_NOT_FOUND`,
`PROGRAM_NOT_FOUND`, `WORKOUT_NOT_FOUND` (`404`); `UNKNOWN_EXERCISES`, `NO_EXERCISE_CATALOG`
- (`400`).
+ (`400`); `EXERCISE_CATALOG_UNREACHABLE` (`503`, with `Retry-After: 2`).
- Dates: `INVALID_DATE`, `INVALID_LOGGED_ON`, `INVALID_FROM_DATE`, `INVALID_TO_DATE` (`400`).
- Food: `FOOD_NAME_TOO_LONG`, `FOOD_BRAND_TOO_LONG`, `SERVING_SIZE_TOO_LONG`,
`BARCODE_TOO_LONG`, `IMAGE_URL_TOO_LONG`, `SEARCH_TERM_REQUIRED`, `INVALID_BARCODE` (`400`);
@@ -202,6 +202,9 @@ populate an empty one. A caller using this to fill a fresh install gets `{"refre
and an instance that is still empty — search populates the cache now, so there is nothing
to call. New failure mode: `400` with "This server has no exercise catalog configured."
when no upstream is set.
+When the upstream is configured but cannot be reached, or answers with an error, it answers
+`503` `EXERCISE_CATALOG_UNREACHABLE` "Couldn't reach the exercise catalog."; it used to
+answer `400` "The request couldn't be read."
## `POST /api/v1/admin/reset-exercises` — `{"reset","message"}` became `{"cleared"}`, and it no longer re-seeds
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 32656c2..a177062 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -688,6 +688,7 @@ describe('apiErrorMessage — server codes', () => {
it.each([
['FOOD_DATABASE_TIMEOUT', 503, undefined, undefined],
+ ['EXERCISE_CATALOG_UNREACHABLE', 503, undefined, undefined],
['PRODUCT_NOT_FOUND', 404, undefined, undefined],
['SEARCH_TERM_REQUIRED', 400, undefined, undefined],
['INVALID_WORKOUT_ID', 400, undefined, undefined],
diff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.json
index 67ac867..693c8e8 100644
--- a/packages/shared/src/i18n/locales/en.json
+++ b/packages/shared/src/i18n/locales/en.json
@@ -357,6 +357,7 @@
"FOOD_SEARCH_UNAVAILABLE": "Food search is temporarily unavailable.",
"BARCODE_LOOKUP_UNAVAILABLE": "Barcode lookup is temporarily unavailable.",
"NO_EXERCISE_CATALOG": "This server has no exercise catalog configured.",
+ "EXERCISE_CATALOG_UNREACHABLE": "Couldn't reach the exercise catalog.",
"DISPLAY_NAME_CONTROL_CHARS": "A name can't contain line breaks or other control characters.",
"TIMEZONE_EMPTY": "Timezone can't be empty.",
"UNKNOWN_TIMEZONE": "Unknown timezone: {{timezone}}.",
diff --git a/packages/shared/src/i18n/locales/es.json b/packages/shared/src/i18n/locales/es.json
index fb29205..576fb52 100644
--- a/packages/shared/src/i18n/locales/es.json
+++ b/packages/shared/src/i18n/locales/es.json
@@ -364,6 +364,7 @@
"FOOD_SEARCH_UNAVAILABLE": "La búsqueda de alimentos no está disponible por ahora.",
"BARCODE_LOOKUP_UNAVAILABLE": "La búsqueda por código de barras no está disponible por ahora.",
"NO_EXERCISE_CATALOG": "Este servidor no tiene un catálogo de ejercicios configurado.",
+ "EXERCISE_CATALOG_UNREACHABLE": "No se pudo conectar con el catálogo de ejercicios.",
"DISPLAY_NAME_CONTROL_CHARS": "Un nombre no puede contener saltos de línea ni otros caracteres de control.",
"TIMEZONE_EMPTY": "La zona horaria no puede estar vacía.",
"UNKNOWN_TIMEZONE": "Zona horaria desconocida: {{timezone}}.",