-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor.go
More file actions
268 lines (228 loc) · 6.46 KB
/
processor.go
File metadata and controls
268 lines (228 loc) · 6.46 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"math/rand/v2"
"time"
"github.com/rabbitmq/amqp091-go"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
var jsonMarshal = json.Marshal
const QueueProcessingName = "queue_processing"
type RestAPI interface {
SimulateProcessing(*Queue) error
}
type Publisher interface {
PublishWithContext(ctx context.Context, exchange, key string, mandatory, immediate bool, msg amqp091.Publishing) error
Consume(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args amqp091.Table) (<-chan amqp091.Delivery, error)
QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp091.Table) (amqp091.Queue, error)
Close() error
}
type Closer interface {
Close() error
Channel() (*amqp091.Channel, error)
}
type QueueProcessor struct {
repo *Repository
conn Closer
channel Publisher
api RestAPI
}
// processorOptions is an unexported struct to hold optional dependencies for testing.
type processorOptions struct {
conn Closer
channel Publisher
}
func WithConnection(conn Closer) func(*processorOptions) {
return func(o *processorOptions) {
o.conn = conn
}
}
func WithChannel(channel Publisher) func(*processorOptions) {
return func(o *processorOptions) {
o.channel = channel
}
}
func NewQueueProcessor(cfg *Config, db *gorm.DB, api RestAPI, opts ...func(*processorOptions)) (*QueueProcessor, error) {
options := &processorOptions{}
for _, opt := range opts {
opt(options)
}
if options.conn == nil {
// Create real connection and channel (for production)
if cfg == nil {
return nil, errors.New("config is required for production setup")
}
conn, err := amqp091.Dial(cfg.RabbitMQURL)
if err != nil {
return nil, fmt.Errorf("failed to connect to RabbitMQ: %w", err)
}
options.conn = conn
}
if options.channel == nil {
conn := options.conn
chann, err := conn.Channel()
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to open RabbitMQ channel: %w", err)
}
_, err = chann.QueueDeclare(
QueueProcessingName, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
chann.Close()
conn.Close()
return nil, fmt.Errorf("failed to declare RabbitMQ queue: %w", err)
}
options.channel = chann
}
return &QueueProcessor{
repo: NewRepository(db),
conn: options.conn,
channel: options.channel,
api: api,
}, nil
}
func (p *QueueProcessor) Start() error {
log.Info().Msg("Queue processor started")
// Start consuming messages from RabbitMQ
msgs, err := p.channel.Consume(
QueueProcessingName, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return fmt.Errorf("failed to register RabbitMQ consumer: %w", err)
}
log.Info().Msg("RabbitMQ consumer started, waiting for messages...")
for d := range msgs {
ctx := context.Background()
if err := p.ProcessEligibleQueue(ctx); err != nil {
log.Error().Msgf("failed to process eligible queue: %s", err.Error())
d.Nack(false, true) // requeue
} else {
d.Ack(false)
}
}
return nil
}
func (p *QueueProcessor) Stop() {
if p.channel != nil {
p.channel.Close()
}
if p.conn != nil {
p.conn.Close()
}
log.Info().Msg("Queue processor stopped")
}
func (p *QueueProcessor) TriggerProcessing(ctx context.Context) error {
message := map[string]string{"trigger": TriggerStartProcessing}
body, err := jsonMarshal(message)
if err != nil {
return err
}
return p.channel.PublishWithContext(
ctx,
"", // exchange
QueueProcessingName, // routing key
false, // mandatory
false, // immediate
amqp091.Publishing{
ContentType: "application/json",
Body: body,
},
)
}
func (p *QueueProcessor) ProcessEligibleQueue(ctx context.Context) error {
// Get next eligible queue (1 queue only, ordered by shifting logic)
queues, err := p.repo.GetEligibleQueues(ctx)
if err != nil {
return err
}
if len(queues) == 0 {
log.Debug().Msg("no eligible queues to process")
return nil
}
queue := &queues[0]
log.Info().Msgf("processing queue %s (ID: %d)", queue.Name, queue.ID)
// Simulate actual processing logic
if err := p.api.SimulateProcessing(queue); err != nil {
log.Warn().Msgf("queue %s (ID: %d) failed, retry count: %d", queue.Name, queue.ID, queue.RetryCount)
queue.Status = StatusFailed
queue.LastRetryAt = sql.NullTime{Time: time.Now(), Valid: true}
queue.RetryCount++
if err := p.repo.Save(ctx, queue); err != nil {
log.Error().Msgf("failed to update queue %s: %s", queue.Name, err.Error())
return err
}
return err
}
queue.Status = StatusCompleted
// Update queue status in database
if err := p.repo.Save(ctx, queue); err != nil {
log.Error().Msgf("failed to update queue %s: %s", queue.Name, err.Error())
return err
}
// Check if there are more eligible queues to process
exist, err := p.repo.HasRemainingQueues(ctx)
if err != nil {
log.Error().Msgf("failed to check remaining queues: %s", err.Error())
return err
}
// If there are more queues, trigger RabbitMQ again for chain processing
if !exist {
log.Info().Msg("no more eligible queues, processing complete")
return nil
}
log.Info().Msg("found more eligible queues, triggering next processing")
if err := p.triggerNextProcessing(ctx); err != nil {
log.Error().Msgf("failed to trigger next processing: %s", err.Error())
}
return nil
}
func (p *QueueProcessor) triggerNextProcessing(ctx context.Context) error {
message := map[string]string{"trigger": TriggerProcessNext}
body, err := jsonMarshal(message)
if err != nil {
return err
}
return p.channel.PublishWithContext(
ctx,
"", // exchange
QueueProcessingName, // routing key
false, // mandatory
false, // immediate
amqp091.Publishing{
ContentType: "application/json",
Body: body,
},
)
}
type FakeAPI struct {
randFloat func() float32
}
// SimulateProcessing simulates random success/failure for demo purposes
func (p *FakeAPI) SimulateProcessing(*Queue) error {
// Use default if not set
rander := p.randFloat
if rander == nil {
rander = rand.Float32
}
if rander() < 0.7 {
return nil
}
return errors.New("processing failed")
}