From b93de95dd24ff2a1d3126e6d7d00cd77530a03bf Mon Sep 17 00:00:00 2001 From: Lukasz Kasprzak Date: Fri, 24 Jul 2026 09:15:40 +0200 Subject: tradlit: offline caching + read; update pre-caches traditional; --clean prunes it; v0.2.0 --- internal/tradlit/tradlit.go | 70 ++++++++++++++++++++-- internal/tradlit/tradlit_test.go | 121 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 185 insertions(+), 6 deletions(-) create mode 100644 internal/tradlit/tradlit_test.go (limited to 'internal/tradlit') diff --git a/internal/tradlit/tradlit.go b/internal/tradlit/tradlit.go index edb9ce0..a7b53bc 100644 --- a/internal/tradlit/tradlit.go +++ b/internal/tradlit/tradlit.go @@ -9,6 +9,8 @@ import ( "fmt" "io" "net/http" + "os" + "path/filepath" "regexp" "strings" @@ -86,11 +88,57 @@ func Parse(jsonBody []byte) ([]liturgy.Section, error) { return out, nil } -// Load fetches a day's traditional propers from the missalemeum API -// (https://www.missalemeum.com/{lang}/api/v5/proper/{date}) and parses -// them. On HTTP 404 (no propers published for that date) it returns a -// clear error rather than attempting to parse. -func Load(date, lang string) ([]liturgy.Section, error) { +// cachePath returns where Load caches a (date, lang) day's raw API response: +// /.trad..json -- date-prefixed (like the modern +// lectionary's own cache files) so liturgy.CleanCache can prune it by date. +func cachePath(date, lang string) string { + return filepath.Join(liturgy.CacheDir(), date+".trad."+lang+".json") +} + +// Load returns a day's traditional propers for lang, either read from the +// on-disk cache (offline) or fetched live from missalemeum and cached for +// next time (online). Both paths share Parse, so cached and live results +// are identical. +// +// - offline: reads the cache file written by a prior online Load (see +// cachePath); if it doesn't exist, returns a clear error telling the +// caller to go online or run 'lectio update' first. +// - online: fetches https://www.missalemeum.com/{lang}/api/v5/proper/{date} +// as before. On a successful 200, the raw response body is written to +// the cache path (best-effort -- a cache-write failure never fails the +// request) before being parsed. On HTTP 404 (no propers published for +// that date) it returns a clear error and writes nothing to the cache. +func Load(date, lang string, offline bool) ([]liturgy.Section, error) { + if offline { + return loadCached(date, lang) + } + return loadLive(date, lang) +} + +// loadCached implements Load's offline path. +func loadCached(date, lang string) ([]liturgy.Section, error) { + body, err := os.ReadFile(cachePath(date, lang)) + if err != nil { + return nil, fmt.Errorf("tradlit: no cached traditional propers for %s (%s); view it online or run 'lectio update' first", date, lang) + } + return Parse(body) +} + +// loadLive implements Load's online path: fetch, best-effort cache the raw +// body, then parse. +func loadLive(date, lang string) ([]liturgy.Section, error) { + body, err := fetch(date, lang) + if err != nil { + return nil, err + } + writeCache(date, lang, body) + return Parse(body) +} + +// fetch GETs the day's proper-of-the-day JSON from missalemeum and returns +// the raw response body. On HTTP 404 (no propers published for that date) +// it returns a clear error rather than the raw 404 body. +func fetch(date, lang string) ([]byte, error) { url := fmt.Sprintf(baseURL, lang, date) req, err := http.NewRequest(http.MethodGet, url, nil) @@ -116,6 +164,16 @@ func Load(date, lang string) ([]liturgy.Section, error) { if err != nil { return nil, fmt.Errorf("tradlit: load %s: %w", date, err) } + return body, nil +} - return Parse(body) +// writeCache best-effort writes a day's raw API response body to its cache +// path; a failure to cache (e.g. an unwritable cache dir) must never fail +// the live request that produced body. +func writeCache(date, lang string, body []byte) { + path := cachePath(date, lang) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return + } + _ = os.WriteFile(path, body, 0o644) } diff --git a/internal/tradlit/tradlit_test.go b/internal/tradlit/tradlit_test.go new file mode 100644 index 0000000..cd2cc83 --- /dev/null +++ b/internal/tradlit/tradlit_test.go @@ -0,0 +1,121 @@ +package tradlit + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/lukaszkasprzak/lectio/internal/liturgy" +) + +// TestLoadOnlineCachesRawBody exercises Load's online path: a successful +// fetch is cached verbatim (the raw response body, not the parsed +// sections) at tradlit's cache path, and parses the same way a cached read +// would. +func TestLoadOnlineCachesRawBody(t *testing.T) { + body, err := os.ReadFile("testdata/2026-07-22.json") + if err != nil { + t.Fatal(err) + } + hits := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits++ + w.Write(body) + })) + defer srv.Close() + + orig := baseURL + baseURL = srv.URL + "/%s/api/v5/proper/%s" + defer func() { baseURL = orig }() + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + + secs, err := Load("2026-07-22", "en", false) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(secs) == 0 { + t.Fatal("Load returned no sections") + } + if hits != 1 { + t.Errorf("server hit %d times, want 1", hits) + } + + cached, err := os.ReadFile(filepath.Join(liturgy.CacheDir(), "2026-07-22.trad.en.json")) + if err != nil { + t.Fatalf("cache file not written: %v", err) + } + if string(cached) != string(body) { + t.Error("cached content does not match the raw response body") + } +} + +// TestLoadOnline404WritesNoCache checks the documented invariant: a 404 (no +// propers published for that date) returns an error and leaves the cache +// directory untouched. +func TestLoadOnline404WritesNoCache(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + defer srv.Close() + + orig := baseURL + baseURL = srv.URL + "/%s/api/v5/proper/%s" + defer func() { baseURL = orig }() + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + + _, err := Load("2026-07-22", "en", false) + if err == nil { + t.Fatal("expected error on 404, got nil") + } + + cachePath := filepath.Join(liturgy.CacheDir(), "2026-07-22.trad.en.json") + if _, statErr := os.Stat(cachePath); !os.IsNotExist(statErr) { + t.Errorf("cache file should not exist after a 404 (stat err = %v)", statErr) + } +} + +// TestLoadOfflineReadsCache exercises Load's offline path against a +// pre-written cache file (as an earlier online Load, or 'lectio update', +// would have left behind) -- no network access at all. +func TestLoadOfflineReadsCache(t *testing.T) { + body, err := os.ReadFile("testdata/2026-07-22.json") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + t.Setenv("XDG_CACHE_HOME", dir) + cacheDir := filepath.Join(dir, "lectio") + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(cacheDir, "2026-07-22.trad.pl.json"), body, 0o644); err != nil { + t.Fatal(err) + } + + secs, err := Load("2026-07-22", "pl", true) + if err != nil { + t.Fatalf("Load offline: %v", err) + } + if len(secs) == 0 { + t.Fatal("Load offline returned no sections") + } +} + +// TestLoadOfflineMissingCacheErrors checks Load's offline path errors +// clearly (mentioning the missing cache) rather than trying the network, +// when nothing has been cached yet for that (date, lang). +func TestLoadOfflineMissingCacheErrors(t *testing.T) { + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + + _, err := Load("2026-07-22", "pl", true) + if err == nil { + t.Fatal("expected error for missing cache, got nil") + } + msg := strings.ToLower(err.Error()) + if !strings.Contains(msg, "no cached") { + t.Errorf("error %q should mention no cached propers", err.Error()) + } +} -- cgit v1.3