Initial commit: LastRecc discovery feed and weekly engine
This commit is contained in:
40 files changed
+6972
No files matched your search
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
type JSONCache struct {
|
||||
Dir string
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
func (c JSONCache) path(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return filepath.Join(c.Dir, hex.EncodeToString(sum[:])+".json")
|
||||
}
|
||||
|
||||
func (c JSONCache) Get(key string, out any) bool {
|
||||
path := c.path(key)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || time.Since(info.ModTime()) > c.TTL {
|
||||
return false
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return json.Unmarshal(data, out) == nil
|
||||
}
|
||||
|
||||
func (c JSONCache) GetBytes(key string) ([]byte, bool) {
|
||||
path := c.path(key)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || time.Since(info.ModTime()) > c.TTL {
|
||||
return nil, false
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
return data, err == nil
|
||||
}
|
||||
|
||||
func (c JSONCache) Set(key string, value any) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.SetBytes(key, data)
|
||||
}
|
||||
|
||||
func (c JSONCache) SetBytes(key string, data []byte) error {
|
||||
return WriteFileAtomic(c.path(key), data)
|
||||
}
|
||||
|
||||
func LoadJSON(path string, out any) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(data, out)
|
||||
}
|
||||
|
||||
func SaveJSON(path string, value any) error {
|
||||
data, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return WriteFileAtomic(path, data)
|
||||
}
|
||||
|
||||
func WriteFileAtomic(path string, data []byte) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer func() {
|
||||
_ = os.Remove(tmp)
|
||||
}()
|
||||
if _, err := f.Write(data); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
func Fresh(path string, ttl time.Duration) bool {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return time.Since(info.ModTime()) <= ttl
|
||||
}
|
||||
Reference in new issue
Block a user