forked from beatlabs/patron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
component.go
92 lines (81 loc) · 1.85 KB
/
component.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
package async
import (
"context"
"sync"
agr_errors "github.com/mantzas/patron/errors"
"github.com/mantzas/patron/log"
"github.com/pkg/errors"
)
// Component implementation of a async component.
type Component struct {
proc ProcessorFunc
sync.Mutex
cns Consumer
cnl context.CancelFunc
}
// New returns a new async component.
func New(p ProcessorFunc, cns Consumer) (*Component, error) {
if p == nil {
return nil, errors.New("work processor is required")
}
if cns == nil {
return nil, errors.New("consumer is required")
}
return &Component{
proc: p,
cns: cns,
}, nil
}
// Run starts the consumer processing loop messages.
func (c *Component) Run(ctx context.Context) error {
c.Lock()
ctx, cnl := context.WithCancel(ctx)
c.cnl = cnl
c.Unlock()
chMsg, chErr, err := c.cns.Consume(ctx)
if err != nil {
return errors.Wrap(err, "failed to get consumer channels")
}
failCh := make(chan error)
go func() {
for {
select {
case <-ctx.Done():
log.Info("canceling consuming messages requested")
failCh <- nil
return
case m := <-chMsg:
log.Debug("New message from consumer arrived")
go func(msg Message) {
err = c.proc(msg)
if err != nil {
agr := agr_errors.New()
agr.Append(errors.Wrap(err, "failed to process message. Nack message"))
agr.Append(errors.Wrap(msg.Nack(), "failed to NACK message"))
failCh <- agr
return
}
if err := msg.Ack(); err != nil {
failCh <- err
}
}(m)
case errMsg := <-chErr:
failCh <- errors.Wrap(errMsg, "an error occurred during message consumption")
return
}
}
}()
return <-failCh
}
// Shutdown gracefully the component by closing the consumer.
func (c *Component) Shutdown(ctx context.Context) error {
c.Lock()
defer c.Unlock()
if c.cnl != nil {
c.cnl()
}
if c.cns == nil {
return nil
}
return c.cns.Close()
}