diff --git a/relay/healthcheck/receiver.go b/relay/healthcheck/receiver.go index b3503d5db..299adba15 100644 --- a/relay/healthcheck/receiver.go +++ b/relay/healthcheck/receiver.go @@ -2,14 +2,26 @@ package healthcheck import ( "context" + "sync" "time" log "github.com/sirupsen/logrus" ) -var ( - heartbeatTimeout = healthCheckInterval + 10*time.Second -) +var heartbeatTimeout = healthCheckInterval + 10*time.Second +var mux sync.Mutex + +func getHealthCheckInterval() time.Duration { + mux.Lock() + defer mux.Unlock() + return heartbeatTimeout +} + +func setHealthCheckInterval(interval time.Duration) { + mux.Lock() + defer mux.Unlock() + heartbeatTimeout = interval +} // Receiver is a healthcheck receiver // It will listen for heartbeat and check if the heartbeat is not received in a certain time @@ -56,7 +68,7 @@ func (r *Receiver) Stop() { } func (r *Receiver) waitForHealthcheck() { - ticker := time.NewTicker(heartbeatTimeout) + ticker := time.NewTicker(getHealthCheckInterval()) defer ticker.Stop() defer r.ctxCancel() defer close(r.OnTimeout) diff --git a/relay/healthcheck/receiver_test.go b/relay/healthcheck/receiver_test.go index 3b3e32fe6..60f165af0 100644 --- a/relay/healthcheck/receiver_test.go +++ b/relay/healthcheck/receiver_test.go @@ -11,7 +11,7 @@ import ( ) func TestNewReceiver(t *testing.T) { - heartbeatTimeout = 5 * time.Second + setHealthCheckInterval(5 * time.Second) r := NewReceiver(log.WithContext(context.Background())) select { @@ -23,7 +23,7 @@ func TestNewReceiver(t *testing.T) { } func TestNewReceiverNotReceive(t *testing.T) { - heartbeatTimeout = 1 * time.Second + setHealthCheckInterval(1 * time.Second) r := NewReceiver(log.WithContext(context.Background())) select { @@ -34,7 +34,7 @@ func TestNewReceiverNotReceive(t *testing.T) { } func TestNewReceiverAck(t *testing.T) { - heartbeatTimeout = 2 * time.Second + setHealthCheckInterval(2 * time.Second) r := NewReceiver(log.WithContext(context.Background())) r.Heartbeat() @@ -60,12 +60,12 @@ func TestReceiverHealthCheckAttemptThreshold(t *testing.T) { for _, tc := range testsCases { t.Run(tc.name, func(t *testing.T) { originalInterval := healthCheckInterval - originalTimeout := heartbeatTimeout + originalTimeout := getHealthCheckInterval() healthCheckInterval = 1 * time.Second - heartbeatTimeout = healthCheckInterval + 500*time.Millisecond + setHealthCheckInterval(originalTimeout + 500*time.Millisecond) defer func() { healthCheckInterval = originalInterval - heartbeatTimeout = originalTimeout + setHealthCheckInterval(originalTimeout) }() //nolint:tenv os.Setenv(defaultAttemptThresholdEnv, fmt.Sprintf("%d", tc.threshold)) @@ -73,7 +73,7 @@ func TestReceiverHealthCheckAttemptThreshold(t *testing.T) { receiver := NewReceiver(log.WithField("test_name", tc.name)) - testTimeout := heartbeatTimeout*time.Duration(tc.threshold) + healthCheckInterval + testTimeout := originalTimeout*time.Duration(tc.threshold) + healthCheckInterval if tc.resetCounterOnce { receiver.Heartbeat()