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.

Query open-exercise-db for exercises instead of shipping a copy (#116)

Cartera0354e51e975
diff --git a/.env.example b/.env.example
index e196166..250b723 100644
--- a/.env.example
+++ b/.env.example
@@ -11,6 +11,12 @@ REGISTRATION=open
# Seeds [email protected], whose password is public. Leave off on a reachable instance.
DEMO_MODE=false
+# The open-exercise-db instance the exercise catalog is queried from. Lyftr does not
+# ship or seed an exercise library: it asks this API as you search, and keeps only the
+# rows it has shown. Unset uses the hosted instance; point it at your own to self-host
+# the catalog too.
+# OEDB_BASE_URL=https://oedb-api-o4dqddih5q-uk.a.run.app
+
# Address the frontend's nginx proxies /api to, over the internal Docker network.
# This MUST be the backend's Docker service name (backend) — NOT your host/LAN IP.
# Only change the port, and only if you set a custom backend PORT, e.g. backend:3008.
diff --git a/backend/config/config.go b/backend/config/config.go
index 4559739..5537158 100644
--- a/backend/config/config.go
+++ b/backend/config/config.go
@@ -28,6 +28,11 @@ type Config struct {
// Registration is who may create an account: RegistrationOpen, RegistrationClosed,
// or RegistrationFirstUser (open only while the users table is empty).
Registration string
+ // OEDBBaseURL is the open-exercise-db instance Lyftr queries for its exercise
+ // catalog. Empty selects the hosted one; point it at a self-hosted catalog, or
+ // at a test double, by setting OEDB_BASE_URL.
+ OEDBBaseURL string
+
// DemoMode seeds the demo account and its 8 weeks of sample data. Off outside
// development: the credentials are published in the README, so an instance that
// seeds them has a known-password account whatever Registration says.
@@ -78,6 +83,8 @@ func Load() {
Env: env,
Version: buildVersion,
+ OEDBBaseURL: getEnv("OEDB_BASE_URL", ""),
+
Registration: getEnv("REGISTRATION", RegistrationOpen),
// Contributors following CONTRIBUTING.md get the demo account without setting
// anything; a self-hoster or the Fly demo has to ask for it.
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.go
index 4023ffa..f23c6db 100644
--- a/backend/controllers/exercises.go
+++ b/backend/controllers/exercises.go
@@ -2,6 +2,7 @@ package controllers
import (
"database/sql"
+ "errors"
"strconv"
"github.com/Cawlumm/lyftr-backend/middleware"
@@ -21,7 +22,10 @@ func (h *Handler) ListExercises(c *gin.Context) {
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 2000 {
f.Limit = l
}
- exercises, err := h.s.Exercise.List(f)
+ if p, err := strconv.Atoi(c.Query("page")); err == nil && p > 1 {
+ f.Page = p
+ }
+ exercises, err := h.s.Exercise.Search(c.Request.Context(), f)
if utils.DBError(c, err) {
return
}
@@ -87,29 +91,39 @@ func (h *Handler) GetExerciseHistory(c *gin.Context) {
utils.OK(c, history)
}
-// SyncExercises is an admin-only endpoint to re-pull from ExerciseDB.
-func (h *Handler) SyncExercises(c *gin.Context) {
- if err := h.s.Exercise.Sync(); err != nil {
- utils.BadRequest(c, err.Error())
+// 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.
+func (h *Handler) RefreshExerciseCache(c *gin.Context) {
+ n, err := h.s.Exercise.RefreshCached(c.Request.Context())
+ if errors.Is(err, stores.ErrNoCatalog) {
+ utils.BadRequest(c, "no exercise catalog configured")
return
}
- count, err := h.s.Exercise.Count()
- if utils.DBError(c, err) {
+ if err != nil {
+ utils.BadRequest(c, err.Error())
return
}
- utils.OK(c, gin.H{"synced": true, "total": count})
+ utils.OK(c, gin.H{"refreshed": n})
}
-// ExerciseSeedStatus returns exercise count and whether seeding is running.
-func (h *Handler) ExerciseSeedStatus(c *gin.Context) {
- utils.OK(c, h.s.Exercise.SeedStatus())
+// ExerciseCacheStatus reports how many catalog rows this instance holds.
+func (h *Handler) ExerciseCacheStatus(c *gin.Context) {
+ count, err := h.s.Exercise.CachedCount()
+ if utils.DBError(c, err) {
+ return
+ }
+ utils.OK(c, gin.H{"count": count})
}
-// ResetExercises wipes the exercises table and triggers a fresh seed in background.
-func (h *Handler) ResetExercises(c *gin.Context) {
- if err := h.s.Exercise.Reset(); err != nil {
- utils.BadRequest(c, err.Error())
+// 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{"reset": true, "message": "exercises wiped, re-seeding in background"})
+ utils.OK(c, gin.H{"cleared": n})
}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 34c8236..f66a402 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -120,6 +120,93 @@ func alterMigrations() {
ensureIndex("idx_food_logs_user_day", `CREATE INDEX IF NOT EXISTS idx_food_logs_user_day ON food_logs(user_id, logged_on)`)
ensureIndex("idx_weight_logs_user_day", `CREATE INDEX IF NOT EXISTS idx_weight_logs_user_day ON weight_logs(user_id, logged_on)`)
backfillLocalDays()
+
+ // Identity for the open-exercise-db row this exercise mirrors.
+ //
+ // Lyftr keeps its own INTEGER id as the primary key and does not adopt oedb's
+ // UUID as one: workout_exercises and program_exercises FK into exercises(id)
+ // with no cascade, so that key is load-bearing in user data that predates oedb
+ // entirely. oedb_id is the join key upward, not the identity downward.
+ //
+ // Nullable on purpose. A row with oedb_id IS NULL is one oedb does not know
+ // about — a pre-migration row whose name did not match, or (later) a
+ // user-created exercise not yet contributed. SQLite treats NULLs as distinct in
+ // a UNIQUE index, so any number of them coexist while still forbidding two rows
+ // claiming the same upstream exercise.
+ ensureColumn("exercises", "oedb_id", `ALTER TABLE exercises ADD COLUMN oedb_id TEXT`)
+ ensureColumn("exercises", "slug", `ALTER TABLE exercises ADD COLUMN slug TEXT`)
+ ensureIndex("idx_exercises_oedb_id", `CREATE UNIQUE INDEX IF NOT EXISTS idx_exercises_oedb_id ON exercises(oedb_id)`)
+
+ normalizeExerciseTaxonomy()
+}
+
+// normalizeExerciseTaxonomy rewrites the eight taxonomy values Lyftr inherited
+// verbatim from free-exercise-db into the slug forms open-exercise-db serves.
+//
+// Lyftr's seeder copied upstream's display strings ("body only", "lower back")
+// straight into the column. oedb normalizes the same vocabulary to slugs
+// ("body-only", "lower-back"). Once exercises arrive from oedb, a database left
+// unconverted holds both spellings of the same concept, and every equipment
+// filter silently returns half its rows.
+//
+// Safe to rewrite in place: no user-owned row stores a taxonomy string. Workouts
+// and programs reference exercises by id, so this touches presentation values
+// only. The set is closed and was verified against both corpora — these are the
+// only values that differ, in either direction.
+func normalizeExerciseTaxonomy() {
+ done, err := hasMigrationFlag("normalize_exercise_taxonomy")
+ if err != nil || done {
+ return
+ }
+
+ // secondary_muscles is a JSON array in a TEXT column, so it is rewritten with
+ // string replacement over the encoded form rather than by decoding each row.
+ // The quotes are part of the match: they pin the replacement to a whole JSON
+ // string element, so a value that merely contains another as a substring cannot
+ // be corrupted from the middle.
+ stmts := []struct {
+ sql string
+ args []any
+ }{
+ {`UPDATE exercises SET equipment = ? WHERE equipment = ?`, []any{"body-only", "body only"}},
+ {`UPDATE exercises SET equipment = ? WHERE equipment = ?`, []any{"e-z-curl-bar", "e-z curl bar"}},
+ {`UPDATE exercises SET equipment = ? WHERE equipment = ?`, []any{"exercise-ball", "exercise ball"}},
+ {`UPDATE exercises SET equipment = ? WHERE equipment = ?`, []any{"foam-roll", "foam roll"}},
+ {`UPDATE exercises SET equipment = ? WHERE equipment = ?`, []any{"medicine-ball", "medicine ball"}},
+ // oedb has no empty equipment: upstream's blank becomes the explicit "none".
+ {`UPDATE exercises SET equipment = ? WHERE equipment = ?`, []any{"none", ""}},
+ {`UPDATE exercises SET category = ? WHERE category = ?`, []any{"olympic-weightlifting", "olympic weightlifting"}},
+ {`UPDATE exercises SET muscle_group = ? WHERE muscle_group = ?`, []any{"lower-back", "lower back"}},
+ {`UPDATE exercises SET muscle_group = ? WHERE muscle_group = ?`, []any{"middle-back", "middle back"}},
+ {`UPDATE exercises SET secondary_muscles = replace(secondary_muscles, ?, ?)`, []any{`"lower back"`, `"lower-back"`}},
+ {`UPDATE exercises SET secondary_muscles = replace(secondary_muscles, ?, ?)`, []any{`"middle back"`, `"middle-back"`}},
+ }
+
+ tx, err := DB.Begin()
+ if err != nil {
+ log.Printf("migration: normalize exercise taxonomy: begin: %v", err)
+ return
+ }
+ changed := int64(0)
+ for _, s := range stmts {
+ res, err := tx.Exec(s.sql, s.args...)
+ if err != nil {
+ tx.Rollback()
+ log.Printf("migration: normalize exercise taxonomy: %v", err)
+ return
+ }
+ if n, err := res.RowsAffected(); err == nil {
+ changed += n
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ log.Printf("migration: normalize exercise taxonomy: commit: %v", err)
+ return
+ }
+ setMigrationFlag("normalize_exercise_taxonomy")
+ if changed > 0 {
+ log.Printf("migration: normalized %d exercise taxonomy values to oedb slugs", changed)
+ }
}
// backfillLocalDays fills the stored day/offset for rows written before those
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
index 08410ad..b9cb4e0 100644
--- a/backend/db/migrations_test.go
+++ b/backend/db/migrations_test.go
@@ -554,3 +554,78 @@ func TestBackfillLocalDays_oneUnreadableRowDoesNotBlockTheRest(t *testing.T) {
t.Error("completion flag never set — every boot will retry this forever")
}
}
+
+// An existing install carries the taxonomy exactly as free-exercise-db spelled it
+// ("body only", "lower back"). open-exercise-db serves the same vocabulary as
+// slugs. Left unconverted the table holds both spellings of one concept, and
+// every equipment or muscle filter silently returns half its rows.
+func TestNormalizeExerciseTaxonomy_RewritesLegacySpellings(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ rows := []struct{ name, muscle, category, equipment, secondary string }{
+ {"Push Up", "chest", "strength", "body only", `["triceps","lower back"]`},
+ {"Deadlift", "lower back", "strength", "barbell", `["middle back","glutes"]`},
+ {"Snatch", "shoulders", "olympic weightlifting", "", `[]`},
+ {"Curl", "biceps", "strength", "e-z curl bar", `[]`},
+ {"Ball Crunch", "abdominals", "strength", "exercise ball", `[]`},
+ {"Roll Out", "abdominals", "strength", "foam roll", `[]`},
+ {"Med Ball Throw", "chest", "plyometrics", "medicine ball", `[]`},
+ }
+ for _, r := range rows {
+ if _, err := DB.Exec(`INSERT INTO exercises (name, muscle_group, category, equipment, secondary_muscles)
+ VALUES (?, ?, ?, ?, ?)`, r.name, r.muscle, r.category, r.equipment, r.secondary); err != nil {
+ t.Fatalf("seed %s: %v", r.name, err)
+ }
+ }
+
+ alterMigrations()
+
+ want := map[string][3]string{ // name -> {muscle_group, category, equipment}
+ "Push Up": {"chest", "strength", "body-only"},
+ "Deadlift": {"lower-back", "strength", "barbell"},
+ "Snatch": {"shoulders", "olympic-weightlifting", "none"},
+ "Curl": {"biceps", "strength", "e-z-curl-bar"},
+ "Ball Crunch": {"abdominals", "strength", "exercise-ball"},
+ "Roll Out": {"abdominals", "strength", "foam-roll"},
+ "Med Ball Throw": {"chest", "plyometrics", "medicine-ball"},
+ }
+ for name, w := range want {
+ var muscle, category, equipment string
+ if err := DB.QueryRow(`SELECT muscle_group, category, equipment FROM exercises WHERE name = ?`, name).
+ Scan(&muscle, &category, &equipment); err != nil {
+ t.Fatalf("read %s: %v", name, err)
+ }
+ if muscle != w[0] || category != w[1] || equipment != w[2] {
+ t.Errorf("%s = %q/%q/%q, want %q/%q/%q", name, muscle, category, equipment, w[0], w[1], w[2])
+ }
+ }
+
+ var secondary string
+ DB.QueryRow(`SELECT secondary_muscles FROM exercises WHERE name = 'Deadlift'`).Scan(&secondary)
+ if secondary != `["middle-back","glutes"]` {
+ t.Errorf("secondary_muscles = %s, want the slug form", secondary)
+ }
+}
+
+// The rewrite runs once and is not re-applied. It is guarded by a migration flag
+// rather than being idempotent by construction, because a second pass over a
+// table that has since gained user-contributed values could rewrite something it
+// should not.
+func TestNormalizeExerciseTaxonomy_RunsOnce(t *testing.T) {
+ setupMigrationTestDB(t)
+ if _, err := DB.Exec(`INSERT INTO exercises (name, equipment) VALUES ('Push Up', 'body only')`); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+
+ alterMigrations()
+ if _, err := DB.Exec(`UPDATE exercises SET equipment = 'body only' WHERE name = 'Push Up'`); err != nil {
+ t.Fatalf("reintroduce: %v", err)
+ }
+ alterMigrations()
+
+ var equipment string
+ DB.QueryRow(`SELECT equipment FROM exercises WHERE name = 'Push Up'`).Scan(&equipment)
+ if equipment != "body only" {
+ t.Errorf("equipment = %q, want the migration to have skipped its second run", equipment)
+ }
+}
diff --git a/backend/main.go b/backend/main.go
index 25ba91d..31a45d3 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -11,6 +11,7 @@ import (
"github.com/Cawlumm/lyftr-backend/config"
"github.com/Cawlumm/lyftr-backend/controllers"
"github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/oedb"
"github.com/Cawlumm/lyftr-backend/routes"
"github.com/Cawlumm/lyftr-backend/seed"
"github.com/Cawlumm/lyftr-backend/stores"
@@ -92,15 +93,20 @@ func main() {
warnIfUnclaimed()
// The demo account's credentials are published, so it is not something a self-hosted
// instance should get by default — only the public demo and local development ask for
- // it. The exercise library is not demo data and always seeds.
if config.C.DemoMode {
seed.DemoUser(db.DB)
} else {
seed.WarnLeftoverDemoUser(db.DB)
}
- seed.Exercises(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.
+ s := stores.New(db.DB)
+ s.Exercise.UseCatalog(oedb.New(config.C.OEDBBaseURL, config.Version()))
+
if config.C.DemoMode {
- go seed.DemoData(db.DB)
+ go seed.DemoData(db.DB, s.Exercise)
}
if config.C.Env == "production" {
@@ -108,7 +114,6 @@ func main() {
}
r := gin.Default()
- s := stores.New(db.DB)
h := controllers.NewHandler(s)
routes.Setup(r, h)
diff --git a/backend/oedb/client.go b/backend/oedb/client.go
new file mode 100644
index 0000000..93ba61b
--- /dev/null
+++ b/backend/oedb/client.go
@@ -0,0 +1,448 @@
+// Package oedb is Lyftr's client for open-exercise-db, the upstream community
+// exercise catalog.
+//
+// Lyftr queries oedb rather than mirroring it. The local exercises table still
+// exists, but as a snapshot of rows a user has actually seen — see
+// stores.ExerciseStore.Materialize — not as a copy of the catalog kept in step by
+// a periodic sync. Search, filtering and ordering are answered upstream, so the
+// data Lyftr shows improves when oedb improves, without a redeploy.
+//
+// The cache here is what makes that affordable. oedb serves list and detail reads
+// with `Cache-Control: public, max-age=300, stale-while-revalidate=86400` plus an
+// ETag, so one popular query costs oedb roughly twelve requests an hour no matter
+// how many Lyftr users run it. Caching in the backend rather than the browser is
+// deliberate: it is one cache shared by every user of an instance, and it keeps
+// Lyftr's own API contract unchanged.
+package oedb
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// DefaultBaseURL is the hosted instance. Override with OEDB_BASE_URL to point a
+// self-hosted Lyftr at a self-hosted catalog.
+const DefaultBaseURL = "https://oedb-api-o4dqddih5q-uk.a.run.app"
+
+// maxPerPage is oedb's cap; asking for more is a 422, not a clamp.
+const maxPerPage = 100
+
+// Client is a cache-aware reader for the oedb HTTP API. Safe for concurrent use.
+type Client struct {
+ baseURL string
+ userAgent string
+ http *http.Client
+
+ mu sync.Mutex
+ cache map[string]*entry
+}
+
+// entry is one cached response body plus the metadata needed to revalidate it.
+type entry struct {
+ body []byte
+ etag string
+ freshFor time.Time // max-age boundary
+ staleFor time.Time // stale-while-revalidate boundary
+ refreshing bool // a background revalidation is already in flight
+}
+
+// New builds a client. An empty baseURL selects DefaultBaseURL.
+//
+// The User-Agent is not cosmetic: oedb tiers rate limits on caller identity, and
+// a request with a generic or absent User-Agent is served 5 requests/minute
+// instead of 60. Identifying properly is the difference between a working
+// exercise picker and a 429.
+func New(baseURL, version string) *Client {
+ if baseURL == "" {
+ baseURL = DefaultBaseURL
+ }
+ if version == "" {
+ version = "dev"
+ }
+ return &Client{
+ baseURL: strings.TrimRight(baseURL, "/"),
+ userAgent: fmt.Sprintf("lyftr/%s (+https://github.com/Cawlumm/lyftr)", version),
+ // Generous, because this bounds the slowest legitimate call — the ~300 KB
+ // bulk export, measured at ~14s against the hosted instance. Interactive
+ // reads must not inherit that patience, so they carry their own deadline:
+ // see the context each caller passes in.
+ http: &http.Client{Timeout: 90 * time.Second},
+ cache: map[string]*entry{},
+ }
+}
+
+// ListParams are the filters Lyftr forwards upstream. Zero values are omitted,
+// so the zero ListParams asks for the unfiltered first page.
+type ListParams struct {
+ Query string
+ MuscleGroup string
+ Category string
+ Equipment string
+ Page int
+ PerPage int
+}
+
+func (p ListParams) query() url.Values {
+ v := url.Values{}
+ set := func(k, s string) {
+ if s = strings.TrimSpace(s); s != "" {
+ v.Set(k, s)
+ }
+ }
+ set("q", p.Query)
+ set("muscle_group", p.MuscleGroup)
+ set("category", p.Category)
+ set("equipment", p.Equipment)
+ if p.Page > 1 {
+ v.Set("page", strconv.Itoa(p.Page))
+ }
+ per := p.PerPage
+ if per <= 0 {
+ per = maxPerPage
+ }
+ if per > maxPerPage {
+ per = maxPerPage
+ }
+ v.Set("per_page", strconv.Itoa(per))
+ return v
+}
+
+// Image is one rendition of an exercise image. Lyftr uses the first image's URL
+// and ignores variants for now.
+type Image struct {
+ ID string `json:"id"`
+ URL string `json:"url"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+ ContentType string `json:"content_type"`
+ License string `json:"license"`
+}
+
+// Translation is the locale-resolved text for an exercise. oedb keeps name and
+// instructions here rather than on the exercise because they vary by locale
+// while the taxonomy does not.
+type Translation struct {
+ Name string `json:"name"`
+ Aliases []string `json:"aliases"`
+ Instructions []string `json:"instructions"`
+ Locale string `json:"name_locale"`
+}
+
+// Exercise is one oedb catalog row, trimmed to the fields Lyftr reads.
+type Exercise struct {
+ ID string `json:"id"`
+ Slug string `json:"slug"`
+ SourceID string `json:"source_id"`
+ MuscleGroup string `json:"muscle_group"`
+ SecondaryMuscles []string `json:"secondary_muscles"`
+ Category string `json:"category"`
+ Equipment string `json:"equipment"`
+ Mechanic string `json:"mechanic"`
+ Force string `json:"force"`
+ Level string `json:"level"`
+ Images []Image `json:"images"`
+ Translation Translation `json:"translation"`
+}
+
+// Name is the display name, which lives on the translation.
+func (e Exercise) Name() string { return e.Translation.Name }
+
+// Description renders the instruction steps as the single numbered block
+// Lyftr's description column holds.
+//
+// The numbering is not decoration: every exercise seeded before oedb was stored
+// in exactly this shape by seed.buildInstructions, and the UI renders the column
+// as preformatted text. Joining with blank lines instead would make the same
+// exercise look different depending on whether its row predates the migration.
+func (e Exercise) Description() string {
+ var b strings.Builder
+ for i, step := range e.Translation.Instructions {
+ if i > 0 {
+ b.WriteByte('\n')
+ }
+ fmt.Fprintf(&b, "%d. %s", i+1, step)
+ }
+ return b.String()
+}
+
+// ImageURL returns an absolute URL for the first image, or "" when there is
+// none. oedb serves image URLs relative to its own origin, so they are unusable
+// verbatim by a client that is not oedb.
+func (e Exercise) ImageURL(baseURL string) string {
+ if len(e.Images) == 0 {
+ return ""
+ }
+ u := e.Images[0].URL
+ if u == "" || strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://") {
+ return u
+ }
+ return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(u, "/")
+}
+
+// BaseURL exposes the configured origin so callers can absolutize image URLs.
+func (c *Client) BaseURL() string { return c.baseURL }
+
+// ListResult is one page of catalog results.
+type ListResult struct {
+ Exercises []Exercise `json:"exercises"`
+ Total int `json:"total"`
+ Page int `json:"page"`
+ PerPage int `json:"per_page"`
+}
+
+// List queries the catalog.
+func (c *Client) List(ctx context.Context, p ListParams) (ListResult, error) {
+ var out ListResult
+ err := c.getJSON(ctx, "/api/v1/exercises?"+p.query().Encode(), &out)
+ return out, err
+}
+
+// ErrNotFound is returned for a 404 so callers can tell "no such exercise" from
+// "the catalog is unreachable" — the first is a client error, the second is a
+// reason to fall back to the local snapshot.
+var ErrNotFound = errors.New("oedb: exercise not found")
+
+// Get fetches one exercise by its oedb UUID.
+func (c *Client) Get(ctx context.Context, id string) (Exercise, error) {
+ var out Exercise
+ err := c.getJSON(ctx, "/api/v1/exercises/"+url.PathEscape(id), &out)
+ return out, err
+}
+
+// getJSON performs a cache-aware GET and decodes the body.
+func (c *Client) getJSON(ctx context.Context, path string, dst any) error {
+ body, err := c.get(ctx, path)
+ if err != nil {
+ return err
+ }
+ if err := json.Unmarshal(body, dst); err != nil {
+ return fmt.Errorf("oedb: decode %s: %w", path, err)
+ }
+ return nil
+}
+
+// get returns a response body, from cache when it is still fresh.
+//
+// The three states mirror what oedb's Cache-Control describes:
+//
+// - fresh (within max-age): serve from memory, no request at all.
+// - stale but within stale-while-revalidate: serve the stale body immediately
+// and revalidate in the background. This is the state a moderately-used query
+// spends most of its life in, and serving through it is what keeps a user's
+// search off the critical path of an upstream round trip.
+// - beyond both: fetch synchronously.
+func (c *Client) get(ctx context.Context, path string) ([]byte, error) {
+ now := time.Now()
+
+ c.mu.Lock()
+ e, ok := c.cache[path]
+ if ok && now.Before(e.freshFor) {
+ body := e.body
+ c.mu.Unlock()
+ return body, nil
+ }
+ if ok && now.Before(e.staleFor) && len(e.body) > 0 {
+ body := e.body
+ if !e.refreshing {
+ e.refreshing = true
+ go c.revalidate(path)
+ }
+ c.mu.Unlock()
+ return body, nil
+ }
+ etag := ""
+ if ok {
+ etag = e.etag
+ }
+ c.mu.Unlock()
+
+ return c.fetch(ctx, path, etag)
+}
+
+// revalidate refreshes a stale entry off the request path. It deliberately uses
+// its own timeout-bounded context rather than the caller's: the caller has
+// already been served, and cancelling the refresh when that request finishes
+// would mean the entry never refreshes under steady traffic.
+func (c *Client) revalidate(path string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ c.mu.Lock()
+ etag := ""
+ if e, ok := c.cache[path]; ok {
+ etag = e.etag
+ }
+ c.mu.Unlock()
+
+ _, _ = c.fetch(ctx, path, etag)
+
+ c.mu.Lock()
+ if e, ok := c.cache[path]; ok {
+ e.refreshing = false
+ }
+ c.mu.Unlock()
+}
+
+// maxRateLimitRetries bounds the 429 backoff. Two retries covers a burst
+// overrun, which refills in seconds; more than that means the per-minute budget
+// is genuinely gone and waiting would just move the failure later.
+const maxRateLimitRetries = 2
+
+func (c *Client) fetch(ctx context.Context, path, etag string) ([]byte, error) {
+ return c.fetchAttempt(ctx, path, etag, 0)
+}
+
+// retryAfter parses the delay-seconds form of Retry-After, which is what oedb
+// sends. The HTTP-date form is rejected rather than guessed at: a misparsed date
+// becomes an unbounded sleep, and reporting the 429 is the safer failure.
+func retryAfter(h string) (time.Duration, bool) {
+ secs, err := strconv.Atoi(strings.TrimSpace(h))
+ if err != nil || secs < 0 || secs > 60 {
+ return 0, false
+ }
+ // A zero-second Retry-After still needs a beat, or the retry races the refill.
+ return time.Duration(secs)*time.Second + 250*time.Millisecond, true
+}
+
+func (c *Client) fetchAttempt(ctx context.Context, path, etag string, attempt int) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
+ if err != nil {
+ return nil, fmt.Errorf("oedb: build request: %w", err)
+ }
+ req.Header.Set("User-Agent", c.userAgent)
+ req.Header.Set("Accept", "application/json")
+ // Deliberately NOT setting Accept-Encoding. net/http adds it and transparently
+ // decompresses the response only when it owns the header; setting it by hand
+ // opts out of that and hands back raw gzip bytes, which fail to decode with
+ // "invalid character '\x1f'". Compression still happens — Go just does it.
+ if etag != "" {
+ req.Header.Set("If-None-Match", etag)
+ }
+
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("oedb: %s: %w", path, err)
+ }
+ defer resp.Body.Close()
+
+ // oedb rate-limits per tier and says when to come back. Honour that rather
+ // than treating 429 as a failure: its search tier allows 60 requests a minute
+ // but a far smaller instantaneous burst, so a client issuing a short run of
+ // legitimate queries trips it while nowhere near the per-minute budget. A
+ // caller that retries on the server's own schedule gets its data; one that
+ // gives up degrades for no reason, and one that retries immediately makes it
+ // worse for everyone.
+ if resp.StatusCode == http.StatusTooManyRequests {
+ wait, ok := retryAfter(resp.Header.Get("Retry-After"))
+ if !ok || attempt >= maxRateLimitRetries {
+ snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
+ return nil, fmt.Errorf("oedb: %s: http 429: %s", path, strings.TrimSpace(string(snippet)))
+ }
+ select {
+ case <-ctx.Done():
+ return nil, fmt.Errorf("oedb: %s: %w", path, ctx.Err())
+ case <-time.After(wait):
+ }
+ return c.fetchAttempt(ctx, path, etag, attempt+1)
+ }
+
+ // 304 means the cached body is still correct: keep it and only push the
+ // freshness window forward. This is the cheap path, and the reason ETags are
+ // worth sending at all — a revalidation that changes nothing costs headers.
+ if resp.StatusCode == http.StatusNotModified {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if e, ok := c.cache[path]; ok {
+ fresh, stale := cacheWindow(resp.Header.Get("Cache-Control"))
+ now := time.Now()
+ e.freshFor = now.Add(fresh)
+ e.staleFor = now.Add(fresh + stale)
+ return e.body, nil
+ }
+ return nil, fmt.Errorf("oedb: %s: 304 with no cached body", path)
+ }
+
+ if resp.StatusCode == http.StatusNotFound {
+ return nil, ErrNotFound
+ }
+ if resp.StatusCode != http.StatusOK {
+ // Cap the body read: an error page is not a reason to buffer whatever the
+ // far side chose to send.
+ snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
+ return nil, fmt.Errorf("oedb: %s: http %d: %s", path, resp.StatusCode, strings.TrimSpace(string(snippet)))
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("oedb: %s: read body: %w", path, err)
+ }
+
+ fresh, stale := cacheWindow(resp.Header.Get("Cache-Control"))
+ now := time.Now()
+ c.mu.Lock()
+ c.cache[path] = &entry{
+ body: body,
+ etag: resp.Header.Get("ETag"),
+ freshFor: now.Add(fresh),
+ staleFor: now.Add(fresh + stale),
+ }
+ c.mu.Unlock()
+
+ return body, nil
+}
+
+// cacheWindow reads max-age and stale-while-revalidate out of a Cache-Control
+// header, falling back to a conservative 60s/0 when the header is absent or
+// unparseable. The fallback is short rather than long: guessing a long freshness
+// for a response that never claimed one would serve stale data on a header
+// change we did not notice.
+func cacheWindow(header string) (fresh, stale time.Duration) {
+ fresh, stale = 60*time.Second, 0
+
+ for _, part := range strings.Split(header, ",") {
+ part = strings.TrimSpace(part)
+ k, v, ok := strings.Cut(part, "=")
+ if !ok {
+ continue
+ }
+ secs, err := strconv.Atoi(strings.TrimSpace(v))
+ if err != nil || secs < 0 {
+ continue
+ }
+ switch strings.ToLower(strings.TrimSpace(k)) {
+ case "max-age":
+ fresh = time.Duration(secs) * time.Second
+ case "stale-while-revalidate":
+ stale = time.Duration(secs) * time.Second
+ }
+ }
+ return fresh, stale
+}
+
+// Export fetches the entire published catalog in one request.
+//
+// oedb caps per_page at 100, so assembling all ~873 exercises through List would
+// take nine round trips. The export endpoint returns them in a single ~300 KB
+// response carrying the same row shape, and is cached upstream for 900s rather
+// than 300s. It is the right call for "give me everything" — which is exactly
+// what Lyftr's exercise picker asks for — and the wrong one for anything
+// filtered, where List returns far less data.
+func (c *Client) Export(ctx context.Context) ([]Exercise, error) {
+ var out struct {
+ Exercises []Exercise `json:"exercises"`
+ Total int `json:"total"`
+ }
+ if err := c.getJSON(ctx, "/api/v1/exercises/export", &out); err != nil {
+ return nil, err
+ }
+ return out.Exercises, nil
+}
diff --git a/backend/oedb/client_test.go b/backend/oedb/client_test.go
new file mode 100644
index 0000000..eaef536
--- /dev/null
+++ b/backend/oedb/client_test.go
@@ -0,0 +1,347 @@
+package oedb
+
+import (
+ "compress/gzip"
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// listBody is a minimal but structurally real oedb list response.
+func listBody(name string) string {
+ return fmt.Sprintf(`{"exercises":[{"id":"uuid-1","slug":"bench-press","muscle_group":"chest",
+ "secondary_muscles":["triceps"],"category":"strength","equipment":"barbell",
+ "images":[{"id":"img-1","url":"/api/v1/images/img-1"}],
+ "translation":{"name":%q,"instructions":["Step one.","Step two."]}}],
+ "total":1,"page":1,"per_page":100}`, name)
+}
+
+// A response still inside max-age must be served from memory without touching
+// the network. This is the whole economic argument for querying oedb live rather
+// than mirroring it: a popular search costs one upstream request per max-age
+// window no matter how many users run it.
+func TestGet_FreshResponseIsServedFromCache(t *testing.T) {
+ var hits int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&hits, 1)
+ w.Header().Set("Cache-Control", "public, max-age=300, stale-while-revalidate=86400")
+ w.Header().Set("ETag", `"v1"`)
+ fmt.Fprint(w, listBody("Bench Press"))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL, "test")
+ for i := 0; i < 3; i++ {
+ if _, err := c.List(context.Background(), ListParams{}); err != nil {
+ t.Fatalf("list %d: %v", i, err)
+ }
+ }
+ if got := atomic.LoadInt32(&hits); got != 1 {
+ t.Errorf("upstream hits = %d, want 1 (cache did not hold)", got)
+ }
+}
+
+// A revalidation that returns 304 carries no body, so the cached one must be
+// reused. Getting this wrong is not a performance bug — it returns an empty
+// exercise list to the caller.
+func TestGet_304ReusesCachedBody(t *testing.T) {
+ var hits int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&hits, 1)
+ if r.Header.Get("If-None-Match") == `"v1"` {
+ w.Header().Set("Cache-Control", "public, max-age=300")
+ w.WriteHeader(http.StatusNotModified)
+ return
+ }
+ w.Header().Set("Cache-Control", "public, max-age=0")
+ w.Header().Set("ETag", `"v1"`)
+ fmt.Fprint(w, listBody("Bench Press"))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL, "test")
+ if _, err := c.List(context.Background(), ListParams{}); err != nil {
+ t.Fatalf("first list: %v", err)
+ }
+ // max-age=0 leaves the entry immediately stale with no stale-while-revalidate
+ // window, so the second call revalidates synchronously and gets a 304.
+ res, err := c.List(context.Background(), ListParams{})
+ if err != nil {
+ t.Fatalf("second list: %v", err)
+ }
+ if len(res.Exercises) != 1 {
+ t.Fatalf("got %d exercises after 304, want 1 — the cached body was lost", len(res.Exercises))
+ }
+ if got := atomic.LoadInt32(&hits); got != 2 {
+ t.Errorf("upstream hits = %d, want 2", got)
+ }
+}
+
+// Past max-age but inside stale-while-revalidate, the caller must be served
+// immediately from the stale copy rather than waiting on the network.
+func TestGet_ServesStaleWhileRevalidating(t *testing.T) {
+ var hits int32
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if atomic.AddInt32(&hits, 1) > 1 {
+ <-release // hold the revalidation open so a slow refresh is unmistakable
+ }
+ w.Header().Set("Cache-Control", "public, max-age=0, stale-while-revalidate=86400")
+ w.Header().Set("ETag", `"v1"`)
+ fmt.Fprint(w, listBody("Bench Press"))
+ }))
+ defer srv.Close()
+ defer close(release)
+
+ c := New(srv.URL, "test")
+ if _, err := c.List(context.Background(), ListParams{}); err != nil {
+ t.Fatalf("first list: %v", err)
+ }
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ res, err := c.List(context.Background(), ListParams{})
+ if err != nil {
+ t.Errorf("stale list: %v", err)
+ return
+ }
+ if len(res.Exercises) != 1 {
+ t.Errorf("got %d exercises, want the stale copy", len(res.Exercises))
+ }
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("stale read blocked on the background revalidation")
+ }
+}
+
+// oedb tiers rate limits on caller identity: an unidentified client gets 5
+// requests/minute instead of 60. A request that forgets to say who it is works
+// in testing and 429s in production.
+func TestFetch_SendsIdentifyingUserAgent(t *testing.T) {
+ got := make(chan string, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case got <- r.Header.Get("User-Agent"):
+ default:
+ }
+ fmt.Fprint(w, listBody("Bench Press"))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL, "1.2.3")
+ if _, err := c.List(context.Background(), ListParams{}); err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ ua := <-got
+ if !strings.HasPrefix(ua, "lyftr/1.2.3 ") || !strings.Contains(ua, "github.com/Cawlumm/lyftr") {
+ t.Errorf("User-Agent = %q, want an identifying lyftr agent with a contact URL", ua)
+ }
+}
+
+// A 404 must be distinguishable from an outage: the first is a client error, the
+// second is the signal to fall back to the local snapshot.
+func TestGet_404IsErrNotFound(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNotFound)
+ }))
+ defer srv.Close()
+
+ _, err := New(srv.URL, "test").Get(context.Background(), "missing")
+ if !errors.Is(err, ErrNotFound) {
+ t.Errorf("err = %v, want ErrNotFound", err)
+ }
+}
+
+// per_page above 100 is a 422 from oedb, not a clamp, so the client must clamp
+// before asking.
+func TestListParams_ClampsPerPage(t *testing.T) {
+ for _, tc := range []struct{ in, want string }{
+ {"1000", "100"},
+ {"0", "100"},
+ } {
+ v := ListParams{PerPage: atoiOrZero(tc.in)}.query()
+ if got := v.Get("per_page"); got != tc.want {
+ t.Errorf("per_page for %s = %s, want %s", tc.in, got, tc.want)
+ }
+ }
+}
+
+func atoiOrZero(s string) int {
+ n := 0
+ for _, r := range s {
+ if r < '0' || r > '9' {
+ return 0
+ }
+ n = n*10 + int(r-'0')
+ }
+ return n
+}
+
+func TestCacheWindow(t *testing.T) {
+ tests := []struct {
+ header string
+ fresh, stal time.Duration
+ }{
+ {"public, max-age=300, stale-while-revalidate=86400", 300 * time.Second, 86400 * time.Second},
+ {"public, max-age=900", 900 * time.Second, 0},
+ {"", 60 * time.Second, 0},
+ {"no-cache", 60 * time.Second, 0},
+ {"max-age=abc", 60 * time.Second, 0},
+ }
+ for _, tc := range tests {
+ fresh, stale := cacheWindow(tc.header)
+ if fresh != tc.fresh || stale != tc.stal {
+ t.Errorf("cacheWindow(%q) = %v/%v, want %v/%v", tc.header, fresh, stale, tc.fresh, tc.stal)
+ }
+ }
+}
+
+func TestExercise_DescriptionAndImageURL(t *testing.T) {
+ e := Exercise{
+ Images: []Image{{URL: "/api/v1/images/img-1"}},
+ Translation: Translation{Instructions: []string{"One.", "Two."}},
+ }
+ if got := e.Description(); got != "1. One.\n2. Two." {
+ t.Errorf("Description() = %q", got)
+ }
+ if got := e.ImageURL("https://oedb.test/"); got != "https://oedb.test/api/v1/images/img-1" {
+ t.Errorf("ImageURL() = %q", got)
+ }
+ if got := (Exercise{}).ImageURL("https://oedb.test"); got != "" {
+ t.Errorf("ImageURL() with no images = %q, want empty", got)
+ }
+ absolute := Exercise{Images: []Image{{URL: "https://cdn.test/x.jpg"}}}
+ if got := absolute.ImageURL("https://oedb.test"); got != "https://cdn.test/x.jpg" {
+ t.Errorf("ImageURL() rewrote an already-absolute URL: %q", got)
+ }
+}
+
+// oedb compresses its responses, and the export endpoint in particular is ~300 KB
+// uncompressed. net/http negotiates and decompresses gzip transparently only
+// while it owns the Accept-Encoding header — setting that header by hand opts out
+// of the decompression too, and the body arrives as raw gzip that fails to decode
+// with "invalid character '\x1f'". Unit tests over an uncompressed test server
+// cannot see that, so this one compresses.
+func TestFetch_TransparentlyDecompressesGzip(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
+ t.Errorf("Accept-Encoding = %q, want gzip offered", r.Header.Get("Accept-Encoding"))
+ }
+ w.Header().Set("Content-Encoding", "gzip")
+ w.Header().Set("Content-Type", "application/json")
+ zw := gzip.NewWriter(w)
+ defer zw.Close()
+ fmt.Fprint(zw, listBody("Bench Press"))
+ }))
+ defer srv.Close()
+
+ res, err := New(srv.URL, "test").List(context.Background(), ListParams{})
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if len(res.Exercises) != 1 || res.Exercises[0].Name() != "Bench Press" {
+ t.Fatalf("got %+v, want one decoded exercise", res.Exercises)
+ }
+}
+
+// Page must be sent for anything past the first, and omitted for it — oedb
+// defaults to page 1, and sending page=1 explicitly is noise in the cache key.
+func TestListParams_PagingAndFilters(t *testing.T) {
+ v := ListParams{Query: " squat ", Equipment: "dumbbell", Page: 3, PerPage: 25}.query()
+ if got := v.Get("q"); got != "squat" {
+ t.Errorf("q = %q, want trimmed", got)
+ }
+ if got := v.Get("equipment"); got != "dumbbell" {
+ t.Errorf("equipment = %q", got)
+ }
+ if got := v.Get("page"); got != "3" {
+ t.Errorf("page = %q, want 3", got)
+ }
+ if got := v.Get("per_page"); got != "25" {
+ t.Errorf("per_page = %q, want 25", got)
+ }
+ if got := (ListParams{Page: 1}).query().Get("page"); got != "" {
+ t.Errorf("page for page 1 = %q, want omitted", got)
+ }
+ if got := (ListParams{}).query().Get("muscle_group"); got != "" {
+ t.Errorf("empty filter was sent: %q", got)
+ }
+}
+
+// oedb's search tier permits 60 requests a minute but a much smaller burst, so a
+// client issuing a short run of legitimate queries trips 429 while well inside
+// its per-minute budget. Retrying on the server's own Retry-After turns that into
+// a pause instead of a failure.
+func TestFetch_RetriesAfter429(t *testing.T) {
+ var hits int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if atomic.AddInt32(&hits, 1) == 1 {
+ w.Header().Set("Retry-After", "0")
+ w.WriteHeader(http.StatusTooManyRequests)
+ fmt.Fprint(w, `{"detail":"rate limit exceeded"}`)
+ return
+ }
+ fmt.Fprint(w, listBody("Bench Press"))
+ }))
+ defer srv.Close()
+
+ res, err := New(srv.URL, "test").List(context.Background(), ListParams{})
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if len(res.Exercises) != 1 {
+ t.Fatalf("got %d exercises, want 1", len(res.Exercises))
+ }
+ if got := atomic.LoadInt32(&hits); got != 2 {
+ t.Errorf("upstream hits = %d, want 2 (one 429 then one success)", got)
+ }
+}
+
+// A persistent 429 must surface rather than retry forever — at that point the
+// per-minute budget is genuinely spent and the caller should fall back.
+func TestFetch_GivesUpOnPersistent429(t *testing.T) {
+ var hits int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&hits, 1)
+ w.Header().Set("Retry-After", "0")
+ w.WriteHeader(http.StatusTooManyRequests)
+ }))
+ defer srv.Close()
+
+ _, err := New(srv.URL, "test").List(context.Background(), ListParams{})
+ if err == nil {
+ t.Fatal("want an error after exhausting retries")
+ }
+ if !strings.Contains(err.Error(), "429") {
+ t.Errorf("err = %v, want it to name the 429", err)
+ }
+ if got := atomic.LoadInt32(&hits); got != maxRateLimitRetries+1 {
+ t.Errorf("upstream hits = %d, want %d", got, maxRateLimitRetries+1)
+ }
+}
+
+func TestRetryAfter(t *testing.T) {
+ if _, ok := retryAfter("Wed, 21 Oct 2015 07:28:00 GMT"); ok {
+ t.Error("HTTP-date Retry-After was accepted; it must be rejected, not guessed")
+ }
+ if _, ok := retryAfter(""); ok {
+ t.Error("empty Retry-After was accepted")
+ }
+ if _, ok := retryAfter("600"); ok {
+ t.Error("an implausibly long Retry-After was accepted")
+ }
+ d, ok := retryAfter("2")
+ if !ok || d < 2*time.Second {
+ t.Errorf("retryAfter(\"2\") = %v, %v", d, ok)
+ }
+}
diff --git a/backend/routes/routes.go b/backend/routes/routes.go
index 06e1e78..c9b7bad 100644
--- a/backend/routes/routes.go
+++ b/backend/routes/routes.go
@@ -91,9 +91,9 @@ func Setup(r *gin.Engine, h *controllers.Handler) {
protected.POST("programs/:id/suggestions/resolve", h.ResolveSuggestions)
// Admin
- protected.POST("admin/sync-exercises", h.SyncExercises)
- protected.GET("admin/seed-status", h.ExerciseSeedStatus)
- protected.POST("admin/reset-exercises", h.ResetExercises)
+ 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/seed/demo_data.go b/backend/seed/demo_data.go
index fccd1f2..4d77180 100644
--- a/backend/seed/demo_data.go
+++ b/backend/seed/demo_data.go
@@ -1,10 +1,12 @@
package seed
import (
+ "context"
"database/sql"
"fmt"
"log"
"math/rand"
+ "strings"
"time"
)
@@ -80,21 +82,23 @@ var workoutNames = []string{"Push A", "Pull A", "Legs A", "Push B", "Pull B", "L
var workoutDurations = []int{3720, 3480, 4200, 3660, 3540, 4320}
var workoutTemplates = [][]demoEx{pushA, pullA, legsA, pushB, pullB, legsB}
-func DemoData(db *sql.DB) {
- // Wait for exercises to be seeded (up to 90s)
- var exCount int
- for i := 0; i < 18; i++ {
- db.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&exCount)
- if exCount >= 100 {
- break
- }
- log.Printf("seed: demo data waiting for exercises... (%d/18)", i+1)
- time.Sleep(5 * time.Second)
- }
- if exCount < 100 {
- log.Println("seed: exercises not ready, skipping demo data")
+// CatalogPrimer materializes the catalog rows matching a search term, so a caller
+// that needs particular exercises to exist locally can ask for exactly those.
+//
+// Demo data is the only caller. It exists because Lyftr no longer seeds an
+// exercise library: the demo account's routine references about thirty specific
+// exercises, and this pulls those thirty rather than importing a catalog nothing
+// else needs.
+type CatalogPrimer interface {
+ PrimeQuery(ctx context.Context, query string) error
+}
+
+func DemoData(db *sql.DB, primer CatalogPrimer) {
+ if primer == nil {
+ log.Println("seed: no exercise catalog configured, skipping demo data")
return
}
+ primeDemoExercises(db, primer)
var userID int64
if err := db.QueryRow(`SELECT id FROM users WHERE email = ?`, DemoEmail).Scan(&userID); err != nil {
@@ -353,3 +357,39 @@ func seedFoodLogs(db *sql.DB, userID int64) {
}
}
}
+
+// primeDemoExercises pulls the exercises the demo routine references.
+//
+// One catalog query per exercise slot, using the first LIKE pattern with its
+// wildcards stripped — the patterns were written as fallbacks for a local LIKE
+// search, and the first is always the most specific spelling. Failures are logged
+// and skipped rather than fatal: lookupExercise already tolerates a missing
+// exercise, and a demo account with 29 of 30 movements is far better than none.
+func primeDemoExercises(db *sql.DB, primer CatalogPrimer) {
+ seen := map[string]bool{}
+ for _, template := range workoutTemplates {
+ for _, ex := range template {
+ for _, pattern := range ex.patterns {
+ term := strings.TrimSpace(strings.ReplaceAll(pattern, "%", " "))
+ if term == "" || seen[term] {
+ continue
+ }
+ seen[term] = true
+
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ err := primer.PrimeQuery(ctx, term)
+ cancel()
+ if err != nil {
+ log.Printf("seed: demo catalog prime %q: %v", term, err)
+ continue
+ }
+ // The first pattern that resolves is the one lookupExercise will
+ // pick, so there is no reason to fetch its fallbacks too.
+ if _, ok := lookupExercise(db, ex.patterns); ok {
+ break
+ }
+ }
+ }
+ }
+ log.Printf("seed: primed demo exercises from open-exercise-db (%d queries)", len(seen))
+}
diff --git a/backend/seed/exercises.go b/backend/seed/exercises.go
deleted file mode 100644
index e088de5..0000000
--- a/backend/seed/exercises.go
+++ /dev/null
@@ -1,208 +0,0 @@
-package seed
-
-import (
- "database/sql"
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "strings"
- "sync/atomic"
- "time"
-)
-
-const (
- exerciseDBURL = "https://raw.githubusercontent.com/yuhonas/free-exercise-db/main/dist/exercises.json"
- imageBaseURL = "https://raw.githubusercontent.com/yuhonas/free-exercise-db/main/exercises"
-)
-
-var seeding atomic.Bool
-
-type freeExerciseItem struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Force string `json:"force"`
- Level string `json:"level"`
- Mechanic string `json:"mechanic"`
- Equipment string `json:"equipment"`
- PrimaryMuscles []string `json:"primaryMuscles"`
- SecondaryMuscles []string `json:"secondaryMuscles"`
- Instructions []string `json:"instructions"`
- Category string `json:"category"`
- Images []string `json:"images"`
-}
-
-// SeedStatus returns current exercise count and whether a seed is running.
-type SeedStatus struct {
- Count int `json:"count"`
- InProgress bool `json:"in_progress"`
-}
-
-func GetSeedStatus(db *sql.DB) SeedStatus {
- var count int
- db.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&count)
- return SeedStatus{Count: count, InProgress: seeding.Load()}
-}
-
-// Exercises seeds on first run if the table is empty (async to avoid blocking startup).
-func Exercises(db *sql.DB) {
- var count int
- db.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&count)
- if count > 0 {
- log.Printf("seed: %d exercises already in database, skipping sync", count)
- return
- }
-
- log.Println("seed: exercises table empty - syncing from free-exercise-db in background...")
- go fetchAndStoreAsync(db)
-}
-
-func fetchAndStoreAsync(db *sql.DB) {
- if err := fetchAndStore(db); err != nil {
- log.Printf("seed: exercise sync failed: %v", err)
- return
- }
-}
-
-// SyncExercises forces a full re-sync (used by admin endpoint).
-func SyncExercises(db *sql.DB) error {
- return fetchAndStore(db)
-}
-
-// WipeAndReseed deletes all exercises then re-fetches from source.
-func WipeAndReseed(db *sql.DB) error {
- // Claim the flag atomically BEFORE wiping: a Load-then-act check races —
- // two concurrent calls could both pass it, double-wipe, and seed twice.
- if !seeding.CompareAndSwap(false, true) {
- return fmt.Errorf("seed already in progress")
- }
- // Prune only unreferenced exercises: with foreign_keys enforced, deleting an
- // exercise that a saved workout/program references is (correctly) rejected.
- // Referenced rows are refreshed in place by the ON CONFLICT(name) upsert below.
- if _, err := 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)`); err != nil {
- seeding.Store(false)
- return fmt.Errorf("wipe failed: %w", err)
- }
- log.Println("seed: exercises wiped, starting re-seed...")
- go func() {
- defer seeding.Store(false)
- if err := fetchAndStoreLocked(db); err != nil {
- log.Printf("seed: exercise sync failed: %v", err)
- }
- }()
- return nil
-}
-
-// fetchAndStore claims the seeding flag for the duration of the sync.
-func fetchAndStore(db *sql.DB) error {
- if !seeding.CompareAndSwap(false, true) {
- return fmt.Errorf("seed already in progress")
- }
- defer seeding.Store(false)
- return fetchAndStoreLocked(db)
-}
-
-// fetchAndStoreLocked does the sync; the caller must hold the seeding flag.
-func fetchAndStoreLocked(db *sql.DB) error {
- items, err := fetchAll()
- if err != nil {
- return err
- }
-
- tx, err := db.Begin()
- if err != nil {
- return err
- }
-
- stmt, err := tx.Prepare(`
- INSERT INTO exercises (name, muscle_group, secondary_muscles, category, equipment, description, image_url)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(name) DO UPDATE SET
- muscle_group = excluded.muscle_group,
- secondary_muscles = excluded.secondary_muscles,
- category = excluded.category,
- equipment = excluded.equipment,
- description = excluded.description,
- image_url = excluded.image_url
- `)
- if err != nil {
- tx.Rollback()
- return err
- }
- defer stmt.Close()
-
- inserted := 0
- for _, e := range items {
- primaryMuscle := ""
- if len(e.PrimaryMuscles) > 0 {
- primaryMuscle = e.PrimaryMuscles[0]
- }
-
- secondaryJSON, _ := json.Marshal(e.SecondaryMuscles)
- if e.SecondaryMuscles == nil {
- secondaryJSON = []byte("[]")
- }
-
- instructions := buildInstructions(e.Instructions)
-
- imageURL := ""
- if len(e.Images) > 0 {
- imageURL = fmt.Sprintf("%s/%s/0.jpg", imageBaseURL, e.ID)
- }
-
- if _, err := stmt.Exec(
- e.Name,
- primaryMuscle,
- string(secondaryJSON),
- e.Category,
- e.Equipment,
- instructions,
- imageURL,
- ); err != nil {
- log.Printf("seed: skip %q: %v", e.Name, err)
- continue
- }
- inserted++
- }
-
- if err := tx.Commit(); err != nil {
- return err
- }
-
- log.Printf("seed: synced %d exercises", inserted)
- return nil
-}
-
-func fetchAll() ([]freeExerciseItem, error) {
- client := &http.Client{Timeout: 30 * time.Second}
- resp, err := client.Get(exerciseDBURL)
- if err != nil {
- return nil, fmt.Errorf("request failed: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK {
- body, _ := io.ReadAll(resp.Body)
- return nil, fmt.Errorf("fetch returned %d: %s", resp.StatusCode, string(body))
- }
-
- var items []freeExerciseItem
- if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
- return nil, fmt.Errorf("decode failed: %w", err)
- }
- return items, nil
-}
-
-func buildInstructions(steps []string) string {
- var b strings.Builder
- for i, step := range steps {
- if i > 0 {
- b.WriteByte('\n')
- }
- fmt.Fprintf(&b, "%d. %s", i+1, step)
- }
- return b.String()
-}
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.go
index e7a1be0..fcb7687 100644
--- a/backend/stores/exercise.go
+++ b/backend/stores/exercise.go
@@ -1,16 +1,23 @@
package stores
import (
+ "context"
"database/sql"
"encoding/json"
+ "errors"
+ "log"
+ "time"
"github.com/Cawlumm/lyftr-backend/models"
- "github.com/Cawlumm/lyftr-backend/seed"
+ "github.com/Cawlumm/lyftr-backend/oedb"
)
// ExerciseStore owns all SQL for the (global, read-only) exercises catalog, and
// wraps the seed subsystem for the admin sync/reset endpoints.
-type ExerciseStore struct{ db *sql.DB }
+type ExerciseStore struct {
+ db *sql.DB
+ catalog *oedb.Client
+}
func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db} }
@@ -18,6 +25,17 @@ func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db}
type ExerciseFilter struct {
Query, MuscleGroup, Category, Equipment string
Limit int
+ // Page is 1-based; zero and one both mean the first page. Paging is what lets
+ // the pickers stop downloading the catalog to filter it in the browser.
+ Page int
+}
+
+// offset converts the 1-based page into a SQL offset.
+func (f ExerciseFilter) offset() int {
+ if f.Page < 2 {
+ return 0
+ }
+ return (f.Page - 1) * f.Limit
}
const exerciseSelect = `SELECT id, name, muscle_group, secondary_muscles, category, equipment, description, image_url FROM exercises`
@@ -55,8 +73,8 @@ func (s *ExerciseStore) List(f ExerciseFilter) ([]models.Exercise, error) {
q += " AND equipment = ?"
args = append(args, f.Equipment)
}
- q += " ORDER BY name LIMIT ?"
- args = append(args, f.Limit)
+ q += " ORDER BY name LIMIT ? OFFSET ?"
+ args = append(args, f.Limit, f.offset())
rows, err := s.db.Query(q, args...)
if err != nil {
@@ -89,8 +107,299 @@ func (s *ExerciseStore) Count() (int, error) {
return n, err
}
-// Sync / SeedStatus / Reset delegate to the seed subsystem (which owns the
-// ExerciseDB fetch + the concurrency guard) so the controller stays SQL-free.
-func (s *ExerciseStore) Sync() error { return seed.SyncExercises(s.db) }
-func (s *ExerciseStore) SeedStatus() seed.SeedStatus { return seed.GetSeedStatus(s.db) }
-func (s *ExerciseStore) Reset() error { return seed.WipeAndReseed(s.db) }
+// Materialize records upstream catalog rows in the local exercises table and
+// returns them as Lyftr exercises, each carrying its local integer id.
+//
+// This is what lets Lyftr query oedb live while keeping referential integrity.
+// workout_exercises and program_exercises FK into exercises(id) with no cascade,
+// so an exercise a user can see in the picker must already exist locally by the
+// time they add it to a workout — otherwise the insert fails, or worse, succeeds
+// against an id that means something else. Materializing on read closes that gap
+// without a second round trip when the user picks.
+//
+// Rows are matched by oedb_id first and name second. The order matters: name is
+// the only key legacy rows have (they predate oedb entirely and were seeded from
+// free-exercise-db), while oedb_id is the only key that survives an upstream
+// rename. Trying oedb_id first means a renamed exercise updates the row it
+// already owns instead of inserting a duplicate under the new name.
+func (s *ExerciseStore) Materialize(items []oedb.Exercise, imageBase string) ([]models.Exercise, error) {
+ if len(items) == 0 {
+ return []models.Exercise{}, nil
+ }
+
+ tx, err := s.db.Begin()
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ byOedbID, err := tx.Prepare(`
+ UPDATE exercises SET
+ name = ?, muscle_group = ?, secondary_muscles = ?, category = ?,
+ equipment = ?, description = ?, image_url = ?, slug = ?
+ WHERE oedb_id = ?`)
+ if err != nil {
+ return nil, err
+ }
+ defer byOedbID.Close()
+
+ byName, err := tx.Prepare(`
+ INSERT INTO exercises (name, muscle_group, secondary_muscles, category, equipment, description, image_url, oedb_id, slug)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(name) DO UPDATE SET
+ muscle_group = excluded.muscle_group,
+ secondary_muscles = excluded.secondary_muscles,
+ category = excluded.category,
+ equipment = excluded.equipment,
+ description = excluded.description,
+ image_url = excluded.image_url,
+ oedb_id = excluded.oedb_id,
+ slug = excluded.slug`)
+ if err != nil {
+ return nil, err
+ }
+ defer byName.Close()
+
+ out := make([]models.Exercise, 0, len(items))
+ for _, it := range items {
+ secondary := it.SecondaryMuscles
+ if secondary == nil {
+ secondary = []string{}
+ }
+ secondaryJSON, err := json.Marshal(secondary)
+ if err != nil {
+ return nil, err
+ }
+
+ name := it.Name()
+ args := []any{
+ name, it.MuscleGroup, string(secondaryJSON), it.Category,
+ it.Equipment, it.Description(), it.ImageURL(imageBase), it.Slug,
+ }
+
+ res, err := byOedbID.Exec(append(append([]any{}, args...), it.ID)...)
+ if err != nil {
+ return nil, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return nil, err
+ }
+ if n == 0 {
+ insertArgs := []any{
+ name, it.MuscleGroup, string(secondaryJSON), it.Category,
+ it.Equipment, it.Description(), it.ImageURL(imageBase), it.ID, it.Slug,
+ }
+ if _, err := byName.Exec(insertArgs...); err != nil {
+ return nil, err
+ }
+ }
+
+ var e models.Exercise
+ row := tx.QueryRow(exerciseSelect+` WHERE oedb_id = ?`, it.ID)
+ if err := scanExercise(row, &e); err != nil {
+ return nil, err
+ }
+ out = append(out, e)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// UseCatalog points this store at an upstream open-exercise-db instance.
+//
+// Optional by design: with no catalog the store answers from the local table
+// alone, which is both the pre-oedb behaviour and the behaviour every test
+// exercises. Nothing in Lyftr requires the network to work.
+func (s *ExerciseStore) UseCatalog(c *oedb.Client) { s.catalog = c }
+
+// 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.
+//
+// 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
+// exercise this instance has shown before — which, for an established install,
+// is most of the ones its users search for.
+func (s *ExerciseStore) Search(ctx context.Context, f ExerciseFilter) ([]models.Exercise, error) {
+ if s.catalog == nil {
+ return s.List(f)
+ }
+
+ items, err := s.fetchCatalog(ctx, f)
+ if err != nil {
+ log.Printf("exercises: catalog query failed, serving local snapshot: %v", err)
+ return s.List(f)
+ }
+
+ out, err := s.Materialize(items, s.catalog.BaseURL())
+ if err != nil {
+ log.Printf("exercises: could not record catalog results, serving local snapshot: %v", err)
+ return s.List(f)
+ }
+ return out, nil
+}
+
+// fetchCatalog picks between the paged endpoint and the bulk export.
+//
+// The picker asks for the whole catalog (limit=1000) to build its client-side
+// cache, and oedb rejects per_page above 100 outright rather than clamping it.
+// Rather than issue nine paged requests for that case, an unfiltered bulk read
+// goes to the export endpoint, which returns everything at once. Anything
+// filtered stays on List, where the filter is what keeps the response small.
+func (s *ExerciseStore) fetchCatalog(ctx context.Context, f ExerciseFilter) ([]oedb.Exercise, error) {
+ filtered := f.Query != "" || f.MuscleGroup != "" || f.Category != "" || f.Equipment != ""
+ if !filtered && f.Limit > 100 && f.Page < 2 {
+ // The export is ~300 KB and measured around 14s against the hosted
+ // instance, so it gets a deadline sized for that. It is also cached
+ // upstream-style for 900s, so only the first caller after a cold start
+ // waits at all.
+ ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
+ defer cancel()
+ return s.catalog.Export(ctx)
+ }
+
+ // 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)
+ defer cancel()
+
+ // A filtered request for more than one page walks the pages. oedb caps
+ // per_page at 100, so without this a caller asking for 1000 dumbbell
+ // exercises would silently receive the first 100 and no indication that more
+ // existed — which is what the local table used to answer in full.
+ first := f.Page
+ if first < 1 {
+ first = 1
+ }
+ var out []oedb.Exercise
+ for page := first; ; page++ {
+ res, err := s.catalog.List(ctx, oedb.ListParams{
+ Query: f.Query,
+ MuscleGroup: f.MuscleGroup,
+ Category: f.Category,
+ Equipment: f.Equipment,
+ Page: page,
+ PerPage: f.Limit - len(out),
+ })
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, res.Exercises...)
+ if len(out) >= f.Limit || len(res.Exercises) == 0 {
+ return out, nil
+ }
+ // res.Total counts the whole result set, not the remainder, so it only
+ // terminates the walk once this page's offset has consumed it.
+ if (page-first+1)*len(res.Exercises) >= res.Total {
+ return out, nil
+ }
+ }
+}
+
+// with no upstream configured.
+var errNoCatalog = errors.New("no exercise catalog configured")
+
+// ErrNoCatalog is returned by the cache-management operations on an instance with
+// no upstream configured.
+var ErrNoCatalog = errors.New("no exercise catalog configured")
+
+// 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.
+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.
+func (s *ExerciseStore) RefreshCached(ctx context.Context) (int, error) {
+ if s.catalog == nil {
+ return 0, ErrNoCatalog
+ }
+
+ held, err := s.cachedOedbIDs()
+ if err != nil {
+ return 0, err
+ }
+ if len(held) == 0 {
+ return 0, nil
+ }
+
+ items, err := s.catalog.Export(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ keep := items[:0]
+ for _, it := range items {
+ if held[it.ID] {
+ keep = append(keep, it)
+ }
+ }
+
+ out, err := s.Materialize(keep, s.catalog.BaseURL())
+ if err != nil {
+ return 0, err
+ }
+ return len(out), nil
+}
+
+func (s *ExerciseStore) cachedOedbIDs() (map[string]bool, error) {
+ rows, err := s.db.Query(`SELECT oedb_id FROM exercises WHERE oedb_id IS NOT NULL AND oedb_id != ''`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ held := map[string]bool{}
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ held[id] = true
+ }
+ 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.
+func (s *ExerciseStore) PrimeQuery(ctx context.Context, query string) error {
+ if s.catalog == nil {
+ return ErrNoCatalog
+ }
+ _, err := s.Search(ctx, ExerciseFilter{Query: query, Limit: 25})
+ return err
+}
diff --git a/backend/stores/exercise_test.go b/backend/stores/exercise_test.go
new file mode 100644
index 0000000..88af658
--- /dev/null
+++ b/backend/stores/exercise_test.go
@@ -0,0 +1,405 @@
+package stores
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/oedb"
+ _ "modernc.org/sqlite"
+)
+
+func testDB(t *testing.T) *sql.DB {
+ t.Helper()
+ name := fmt.Sprintf("file:storetest_%d?mode=memory&cache=shared&_pragma=foreign_keys(on)", rand.Int63())
+ conn, err := sql.Open("sqlite", name)
+ if err != nil {
+ t.Fatalf("open: %v", err)
+ }
+ if err := conn.Ping(); err != nil {
+ t.Fatalf("ping: %v", err)
+ }
+ prev := db.DB
+ db.DB = conn
+ if err := db.BuildSchema(); err != nil {
+ t.Fatalf("schema: %v", err)
+ }
+ t.Cleanup(func() {
+ conn.Close()
+ db.DB = prev
+ })
+ return conn
+}
+
+func catalogExercise(id, name string) oedb.Exercise {
+ return oedb.Exercise{
+ ID: id,
+ Slug: name,
+ MuscleGroup: "chest",
+ SecondaryMuscles: []string{"triceps"},
+ Category: "strength",
+ Equipment: "barbell",
+ Images: []oedb.Image{{URL: "/api/v1/images/img-1"}},
+ Translation: oedb.Translation{
+ Name: name,
+ Instructions: []string{"Step one.", "Step two."},
+ },
+ }
+}
+
+// A legacy row — one seeded from free-exercise-db before oedb existed — must keep
+// its integer id when the catalog claims it. That id is what every saved workout
+// and program references, through a foreign key with no cascade: replacing the
+// row instead of adopting it would either fail the insert or, worse, silently
+// repoint someone's logged sets at a different exercise.
+func TestMaterialize_AdoptsLegacyRowByNameAndKeepsID(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ res, err := conn.Exec(`INSERT INTO exercises (name, muscle_group, category, equipment, description)
+ VALUES ('Bench Press', 'chest', 'strength', 'barbell', 'old text')`)
+ if err != nil {
+ t.Fatalf("seed legacy row: %v", err)
+ }
+ legacyID, _ := res.LastInsertId()
+
+ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press")}, "https://oedb.test")
+ if err != nil {
+ t.Fatalf("materialize: %v", err)
+ }
+ if len(out) != 1 {
+ t.Fatalf("got %d rows, want 1", len(out))
+ }
+ if out[0].ID != legacyID {
+ t.Errorf("legacy id changed: got %d, want %d", out[0].ID, legacyID)
+ }
+
+ var n int
+ conn.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&n)
+ if n != 1 {
+ t.Errorf("got %d exercises, want 1 (row was duplicated, not adopted)", n)
+ }
+
+ var oedbID string
+ conn.QueryRow(`SELECT oedb_id FROM exercises WHERE id = ?`, legacyID).Scan(&oedbID)
+ if oedbID != "uuid-1" {
+ t.Errorf("oedb_id = %q, want uuid-1", oedbID)
+ }
+ if out[0].Description != "1. Step one.\n2. Step two." {
+ t.Errorf("description = %q, want the numbered form", out[0].Description)
+ }
+ if out[0].ImageURL != "https://oedb.test/api/v1/images/img-1" {
+ t.Errorf("image_url = %q, want an absolute oedb URL", out[0].ImageURL)
+ }
+}
+
+// An upstream rename must update the row Lyftr already holds for that exercise,
+// not insert a second one. Matching on name alone cannot do this: the new name
+// matches nothing, so the row would be inserted and the catalog would then hold
+// the same exercise twice under two ids — with a user's history attached to the
+// stale one.
+func TestMaterialize_UpstreamRenameUpdatesSameRow(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ first, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Barbell Bench Press")}, "https://oedb.test")
+ if err != nil {
+ t.Fatalf("first materialize: %v", err)
+ }
+
+ second, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press (Barbell)")}, "https://oedb.test")
+ if err != nil {
+ t.Fatalf("second materialize: %v", err)
+ }
+
+ if first[0].ID != second[0].ID {
+ t.Errorf("rename moved the row: %d then %d", first[0].ID, second[0].ID)
+ }
+ var n int
+ conn.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&n)
+ if n != 1 {
+ t.Errorf("got %d exercises after rename, want 1", n)
+ }
+ if second[0].Name != "Bench Press (Barbell)" {
+ t.Errorf("name = %q, want the new upstream name", second[0].Name)
+ }
+}
+
+func TestMaterialize_DecodesSecondaryMuscles(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ out, err := s.Materialize([]oedb.Exercise{catalogExercise("uuid-1", "Bench Press")}, "https://oedb.test")
+ if err != nil {
+ t.Fatalf("materialize: %v", err)
+ }
+ if len(out[0].SecondaryMuscles) != 1 || out[0].SecondaryMuscles[0] != "triceps" {
+ t.Errorf("secondary_muscles = %v, want [triceps]", out[0].SecondaryMuscles)
+ }
+
+ var raw string
+ conn.QueryRow(`SELECT secondary_muscles FROM exercises WHERE oedb_id = 'uuid-1'`).Scan(&raw)
+ var decoded []string
+ if err := json.Unmarshal([]byte(raw), &decoded); err != nil {
+ t.Errorf("stored secondary_muscles is not valid JSON: %q", raw)
+ }
+}
+
+// With no catalog configured the store must answer from the local table rather
+// than error. Self-hosted instances that never set OEDB_BASE_URL, and every test
+// in this repo, depend on that path.
+func TestSearch_WithoutCatalogUsesLocalTable(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+
+ if _, err := conn.Exec(`INSERT INTO exercises (name, muscle_group) VALUES ('Local Only', 'chest')`); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+
+ got, err := s.Search(context.Background(), ExerciseFilter{Limit: 10})
+ if err != nil {
+ t.Fatalf("search: %v", err)
+ }
+ if len(got) != 1 || got[0].Name != "Local Only" {
+ t.Fatalf("got %v, want the local row", got)
+ }
+}
+
+// The catalog being unreachable must degrade to the local snapshot, not fail the
+// request. Someone mid-workout with no route to oedb still needs their exercise
+// list.
+func TestSearch_FallsBackToLocalWhenCatalogFails(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ // A port nothing listens on: the client fails to connect rather than
+ // returning an error status, which is the outage shape being modelled.
+ s.UseCatalog(oedb.New("http://127.0.0.1:1", "test"))
+
+ if _, err := conn.Exec(`INSERT INTO exercises (name, muscle_group) VALUES ('Cached Squat', 'quadriceps')`); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+
+ got, err := s.Search(context.Background(), ExerciseFilter{Limit: 10})
+ if err != nil {
+ t.Fatalf("search returned an error instead of falling back: %v", err)
+ }
+ if len(got) != 1 || got[0].Name != "Cached Squat" {
+ t.Fatalf("got %v, want the locally cached row", got)
+ }
+}
+
+func TestCacheControls_WithoutCatalogError(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ if _, err := s.RefreshCached(context.Background()); !errors.Is(err, ErrNoCatalog) {
+ t.Errorf("RefreshCached err = %v, want ErrNoCatalog", err)
+ }
+ if err := s.PrimeQuery(context.Background(), "squat"); !errors.Is(err, ErrNoCatalog) {
+ t.Errorf("PrimeQuery err = %v, want ErrNoCatalog", err)
+ }
+}
+
+// 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); err != nil {
+ t.Fatalf("seed held row: %v", err)
+ }
+
+ n, err := s.RefreshCached(context.Background())
+ if err != nil {
+ t.Fatalf("refresh: %v", err)
+ }
+ if n != 1 {
+ t.Errorf("refreshed %d, want 1", 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)
+ }
+ 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)
+ }
+}
+
+// oedb caps per_page at 100. A filtered request for more than that must walk the
+// pages rather than quietly returning the first one — the local table it replaced
+// answered such a query in full.
+func TestSearch_PaginatesFilteredResultsBeyondOnePage(t *testing.T) {
+ const total = 250
+ var pages int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&pages, 1)
+ page, _ := strconv.Atoi(r.URL.Query().Get("page"))
+ if page == 0 {
+ page = 1
+ }
+ perPage, _ := strconv.Atoi(r.URL.Query().Get("per_page"))
+ if perPage <= 0 || perPage > 100 {
+ // Mirror oedb: above 100 is rejected, not clamped.
+ w.WriteHeader(http.StatusUnprocessableEntity)
+ return
+ }
+ start := (page - 1) * perPage
+ var items []string
+ for i := start; i < start+perPage && i < total; i++ {
+ items = append(items, fmt.Sprintf(
+ `{"id":"uuid-%d","slug":"ex-%d","translation":{"name":"Exercise %d","instructions":[]}}`, i, i, i))
+ }
+ fmt.Fprintf(w, `{"exercises":[%s],"total":%d,"page":%d,"per_page":%d}`,
+ strings.Join(items, ","), total, page, perPage)
+ }))
+ defer srv.Close()
+
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ s.UseCatalog(oedb.New(srv.URL, "test"))
+
+ got, err := s.Search(context.Background(), ExerciseFilter{Equipment: "dumbbell", Limit: 250})
+ if err != nil {
+ t.Fatalf("search: %v", err)
+ }
+ if len(got) != total {
+ t.Fatalf("got %d exercises, want %d (pagination stopped early)", len(got), total)
+ }
+ if n := atomic.LoadInt32(&pages); n != 3 {
+ t.Errorf("upstream pages fetched = %d, want 3", n)
+ }
+}
+
+// Paging is what lets a picker stop downloading the catalog to filter it in the
+// browser, so an explicitly paged request must return that page and stop — not
+// everything from that page onward.
+func TestSearch_ExplicitPageReturnsOnlyThatPage(t *testing.T) {
+ const total = 250
+ var seen []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ seen = append(seen, q.Get("page")+"/"+q.Get("per_page"))
+ page, _ := strconv.Atoi(q.Get("page"))
+ if page == 0 {
+ page = 1
+ }
+ perPage, _ := strconv.Atoi(q.Get("per_page"))
+ start := (page - 1) * perPage
+ var items []string
+ for i := start; i < start+perPage && i < total; i++ {
+ items = append(items, fmt.Sprintf(
+ `{"id":"uuid-%d","slug":"ex-%d","translation":{"name":"Exercise %d","instructions":[]}}`, i, i, i))
+ }
+ fmt.Fprintf(w, `{"exercises":[%s],"total":%d,"page":%d,"per_page":%d}`,
+ strings.Join(items, ","), total, page, perPage)
+ }))
+ defer srv.Close()
+
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ s.UseCatalog(oedb.New(srv.URL, "test"))
+
+ got, err := s.Search(context.Background(), ExerciseFilter{Query: "ex", Limit: 50, Page: 3})
+ if err != nil {
+ t.Fatalf("search: %v", err)
+ }
+ if len(got) != 50 {
+ t.Fatalf("got %d exercises, want 50 (one page)", len(got))
+ }
+ if len(seen) != 1 || seen[0] != "3/50" {
+ t.Errorf("upstream requests = %v, want exactly [3/50]", seen)
+ }
+ if got[0].Name != "Exercise 100" {
+ t.Errorf("first row = %q, want the start of page 3", got[0].Name)
+ }
+}
+
+// The local fallback has to page too, or an offline picker silently repeats its
+// first page forever as the user scrolls.
+func TestList_LocalFallbackPages(t *testing.T) {
+ conn := testDB(t)
+ s := NewExerciseStore(conn)
+ for i := 0; i < 25; i++ {
+ if _, err := conn.Exec(`INSERT INTO exercises (name) VALUES (?)`, fmt.Sprintf("Exercise %02d", i)); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ }
+
+ page1, err := s.List(ExerciseFilter{Limit: 10, Page: 1})
+ if err != nil {
+ t.Fatalf("page 1: %v", err)
+ }
+ page3, err := s.List(ExerciseFilter{Limit: 10, Page: 3})
+ if err != nil {
+ t.Fatalf("page 3: %v", err)
+ }
+ if len(page1) != 10 || len(page3) != 5 {
+ t.Fatalf("page sizes = %d and %d, want 10 and 5", len(page1), len(page3))
+ }
+ if page1[0].Name == page3[0].Name {
+ t.Errorf("page 3 repeated page 1, starting at %q", page1[0].Name)
+ }
+ if page3[0].Name != "Exercise 20" {
+ t.Errorf("page 3 starts at %q, want Exercise 20", page3[0].Name)
+ }
+}
diff --git a/mobile/src/components/workouts/ExercisePicker.tsx b/mobile/src/components/workouts/ExercisePicker.tsx
index f0e96bd..523f931 100644
--- a/mobile/src/components/workouts/ExercisePicker.tsx
+++ b/mobile/src/components/workouts/ExercisePicker.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { ActivityIndicator, FlatList, Modal, Pressable, TextInput, View } from 'react-native'
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'
import { ArrowLeft, Search } from 'lucide-react-native'
@@ -15,7 +15,9 @@ interface Props {
onClose: () => void
}
-const MAX_SHOWN = 40
+// Must match the server's default page size: a short page is what tells us there
+// is nothing left for this query.
+const PAGE_SIZE = 50
function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => void }) {
return (
@@ -56,30 +58,51 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
const [exercises, setExercises] = useState<Exercise[]>([])
const [query, setQuery] = useState('')
const [loading, setLoading] = useState(false)
+ const [page, setPage] = useState(1)
+ const [exhausted, setExhausted] = useState(false)
+ // FlatList fires onEndReached more than once near the boundary; this keeps those
+ // repeats from each starting their own request for the same page.
+ const loadingRef = useRef(false)
+ // Identifies the newest request so a slow earlier one cannot overwrite it.
+ const reqRef = useRef(0)
- // One debounced loader (250ms, web parity); the empty query is served instantly —
- // the client caches the unfiltered exercise list after the first fetch.
- useEffect(() => {
- let cancelled = false
- const t = setTimeout(async () => {
- setLoading(true)
- try {
- const data = await client.exerciseAPI.list(query ? { q: query } : undefined)
- if (!cancelled) setExercises(data || [])
- } catch {
- // Web swallows picker fetch errors too — the empty state covers it.
- } finally {
- if (!cancelled) setLoading(false)
+ // Every page comes from the server, which queries open-exercise-db. The client
+ // used to cache the whole unfiltered catalog on first open and slice it locally;
+ // that made each install a copy of a database it does not own, and on a phone it
+ // is the difference between one 50-row response and ~873 rows of JSON.
+ const load = useCallback(async (q: string, nextPage: number, append = false) => {
+ // Only an append is skippable. Dropping a search because a page fetch is still
+ // in flight leaves the user looking at the unfiltered first page while their
+ // query appears to have done nothing.
+ if (append && loadingRef.current) return
+ const id = ++reqRef.current
+ loadingRef.current = true
+ setLoading(true)
+ try {
+ const data = (await client.exerciseAPI.list({ ...(q ? { q } : {}), page: nextPage })) || []
+ if (reqRef.current !== id) return // a newer request has taken over
+ setExercises((prev) => (append ? [...prev, ...data] : data))
+ setExhausted(data.length < PAGE_SIZE)
+ setPage(nextPage)
+ } catch {
+ // Web swallows picker fetch errors too — the empty state covers it.
+ } finally {
+ if (reqRef.current === id) {
+ loadingRef.current = false
+ setLoading(false)
}
- }, query ? 250 : 0)
- return () => {
- cancelled = true
- clearTimeout(t)
}
- }, [query])
+ }, [])
+
+ useEffect(() => {
+ const t = setTimeout(() => {
+ setExhausted(false)
+ load(query, 1)
+ }, query ? 250 : 0)
+ return () => clearTimeout(t)
+ }, [query, load])
const available = exercises.filter((e) => !selectedIds.includes(e.id))
- const shown = available.slice(0, MAX_SHOWN)
return (
<Modal visible animationType="slide" onRequestClose={onClose}>
@@ -96,7 +119,9 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
{/* Large title (matches the sibling "Log Workout" screen title) — the
18px heading read undersized for a full-screen surface. */}
<AppText variant="title">Add Exercise</AppText>
- <AppText variant="caption" color="muted">{available.length} available</AppText>
+ <AppText variant="caption" color="muted">
+ {available.length} loaded{exhausted ? '' : '…'}
+ </AppText>
</View>
</View>
@@ -113,7 +138,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
className="flex-1 font-sans text-base text-tx-primary"
value={query}
onChangeText={setQuery}
- placeholder="Search name, muscle, equipment…"
+ placeholder="Search exercises…"
placeholderTextColor={colors.txMuted}
autoCapitalize="none"
autoCorrect={false}
@@ -130,7 +155,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
</View>
) : (
<FlatList
- data={shown}
+ data={available}
keyExtractor={(e) => String(e.id)}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
@@ -139,16 +164,19 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
// media so the thumbnails read as a column, not boxed cells.
ItemSeparatorComponent={() => <View className="ml-[56px] h-px bg-surface-border/60" />}
renderItem={({ item }) => <PickerRow exercise={item} onPress={() => onSelect(item)} />}
+ onEndReached={() => { if (!exhausted && !loading) load(query, page + 1, true) }}
+ onEndReachedThreshold={0.5}
ListEmptyComponent={
<View className="items-center py-16">
<AppText variant="body" color="muted">No exercises found</AppText>
</View>
}
ListFooterComponent={
- available.length > MAX_SHOWN ? (
- <AppText variant="caption" color="muted" className="py-3 text-center">
- Showing {MAX_SHOWN} of {available.length} — refine search
- </AppText>
+ !exhausted && exercises.length > 0 ? (
+ <View className="flex-row items-center justify-center gap-2 py-4">
+ <ActivityIndicator color={accent} />
+ <AppText variant="caption" color="muted">Loading more…</AppText>
+ </View>
) : null
}
/>
diff --git a/mobile/src/utils/exerciseUtils.ts b/mobile/src/utils/exerciseUtils.ts
index 98963e9..8648681 100644
--- a/mobile/src/utils/exerciseUtils.ts
+++ b/mobile/src/utils/exerciseUtils.ts
@@ -53,7 +53,9 @@ const MUSCLE_TO_BODY_SLUG: Record<string, string[]> = {
back: ['upper-back', 'lower-back'],
'upper back': ['upper-back'],
'middle back': ['upper-back'], // RN lib has no 'middle-back'
+ 'middle-back': ['upper-back'],
'lower back': ['lower-back'],
+ 'lower-back': ['lower-back'],
lats: ['upper-back'],
shoulders: ['deltoids'],
deltoids: ['deltoids'],
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 9c62d60..284b5e5 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -110,52 +110,75 @@ describe('workoutAPI tz_offset_minutes on legacy rows', () => {
})
})
-// The unparameterised exercise list is fetched once and cached, because it is ~820 KB
-// and every picker opens with an empty search box.
-describe('exerciseAPI.list caching', () => {
- // Adapter that fails the first N calls, then succeeds, counting requests.
- const flakyClient = (failures: number) => {
- let calls = 0
+// The exercise catalog is not the client's to hold. It lives in open-exercise-db,
+// the server queries it and returns a page at a time, and the browser keeps only
+// what it is showing.
+describe('exerciseAPI.list is server-side and unbuffered', () => {
+ // Adapter that records the params of every request and answers with one row.
+ const recordingClient = () => {
+ const seen: any[] = []
const client = createClient(memStorage())
client.api.defaults.adapter = async (config: any) => {
- calls += 1
- if (calls <= failures) throw new Error('network')
+ seen.push(config.params)
return {
data: { data: [{ id: 1, name: 'Bench Press' }] },
status: 200, statusText: 'OK', headers: {}, config,
}
}
- return { client, count: () => calls }
+ return { client, seen }
}
- it('fetches once and serves later calls from cache', async () => {
- const { client, count } = flakyClient(0)
+ // The previous client cached the whole unfiltered catalog on first call, which is
+ // what made every app instance a copy of a database it does not own. Repeating a
+ // request must reach the server, whose own cache holds upstream responses for five
+ // minutes and answers it for free.
+ it('sends every call to the server, including repeats', async () => {
+ const { client, seen } = recordingClient()
await client.exerciseAPI.list()
await client.exerciseAPI.list()
- expect(count()).toBe(1)
+ expect(seen).toHaveLength(2)
})
- it('recovers after a failed fetch instead of caching the rejection forever', async () => {
- // Clearing the in-flight promise only on success left a rejected promise cached for
- // the life of the page: every later call replayed that same rejection, so one
- // dropped request while the picker was opening broke the picker until a reload.
- const { client, count } = flakyClient(1)
+ it('asks for one page by default rather than the whole catalog', async () => {
+ const { client, seen } = recordingClient()
+ await client.exerciseAPI.list()
+ expect(seen[0].limit).toBe(50)
+ expect(seen[0].limit).toBeLessThanOrEqual(100) // the server's per-page ceiling
+ })
- await expect(client.exerciseAPI.list()).rejects.toThrow()
- await expect(client.exerciseAPI.list()).resolves.toHaveLength(1)
- expect(count()).toBe(2)
+ it('forwards paging and filters', async () => {
+ const { client, seen } = recordingClient()
+ await client.exerciseAPI.list({ q: 'bench', page: 3 })
+ expect(seen[0]).toMatchObject({ q: 'bench', page: 3, limit: 50 })
+ })
+
+ it('lets an explicit limit override the default', async () => {
+ const { client, seen } = recordingClient()
+ await client.exerciseAPI.list({ limit: 10 })
+ expect(seen[0].limit).toBe(10)
})
- it('still surfaces the failure to the caller — it only stops caching it', async () => {
- const { client } = flakyClient(1)
+ // A failure must reach the caller rather than being swallowed or, as the cached
+ // version once did, replayed to every later call for the life of the page.
+ it('surfaces failures to the caller', async () => {
+ const client = createClient(memStorage())
+ client.api.defaults.adapter = async () => { throw new Error('network') }
await expect(client.exerciseAPI.list()).rejects.toThrow('network')
})
- it('does not cache filtered searches', async () => {
- const { client, count } = flakyClient(0)
- await client.exerciseAPI.list({ q: 'bench' })
- await client.exerciseAPI.list({ q: 'bench' })
- expect(count()).toBe(2)
+ it('recovers on the next call after a failure', async () => {
+ let calls = 0
+ const client = createClient(memStorage())
+ client.api.defaults.adapter = async (config: any) => {
+ calls += 1
+ if (calls === 1) throw new Error('network')
+ return {
+ data: { data: [{ id: 1, name: 'Bench Press' }] },
+ status: 200, statusText: 'OK', headers: {}, config,
+ }
+ }
+ await expect(client.exerciseAPI.list()).rejects.toThrow()
+ await expect(client.exerciseAPI.list()).resolves.toHaveLength(1)
})
})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index c258243..b8d254d 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -205,43 +205,44 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
// a dropped request.
const listTimeout = (limit?: number) => ((limit ?? 0) > 50 ? { timeout: BULK_TIMEOUT } : undefined)
- let exerciseCache: types.Exercise[] | null = null
- let exerciseCachePromise: Promise<types.Exercise[]> | null = null
+ // One screenful and change. Small enough that the first page of the picker arrives
+ // in one round trip, large enough that scrolling does not fetch constantly. The
+ // server caps a page at 100, which is open-exercise-db's own per_page ceiling.
+ const DEFAULT_EXERCISE_PAGE_SIZE = 50
+
const exerciseAPI = {
- list: (params?: { q?: string; muscle_group?: string; category?: string; equipment?: string }) => {
- if (params?.q || params?.muscle_group || params?.category || params?.equipment) {
- return api.get<{ data: types.Exercise[] }>('/exercises', { params }).then(unwrap)
- }
- if (exerciseCache) return Promise.resolve(exerciseCache)
- if (exerciseCachePromise) return exerciseCachePromise
- // The in-flight promise is cleared on BOTH settle paths. Clearing it only in
- // .then() leaves a rejected promise cached for the life of the page: every later
- // call returns that same rejection, so one dropped request while the picker was
- // opening breaks the picker until a full reload. clearCache() would recover it
- // but nothing calls it. The rejection is re-thrown so the caller still sees the
- // failure — only the caching of it is undone.
- exerciseCachePromise = api.get<{ data: types.Exercise[] }>('/exercises', { params: { limit: 1000 }, timeout: BULK_TIMEOUT })
- .then((res) => {
- exerciseCache = unwrap(res)
- exerciseCachePromise = null
- return exerciseCache
- })
- .catch((err) => {
- exerciseCachePromise = null
- throw err
- })
- return exerciseCachePromise
- },
+ // Every call goes to the server, which queries open-exercise-db and returns one
+ // page. There is deliberately no client-side catalog here: the previous version
+ // fetched all ~873 rows once and filtered them in memory, which made every app
+ // instance a copy of a database it does not own and put the whole catalog behind
+ // one slow request before the picker could show anything. Paging keeps the first
+ // screen fast and the memory flat, and lets the server's own cache do the work —
+ // it holds upstream responses for five minutes, so a repeated search costs it
+ // nothing.
+ list: (params?: {
+ q?: string
+ muscle_group?: string
+ category?: string
+ equipment?: string
+ limit?: number
+ page?: number
+ }) => api.get<{ data: types.Exercise[] }>('/exercises', {
+ params: { limit: DEFAULT_EXERCISE_PAGE_SIZE, ...params },
+ ...listTimeout(params?.limit),
+ }).then(unwrap),
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),
- clearCache: () => { exerciseCache = null; exerciseCachePromise = null },
- seedStatus: () => api.get<{ data: { count: number; in_progress: boolean } }>('/admin/seed-status').then(unwrap),
- // Re-seeds the whole exercise library from the upstream DB: hundreds of rows, and on
- // a cold or low-powered server it routinely 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 the server goes on to finish successfully.
- sync: () => api.post<{ data: { synced: boolean; total: number } }>('/admin/sync-exercises', undefined, { timeout: SYNC_TIMEOUT }).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.
+ 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
+ // 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/utils/exerciseUtils.ts b/packages/shared/src/utils/exerciseUtils.ts
index 53877e2..dc47073 100644
--- a/packages/shared/src/utils/exerciseUtils.ts
+++ b/packages/shared/src/utils/exerciseUtils.ts
@@ -14,16 +14,33 @@
//
// The *lookup rule* over those tables is identical on both sides, so it lives here.
+// Keys are open-exercise-db's equipment slugs, which is what the API now serves.
+//
+// The spaced spellings below them are the same vocabulary as free-exercise-db wrote
+// it, and they stay as aliases rather than being replaced: a self-hosted instance
+// that has not yet run the taxonomy migration still holds rows spelled that way, and
+// a label table that silently stopped matching them would degrade to raw values in
+// the UI with nothing to explain why.
export const EQUIPMENT_LABEL: Record<string, string> = {
+ 'body-only': 'Bodyweight',
+ 'barbell': 'Barbell',
+ 'dumbbell': 'Dumbbell',
+ 'machine': 'Machine',
+ 'cable': 'Cable',
+ 'kettlebells': 'Kettlebell',
+ 'bands': 'Bands',
+ 'medicine-ball': 'Med Ball',
+ 'e-z-curl-bar': 'EZ Bar',
+ 'exercise-ball': 'Exercise Ball',
+ 'foam-roll': 'Foam Roll',
+ 'none': 'None',
+ 'other': 'Other',
+
+ // Pre-migration spellings.
'body only': 'Bodyweight',
- 'barbell': 'Barbell',
- 'dumbbell': 'Dumbbell',
- 'machine': 'Machine',
- 'cable': 'Cable',
- 'kettlebells': 'Kettlebell',
- 'bands': 'Bands',
'medicine ball': 'Med Ball',
- 'other': 'Other',
+ 'e-z curl bar': 'EZ Bar',
+ 'exercise ball': 'Exercise Ball',
'foam roll': 'Foam Roll',
}
diff --git a/web/e2e/programs.spec.ts b/web/e2e/programs.spec.ts
index c852bec..dff4a9c 100644
--- a/web/e2e/programs.spec.ts
+++ b/web/e2e/programs.spec.ts
@@ -72,8 +72,8 @@ test.describe('Programs', () => {
// Programs are day-nested now — add a workout day before its exercise editor appears.
await page.getByRole('button', { name: /add workout day/i }).click()
await page.getByRole('button', { name: /add exercise/i }).click()
- await expect(page.getByPlaceholder(/search name/i)).toBeVisible()
- await page.getByPlaceholder(/search name/i).fill('squat')
+ await expect(page.getByPlaceholder(/search exercises/i)).toBeVisible()
+ await page.getByPlaceholder(/search exercises/i).fill('squat')
await page.getByText(/squat/i).first().click()
// Fill target sets
@@ -131,7 +131,7 @@ test.describe('Programs', () => {
await page.goto('/programs/new')
await page.getByRole('button', { name: /add workout day/i }).click()
await page.getByRole('button', { name: /add exercise/i }).click()
- await page.getByPlaceholder(/search name/i).fill('deadlift')
+ await page.getByPlaceholder(/search exercises/i).fill('deadlift')
await page.getByText(/deadlift/i).first().click()
const weightSuffix = page.locator('text=/^(lb|kg)$/')
diff --git a/web/e2e/workouts.spec.ts b/web/e2e/workouts.spec.ts
index 7d4c4e3..7398c4b 100644
--- a/web/e2e/workouts.spec.ts
+++ b/web/e2e/workouts.spec.ts
@@ -88,8 +88,8 @@ test.describe('Workouts', () => {
// Add exercise
await page.getByRole('button', { name: /add exercise/i }).click()
- await expect(page.getByPlaceholder(/search name/i)).toBeVisible()
- await page.getByPlaceholder(/search name/i).fill('bench press')
+ await expect(page.getByPlaceholder(/search exercises/i)).toBeVisible()
+ await page.getByPlaceholder(/search exercises/i).fill('bench press')
await page.getByText(/bench press/i).first().click()
// Fill in set
diff --git a/web/src/components/ExercisePicker.test.tsx b/web/src/components/ExercisePicker.test.tsx
new file mode 100644
index 0000000..f5061b6
--- /dev/null
+++ b/web/src/components/ExercisePicker.test.tsx
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import ExercisePicker from './ExercisePicker'
+import { types } from '@lyftr/shared'
+
+type ListParams = {
+ q?: string
+ muscle_group?: string
+ category?: string
+ equipment?: string
+ limit?: number
+ page?: number
+}
+
+const listMock = vi.fn()
+vi.mock('../services/api', () => ({
+ exerciseAPI: { list: (params?: ListParams) => listMock(params) },
+}))
+
+// @tanstack/react-virtual measures a real scroll container, which jsdom has no
+// layout for — every row would render at zero height and none would be visible.
+// Reporting one row per loaded exercise keeps the list assertable without making
+// the test about virtualization.
+vi.mock('@tanstack/react-virtual', () => ({
+ useVirtualizer: ({ count }: { count: number }) => ({
+ getTotalSize: () => count * 64,
+ getVirtualItems: () =>
+ Array.from({ length: count }, (_, index) => ({ index, key: index, start: index * 64, size: 64 })),
+ }),
+}))
+
+const exercise = (id: number, name: string): types.Exercise => ({
+ id,
+ name,
+ muscle_group: 'quadriceps',
+ secondary_muscles: [],
+ category: 'strength',
+ equipment: 'barbell',
+ description: '',
+})
+
+// A page of exactly PAGE_SIZE rows, so the component does not treat it as the end.
+const fullPage = (prefix: string) =>
+ Array.from({ length: 50 }, (_, i) => exercise(i + 1, `${prefix} ${i + 1}`))
+
+beforeEach(() => {
+ listMock.mockReset()
+})
+
+describe('ExercisePicker', () => {
+ // The picker opens with an unfiltered first page in flight. If typing a query
+ // while that request is outstanding is treated as "a load is already running,
+ // skip it", the search is silently dropped: the user is left looking at the
+ // alphabetical first page, having typed a query that appears to do nothing. This
+ // is not hypothetical — it took an e2e run 30s to fail on exactly this.
+ it('runs a search typed while the initial page is still loading', async () => {
+ let releaseInitial: (v: types.Exercise[]) => void = () => {}
+ listMock
+ .mockImplementationOnce(() => new Promise(resolve => { releaseInitial = resolve }))
+ .mockImplementation(() => Promise.resolve([exercise(999, 'Barbell Squat')]))
+
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+
+ // Type before the first page resolves.
+ fireEvent.change(screen.getByPlaceholderText(/search exercises/i), { target: { value: 'squat' } })
+
+ await waitFor(() => {
+ expect(listMock).toHaveBeenCalledWith(expect.objectContaining({ q: 'squat', page: 1 }))
+ })
+
+ releaseInitial(fullPage('Unfiltered'))
+
+ expect(await screen.findByText('Barbell Squat')).toBeTruthy()
+ })
+
+ // A slow earlier response must not overwrite a newer one. Without a sequence
+ // guard the list ends up showing results for a query the user has moved past.
+ it('ignores a stale response that arrives after a newer one', async () => {
+ let releaseFirst: (v: types.Exercise[]) => void = () => {}
+ listMock
+ .mockImplementationOnce(() => new Promise(resolve => { releaseFirst = resolve }))
+ .mockImplementation(() => Promise.resolve([exercise(2, 'Front Squat')]))
+
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+ fireEvent.change(screen.getByPlaceholderText(/search exercises/i), { target: { value: 'squat' } })
+
+ expect(await screen.findByText('Front Squat')).toBeTruthy()
+
+ // The initial unfiltered page lands late; it must not replace the search results.
+ releaseFirst([exercise(1, 'Stale Unfiltered Row')])
+
+ await waitFor(() => {
+ expect(screen.queryByText('Stale Unfiltered Row')).toBeNull()
+ })
+ expect(screen.getByText('Front Squat')).toBeTruthy()
+ })
+
+ it('asks the server for each page rather than filtering locally', async () => {
+ listMock.mockResolvedValue(fullPage('Exercise'))
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+
+ await waitFor(() => expect(listMock).toHaveBeenCalled())
+ // page is always explicit, and no call asks for the whole catalog.
+ for (const call of listMock.mock.calls) {
+ expect(call[0]).toHaveProperty('page')
+ expect(call[0]?.limit ?? 50).toBeLessThanOrEqual(100)
+ }
+ })
+})
diff --git a/web/src/components/ExercisePicker.tsx b/web/src/components/ExercisePicker.tsx
index 513c195..27a4f0e 100644
--- a/web/src/components/ExercisePicker.tsx
+++ b/web/src/components/ExercisePicker.tsx
@@ -6,6 +6,12 @@ import { exerciseAPI } from '../services/api'
import { types } from '@lyftr/shared'
import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'
+// Must match the server's default page size, since a short page is what signals
+// the end of the results.
+const PAGE_SIZE = 50
+// How close to the end of the loaded rows to get before fetching the next page.
+const PREFETCH_ROWS = 10
+
interface Props {
selectedIds: number[]
onSelect: (exercise: types.Exercise) => void
@@ -16,23 +22,54 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
const [exercises, setExercises] = useState<types.Exercise[]>([])
const [query, setQuery] = useState('')
const [loading, setLoading] = useState(false)
+ const [page, setPage] = useState(1)
+ const [exhausted, setExhausted] = useState(false)
const scrollRef = useRef<HTMLDivElement>(null)
+ // Guards against the virtualizer asking for the next page repeatedly while the
+ // first request for it is still in flight — it fires on every scroll frame, not
+ // once per boundary crossing. It only ever suppresses an append: a new search
+ // must never be dropped because a page fetch is outstanding.
+ const loadingRef = useRef(false)
+ // Identifies the newest request so a slow earlier one cannot overwrite it. Typing
+ // fast enough to outrun a response otherwise leaves the list showing results for
+ // a query the user has already moved on from.
+ const reqRef = useRef(0)
- useEffect(() => { load('') }, [])
-
- useEffect(() => {
- const t = setTimeout(() => load(query), 250)
- return () => clearTimeout(t)
- }, [query])
-
- const load = async (q: string) => {
+ // Results come a page at a time from the server, which queries open-exercise-db.
+ // Nothing downloads the catalog to filter it here: with ~873 exercises upstream
+ // and growing, the browser is the wrong place to do that, and it put the whole
+ // library behind one slow request before the picker could render anything.
+ const load = useCallback(async (q: string, nextPage: number, append = false) => {
+ if (append && loadingRef.current) return
+ const id = ++reqRef.current
+ loadingRef.current = true
setLoading(true)
try {
- const data = await exerciseAPI.list(q ? { q } : undefined)
- setExercises(data || [])
+ const data = await exerciseAPI.list({ ...(q ? { q } : {}), page: nextPage }) || []
+ if (reqRef.current !== id) return // a newer request has taken over
+ setExercises(prev => (append ? [...prev, ...data] : data))
+ // A short page means the server has nothing left for this query. Asking again
+ // would just repeat the request for every remaining scroll event.
+ setExhausted(data.length < PAGE_SIZE)
+ setPage(nextPage)
} catch { /* a failed search keeps the previous list rather than blanking it */ }
- finally { setLoading(false) }
- }
+ finally {
+ if (reqRef.current === id) {
+ loadingRef.current = false
+ setLoading(false)
+ }
+ }
+ }, [])
+
+ useEffect(() => { load('', 1) }, [load])
+
+ useEffect(() => {
+ const t = setTimeout(() => {
+ setExhausted(false)
+ load(query, 1)
+ }, 250)
+ return () => clearTimeout(t)
+ }, [query, load])
const available = exercises.filter(e => !selectedIds.includes(e.id))
@@ -43,6 +80,17 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
overscan: 5,
})
+ const virtualItems = virtualizer.getVirtualItems()
+
+ // Fetch the next page as the last rendered row approaches the end of what we
+ // hold. Keyed on the last visible index rather than a scroll handler so it works
+ // with the virtualizer's own windowing.
+ const lastVisible = virtualItems.length ? virtualItems[virtualItems.length - 1].index : 0
+ useEffect(() => {
+ if (exhausted || loading || available.length === 0) return
+ if (lastVisible >= available.length - PREFETCH_ROWS) load(query, page + 1, true)
+ }, [lastVisible, available.length, exhausted, loading, query, page, load])
+
return createPortal(
<div className="fixed inset-0 z-[60] bg-surface-base flex flex-col animate-slide-up">
{/* Header */}
@@ -55,7 +103,9 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
</button>
<div>
<h2 className="font-display font-bold text-xl text-tx-primary">Add Exercise</h2>
- <p className="text-xs text-tx-muted">{available.length} available</p>
+ <p className="text-xs text-tx-muted">
+ {available.length} loaded{exhausted ? '' : '…'}
+ </p>
</div>
</div>
@@ -67,7 +117,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
- placeholder="Search name, muscle, equipment…"
+ placeholder="Search exercises…"
className="input pl-10 w-full"
autoFocus
/>
@@ -90,7 +140,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
className="px-4 py-2 relative"
style={{ height: virtualizer.getTotalSize() }}
>
- {virtualizer.getVirtualItems().map(row => {
+ {virtualItems.map(row => {
const ex = available[row.index]
return (
<div
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 31fe714..2dff27f 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -69,8 +69,8 @@ export default function Settings() {
const [success, setSuccess] = useState(false)
const [showCustomRest, setShowCustomRest] = useState(false)
- const [seedStatus, setSeedStatus] = useState<{ count: number; in_progress: boolean } | null>(null)
- const [seedAction, setSeedAction] = useState<'sync' | null>(null)
+ const [cacheStatus, setCacheStatus] = useState<{ count: number } | null>(null)
+ const [seedAction, setSeedAction] = useState<'refresh' | 'clear' | null>(null)
const [seedMsg, setSeedMsg] = useState<string | null>(null)
const [formData, setFormData] = useState({
@@ -81,12 +81,12 @@ export default function Settings() {
fat_target: storedSettings.fat_target,
})
- const loadSeedStatus = useCallback(async () => {
+ const loadCacheStatus = useCallback(async () => {
try {
- const s = await exerciseAPI.seedStatus()
- setSeedStatus(s)
+ const s = await exerciseAPI.cacheStatus()
+ setCacheStatus(s)
return s
- } catch { /* seeding status is a best-effort probe; absence just hides the banner */ }
+ } catch { /* cache status is a best-effort probe; absence just hides the count */ }
}, [])
useEffect(() => {
@@ -108,28 +108,35 @@ export default function Settings() {
}
}
load()
- loadSeedStatus()
- }, [loadSeedStatus])
+ loadCacheStatus()
+ }, [loadCacheStatus])
- // Poll while seeding in progress
- useEffect(() => {
- if (!seedStatus?.in_progress) return
- const id = setInterval(async () => {
- const s = await loadSeedStatus()
- if (s && !s.in_progress) clearInterval(id)
- }, 2000)
- return () => clearInterval(id)
- }, [seedStatus?.in_progress, loadSeedStatus])
-
- const handleSync = async () => {
- setSeedAction('sync')
+ // 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.
+
+ const handleRefreshCache = async () => {
+ setSeedAction('refresh')
setSeedMsg(null)
try {
- const res = await exerciseAPI.sync()
- setSeedMsg(`Synced ${res.total.toLocaleString()} exercises`)
- loadSeedStatus()
+ const res = await exerciseAPI.refreshCache()
+ setSeedMsg(`Refreshed ${res.refreshed.toLocaleString()} exercises`)
+ loadCacheStatus()
} catch (err: any) {
- setSeedMsg(err.message || 'Sync failed')
+ setSeedMsg(err.message || 'Refresh failed')
+ } finally {
+ setSeedAction(null)
+ }
+ }
+
+ const handleClearCache = async () => {
+ setSeedAction('clear')
+ setSeedMsg(null)
+ try {
+ const res = await exerciseAPI.clearCacheOnServer()
+ setSeedMsg(`Cleared ${res.cleared.toLocaleString()} unused exercises`)
+ loadCacheStatus()
+ } catch (err) {
+ setSeedMsg(err instanceof Error ? err.message : 'Clear failed')
} finally {
setSeedAction(null)
}
@@ -412,19 +419,11 @@ export default function Settings() {
<Section title="Exercise Library">
<SettingRow
label="Exercise database"
- description="800+ exercises seeded automatically on first run"
+ description="Exercises come from open-exercise-db, queried as you search. This server keeps a copy of the ones it has shown."
>
- <div className="flex items-center gap-2">
- {seedStatus?.in_progress ? (
- <span className="flex items-center gap-1.5 text-xs text-brand-400">
- <Loader className="w-3.5 h-3.5 animate-spin" /> Seeding...
- </span>
- ) : (
- <span className="text-sm font-mono text-tx-muted">
- {seedStatus ? seedStatus.count.toLocaleString() : '—'} exercises
- </span>
- )}
- </div>
+ <span className="text-sm font-mono text-tx-muted">
+ {cacheStatus ? cacheStatus.count.toLocaleString() : '—'} cached
+ </span>
</SettingRow>
{seedMsg && (
@@ -433,15 +432,25 @@ export default function Settings() {
</div>
)}
- <div className="py-3">
+ <div className="py-3 flex items-center gap-2">
+ <button
+ onClick={handleRefreshCache}
+ disabled={!!seedAction}
+ className="btn-secondary btn-sm"
+ >
+ {seedAction === 'refresh'
+ ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Refreshing...</>
+ : <><RefreshCw className="w-3.5 h-3.5" /> Refresh cached</>
+ }
+ </button>
<button
- onClick={handleSync}
- disabled={!!seedAction || seedStatus?.in_progress}
+ onClick={handleClearCache}
+ disabled={!!seedAction}
className="btn-secondary btn-sm"
>
- {seedAction === 'sync'
- ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Syncing...</>
- : <><RefreshCw className="w-3.5 h-3.5" /> Re-sync</>
+ {seedAction === 'clear'
+ ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Clearing...</>
+ : <><Trash2 className="w-3.5 h-3.5" /> Clear unused</>
}
</button>
</div>
diff --git a/web/src/pages/WorkoutExercisePicker.tsx b/web/src/pages/WorkoutExercisePicker.tsx
index a894ef8..f58d5e2 100644
--- a/web/src/pages/WorkoutExercisePicker.tsx
+++ b/web/src/pages/WorkoutExercisePicker.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import { useState, useEffect, useCallback, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowLeft, Search, Dumbbell } from 'lucide-react'
import { exerciseAPI } from '../services/api'
@@ -6,32 +6,50 @@ import { useWorkoutSession } from '../stores/workoutSession'
import { types } from '@lyftr/shared'
import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'
+// Must match the server's default page size: a short page is what signals the end.
+const PAGE_SIZE = 50
+
export default function WorkoutExercisePicker() {
const navigate = useNavigate()
const { session, addExercise } = useWorkoutSession()
const [exercises, setExercises] = useState<types.Exercise[]>([])
const [query, setQuery] = useState('')
const [loading, setLoading] = useState(false)
+ const [page, setPage] = useState(1)
+ const [exhausted, setExhausted] = useState(false)
+ // Identifies the newest request so a slow earlier one cannot overwrite it.
+ const reqRef = useRef(0)
const selectedIds = session?.exercises.map(e => e.exercise_id) ?? []
- useEffect(() => {
- load('')
+ // The server answers each page from open-exercise-db. Nothing pulls the catalog
+ // into the browser to slice it here — this screen used to render the first 40 of
+ // whatever it had downloaded and tell the user to refine their search, which was
+ // a truncation dressed up as advice.
+ const load = useCallback(async (q: string, nextPage: number, append = false) => {
+ const id = ++reqRef.current
+ setLoading(true)
+ try {
+ const data = await exerciseAPI.list({ ...(q ? { q } : {}), page: nextPage }) || []
+ // Typing faster than the network otherwise leaves the list showing results for
+ // a query the user has already moved on from.
+ if (reqRef.current !== id) return
+ setExercises(prev => (append ? [...prev, ...data] : data))
+ setExhausted(data.length < PAGE_SIZE)
+ setPage(nextPage)
+ } catch { /* a failed search keeps the previous list rather than blanking it */ }
+ finally { if (reqRef.current === id) setLoading(false) }
}, [])
+ useEffect(() => { load('', 1) }, [load])
+
useEffect(() => {
- const t = setTimeout(() => load(query), 250)
+ const t = setTimeout(() => {
+ setExhausted(false)
+ load(query, 1)
+ }, 250)
return () => clearTimeout(t)
- }, [query])
-
- const load = async (q: string) => {
- setLoading(true)
- try {
- const data = await exerciseAPI.list(q ? { q } : undefined)
- setExercises(data || [])
- } catch { /* a failed search keeps the previous list rather than blanking it */ }
- finally { setLoading(false) }
- }
+ }, [query, load])
const handleSelect = (exercise: types.Exercise) => {
const newEx: types.ActiveSessionExercise = {
@@ -65,7 +83,9 @@ export default function WorkoutExercisePicker() {
</button>
<div>
<h1 className="font-display font-bold text-xl text-tx-primary">Add Exercise</h1>
- <p className="text-xs text-tx-muted">{available.length} available</p>
+ <p className="text-xs text-tx-muted">
+ {available.length} loaded{exhausted ? '' : '…'}
+ </p>
</div>
</div>
@@ -76,7 +96,7 @@ export default function WorkoutExercisePicker() {
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
- placeholder="Search name, muscle, equipment…"
+ placeholder="Search exercises…"
className="input pl-10 w-full"
autoFocus
/>
@@ -95,7 +115,7 @@ export default function WorkoutExercisePicker() {
</div>
) : (
<div className="space-y-1">
- {available.slice(0, 40).map(ex => (
+ {available.map(ex => (
<button
key={ex.id}
onClick={() => handleSelect(ex)}
@@ -129,10 +149,15 @@ export default function WorkoutExercisePicker() {
</div>
</button>
))}
- {available.length > 40 && (
- <p className="text-xs text-tx-muted text-center py-3">
- Showing 40 of {available.length} — refine search
- </p>
+ {!exhausted && (
+ <button
+ type="button"
+ onClick={() => load(query, page + 1, true)}
+ disabled={loading}
+ className="btn-secondary btn-sm w-full my-3"
+ >
+ {loading ? 'Loading…' : 'Load more'}
+ </button>
)}
</div>
)}
diff --git a/web/src/utils/exerciseUtils.ts b/web/src/utils/exerciseUtils.ts
index e1b50db..308b275 100644
--- a/web/src/utils/exerciseUtils.ts
+++ b/web/src/utils/exerciseUtils.ts
@@ -67,6 +67,8 @@ const MUSCLE_TO_BODY_SLUG: Record<string, string[]> = {
'spinal erectors': ['lower-back'],
erectors: ['lower-back'],
'lower back': ['lower-back'],
+ 'lower-back': ['lower-back'],
+ 'middle-back': ['upper-back'],
'upper back': ['upper-back'],
'hip flexors': ['adductor'],
adductors: ['adductor'],