From 3a7ffab4d59b9ae5c9fd084a5d6c27f076466116 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Tue, 24 Nov 2026 00:19:36 +0000 Subject: [PATCH] fix(prewarming): start the worker and cache through the proxy path The pre-warm worker was never started, and its fetch discarded the response body, so nothing reached the cache. startWorkers now calls Start. The worker hands each package to a Fetcher. ProxyFetcher calls the npm, Go and PyPI handlers in-process, resolves the latest version, and downloads the artifact. The cache and the scan queue then treat it like a client request. Pre-warming stays off unless prewarming.enabled is set. Stop is safe on a worker that never started, and a second Start does nothing. --- pkg/app/app.go | 22 ++- pkg/app/workers_test.go | 46 +++++ pkg/prewarming/proxyfetcher.go | 266 ++++++++++++++++++++++++++++ pkg/prewarming/proxyfetcher_test.go | 129 ++++++++++++++ pkg/prewarming/worker.go | 151 ++++++++-------- pkg/prewarming/worker_test.go | 134 ++++++++++++++ 6 files changed, 661 insertions(+), 87 deletions(-) create mode 100644 pkg/prewarming/proxyfetcher.go create mode 100644 pkg/prewarming/proxyfetcher_test.go create mode 100644 pkg/prewarming/worker_test.go diff --git a/pkg/app/app.go b/pkg/app/app.go index 0657fe5..a501408 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -60,6 +60,7 @@ type App struct { analyticsEngine *analytics.Engine wsServer *websocket.Server prewarmWorker *prewarming.Worker + prewarmFetcher *prewarming.ProxyFetcher cdnMiddleware *cdn.Middleware } @@ -348,14 +349,14 @@ func (a *App) initializeComponents() error { // Initialize pre-warming worker. Operator-controlled via cfg.Prewarming; // defaults are baked into config.Default() so unset fields stay sane. log.Info().Msg("Initializing pre-warming worker") + a.prewarmFetcher = prewarming.NewProxyFetcher() a.prewarmWorker = prewarming.NewWorker(prewarming.Config{ Enabled: a.config.Prewarming.Enabled, Interval: a.config.Prewarming.Interval, MaxConcurrent: a.config.Prewarming.MaxConcurrent, TopPackages: a.config.Prewarming.TopPackages, - CacheManager: a.cache, - Analytics: a.analyticsEngine, - NetworkClient: a.networkClient, + Popularity: a.analyticsEngine, + Fetcher: a.prewarmFetcher, }) // Initialize CDN middleware @@ -536,7 +537,9 @@ func (a *App) setupServer() error { SumDBURL: sumDB, CredStore: credStore, }) - goProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/go", goProxyHandler)) + goProxyMounted := http.StripPrefix("/go", goProxyHandler) + a.prewarmFetcher.Mount("go", goProxyMounted) + goProxyWithCDN := a.cdnMiddleware.Handler(goProxyMounted) if authEnabled { a.app.All("/go/*", mwAuth, adaptor.HTTPHandler(goProxyWithCDN)) } else { @@ -552,7 +555,9 @@ func (a *App) setupServer() error { npmProxyHandler := npm.New(a.cache, a.networkClient, npm.Config{ Upstream: npmUpstream, }) - npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler)) + npmProxyMounted := http.StripPrefix("/npm", npmProxyHandler) + a.prewarmFetcher.Mount("npm", npmProxyMounted) + npmProxyWithCDN := a.cdnMiddleware.Handler(npmProxyMounted) a.app.Use("/npm", func(c fiber.Ctx) error { if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() { c.Path(canonical) @@ -574,7 +579,9 @@ func (a *App) setupServer() error { pypiProxyHandler := pypi.New(a.cache, a.networkClient, pypi.Config{ Upstream: pypiUpstream, }) - pypiProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/pypi", pypiProxyHandler)) + pypiProxyMounted := http.StripPrefix("/pypi", pypiProxyHandler) + a.prewarmFetcher.Mount("pypi", pypiProxyMounted) + pypiProxyWithCDN := a.cdnMiddleware.Handler(pypiProxyMounted) if authEnabled { a.app.All("/pypi/*", mwAuth, adaptor.HTTPHandler(pypiProxyWithCDN)) } else { @@ -631,6 +638,9 @@ func (a *App) startWorkers(ctx context.Context) { if a.rescanWorker != nil { go a.rescanWorker.Start(ctx) } + + // Start is a no-op unless prewarming.enabled is set. + a.prewarmWorker.Start(ctx) } func (a *App) Run() error { diff --git a/pkg/app/workers_test.go b/pkg/app/workers_test.go index 1509cb7..b2f8472 100644 --- a/pkg/app/workers_test.go +++ b/pkg/app/workers_test.go @@ -4,6 +4,10 @@ import ( "context" "testing" "time" + + "github.com/lukaszraczylo/gohoarder/pkg/analytics" + "github.com/lukaszraczylo/gohoarder/pkg/config" + "github.com/lukaszraczylo/gohoarder/pkg/prewarming" ) // TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket @@ -36,3 +40,45 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) { t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen) } } + +type recordingFetcher struct{ got chan prewarming.PackageInfo } + +func (f recordingFetcher) Fetch(_ context.Context, pkg prewarming.PackageInfo) error { + f.got <- pkg + return nil +} + +type fixedPopularity struct{} + +func (fixedPopularity) GetTopPackages(int) []analytics.PopularPackage { + return []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}} +} + +func (fixedPopularity) GetTrendingPackages(int) []analytics.PopularPackage { return nil } + +// TestEnabledPrewarmWorkerStartsWithTheApp pins that startWorkers starts the pre-warm loop. +func TestEnabledPrewarmWorkerStartsWithTheApp(t *testing.T) { + a := newTestApp(t, nil) + f := recordingFetcher{got: make(chan prewarming.PackageInfo, 4)} + a.prewarmWorker = prewarming.NewWorker(prewarming.Config{Enabled: true, Fetcher: f, Popularity: fixedPopularity{}}) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + a.startWorkers(ctx) + defer a.prewarmWorker.Stop() + + select { + case pkg := <-f.got: + if pkg.Name != "lodash" { + t.Fatalf("pre-warmed %q, want lodash", pkg.Name) + } + case <-time.After(10 * time.Second): + t.Fatal("pre-warm worker never ran after startWorkers") + } +} + +func TestPrewarmingStaysOffByDefault(t *testing.T) { + if config.Default().Prewarming.Enabled { + t.Fatal("prewarming.enabled must default to false") + } +} diff --git a/pkg/prewarming/proxyfetcher.go b/pkg/prewarming/proxyfetcher.go new file mode 100644 index 0000000..c25b271 --- /dev/null +++ b/pkg/prewarming/proxyfetcher.go @@ -0,0 +1,266 @@ +package prewarming + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "html" + "net/http" + "net/url" + "path" + "regexp" + "strconv" + "strings" + + "github.com/lukaszraczylo/gohoarder/pkg/proxy/pypi" +) + +const ( + registryNPM = "npm" + registryPyPI = "pypi" + registryGo = "go" + + // proxyHost is only a placeholder: the handlers are called in-process and never dial it. + proxyHost = "gohoarder.invalid" + maxMetadataBytes = 64 << 20 +) + +var ( + hrefPattern = regexp.MustCompile(`href="([^"]+)"`) + numericSemVer = regexp.MustCompile(`^\d+(\.\d+)*$`) + distSuffixes = []string{".whl", ".tar.gz", ".zip", ".egg"} +) + +// ProxyFetcher pre-warms through the registry handlers in-process, so artifacts are cached, +// scanned and policy-checked exactly like a client request. +type ProxyFetcher struct { + handlers map[string]http.Handler +} + +// NewProxyFetcher returns a fetcher with no registries mounted. +func NewProxyFetcher() *ProxyFetcher { + return &ProxyFetcher{handlers: make(map[string]http.Handler)} +} + +// Mount registers the handler serving a registry; it must already strip the "/" prefix +// the way the HTTP server mounts it. Mount before the worker starts. +func (f *ProxyFetcher) Mount(registry string, h http.Handler) { + f.handlers[registry] = h +} + +// Fetch resolves the version when it is empty or LatestVersion, then downloads the artifact. +func (f *ProxyFetcher) Fetch(ctx context.Context, pkg PackageInfo) error { + h, ok := f.handlers[pkg.Registry] + if !ok { + return fmt.Errorf("registry %q is not mounted", pkg.Registry) + } + if !safeName(pkg.Name) { + return fmt.Errorf("unsafe package name %q", pkg.Name) + } + latest := pkg.Version == "" || pkg.Version == LatestVersion + switch pkg.Registry { + case registryNPM: + return f.fetchNPM(ctx, h, pkg.Name, pkg.Version, latest) + case registryGo: + return f.fetchGo(ctx, h, pkg.Name, pkg.Version, latest) + case registryPyPI: + return f.fetchPyPI(ctx, h, pkg.Name, pkg.Version, latest) + default: + return fmt.Errorf("unsupported registry %q", pkg.Registry) + } +} + +func safeName(name string) bool { + return name != "" && !strings.ContainsAny(name, "?#\\") && !strings.Contains(name, "..") && !strings.HasPrefix(name, "/") +} + +func (f *ProxyFetcher) fetchNPM(ctx context.Context, h http.Handler, name, version string, latest bool) error { + if latest { + body, err := call(ctx, h, "/npm/"+name, "", true) + if err != nil { + return fmt.Errorf("npm metadata: %w", err) + } + var meta struct { + DistTags map[string]string `json:"dist-tags"` + } + if err := json.Unmarshal(body, &meta); err != nil { + return fmt.Errorf("npm metadata: %w", err) + } + if version = meta.DistTags["latest"]; version == "" { + return fmt.Errorf("npm %s has no latest dist-tag", name) + } + } + bare := name[strings.LastIndex(name, "/")+1:] + _, err := call(ctx, h, "/npm/"+name+"/-/"+bare+"-"+version+".tgz", "", false) + return err +} + +func (f *ProxyFetcher) fetchGo(ctx context.Context, h http.Handler, name, version string, latest bool) error { + if latest { + body, err := call(ctx, h, "/go/"+name+"/@latest", "", true) + if err != nil { + return fmt.Errorf("go latest: %w", err) + } + var info struct{ Version string } + if err := json.Unmarshal(body, &info); err != nil { + return fmt.Errorf("go latest: %w", err) + } + if version = info.Version; version == "" { + return fmt.Errorf("go %s has no latest version", name) + } + } + _, err := call(ctx, h, "/go/"+name+"/@v/"+version+".zip", "", false) + return err +} + +func (f *ProxyFetcher) fetchPyPI(ctx context.Context, h http.Handler, name, version string, latest bool) error { + page, err := call(ctx, h, "/pypi/simple/"+name+"/", "text/html", true) + if err != nil { + return fmt.Errorf("pypi package page: %w", err) + } + link, err := pickPyPIFile(page, version, latest) + if err != nil { + return fmt.Errorf("pypi %s: %w", name, err) + } + if !strings.HasPrefix(link.Path, "/pypi/") { + return fmt.Errorf("pypi %s: link %q is not a proxy path", name, link.Path) + } + _, err = call(ctx, h, link.Path, "", false, link.RawQuery) + return err +} + +type distFile struct { + link *url.URL + version string +} + +// pickPyPIFile chooses one distribution: the wanted version or the highest plain release, +// preferring a wheel over an sdist. +func pickPyPIFile(page []byte, version string, latest bool) (*url.URL, error) { + var wheel, sdist *distFile + for _, m := range hrefPattern.FindAllSubmatch(page, -1) { + u, err := url.Parse(html.UnescapeString(string(m[1]))) + if err != nil { + continue + } + file := path.Base(u.Path) + if !hasDistSuffix(file) { + continue + } + cand := &distFile{link: u, version: pypi.ReleaseVersion(file)} + if latest { + if !numericSemVer.MatchString(cand.version) { + continue + } + } else if cand.version != version { + continue + } + if strings.HasSuffix(file, ".whl") { + wheel = better(wheel, cand, latest) + } else { + sdist = better(sdist, cand, latest) + } + } + for _, c := range []*distFile{wheel, sdist} { + if c != nil { + return c.link, nil + } + } + if latest { + return nil, fmt.Errorf("no plain release file listed") + } + return nil, fmt.Errorf("no file listed for version %q", version) +} + +func better(cur, cand *distFile, latest bool) *distFile { + if cur == nil || (latest && compareVersions(cand.version, cur.version) > 0) { + return cand + } + return cur +} + +func hasDistSuffix(file string) bool { + for _, s := range distSuffixes { + if strings.HasSuffix(file, s) { + return true + } + } + return false +} + +func compareVersions(a, b string) int { + as, bs := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < len(as) || i < len(bs); i++ { + var x, y int + if i < len(as) { + x, _ = strconv.Atoi(as[i]) + } + if i < len(bs) { + y, _ = strconv.Atoi(bs[i]) + } + if x != y { + if x > y { + return 1 + } + return -1 + } + } + return 0 +} + +// call serves a GET through h. It keeps the body only when capture is set and fails on non-200. +func call(ctx context.Context, h http.Handler, p, accept string, capture bool, rawQuery ...string) ([]byte, error) { + u := url.URL{Scheme: "http", Host: proxyHost, Path: p} + if len(rawQuery) > 0 { + u.RawQuery = rawQuery[0] + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, err + } + if accept != "" { + req.Header.Set("Accept", accept) + } + w := &sink{header: make(http.Header), capture: capture} + h.ServeHTTP(w, req) + if w.status == 0 { + w.status = http.StatusOK + } + if w.status != http.StatusOK { + return nil, fmt.Errorf("GET %s: status %d", p, w.status) + } + if w.overflow { + return nil, fmt.Errorf("GET %s: response over %d bytes", p, maxMetadataBytes) + } + return w.buf.Bytes(), nil +} + +// sink is a ResponseWriter that discards artifact bytes so a pre-warm never holds one in memory. +type sink struct { + header http.Header + buf bytes.Buffer + status int + capture bool + overflow bool +} + +func (s *sink) Header() http.Header { return s.header } + +func (s *sink) WriteHeader(code int) { + if s.status == 0 { + s.status = code + } +} + +func (s *sink) Write(b []byte) (int, error) { + s.WriteHeader(http.StatusOK) + if s.capture { + if s.buf.Len()+len(b) > maxMetadataBytes { + s.overflow = true + } else { + s.buf.Write(b) + } + } + return len(b), nil +} diff --git a/pkg/prewarming/proxyfetcher_test.go b/pkg/prewarming/proxyfetcher_test.go new file mode 100644 index 0000000..64738b2 --- /dev/null +++ b/pkg/prewarming/proxyfetcher_test.go @@ -0,0 +1,129 @@ +package prewarming + +import ( + "context" + "net/http" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type routes struct { + resp map[string]string + hits []string + mu sync.Mutex +} + +func (r *routes) ServeHTTP(w http.ResponseWriter, req *http.Request) { + key := req.URL.RequestURI() + r.mu.Lock() + r.hits = append(r.hits, key) + r.mu.Unlock() + body, ok := r.resp[key] + if !ok { + http.NotFound(w, req) + return + } + _, _ = w.Write([]byte(body)) +} + +func fetcherFor(registry string, resp map[string]string) (*ProxyFetcher, *routes) { + rt := &routes{resp: resp} + f := NewProxyFetcher() + f.Mount(registry, rt) + return f, rt +} + +func TestFetchNPMLatestDownloadsTheTarball(t *testing.T) { + f, rt := fetcherFor("npm", map[string]string{ + "/npm/@scope/pkg": `{"dist-tags":{"latest":"2.1.0"}}`, + "/npm/@scope/pkg/-/pkg-2.1.0.tgz": "tarball", + }) + + require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "@scope/pkg", Version: LatestVersion})) + + assert.Equal(t, []string{"/npm/@scope/pkg", "/npm/@scope/pkg/-/pkg-2.1.0.tgz"}, rt.hits) +} + +func TestFetchNPMExplicitVersionSkipsMetadata(t *testing.T) { + f, rt := fetcherFor("npm", map[string]string{"/npm/lodash/-/lodash-4.17.21.tgz": "x"}) + + require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "lodash", Version: "4.17.21"})) + + assert.Equal(t, []string{"/npm/lodash/-/lodash-4.17.21.tgz"}, rt.hits) +} + +func TestFetchGoLatestDownloadsTheZip(t *testing.T) { + f, rt := fetcherFor("go", map[string]string{ + "/go/example.com/m/@latest": `{"Version":"v1.2.3","Time":"2026-01-01T00:00:00Z"}`, + "/go/example.com/m/@v/v1.2.3.zip": "zip", + }) + + require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "go", Name: "example.com/m", Version: LatestVersion})) + + assert.Equal(t, []string{"/go/example.com/m/@latest", "/go/example.com/m/@v/v1.2.3.zip"}, rt.hits) +} + +const pypiPage = ` +a +b +c +d +m +` + +func TestFetchPyPILatestPicksHighestPlainReleaseWheel(t *testing.T) { + f, rt := fetcherFor("pypi", map[string]string{ + "/pypi/simple/req/": pypiPage, + "/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1": "whl", + }) + + require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: LatestVersion})) + + require.Len(t, rt.hits, 2) + assert.Equal(t, "/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1", rt.hits[1]) +} + +func TestFetchPyPIExplicitVersionAndMissingVersion(t *testing.T) { + f, rt := fetcherFor("pypi", map[string]string{ + "/pypi/simple/req/": pypiPage, + "/pypi/req/req-2.9.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fa": "whl", + }) + + require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: "2.9.0"})) + assert.Contains(t, rt.hits[1], "req-2.9.0") + require.ErrorContains(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: "9.9.9"}), "no file listed") +} + +func TestFetchRejectsBadInput(t *testing.T) { + f, rt := fetcherFor("npm", map[string]string{}) + ctx := context.Background() + + require.ErrorContains(t, f.Fetch(ctx, PackageInfo{Registry: "cargo", Name: "x"}), "not mounted") + for _, name := range []string{"", "../etc", "a?b", "/abs", "a#b"} { + assert.ErrorContains(t, f.Fetch(ctx, PackageInfo{Registry: "npm", Name: name}), "unsafe package name", name) + } + assert.Empty(t, rt.hits) +} + +func TestFetchReportsUpstreamFailure(t *testing.T) { + f, _ := fetcherFor("npm", map[string]string{}) + + err := f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "ghost", Version: LatestVersion}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "404") +} + +func TestSinkDiscardsArtifactBytes(t *testing.T) { + big := strings.Repeat("a", 1<<20) + h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(big)) }) + + body, err := call(context.Background(), h, "/x", "", false) + + require.NoError(t, err) + assert.Empty(t, body) +} diff --git a/pkg/prewarming/worker.go b/pkg/prewarming/worker.go index 9c9fdcd..e71d0d4 100644 --- a/pkg/prewarming/worker.go +++ b/pkg/prewarming/worker.go @@ -8,11 +8,28 @@ import ( "time" "github.com/lukaszraczylo/gohoarder/pkg/analytics" - "github.com/lukaszraczylo/gohoarder/pkg/cache" - "github.com/lukaszraczylo/gohoarder/pkg/network" "github.com/rs/zerolog/log" ) +// LatestVersion asks the Fetcher to resolve the newest release itself. +const LatestVersion = "latest" + +const ( + fetchTimeout = 5 * time.Minute + trendingPackages = 50 +) + +// Fetcher pulls an artifact through the proxy path, so it is cached and scanned like a client request. +type Fetcher interface { + Fetch(ctx context.Context, pkg PackageInfo) error +} + +// Popularity ranks packages by recent demand. +type Popularity interface { + GetTopPackages(limit int) []analytics.PopularPackage + GetTrendingPackages(limit int) []analytics.PopularPackage +} + // PackageInfo represents a package to pre-warm type PackageInfo struct { Registry string @@ -23,21 +40,21 @@ type PackageInfo struct { // Worker handles background pre-warming of popular packages type Worker struct { - cache *cache.Manager - analytics *analytics.Engine - client *network.Client - stopChan chan struct{} + popularity Popularity + fetcher Fetcher + cancel context.CancelFunc wg sync.WaitGroup + mu sync.Mutex interval time.Duration maxConcurrent int + topPackages int enabled bool } // Config holds pre-warming worker configuration type Config struct { - CacheManager *cache.Manager - Analytics *analytics.Engine - NetworkClient *network.Client + Popularity Popularity + Fetcher Fetcher Interval time.Duration MaxConcurrent int TopPackages int @@ -57,13 +74,12 @@ func NewWorker(cfg Config) *Worker { } worker := &Worker{ - cache: cfg.CacheManager, - analytics: cfg.Analytics, - client: cfg.NetworkClient, + popularity: cfg.Popularity, + fetcher: cfg.Fetcher, interval: cfg.Interval, maxConcurrent: cfg.MaxConcurrent, + topPackages: cfg.TopPackages, enabled: cfg.Enabled, - stopChan: make(chan struct{}), } if cfg.Enabled { @@ -78,15 +94,26 @@ func NewWorker(cfg Config) *Worker { return worker } -// Start begins the pre-warming worker +// Start begins the pre-warming worker; it is a no-op when disabled or already started. func (w *Worker) Start(ctx context.Context) { if !w.enabled { log.Debug().Msg("Pre-warming worker is disabled, not starting") return } + if w.fetcher == nil || w.popularity == nil { + log.Warn().Msg("Pre-warming worker has no fetcher or popularity source, not starting") + return + } + w.mu.Lock() + defer w.mu.Unlock() + if w.cancel != nil { + return + } + runCtx, cancel := context.WithCancel(ctx) + w.cancel = cancel w.wg.Add(1) - go w.run(ctx) + go w.run(runCtx) log.Info().Msg("Pre-warming worker started") } @@ -97,15 +124,11 @@ func (w *Worker) run(ctx context.Context) { ticker := time.NewTicker(w.interval) defer ticker.Stop() - // Run immediately on start w.prewarmPopularPackages(ctx) for { select { case <-ctx.Done(): - log.Info().Msg("Pre-warming worker stopping due to context cancellation") - return - case <-w.stopChan: log.Info().Msg("Pre-warming worker stopped") return case <-ticker.C: @@ -119,14 +142,14 @@ func (w *Worker) prewarmPopularPackages(ctx context.Context) { log.Info().Msg("Starting pre-warming cycle") // Get popular packages from analytics - popularPackages := w.analytics.GetTopPackages(100) + popularPackages := w.popularity.GetTopPackages(w.topPackages) if len(popularPackages) == 0 { log.Debug().Msg("No popular packages found for pre-warming") return } // Get trending packages for additional candidates - trendingPackages := w.analytics.GetTrendingPackages(50) + trendingPackages := w.popularity.GetTrendingPackages(trendingPackages) // Combine and deduplicate packages := w.combinePackages(popularPackages, trendingPackages) @@ -141,7 +164,7 @@ func (w *Worker) prewarmPopularPackages(ctx context.Context) { workChan <- PackageInfo{ Registry: pkg.Registry, Name: pkg.Name, - Version: "latest", // Pre-warm latest version + Version: LatestVersion, Priority: int(pkg.Downloads), } } @@ -168,13 +191,13 @@ func (w *Worker) processPackages(ctx context.Context, workerID int, workChan <-c case <-ctx.Done(): return default: - w.prewarmPackage(ctx, pkg, workerID) + _ = w.prewarmPackage(ctx, pkg, workerID) // logged inside } } } -// prewarmPackage fetches and caches a single package -func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID int) { +// prewarmPackage fetches a single package through the proxy path +func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID int) error { log.Debug(). Int("worker", workerID). Str("registry", pkg.Registry). @@ -182,60 +205,24 @@ func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID i Str("version", pkg.Version). Msg("Pre-warming package") - // Build URL based on registry - url := w.buildPackageURL(pkg) - if url == "" { - log.Warn(). - Str("registry", pkg.Registry). - Str("package", pkg.Name). - Msg("Cannot build URL for registry") - return - } - - // Fetch package from upstream - reqCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) + reqCtx, cancel := context.WithTimeout(ctx, fetchTimeout) defer cancel() - body, statusCode, err := w.client.Get(reqCtx, url, nil) - if err != nil { + if err := w.fetcher.Fetch(reqCtx, pkg); err != nil { log.Error(). Err(err). + Str("registry", pkg.Registry). Str("package", pkg.Name). - Msg("Failed to fetch package for pre-warming") - return - } - defer func() { _ = body.Close() }() // #nosec G104 -- Cleanup, error not critical - - if statusCode != 200 { - log.Warn(). - Int("status", statusCode). - Str("package", pkg.Name). - Msg("Non-200 response for package") - return + Msg("Failed to pre-warm package") + return err } - // Cache the package - // In a real implementation, this would read the response body and store it log.Info(). + Str("registry", pkg.Registry). Str("package", pkg.Name). Str("version", pkg.Version). - Msg("Successfully pre-warmed package") -} - -// buildPackageURL builds the upstream URL for a package -func (w *Worker) buildPackageURL(pkg PackageInfo) string { - // This is simplified - in reality, each registry has different URL patterns - switch pkg.Registry { - case "npm": - return "https://registry.npmjs.org/" + pkg.Name - case "pypi": - return "https://pypi.org/simple/" + pkg.Name + "/" - case "go": - // Go modules use different URL patterns - return "https://proxy.golang.org/" + pkg.Name + "/@latest" - default: - return "" - } + Msg("Pre-warmed package") + return nil } // combinePackages merges popular and trending packages, removing duplicates @@ -262,22 +249,25 @@ func (w *Worker) combinePackages(popular, trending []analytics.PopularPackage) [ return result } -// Stop gracefully stops the pre-warming worker +// Stop stops the worker and waits for it; it is safe on a nil, disabled or never-started worker. func (w *Worker) Stop() { - if !w.enabled { + if w == nil { return } - - log.Info().Msg("Stopping pre-warming worker") - close(w.stopChan) + w.mu.Lock() + cancel := w.cancel + w.mu.Unlock() + if cancel != nil { + log.Info().Msg("Stopping pre-warming worker") + cancel() + } w.wg.Wait() - log.Info().Msg("Pre-warming worker stopped") } // TriggerPrewarm manually triggers a pre-warming cycle func (w *Worker) TriggerPrewarm(ctx context.Context) { - if !w.enabled { - log.Warn().Msg("Cannot trigger pre-warm: worker is disabled") + if !w.enabled || w.fetcher == nil || w.popularity == nil { + log.Warn().Msg("Cannot trigger pre-warm: worker is disabled or unconfigured") return } @@ -287,8 +277,8 @@ func (w *Worker) TriggerPrewarm(ctx context.Context) { // PrewarmPackage pre-warms a specific package func (w *Worker) PrewarmPackage(ctx context.Context, registry, name, version string) error { - if !w.enabled { - log.Warn().Msg("Pre-warming worker is disabled") + if !w.enabled || w.fetcher == nil { + log.Warn().Msg("Pre-warming worker is disabled or unconfigured") return nil } @@ -299,8 +289,7 @@ func (w *Worker) PrewarmPackage(ctx context.Context, registry, name, version str Priority: 100, } - w.prewarmPackage(ctx, pkg, 0) - return nil + return w.prewarmPackage(ctx, pkg, 0) } // GetStatus returns the current status of the pre-warming worker diff --git a/pkg/prewarming/worker_test.go b/pkg/prewarming/worker_test.go new file mode 100644 index 0000000..b07972f --- /dev/null +++ b/pkg/prewarming/worker_test.go @@ -0,0 +1,134 @@ +package prewarming + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/analytics" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type fakeFetcher struct { + err error + got map[string]PackageInfo + calls chan PackageInfo + mu sync.Mutex +} + +func newFakeFetcher() *fakeFetcher { + return &fakeFetcher{got: map[string]PackageInfo{}, calls: make(chan PackageInfo, 64)} +} + +func (f *fakeFetcher) Fetch(_ context.Context, pkg PackageInfo) error { + f.mu.Lock() + f.got[pkg.Registry+":"+pkg.Name] = pkg + f.mu.Unlock() + f.calls <- pkg + return f.err +} + +type fakePopularity struct { + top, trending []analytics.PopularPackage + topLimit int +} + +func (p *fakePopularity) GetTopPackages(limit int) []analytics.PopularPackage { + p.topLimit = limit + return p.top +} + +func (p *fakePopularity) GetTrendingPackages(int) []analytics.PopularPackage { return p.trending } + +func samplePopularity() *fakePopularity { + return &fakePopularity{ + top: []analytics.PopularPackage{{Registry: "npm", Name: "lodash", Downloads: 9}, {Registry: "go", Name: "example.com/m", Downloads: 3}}, + trending: []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}, {Registry: "pypi", Name: "requests"}}, + } +} + +func TestCycleFetchesEachPopularPackageOnceAsLatest(t *testing.T) { + f, pop := newFakeFetcher(), samplePopularity() + w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: pop, MaxConcurrent: 2, TopPackages: 7}) + + w.prewarmPopularPackages(context.Background()) + + assert.Len(t, f.got, 3, "lodash appears in both lists and must be fetched once") + for _, p := range f.got { + assert.Equal(t, LatestVersion, p.Version) + } + assert.Equal(t, 7, pop.topLimit) +} + +func TestFetchFailureDoesNotStopTheCycle(t *testing.T) { + f := newFakeFetcher() + f.err = errors.New("upstream down") + w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity(), MaxConcurrent: 1}) + + w.prewarmPopularPackages(context.Background()) + + assert.Len(t, f.got, 3) +} + +func TestStartRunsACycleAndStopEndsIt(t *testing.T) { + f := newFakeFetcher() + w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity(), Interval: time.Hour}) + + w.Start(context.Background()) + w.Start(context.Background()) // second start must not spawn a second loop + + select { + case <-f.calls: + case <-time.After(5 * time.Second): + t.Fatal("Start never ran a pre-warm cycle") + } + done := make(chan struct{}) + go func() { w.Stop(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Stop did not return") + } + w.Stop() // idempotent +} + +func TestDisabledWorkerNeverFetches(t *testing.T) { + f := newFakeFetcher() + w := NewWorker(Config{Enabled: false, Fetcher: f, Popularity: samplePopularity()}) + + w.Start(context.Background()) + w.TriggerPrewarm(context.Background()) + require.NoError(t, w.PrewarmPackage(context.Background(), "npm", "lodash", "4.17.21")) + w.Stop() + + assert.Empty(t, f.calls) +} + +func TestStopIsSafeWithoutStart(t *testing.T) { + assert.NotPanics(t, func() { + NewWorker(Config{Enabled: true, Fetcher: newFakeFetcher(), Popularity: samplePopularity()}).Stop() + NewWorker(Config{}).Stop() + (*Worker)(nil).Stop() + }) +} + +func TestStartWithoutFetcherDoesNotRun(t *testing.T) { + w := NewWorker(Config{Enabled: true, Popularity: samplePopularity()}) + w.Start(context.Background()) + w.Stop() + assert.Nil(t, w.cancel) +} + +func TestPrewarmPackagePassesExplicitVersionAndReturnsError(t *testing.T) { + f := newFakeFetcher() + f.err = errors.New("boom") + w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity()}) + + err := w.PrewarmPackage(context.Background(), "npm", "lodash", "4.17.21") + + require.ErrorContains(t, err, "boom") + assert.Equal(t, "4.17.21", f.got["npm:lodash"].Version) +}