package main import ( "context" "errors" "os" "strings" "sync" "syscall" "testing" "time" ) func TestPanelRestartDeadlineFencesBlockedDrain(t *testing.T) { entered, release, drained := make(chan struct{}), make(chan struct{}), make(chan struct{}) unblock := sync.OnceFunc(func() { close(release) }) t.Cleanup(unblock) newGeneration := make(chan struct{}) _, err := runPanelRestart(nil, 250*time.Millisecond, panelRestartPhase{"panel drain", func(context.Context) error { close(entered) <-release close(drained) return nil }}, panelRestartPhase{"panel startup", func(context.Context) error { close(newGeneration); return nil }}, ) if !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "panel drain") { t.Fatalf("blocked drain: %v", err) } <-entered unblock() <-drained select { case <-newGeneration: t.Fatal("new workers started after a failed drain") case <-time.After(75 * time.Millisecond): } } func TestPanelRestartDrainsBeforeGracefulShutdown(t *testing.T) { entered, release := make(chan struct{}), make(chan struct{}) unblock := sync.OnceFunc(func() { close(release) }) t.Cleanup(unblock) signals := make(chan os.Signal) type outcome struct { pending panelRestartSignals err error } result := make(chan outcome, 1) started := false go func() { pending, err := runPanelRestart(signals, 3*time.Second, panelRestartPhase{"panel shutdown", func(context.Context) error { close(entered) <-release return nil }}, panelRestartPhase{"panel startup", func(context.Context) error { started = true return nil }}, ) result <- outcome{pending, err} }() <-entered signals <- syscall.SIGHUP signals <- syscall.SIGTERM unblock() got := <-result if got.err != nil || !got.pending.shutdown || !started { t.Fatalf("current restart must finish before graceful cleanup: started=%v, result=%+v", started, got) } } func TestPanelRestartDoesNotStartListenersAfterShutdownFailure(t *testing.T) { failure := errors.New("old listener did not drain") started := false _, err := runPanelRestart(nil, time.Second, panelRestartPhase{"panel shutdown", func(context.Context) error { return failure }}, panelRestartPhase{"panel startup", func(context.Context) error { started = true; return nil }}, ) if started || !errors.Is(err, failure) { t.Fatalf("started=%t, error=%v", started, err) } }