feat: multi-region evaluation, incidents and notifications (M5) #51
No files matched your search
@@ -0,0 +1,137 @@
|
||||
// Package evaluate turns per-region check results into a monitor state.
|
||||
//
|
||||
// A monitor goes down only when every region it is assigned to has failed
|
||||
// the configured number of times in a row and reported recently. A region
|
||||
// without recent results counts as unknown and keeps the monitor up: one
|
||||
// checker losing its network must not page anyone. Any successful region
|
||||
// brings the monitor back up.
|
||||
//
|
||||
// The state lives in Redis and each observation is applied by one Lua
|
||||
// script, so concurrent results on several API replicas produce exactly one
|
||||
// transition.
|
||||
package evaluate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Transition is the change an observation caused.
|
||||
type Transition int
|
||||
|
||||
// Transitions.
|
||||
const (
|
||||
None Transition = iota
|
||||
Down
|
||||
Up
|
||||
)
|
||||
|
||||
func (t Transition) String() string {
|
||||
switch t {
|
||||
case Down:
|
||||
return "down"
|
||||
case Up:
|
||||
return "up"
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
// Observation is one check result with the monitor settings needed to judge
|
||||
// it.
|
||||
type Observation struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
OK bool
|
||||
At time.Time
|
||||
Interval time.Duration
|
||||
Confirmations int
|
||||
// Regions are all regions the monitor is assigned to.
|
||||
Regions []string
|
||||
}
|
||||
|
||||
// staleAfter is how old a region's last result may be before the region
|
||||
// counts as unknown.
|
||||
func staleAfter(interval time.Duration) time.Duration {
|
||||
return max(3*interval, 2*time.Minute)
|
||||
}
|
||||
|
||||
const stateTTL = 7 * 24 * time.Hour
|
||||
|
||||
// observeScript applies one result.
|
||||
//
|
||||
// KEYS: monitor state hash.
|
||||
// ARGV: region, ok (1/0), at ms, confirmations, stale-before ms, ttl s,
|
||||
// then every assigned region.
|
||||
var observeScript = redis.NewScript(`
|
||||
local key, region = KEYS[1], ARGV[1]
|
||||
local ok, at, need, stale = ARGV[2] == '1', tonumber(ARGV[3]), tonumber(ARGV[4]), tonumber(ARGV[5])
|
||||
local last = tonumber(redis.call('HGET', key, 'a:' .. region) or '0')
|
||||
if at < last then return 'none' end
|
||||
redis.call('HSET', key, 'a:' .. region, string.format('%.0f', at))
|
||||
if ok then
|
||||
redis.call('HSET', key, 'f:' .. region, 0)
|
||||
else
|
||||
redis.call('HINCRBY', key, 'f:' .. region, 1)
|
||||
end
|
||||
redis.call('EXPIRE', key, ARGV[6])
|
||||
local state = redis.call('HGET', key, 'state') or 'up'
|
||||
if state == 'down' then
|
||||
if ok then
|
||||
redis.call('HSET', key, 'state', 'up')
|
||||
return 'up'
|
||||
end
|
||||
return 'none'
|
||||
end
|
||||
for i = 7, #ARGV do
|
||||
local r = ARGV[i]
|
||||
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
|
||||
local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0')
|
||||
if fails < need or seen < stale then return 'none' end
|
||||
end
|
||||
redis.call('HSET', key, 'state', 'down')
|
||||
return 'down'
|
||||
`)
|
||||
|
||||
// Evaluator is safe for concurrent use.
|
||||
type Evaluator struct {
|
||||
rdb redis.UniversalClient
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// New returns an Evaluator on rdb.
|
||||
func New(rdb redis.UniversalClient) *Evaluator {
|
||||
return &Evaluator{rdb: rdb, now: time.Now}
|
||||
}
|
||||
|
||||
// Observe applies o and reports the resulting transition.
|
||||
func (e *Evaluator) Observe(ctx context.Context, o Observation) (Transition, error) {
|
||||
ok := "0"
|
||||
if o.OK {
|
||||
ok = "1"
|
||||
}
|
||||
stale := e.now().Add(-staleAfter(o.Interval)).UnixMilli()
|
||||
args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())}
|
||||
for _, r := range o.Regions {
|
||||
args = append(args, r)
|
||||
}
|
||||
res, err := observeScript.Run(ctx, e.rdb, []string{"eval:" + o.MonitorID.String()}, args...).Text()
|
||||
if err != nil {
|
||||
return None, fmt.Errorf("evaluate: %w", err)
|
||||
}
|
||||
switch res {
|
||||
case "down":
|
||||
return Down, nil
|
||||
case "up":
|
||||
return Up, nil
|
||||
}
|
||||
return None, nil
|
||||
}
|
||||
|
||||
// Forget drops the state of a deleted monitor.
|
||||
func (e *Evaluator) Forget(ctx context.Context, id uuid.UUID) error {
|
||||
return e.rdb.Del(ctx, "eval:"+id.String()).Err()
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package evaluate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newTest(t *testing.T) (*Evaluator, *time.Time) {
|
||||
t.Helper()
|
||||
url := os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if url == "" {
|
||||
t.Skip("UPTIME_TEST_REDIS_URL not set")
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rdb := redis.NewClient(opts)
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
now := time.UnixMilli(1_800_000_000_000)
|
||||
e := New(rdb)
|
||||
e.now = func() time.Time { return now }
|
||||
return e, &now
|
||||
}
|
||||
|
||||
type step struct {
|
||||
region string
|
||||
ok bool
|
||||
want Transition
|
||||
}
|
||||
|
||||
func play(t *testing.T, e *Evaluator, now *time.Time, regions []string, confirmations int, steps []step) {
|
||||
t.Helper()
|
||||
id := uuid.New()
|
||||
for i, s := range steps {
|
||||
*now = now.Add(time.Second)
|
||||
got, err := e.Observe(context.Background(), Observation{
|
||||
MonitorID: id, Region: s.region, OK: s.ok, At: *now,
|
||||
Interval: time.Minute, Confirmations: confirmations, Regions: regions,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != s.want {
|
||||
t.Errorf("step %d (%s ok=%t) = %v, want %v", i, s.region, s.ok, got, s.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownOnlyWhenAllRegionsFail(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu", "us"}, 2, []step{
|
||||
{"eu", false, None},
|
||||
{"eu", false, None}, // eu confirmed down, us has not reported
|
||||
{"us", true, None},
|
||||
{"us", false, None},
|
||||
{"eu", false, None},
|
||||
{"us", false, Down}, // both regions failed twice in a row
|
||||
{"us", false, None}, // no repeated transition
|
||||
{"eu", true, Up}, // one healthy region is enough to recover
|
||||
{"eu", true, None},
|
||||
})
|
||||
}
|
||||
|
||||
func TestSingleRegionWithConfirmations(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu"}, 3, []step{
|
||||
{"eu", false, None},
|
||||
{"eu", false, None},
|
||||
{"eu", true, None}, // a success resets the count
|
||||
{"eu", false, None},
|
||||
{"eu", false, None},
|
||||
{"eu", false, Down},
|
||||
})
|
||||
}
|
||||
|
||||
func TestSilentRegionBlocksAlert(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
id := uuid.New()
|
||||
obs := func(region string, ok bool) Transition {
|
||||
got, err := e.Observe(context.Background(), Observation{
|
||||
MonitorID: id, Region: region, OK: ok, At: *now,
|
||||
Interval: time.Minute, Confirmations: 1, Regions: []string{"eu", "us"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
obs("us", false)
|
||||
// us stops reporting for longer than three intervals.
|
||||
*now = now.Add(5 * time.Minute)
|
||||
if got := obs("eu", false); got != None {
|
||||
t.Errorf("eu failure with us silent = %v, want none", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutOfOrderResultIgnored(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
id := uuid.New()
|
||||
obs := func(at time.Time, ok bool) Transition {
|
||||
got, err := e.Observe(context.Background(), Observation{
|
||||
MonitorID: id, Region: "eu", OK: ok, At: at, Interval: time.Minute, Confirmations: 1, Regions: []string{"eu"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
if got := obs(*now, false); got != Down {
|
||||
t.Fatalf("first failure = %v, want down", got)
|
||||
}
|
||||
if got := obs(now.Add(-time.Minute), true); got != None {
|
||||
t.Errorf("older success = %v, want ignored", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user