2023-07-18 00:25:13 +01:00
|
|
|
package messaging
|
|
|
|
|
2023-07-18 14:09:28 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-07-19 13:22:55 +01:00
|
|
|
// Fetches credentials from environment variables and exits if none provided.
|
2023-07-18 14:09:28 +01:00
|
|
|
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")
|
|
|
|
}
|
2023-07-19 01:18:55 +01:00
|
|
|
log.Msg.Debug("NROD Credentials loaded for user: " + nrod_user)
|
2023-07-18 14:09:28 +01:00
|
|
|
return nrodCredential{
|
|
|
|
user: nrod_user,
|
|
|
|
pass: nrod_pass,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-19 13:22:55 +01:00
|
|
|
var Client = dial()
|
2023-07-18 14:09:28 +01:00
|
|
|
|
2023-07-19 13:22:55 +01:00
|
|
|
// Connects the STOMP file to the Network Rail MQ Server
|
2023-07-18 14:09:28 +01:00
|
|
|
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),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
log.Msg.Fatal("Unable to connect to STOMP Client", zap.String("err", err.Error()))
|
2023-07-19 13:22:55 +01:00
|
|
|
conn.MustDisconnect()
|
2023-07-18 14:09:28 +01:00
|
|
|
}
|
2023-07-19 13:22:55 +01:00
|
|
|
|
2023-07-19 01:18:55 +01:00
|
|
|
log.Msg.Info("Initialised STOMP Client")
|
2023-07-18 14:09:28 +01:00
|
|
|
return conn
|
|
|
|
}
|
|
|
|
|
2023-07-19 13:22:55 +01:00
|
|
|
// Handles graceful disconnection of the STOMP client, falls back to
|
|
|
|
// a force disconnect if this fails.
|
|
|
|
func Disconnect(conn *stomp.Conn) {
|
2023-07-18 14:09:28 +01:00
|
|
|
if conn != nil {
|
|
|
|
err := conn.Disconnect()
|
2023-07-19 13:22:55 +01:00
|
|
|
log.Msg.Warn("Disconnected STOMP Client")
|
2023-07-18 14:09:28 +01:00
|
|
|
if err != nil {
|
|
|
|
conn.MustDisconnect()
|
2023-07-19 13:22:55 +01:00
|
|
|
log.Msg.Error("STOMP Disconnection failed, forced disconnect")
|
2023-07-18 14:09:28 +01:00
|
|
|
}
|
2023-07-19 13:22:55 +01:00
|
|
|
return
|
2023-07-18 14:09:28 +01:00
|
|
|
}
|
2023-07-19 13:22:55 +01:00
|
|
|
log.Msg.Error("STOMP Disconnect failed, next connection attempt may fail")
|
2023-07-18 14:09:28 +01:00
|
|
|
}
|
|
|
|
|
2023-07-18 00:25:13 +01:00
|
|
|
// Register against the MQ Server and log each message for testing purposes
|