2017-06-27 20:49:53 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"time"
|
2023-10-15 11:19:01 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
cacheDirMode = 0o700
|
|
|
|
cacheFileMode = 0o600
|
2017-06-27 20:49:53 +00:00
|
|
|
)
|
|
|
|
|
2018-06-17 13:19:28 +00:00
|
|
|
func filesystemCache(opts generateMapConfig) (io.ReadCloser, error) {
|
|
|
|
cacheKey := opts.getCacheKey()
|
2017-06-27 20:49:53 +00:00
|
|
|
cacheFileName := path.Join(cfg.CacheDir, cacheKey[0:2], cacheKey+".png")
|
|
|
|
|
|
|
|
if info, err := os.Stat(cacheFileName); err == nil && info.ModTime().Add(cfg.ForceCache).After(time.Now()) {
|
2023-10-15 11:19:01 +00:00
|
|
|
f, err := os.Open(cacheFileName) //#nosec:G304 // Intended to open a variable file
|
|
|
|
return f, errors.Wrap(err, "opening file")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// No cache hit, generate a new map
|
2018-06-17 13:19:28 +00:00
|
|
|
mapReader, err := generateMap(opts)
|
2017-06-27 20:49:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := new(bytes.Buffer)
|
2017-06-27 22:59:06 +00:00
|
|
|
if _, err = io.Copy(buf, mapReader); err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
return nil, errors.Wrap(err, "writing file")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
if err = os.MkdirAll(path.Dir(cacheFileName), cacheDirMode); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "creating cache dir")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
if err = os.WriteFile(cacheFileName, buf.Bytes(), cacheFileMode); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "writing cache file")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
return io.NopCloser(buf), err
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|