1
0
mirror of https://github.com/eventials/goevents.git synced 2025-04-24 13:48:53 +08:00
eventials.goevents/amqp/producer.go

393 lines
7.8 KiB
Go
Raw Normal View History

2016-12-01 10:52:22 -02:00
package amqp
import (
2017-10-09 19:33:27 -03:00
"errors"
"fmt"
"runtime/debug"
2017-03-09 17:32:05 -03:00
"sync"
2016-12-01 10:52:22 -02:00
"time"
2018-02-10 14:38:29 -02:00
"github.com/eventials/goevents/messaging"
2017-07-17 10:14:51 -03:00
log "github.com/sirupsen/logrus"
2020-10-21 19:41:11 -03:00
"github.com/streadway/amqp"
2016-12-01 10:52:22 -02:00
amqplib "github.com/streadway/amqp"
)
// ErrNotAcked indicated that published messages was not acked by RabbitMQ
var ErrNotAcked = errors.New("message was not acked")
var ErrTimedout = errors.New("message was timed out")
2017-10-09 19:33:27 -03:00
2017-03-09 17:32:05 -03:00
type message struct {
action string
2017-10-10 17:49:53 -03:00
msg amqplib.Publishing
2017-03-09 17:32:05 -03:00
}
2017-10-10 17:49:53 -03:00
// producer holds a amqp connection and channel to publish messages to.
type producer struct {
2019-05-14 12:08:15 -03:00
m sync.RWMutex
wg sync.WaitGroup
conn *connection
channel *amqplib.Channel
notifyConfirm chan amqplib.Confirmation
notifyChanClose chan *amqplib.Error
config ProducerConfig
2017-03-09 17:32:05 -03:00
internalQueue chan message
2016-12-28 09:20:29 -02:00
exchangeName string
2017-03-09 17:32:05 -03:00
closed bool
channelReady bool
closes []chan bool
2017-03-09 17:32:05 -03:00
}
// ProducerConfig to be used when creating a new producer.
type ProducerConfig struct {
2019-05-14 12:08:15 -03:00
PublishInterval time.Duration
ConfirmTimeout time.Duration
2016-12-01 10:52:22 -02:00
}
2016-12-01 16:17:55 -02:00
// NewProducer returns a new AMQP Producer.
// Uses a default ProducerConfig with 2 second of publish interval.
2017-10-10 17:49:53 -03:00
func NewProducer(c messaging.Connection, exchange string) (*producer, error) {
return NewProducerConfig(c, exchange, ProducerConfig{
2019-05-14 12:08:15 -03:00
PublishInterval: 2 * time.Second,
ConfirmTimeout: 10 * time.Second,
2017-03-09 17:32:05 -03:00
})
}
// NewProducerConfig returns a new AMQP Producer.
2017-10-10 17:49:53 -03:00
func NewProducerConfig(c messaging.Connection, exchange string, config ProducerConfig) (*producer, error) {
producer := &producer{
conn: c.(*connection),
config: config,
2019-05-14 12:08:15 -03:00
internalQueue: make(chan message),
exchangeName: exchange,
2017-03-09 17:32:05 -03:00
}
err := producer.setupTopology()
2017-10-10 17:49:53 -03:00
if err != nil {
return nil, err
}
go producer.drainInternalQueue()
go producer.handleReestablishedConnnection()
return producer, err
2017-03-09 17:32:05 -03:00
}
// Publish publishes an action.
2017-10-10 17:49:53 -03:00
func (p *producer) Publish(action string, data []byte) {
// ignore messages published to a closed producer
if p.isClosed() {
return
}
messageID, _ := NewUUIDv4()
2017-10-10 17:49:53 -03:00
2020-10-21 19:41:11 -03:00
now := time.Now().UTC()
2017-10-10 17:49:53 -03:00
p.publishAmqMessage(action, amqplib.Publishing{
MessageId: messageID,
2017-10-10 17:49:53 -03:00
DeliveryMode: amqplib.Persistent,
2020-10-21 19:41:11 -03:00
Timestamp: now,
2017-10-10 17:49:53 -03:00
Body: data,
2020-10-21 19:41:11 -03:00
Headers: amqp.Table{
2020-10-21 21:38:41 -03:00
"x-epoch-milli": int64(now.UnixNano()/int64(time.Nanosecond)) / int64(time.Millisecond),
2020-10-21 19:41:11 -03:00
},
2017-10-10 17:49:53 -03:00
})
}
func (p *producer) publishAmqMessage(queue string, msg amqplib.Publishing) {
p.wg.Add(1)
2019-05-14 12:08:15 -03:00
log.WithFields(log.Fields{
"action": queue,
"message_id": msg.MessageId,
"type": "goevents",
"sub_type": "producer",
"exchange": p.exchangeName,
"length": len(p.internalQueue),
}).Debug("Publishing message to internal queue.")
2017-10-10 17:49:53 -03:00
p.internalQueue <- message{
action: queue,
msg: msg,
}
2017-03-09 17:32:05 -03:00
}
2016-12-01 10:52:22 -02:00
2017-03-09 17:32:05 -03:00
// NotifyClose returns a channel to be notified then this producer closes.
2017-10-10 17:49:53 -03:00
func (p *producer) NotifyClose() <-chan bool {
receiver := make(chan bool, 1)
p.m.Lock()
2017-03-09 17:32:05 -03:00
p.closes = append(p.closes, receiver)
p.m.Unlock()
2017-03-09 17:32:05 -03:00
return receiver
}
func (p *producer) setClosed() {
2017-10-09 19:33:27 -03:00
p.m.Lock()
defer p.m.Unlock()
2017-03-09 17:32:05 -03:00
p.closed = true
}
2019-05-14 12:08:15 -03:00
func (p *producer) notifyProducerClosed() {
p.m.RLock()
defer p.m.RUnlock()
for _, c := range p.closes {
c <- true
}
}
// Close the producer's internal queue.
func (p *producer) Close() {
p.setClosed()
p.wg.Wait()
2017-03-09 17:32:05 -03:00
close(p.internalQueue)
p.channel.Close()
2019-05-14 12:08:15 -03:00
p.notifyProducerClosed()
}
// changeChannel takes a new channel to the queue,
// and updates the channel listeners to reflect this.
func (p *producer) changeChannel(channel *amqplib.Channel) {
p.channel = channel
p.notifyChanClose = make(chan *amqplib.Error)
p.channel.NotifyClose(p.notifyChanClose)
2019-05-20 12:29:42 -03:00
p.notifyConfirm = make(chan amqplib.Confirmation, 1)
p.channel.NotifyPublish(p.notifyConfirm)
p.channelReady = true
2017-03-09 17:32:05 -03:00
}
2017-10-10 17:49:53 -03:00
func (p *producer) setupTopology() error {
log.WithFields(log.Fields{
2017-05-24 18:23:07 -03:00
"type": "goevents",
"sub_type": "producer",
}).Debug("Setting up topology...")
2017-03-09 17:32:05 -03:00
p.m.Lock()
defer p.m.Unlock()
channel, err := p.conn.openChannel()
if err != nil {
return err
}
2017-03-09 17:32:05 -03:00
if p.exchangeName != "" {
2017-10-10 17:49:53 -03:00
if err != nil {
return err
}
2016-12-28 09:20:29 -02:00
2017-10-10 17:49:53 -03:00
err = channel.ExchangeDeclare(
p.exchangeName, // name
"topic", // type
true, // durable
false, // auto-delete
false, // internal
false, // no-wait
nil, // arguments
)
2017-10-09 19:33:27 -03:00
2017-10-10 17:49:53 -03:00
if err != nil {
return err
}
2016-12-28 09:20:29 -02:00
}
err = channel.Confirm(false)
if err != nil {
err = fmt.Errorf("Channel could not be put into confirm mode: %s", err)
return err
}
p.changeChannel(channel)
log.WithFields(log.Fields{
2017-05-24 18:23:07 -03:00
"type": "goevents",
"sub_type": "producer",
}).Debug("Topology ready.")
2017-03-09 17:32:05 -03:00
return nil
2016-12-01 10:52:22 -02:00
}
func (p *producer) setChannelReady(ready bool) {
p.m.Lock()
defer p.m.Unlock()
p.channelReady = ready
}
func (p *producer) isChannelReady() bool {
2019-05-14 12:08:15 -03:00
p.m.RLock()
defer p.m.RUnlock()
return p.channelReady
}
func (p *producer) isConnected() bool {
if !p.conn.IsConnected() {
return false
}
return p.isChannelReady()
}
func (p *producer) waitConnectionLost() bool {
if !p.isConnected() {
return true
}
defer p.setChannelReady(false)
select {
case <-p.conn.NotifyConnectionClose():
log.Warn("Producer connection closed")
return true
case <-p.notifyChanClose:
log.Warn("Producer channel closed")
return false
}
}
2017-10-10 17:49:53 -03:00
func (p *producer) handleReestablishedConnnection() {
rs := p.conn.NotifyReestablish()
for !p.isClosed() {
// true if connection is lot
// false if channel connection is lost
connectionLost := p.waitConnectionLost()
2017-03-09 17:32:05 -03:00
if connectionLost {
// Wait reconnect
<-rs
}
2017-03-09 17:32:05 -03:00
err := p.setupTopology()
2017-03-09 17:32:05 -03:00
if err != nil {
log.WithFields(log.Fields{
"type": "goevents",
"sub_type": "producer",
"error": err,
2017-05-24 18:23:07 -03:00
}).Error("Error setting up topology after reconnection.")
2017-03-09 17:32:05 -03:00
}
}
}
func (p *producer) publishMessage(msg amqplib.Publishing, queue string) (err error) {
if !p.isConnected() {
err = errors.New("connection/channel is not open")
return
}
2019-05-14 12:08:15 -03:00
logMessage := log.WithFields(log.Fields{
"action": queue,
"message_id": msg.MessageId,
"type": "goevents",
"sub_type": "producer",
"exchange": p.exchangeName,
2019-05-14 12:08:15 -03:00
})
logMessage.WithFields(log.Fields{
"body": msg.Body,
}).Debug("Publishing message to the exchange.")
defer func() {
if r := recover(); r != nil {
debug.PrintStack()
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = errors.New("Unknown panic")
}
}
}()
err = p.channel.Publish(
p.exchangeName, // Exchange
queue, // Routing key
false, // Mandatory
false, // Immediate
msg)
2017-10-09 19:33:27 -03:00
if err != nil {
return
2017-10-09 19:33:27 -03:00
}
2019-05-14 12:08:15 -03:00
logMessage.Debug("Waiting message to be acked or timed out.")
select {
case confirm := <-p.notifyConfirm:
if confirm.Ack {
return
2017-10-09 19:33:27 -03:00
}
err = ErrNotAcked
return
2019-05-14 12:08:15 -03:00
case <-time.After(p.config.ConfirmTimeout):
err = ErrTimedout
return
2017-10-09 19:33:27 -03:00
}
return
2017-10-09 19:33:27 -03:00
}
2017-10-10 17:49:53 -03:00
func (p *producer) isClosed() bool {
2019-05-14 12:08:15 -03:00
p.m.RLock()
defer p.m.RUnlock()
2017-10-09 19:33:27 -03:00
return p.closed
}
2017-10-10 17:49:53 -03:00
func (p *producer) drainInternalQueue() {
2019-05-01 14:08:44 -03:00
for m := range p.internalQueue {
retry := true
for retry {
// block until confirmation
err := p.publishMessage(m.msg, m.action)
if err != nil {
log.WithFields(log.Fields{
"action": m.action,
"body": m.msg.Body,
"message_id": m.msg.MessageId,
"error": err,
"type": "goevents",
"sub_type": "producer",
}).Error("Error publishing message to the exchange. Retrying...")
if err == ErrTimedout {
log.Warn("Closing producer channel due timeout wating msg confirmation")
// force close to run setupTopology
p.setChannelReady(false)
p.channel.Close()
}
2019-05-14 12:08:15 -03:00
time.Sleep(p.config.PublishInterval)
2019-05-01 14:08:44 -03:00
} else {
p.wg.Done()
retry = false
2017-03-09 17:32:05 -03:00
}
}
2016-12-01 10:52:22 -02:00
}
}