175 lines
4.0 KiB
Go
175 lines
4.0 KiB
Go
// Package state persists the Qobuz match cache and provides a run lock.
|
|
package state
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
|
|
"applesync/internal/model"
|
|
)
|
|
|
|
// ExpandPath expands a leading ~ using the current user's home directory.
|
|
func ExpandPath(path string) string {
|
|
if path == "" || path[0] != '~' {
|
|
return path
|
|
}
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return path
|
|
}
|
|
if path == "~" {
|
|
return home
|
|
}
|
|
if len(path) > 1 && path[1] == '/' {
|
|
return filepath.Join(home, path[2:])
|
|
}
|
|
return path
|
|
}
|
|
|
|
// WriteFileAtomic writes data to path via a temporary file and rename.
|
|
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)
|
|
}
|
|
|
|
// MatchCache is a concurrency-safe JSON cache of Apple album -> Qobuz match
|
|
// lookups.
|
|
type MatchCache struct {
|
|
mu sync.Mutex
|
|
path string
|
|
entries map[string]model.CachedMatch
|
|
dirty bool
|
|
}
|
|
|
|
type cacheFile struct {
|
|
Version int `json:"version"`
|
|
Entries map[string]model.CachedMatch `json:"entries"`
|
|
}
|
|
|
|
// LoadMatchCache loads (or creates) the cache at path.
|
|
func LoadMatchCache(path string) (*MatchCache, error) {
|
|
c := &MatchCache{path: path, entries: map[string]model.CachedMatch{}}
|
|
data, err := os.ReadFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return c, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var file cacheFile
|
|
if err := json.Unmarshal(data, &file); err != nil {
|
|
// A corrupt cache should not stop a sync; start fresh.
|
|
return c, nil
|
|
}
|
|
if file.Entries != nil {
|
|
c.entries = file.Entries
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// Get returns a cached entry if it is still fresh.
|
|
func (c *MatchCache) Get(appleAlbumID string) (model.CachedMatch, bool) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
entry, ok := c.entries[appleAlbumID]
|
|
if !ok {
|
|
return model.CachedMatch{}, false
|
|
}
|
|
ttl := 90 * 24 * time.Hour
|
|
if entry.Match == nil {
|
|
ttl = 7 * 24 * time.Hour
|
|
}
|
|
if time.Since(entry.CheckedAt) > ttl {
|
|
return model.CachedMatch{}, false
|
|
}
|
|
return entry, true
|
|
}
|
|
|
|
// Put stores an entry and marks the cache dirty.
|
|
func (c *MatchCache) Put(appleAlbumID string, entry model.CachedMatch) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.entries[appleAlbumID] = entry
|
|
c.dirty = true
|
|
}
|
|
|
|
// Save writes the cache atomically if it changed.
|
|
func (c *MatchCache) Save() error {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if !c.dirty {
|
|
return nil
|
|
}
|
|
data, err := json.MarshalIndent(cacheFile{Version: 1, Entries: c.entries}, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := WriteFileAtomic(c.path, data); err != nil {
|
|
return err
|
|
}
|
|
c.dirty = false
|
|
return nil
|
|
}
|
|
|
|
// Lock is an exclusive run lock.
|
|
type Lock struct {
|
|
path string
|
|
}
|
|
|
|
// AcquireLock creates an exclusive lock in dir. A lock older than 24 hours is
|
|
// considered stale and is replaced.
|
|
func AcquireLock(dir string) (*Lock, error) {
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
path := filepath.Join(dir, "applesync.lock")
|
|
for attempt := 0; attempt < 2; attempt++ {
|
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
|
|
if err == nil {
|
|
_, _ = fmt.Fprintf(f, "pid=%d\nstarted=%s\n", os.Getpid(), time.Now().Format(time.RFC3339))
|
|
_ = f.Close()
|
|
return &Lock{path: path}, nil
|
|
}
|
|
if !errors.Is(err, os.ErrExist) {
|
|
return nil, err
|
|
}
|
|
info, statErr := os.Stat(path)
|
|
if statErr == nil && time.Since(info.ModTime()) > 24*time.Hour {
|
|
_ = os.Remove(path)
|
|
continue
|
|
}
|
|
data, _ := os.ReadFile(path)
|
|
return nil, fmt.Errorf("another applesync run holds the lock %s (%s)", path, strconv.Quote(string(data)))
|
|
}
|
|
return nil, fmt.Errorf("could not acquire lock %s", path)
|
|
}
|
|
|
|
// Release removes the lock file.
|
|
func (l *Lock) Release() {
|
|
if l != nil {
|
|
_ = os.Remove(l.path)
|
|
}
|
|
}
|