package control import ( "log/slog" "path/filepath" "testing" "time" "gitea.mynodes.xyz/ilker/llmgw/internal/store" ) func TestAStoppingLeaderHandsOverAtOnceAndNeverTakesItBack(t *testing.T) { st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "s.db")) if err != nil { t.Fatal(err) } defer st.Close() log := slog.New(slog.DiscardHandler) a := NewLeadership(st, time.Minute, log) b := NewLeadership(st, time.Minute, log) a.attempt(t.Context()) b.attempt(t.Context()) if !a.IsLeader() || b.IsLeader() { t.Fatalf("a %v, b %v", a.IsLeader(), b.IsLeader()) } // Stepping down gives the lease back, rather than leaving b to wait out // the minute it was taken for. a.StepDown() if a.IsLeader() { t.Error("still leading after stepping down") } // A renewal already on its way when the process began to stop must not // take it back. a.attempt(t.Context()) if a.IsLeader() { t.Error("took the lease again after stepping down") } b.attempt(t.Context()) if !b.IsLeader() { t.Error("the standby could not take the lease that was given up") } lease, err := st.Leadership(t.Context(), ControlRole) if err != nil || lease.Owner != b.Owner() { t.Errorf("the lease is %q (%v), not b's", lease.Owner, err) } if got := HolderName(b.Owner()); got == "" || got == b.Owner() { t.Errorf("holder name %q from %q", got, b.Owner()) } } func TestAStandbyIsToldWhenItBecomesTheLeader(t *testing.T) { st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "s.db")) if err != nil { t.Fatal(err) } defer st.Close() log := slog.New(slog.DiscardHandler) a := NewLeadership(st, time.Minute, log) b := NewLeadership(st, time.Minute, log) led := make(chan struct{}, 4) b.OnLead(func() { led <- struct{}{} }) ctx := t.Context() a.attempt(ctx) b.attempt(ctx) if !a.IsLeader() || b.IsLeader() { t.Fatal("a should lead, b stand by") } a.StepDown() b.attempt(ctx) select { case <-led: case <-time.After(time.Second): t.Fatal("b became the leader and was not told") } }