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.

Hold the whole exercise catalog and remove Clear cache (#211)

Carterb9f3a097a1ce
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.go
index 0ffa2c9..2e63fe7 100644
--- a/backend/controllers/exercises.go
+++ b/backend/controllers/exercises.go
@@ -101,18 +101,19 @@ func (h *Handler) GetExerciseHistory(c *gin.Context) {
utils.OK(c, history)
}
-// RefreshExerciseCache re-reads the catalog rows this instance already holds and
-// applies any upstream edits.
-//
-// Not a re-import: Lyftr does not keep a copy of open-exercise-db, and this
-// endpoint does not create one. New exercises appear the way every cached row
-// did — the first time a search returns them.
+// RefreshExerciseCache runs the scheduled catalog pass now, importing every upstream
+// exercise in English and refreshing translations for every held one. `refreshed` is
+// how many exercises the English pass recorded.
func (h *Handler) RefreshExerciseCache(c *gin.Context) {
n, err := h.s.Exercise.RefreshCached(c.Request.Context())
if errors.Is(err, stores.ErrNoCatalog) {
utils.Fail(c, utils.CodeNoExerciseCatalog, nil)
return
}
+ if errors.Is(err, stores.ErrSyncRunning) {
+ utils.Fail(c, utils.CodeExerciseSyncRunning, nil)
+ return
+ }
if errors.Is(err, stores.ErrCatalogUnreachable) {
log.Printf("exercises: refresh could not reach the catalog: %v", err)
utils.Fail(c, utils.CodeCatalogUnreachable, nil)
@@ -132,12 +133,3 @@ func (h *Handler) ExerciseCacheStatus(c *gin.Context) {
}
utils.OK(c, gin.H{"count": count})
}
-
-// ClearExerciseCache drops cached rows nothing references.
-func (h *Handler) ClearExerciseCache(c *gin.Context) {
- n, err := h.s.Exercise.ClearUnreferenced()
- if utils.DBError(c, err) {
- return
- }
- utils.OK(c, gin.H{"cleared": n})
-}
diff --git a/backend/controllers/food_codes_test.go b/backend/controllers/food_codes_test.go
index 59fd296..b3b1195 100644
--- a/backend/controllers/food_codes_test.go
+++ b/backend/controllers/food_codes_test.go
@@ -207,14 +207,64 @@ func TestRefreshExerciseCache_catalogFailureCodes(t *testing.T) {
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}`))
+ _, _ = w.Write([]byte(`{"exercises":[{"id":"uuid-1","slug":"held","muscle_group":"chest","translation":{"name":"Held Renamed","instructions":[]}},{"id":"uuid-2","slug":"new","muscle_group":"back","translation":{"name":"New One","instructions":[]}}],"total":2}`))
}))
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)
+ if w.Code != http.StatusOK || data["refreshed"] != float64(2) || body["code"] != nil {
+ t.Fatalf("got %d %v, want 200 refreshed 2", w.Code, body)
}
}
+
+// A second sync while one is running must be refused, not run alongside it: the
+// route is open to every signed-in user and a pass is a full catalog import.
+func TestRefreshExerciseCache_secondCallWhileRunningIs409(t *testing.T) {
+ release := make(chan struct{})
+ started := make(chan struct{}, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.Contains(r.URL.Path, "locales") {
+ _, _ = w.Write([]byte(`{"locales":[],"total":0}`))
+ return
+ }
+ select {
+ case started <- struct{}{}:
+ default:
+ }
+ <-release
+ _, _ = w.Write([]byte(`{"exercises":[],"total":0}`))
+ }))
+ defer srv.Close()
+
+ setupTestDB(t)
+ uid := createTestUser(t)
+ th.s.Exercise.UseCatalog(oedb.New(srv.URL, "test"))
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ c, _ := newContext(uid, http.MethodPost, "/api/v1/admin/sync-exercises", nil)
+ th.RefreshExerciseCache(c)
+ }()
+ <-started
+
+ second := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ c, w := newContext(uid, http.MethodPost, "/api/v1/admin/sync-exercises", nil)
+ th.RefreshExerciseCache(c)
+ second <- w
+ }()
+ var w *httptest.ResponseRecorder
+ select {
+ case w = <-second:
+ case <-time.After(5 * time.Second):
+ close(release)
+ t.Fatal("the second sync blocked instead of being refused")
+ }
+ wantCode(t, w, http.StatusConflict, "EXERCISE_SYNC_RUNNING", "An exercise sync is already running. Try again when it finishes.")
+
+ close(release)
+ <-done
+}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index ff67437..800f76b 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -187,8 +187,8 @@ func alterMigrations() {
// from text oedb served in English, so there is nothing to backfill. Every other
// language lives here, one row per (exercise, locale), and a reader falls through to
// the base row field by field (stores.translationJoin). The cascade is required, not
- // tidy: ClearUnreferenced deletes exercises with foreign keys on, and a single
- // translation row without it would make that delete fail.
+ // tidy: deleting an exercise with foreign keys on would otherwise fail on its first
+ // translation row.
if _, err := DB.Exec(`
CREATE TABLE IF NOT EXISTS exercise_translations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/backend/main.go b/backend/main.go
index 1aaef53..7d30519 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -107,10 +107,9 @@ func main() {
} else {
seed.WarnLeftoverDemoUser(db.DB)
}
- // Lyftr does not seed or mirror an exercise library. open-exercise-db is the
- // source, queried live; the local exercises table is filled only as a
- // side-effect of reads, so a fresh instance starts with an empty one and is
- // fully functional.
+ // The background pass below imports the whole open-exercise-db catalog at boot and
+ // daily, and reads record rows too, so a fresh instance is usable before that pass
+ // finishes.
s := stores.New(db.DB)
s.Exercise.UseCatalog(oedb.New(config.C.OEDBBaseURL, config.Version()))
diff --git a/backend/routes/routes.go b/backend/routes/routes.go
index 904424a..50ba17a 100644
--- a/backend/routes/routes.go
+++ b/backend/routes/routes.go
@@ -94,7 +94,6 @@ func Setup(r *gin.Engine, h *controllers.Handler) {
// Admin
protected.POST("admin/sync-exercises", h.RefreshExerciseCache)
protected.GET("admin/seed-status", h.ExerciseCacheStatus)
- protected.POST("admin/reset-exercises", h.ClearExerciseCache)
}
}
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.go
index cb028be..debd7d0 100644
--- a/backend/stores/exercise.go
+++ b/backend/stores/exercise.go
@@ -9,6 +9,7 @@ import (
"log"
"sort"
"strings"
+ "sync/atomic"
"time"
"github.com/Cawlumm/lyftr-backend/models"
@@ -18,10 +19,13 @@ import (
// ExerciseStore owns all SQL for the (global, read-only) exercises catalog: the
// local cache of oedb rows, the scheduled sync that fills it, and the admin
-// refresh/reset endpoints.
+// sync endpoint.
type ExerciseStore struct {
db *sql.DB
catalog *oedb.Client
+ // syncing is held for the length of a catalog pass, so the daily timer and the
+ // admin endpoint can never run two imports against the one SQLite connection.
+ syncing atomic.Bool
}
func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db} }
@@ -571,31 +575,28 @@ var ErrNoCatalog = errors.New("This server has no exercise catalog configured.")
// caller can tell an oedb outage from a local database failure.
var ErrCatalogUnreachable = errors.New("exercise catalog unreachable")
+// ErrSyncRunning is returned when a catalog pass is already in progress.
+var ErrSyncRunning = errors.New("exercise sync already running")
+
// 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
-// exercise library" — it is how much of open-exercise-db this instance has had
-// reason to look at. A fresh install reports zero and is fully functional.
+// After the first scheduled pass the table holds the whole catalog plus any legacy
+// rows; before it, only what reads have had reason to record. A fresh install reports
+// zero and is fully functional.
func (s *ExerciseStore) CachedCount() (int, error) { return s.Count() }
-// RefreshCached re-reads the rows this instance already holds and applies any
-// upstream edits, returning how many were refreshed.
-//
-// Deliberately scoped to rows already present: it picks up corrections made
-// upstream without importing the catalog. New exercises arrive the same way every
-// other row did — the first time someone's search returns one.
-//
-// It reads the bulk export and intersects locally rather than fetching each row
-// by id, because oedb has no batch-by-ids endpoint: refreshing 873 rows one at a
-// time would be 873 requests against a 60/minute limit, or about a quarter hour.
+// RefreshCached is the scheduled catalog pass run on demand: it imports every upstream
+// exercise in English and re-reads every held one in each other language. The int is
+// the number of exercises the English pass recorded.
func (s *ExerciseStore) RefreshCached(ctx context.Context) (int, error) {
- return s.refresh(ctx, defaultLocale)
+ return s.syncCatalog(ctx)
}
-// refresh re-reads every held row in one language. English comes from the bulk
-// export; any other language is read by id in oedb's batch size, because the export
-// is English-only and a list call is the only way to ask for a translation. One code
-// path serves every language, so adding a locale needs no new fetching logic.
+// refresh brings one language up to date. English imports every exercise in the bulk
+// export, oedb.MaxPerPage rows per transaction so a pass never holds the single
+// connection for long. Any other language re-reads every held row by id in oedb's
+// batch size, because the export is English-only and a list call is the only way to
+// ask for a translation.
//
// It stops at the first failed batch and reports how many rows it did apply: the
// rows written so far are valid, and the caller decides whether a partial pass counts.
@@ -608,27 +609,25 @@ func (s *ExerciseStore) refresh(ctx context.Context, locale string) (int, error)
}
cat := s.catalog.Revalidating()
- held, err := s.cachedOedbIDs()
- if err != nil {
- return 0, err
- }
- if len(held) == 0 {
- return 0, nil
- }
-
if servedInEnglish(locale) {
items, err := cat.Export(ctx)
if err != nil {
return 0, fmt.Errorf("%w: %w", ErrCatalogUnreachable, err)
}
- keep := items[:0]
- for _, it := range items {
- if held[it.ID] {
- keep = append(keep, it)
+ done := 0
+ for start := 0; start < len(items); start += oedb.MaxPerPage {
+ out, err := s.Materialize(items[start:min(start+oedb.MaxPerPage, len(items))], s.catalog.BaseURL(), defaultLocale)
+ if err != nil {
+ return done, err
}
+ done += len(out)
}
- out, err := s.Materialize(keep, s.catalog.BaseURL(), defaultLocale)
- return len(out), err
+ return done, nil
+ }
+
+ held, err := s.cachedOedbIDs()
+ if err != nil {
+ return 0, err
}
ids := make([]string, 0, len(held))
@@ -670,29 +669,10 @@ func (s *ExerciseStore) cachedOedbIDs() (map[string]bool, error) {
return held, rows.Err()
}
-// ClearUnreferenced drops cached rows no workout or program points at, returning
-// how many went.
-//
-// Referenced rows are left alone rather than the whole table being emptied:
-// workout_exercises and program_exercises FK into exercises(id) with no cascade,
-// so deleting a referenced row is (correctly) refused by SQLite and would take a
-// user's logged history with it if it were not.
-func (s *ExerciseStore) ClearUnreferenced() (int, error) {
- res, err := s.db.Exec(`DELETE FROM exercises
- WHERE id NOT IN (SELECT exercise_id FROM workout_exercises)
- AND id NOT IN (SELECT exercise_id FROM program_exercises)`)
- if err != nil {
- return 0, err
- }
- n, err := res.RowsAffected()
- return int(n), err
-}
-
// PrimeQuery materializes whatever the catalog returns for one search term.
//
// This is how a caller that needs specific exercises to exist locally — demo data
-// building a routine, say — gets them, without anything importing the catalog
-// wholesale.
+// building a routine, say — gets them, so it does not wait for the scheduled pass.
func (s *ExerciseStore) PrimeQuery(ctx context.Context, query string) error {
if s.catalog == nil {
return ErrNoCatalog
diff --git a/backend/stores/exercise_locale_sync.go b/backend/stores/exercise_locale_sync.go
index 287bec1..e62146b 100644
--- a/backend/stores/exercise_locale_sync.go
+++ b/backend/stores/exercise_locale_sync.go
@@ -2,6 +2,7 @@ package stores
import (
"context"
+ "errors"
"fmt"
"log"
"sort"
@@ -21,8 +22,9 @@ var catalogRetryBackoff = []time.Duration{time.Minute, 5 * time.Minute, 30 * tim
// stall the loop. A var so a test can shrink it.
var localeSyncTimeout = 2 * time.Minute
-// RunCatalogSync re-reads every held exercise in every language the catalog offers, once
-// at start and then every interval, sooner while a pass is failing. No request triggers it
+// RunCatalogSync imports every catalog exercise in English and then re-reads every held
+// one in every other language the catalog offers, once at start and then every interval,
+// sooner while a pass is failing. No request triggers it
// or waits on it; it blocks until ctx is done, so callers run it in a goroutine.
func (s *ExerciseStore) RunCatalogSync(ctx context.Context, every time.Duration) {
if s.catalog == nil {
@@ -31,7 +33,7 @@ func (s *ExerciseStore) RunCatalogSync(ctx context.Context, every time.Duration)
failures := 0
for {
wait := every
- if err := s.syncCatalog(ctx); err != nil {
+ if _, err := s.syncCatalog(ctx); err != nil {
wait = retryDelay(failures, every)
failures++
log.Printf("exercises: catalog sync incomplete, will try again in %s: %v", wait, err)
@@ -53,17 +55,27 @@ func retryDelay(failures int, every time.Duration) time.Duration {
return min(d, every)
}
-func (s *ExerciseStore) syncCatalog(ctx context.Context) error {
+// syncCatalog is the one catalog pass. English goes first, because it creates the rows
+// every translation attaches to; the other languages follow. The int is how many
+// exercises the English pass recorded. A language that fails does not stop the rest.
+func (s *ExerciseStore) syncCatalog(ctx context.Context) (int, error) {
+ if s.catalog == nil {
+ return 0, ErrNoCatalog
+ }
+ if !s.syncing.CompareAndSwap(false, true) {
+ return 0, ErrSyncRunning
+ }
+ defer s.syncing.Store(false)
dctx, cancel := context.WithTimeout(ctx, localeSyncTimeout)
codes, err := s.catalog.Revalidating().Locales(dctx)
cancel()
if err != nil {
- return err
+ return 0, fmt.Errorf("%w: %w", ErrCatalogUnreachable, err)
}
seen := map[string]bool{}
var locales []string
for _, c := range codes {
- if l := NormalizeLocale(c); !seen[l] {
+ if l := NormalizeLocale(c); l != defaultLocale && !seen[l] {
seen[l] = true
locales = append(locales, l)
}
@@ -71,20 +83,25 @@ func (s *ExerciseStore) syncCatalog(ctx context.Context) error {
// replaceTranslation for es-MX deletes the es row it falls back over, so every
// regional tag must be synced before its base language.
sort.Sort(sort.Reverse(sort.StringSlice(locales)))
- failed := 0
+ locales = append([]string{defaultLocale}, locales...)
+ english := 0
+ var errs []error
for _, l := range locales {
lctx, cancel := context.WithTimeout(ctx, localeSyncTimeout)
n, err := s.refresh(lctx, l)
cancel()
+ if l == defaultLocale {
+ english = n
+ }
if err != nil {
- failed++
+ errs = append(errs, err)
log.Printf("exercises: catalog sync for %q failed after %d rows: %.200v", l, n, err)
continue
}
- log.Printf("exercises: refreshed %d cached exercises in %q", n, l)
+ log.Printf("exercises: synced %d exercises in %q", n, l)
}
- if failed > 0 {
- return fmt.Errorf("%d of %d languages did not sync", failed, len(locales))
+ if len(errs) > 0 {
+ return english, fmt.Errorf("%d of %d languages did not sync: %w", len(errs), len(locales), errors.Join(errs...))
}
- return nil
+ return english, nil
}
diff --git a/backend/stores/exercise_locale_sync_test.go b/backend/stores/exercise_locale_sync_test.go
index dfcde40..eafcc97 100644
--- a/backend/stores/exercise_locale_sync_test.go
+++ b/backend/stores/exercise_locale_sync_test.go
@@ -29,9 +29,11 @@ type localeCatalog struct {
mu sync.Mutex
calls []catalogCall
locales []string
- held int
+ upstream int
failPath map[string]bool
failLocale map[string]bool
+ // exportExtra is appended to the export, for a duplicate-name upstream.
+ exportExtra []oedb.Exercise
// cacheControl is sent on every response; empty means max-age=0.
cacheControl string
@@ -39,15 +41,16 @@ type localeCatalog struct {
rev int
}
-func newLocaleCatalog(t *testing.T, held int, locales ...string) *localeCatalog {
+func newLocaleCatalog(t *testing.T, upstream int, locales ...string) *localeCatalog {
t.Helper()
- c := &localeCatalog{locales: locales, held: held, failPath: map[string]bool{}, failLocale: map[string]bool{}}
+ c := &localeCatalog{locales: locales, upstream: upstream, failPath: map[string]bool{}, failLocale: map[string]bool{}}
c.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
c.mu.Lock()
failed := c.failPath[r.URL.Path] || c.failLocale[q.Get("locale")] && r.URL.Path == "/api/v1/exercises"
locs := append([]string(nil), c.locales...)
rev := c.rev
+ extra := append([]oedb.Exercise(nil), c.exportExtra...)
cc := c.cacheControl
etag := fmt.Sprintf("\"r%d\"", rev)
inm := r.Header.Get("If-None-Match")
@@ -87,9 +90,10 @@ func newLocaleCatalog(t *testing.T, held int, locales ...string) *localeCatalog
_ = json.NewEncoder(w).Encode(out)
case "/api/v1/exercises/export":
var items []oedb.Exercise
- for i := 0; i < c.held; i++ {
+ for i := 0; i < c.upstream; i++ {
items = append(items, catalogExercise(fmt.Sprintf("uuid-%03d", i), fmt.Sprintf("Exercise %03d", i)+suffix))
}
+ items = append(items, extra...)
_ = json.NewEncoder(w).Encode(oedb.ListResult{Exercises: items, Total: len(items)})
case "/api/v1/exercises":
loc := q.Get("locale")
@@ -164,11 +168,19 @@ func holdEnglish(t *testing.T, s *ExerciseStore, n int) {
materialize(t, s, "en", items...)
}
-func syncStore(t *testing.T, held int, locales ...string) (*ExerciseStore, *localeCatalog) {
+// catalogStore is an empty database wired to a fake catalog serving upstream exercises.
+func catalogStore(t *testing.T, upstream int, locales ...string) (*ExerciseStore, *localeCatalog) {
t.Helper()
- cat := newLocaleCatalog(t, held, locales...)
+ cat := newLocaleCatalog(t, upstream, locales...)
s := NewExerciseStore(testDB(t))
s.UseCatalog(oedb.New(cat.srv.URL, "test"))
+ return s, cat
+}
+
+// syncStore is a catalogStore that already holds every upstream exercise in English.
+func syncStore(t *testing.T, held int, locales ...string) (*ExerciseStore, *localeCatalog) {
+ t.Helper()
+ s, cat := catalogStore(t, held, locales...)
holdEnglish(t, s, held)
return s, cat
}
@@ -211,7 +223,7 @@ func TestRefresh_FillsEveryHeldRowInBatches(t *testing.T) {
func TestSyncCatalog_SyncsEveryLanguageTheCatalogLists(t *testing.T) {
s, cat := syncStore(t, 5, "en", "es", "pt")
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
if got := cat.count("/api/v1/exercises/export", ""); got != 1 {
@@ -233,7 +245,7 @@ func TestSyncCatalog_SyncsEveryLanguageTheCatalogLists(t *testing.T) {
func TestSyncCatalog_RegionalBeforeBase(t *testing.T) {
s, cat := syncStore(t, 3, "en", "es", "es-MX")
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
id := localID(t, s, "uuid-001")
@@ -260,7 +272,7 @@ func TestSyncCatalog_RegionalBeforeBase(t *testing.T) {
func TestSyncCatalog_NormalizesAndDedupesDiscoveredCodes(t *testing.T) {
s, cat := syncStore(t, 3, "EN", "es", "ES", "bad tag!")
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
if got := cat.count("/api/v1/exercises/export", ""); got != 1 {
@@ -280,7 +292,7 @@ func TestSyncCatalog_DiscoveryFailureSyncsNothing(t *testing.T) {
s, cat := syncStore(t, 3, "en", "es")
cat.setFail("/api/v1/meta/locales", "")
- if err := s.syncCatalog(t.Context()); err == nil {
+ if _, err := s.syncCatalog(t.Context()); err == nil {
t.Fatal("want the discovery failure reported")
}
if got := cat.listCount(""); got != 0 {
@@ -298,7 +310,7 @@ func TestSyncCatalog_OneLanguageFailingDoesNotStopTheRest(t *testing.T) {
s, cat := syncStore(t, 4, "en", "es", "pt")
cat.setFail("", "es")
- if err := s.syncCatalog(t.Context()); err == nil {
+ if _, err := s.syncCatalog(t.Context()); err == nil {
t.Fatal("want the failed language reported so the loop retries sooner")
}
if got := countRows(t, s.db, `SELECT COUNT(*) FROM exercise_translations WHERE locale = 'pt'`); got != 4 {
@@ -309,14 +321,170 @@ func TestSyncCatalog_OneLanguageFailingDoesNotStopTheRest(t *testing.T) {
}
}
-func TestSyncCatalog_EmptyCacheRequestsOnlyLocales(t *testing.T) {
- s, cat := syncStore(t, 0, "en", "es")
+func TestSyncCatalog_EmptyUpstreamWritesNothing(t *testing.T) {
+ s, cat := catalogStore(t, 0, "en", "es")
+
+ n, err := s.syncCatalog(t.Context())
+ if err != nil || n != 0 {
+ t.Fatalf("syncCatalog = %d, %v, want 0, nil", n, err)
+ }
+ if cat.localeRequests() != 1 || cat.count("/api/v1/exercises/export", "") != 1 || cat.listCount("") != 0 {
+ t.Errorf("calls = %+v, want 1 locales, 1 export, 0 list", cat.snapshot())
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 0 {
+ t.Errorf("exercises = %d, want 0", got)
+ }
+}
+
+func TestSyncCatalog_EmptyDBImportsEveryExerciseAndItsTranslations(t *testing.T) {
+ s, cat := catalogStore(t, 250, "en", "es")
- if err := s.syncCatalog(t.Context()); err != nil {
+ n, err := s.syncCatalog(t.Context())
+ if err != nil || n != 250 {
+ t.Fatalf("syncCatalog = %d, %v, want 250, nil", n, err)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 250 {
+ t.Errorf("exercises = %d, want 250", got)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercise_translations WHERE locale = 'es'"); got != 250 {
+ t.Errorf("es translations = %d, want 250", got)
+ }
+ id := localID(t, s, "uuid-007")
+ if got := mustGet(t, s, id, "es").Name; got != "es uuid-007" {
+ t.Errorf("Get(es).Name = %q, want the es name", got)
+ }
+ if got := mustGet(t, s, id, "en").Name; got != "Exercise 007" {
+ t.Errorf("Get(en).Name = %q, want English", got)
+ }
+ if cat.localeRequests() != 1 || cat.count("/api/v1/exercises/export", "") != 1 || cat.listCount("es") != 3 {
+ t.Errorf("requests: locales=%d export=%d es lists=%d, want 1, 1, 3",
+ cat.localeRequests(), cat.count("/api/v1/exercises/export", ""), cat.listCount("es"))
+ }
+ for _, c := range cat.snapshot() {
+ if c.path == "/api/v1/exercises" && len(strings.Split(c.ids, ",")) > oedb.MaxPerPage {
+ t.Errorf("list request carried more than %d ids", oedb.MaxPerPage)
+ }
+ }
+}
+
+func TestSyncCatalog_SecondPassIsIdempotent(t *testing.T) {
+ s, _ := catalogStore(t, 250, "en", "es")
+ ids := func() map[string]int64 {
+ m := map[string]int64{}
+ rows, err := s.db.Query("SELECT oedb_id, id FROM exercises")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var k string
+ var v int64
+ if err := rows.Scan(&k, &v); err != nil {
+ t.Fatal(err)
+ }
+ m[k] = v
+ }
+ return m
+ }
+
+ n1, err := s.syncCatalog(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ first := ids()
+ n2, err := s.syncCatalog(t.Context())
+ if err != nil {
t.Fatal(err)
}
- if got := len(cat.snapshot()); got != 1 || cat.localeRequests() != 1 {
- t.Errorf("calls = %+v, want only the locales request", cat.snapshot())
+ second := ids()
+ if n1 != 250 || n2 != 250 {
+ t.Errorf("recorded = %d then %d, want 250 both times", n1, n2)
+ }
+ if len(first) != 250 || len(second) != 250 {
+ t.Fatalf("rows = %d then %d, want 250", len(first), len(second))
+ }
+ for k, v := range first {
+ if second[k] != v {
+ t.Errorf("%s moved from local id %d to %d", k, v, second[k])
+ }
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercise_translations WHERE locale = 'es'"); got != 250 {
+ t.Errorf("es translations = %d, want 250", got)
+ }
+}
+
+func TestSyncCatalog_ImportsInTransactionsOfAtMostOnePage(t *testing.T) {
+ s, _ := catalogStore(t, 250, "en")
+ if _, err := s.db.Exec("CREATE TRIGGER t BEFORE INSERT ON exercises WHEN NEW.oedb_id = 'uuid-150' BEGIN SELECT RAISE(ABORT, 'boom'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err := s.syncCatalog(t.Context())
+ if err == nil || errors.Is(err, ErrCatalogUnreachable) {
+ t.Fatalf("err = %v, want a database error, not ErrCatalogUnreachable", err)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 100 {
+ t.Errorf("exercises = %d, want exactly the first committed chunk of 100", got)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises WHERE oedb_id = 'uuid-099'"); got != 1 {
+ t.Errorf("uuid-099 missing: the first chunk must have committed")
+ }
+
+ if _, err := s.db.Exec("DROP TRIGGER t"); err != nil {
+ t.Fatal(err)
+ }
+ n, err := s.syncCatalog(t.Context())
+ if err != nil || n != 250 {
+ t.Fatalf("retry = %d, %v, want 250, nil", n, err)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 250 {
+ t.Errorf("exercises = %d after retry, want 250", got)
+ }
+}
+
+func TestSyncCatalog_FailedLanguageKeepsImportedRowsAndReportsUnreachable(t *testing.T) {
+ s, cat := catalogStore(t, 5, "en", "es")
+ cat.setFail("", "es")
+
+ n, err := s.syncCatalog(t.Context())
+ if !errors.Is(err, ErrCatalogUnreachable) {
+ t.Fatalf("err = %v, want ErrCatalogUnreachable", err)
+ }
+ if n != 5 {
+ t.Errorf("recorded = %d, want 5", n)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 5 {
+ t.Errorf("exercises = %d, want the 5 English rows kept", got)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercise_translations WHERE locale = 'es'"); got != 0 {
+ t.Errorf("es translations = %d, want 0", got)
+ }
+}
+
+func TestSyncCatalog_BulkImportSkipsADuplicateUpstreamName(t *testing.T) {
+ s, cat := catalogStore(t, 2, "en", "es")
+ cat.exportExtra = []oedb.Exercise{catalogExercise("uuid-dup", "Exercise 000")}
+
+ if _, err := s.syncCatalog(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ first := localID(t, s, "uuid-000")
+ if _, err := s.syncCatalog(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 2 {
+ t.Errorf("exercises = %d, want 2", got)
+ }
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises WHERE oedb_id = 'uuid-dup'"); got != 0 {
+ t.Errorf("the duplicate name was imported as its own row")
+ }
+ if got := localID(t, s, "uuid-000"); got != first {
+ t.Errorf("uuid-000 moved from %d to %d", first, got)
+ }
+ for _, c := range cat.snapshot() {
+ if strings.Contains(c.ids, "uuid-dup") {
+ t.Errorf("listed the skipped id: %+v", c)
+ }
}
}
@@ -423,12 +591,12 @@ func TestSyncCatalog_SecondPassAppliesUpstreamChangesInsideTheCacheWindow(t *tes
s, cat := syncStore(t, 3, "en", "es")
cat.setCacheControl(slowCacheControl)
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
cat.setRev(1)
cat.setLocales("en", "es", "pt")
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
id := localID(t, s, "uuid-001")
@@ -447,7 +615,7 @@ func TestSyncCatalog_UnchangedUpstreamIsRevalidatedWithout304Bodies(t *testing.T
s, cat := syncStore(t, 3, "en", "es")
cat.setCacheControl(slowCacheControl)
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
if _, err := s.db.Exec(`UPDATE exercise_translations SET name = 'tampered' WHERE locale = 'es'`); err != nil {
@@ -457,7 +625,7 @@ func TestSyncCatalog_UnchangedUpstreamIsRevalidatedWithout304Bodies(t *testing.T
t.Fatal(err)
}
before := len(cat.snapshot())
- if err := s.syncCatalog(t.Context()); err != nil {
+ if _, err := s.syncCatalog(t.Context()); err != nil {
t.Fatal(err)
}
second := cat.snapshot()[before:]
@@ -492,7 +660,7 @@ func TestSyncCatalog_LocaleDiscoveryHasADeadline(t *testing.T) {
holdEnglish(t, s, 2)
start := time.Now()
- err := s.syncCatalog(t.Context())
+ _, err := s.syncCatalog(t.Context())
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want context.DeadlineExceeded", err)
}
@@ -503,3 +671,25 @@ func TestSyncCatalog_LocaleDiscoveryHasADeadline(t *testing.T) {
t.Errorf("non-English translations = %d, want 0", got)
}
}
+
+func TestSyncCatalog_RefusesASecondPassWhileOneRuns(t *testing.T) {
+ s, cat := syncStore(t, 3, "es")
+ before := len(cat.snapshot())
+ s.syncing.Store(true)
+
+ _, err := s.syncCatalog(context.Background())
+ if !errors.Is(err, ErrSyncRunning) {
+ t.Fatalf("err = %v, want ErrSyncRunning", err)
+ }
+ if n := len(cat.snapshot()) - before; n != 0 {
+ t.Errorf("a refused pass made %d upstream requests, want none", n)
+ }
+
+ s.syncing.Store(false)
+ if _, err := s.syncCatalog(context.Background()); err != nil {
+ t.Fatalf("pass after the flag cleared: %v", err)
+ }
+ if s.syncing.Load() {
+ t.Error("the flag was left held after a pass")
+ }
+}
diff --git a/backend/stores/exercise_locale_test.go b/backend/stores/exercise_locale_test.go
index b86004c..a937319 100644
--- a/backend/stores/exercise_locale_test.go
+++ b/backend/stores/exercise_locale_test.go
@@ -349,31 +349,23 @@ func TestList_LocalSearchCoversTranslationAndEnglish(t *testing.T) {
eq(names("", "en"), "Bench Press", "Curl", "Squat")
}
-func TestClearUnreferenced_CascadesTranslations(t *testing.T) {
+func TestDeletingAnExercise_CascadesItsTranslations(t *testing.T) {
conn := testDB(t)
s := NewExerciseStore(conn)
materialize(t, s, "en", englishSquat(), served("uuid-2", "Deadlift", "en", []string{"Lift."}, "en"))
materialize(t, s, "es", spanishSquat())
materialize(t, s, "es", served("uuid-2", "Peso muerto", "es", []string{"Levanta."}, "es"))
-
- uid := seedUser(t, conn)
var keep int64
- conn.QueryRow(`SELECT id FROM exercises WHERE oedb_id = 'uuid-2'`).Scan(&keep)
- pid := seedProgram(t, conn, uid, keep)
- _ = pid
+ conn.QueryRow("SELECT id FROM exercises WHERE oedb_id = 'uuid-2'").Scan(&keep)
- n, err := s.ClearUnreferenced()
- if err != nil {
- t.Fatalf("ClearUnreferenced: %v", err)
- }
- if n != 1 {
- t.Errorf("deleted %d, want the one unreferenced exercise", n)
+ if _, err := conn.Exec("DELETE FROM exercises WHERE oedb_id = 'uuid-1'"); err != nil {
+ t.Fatalf("delete: %v", err)
}
- if c := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations`); c != 1 {
- t.Errorf("translation rows = %d, want only the referenced exercise's", c)
+ if c := countRows(t, conn, "SELECT COUNT(*) FROM exercise_translations"); c != 1 {
+ t.Errorf("translation rows = %d, want only the surviving exercise's", c)
}
- if c := countRows(t, conn, `SELECT COUNT(*) FROM exercise_translations WHERE exercise_id = ?`, keep); c != 1 {
- t.Errorf("the referenced exercise lost its translation")
+ if c := countRows(t, conn, "SELECT COUNT(*) FROM exercise_translations WHERE exercise_id = ?", keep); c != 1 {
+ t.Errorf("the surviving exercise lost its translation")
}
}
diff --git a/backend/stores/exercise_test.go b/backend/stores/exercise_test.go
index 67256a0..af3a46b 100644
--- a/backend/stores/exercise_test.go
+++ b/backend/stores/exercise_test.go
@@ -210,79 +210,32 @@ func TestCacheControls_WithoutCatalogError(t *testing.T) {
}
}
-// Clearing the cache must leave anything a workout or program references. Those
-// foreign keys have no cascade, so deleting a referenced row would either be
-// refused or, without the FK, orphan a user's logged sets.
-func TestClearUnreferenced_KeepsReferencedRows(t *testing.T) {
- conn := testDB(t)
- s := NewExerciseStore(conn)
-
- if _, err := conn.Exec(`INSERT INTO exercises (id, name) VALUES (1, 'Used'), (2, 'Unused')`); err != nil {
- t.Fatalf("seed exercises: %v", err)
- }
- if _, err := conn.Exec(`INSERT INTO users (id, email, password_hash) VALUES (1, '[email protected]', 'x')`); err != nil {
- t.Fatalf("seed user: %v", err)
- }
- if _, err := conn.Exec(`INSERT INTO workouts (id, user_id, name) VALUES (1, 1, 'W')`); err != nil {
- t.Fatalf("seed workout: %v", err)
- }
- if _, err := conn.Exec(`INSERT INTO workout_exercises (workout_id, exercise_id, order_index) VALUES (1, 1, 0)`); err != nil {
- t.Fatalf("seed workout_exercise: %v", err)
- }
-
- n, err := s.ClearUnreferenced()
- if err != nil {
- t.Fatalf("clear: %v", err)
- }
- if n != 1 {
- t.Errorf("cleared %d, want 1", n)
- }
- var remaining string
- if err := conn.QueryRow(`SELECT name FROM exercises`).Scan(&remaining); err != nil {
- t.Fatalf("read remaining: %v", err)
- }
- if remaining != "Used" {
- t.Errorf("remaining = %q, want the referenced row", remaining)
- }
-}
-
-// Refresh applies upstream edits to rows already held, and must not import rows
-// the instance has never seen — that is the line between refreshing a cache and
-// seeding a library.
-func TestRefreshCached_UpdatesHeldRowsWithoutImporting(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, `{"exercises":[
- {"id":"uuid-1","slug":"held","muscle_group":"chest","translation":{"name":"Held Renamed","instructions":[]}},
- {"id":"uuid-2","slug":"new","muscle_group":"back","translation":{"name":"Never Seen","instructions":[]}}
- ],"total":2}`)
- }))
- defer srv.Close()
-
- conn := testDB(t)
- s := NewExerciseStore(conn)
- s.UseCatalog(oedb.New(srv.URL, "test"))
-
- if _, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Held Original")}, srv.URL, "en"); err != nil {
+// The admin entry point is the scheduled pass: it imports rows the instance never
+// held, and updates the ones it did hold under the same local id.
+func TestRefreshCached_ImportsTheWholeCatalog(t *testing.T) {
+ s, _ := catalogStore(t, 3, "en")
+ if _, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-000", "Held Original")}, s.catalog.BaseURL(), "en"); err != nil {
t.Fatalf("seed held row: %v", err)
}
+ heldID := localID(t, s, "uuid-000")
n, err := s.RefreshCached(context.Background())
if err != nil {
t.Fatalf("refresh: %v", err)
}
- if n != 1 {
- t.Errorf("refreshed %d, want 1", n)
+ if n != 3 {
+ t.Errorf("refreshed %d, want 3", n)
}
-
- var total int
- conn.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&total)
- if total != 1 {
- t.Errorf("exercise count = %d, want 1 — refresh imported an unseen row", total)
+ if got := countRows(t, s.db, "SELECT COUNT(*) FROM exercises"); got != 3 {
+ t.Errorf("exercise count = %d, want the whole catalog of 3", got)
}
var name string
- conn.QueryRow(`SELECT name FROM exercises WHERE oedb_id = 'uuid-1'`).Scan(&name)
- if name != "Held Renamed" {
- t.Errorf("name = %q, want the upstream edit applied", name)
+ s.db.QueryRow("SELECT name FROM exercises WHERE id = ?", heldID).Scan(&name)
+ if name != "Exercise 000" {
+ t.Errorf("held row name = %q, want the upstream edit under the same local id", name)
+ }
+ for _, id := range []string{"uuid-001", "uuid-002"} {
+ localID(t, s, id)
}
}
diff --git a/backend/utils/codes.go b/backend/utils/codes.go
index e89e148..8529135 100644
--- a/backend/utils/codes.go
+++ b/backend/utils/codes.go
@@ -115,6 +115,7 @@ var (
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.")
+ CodeExerciseSyncRunning = define("EXERCISE_SYNC_RUNNING", 409, "An exercise sync is already running. Try again when it finishes.")
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 22f297f..54bfe44 100644
--- a/docs/API_CHANGES.md
+++ b/docs/API_CHANGES.md
@@ -14,6 +14,19 @@ catches what the author knew and forgot; it cannot catch what the author never n
If your PR changes a status code, narrows an accepted value, or renames a response field,
add the entry in that PR.
+## `POST /api/v1/admin/reset-exercises` removed; `POST /api/v1/admin/sync-exercises` imports the whole catalog
+
+`reset-exercises` no longer exists and answers 404, so a caller using it to drop unreferenced
+rows has nothing to call: the server now keeps the whole catalog. A background pass at boot
+and every 24h, retried with backoff on failure, imports every open-exercise-db exercise in
+English, then translations for every held exercise in each catalog language.
+
+`sync-exercises` runs that same pass on demand. It now fills an empty install, `refreshed`
+is the number of exercises the English pass recorded, and it covers every language, so it
+takes longer, and answers 409 `EXERCISE_SYNC_RUNNING` if a pass (this call or the daily one) is already running. A pass that fails partway keeps what it wrote and answers 503
+`EXERCISE_CATALOG_UNREACHABLE` (upstream) or a database error code. `GET
+/admin/seed-status` `count` is the whole catalog once a pass has completed.
+
## Every error response — gains a stable `code` beside `error`
Additive: `error` is byte-identical to before and still authoritative for any caller that
@@ -21,7 +34,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 (71). Every error has its own code with a fixed status; there is no generic
+Codes (72). 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 +53,7 @@ Codes (71). 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`); `EXERCISE_CATALOG_UNREACHABLE` (`503`, with `Retry-After: 2`).
+ (`400`); `EXERCISE_CATALOG_UNREACHABLE` (`503`, with `Retry-After: 2`); `EXERCISE_SYNC_RUNNING` (`409`).
- 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`);
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index a177062..ab460fd 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -689,6 +689,7 @@ describe('apiErrorMessage — server codes', () => {
it.each([
['FOOD_DATABASE_TIMEOUT', 503, undefined, undefined],
['EXERCISE_CATALOG_UNREACHABLE', 503, undefined, undefined],
+ ['EXERCISE_SYNC_RUNNING', 409, 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/client.ts b/packages/shared/src/client.ts
index 32a911f..6f4fbfb 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -449,16 +449,14 @@ export function createClient(
get: (id: number) => api.get<{ data: types.Exercise }>(`/exercises/${id}`).then(unwrap),
getPRs: (id: number) => api.get<{ data: types.PersonalRecord }>(`/exercises/${id}/prs`).then(unwrap),
getHistory: (id: number, limit = 20) => api.get<{ data: types.ExerciseHistoryPoint[] }>(`/exercises/${id}/history`, { params: { limit } }).then(unwrap),
- // Lyftr does not keep its own exercise library. open-exercise-db is the source and
- // is queried live; the server holds only the rows it has had reason to look at, and
- // these three manage that cache rather than a catalog.
+ // The server imports the whole open-exercise-db catalog in a daily background pass;
+ // these two report its size and run that pass now.
cacheStatus: () => api.get<{ data: { count: number } }>('/admin/seed-status').then(unwrap),
- // Re-reads every row the server already holds, applying upstream corrections. It
- // pulls the full upstream export to do so, which on a cold server runs past the
+ // Runs the full catalog pass now: imports every upstream exercise and refreshes every
+ // language. On a cold server that runs past the
// global 20s — the button is an explicit admin action the user waits on, so it gets
// its own bound. A timeout here would report failure for work that goes on to finish.
refreshCache: () => api.post<{ data: { refreshed: number } }>('/admin/sync-exercises', undefined, { timeout: SYNC_TIMEOUT }).then(unwrap),
- clearCacheOnServer: () => api.post<{ data: { cleared: number } }>('/admin/reset-exercises', undefined, { timeout: SYNC_TIMEOUT }).then(unwrap),
}
const programAPI = {
diff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.json
index 693c8e8..fa1f684 100644
--- a/packages/shared/src/i18n/locales/en.json
+++ b/packages/shared/src/i18n/locales/en.json
@@ -172,21 +172,16 @@
"title": "Exercise Library",
"database": {
"label": "Exercise database",
- "description": "Exercises come from open-exercise-db, queried as you search. This server keeps a copy of the ones it has shown."
+ "description": "Exercises come from open-exercise-db. This server keeps a copy of the whole catalog and refreshes it daily."
},
"cached_one": "{{amount}} cached",
"cached_other": "{{amount}} cached",
"cachedUnknown": "— cached",
"refreshed_one": "Refreshed {{amount}} exercise",
"refreshed_other": "Refreshed {{amount}} exercises",
- "cleared_one": "Cleared {{amount}} unused exercise",
- "cleared_other": "Cleared {{amount}} unused exercises",
"refresh": "Refresh cached",
"refreshing": "Refreshing…",
- "refreshFailed": "Couldn't refresh the cache.",
- "clear": "Clear unused",
- "clearing": "Clearing…",
- "clearFailed": "Couldn't clear the cache."
+ "refreshFailed": "Couldn't refresh the cache."
},
"danger": {
"title": "Danger Zone",
@@ -358,6 +353,7 @@
"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.",
+ "EXERCISE_SYNC_RUNNING": "An exercise sync is already running. Try again when it finishes.",
"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 576fb52..d9b7ad1 100644
--- a/packages/shared/src/i18n/locales/es.json
+++ b/packages/shared/src/i18n/locales/es.json
@@ -172,7 +172,7 @@
"title": "Biblioteca de ejercicios",
"database": {
"label": "Base de datos de ejercicios",
- "description": "Los ejercicios vienen de open-exercise-db y se consultan mientras buscas. Este servidor guarda una copia de los que ha mostrado."
+ "description": "Los ejercicios vienen de open-exercise-db. Este servidor guarda una copia de todo el catálogo y la actualiza cada día."
},
"cached_one": "{{amount}} en caché",
"cached_many": "{{amount}} en caché",
@@ -181,15 +181,9 @@
"refreshed_one": "Se actualizó {{amount}} ejercicio",
"refreshed_many": "Se actualizaron {{amount}} de ejercicios",
"refreshed_other": "Se actualizaron {{amount}} ejercicios",
- "cleared_one": "Se eliminó {{amount}} ejercicio sin usar",
- "cleared_many": "Se eliminaron {{amount}} de ejercicios sin usar",
- "cleared_other": "Se eliminaron {{amount}} ejercicios sin usar",
"refresh": "Actualizar caché",
"refreshing": "Actualizando…",
- "refreshFailed": "No se pudo actualizar la caché.",
- "clear": "Eliminar no usados",
- "clearing": "Eliminando…",
- "clearFailed": "No se pudo borrar la caché."
+ "refreshFailed": "No se pudo actualizar la caché."
},
"danger": {
"title": "Zona de peligro",
@@ -365,6 +359,7 @@
"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.",
+ "EXERCISE_SYNC_RUNNING": "Ya hay una sincronización de ejercicios en curso. Inténtalo de nuevo cuando termine.",
"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}}.",
diff --git a/web/src/pages/Settings.test.tsx b/web/src/pages/Settings.test.tsx
index 9c797a2..8e81476 100644
--- a/web/src/pages/Settings.test.tsx
+++ b/web/src/pages/Settings.test.tsx
@@ -64,7 +64,6 @@ vi.mock('../services/api', () => ({
exerciseAPI: {
cacheStatus: vi.fn().mockResolvedValue({ count: 0 }),
refreshCache: vi.fn(),
- clearCacheOnServer: vi.fn(),
},
userAPI: { deleteAccount: vi.fn() },
}))
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 111b096..2b0d0c2 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -98,7 +98,7 @@ export default function Settings() {
const [unitError, setUnitError] = useState<UiMessage | null>(null)
const [cacheStatus, setCacheStatus] = useState<{ count: number } | null>(null)
- const [seedAction, setSeedAction] = useState<'refresh' | 'clear' | null>(null)
+ const [seedAction, setSeedAction] = useState<'refresh' | null>(null)
// Carries whether it FAILED, not just what it said. Both outcomes used to land in
// one muted grey line, so "Refreshed 812 exercises" and "Can't reach the server
// right now." were the same small grey text — a failure that does not read as one.
@@ -154,8 +154,8 @@ export default function Settings() {
loadCacheStatus()
}, [load, loadCacheStatus])
- // No polling: nothing populates the cache in the background any more. It fills as
- // a side-effect of reads, and these two actions are synchronous.
+ // No polling: the count is a snapshot, the server's daily pass fills the table on its
+ // own schedule, and Refresh runs that pass synchronously.
const handleRefreshCache = async () => {
setSeedAction('refresh')
@@ -171,20 +171,6 @@ export default function Settings() {
}
}
- const handleClearCache = async () => {
- setSeedAction('clear')
- setSeedMsg(null)
- try {
- const res = await exerciseAPI.clearCacheOnServer()
- setSeedMsg({ message: { key: 'settings.library.cleared', params: { count: res.cleared, amount: res.cleared.toLocaleString() } }, failed: false })
- loadCacheStatus()
- } catch (err) {
- setSeedMsg({ message: { key: 'settings.library.clearFailed', cause: err }, failed: true })
- } finally {
- setSeedAction(null)
- }
- }
-
// The store rolls its own optimistic patch back when the write fails, so the app no
// longer shows a unit the server never accepted. Saying so is still this page's job —
@@ -613,16 +599,6 @@ export default function Settings() {
: <><RefreshCw className="w-3.5 h-3.5" /> {t('settings.library.refresh')}</>
}
</button>
- <button
- onClick={handleClearCache}
- disabled={!!seedAction}
- className="btn-secondary btn-sm"
- >
- {seedAction === 'clear'
- ? <><Loader className="w-3.5 h-3.5 animate-spin" /> {t('settings.library.clearing')}</>
- : <><Trash2 className="w-3.5 h-3.5" /> {t('settings.library.clear')}</>
- }
- </button>
</div>
</Section>