-
Notifications
You must be signed in to change notification settings - Fork 2
/
ampqhandler.go
232 lines (190 loc) · 5.43 KB
/
ampqhandler.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package amqphandler
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/ViBiOh/httputils/v3/pkg/cron"
"github.com/ViBiOh/httputils/v3/pkg/flags"
"github.com/ViBiOh/httputils/v3/pkg/logger"
"github.com/ViBiOh/mailer/pkg/mailer"
"github.com/ViBiOh/mailer/pkg/model"
"github.com/streadway/amqp"
)
// App of package
type App interface {
Start(<-chan struct{})
Ping() error
Close()
}
// Config of package
type Config struct {
url *string
queue *string
exchange *string
retryInterval *string
maxRetry *int
}
type app struct {
mailerApp mailer.App
amqpClient model.AMQPClient
retryInterval time.Duration
maxRetry int64
}
// Flags adds flags for configuring package
func Flags(fs *flag.FlagSet, prefix string) Config {
return Config{
url: flags.New(prefix, "amqp").Name("URL").Default("").Label("Address in the form amqps?://<user>:<password>@<address>:<port>/<vhost>").ToString(fs),
exchange: flags.New(prefix, "amqp").Name("Exchange").Default("mailer").Label("Exchange name").ToString(fs),
queue: flags.New(prefix, "amqp").Name("Queue").Default("mailer").Label("Queue name").ToString(fs),
retryInterval: flags.New(prefix, "amqp").Name("RetryInterval").Default("1h").Label("Interval duration when send fails").ToString(fs),
maxRetry: flags.New(prefix, "amqp").Name("MaxRetry").Default(3).Label("Max send retries").ToInt(fs),
}
}
// New creates new App from Config
func New(config Config, mailerApp mailer.App) (App, error) {
url := strings.TrimSpace(*config.url)
if len(url) == 0 {
return app{}, nil
}
retryInterval, err := time.ParseDuration(strings.TrimSpace(*config.retryInterval))
if err != nil {
return nil, fmt.Errorf("unable to parse retry duration: %s", err)
}
client, err := model.GetAMQPClient(url, strings.TrimSpace(*config.exchange), strings.TrimSpace(*config.queue))
if err != nil {
return nil, fmt.Errorf("unable to create amqp client: %s", err)
}
return app{
retryInterval: retryInterval,
maxRetry: int64(*config.maxRetry),
mailerApp: mailerApp,
amqpClient: client,
}, nil
}
func (a app) Start(done <-chan struct{}) {
messages, err := a.amqpClient.Listen()
if err != nil {
logger.Error("unable to listen on queue: %s", err)
return
}
defer a.amqpClient.Close()
logger.Info("Listening queue `%s` on vhost `%s` as `%s`", a.amqpClient.QueueName(), a.amqpClient.Vhost(), a.amqpClient.ClientName())
go a.startGarbageCollector(done)
for {
select {
case <-done:
return
case message := <-messages:
if err := a.sendEmail(message.Body); err != nil {
logger.Error("unable to send email: %s", err)
model.LoggedReject(message, false)
continue
}
model.LoggedAck(message)
}
}
}
func (a app) sendEmail(payload []byte) error {
ctx := context.Background()
var mailRequest model.MailRequest
if err := json.Unmarshal(payload, &mailRequest); err != nil {
return fmt.Errorf("unable to parse payload: %s", err)
}
output, err := a.mailerApp.Render(ctx, mailRequest)
if err != nil {
return fmt.Errorf("unable to render email: %s", err)
}
return a.mailerApp.Send(ctx, mailRequest.ConvertToMail(output))
}
func (a app) startGarbageCollector(done <-chan struct{}) {
logger.Info("Launching garbage collector every %s", a.retryInterval)
defer logger.Info("Garbage collector cron is off")
garbageCron := cron.New().Each(a.retryInterval).Now()
defer garbageCron.Stop()
go garbageCron.Start(func(_ time.Time) error {
return a.garbageCollector(done)
}, func(err error) {
logger.Error("error while running garbage collector: %s", err)
})
signals := make(chan os.Signal, 1)
defer close(signals)
signal.Notify(signals, syscall.SIGUSR1)
defer signal.Stop(signals)
for {
select {
case <-done:
return
case <-signals:
garbageCron.Now()
}
}
}
func (a app) garbageCollector(done <-chan struct{}) error {
isDone := func() bool {
select {
case <-done:
return true
default:
return false
}
}
for !isDone() {
garbage, ok, err := a.amqpClient.GetGarbage()
if err != nil {
return fmt.Errorf("unable to get garbage message: %s", err)
}
if !ok {
return nil
}
count, err := getDeathCount(garbage.Headers)
if err != nil {
logger.Error("unable to get count from garbage: %s", err)
model.LoggedReject(garbage, false)
continue
}
if count > a.maxRetry {
logger.Error("message was rejected %d times, content was `%s`", a.maxRetry, garbage.Body)
model.LoggedAck(garbage)
continue
}
logger.Info("Requeuing message from garbage with payload=`%s`", garbage.Body)
if err := a.amqpClient.Send(model.ConvertDeliveryToPublishing(garbage), false); err != nil {
logger.Error("unable to re-send garbage message: %s", err)
model.LoggedReject(garbage, true)
continue
}
model.LoggedAck(garbage)
}
return nil
}
func getDeathCount(table amqp.Table) (int64, error) {
rawDeath := table["x-death"]
death, ok := rawDeath.([]interface{})
if !ok {
return 0, fmt.Errorf("`x-death` header in not an array")
}
if len(death) == 0 {
return 0, fmt.Errorf("`x-death` is an empty array")
}
deathData, ok := death[0].(amqp.Table)
if !ok {
return 0, fmt.Errorf("`x-death` datas are not a map")
}
count, ok := deathData["count"].(int64)
if !ok {
return 0, fmt.Errorf("`count` is not an int")
}
return count, nil
}
func (a app) Ping() error {
return a.amqpClient.Ping()
}
func (a app) Close() {
a.amqpClient.Close()
}