timetable-mgr/src/messaging/client.go

66 lines
1.7 KiB
Go

package messaging
import (
"os"
"git.fjla.uk/owlboard/mq-client/log"
"go.uber.org/zap"
"github.com/go-stomp/stomp/v3"
)
type nrodCredential struct {
user string
pass string
}
// Fetches credentials from environment variables and exits if none provided.
func getCredentials() nrodCredential {
var nrod_user string = os.Getenv("OWL_LDB_CORPUSUSER")
var nrod_pass string = os.Getenv("OWL_LDB_CORPUSPASS")
if nrod_user == "" || nrod_pass == "" {
log.Msg.Fatal("No NROD Credentials provided")
}
log.Msg.Debug("NROD Credentials loaded for user: " + nrod_user)
return nrodCredential{
user: nrod_user,
pass: nrod_pass,
}
}
var Client = dial()
// Connects the STOMP file to the Network Rail MQ Server
func dial() *stomp.Conn {
var credentials nrodCredential = getCredentials()
conn, err := stomp.Dial("tcp", "publicdatafeeds.networkrail.co.uk:61618",
stomp.ConnOpt.Login(credentials.user, credentials.pass),
stomp.ConnOpt.HeartBeat(15000, 15000),
stomp.ConnOpt.Header("client-id", credentials.user+"-mq-client"),
)
if err != nil {
log.Msg.Fatal("Unable to connect to STOMP Client", zap.String("err", err.Error()))
conn.MustDisconnect()
}
log.Msg.Info("Initialised STOMP Client")
return conn
}
// Handles graceful disconnection of the STOMP client, falls back to
// a force disconnect if this fails.
func Disconnect(conn *stomp.Conn) {
if conn != nil {
err := conn.Disconnect()
log.Msg.Warn("Disconnected STOMP Client")
if err != nil {
conn.MustDisconnect()
log.Msg.Error("STOMP Disconnection failed, forced disconnect")
}
return
}
log.Msg.Error("STOMP Disconnect failed, next connection attempt may fail")
}
// Register against the MQ Server and log each message for testing purposes