Files
dibs/internal/state/state.go
T
Overlord 8f0eda5d4d Add alerts, currency conversion and notifications.
Items fire when a page is available from an accepted seller at or below
max_price, converted with the ECB's daily rates when the page uses
another currency. A per-item cooldown, kept in the state file, holds
back repeat alerts unless the price drops. Alerts go to Discord, ntfy
and JSON webhooks with retries, and to the desktop;
'dibs notify test' sends a sample.
2026-10-14 11:55:27 +02:00

185 lines
4.5 KiB
Go

// Package state keeps what dibs must remember between runs in a JSON file in
// the user config dir. Every dibs process shares it, so a `dibs check` run
// next to a running watcher still respects the rate limits.
package state
import (
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/fsutil"
"git.security-command.org/Overlord/dibs/internal/fx"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
)
// Hosts, URLs and alerts untouched for forgetAfter are dropped, such as URLs
// removed from the config. An alert is kept for as long as the longest
// cooldown lasts.
const forgetAfter = config.MaxCooldown
type file struct {
Hosts map[string]ratelimit.HostState `json:"hosts"`
URLs map[string]time.Time `json:"urls"`
Alerts map[string]alert.Sent `json:"alerts,omitempty"`
FX *fx.Rates `json:"fx,omitempty"`
}
// Store is the state file. It implements ratelimit.Persister, alert.Store
// and fx.Store.
type Store struct {
path string
lock string
mu sync.Mutex
err error
}
// Dir is the directory dibs keeps its files in.
func Dir() (string, error) {
dir, err := os.UserConfigDir()
if err != nil { return "", err }
return filepath.Join(dir, "dibs"), nil
}
// Open returns the store at dir/state.json. The file is created on the first
// write.
func Open(dir string) *Store {
return &Store{path: filepath.Join(dir, "state.json"), lock: filepath.Join(dir, "state.lock")}
}
// Err returns the last error reading or writing the file, if any. The
// limiter still works in memory without the file.
func (s *Store) Err() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.err
}
// Lock takes the lock shared by every dibs process using this directory.
// When that fails, the limiter carries on with only its in-process lock.
func (s *Store) Lock() func() {
unlock, err := fsutil.Lock(s.lock)
if err != nil {
s.mu.Lock()
s.err = err
s.mu.Unlock()
return func() {}
}
return unlock
}
func (s *Store) LoadHost(host string) (ratelimit.HostState, bool) {
s.mu.Lock()
defer s.mu.Unlock()
h, ok := s.read().Hosts[host]
return h, ok
}
// StoreHost replaces the state of host. The limiter has already merged in
// what other processes stored.
func (s *Store) StoreHost(host string, h ratelimit.HostState) {
s.update(func(f *file) { f.Hosts[host] = h })
}
func (s *Store) LoadURL(url string) (time.Time, bool) {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.read().URLs[url]
return t, ok
}
func (s *Store) StoreURL(url string, last time.Time) {
s.update(func(f *file) {
if last.After(f.URLs[url]) { f.URLs[url] = last }
})
}
func (s *Store) LoadAlert(item string) (alert.Sent, bool) {
s.mu.Lock()
defer s.mu.Unlock()
a, ok := s.read().Alerts[item]
return a, ok
}
func (s *Store) StoreAlert(item string, a alert.Sent) {
s.update(func(f *file) { f.Alerts[item] = a })
}
func (s *Store) LoadRates() (*fx.Rates, bool) {
s.mu.Lock()
defer s.mu.Unlock()
r := s.read().FX
return r, r != nil
}
func (s *Store) StoreRates(r *fx.Rates) {
s.update(func(f *file) {
if f.FX == nil || r.Fetched.After(f.FX.Fetched) { f.FX = r }
})
}
// read returns the file's contents, or empty state if there is none yet.
// Callers hold mu.
func (s *Store) read() *file {
f := &file{Hosts: map[string]ratelimit.HostState{}, URLs: map[string]time.Time{}, Alerts: map[string]alert.Sent{}}
data, err := os.ReadFile(s.path)
switch {
case errors.Is(err, fs.ErrNotExist):
return f
case err != nil:
s.err = err
return f
}
if err := json.Unmarshal(data, f); err != nil {
s.err = err
return f
}
if f.Hosts == nil { f.Hosts = map[string]ratelimit.HostState{} }
if f.URLs == nil { f.URLs = map[string]time.Time{} }
if f.Alerts == nil { f.Alerts = map[string]alert.Sent{} }
return f
}
func (s *Store) update(change func(f *file)) {
s.mu.Lock()
defer s.mu.Unlock()
f := s.read()
change(f)
cutoff := time.Now().Add(-forgetAfter)
for host, h := range f.Hosts {
if h.Next.Before(cutoff) && h.BackoffUntil.Before(cutoff) { delete(f.Hosts, host) }
}
for url, t := range f.URLs {
if t.Before(cutoff) { delete(f.URLs, url) }
}
for item, a := range f.Alerts {
if a.Time.Before(cutoff) { delete(f.Alerts, item) }
}
data, err := json.MarshalIndent(f, "", " ")
if err == nil { err = fsutil.WriteFileAtomic(s.path, data, 0o600) }
s.err = err
}