tile38/internal/endpoint/nats.go

94 lines
1.7 KiB
Go
Raw Normal View History

2018-08-07 22:04:04 +03:00
package endpoint
import (
"fmt"
"sync"
"time"
"github.com/nats-io/nats.go"
2018-08-07 22:04:04 +03:00
)
const natsExpiresAfter = time.Second * 30
2018-08-07 22:04:04 +03:00
// NATSConn is an endpoint connection
type NATSConn struct {
mu sync.Mutex
ep Endpoint
ex bool
t time.Time
conn *nats.Conn
}
func newNATSConn(ep Endpoint) *NATSConn {
return &NATSConn{
ep: ep,
t: time.Now(),
}
}
// Expired returns true if the connection has expired
func (conn *NATSConn) Expired() bool {
conn.mu.Lock()
defer conn.mu.Unlock()
if !conn.ex {
if time.Since(conn.t) > natsExpiresAfter {
2022-09-25 16:28:17 +03:00
conn.close()
2018-08-07 22:04:04 +03:00
conn.ex = true
}
}
return conn.ex
}
2022-09-25 16:28:17 +03:00
// ExpireNow forces the connection to expire
func (conn *NATSConn) ExpireNow() {
conn.mu.Lock()
defer conn.mu.Unlock()
conn.close()
conn.ex = true
}
2018-08-07 22:04:04 +03:00
func (conn *NATSConn) close() {
if conn.conn != nil {
conn.conn.Close()
conn.conn = nil
}
}
// Send sends a message
func (conn *NATSConn) Send(msg string) error {
conn.mu.Lock()
defer conn.mu.Unlock()
if conn.ex {
return errExpired
}
conn.t = time.Now()
if conn.conn == nil {
addr := fmt.Sprintf("%s:%d", conn.ep.NATS.Host, conn.ep.NATS.Port)
2018-08-07 22:04:04 +03:00
var err error
var opts []nats.Option
2018-08-07 22:04:04 +03:00
if conn.ep.NATS.User != "" && conn.ep.NATS.Pass != "" {
opts = append(opts, nats.UserInfo(conn.ep.NATS.User, conn.ep.NATS.Pass))
2018-08-07 22:04:04 +03:00
}
if conn.ep.NATS.TLS {
opts = append(opts, nats.ClientCert(
conn.ep.NATS.TLSCert, conn.ep.NATS.TLSKey,
))
}
if conn.ep.NATS.Token != "" {
opts = append(opts, nats.Token(conn.ep.NATS.Token))
}
conn.conn, err = nats.Connect(addr, opts...)
2018-08-07 22:04:04 +03:00
if err != nil {
conn.close()
return err
}
}
err := conn.conn.Publish(conn.ep.NATS.Topic, []byte(msg))
if err != nil {
conn.close()
return err
}
return nil
}