File size: 4,498 Bytes
514d2ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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)
		}
	}
}