-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher.go
219 lines (172 loc) · 4.22 KB
/
publisher.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
package watermillnet
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/andyollylarkin/watermill-net/internal"
"github.com/sethvargo/go-retry"
)
type PublisherConfig struct {
RemoteAddr net.Addr
Marshaler Marshaler
Unmarshaler Unmarshaler
Logger watermill.LoggerAdapter
}
type Publisher struct {
conn Connection
marshaler Marshaler
unmarshaler Unmarshaler
addr net.Addr
logger watermill.LoggerAdapter
closed bool
mu sync.Mutex
waitAck bool
}
// NewPublisher create new publisher.
// ATTENTION! Set connection immediately after creation.
func NewPublisher(config PublisherConfig, waitAck bool) (*Publisher, error) {
if err := validatePublisherConfig(config); err != nil {
return nil, err
}
p := new(Publisher)
p.addr = config.RemoteAddr
p.marshaler = config.Marshaler
p.unmarshaler = config.Unmarshaler
p.logger = config.Logger
p.waitAck = waitAck
return p, nil
}
func validatePublisherConfig(c PublisherConfig) error {
if c.RemoteAddr == nil {
return &InvalidConfigError{InvalidField: "Addr", InvalidReason: "cant be nil"}
}
if c.Marshaler == nil {
return &InvalidConfigError{InvalidField: "Marshaler", InvalidReason: "cant be nil"}
}
if c.Unmarshaler == nil {
return &InvalidConfigError{InvalidField: "Unmarshaler", InvalidReason: "cant be nil"}
}
return nil
}
func (p *Publisher) SetConnection(c Connection) {
p.mu.Lock()
defer p.mu.Unlock()
p.conn = c
}
// GetConnection get publisher connection.
func (p *Publisher) GetConnection() (Connection, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn == nil {
return nil, ErrConnectionNotSet
}
if p.closed {
return nil, ErrPublisherClosed
}
return p.conn, nil
}
// Connect to remote side.
func (p *Publisher) Connect() error {
if p.closed {
return ErrPublisherClosed
}
if p.conn == nil {
return ErrConnectionNotSet
}
return p.conn.Connect(p.addr)
}
// Publish publishes provided messages to given topic.
// Publish can be synchronous or asynchronous - it depends on the implementation.
//
// Most publishers implementations don't support atomic publishing of messages.
// This means that if publishing one of the messages fails, the next messages will not be published.
//
// Publish must be thread safe.
func (p *Publisher) Publish(topic string, messages ...*message.Message) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return ErrPublisherClosed
}
if p.conn == nil {
return ErrConnectionNotSet
}
for _, msg := range messages {
m := internal.Message{
Topic: topic,
Message: msg,
}
b, err := p.marshaler.MarshalMessage(m)
if err != nil {
return err
}
b = internal.PrepareMessageForSend(b)
//nolint: gomnd
err = retry.Do(context.Background(), retry.NewConstant(time.Second*3), func(ctx context.Context) error {
_, err = p.conn.Write(b)
if err != nil {
return err
}
if p.waitAck {
if err = p.handleResponse(); err != nil { // wait ack or nack
if errors.Is(err, ErrIOTimeout) {
return retry.RetryableError(err)
}
return err
}
}
return nil
})
if err != nil {
return err
}
if p.logger != nil {
fields := watermill.LogFields{
"uuid": msg.UUID,
"topic": topic,
}
p.logger.Trace("Message published", fields)
}
}
return nil
}
func (p *Publisher) handleResponse() error {
r := bufio.NewReader(p.conn)
lenRaw, err := r.ReadBytes(internal.LenDelimiter)
if err != nil {
return err
}
readLen := internal.ReadLen(lenRaw[:len(lenRaw)-1]) // trim len delimiter
lr := io.LimitReader(r, int64(readLen))
respBody := make([]byte, readLen)
_, err = lr.Read(respBody)
if err != nil {
return fmt.Errorf("error read ack message %w", err)
}
var ackMsg internal.AckMessage
err = p.unmarshaler.UnmarshalMessage(respBody, &ackMsg)
if err != nil {
return err
}
if !ackMsg.Acked {
return fmt.Errorf("%w: %s", ErrNacked, ackMsg.UUID)
}
return nil
}
// Close should flush unsent messages, if publisher is async.
func (p *Publisher) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn == nil {
return ErrConnectionNotSet
}
p.closed = true
return p.conn.Close()
}