1
0
mirror of https://github.com/eventials/goevents.git synced 2025-05-02 22:17:09 +08:00
eventials.goevents/amqp/producer.go

280 lines
5.6 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"
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("messge was not acked")
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 {
m sync.Mutex
conn *connection
channel *amqp.Channel
notifyConfirm chan amqp.Confirmation
2016-12-28 09:20:29 -02:00
2017-03-09 17:32:05 -03:00
config ProducerConfig
internalQueue chan message
ackChannel chan uint64
nackChannel chan uint64
2016-12-28 09:20:29 -02:00
exchangeName string
2017-03-09 17:32:05 -03:00
closed bool
closes []chan bool
}
// ProducerConfig to be used when creating a new producer.
type ProducerConfig struct {
publishInterval 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{
2017-03-09 17:32:05 -03:00
publishInterval: 2 * time.Second,
})
}
// 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{
2018-02-10 14:38:29 -02:00
conn: c.(*connection),
2017-03-09 17:32:05 -03:00
config: config,
internalQueue: make(chan message),
exchangeName: exchange,
notifyConfirm: make(chan amqp.Confirmation),
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.handleReestablishedConnnection()
go producer.drainInternalQueue()
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) {
messageID, _ := NewUUIDv4()
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,
2018-04-24 15:41:26 -03:00
Timestamp: time.Now().UTC(),
2017-10-10 17:49:53 -03:00
Body: data,
})
}
func (p *producer) publishAmqMessage(queue string, msg amqplib.Publishing) {
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
}
// Close the producer's internal queue.
2017-10-10 17:49:53 -03:00
func (p *producer) Close() {
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
close(p.internalQueue)
p.channel.Close()
}
// changeChannel takes a new channel to the queue,
// and updates the channel listeners to reflect this.
func (p *producer) changeChannel(channel *amqp.Channel) {
p.channel = channel
p.notifyConfirm = make(chan amqp.Confirmation)
p.channel.NotifyPublish(p.notifyConfirm)
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
}
2017-10-10 17:49:53 -03:00
func (p *producer) handleReestablishedConnnection() {
rs := p.conn.NotifyReestablish()
2017-03-09 17:32:05 -03:00
for !p.closed {
<-rs
2017-03-09 17:32:05 -03:00
err := p.setupTopology()
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) {
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")
}
}
}()
if !p.conn.IsConnected() {
err = errors.New("connection is not open")
return
}
err = p.channel.Publish(p.exchangeName, queue, false, false, msg)
2017-10-09 19:33:27 -03:00
if err != nil {
return
2017-10-09 19:33:27 -03:00
}
select {
case confirm := <-p.notifyConfirm:
if confirm.Ack {
return
2017-10-09 19:33:27 -03:00
}
case <-time.After(p.config.publishInterval):
err = ErrNotAcked
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 {
2017-10-09 19:33:27 -03:00
p.m.Lock()
defer p.m.Unlock()
return p.closed
}
2017-10-10 17:49:53 -03:00
func (p *producer) drainInternalQueue() {
2017-03-09 17:32:05 -03:00
for m := range p.internalQueue {
2017-10-09 19:33:27 -03:00
var retry = true
2017-10-30 16:51:47 -02:00
2017-10-09 19:33:27 -03:00
for retry && !p.isClosed() {
log.WithFields(log.Fields{
2017-10-30 16:51:47 -02:00
"action": m.action,
"body": m.msg.Body,
"message_id": m.msg.MessageId,
"type": "goevents",
"sub_type": "producer",
2018-02-12 00:54:10 -02:00
"exchange": p.exchangeName,
2018-05-04 09:55:55 -03:00
}).Debug("Publishing message to the exchange.")
2017-03-09 17:32:05 -03:00
// block until confirmation
2017-10-10 17:49:53 -03:00
err := p.publishMessage(m.msg, m.action)
retry = err != nil
2017-03-09 17:32:05 -03:00
if err != nil {
log.WithFields(log.Fields{
2017-10-30 16:51:47 -02:00
"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...")
2017-03-09 17:32:05 -03:00
}
}
2016-12-01 10:52:22 -02:00
}
2017-03-09 17:32:05 -03:00
for _, c := range p.closes {
c <- true
}
2016-12-01 10:52:22 -02:00
}