-
Notifications
You must be signed in to change notification settings - Fork 5
/
NatsClient.go
147 lines (128 loc) · 5.18 KB
/
NatsClient.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
/*
* Copyright (c) 2020 Devtron Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pubsub_lib
import (
"github.com/caarlos0/env"
"github.com/nats-io/nats.go"
"go.uber.org/zap"
"time"
)
type NatsClient struct {
logger *zap.SugaredLogger
JetStrCtxt nats.JetStreamContext
Conn *nats.Conn
}
type NatsClientConfig struct {
NatsServerHost string `env:"NATS_SERVER_HOST" envDefault:"nats://devtron-nats.devtroncd:4222"`
// consumer wise
// NatsMsgProcessingBatchSize is the number of messages that will be processed in one go
NatsMsgProcessingBatchSize int `env:"NATS_MSG_PROCESSING_BATCH_SIZE" envDefault:"1"`
// NatsMsgBufferSize is the number of messages that will be buffered in memory (channel size)
// it is recommended to set this value equal to NatsMsgProcessingBatchSize as we want to process maximum messages in the buffer in one go.
// Note: if NatsMsgBufferSize is less than NatsMsgProcessingBatchSize
// then the wait time for the unprocessed messages in the buffer will be high.(total process time = life-time in buffer + processing time)
// NatsMsgBufferSize can be configured independently of NatsMsgProcessingBatchSize if needed by setting its value to positive value in env.
// if NatsMsgBufferSize set to a non-positive value then it will take the value of NatsMsgProcessingBatchSize.
// Note: always get this value by calling GetNatsMsgBufferSize method
NatsMsgBufferSize int `env:"NATS_MSG_BUFFER_SIZE" envDefault:"-1"`
NatsMsgMaxAge int `env:"NATS_MSG_MAX_AGE" envDefault:"86400"`
NatsMsgAckWaitInSecs int `env:"NATS_MSG_ACK_WAIT_IN_SECS" envDefault:"120"`
}
func (ncc NatsClientConfig) GetNatsMsgBufferSize() int {
// if NatsMsgBufferSize is set to a non-positive value then it will take the value of NatsMsgProcessingBatchSize.
if ncc.NatsMsgBufferSize <= 0 {
return ncc.NatsMsgProcessingBatchSize
}
return ncc.NatsMsgBufferSize
}
func (ncc NatsClientConfig) GetDefaultNatsConsumerConfig() NatsConsumerConfig {
return NatsConsumerConfig{
NatsMsgProcessingBatchSize: ncc.NatsMsgProcessingBatchSize,
NatsMsgBufferSize: ncc.GetNatsMsgBufferSize(),
AckWaitInSecs: ncc.NatsMsgAckWaitInSecs,
}
}
func (ncc NatsClientConfig) GetDefaultNatsStreamConfig() NatsStreamConfig {
return NatsStreamConfig{
StreamConfig: StreamConfig{
MaxAge: time.Duration(ncc.NatsMsgMaxAge) * time.Second,
},
}
}
type StreamConfig struct {
MaxAge time.Duration `json:"max_age"`
}
type NatsStreamConfig struct {
StreamConfig StreamConfig `json:"streamConfig"`
}
type NatsConsumerConfig struct {
// NatsMsgProcessingBatchSize is the number of messages that will be processed in one go
NatsMsgProcessingBatchSize int `json:"natsMsgProcessingBatchSize"`
// NatsMsgBufferSize is the number of messages that will be buffered in memory (channel size).
// Note: always get this value by calling GetNatsMsgBufferSize method
NatsMsgBufferSize int `json:"natsMsgBufferSize"`
// AckWaitInSecs is the time in seconds for which the message can be in unacknowledged state
AckWaitInSecs int `json:"ackWaitInSecs"`
}
func (consumerConf NatsConsumerConfig) GetNatsMsgBufferSize() int {
// if NatsMsgBufferSize is set to a non-positive value then it will take the value of NatsMsgProcessingBatchSize.
if consumerConf.NatsMsgBufferSize <= 0 {
return consumerConf.NatsMsgProcessingBatchSize
}
return consumerConf.NatsMsgBufferSize
}
// func (consumerConf NatsConsumerConfig) GetNatsMsgProcessingBatchSize() int {
// if nbs := consumerConf.GetNatsMsgBufferSize(); nbs < consumerConf.NatsMsgProcessingBatchSize {
// return nbs
// }
// return consumerConf.NatsMsgProcessingBatchSize
// }
func NewNatsClient(logger *zap.SugaredLogger) (*NatsClient, error) {
cfg := &NatsClientConfig{}
err := env.Parse(cfg)
if err != nil {
logger.Error("error occurred while parsing nats client config", "err", err)
return &NatsClient{}, err
}
// Connect to NATS
nc, err := nats.Connect(cfg.NatsServerHost,
nats.ReconnectWait(10*time.Second), nats.MaxReconnects(100),
nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
logger.Errorw("Nats Connection got disconnected!", "Reason", err)
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
logger.Infow("Nats Connection got reconnected", "url", nc.ConnectedUrl())
}),
nats.ClosedHandler(func(nc *nats.Conn) {
logger.Errorw("Nats Client Connection closed!", "Reason", nc.LastError())
}))
if err != nil {
logger.Error("err", err)
return &NatsClient{}, err
}
// Create a jetstream context
js, err := nc.JetStream()
if err != nil {
logger.Errorw("Error while creating jetstream context", "error", err)
}
natsClient := &NatsClient{
logger: logger,
JetStrCtxt: js,
Conn: nc,
}
return natsClient, nil
}