feat(jobs): add durable due-time job runner with leases

This commit is contained in:
shira committed 2026-10-06 14:29:23 +03:00
1 parent 7e80c8ad2a
commit 008254e44a
39 files changed
+4909 -43

No files matched your search

View File
Whitespace-only changes.
+51
View File
@@ -0,0 +1,51 @@
// Package testutil holds small test helpers that several backend packages
// share. It has no production callers.
package testutil
import (
"sync"
"time"
)
// FakeClock is a manual application clock for tests. Code under test takes
// its Now method as its clock function, and the test moves time with
// Advance or Set instead of waiting, so a deadline days away is checked in
// microseconds. It is safe for concurrent use, so a worker goroutine can
// read it while the test moves it.
type FakeClock struct {
mu sync.Mutex
now time.Time
}
// NewFakeClock returns a clock that stands at start until it is moved.
func NewFakeClock(start time.Time) *FakeClock {
return &FakeClock{now: start}
}
// Now returns the current fake time. Its signature matches the
// func() time.Time clocks that the backend injects.
func (clock *FakeClock) Now() time.Time {
clock.mu.Lock()
defer clock.mu.Unlock()
return clock.now
}
// Advance moves the clock forward by step and returns the new time. A
// negative step panics, because application clocks are expected to be
// monotonic in tests; use Set to model a clock that jumps back.
func (clock *FakeClock) Advance(step time.Duration) time.Time {
if step < 0 {
panic("testutil.FakeClock.Advance - step must not be negative")
}
clock.mu.Lock()
defer clock.mu.Unlock()
clock.now = clock.now.Add(step)
return clock.now
}
// Set moves the clock to now, forward or back.
func (clock *FakeClock) Set(now time.Time) {
clock.mu.Lock()
defer clock.mu.Unlock()
clock.now = now
}
+48
View File
@@ -0,0 +1,48 @@
package testutil
import (
"sync"
"testing"
"time"
)
func TestFakeClockMovesOnlyWhenTold(t *testing.T) {
start := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
clock := NewFakeClock(start)
if !clock.Now().Equal(start) {
t.Fatalf("Now() = %s, want %s", clock.Now(), start)
}
if got := clock.Advance(14 * 24 * time.Hour); !got.Equal(start.AddDate(0, 0, 14)) || !clock.Now().Equal(got) {
t.Fatalf("Advance() = %s, Now() = %s, want 14 days later", got, clock.Now())
}
clock.Set(start)
if !clock.Now().Equal(start) {
t.Fatalf("Now() after Set = %s, want %s", clock.Now(), start)
}
defer func() {
if recover() == nil {
t.Fatal("Advance() accepted a negative step")
}
}()
clock.Advance(-time.Second)
}
func TestFakeClockIsSafeForConcurrentUse(t *testing.T) {
clock := NewFakeClock(time.Unix(0, 0))
const readers, steps = 4, 100
var group sync.WaitGroup
for range readers {
group.Go(func() {
for range steps {
_ = clock.Now()
}
})
}
for range steps {
clock.Advance(time.Second)
}
group.Wait()
if got := clock.Now(); !got.Equal(time.Unix(steps, 0)) {
t.Fatalf("Now() = %s, want %d seconds after the epoch", got, steps)
}
}