Dispatch runs atomically in Redis so every API replica can do it. Jobs of instances that stop polling return to their region. Refs #11, #49 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
295 lines
8.6 KiB
Go
295 lines
8.6 KiB
Go
// Package schedule distributes due checks to checker instances.
|
|
//
|
|
// It runs inside the API, which is the only component with Redis access.
|
|
// Per region, a sorted set holds each monitor's next due time. Dispatch
|
|
// moves due monitors into the queue of a randomly chosen live instance of
|
|
// that region and schedules their next run in the same atomic step, so any
|
|
// number of API replicas can dispatch concurrently without a leader, and a
|
|
// lost job never stops a monitor from running again.
|
|
//
|
|
// Instances announce themselves by polling. One that stops polling is
|
|
// considered gone after StaleAfter; its queued jobs return to the region.
|
|
package schedule
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// StaleAfter is how long an instance may stay silent before its queued jobs
|
|
// are given to others. Instances poll at least every PollInterval.
|
|
const (
|
|
PollInterval = 20 * time.Second
|
|
StaleAfter = 45 * time.Second
|
|
)
|
|
|
|
const (
|
|
keyRegions = "sched:regions"
|
|
keyIntervals = "sched:intervals"
|
|
jobsPrefix = "sched:jobs:"
|
|
// jobsTTL drops queues of instances that vanished together with every
|
|
// API replica that could have recovered them.
|
|
jobsTTL = 10 * time.Minute
|
|
)
|
|
|
|
func keyDue(region string) string { return "sched:due:" + region }
|
|
func keyInstances(region string) string { return "sched:instances:" + region }
|
|
|
|
// Scheduler is safe for concurrent use.
|
|
type Scheduler struct {
|
|
rdb redis.UniversalClient
|
|
now func() time.Time
|
|
}
|
|
|
|
// New returns a Scheduler on rdb.
|
|
func New(rdb redis.UniversalClient) *Scheduler {
|
|
return &Scheduler{rdb: rdb, now: time.Now}
|
|
}
|
|
|
|
// Entry is one dispatched run.
|
|
type Entry struct {
|
|
MonitorID uuid.UUID
|
|
ScheduledAt time.Time
|
|
}
|
|
|
|
// Monitor is the schedule-relevant part of a monitor.
|
|
type Monitor struct {
|
|
ID uuid.UUID
|
|
Interval time.Duration
|
|
Regions []string
|
|
}
|
|
|
|
// Upsert schedules m in its regions and removes it from others it was in.
|
|
// A monitor new to a region runs right away; an existing schedule keeps its
|
|
// phase so edits do not cause bursts.
|
|
func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error {
|
|
now := s.now().UnixMilli()
|
|
id := m.ID.String()
|
|
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
|
p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond))
|
|
keep := map[string]bool{}
|
|
for _, r := range m.Regions {
|
|
keep[r] = true
|
|
p.SAdd(ctx, keyRegions, r)
|
|
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id})
|
|
}
|
|
for _, r := range previousRegions {
|
|
if !keep[r] {
|
|
p.ZRem(ctx, keyDue(r), id)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
return err
|
|
}
|
|
|
|
// Remove unschedules a monitor from regions. Runs already queued for an
|
|
// instance are dropped at dispatch or job resolution.
|
|
func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error {
|
|
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
|
p.HDel(ctx, keyIntervals, id.String())
|
|
for _, r := range regions {
|
|
p.ZRem(ctx, keyDue(r), id.String())
|
|
}
|
|
return nil
|
|
})
|
|
return err
|
|
}
|
|
|
|
// Reconcile makes Redis match want, the full set of enabled monitors. It
|
|
// repairs drift after a Redis failover or a missed update and is safe to run
|
|
// from several replicas.
|
|
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor) error {
|
|
byRegion := map[string]map[string]bool{}
|
|
for _, m := range want {
|
|
if err := s.Upsert(ctx, m, nil); err != nil {
|
|
return err
|
|
}
|
|
for _, r := range m.Regions {
|
|
if byRegion[r] == nil {
|
|
byRegion[r] = map[string]bool{}
|
|
}
|
|
byRegion[r][m.ID.String()] = true
|
|
}
|
|
}
|
|
wanted := map[string]bool{}
|
|
for _, m := range want {
|
|
wanted[m.ID.String()] = true
|
|
}
|
|
ids, err := s.rdb.HKeys(ctx, keyIntervals).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, id := range ids {
|
|
if !wanted[id] {
|
|
s.rdb.HDel(ctx, keyIntervals, id)
|
|
}
|
|
}
|
|
regions, err := s.rdb.SMembers(ctx, keyRegions).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range regions {
|
|
members, err := s.rdb.ZRange(ctx, keyDue(r), 0, -1).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, id := range members {
|
|
if !byRegion[r][id] {
|
|
s.rdb.ZRem(ctx, keyDue(r), id)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Heartbeat records that instance of region is alive.
|
|
func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.UUID) error {
|
|
return s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: float64(s.now().UnixMilli()), Member: instance.String()}).Err()
|
|
}
|
|
|
|
// dispatchScript runs per region.
|
|
//
|
|
// KEYS: due set, instance set, interval hash.
|
|
// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s.
|
|
var dispatchScript = redis.NewScript(`
|
|
local now = tonumber(ARGV[1])
|
|
for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do
|
|
local q = ARGV[4] .. inst
|
|
for _, job in ipairs(redis.call('LRANGE', q, 0, -1)) do
|
|
local m = string.sub(job, 1, string.find(job, '|', 1, true) - 1)
|
|
if redis.call('HEXISTS', KEYS[3], m) == 1 then
|
|
redis.call('ZADD', KEYS[1], 'LT', now, m)
|
|
end
|
|
end
|
|
redis.call('DEL', q)
|
|
redis.call('ZREM', KEYS[2], inst)
|
|
end
|
|
local live = redis.call('ZRANGE', KEYS[2], 0, -1)
|
|
if #live == 0 then return 0 end
|
|
local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now, 'WITHSCORES', 'LIMIT', 0, ARGV[3])
|
|
local n = 0
|
|
for i = 1, #due, 2 do
|
|
local m, at = due[i], tonumber(due[i + 1])
|
|
local interval = tonumber(redis.call('HGET', KEYS[3], m))
|
|
if interval == nil then
|
|
redis.call('ZREM', KEYS[1], m)
|
|
else
|
|
local q = ARGV[4] .. live[math.random(#live)]
|
|
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at))
|
|
redis.call('EXPIRE', q, ARGV[5])
|
|
local nxt = at + interval
|
|
if nxt <= now then nxt = now + interval end
|
|
redis.call('ZADD', KEYS[1], nxt, m)
|
|
n = n + 1
|
|
end
|
|
end
|
|
return n
|
|
`)
|
|
|
|
// Dispatch hands due runs of every region to random live instances and
|
|
// returns how many it dispatched.
|
|
func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
|
|
regions, err := s.rdb.SMembers(ctx, keyRegions).Result()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
now := s.now()
|
|
total := 0
|
|
for _, r := range regions {
|
|
n, err := dispatchScript.Run(ctx, s.rdb,
|
|
[]string{keyDue(r), keyInstances(r), keyIntervals},
|
|
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
|
|
).Int()
|
|
if err != nil {
|
|
return total, fmt.Errorf("schedule: dispatch %s: %w", r, err)
|
|
}
|
|
total += n
|
|
}
|
|
return total, nil
|
|
}
|
|
|
|
// Take pops up to max queued runs for instance, waiting up to wait for the
|
|
// first one. It returns within about a second once ctx is done, so long polls
|
|
// do not hold up shutdown or cancelled requests.
|
|
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) {
|
|
if max <= 0 {
|
|
return nil, nil
|
|
}
|
|
q := jobsPrefix + instance.String()
|
|
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
|
|
if err != nil && !errors.Is(err, redis.Nil) {
|
|
return nil, err
|
|
}
|
|
deadline := time.Now().Add(wait)
|
|
for len(raw) == 0 && ctx.Err() == nil {
|
|
left := time.Until(deadline)
|
|
if left <= 0 {
|
|
return nil, nil
|
|
}
|
|
// BLPOP blocks server side and ignores ctx, so wait in slices.
|
|
first, err := s.rdb.BLPop(ctx, min(left, time.Second), q).Result()
|
|
if errors.Is(err, redis.Nil) {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
raw = []string{first[1]}
|
|
if max > 1 {
|
|
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
|
|
if err != nil && !errors.Is(err, redis.Nil) {
|
|
return nil, err
|
|
}
|
|
raw = append(raw, more...)
|
|
}
|
|
}
|
|
out := make([]Entry, 0, len(raw))
|
|
for _, r := range raw {
|
|
if e, ok := parseEntry(r); ok {
|
|
out = append(out, e)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Release returns instance's queued runs to its region and forgets it.
|
|
func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error {
|
|
// Marking the instance stale lets the dispatch script do the handover,
|
|
// which keeps that logic in one place.
|
|
if err := s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: 0, Member: instance.String()}).Err(); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.Dispatch(ctx)
|
|
return err
|
|
}
|
|
|
|
// Instances returns the live instance count per region.
|
|
func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error) {
|
|
min := strconv.FormatInt(s.now().Add(-StaleAfter).UnixMilli(), 10)
|
|
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
|
|
}
|
|
|
|
func parseEntry(s string) (Entry, bool) {
|
|
id, at, ok := strings.Cut(s, "|")
|
|
if !ok {
|
|
return Entry{}, false
|
|
}
|
|
mid, err := uuid.Parse(id)
|
|
if err != nil {
|
|
return Entry{}, false
|
|
}
|
|
ms, err := strconv.ParseFloat(at, 64)
|
|
if err != nil {
|
|
return Entry{}, false
|
|
}
|
|
return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true
|
|
}
|