2021-07-10 23:41:21 +03:00
|
|
|
// Package kgo provides a kafka broker using kgo
|
2021-10-03 18:32:41 +03:00
|
|
|
package kgo // import "go.unistack.org/micro-broker-kgo/v3"
|
2021-07-10 23:41:21 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-08-09 00:30:36 +03:00
|
|
|
"fmt"
|
|
|
|
"strings"
|
2021-07-10 23:41:21 +03:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2021-09-17 07:56:31 +03:00
|
|
|
"github.com/twmb/franz-go/pkg/kerr"
|
2021-07-10 23:41:21 +03:00
|
|
|
kgo "github.com/twmb/franz-go/pkg/kgo"
|
2021-09-17 07:56:31 +03:00
|
|
|
"github.com/twmb/franz-go/pkg/kmsg"
|
|
|
|
"github.com/twmb/franz-go/pkg/kversion"
|
2021-10-03 18:30:56 +03:00
|
|
|
"go.unistack.org/micro/v3/broker"
|
|
|
|
"go.unistack.org/micro/v3/logger"
|
|
|
|
"go.unistack.org/micro/v3/metadata"
|
|
|
|
"go.unistack.org/micro/v3/util/id"
|
|
|
|
mrand "go.unistack.org/micro/v3/util/rand"
|
2021-07-10 23:41:21 +03:00
|
|
|
)
|
|
|
|
|
2021-09-23 07:06:51 +03:00
|
|
|
var _ broker.Broker = &kBroker{}
|
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
type kBroker struct {
|
2021-08-09 00:30:36 +03:00
|
|
|
writer *kgo.Client // used only to push messages
|
|
|
|
kopts []kgo.Opt
|
2021-07-10 23:41:21 +03:00
|
|
|
connected bool
|
|
|
|
init bool
|
|
|
|
sync.RWMutex
|
|
|
|
opts broker.Options
|
2021-08-09 00:30:36 +03:00
|
|
|
subs []*subscriber
|
2021-07-10 23:41:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
type subscriber struct {
|
2021-08-09 00:30:36 +03:00
|
|
|
reader *kgo.Client // used only to pull messages
|
|
|
|
topic string
|
|
|
|
opts broker.SubscribeOptions
|
|
|
|
kopts broker.Options
|
|
|
|
handler broker.Handler
|
|
|
|
batchhandler broker.BatchHandler
|
|
|
|
closed bool
|
|
|
|
done chan struct{}
|
2021-09-15 18:30:07 +03:00
|
|
|
consumers map[string]map[int32]worker
|
2021-07-10 23:41:21 +03:00
|
|
|
sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
type publication struct {
|
2021-08-09 00:30:36 +03:00
|
|
|
topic string
|
|
|
|
err error
|
2021-07-10 23:41:21 +03:00
|
|
|
sync.RWMutex
|
|
|
|
msg *broker.Message
|
2021-08-22 12:10:58 +03:00
|
|
|
ack bool
|
2021-07-10 23:41:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *publication) Topic() string {
|
|
|
|
return p.topic
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *publication) Message() *broker.Message {
|
|
|
|
return p.msg
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *publication) Ack() error {
|
2021-08-22 12:10:58 +03:00
|
|
|
p.ack = true
|
2021-07-10 23:41:21 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *publication) Error() error {
|
|
|
|
return p.err
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
func (p *publication) SetError(err error) {
|
|
|
|
p.err = err
|
|
|
|
}
|
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
func (s *subscriber) Options() broker.SubscribeOptions {
|
|
|
|
return s.opts
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *subscriber) Topic() string {
|
|
|
|
return s.topic
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *subscriber) Unsubscribe(ctx context.Context) error {
|
2021-08-24 13:20:31 +03:00
|
|
|
if s.closed {
|
|
|
|
return nil
|
|
|
|
}
|
2021-08-09 00:30:36 +03:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
default:
|
2021-08-24 13:20:31 +03:00
|
|
|
close(s.done)
|
|
|
|
s.closed = true
|
2021-08-09 00:30:36 +03:00
|
|
|
}
|
2021-07-10 23:41:21 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) Address() string {
|
2021-08-09 00:30:36 +03:00
|
|
|
return strings.Join(k.opts.Addrs, ",")
|
2021-07-10 23:41:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) Name() string {
|
|
|
|
return k.opts.Name
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) Connect(ctx context.Context) error {
|
|
|
|
k.RLock()
|
|
|
|
if k.connected {
|
|
|
|
k.RUnlock()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
k.RUnlock()
|
|
|
|
|
|
|
|
nctx := k.opts.Context
|
|
|
|
if ctx != nil {
|
|
|
|
nctx = ctx
|
|
|
|
}
|
|
|
|
|
2021-08-22 12:10:58 +03:00
|
|
|
kaddrs := k.opts.Addrs
|
|
|
|
|
|
|
|
// shuffle addrs
|
2021-09-15 18:30:07 +03:00
|
|
|
var rng mrand.Rand
|
|
|
|
rng.Shuffle(len(kaddrs), func(i, j int) {
|
2021-08-22 12:10:58 +03:00
|
|
|
kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i]
|
|
|
|
})
|
|
|
|
|
|
|
|
kopts := append(k.kopts, kgo.SeedBrokers(kaddrs...))
|
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
select {
|
|
|
|
case <-nctx.Done():
|
|
|
|
return nctx.Err()
|
|
|
|
default:
|
2021-08-22 12:10:58 +03:00
|
|
|
c, err := kgo.NewClient(kopts...)
|
2021-07-10 23:41:21 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-09-17 07:56:31 +03:00
|
|
|
|
|
|
|
// Request versions in order to guess Kafka Cluster version
|
|
|
|
versionsReq := kmsg.NewApiVersionsRequest()
|
|
|
|
versionsRes, err := versionsReq.RequestWith(ctx, c)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to request api versions: %w", err)
|
|
|
|
}
|
|
|
|
err = kerr.ErrorForCode(versionsRes.ErrorCode)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to request api versions. Inner kafka error: %w", err)
|
|
|
|
}
|
|
|
|
versions := kversion.FromApiVersionsResponse(versionsRes)
|
|
|
|
|
|
|
|
if k.opts.Logger.V(logger.InfoLevel) {
|
|
|
|
logger.Infof(ctx, "[kgo] connected to to kafka cluster version %v", versions.VersionGuess())
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
k.Lock()
|
|
|
|
k.connected = true
|
|
|
|
k.writer = c
|
|
|
|
k.Unlock()
|
2021-07-10 23:41:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) Disconnect(ctx context.Context) error {
|
|
|
|
k.RLock()
|
|
|
|
if !k.connected {
|
|
|
|
k.RUnlock()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
k.RUnlock()
|
|
|
|
|
|
|
|
k.Lock()
|
|
|
|
defer k.Unlock()
|
|
|
|
|
|
|
|
nctx := k.opts.Context
|
|
|
|
if ctx != nil {
|
|
|
|
nctx = ctx
|
|
|
|
}
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-nctx.Done():
|
|
|
|
return nctx.Err()
|
|
|
|
default:
|
2021-08-09 00:30:36 +03:00
|
|
|
for _, sub := range k.subs {
|
|
|
|
if err := sub.Unsubscribe(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
k.writer.Close()
|
2021-07-10 23:41:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
k.connected = false
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) Init(opts ...broker.Option) error {
|
|
|
|
k.Lock()
|
|
|
|
defer k.Unlock()
|
|
|
|
|
|
|
|
if len(opts) == 0 && k.init {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&k.opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := k.opts.Register.Init(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := k.opts.Tracer.Init(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := k.opts.Logger.Init(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := k.opts.Meter.Init(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
if k.opts.Context != nil {
|
|
|
|
if v, ok := k.opts.Context.Value(optionsKey{}).([]kgo.Opt); ok && len(v) > 0 {
|
2021-08-25 21:51:15 +03:00
|
|
|
k.kopts = append(k.kopts, v...)
|
2021-08-09 00:30:36 +03:00
|
|
|
}
|
|
|
|
}
|
2021-08-25 21:51:15 +03:00
|
|
|
|
2021-08-24 13:20:31 +03:00
|
|
|
// kgo.RecordPartitioner(),
|
2021-08-09 00:30:36 +03:00
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
k.init = true
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) Options() broker.Options {
|
|
|
|
return k.opts
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
func (k *kBroker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
|
|
|
return k.publish(ctx, msgs, opts...)
|
|
|
|
}
|
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
func (k *kBroker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
2021-08-09 00:30:36 +03:00
|
|
|
msg.Header.Set(metadata.HeaderTopic, topic)
|
|
|
|
return k.publish(ctx, []*broker.Message{msg}, opts...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
2021-08-25 21:51:15 +03:00
|
|
|
options := broker.NewPublishOptions(opts...)
|
2021-08-09 00:30:36 +03:00
|
|
|
records := make([]*kgo.Record, 0, len(msgs))
|
|
|
|
var errs []string
|
2021-08-25 21:51:15 +03:00
|
|
|
var err error
|
2021-08-22 12:10:58 +03:00
|
|
|
|
|
|
|
for _, msg := range msgs {
|
2021-09-23 07:06:51 +03:00
|
|
|
rec := &kgo.Record{}
|
|
|
|
rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic)
|
2021-08-25 21:51:15 +03:00
|
|
|
if options.BodyOnly {
|
2021-09-23 07:06:51 +03:00
|
|
|
rec.Value = msg.Body
|
|
|
|
} else if k.opts.Codec.String() == "noop" {
|
|
|
|
rec.Value = msg.Body
|
|
|
|
for k, v := range msg.Header {
|
|
|
|
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
|
|
|
|
}
|
2021-08-25 21:51:15 +03:00
|
|
|
} else {
|
2021-09-23 07:06:51 +03:00
|
|
|
rec.Value, err = k.opts.Codec.Marshal(msg)
|
2021-08-25 21:51:15 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2021-08-22 12:10:58 +03:00
|
|
|
records = append(records, rec)
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
results := k.writer.ProduceSync(ctx, records...)
|
|
|
|
for _, result := range results {
|
|
|
|
if result.Err != nil {
|
|
|
|
errs = append(errs, result.Err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(errs) > 0 {
|
|
|
|
return fmt.Errorf("publish error: %s", strings.Join(errs, "\n"))
|
|
|
|
}
|
2021-08-22 12:10:58 +03:00
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
type mlogger struct {
|
|
|
|
l logger.Logger
|
|
|
|
ctx context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) {
|
2021-08-24 13:20:31 +03:00
|
|
|
var mlvl logger.Level
|
2021-08-09 00:30:36 +03:00
|
|
|
switch lvl {
|
|
|
|
case kgo.LogLevelNone:
|
|
|
|
return
|
|
|
|
case kgo.LogLevelError:
|
|
|
|
mlvl = logger.ErrorLevel
|
|
|
|
case kgo.LogLevelWarn:
|
|
|
|
mlvl = logger.WarnLevel
|
|
|
|
case kgo.LogLevelInfo:
|
|
|
|
mlvl = logger.InfoLevel
|
|
|
|
case kgo.LogLevelDebug:
|
|
|
|
mlvl = logger.DebugLevel
|
|
|
|
default:
|
|
|
|
return
|
|
|
|
}
|
2021-08-25 21:51:15 +03:00
|
|
|
fields := make(map[string]interface{}, int(len(args)/2))
|
|
|
|
for i := 0; i < len(args)/2; i += 2 {
|
|
|
|
fields[fmt.Sprintf("%v", args[i])] = args[i+1]
|
|
|
|
}
|
|
|
|
l.l.Fields(fields).Log(l.ctx, mlvl, msg)
|
2021-08-09 00:30:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *mlogger) Level() kgo.LogLevel {
|
|
|
|
switch l.l.Options().Level {
|
|
|
|
case logger.ErrorLevel:
|
|
|
|
return kgo.LogLevelError
|
|
|
|
case logger.WarnLevel:
|
|
|
|
return kgo.LogLevelWarn
|
|
|
|
case logger.InfoLevel:
|
|
|
|
return kgo.LogLevelInfo
|
|
|
|
case logger.DebugLevel, logger.TraceLevel:
|
|
|
|
return kgo.LogLevelDebug
|
|
|
|
}
|
|
|
|
return kgo.LogLevelNone
|
|
|
|
}
|
|
|
|
|
2021-08-25 21:51:15 +03:00
|
|
|
func (k *kBroker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
func (k *kBroker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
|
|
options := broker.NewSubscribeOptions(opts...)
|
2021-08-09 00:30:36 +03:00
|
|
|
|
|
|
|
if options.Group == "" {
|
2021-08-22 12:10:58 +03:00
|
|
|
uid, err := id.New()
|
2021-08-09 00:30:36 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-22 12:10:58 +03:00
|
|
|
options.Group = uid
|
2021-08-09 00:30:36 +03:00
|
|
|
}
|
|
|
|
|
2021-08-22 12:10:58 +03:00
|
|
|
kaddrs := k.opts.Addrs
|
|
|
|
|
|
|
|
// shuffle addrs
|
2021-09-15 18:30:07 +03:00
|
|
|
var rng mrand.Rand
|
|
|
|
rng.Shuffle(len(kaddrs), func(i, j int) {
|
2021-08-22 12:10:58 +03:00
|
|
|
kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i]
|
|
|
|
})
|
|
|
|
|
2021-09-02 00:20:55 +03:00
|
|
|
td := DefaultCommitInterval
|
|
|
|
if k.opts.Context != nil {
|
|
|
|
if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 {
|
|
|
|
td = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-15 18:30:07 +03:00
|
|
|
sub := &subscriber{
|
|
|
|
topic: topic,
|
|
|
|
done: make(chan struct{}),
|
|
|
|
opts: options,
|
|
|
|
handler: handler,
|
|
|
|
kopts: k.opts,
|
|
|
|
consumers: make(map[string]map[int32]worker),
|
|
|
|
}
|
|
|
|
|
2021-08-09 00:30:36 +03:00
|
|
|
kopts := append(k.kopts,
|
2021-08-22 12:10:58 +03:00
|
|
|
kgo.SeedBrokers(kaddrs...),
|
2021-08-09 00:30:36 +03:00
|
|
|
kgo.ConsumerGroup(options.Group),
|
|
|
|
kgo.ConsumeTopics(topic),
|
|
|
|
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
2021-08-22 12:10:58 +03:00
|
|
|
kgo.FetchMaxWait(1*time.Second),
|
2021-08-27 02:24:43 +03:00
|
|
|
// kgo.KeepControlRecords(),
|
2021-08-24 13:20:31 +03:00
|
|
|
kgo.Balancers(kgo.CooperativeStickyBalancer(), kgo.StickyBalancer()),
|
|
|
|
kgo.FetchIsolationLevel(kgo.ReadUncommitted()),
|
2021-08-30 20:02:32 +03:00
|
|
|
kgo.WithHooks(&metrics{meter: k.opts.Meter}),
|
2021-09-02 00:20:55 +03:00
|
|
|
kgo.AutoCommitMarks(),
|
|
|
|
kgo.AutoCommitInterval(td),
|
2021-09-15 18:30:07 +03:00
|
|
|
kgo.OnPartitionsAssigned(sub.assigned),
|
|
|
|
kgo.OnPartitionsRevoked(sub.revoked),
|
|
|
|
kgo.OnPartitionsLost(sub.revoked),
|
2021-08-09 00:30:36 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
reader, err := kgo.NewClient(kopts...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-09-15 18:30:07 +03:00
|
|
|
sub.reader = reader
|
2021-08-09 00:30:36 +03:00
|
|
|
go sub.run(ctx)
|
|
|
|
|
|
|
|
k.Lock()
|
|
|
|
k.subs = append(k.subs, sub)
|
|
|
|
k.Unlock()
|
2021-07-10 23:41:21 +03:00
|
|
|
return sub, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *kBroker) String() string {
|
|
|
|
return "kgo"
|
|
|
|
}
|
|
|
|
|
2021-09-23 07:06:51 +03:00
|
|
|
func NewBroker(opts ...broker.Option) *kBroker {
|
2021-08-25 21:51:15 +03:00
|
|
|
options := broker.NewOptions(opts...)
|
2021-09-23 07:06:51 +03:00
|
|
|
if options.Codec.String() != "noop" {
|
|
|
|
options.Logger.Infof(options.Context, "broker codec not noop, disable plain kafka headers usage")
|
|
|
|
}
|
2021-08-25 21:51:15 +03:00
|
|
|
kopts := []kgo.Opt{
|
2021-09-02 00:20:55 +03:00
|
|
|
kgo.DisableIdempotentWrite(),
|
|
|
|
kgo.ProducerBatchCompression(kgo.NoCompression()),
|
2021-08-25 21:51:15 +03:00
|
|
|
kgo.WithLogger(&mlogger{l: options.Logger, ctx: options.Context}),
|
|
|
|
kgo.RetryBackoffFn(
|
|
|
|
func() func(int) time.Duration {
|
|
|
|
var rng mrand.Rand
|
|
|
|
return func(fails int) time.Duration {
|
|
|
|
const (
|
|
|
|
min = 250 * time.Millisecond
|
|
|
|
max = 2 * time.Second
|
|
|
|
)
|
|
|
|
if fails <= 0 {
|
|
|
|
return min
|
|
|
|
}
|
|
|
|
if fails > 10 {
|
|
|
|
return max
|
|
|
|
}
|
|
|
|
|
|
|
|
backoff := min * time.Duration(1<<(fails-1))
|
|
|
|
jitter := 0.8 + 0.4*rng.Float64()
|
|
|
|
backoff = time.Duration(float64(backoff) * jitter)
|
|
|
|
|
|
|
|
if backoff > max {
|
|
|
|
return max
|
|
|
|
}
|
|
|
|
return backoff
|
|
|
|
}
|
|
|
|
}(),
|
|
|
|
),
|
|
|
|
}
|
|
|
|
|
|
|
|
if options.Context != nil {
|
|
|
|
if v, ok := options.Context.Value(optionsKey{}).([]kgo.Opt); ok && len(v) > 0 {
|
|
|
|
kopts = append(kopts, v...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-10 23:41:21 +03:00
|
|
|
return &kBroker{
|
2021-08-25 21:51:15 +03:00
|
|
|
opts: options,
|
|
|
|
kopts: kopts,
|
2021-07-10 23:41:21 +03:00
|
|
|
}
|
|
|
|
}
|