-
Notifications
You must be signed in to change notification settings - Fork 0
/
pub.go
110 lines (88 loc) · 2.21 KB
/
pub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package pubsub
import (
"context"
"sync/atomic"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/rs/zerolog"
"github.com/soulgarden/go-amqp-reconnect/rabbitmq"
)
type Pub interface {
Publish(e amqp.Publishing)
StartPublisher(ctx context.Context) error
}
type pub struct {
errorsNumber int64
events chan amqp.Publishing
conn *rabbitmq.Connection
rmq Rmqer
cfg *Cfg
logger *zerolog.Logger
}
func NewPub(conn *rabbitmq.Connection, cfg *Cfg, rmq Rmqer, logger *zerolog.Logger) *pub {
return &pub{
errorsNumber: 0,
events: make(chan amqp.Publishing, cfg.QueueLen),
conn: conn,
rmq: rmq,
cfg: cfg,
logger: logger,
}
}
func (p *pub) Publish(e amqp.Publishing) {
p.events <- e
}
func (p *pub) StartPublisher(ctx context.Context) error {
sendCh, err := p.rmq.OpenChannel()
if err != nil {
p.logger.Err(err).Msg("open channel")
return err
}
if p.cfg.ExchangeName != "" {
err = p.rmq.ExchangeDeclare(sendCh)
if err != nil {
p.logger.Err(err).Str("name", p.cfg.ExchangeName).Msg("declare exchange")
return err
}
}
if p.cfg.QueueName != "" {
err = p.rmq.QueueDeclare(sendCh)
if err != nil {
p.logger.Err(err).Str("name", p.cfg.QueueName).Msg("declare queue")
return err
}
}
for {
select {
case <-ctx.Done():
p.logger.Warn().Int("count", len(p.events)).Msg("send all remaining events")
for len(p.events) > 0 {
_ = p.sendToQueue(<-p.events, sendCh)
}
p.logger.Warn().Msg("publisher stopped")
return nil
case e := <-p.events:
err = p.sendToQueue(e, sendCh)
if err != nil {
if atomic.LoadInt64(&p.errorsNumber) >= p.cfg.ErrorsThreshold {
p.logger.Err(err).Interface("events", p.events).Msg("errors threshold reached")
return err
}
} else {
atomic.StoreInt64(&p.errorsNumber, 0)
}
}
}
}
func (p *pub) dequeue() interface{} {
return <-p.events
}
func (p *pub) sendToQueue(e amqp.Publishing, sendCh Channel) error {
err := sendCh.Publish(p.cfg.ExchangeName, p.cfg.QueueName, false, false, e)
if err != nil {
atomic.AddInt64(&p.errorsNumber, 1)
p.logger.Err(err).Str("id", e.MessageId).Msg("publish event")
p.events <- e
return err
}
return nil
}