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

307 lines
6.0 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
wg sync.WaitGroup
conn *connection
channel *amqplib.Channel
notifyConfirm chan amqplib.Confirmation
connectionClosed <-chan error
closeQueue chan bool
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
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) {
conn := c.(*connection)
2017-10-10 17:49:53 -03:00
producer := &producer{
conn: c.(*connection),
config: config,
internalQueue: make(chan message, 2),
exchangeName: exchange,
notifyConfirm: make(chan amqplib.Confirmation),
closeQueue: make(chan bool),
connectionClosed: conn.NotifyConnectionClose(),
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()
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
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.wg.Add(1)
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
}
// Close the producer's internal queue.
func (p *producer) Close() {
p.setClosed()
p.wg.Wait()
p.closeQueue <- true
2017-03-09 17:32:05 -03:00
close(p.internalQueue)
close(p.closeQueue)
p.channel.Close()
}
// 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.notifyConfirm = make(chan amqplib.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. Draining internal queue.")
go p.drainInternalQueue()
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()
for !p.isClosed() {
<-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) {
log.WithFields(log.Fields{
"action": queue,
"body": msg.Body,
"message_id": msg.MessageId,
"type": "goevents",
"sub_type": "producer",
"exchange": p.exchangeName,
}).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")
}
}
}()
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() {
for {
select {
case <-p.closeQueue:
return
case <-p.connectionClosed:
return
case m := <-p.internalQueue:
// block until confirmation
2017-10-10 17:49:53 -03:00
err := p.publishMessage(m.msg, m.action)
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...")
p.internalQueue <- m
} else {
p.wg.Done()
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
}