github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/health/checks/mqttclient.go (about)

     1  package checks
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	mqtt "github.com/eclipse/paho.mqtt.golang"
     9  )
    10  
    11  type MqttClientCheck struct {
    12  	Ctx        context.Context
    13  	MqttClient mqtt.Client
    14  	Error      error
    15  }
    16  
    17  func NewMqttClientCheck(ctx context.Context, mqttClient mqtt.Client) MqttClientCheck {
    18  	return MqttClientCheck{
    19  		Ctx:        ctx,
    20  		MqttClient: mqttClient,
    21  		Error:      nil,
    22  	}
    23  }
    24  
    25  func CheckMqttClientStatus(ctx context.Context, mqttClient mqtt.Client) error {
    26  	check := NewMqttClientCheck(ctx, mqttClient)
    27  	return check.CheckStatus()
    28  }
    29  
    30  func (check MqttClientCheck) CheckStatus() error {
    31  	client := check.MqttClient
    32  	var checkErr error
    33  	checkErr = nil
    34  	go func() {
    35  		defer func() {
    36  			if r := recover(); r != nil {
    37  				return
    38  			}
    39  		}()
    40  
    41  		ticker := time.NewTicker(30 * time.Second)
    42  		for range ticker.C {
    43  			if client.IsConnected() {
    44  				checkErr = fmt.Errorf("MQTT Client is not connected")
    45  				check.Error = checkErr
    46  			}
    47  		}
    48  	}()
    49  	return checkErr
    50  }