forked from Trendyol/kafka-konsumer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverify_topic.go
77 lines (63 loc) · 1.62 KB
/
verify_topic.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
package kafka
import (
"context"
"fmt"
"github.com/segmentio/kafka-go"
)
type kafkaClient interface {
Metadata(ctx context.Context, req *kafka.MetadataRequest) (*kafka.MetadataResponse, error)
GetClient() *kafka.Client
}
type client struct {
*kafka.Client
}
func newKafkaClient(cfg *ConsumerConfig) (kafkaClient, error) {
var err error
kc := &client{
Client: &kafka.Client{
Addr: kafka.TCP(cfg.Reader.Brokers...),
},
}
transport := &Transport{
Transport: &kafka.Transport{
MetadataTopics: cfg.getTopics(),
},
}
if err = fillLayer(transport, cfg.SASL, cfg.TLS); err != nil {
err = fmt.Errorf("error when initializing kafka client for verify topic purpose %w", err)
return nil, err
}
kc.Transport = transport
if err != nil {
return nil, err
}
return kc, nil
}
func (k *client) GetClient() *kafka.Client {
return k.Client
}
func verifyTopics(client kafkaClient, cfg *ConsumerConfig) (bool, error) {
topics := cfg.getTopics()
metadata, err := client.Metadata(context.Background(), &kafka.MetadataRequest{
Topics: topics,
})
if err != nil {
return false, fmt.Errorf("error when during verifyTopics metadata request %w", err)
}
return checkTopicsWithinMetadata(metadata, topics)
}
func checkTopicsWithinMetadata(metadata *kafka.MetadataResponse, topics []string) (bool, error) {
metadataTopics := make(map[string]struct{}, len(metadata.Topics))
for _, topic := range metadata.Topics {
if topic.Error != nil {
continue
}
metadataTopics[topic.Name] = struct{}{}
}
for _, topic := range topics {
if _, exist := metadataTopics[topic]; !exist {
return false, nil
}
}
return true, nil
}