Add scheduler, rate limiting and headless mode.
Hard-coded 60s URL and 10s host floors with jitter and per-host backoff, shared between dibs processes through a locked state file. The scheduler shuffles due URLs each round and runs one worker per host; 'dibs --headless' watches and logs JSON.
This commit is contained in:
1 parent
bb010356a0
commit
2175c0e5aa
30 files changed
+1434
-126
No files matched your search
@@ -0,0 +1,147 @@
|
||||
// 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/fsutil"
|
||||
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||
)
|
||||
|
||||
// Hosts and URLs untouched for forgetAfter are dropped, such as URLs removed
|
||||
// from the config.
|
||||
const forgetAfter = 7 * 24 * time.Hour
|
||||
|
||||
type file struct {
|
||||
Hosts map[string]ratelimit.HostState `json:"hosts"`
|
||||
URLs map[string]time.Time `json:"urls"`
|
||||
}
|
||||
|
||||
// Store is the state file. It implements ratelimit.Persister.
|
||||
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 }
|
||||
})
|
||||
}
|
||||
|
||||
// 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{}}
|
||||
|
||||
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{} }
|
||||
|
||||
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) }
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(f, "", " ")
|
||||
if err == nil { err = fsutil.WriteFileAtomic(s.path, data, 0o600) }
|
||||
|
||||
s.err = err
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||
)
|
||||
|
||||
// Two dibs processes, such as a watcher and a `dibs check`, share the floors
|
||||
// through the state file.
|
||||
func TestFloorsHoldAcrossProcesses(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
ctx := context.Background()
|
||||
|
||||
watcher := ratelimit.New(Open(dir))
|
||||
check := ratelimit.New(Open(dir))
|
||||
|
||||
const page = "https://www.amazon.de/dp/B0HMX2FSTF"
|
||||
|
||||
if err := watcher.WaitCheck(ctx, page); err != nil { t.Fatal(err) }
|
||||
|
||||
if d := check.Delay("www.amazon.de"); d < 9*time.Second { t.Errorf("the other process may request again in %s, want about %s", d, ratelimit.HostFloor) }
|
||||
if wait := time.Until(check.URLReady(page)); wait < 59*time.Second { t.Errorf("the other process may check the URL again in %s, want about %s", wait, ratelimit.URLFloor) }
|
||||
|
||||
watcher.Failure("www.amazon.de")
|
||||
if d := check.Delay("www.amazon.de"); d < time.Minute { t.Errorf("the other process ignores the backoff: delay %s", d) }
|
||||
|
||||
if err := Open(dir).Err(); err != nil { t.Error(err) }
|
||||
}
|
||||
|
||||
// stoppedClock never moves, so a limiter that has to wait blocks until its
|
||||
// context ends.
|
||||
type stoppedClock struct{ now time.Time }
|
||||
|
||||
func (c stoppedClock) Now() time.Time { return c.now }
|
||||
func (c stoppedClock) After(time.Duration) <-chan time.Time { return nil }
|
||||
|
||||
// Two processes asking for the same host at the same instant: exactly one
|
||||
// may get it. Without the file lock, both sometimes read "free" before
|
||||
// either writes.
|
||||
func TestReservationsAreExclusive(t *testing.T) {
|
||||
clock := stoppedClock{now: time.Now()}
|
||||
|
||||
for round := range 30 {
|
||||
dir := t.TempDir()
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
granted atomic.Int32
|
||||
)
|
||||
|
||||
for i := range 2 {
|
||||
l := ratelimit.New(Open(dir), ratelimit.WithClock(clock))
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
page := []string{"https://www.amazon.de/dp/B0DK51S84Z", "https://www.amazon.de/dp/B076WS2WJ6"}[i]
|
||||
if l.WaitCheck(ctx, page) == nil { granted.Add(1) }
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if n := granted.Load(); n != 1 {
|
||||
t.Fatalf("round %d: %d processes got the host at once, want 1", round, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user