-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
489 lines (395 loc) · 10.7 KB
/
client.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Package pulsar implements a Apache Pulsar Client.
package pulsar
import (
"context"
"errors"
"fmt"
"net/url"
"reflect"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
pb "github.com/cornelk/pulsar-go/proto"
"google.golang.org/protobuf/proto"
)
// Client constants that get sent to Pulsar.
const (
libraryVersion = "0.01" // TODO use git version tag
protocolVersion = int32(pb.ProtocolVersion_v15)
)
// Client implements a Pulsar client.
type Client struct {
log Logger
host string
cmds commands
dialer dialer
cancel context.CancelFunc
ctx context.Context // passed to consumers/producers
closing atomic.Bool
conn *conn
connMutex sync.RWMutex // protects conn init/close access
req *requests
consumers *consumerRegistry
producers *producerRegistry
connected chan struct{}
stopped chan struct{}
}
// NewClient creates a new Pulsar client.
func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
conf := applyOptions(opts)
if !strings.Contains(serverURL, "://") {
serverURL = "pulsar://" + serverURL
}
u, err := url.Parse(serverURL)
if err != nil {
return nil, fmt.Errorf("parsing URL: %w", err)
}
if u.Port() == "" {
// Use default port.
u.Host += ":6650"
}
ctx, cancel := context.WithCancel(context.Background())
c := &Client{
log: conf.Logger,
host: u.Host,
dialer: conf.dialer,
cancel: cancel,
ctx: ctx,
req: newRequests(),
consumers: newConsumerRegistry(),
producers: newProducerRegistry(),
connected: make(chan struct{}, 1),
stopped: make(chan struct{}, 1),
}
if c.log == nil || (reflect.ValueOf(c.log).Kind() == reflect.Ptr && reflect.ValueOf(c.log).IsNil()) {
c.log = newLogger()
}
c.cmds = c.newCommandMap()
return c, nil
}
// Dial connects to the Pulsar server.
// This needs to be called before a Consumer or Producer can be created.
func (c *Client) Dial(ctx context.Context) error {
conn, err := c.dialer(ctx, c.log, c.host)
if err != nil {
c.log.Errorf("Dialing failed: %s", err.Error())
return err
}
c.connMutex.Lock()
c.conn = conn
c.connMutex.Unlock()
if err = sendConnectCommand(conn); err != nil {
return err
}
go c.readCommands()
select {
case <-ctx.Done():
return ctx.Err()
case <-c.connected:
return nil
}
}
// NewProducer creates a new Producer, returning after the connection
// has been made.
func (c *Client) NewProducer(ctx context.Context, config ProducerConfig) (*Producer, error) {
if c.closing.Load() {
return nil, ErrClientClosing
}
// TODO check connected state
b := c.newBrokerConnection()
id := c.producers.newID()
prod, err := newProducer(c, b, config, id)
if err != nil {
return nil, err
}
c.producers.add(id, prod)
c.topicLookup(prod.topic.CompleteName, prod.topicReady)
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-prod.connected:
return prod, nil
}
}
func (c *Client) createNewConsumer(config ConsumerConfig) (*consumer, error) {
b := c.newBrokerConnection()
id := c.consumers.newID()
cons, err := newConsumer(c, b, config, id)
if err != nil {
return nil, err
}
c.consumers.add(id, cons)
return cons, nil
}
// NewConsumer creates a new Consumer, returning after the connection
// has been made.
// nolint: ireturn
func (c *Client) NewConsumer(ctx context.Context, config ConsumerConfig) (Consumer, error) {
if err := config.Validate(); err != nil {
return nil, fmt.Errorf("validating config: %w", err)
}
if c.closing.Load() {
return nil, ErrClientClosing
}
// TODO check connected state
if config.TopicPattern != "" {
if config.TopicPatternDiscoveryInterval <= 0 {
config.TopicPatternDiscoveryInterval = 30000
}
b := c.newBrokerConnection()
multi, err := newMultiTopicConsumer(c, b, config)
if err != nil {
return nil, err
}
go c.nameSpaceTopicLookup(multi, config)
return multi, nil
}
cons, err := c.createNewConsumer(config)
if err != nil {
return nil, err
}
c.topicLookup(cons.topic, cons.topicLookupFinished)
select {
case <-ctx.Done():
return nil, ctx.Err()
case err = <-cons.connected:
return cons, err
}
}
func (c *Client) newBrokerConnection() brokerConnection {
return brokerConnection{
ctx: c.ctx,
log: c.log,
conn: c.conn,
req: c.req,
}
}
func (c *Client) topicLookup(topic string, topicReady requestCallback) {
reqID := c.req.newID()
cmd := newPartitionedMetadataCommand(reqID, topic)
respHandler := func(resp *command) error {
if resp.err != nil {
return resp.err
}
partitions := resp.PartitionMetadataResponse.GetPartitions()
if partitions != 0 {
return errors.New("partitioned topics are not supported") // TODO support
}
return nil
}
if err := c.conn.SendCallbackCommand(c.req, reqID, cmd, respHandler); err != nil {
c.log.Errorf("Getting partitioned meta data failed: %s", err.Error())
return
}
reqID = c.req.newID()
c.req.addCallbackCustom(reqID, topicReady, topic)
if err := c.sendLookupTopicCommand(topic, reqID); err != nil {
c.log.Errorf("Sending lookup topic command failed: %s", err.Error())
return
}
}
func (c *Client) nameSpaceTopicLookup(multi *multiTopicConsumer, config ConsumerConfig) {
topic, err := NewTopic(config.TopicPattern)
if err != nil {
c.log.Errorf("Processing topic name failed: %s", err.Error())
return
}
pattern, err := regexp.Compile(topic.CompleteName)
if err != nil {
c.log.Errorf("Compiling topic regexp pattern failed: %s", err.Error())
return
}
config.MessageChannel = multi.incomingMessages
config.TopicPattern = ""
knownTopics := map[string]struct{}{}
tick := time.NewTicker(time.Duration(config.TopicPatternDiscoveryInterval) * time.Millisecond)
defer tick.Stop()
for {
var newTopics []string
reqID := c.req.newID()
cmd := newGetTopicsOfNamespaceCommand(reqID, topic.Namespace)
respHandler := func(resp *command) error {
if resp.err != nil {
return resp.err
}
for _, name := range resp.GetTopicsOfNamespaceResponse.Topics {
t, err := NewTopic(name)
if err != nil {
c.log.Errorf("Processing topic name failed: %s", err.Error())
continue
}
if !pattern.MatchString(t.CompleteName) {
continue
}
if _, ok := knownTopics[t.CompleteName]; !ok {
newTopics = append(newTopics, t.CompleteName)
knownTopics[t.CompleteName] = struct{}{}
}
}
return nil
}
// TODO handle deleted topics
if err = c.conn.SendCallbackCommand(c.req, reqID, cmd, respHandler); err != nil {
c.log.Errorf("Getting topics of namespace failed: %s", err.Error())
return
}
if err = c.subscribeToTopics(multi, config, newTopics); err != nil {
return
}
select {
case <-tick.C:
case <-c.ctx.Done():
return
}
}
}
func (c *Client) subscribeToTopics(multi *multiTopicConsumer, config ConsumerConfig, topics []string) error {
var err error
for _, topic := range topics {
if config.InitialPositionCallback != nil {
config.InitialPosition, config.StartMessageID, err = config.InitialPositionCallback(topic)
if err != nil {
c.log.Errorf("Initial position callback failed: %s", err.Error())
continue
}
}
config.Topic = topic
cons, err := c.createNewConsumer(config)
if err != nil {
c.log.Errorf("Creating consumer failed: %s", err.Error())
return err
}
cons.multi = multi
multi.addConsumer(cons.consumerID, cons)
c.topicLookup(cons.topic, cons.topicLookupFinished)
}
return nil
}
// CloseConsumer closes a specific consumer.
func (c *Client) CloseConsumer(consumerID uint64) error {
cons, ok := c.consumers.getAndDelete(consumerID)
if !ok {
return fmt.Errorf("consumer %d not found", consumerID)
}
var err error
cons.stateMu.Lock()
if cons.state == consumerReady || cons.state == consumerSubscribed {
cons.state = consumerClosing
cons.stateMu.Unlock()
reqID := c.req.newID()
cmd := newCloseConsumerCommand(consumerID, reqID)
err = c.conn.SendCallbackCommand(c.req, reqID, cmd)
cons.stateMu.Lock()
cons.state = consumerClosed
}
cons.stateMu.Unlock()
return err
}
// CloseProducer closes a specific producer.
func (c *Client) CloseProducer(producerID uint64) error {
_, ok := c.producers.getAndDelete(producerID)
if !ok {
return fmt.Errorf("producer %d not found", producerID)
}
reqID := c.req.newID()
cmd := newCloseProducerCommand(producerID, reqID)
return c.conn.SendCallbackCommand(c.req, reqID, cmd)
}
// Close closes all consumers, producers and the client connection.
func (c *Client) Close() error {
if !c.closing.CompareAndSwap(false, true) {
return nil
}
c.cancel()
c.connMutex.Lock()
if c.conn == nil {
c.connMutex.Unlock()
return nil
}
c.connMutex.Unlock()
for _, cons := range c.consumers.all() {
_ = c.CloseConsumer(cons.consumerID)
}
for _, prods := range c.producers.all() {
_ = c.CloseProducer(prods.producerID)
}
err := c.conn.close()
<-c.stopped
return err
}
func (c *Client) sendLookupTopicCommand(topic string, reqID uint64) error {
base := &pb.BaseCommand{
Type: pb.BaseCommand_LOOKUP.Enum(),
LookupTopic: &pb.CommandLookupTopic{
Topic: proto.String(topic),
RequestId: proto.Uint64(reqID),
Authoritative: proto.Bool(false),
},
}
return c.conn.WriteCommand(base, nil)
}
func (c *Client) readCommands() {
defer close(c.stopped)
for {
cmd, err := c.conn.readCommand()
if err != nil {
if errors.Is(err, ErrNetClosing) {
return
}
c.log.Errorf("Reading command failed: %s", err.Error())
return
}
if err = c.processReceivedCommand(cmd); err != nil {
c.log.Errorf("Processing received command %+v failed: %s", cmd, err.Error())
}
}
}
func (c *Client) processReceivedCommand(cmd *command) error {
c.log.Debugf("Received command: %+v", cmd)
handler, ok := c.cmds[*cmd.Type]
if !ok {
return fmt.Errorf("unsupported command %q", cmd.GetType())
}
if handler == nil {
return nil
}
return handler(cmd)
}
func newPartitionedMetadataCommand(reqID uint64, topic string) *pb.BaseCommand {
return &pb.BaseCommand{
Type: pb.BaseCommand_PARTITIONED_METADATA.Enum(),
PartitionMetadata: &pb.CommandPartitionedTopicMetadata{
Topic: proto.String(topic),
RequestId: proto.Uint64(reqID),
},
}
}
// Topics returns the topics of a namespace.
// Defaults to DefaultNamespace if no namespace is given.
func (c *Client) Topics(namespace string) ([]*Topic, error) {
if namespace == "" {
namespace = DefaultNamespace
}
reqID := c.req.newID()
cmd := newGetTopicsOfNamespaceCommand(reqID, namespace)
var topics []*Topic
respHandler := func(resp *command) error {
if resp.err != nil {
return resp.err
}
for _, name := range resp.GetTopicsOfNamespaceResponse.Topics {
t, err := NewTopic(name)
if err != nil {
return err
}
topics = append(topics, t)
}
return nil
}
if err := c.conn.SendCallbackCommand(c.req, reqID, cmd, respHandler); err != nil {
return nil, err
}
return topics, nil
}