Files
dibs/internal/state/state_test.go
T
Overlord 2175c0e5aa 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.
2026-10-14 09:04:15 +02:00

78 lines
2.2 KiB
Go

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)
}
}
}