package preview import ( "container/list" "context" "crypto/sha256" "encoding/hex" "fmt" "io" "os" "path" "path/filepath" "sort" "strings" "sync" "time" "vcom/internal/vfs" ) // ImageCache keeps downloaded remote images in a local directory, keyed by // (volume, path, size, mtime), evicting least recently used files above a // total size budget (default 200 MiB). type ImageCache struct { dir string max int64 mu sync.Mutex lru *list.List // of *cached, front = most recent byKey map[string]*list.Element total int64 } type cached struct { key string path string size int64 } // NewImageCache uses dir (created 0700). Files already there are kept up to // the budget (oldest removed first), so the cache survives restarts. func NewImageCache(dir string, maxBytes int64) (*ImageCache, error) { if maxBytes <= 0 { maxBytes = 200 << 20 } if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } c := &ImageCache{dir: dir, max: maxBytes, lru: list.New(), byKey: map[string]*list.Element{}} ents, err := os.ReadDir(dir) if err != nil { return nil, err } type old struct { name string size int64 mt time.Time } var files []old for _, e := range ents { fi, err := e.Info() if err != nil || !fi.Mode().IsRegular() { continue } if strings.HasPrefix(e.Name(), ".tmp-") { // an interrupted download _ = os.Remove(filepath.Join(dir, e.Name())) continue } files = append(files, old{e.Name(), fi.Size(), fi.ModTime()}) } sort.Slice(files, func(i, j int) bool { return files[i].mt.After(files[j].mt) }) for _, f := range files { c.add(strings.TrimSuffix(f.name, path.Ext(f.name)), filepath.Join(dir, f.name), f.size) } c.evict() return c, nil } func cacheKey(vol vfs.VolumeID, p string, size int64, mt time.Time) string { h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d\x00%d", vol, p, size, mt.UnixNano()))) return hex.EncodeToString(h[:16]) } // add appends at the back (least recent): used while loading. func (c *ImageCache) add(key, p string, size int64) { c.byKey[key] = c.lru.PushBack(&cached{key: key, path: p, size: size}) c.total += size } func (c *ImageCache) evict() { for c.total > c.max && c.lru.Len() > 1 { e := c.lru.Back() it := e.Value.(*cached) c.lru.Remove(e) delete(c.byKey, it.key) c.total -= it.size _ = os.Remove(it.path) } } // Fetch returns a local copy of p on fsys, downloading it if needed. func (c *ImageCache) Fetch(ctx context.Context, fsys vfs.FS, p string, size int64, mt time.Time) (string, error) { key := cacheKey(fsys.Volume(), p, size, mt) c.mu.Lock() if e, ok := c.byKey[key]; ok { c.lru.MoveToFront(e) lp := e.Value.(*cached).path c.mu.Unlock() return lp, nil } c.mu.Unlock() src, err := fsys.Open(ctx, p) if err != nil { return "", err } defer src.Close() tmp, err := os.CreateTemp(c.dir, ".tmp-*") if err != nil { return "", err } n, err := io.Copy(tmp, &ctxRead{ctx: ctx, r: io.LimitReader(src, size+1)}) if cerr := tmp.Close(); err == nil { err = cerr } if err == nil && n != size { err = fmt.Errorf("%s changed while downloading (%d of %d bytes)", p, n, size) } final := filepath.Join(c.dir, key+strings.ToLower(path.Ext(p))) if err == nil { err = os.Rename(tmp.Name(), final) } if err != nil { _ = os.Remove(tmp.Name()) return "", err } c.mu.Lock() defer c.mu.Unlock() if _, ok := c.byKey[key]; !ok { c.byKey[key] = c.lru.PushFront(&cached{key: key, path: final, size: n}) c.total += n c.evict() } return final, nil } type ctxRead struct { ctx context.Context r io.Reader } func (c *ctxRead) Read(p []byte) (int, error) { if err := c.ctx.Err(); err != nil { return 0, err } return c.r.Read(p) } // Cache keeps the last results (default 32) by (volume, path, size, mtime, // theme, limits), so moving the cursor back and forth does not rebuild. type Cache struct { mu sync.Mutex max int lru *list.List byKey map[resultKey]*list.Element } type resultKey struct { vol vfs.VolumeID path string size int64 mtime int64 theme string maxBytes int64 maxLines, dirLimit int highlight int hidden bool } type resultEntry struct { key resultKey res Result } // NewCache returns a result cache with room for max results (≤ 0 → 32). func NewCache(max int) *Cache { if max <= 0 { max = 32 } return &Cache{max: max, lru: list.New(), byKey: map[resultKey]*list.Element{}} } // Build returns a cached result or builds and caches it. Errors and // cancelled builds are not cached. func (c *Cache) Build(ctx context.Context, req Request) Result { req.defaults() if req.Info.Name == "" { fi, err := req.Loc.FS.Lstat(ctx, req.Loc.Path) if err != nil { return Result{Kind: Error, Err: err, Meta: Metadata{Path: req.Loc.Path}} } req.Info = fi } k := resultKey{req.Loc.FS.Volume(), req.Loc.Path, req.Info.Size, req.Info.ModTime.UnixNano(), req.Theme, req.MaxBytes, req.MaxLines, req.DirLimit, req.HighlightLines, req.ShowHidden} c.mu.Lock() if e, ok := c.byKey[k]; ok { c.lru.MoveToFront(e) r := e.Value.(*resultEntry).res c.mu.Unlock() return r } c.mu.Unlock() r := Build(ctx, req) if r.Err != nil || r.Kind == Error { return r } c.mu.Lock() defer c.mu.Unlock() if _, ok := c.byKey[k]; !ok { c.byKey[k] = c.lru.PushFront(&resultEntry{key: k, res: r}) for c.lru.Len() > c.max { e := c.lru.Back() c.lru.Remove(e) delete(c.byKey, e.Value.(*resultEntry).key) } } return r }