-
Notifications
You must be signed in to change notification settings - Fork 3
/
consumer.go
100 lines (79 loc) · 2.47 KB
/
consumer.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
package nsq
import (
"context"
"github.com/alexfalkowski/go-service/telemetry/tracer"
"github.com/alexfalkowski/go-service/transport/nsq/handler"
"github.com/alexfalkowski/go-service/transport/nsq/marshaller"
"github.com/alexfalkowski/go-service/transport/nsq/meta"
"github.com/alexfalkowski/go-service/transport/nsq/telemetry/logger"
lzap "github.com/alexfalkowski/go-service/transport/nsq/telemetry/logger/zap"
"github.com/alexfalkowski/go-service/transport/nsq/telemetry/metrics"
ntracer "github.com/alexfalkowski/go-service/transport/nsq/telemetry/tracer"
"github.com/nsqio/go-nsq"
"go.opentelemetry.io/otel/metric"
"go.uber.org/fx"
"go.uber.org/zap"
)
// ConsumerOption for NSQ.
type ConsumerOption interface{ apply(*consumerOptions) }
type consumerOptions struct {
logger *zap.Logger
tracer ntracer.Tracer
meter metric.Meter
}
type consumerOptionFunc func(*consumerOptions)
func (f consumerOptionFunc) apply(o *consumerOptions) { f(o) }
// WithConsumerLogger for NSQ.
func WithConsumerLogger(logger *zap.Logger) ConsumerOption {
return consumerOptionFunc(func(o *consumerOptions) {
o.logger = logger
})
}
// WithConsumerConfig for NSQ.
func WithConsumerTracer(tracer ntracer.Tracer) ConsumerOption {
return consumerOptionFunc(func(o *consumerOptions) {
o.tracer = tracer
})
}
// WithConsumerMetrics for NSQ.
func WithConsumerMetrics(meter metric.Meter) ConsumerOption {
return consumerOptionFunc(func(o *consumerOptions) {
o.meter = meter
})
}
// RegisterConsumer for NSQ.
func RegisterConsumer(lc fx.Lifecycle, topic, channel string, cfg *Config, h handler.Handler, m marshaller.Marshaller, opts ...ConsumerOption) error {
defaultOptions := &consumerOptions{tracer: tracer.NewNoopTracer("nsq")}
for _, o := range opts {
o.apply(defaultOptions)
}
c, err := nsq.NewConsumer(topic, channel, nsq.NewConfig())
if err != nil {
return err
}
c.SetLogger(logger.NewLogger(), nsq.LogLevelInfo)
if defaultOptions.logger != nil {
h = lzap.NewHandler(topic, channel, defaultOptions.logger, h)
}
if defaultOptions.meter != nil {
handler, err := metrics.NewHandler(topic, channel, defaultOptions.meter, h)
if err != nil {
return err
}
h = handler
}
h = ntracer.NewHandler(topic, channel, defaultOptions.tracer, h)
h = meta.NewHandler(h)
c.AddHandler(handler.New(h, m))
err = c.ConnectToNSQLookupd(cfg.LookupHost)
if err != nil {
return err
}
lc.Append(fx.Hook{
OnStop: func(context.Context) error {
c.Stop()
return nil
},
})
return nil
}