-
Notifications
You must be signed in to change notification settings - Fork 27
/
bokchoy.go
345 lines (278 loc) · 7.8 KB
/
bokchoy.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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package bokchoy
import (
"context"
"fmt"
"log"
"os"
"os/user"
"strings"
"sync"
"github.com/redis/go-redis/v9"
"github.com/thoas/bokchoy/logging"
"github.com/thoas/go-funk"
"github.com/pkg/errors"
)
// Bokchoy is the main object which stores all configuration, queues
// and broker.
type Bokchoy struct {
cfg Config
wg *sync.WaitGroup
defaultOptions *Options
broker Broker
queues map[string]*Queue
middlewares []func(Handler) Handler
servers []Server
Serializer Serializer
Logger logging.Logger
Tracer Tracer
}
// New initializes a new Bokchoy instance.
func New(ctx context.Context, cfg Config, options ...Option) (*Bokchoy, error) {
opts := newOptions()
for i := range options {
options[i](opts)
}
var (
err error
tracer Tracer
)
logger := logging.NewNopLogger()
if opts.Logger != nil {
logger = opts.Logger
}
tracer = opts.Tracer
if tracer == nil {
tracer = NewLoggerTracer(logger)
}
wg := &sync.WaitGroup{}
bok := &Bokchoy{
cfg: cfg,
Serializer: newSerializer(cfg.Serializer),
queues: make(map[string]*Queue),
wg: wg,
Logger: logger,
Tracer: tracer,
defaultOptions: opts,
servers: opts.Servers,
}
if opts.Serializer != nil {
bok.Serializer = opts.Serializer
}
if opts.Broker != nil {
bok.broker = opts.Broker
} else {
bok.broker = newBroker(cfg.Broker,
logger.With(logging.String("component", "broker")))
}
if opts.Initialize {
bok.Logger.Debug(ctx, fmt.Sprintf("Connecting to %s...", bok.broker))
err = bok.broker.Initialize(ctx)
if err != nil {
return nil, errors.Wrap(err, "unable to initialize broker")
}
bok.Logger.Debug(ctx, fmt.Sprintf("Connected to %s", bok.broker))
}
for i := range cfg.Queues {
bok.Queue(cfg.Queues[i].Name)
}
return bok, nil
}
// NewDefault initializes a new Bokchoy instance for the most common scenario.
func NewDefault(ctx context.Context, redisURL string) (*Bokchoy, error) {
opt, err := redis.ParseURL(redisURL)
if err != nil {
return nil, errors.Wrap(err, "unable to parse redis url")
}
return New(ctx, Config{
Broker: BrokerConfig{
Type: "redis",
Redis: RedisConfig{
Type: "client",
Client: RedisClientConfig{
Addr: opt.Addr,
Password: opt.Password,
DB: opt.DB,
},
},
},
})
}
// Use append a new middleware to the system.
func (b *Bokchoy) Use(sub ...func(Handler) Handler) *Bokchoy {
b.middlewares = append(b.middlewares, sub...)
return b
}
// Empty empties initialized queues.
func (b *Bokchoy) Empty(ctx context.Context) error {
for i := range b.queues {
err := b.queues[i].Empty(ctx)
if err != nil {
return err
}
}
return nil
}
// Flush flushes data of the entire system.
func (b *Bokchoy) Flush(ctx context.Context) error {
return b.broker.Flush(ctx)
}
// Queue gets or creates a new queue.
func (b *Bokchoy) Queue(name string) *Queue {
queue, ok := b.queues[name]
if !ok {
queue = &Queue{
name: name,
broker: b.broker,
serializer: b.Serializer,
logger: b.Logger.With(logging.String("component", "queue")),
tracer: b.Tracer,
wg: b.wg,
defaultOptions: b.defaultOptions,
middlewares: b.middlewares,
}
b.queues[name] = queue
}
return queue
}
// Stop stops all queues and consumers.
func (b *Bokchoy) Stop(ctx context.Context) {
fields := []logging.Field{
logging.String("queues", strings.Join(b.QueueNames(), ", ")),
}
b.Logger.Debug(ctx, "Stopping queues...", fields...)
for i := range b.queues {
b.queues[i].stop(ctx)
}
b.Logger.Debug(ctx, "Queues stopped", fields...)
if len(b.servers) == 0 {
return
}
fields = []logging.Field{
logging.String("servers", strings.Join(b.ServerNames(), ", ")),
}
b.Logger.Debug(ctx, "Stopping servers...", fields...)
for i := range b.servers {
b.servers[i].Stop(ctx)
b.wg.Done()
}
b.Logger.Debug(ctx, "Servers stopped", fields...)
}
// QueueNames returns the managed queue names.
func (b *Bokchoy) QueueNames() []string {
names := make([]string, 0, len(b.queues))
for k := range b.queues {
names = append(names, k)
}
return names
}
// ServerNames returns the managed server names.
func (b *Bokchoy) ServerNames() []string {
names := make([]string, 0, len(b.servers))
for i := range b.servers {
names = append(names, fmt.Sprintf("%s", b.servers[i]))
}
return names
}
func (b *Bokchoy) displayOutput(ctx context.Context, queueNames []string) {
buf := NewColorWriter(ColorBrightGreen)
buf.Write("%s\n", logo)
buf = buf.WithColor(ColorBrightBlue)
user, err := user.Current()
if err == nil {
hostname, err := os.Hostname()
if err == nil {
buf.Write("%s@%s %v\n", user.Username, hostname, Version)
buf.Write("- uid: %s\n", user.Uid)
buf.Write("- gid: %s\n\n", user.Gid)
}
}
buf.Write("[config]\n")
buf.Write(fmt.Sprintf("- concurrency: %d\n", b.defaultOptions.Concurrency))
buf.Write(fmt.Sprintf("- serializer: %s\n", b.Serializer))
buf.Write(fmt.Sprintf("- max retries: %d\n", b.defaultOptions.MaxRetries))
buf.Write(fmt.Sprintf("- retry intervals: %s\n", b.defaultOptions.RetryIntervalsDisplay()))
buf.Write(fmt.Sprintf("- ttl: %s\n", b.defaultOptions.TTL))
buf.Write(fmt.Sprintf("- countdown: %s\n", b.defaultOptions.Countdown))
buf.Write(fmt.Sprintf("- timeout: %s\n", b.defaultOptions.Timeout))
buf.Write(fmt.Sprintf("- tracer: %s\n", b.Tracer))
buf.Write(fmt.Sprintf("- broker: %s\n", b.broker))
buf.Write("\n[queues]\n")
for i := range queueNames {
buf.Write(fmt.Sprintf("- %s\n", queueNames[i]))
}
if len(b.servers) > 0 {
buf.Write("\n[servers]\n")
for i := range b.servers {
buf.Write(fmt.Sprintf("- %s", b.servers[i]))
}
}
log.Print(buf)
}
// Run runs the system and block the current goroutine.
func (b *Bokchoy) Run(ctx context.Context, options ...Option) error {
opts := newOptions()
for i := range options {
options[i](opts)
}
if len(opts.Servers) > 0 {
b.servers = opts.Servers
}
err := b.broker.Ping(ctx)
if err != nil {
return err
}
queueNames := b.QueueNames()
if len(opts.Queues) > 0 {
queueNames = funk.FilterString(queueNames, func(queueName string) bool {
return funk.InStrings(opts.Queues, queueName)
})
}
if len(queueNames) == 0 {
b.Logger.Debug(ctx, "No queue to run...")
return ErrNoQueueToRun
}
fields := []logging.Field{
logging.String("queues", strings.Join(queueNames, ", ")),
}
b.Logger.Debug(ctx, "Starting queues...", fields...)
for i := range b.queues {
if !funk.InStrings(queueNames, b.queues[i].Name()) {
continue
}
b.queues[i].start(ctx)
}
b.Logger.Debug(ctx, "Queues started", fields...)
fields = []logging.Field{
logging.String("servers", strings.Join(b.ServerNames(), ", ")),
}
if len(b.servers) > 0 {
b.Logger.Debug(ctx, "Starting servers...", fields...)
for i := range b.servers {
b.wg.Add(1)
go func(server Server) {
err := server.Start(ctx)
if err != nil {
b.Logger.Error(ctx, fmt.Sprintf("Receive error when starting %s", server), logging.Error(err))
}
}(b.servers[i])
}
b.Logger.Debug(ctx, "Servers started", fields...)
}
if !b.defaultOptions.DisableOutput {
b.displayOutput(ctx, queueNames)
}
b.wg.Wait()
return nil
}
// Publish publishes a new payload to a queue.
func (b *Bokchoy) Publish(ctx context.Context, queueName string, payload interface{}, options ...Option) (*Task, error) {
return b.Queue(queueName).Publish(ctx, payload, options...)
}
// Handle registers a new handler to consume tasks for a queue.
func (b *Bokchoy) Handle(queueName string, sub Handler, options ...Option) {
b.HandleFunc(queueName, sub.Handle, options...)
}
// HandleFunc registers a new handler function to consume tasks for a queue.
func (b *Bokchoy) HandleFunc(queueName string, f HandlerFunc, options ...Option) {
b.Queue(queueName).HandleFunc(f, options...)
}