Debian Codegraph @

cache/filecache/filecache.go

raw
1 // Copyright 2026 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package filecache
15
16 import (
17 "bytes"
18 "errors"
19 "fmt"
20 "io"
21 "os"
22 "path/filepath"
23 "strings"
24 "sync"
25 "time"
26
27 "github.com/gohugoio/httpcache"
28 "github.com/gohugoio/hugo/common/hugio"
29 "github.com/gohugoio/hugo/hugofs"
30
31 "github.com/gohugoio/hugo/helpers"
32
33 "github.com/BurntSushi/locker"
34 "github.com/bep/helpers/maphelpers"
35 "github.com/spf13/afero"
36 )
37
38 // ErrFatal can be used to signal an unrecoverable error.
39 var ErrFatal = errors.New("fatal filecache error")
40
41 const (
42 FilecacheRootDirname = "filecache"
43 )
44
45 // Cache caches a set of files in a directory. This is usually a file on
46 // disk, but since this is backed by an Afero file system, it can be anything.
47 type Cache struct {
48 Fs afero.Fs
49
50 cfg FileCacheConfig
51
52 entryLocker *lockTracker
53
54 initOnce sync.Once
55 isInited bool
56 initErr error
57 }
58
59 type lockTracker struct {
60 seen *maphelpers.ConcurrentSet[string]
61
62 *locker.Locker
63 }
64
65 // Lock tracks the ids in use. We use this information to do garbage collection
66 // after a Hugo build.
67 func (l *lockTracker) Lock(id string) {
68 l.seen.AddIfAbsent(id)
69 l.Locker.Lock(id)
70 }
71
72 // ItemInfo contains info about a cached file.
73 type ItemInfo struct {
74 // This is the file's name relative to the cache's filesystem.
75 Name string
76 }
77
78 // NewCache creates a new file cache with the given filesystem and max age.
79 func NewCache(fs afero.Fs, cfg FileCacheConfig) *Cache {
80 if err := cfg.init(); err != nil {
81 panic(fmt.Sprintf("invalid cache config: %s", err))
82 }
83
84 return &Cache{
85 Fs: fs,
86 entryLocker: &lockTracker{Locker: locker.NewLocker(), seen: maphelpers.NewConcurrentSet[string]()},
87 cfg: cfg,
88 }
89 }
90
91 // lockedFile is a file with a lock that is released on Close.
92 type lockedFile struct {
93 afero.File
94 unlock func()
95 }
96
97 func (l *lockedFile) Close() error {
98 defer l.unlock()
99 return l.File.Close()
100 }
101
102 func (c *Cache) init() error {
103 if c == nil {
104 panic("cache is nil")
105 }
106
107 c.initOnce.Do(func() {
108 c.isInited = true
109 // Create the base dir if it does not exist.
110 if err := c.Fs.MkdirAll("", 0o777); err != nil && !os.IsExist(err) {
111 err = fmt.Errorf("failled to create base cache directory: %s", err)
112 c.initErr = err
113 }
114 })
115 return c.initErr
116 }
117
118 // WriteCloser returns a transactional writer into the cache.
119 // It's important that it's closed when done.
120 func (c *Cache) WriteCloser(id string) (ItemInfo, io.WriteCloser, error) {
121 if err := c.init(); err != nil {
122 return ItemInfo{}, nil, err
123 }
124
125 id = cleanID(id)
126 c.entryLocker.Lock(id)
127
128 info := ItemInfo{Name: id}
129
130 f, err := helpers.OpenFileForWriting(c.Fs, id)
131 if err != nil {
132 c.entryLocker.Unlock(id)
133 return info, nil, err
134 }
135
136 return info, &lockedFile{
137 File: f,
138 unlock: func() { c.entryLocker.Unlock(id) },
139 }, nil
140 }
141
142 // ReadOrCreate tries to lookup the file in cache.
143 // If found, it is passed to read and then closed.
144 // If not found a new file is created and passed to create, which should close
145 // it when done.
146 func (c *Cache) ReadOrCreate(id string,
147 read func(info ItemInfo, r io.ReadSeeker) error,
148 create func(info ItemInfo, w io.WriteCloser) error,
149 ) (info ItemInfo, err error) {
150 if err := c.init(); err != nil {
151 return ItemInfo{}, err
152 }
153
154 id = cleanID(id)
155
156 c.entryLocker.Lock(id)
157 defer c.entryLocker.Unlock(id)
158
159 info = ItemInfo{Name: id}
160
161 if r := c.getOrRemove(id); r != nil {
162 err = read(info, r)
163 defer r.Close()
164 if err == nil || err == ErrFatal {
165 // See https://github.com/gohugoio/hugo/issues/6401
166 // To recover from file corruption we handle read errors
167 // as the cache item was not found.
168 // Any file permission issue will also fail in the next step.
169 return
170 }
171 }
172
173 f, err := helpers.OpenFileForWriting(c.Fs, id)
174 if err != nil {
175 return
176 }
177
178 err = create(info, f)
179
180 return
181 }
182
183 // NamedLock locks the given id. The lock is released when the returned function is called.
184 func (c *Cache) NamedLock(id string) func() {
185 id = cleanID(id)
186 c.entryLocker.Lock(id)
187 return func() {
188 c.entryLocker.Unlock(id)
189 }
190 }
191
192 // GetOrCreate tries to get the file with the given id from cache. If not found or expired, create will
193 // be invoked and the result cached.
194 // This method is protected by a named lock using the given id as identifier.
195 func (c *Cache) GetOrCreate(id string, create func() (io.ReadCloser, error)) (ItemInfo, io.ReadCloser, error) {
196 if err := c.init(); err != nil {
197 return ItemInfo{}, nil, err
198 }
199 id = cleanID(id)
200
201 c.entryLocker.Lock(id)
202 defer c.entryLocker.Unlock(id)
203
204 info := ItemInfo{Name: id}
205
206 if r := c.getOrRemove(id); r != nil {
207 return info, r, nil
208 }
209
210 var (
211 r io.ReadCloser
212 err error
213 )
214
215 r, err = create()
216 if err != nil {
217 return info, nil, err
218 }
219
220 if c.cfg.MaxAge == 0 {
221 // No caching.
222 return info, hugio.ToReadCloser(r), nil
223 }
224
225 var buff bytes.Buffer
226 return info,
227 hugio.ToReadCloser(&buff),
228 c.writeReader(id, io.TeeReader(r, &buff))
229 }
230
231 // AbsFilenameFromID returns the filename for the given id in the cache.
232 // This will be an absolute path.
233 func (c *Cache) AbsFilenameFromID(id string) string {
234 return filepath.Join(c.cfg.DirCompiled, cleanID(id))
235 }
236
237 // GetOrCreateInfo tries to get the item info with the given id from cache. If not found or expired, create will
238 // be invoked with the id. The create function is expected to create the cache item with the given id. The returned ItemInfo will have the id as Name.
239 // This method is protected by a named lock using the given id as identifier.
240 func (c *Cache) GetOrCreateInfo(id string, create func(id string) error) (ItemInfo, error) {
241 if err := c.init(); err != nil {
242 return ItemInfo{}, err
243 }
244
245 id = cleanID(id)
246
247 c.entryLocker.Lock(id)
248 defer c.entryLocker.Unlock(id)
249
250 info := ItemInfo{Name: id}
251
252 if !c.removeIfNeeded(id) {
253 // The file exists and is not expired, so we consider it a cache hit.
254 return info, nil
255 }
256
257 if err := create(id); err != nil {
258 c.remove(id)
259 return info, err
260 }
261
262 return info, nil
263 }
264
265 func (c *Cache) writeReader(id string, r io.Reader) error {
266 dir := filepath.Dir(id)
267 if dir != "" {
268 _ = c.Fs.MkdirAll(dir, 0o777)
269 }
270 f, err := c.Fs.Create(id)
271 if err != nil {
272 return err
273 }
274 defer f.Close()
275
276 _, _ = io.Copy(f, r)
277
278 return nil
279 }
280
281 // GetOrCreateBytes is the same as GetOrCreate, but produces a byte slice.
282 func (c *Cache) GetOrCreateBytes(id string, create func() ([]byte, error)) (ItemInfo, []byte, error) {
283 if err := c.init(); err != nil {
284 return ItemInfo{}, nil, err
285 }
286 id = cleanID(id)
287
288 c.entryLocker.Lock(id)
289 defer c.entryLocker.Unlock(id)
290
291 info := ItemInfo{Name: id}
292
293 if r := c.getOrRemove(id); r != nil {
294 defer r.Close()
295 b, err := io.ReadAll(r)
296 return info, b, err
297 }
298
299 var (
300 b []byte
301 err error
302 )
303
304 b, err = create()
305 if err != nil {
306 return info, nil, err
307 }
308
309 if c.cfg.MaxAge == 0 {
310 return info, b, nil
311 }
312
313 if err := c.writeReader(id, bytes.NewReader(b)); err != nil {
314 return info, nil, err
315 }
316
317 return info, b, nil
318 }
319
320 // SetBytes sets the file content with the given id in the cache.
321 func (c *Cache) SetBytes(id string, data []byte) error {
322 if err := c.init(); err != nil {
323 return err
324 }
325 id = cleanID(id)
326
327 c.entryLocker.Lock(id)
328 defer c.entryLocker.Unlock(id)
329
330 if c.cfg.MaxAge == 0 {
331 // No caching.
332 return nil
333 }
334
335 return c.writeReader(id, bytes.NewReader(data))
336 }
337
338 // GetBytes gets the file content with the given id from the cache, nil if none found.
339 func (c *Cache) GetBytes(id string) ([]byte, error) {
340 _, b, err := c.GetItemBytes(id)
341 return b, err
342 }
343
344 // GetItemBytes gets the ItemInfo and file content with the given id from the cache, nil if none found.
345 func (c *Cache) GetItemBytes(id string) (ItemInfo, []byte, error) {
346 if err := c.init(); err != nil {
347 return ItemInfo{}, nil, err
348 }
349 id = cleanID(id)
350
351 c.entryLocker.Lock(id)
352 defer c.entryLocker.Unlock(id)
353
354 info := ItemInfo{Name: id}
355
356 if r := c.getOrRemove(id); r != nil {
357 defer r.Close()
358 b, err := io.ReadAll(r)
359 return info, b, err
360 }
361
362 return info, nil, nil
363 }
364
365 // Get gets the file with the given id from the cache, nil if none found.
366 func (c *Cache) Get(id string) (ItemInfo, io.ReadCloser, error) {
367 if err := c.init(); err != nil {
368 return ItemInfo{}, nil, err
369 }
370 id = cleanID(id)
371
372 c.entryLocker.Lock(id)
373 defer c.entryLocker.Unlock(id)
374
375 info := ItemInfo{Name: id}
376
377 r := c.getOrRemove(id)
378
379 return info, r, nil
380 }
381
382 // removeIfNeeded checks if the file with the given id should be re-created.
383 func (c *Cache) removeIfNeeded(id string) bool {
384 if c.cfg.MaxAge == 0 {
385 // No caching, remove.
386 c.remove(id)
387 return true
388 }
389 if removed, err := c.removeIfExpired(id); err != nil || removed {
390 return true
391 }
392 return false
393 }
394
395 // getOrRemove gets the file with the given id. If it's expired, it will
396 // be removed.
397 func (c *Cache) getOrRemove(id string) hugio.ReadSeekCloser {
398 if c.cfg.MaxAge == 0 {
399 // No caching.
400 return nil
401 }
402
403 if removed, err := c.removeIfExpired(id); err != nil || removed {
404 return nil
405 }
406
407 f, err := c.Fs.Open(id)
408 if err != nil {
409 return nil
410 }
411
412 return f
413 }
414
415 func (c *Cache) getBytesAndRemoveIfExpired(id string) ([]byte, bool) {
416 if c.cfg.MaxAge == 0 {
417 // No caching.
418 return nil, false
419 }
420
421 f, err := c.Fs.Open(id)
422 if err != nil {
423 return nil, false
424 }
425 defer f.Close()
426
427 b, err := io.ReadAll(f)
428 if err != nil {
429 return nil, false
430 }
431
432 removed, err := c.removeIfExpired(id)
433 if err != nil {
434 return nil, false
435 }
436
437 return b, removed
438 }
439
440 func (c *Cache) removeIfExpired(id string) (bool, error) {
441 if c.cfg.MaxAge <= 0 {
442 return false, nil
443 }
444
445 fi, err := c.Fs.Stat(id)
446 if err != nil {
447 return false, err
448 }
449
450 if c.isExpired(fi.ModTime()) {
451 c.remove(id)
452 return true, nil
453 }
454
455 return false, nil
456 }
457
458 func (c *Cache) remove(id string) {
459 if c.cfg.entryIsDir {
460 c.Fs.RemoveAll(id)
461 } else {
462 c.Fs.Remove(id)
463 }
464 }
465
466 func (c *Cache) isExpired(modTime time.Time) bool {
467 if c.cfg.MaxAge < 0 {
468 return false
469 }
470
471 // Note the use of time.Since here.
472 // We cannot use Hugo's global Clock for this.
473 return c.cfg.MaxAge == 0 || time.Since(modTime) > c.cfg.MaxAge
474 }
475
476 // For testing
477 func (c *Cache) GetString(id string) string {
478 id = cleanID(id)
479
480 c.entryLocker.Lock(id)
481 defer c.entryLocker.Unlock(id)
482
483 f, err := c.Fs.Open(id)
484 if err != nil {
485 return ""
486 }
487 defer f.Close()
488
489 b, _ := io.ReadAll(f)
490 return string(b)
491 }
492
493 // Caches is a named set of caches.
494 type Caches map[string]*Cache
495
496 func (f Caches) SetResourceFs(fs afero.Fs) {
497 for _, c := range f {
498 if c.cfg.IsResourceDir {
499 if c.isInited {
500 panic("cannot set resource fs after init")
501 }
502 c.Fs = hugofs.NewBasePathFs(fs, c.cfg.DirCompiled)
503 }
504 }
505 }
506
507 // Get gets a named cache, nil if none found.
508 func (f Caches) Get(name string) *Cache {
509 return f[strings.ToLower(name)]
510 }
511
512 // NewCaches creates a new set of file caches from the given
513 // configuration.
514 func NewCaches(dcfg Configs, sourceFs afero.Fs) (Caches, error) {
515 fs := sourceFs
516
517 m := make(Caches)
518 for k, v := range dcfg {
519 var cfs afero.Fs
520 if v.IsResourceDir {
521 cfs = nil // Set later. TODO(bep) this needs to be cleanded up.
522 } else {
523 cfs = hugofs.NewBasePathFs(fs, v.DirCompiled)
524 }
525
526 c := NewCache(cfs, v)
527
528 m[k] = c
529 }
530
531 return m, nil
532 }
533
534 func cleanID(name string) string {
535 return strings.TrimPrefix(filepath.Clean(name), helpers.FilePathSeparator)
536 }
537
538 // AsHTTPCache returns an httpcache.Cache implementation for this file cache.
539 // Note that none of the methods are protected by named locks, so you need to make sure
540 // to do that in your own code.
541 func (c *Cache) AsHTTPCache() httpcache.Cache {
542 return &httpCache{c: c}
543 }
544
545 type httpCache struct {
546 c *Cache
547 }
548
549 func (h *httpCache) Get(id string) (resp []byte, ok bool) {
550 id = cleanID(id)
551 b, removed := h.c.getBytesAndRemoveIfExpired(id)
552
553 return b, !removed
554 }
555
556 func (h *httpCache) Set(id string, resp []byte) {
557 if h.c.cfg.MaxAge == 0 {
558 return
559 }
560
561 id = cleanID(id)
562
563 if err := h.c.writeReader(id, bytes.NewReader(resp)); err != nil {
564 panic(err)
565 }
566 }
567
568 func (h *httpCache) Delete(key string) {
569 h.c.Fs.Remove(key)
570 }