navidrome/core/artwork/cache_warmer.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

64 lines
1.3 KiB
Go
Raw Normal View History

package artwork
2022-12-23 18:28:22 +01:00
import (
"context"
"fmt"
"io"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/pl"
)
type CacheWarmer interface {
2022-12-23 18:28:22 +01:00
PreCache(artID model.ArtworkID)
}
func NewCacheWarmer(artwork Artwork) CacheWarmer {
2022-12-23 18:28:22 +01:00
// If image cache is disabled, return a NOOP implementation
if conf.Server.ImageCacheSize == "0" {
return &noopCacheWarmer{}
}
a := &cacheWarmer{
2022-12-23 18:28:22 +01:00
artwork: artwork,
input: make(chan string),
}
go a.run(context.TODO())
return a
}
type cacheWarmer struct {
2022-12-23 18:28:22 +01:00
artwork Artwork
input chan string
}
func (a *cacheWarmer) PreCache(artID model.ArtworkID) {
2022-12-23 18:28:22 +01:00
a.input <- artID.String()
}
func (a *cacheWarmer) run(ctx context.Context) {
2022-12-23 18:28:22 +01:00
errs := pl.Sink(ctx, 2, a.input, a.doCacheImage)
for err := range errs {
log.Warn(ctx, "Error warming cache", err)
}
}
func (a *cacheWarmer) doCacheImage(ctx context.Context, id string) error {
2022-12-27 18:54:51 +01:00
r, _, err := a.artwork.Get(ctx, id, 0)
2022-12-23 18:28:22 +01:00
if err != nil {
return fmt.Errorf("error cacheing id='%s': %w", id, err)
}
defer r.Close()
_, err = io.Copy(io.Discard, r)
if err != nil {
return err
}
return nil
}
type noopCacheWarmer struct{}
func (a *noopCacheWarmer) PreCache(id model.ArtworkID) {}