package cache import ( "EverythingSuckz/fsb/config" "context" "fmt" "io" "os" "path/filepath" "strconv" "time" "github.com/nickalie/go-webpbin" "go.uber.org/zap" "golang.org/x/sync/singleflight" ) var ( Disk *DiskCache ) type DiskCache struct { dir string sf singleflight.Group log *zap.Logger downloadSem chan struct{} } func InitDiskCache(log *zap.Logger) error { dir := config.ValueOf.CacheDir if err := os.MkdirAll(dir, 0755); err != nil { return fmt.Errorf("failed to create cache directory: %w", err) } Disk = &DiskCache{ dir: dir, log: log.Named("DiskCache"), downloadSem: make(chan struct{}, config.ValueOf.MaxConcurrentDownloads), } // Start cache sweeper (every 1 hour, delete files older than 24h) go Disk.startSweeper() Disk.log.Info("Disk cache initialized", zap.String("dir", dir), zap.Int("max_downloads", config.ValueOf.MaxConcurrentDownloads)) return nil } // GetOrDownload returns the path to the cached original file. // If not exists, executes the fetcher under a singleflight lock and a semaphore. func (c *DiskCache) GetOrDownload(ctx context.Context, messageID int, fetcher func() (io.ReadCloser, error)) (string, error) { filename := strconv.Itoa(messageID) path := filepath.Join(c.dir, filename) if c.fileExists(path) { // return directly return path, nil } // fetch with singleflight to avoid duplicated downloads result, err, _ := c.sf.Do(filename, func() (interface{}, error) { if c.fileExists(path) { return path, nil } c.log.Sugar().Infof("Starting download to disk cache: %s", filename) // Acquire semaphore select { case c.downloadSem <- struct{}{}: case <-ctx.Done(): return nil, ctx.Err() } defer func() { <-c.downloadSem }() reader, err := fetcher() if err != nil { return nil, err } defer reader.Close() tempPath := path + ".tmp" fw, err := os.Create(tempPath) if err != nil { return nil, err } if _, err := io.Copy(fw, reader); err != nil { fw.Close() os.Remove(tempPath) return nil, err } fw.Close() if err := os.Rename(tempPath, path); err != nil { os.Remove(tempPath) return nil, err } c.log.Sugar().Infof("Cached file saved: %s", filename) return path, nil }) if err != nil { return "", err } return result.(string), nil } // GetOrConvertWebP returns the path to the cached WebP file. // It uses GetOrDownload first to ensure the original is present, then converts. func (c *DiskCache) GetOrConvertWebP(ctx context.Context, messageID int, fetcher func() (io.ReadCloser, error)) (string, error) { webpFilename := strconv.Itoa(messageID) + "_webp" webpPath := filepath.Join(c.dir, webpFilename) if c.fileExists(webpPath) { return webpPath, nil } result, err, _ := c.sf.Do(webpFilename, func() (interface{}, error) { if c.fileExists(webpPath) { return webpPath, nil } // First, get the original file origPath, err := c.GetOrDownload(ctx, messageID, fetcher) if err != nil { return nil, err } c.log.Sugar().Infof("Starting WebP conversion for: %s", webpFilename) tempPath := webpPath + ".tmp" err = webpbin.NewCWebP(). Quality(uint(config.ValueOf.WebPQuality)). InputFile(origPath). OutputFile(tempPath). Run() if err != nil { return nil, fmt.Errorf("failed to encode webp: %w", err) } if err := os.Rename(tempPath, webpPath); err != nil { os.Remove(tempPath) return nil, err } c.log.Sugar().Infof("WebP cached file saved: %s", webpFilename) return webpPath, nil }) if err != nil { return "", err } return result.(string), nil } func (c *DiskCache) fileExists(path string) bool { info, err := os.Stat(path) if err == nil && !info.IsDir() { return true } return false } func (c *DiskCache) startSweeper() { ticker := time.NewTicker(time.Hour) defer ticker.Stop() for range ticker.C { c.log.Info("Running cache cleanup sweeper") threshold := time.Now().Add(-24 * time.Hour) entries, err := os.ReadDir(c.dir) if err != nil { c.log.Error("Failed to read cache dir for sweep", zap.Error(err)) continue } count := 0 for _, e := range entries { if e.IsDir() { continue } path := filepath.Join(c.dir, e.Name()) info, err := e.Info() if err != nil { continue } if info.ModTime().Before(threshold) { os.Remove(path) count++ } } if count > 0 { c.log.Sugar().Infof("Cleared %d old files from disk cache", count) } } }