package control_test import ( "testing" "time" "google.golang.org/protobuf/types/known/timestamppb" "hth/internal/control" hthv1 "hth/internal/gen/hth/api/v1" ) func TestLeaseAcquireRenewExpire(t *testing.T) { m := control.NewManager("d0", time.Second, 10*time.Second, 8) now := time.Unix(1000, 0) l, err := m.Acquire(now, "alice", 2*time.Second) if err != nil { t.Fatal(err) } if l.ID == "" || l.Epoch == 0 { t.Fatal("id/epoch") } if _, err := m.Acquire(now, "bob", time.Second); err == nil { t.Fatal("second holder") } if _, err := m.Renew(now.Add(time.Second), l.ID, l.Epoch, 2*time.Second); err != nil { t.Fatal(err) } if expired := m.ExpireIfNeeded(now.Add(10 * time.Second)); expired == nil { t.Fatal("should expire") } if m.Current() != nil { t.Fatal("cleared") } } func TestReconnectInvalidates(t *testing.T) { m := control.NewManager("d0", time.Second, 10*time.Second, 8) now := time.Unix(1, 0) l, _ := m.Acquire(now, "alice", time.Second) m.InvalidateAndBump() batch := &hthv1.ActionBatch{CommandId: "c1", LeaseId: l.ID, LeaseEpoch: l.Epoch} if got := m.CheckAction(now, batch, 1, 1); got != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED { t.Fatalf("got %v", got) } } func TestCommandIDCache(t *testing.T) { c := control.NewCache(2) b1 := &hthv1.ActionBatch{CommandId: "c1", DeviceId: "d", ContinuousTargets: []*hthv1.ContinuousTarget{{Id: "fan.chamber.1", Value: 10}}} b2 := &hthv1.ActionBatch{CommandId: "c1", DeviceId: "d", ContinuousTargets: []*hthv1.ContinuousTarget{{Id: "fan.chamber.1", Value: 11}}} h1 := control.PayloadHash(b1) h2 := control.PayloadHash(b2) res := &hthv1.ActionResult{CommandId: "c1", Accepted: true} c.Store("c1", h1, res) hit, conflict := c.Lookup("c1", h1) if hit == nil || conflict { t.Fatal("replay") } hit, conflict = c.Lookup("c1", h2) if hit != nil || !conflict { t.Fatal("conflict") } } func TestStaleSnapshotAndDeadline(t *testing.T) { m := control.NewManager("d0", time.Second, 10*time.Second, 8) now := time.Unix(50, 0) l, _ := m.Acquire(now, "alice", time.Second) batch := &hthv1.ActionBatch{ CommandId: "c1", LeaseId: l.ID, LeaseEpoch: l.Epoch, BasedOnSnapshotSeq: 1, ExpectedControlRevision: 9, ValidUntil: timestamppb.New(now.Add(-time.Millisecond)), } if got := m.CheckAction(now, batch, 2, 9); got != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE { t.Fatalf("deadline got %v", got) } batch.ValidUntil = timestamppb.New(now.Add(time.Second)) if got := m.CheckAction(now, batch, 100, 9); got != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT { t.Fatalf("stale snap got %v", got) } batch.BasedOnSnapshotSeq = 100 if got := m.CheckAction(now, batch, 100, 1); got != hthv1.RejectReason_REJECT_REASON_STALE_CONTROL_REVISION { t.Fatalf("stale rev got %v", got) } } func TestCacheBounded(t *testing.T) { c := control.NewCache(2) r := &hthv1.ActionResult{Accepted: true} c.Store("a", []byte{1}, r) c.Store("b", []byte{2}, r) c.Store("c", []byte{3}, r) if hit, _ := c.Lookup("a", []byte{1}); hit != nil { t.Fatal("oldest should evict") } }