Compare commits
35 Commits
Author | SHA1 | Date | |
---|---|---|---|
cbab0b5cb6 | |||
947132c25b | |||
98da69fbe8 | |||
d6d2483d8d | |||
7676631737 | |||
6c2cf494ca | |||
6e5e2e0338 | |||
6dd3b4548a | |||
fff768dc2a | |||
755bd187ba | |||
141c7fb848 | |||
|
f347ca4e12 | ||
c78bffdb8d | |||
49ba8880f2 | |||
|
bbd840b96e | ||
1ee739de80 | |||
|
7f0265b6d1 | ||
4dc19dc63f | |||
|
5eb2718cd4 | ||
b4c98e207f | |||
|
20652894b3 | ||
27bb8c50d1 | |||
|
b90ef8cdf3 | ||
222370f96c | |||
|
1152be720d | ||
f0b9665816 | |||
|
310e9a8ceb | ||
cc155511e1 | |||
|
0a0c592b64 | ||
372c5c92f0 | |||
|
2601514578 | ||
8a1856e814 | |||
|
08e04cdb70 | ||
7286521472 | |||
|
b01e2b5563 |
6
.gitignore
vendored
6
.gitignore
vendored
@ -13,9 +13,3 @@
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
|
||||
# General
|
||||
.DS_Store
|
||||
.idea
|
||||
.vscode
|
||||
bin/
|
||||
|
@ -1,2 +1,9 @@
|
||||
# broker-kgo
|
||||
# micro-broker-kgo
|
||||
yet another micro kafka broker alternative
|
||||
|
||||
TODO:
|
||||
* dont always append options from context on Init and New
|
||||
* add SubscriberOptions(...kgo.Opt)
|
||||
* add ServerSubscribeOptions(...kgo.Opt)
|
||||
* check PublisherOptions(...kgo.Opt)
|
||||
* check ClientPublisherOptions(...kgo.Opt)
|
76
carrier.go
76
carrier.go
@ -1,76 +0,0 @@
|
||||
package kgo
|
||||
|
||||
import (
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// RecordCarrier injects and extracts traces from a kgo.Record.
|
||||
//
|
||||
// This type exists to satisfy the otel/propagation.TextMapCarrier interface.
|
||||
type RecordCarrier struct {
|
||||
record *kgo.Record
|
||||
}
|
||||
|
||||
// NewRecordCarrier creates a new RecordCarrier.
|
||||
func NewRecordCarrier(record *kgo.Record) RecordCarrier {
|
||||
return RecordCarrier{record: record}
|
||||
}
|
||||
|
||||
// Get retrieves a single value for a given key if it exists.
|
||||
func (c RecordCarrier) Get(key string) string {
|
||||
for _, h := range c.record.Headers {
|
||||
if h.Key == key {
|
||||
return string(h.Value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Set sets a header.
|
||||
func (c RecordCarrier) Set(key, val string) {
|
||||
// Check if key already exists.
|
||||
for i, h := range c.record.Headers {
|
||||
if h.Key == key {
|
||||
// Key exist, update the value.
|
||||
c.record.Headers[i].Value = []byte(val)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Key does not exist, append new header.
|
||||
c.record.Headers = append(c.record.Headers, kgo.RecordHeader{
|
||||
Key: key,
|
||||
Value: []byte(val),
|
||||
})
|
||||
}
|
||||
|
||||
// Keys returns a slice of all key identifiers in the carrier.
|
||||
func (c RecordCarrier) Keys() []string {
|
||||
out := make([]string, len(c.record.Headers))
|
||||
for i, h := range c.record.Headers {
|
||||
out[i] = h.Key
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func setHeaders(r *kgo.Record, md metadata.Metadata) {
|
||||
seen := make(map[string]struct{})
|
||||
loop:
|
||||
for k, v := range md {
|
||||
for i := 0; i < len(r.Headers); i++ {
|
||||
if r.Headers[i].Key == k {
|
||||
// Key exist, update the value.
|
||||
r.Headers[i].Value = []byte(v)
|
||||
continue loop
|
||||
} else if _, ok := seen[k]; ok {
|
||||
continue loop
|
||||
}
|
||||
// Key does not exist, append new header.
|
||||
r.Headers = append(r.Headers, kgo.RecordHeader{
|
||||
Key: k,
|
||||
Value: []byte(v),
|
||||
})
|
||||
seen[k] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
8
event.go
8
event.go
@ -1,14 +1,12 @@
|
||||
package kgo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v4/broker"
|
||||
)
|
||||
|
||||
type event struct {
|
||||
ctx context.Context
|
||||
topic string
|
||||
err error
|
||||
sync.RWMutex
|
||||
@ -16,10 +14,6 @@ type event struct {
|
||||
ack bool
|
||||
}
|
||||
|
||||
func (p *event) Context() context.Context {
|
||||
return p.ctx
|
||||
}
|
||||
|
||||
func (p *event) Topic() string {
|
||||
return p.topic
|
||||
}
|
||||
|
23
go.mod
23
go.mod
@ -1,25 +1,14 @@
|
||||
module go.unistack.org/micro-broker-kgo/v3
|
||||
module go.unistack.org/micro-broker-kgo/v4
|
||||
|
||||
go 1.22
|
||||
|
||||
toolchain go1.23.1
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/twmb/franz-go v1.18.0
|
||||
github.com/twmb/franz-go/pkg/kadm v1.14.0
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.9.0
|
||||
go.opentelemetry.io/otel v1.32.0
|
||||
go.unistack.org/micro/v3 v3.10.101
|
||||
github.com/twmb/franz-go v1.16.1
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.7.0
|
||||
go.unistack.org/micro/v4 v4.0.17
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/klauspost/compress v1.17.7 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.21 // indirect
|
||||
go.unistack.org/micro-proto/v3 v3.4.1 // indirect
|
||||
golang.org/x/crypto v0.29.0 // indirect
|
||||
golang.org/x/sys v0.27.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697 // indirect
|
||||
google.golang.org/grpc v1.67.1 // indirect
|
||||
google.golang.org/protobuf v1.35.2 // indirect
|
||||
)
|
||||
|
49
go.sum
49
go.sum
@ -1,42 +1,11 @@
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
|
||||
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=
|
||||
github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/twmb/franz-go v1.18.0 h1:25FjMZfdozBywVX+5xrWC2W+W76i0xykKjTdEeD2ejw=
|
||||
github.com/twmb/franz-go v1.18.0/go.mod h1:zXCGy74M0p5FbXsLeASdyvfLFsBvTubVqctIaa5wQ+I=
|
||||
github.com/twmb/franz-go/pkg/kadm v1.14.0 h1:nAn1co1lXzJQocpzyIyOFOjUBf4WHWs5/fTprXy2IZs=
|
||||
github.com/twmb/franz-go/pkg/kadm v1.14.0/go.mod h1:XjOPz6ZaXXjrW2jVCfLuucP8H1w2TvD6y3PT2M+aAM4=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.9.0 h1:JojYUph2TKAau6SBtErXpXGC7E3gg4vGZMv9xFU/B6M=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.9.0/go.mod h1:CMbfazviCyY6HM0SXuG5t9vOwYDHRCSrJJyBAe5paqg=
|
||||
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U=
|
||||
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
|
||||
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
|
||||
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
|
||||
go.unistack.org/micro/v3 v3.10.101 h1:CwMg7f2Mnsy+tRcsY0RTcAMkTVp+GMUgPU6pPaG8gpw=
|
||||
go.unistack.org/micro/v3 v3.10.101/go.mod h1:YzMldzHN9Ei+zy5t/Psu7RUWDZwUfrNYiStSQtTz90g=
|
||||
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
|
||||
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
|
||||
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
|
||||
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697 h1:LWZqQOEjDyONlF1H6afSWpAL/znlREo2tHfLoe+8LMA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU=
|
||||
google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E=
|
||||
google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=
|
||||
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
|
||||
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
github.com/twmb/franz-go v1.16.1 h1:rpWc7fB9jd7TgmCyfxzenBI+QbgS8ZfJOUQE+tzPtbE=
|
||||
github.com/twmb/franz-go v1.16.1/go.mod h1:/pER254UPPGp/4WfGqRi+SIRGE50RSQzVubQp6+N4FA=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.7.0 h1:a457IbvezYfA5UkiBvyV3zj0Is3y1i8EJgqjJYoij2E=
|
||||
github.com/twmb/franz-go/pkg/kmsg v1.7.0/go.mod h1:se9Mjdt0Nwzc9lnjJ0HyDtLyBnaBDAd7pCje47OhSyw=
|
||||
go.unistack.org/micro/v4 v4.0.17 h1:mF7uM+J4ILdG+1fcwzKYCwDlxhdbF/e1WnGzKKLnIXc=
|
||||
go.unistack.org/micro/v4 v4.0.17/go.mod h1:ZDgU9931vm2l7X6RN/6UuwRIVp24GRdmQ7dKmegArk4=
|
||||
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
|
||||
|
65
kadmtest.go
65
kadmtest.go
@ -1,65 +0,0 @@
|
||||
//go:build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kadm"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"github.com/twmb/franz-go/pkg/kversion"
|
||||
|
||||
//"github.com/twmb/franz-go/pkg/sasl/scram"
|
||||
"github.com/twmb/franz-go/pkg/sasl/plain"
|
||||
)
|
||||
|
||||
func die(msg string, args ...any) {
|
||||
fmt.Fprintf(os.Stderr, msg, args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func main() {
|
||||
seeds := []string{"vm-kafka-ump01tn.mbrd.ru:9092", "vm-kafka-ump02tn.mbrd.ru:9092", "vm-kafka-ump03tn.mbrd.ru:9092"}
|
||||
|
||||
pass := "XXXXX"
|
||||
user := "XXXXX"
|
||||
|
||||
var adminClient *kadm.Client
|
||||
{
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(seeds...),
|
||||
// kgo.SASL((scram.Auth{User: user, Pass: pass}).AsSha512Mechanism()),
|
||||
kgo.SASL((plain.Auth{User: user, Pass: pass}).AsMechanism()),
|
||||
|
||||
// Do not try to send requests newer than 2.4.0 to avoid breaking changes in the request struct.
|
||||
// Sometimes there are breaking changes for newer versions where more properties are required to set.
|
||||
kgo.MaxVersions(kversion.V2_4_0()),
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
adminClient = kadm.NewClient(client)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dg, err := adminClient.DescribeGroups(ctx, "interestrate_loader")
|
||||
if err != nil {
|
||||
die("failed to describe group: %v", err)
|
||||
}
|
||||
|
||||
for _, m := range dg["interestrate_loader"].Members {
|
||||
mc, _ := m.Assigned.AsConsumer()
|
||||
for _, mt := range mc.Topics {
|
||||
for _, p := range mt.Partitions {
|
||||
fmt.Printf("client:%s\tpartitions: %d\n", m.ClientID, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
131
kgo.go
131
kgo.go
@ -1,25 +1,21 @@
|
||||
// Package kgo provides a kafka broker using kgo
|
||||
package kgo
|
||||
package kgo // import "go.unistack.org/micro-broker-kgo/v4"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"github.com/twmb/franz-go/pkg/kmsg"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/semconv"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
mrand "go.unistack.org/micro/v3/util/rand"
|
||||
"go.unistack.org/micro/v4/broker"
|
||||
"go.unistack.org/micro/v4/metadata"
|
||||
id "go.unistack.org/micro/v4/util/id"
|
||||
mrand "go.unistack.org/micro/v4/util/rand"
|
||||
)
|
||||
|
||||
var _ broker.Broker = (*Broker)(nil)
|
||||
@ -63,7 +59,7 @@ type Broker struct {
|
||||
connected bool
|
||||
sync.RWMutex
|
||||
opts broker.Options
|
||||
subs []*Subscriber
|
||||
subs []*subscriber
|
||||
}
|
||||
|
||||
func (k *Broker) Address() string {
|
||||
@ -74,54 +70,23 @@ func (k *Broker) Name() string {
|
||||
return k.opts.Name
|
||||
}
|
||||
|
||||
func (k *Broker) Client() *kgo.Client {
|
||||
return k.c
|
||||
}
|
||||
|
||||
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) {
|
||||
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, error) {
|
||||
var c *kgo.Client
|
||||
var err error
|
||||
|
||||
sp, _ := tracer.SpanFromContext(ctx)
|
||||
|
||||
clientID := "kgo"
|
||||
group := ""
|
||||
if k.opts.Context != nil {
|
||||
if id, ok := k.opts.Context.Value(clientIDKey{}).(string); ok {
|
||||
clientID = id
|
||||
}
|
||||
if id, ok := k.opts.Context.Value(groupKey{}).(string); ok {
|
||||
group = id
|
||||
}
|
||||
}
|
||||
|
||||
htracer := &hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer}
|
||||
opts = append(opts,
|
||||
kgo.WithHooks(&hookMeter{meter: k.opts.Meter}),
|
||||
kgo.WithHooks(htracer),
|
||||
)
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if ctx.Err() != nil {
|
||||
if sp != nil {
|
||||
sp.SetStatus(tracer.SpanStatusError, ctx.Err().Error())
|
||||
}
|
||||
}
|
||||
return nil, nil, ctx.Err()
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
c, err = kgo.NewClient(opts...)
|
||||
if err == nil {
|
||||
err = c.Ping(ctx) // check connectivity to cluster
|
||||
}
|
||||
if err != nil {
|
||||
if sp != nil {
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return c, htracer, nil
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (k *Broker) Connect(ctx context.Context) error {
|
||||
@ -137,7 +102,7 @@ func (k *Broker) Connect(ctx context.Context) error {
|
||||
nctx = ctx
|
||||
}
|
||||
|
||||
c, _, err := k.connect(nctx, k.kopts...)
|
||||
c, err := k.connect(nctx, k.kopts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -162,9 +127,6 @@ func (k *Broker) Disconnect(ctx context.Context) error {
|
||||
if ctx != nil {
|
||||
nctx = ctx
|
||||
}
|
||||
var span tracer.Span
|
||||
ctx, span = k.opts.Tracer.Start(ctx, "Disconnect")
|
||||
defer span.Finish()
|
||||
|
||||
k.Lock()
|
||||
defer k.Unlock()
|
||||
@ -222,7 +184,6 @@ func (k *Broker) Init(opts ...broker.Option) error {
|
||||
}
|
||||
|
||||
k.init = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -240,17 +201,21 @@ func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message,
|
||||
}
|
||||
|
||||
func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
||||
k.RLock()
|
||||
ok := k.connected
|
||||
k.RUnlock()
|
||||
|
||||
if !ok {
|
||||
k.Lock()
|
||||
if !k.connected {
|
||||
c, _, err := k.connect(ctx, k.kopts...)
|
||||
c, err := k.connect(ctx, k.kopts...)
|
||||
if err != nil {
|
||||
k.Unlock()
|
||||
return err
|
||||
}
|
||||
k.c = c
|
||||
k.connected = true
|
||||
}
|
||||
k.Unlock()
|
||||
}
|
||||
|
||||
options := broker.NewPublishOptions(opts...)
|
||||
records := make([]*kgo.Record, 0, len(msgs))
|
||||
@ -271,12 +236,13 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br
|
||||
for _, msg := range msgs {
|
||||
rec := &kgo.Record{Context: ctx, Key: key}
|
||||
rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic)
|
||||
msg.Header.Del(metadata.HeaderTopic)
|
||||
k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc()
|
||||
if options.BodyOnly || k.opts.Codec.String() == "noop" {
|
||||
k.opts.Meter.Counter(broker.PublishMessageInflight, "endpoint", rec.Topic).Inc()
|
||||
if options.BodyOnly {
|
||||
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: http.CanonicalHeaderKey(k), Value: []byte(v)})
|
||||
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
|
||||
}
|
||||
} else {
|
||||
rec.Value, err = k.opts.Codec.Marshal(msg)
|
||||
@ -292,13 +258,13 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br
|
||||
for _, rec := range records {
|
||||
k.c.Produce(ctx, rec, func(r *kgo.Record, err error) {
|
||||
te := time.Since(ts)
|
||||
k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec()
|
||||
k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Counter(broker.PublishMessageInflight, "endpoint", rec.Topic).Dec()
|
||||
k.opts.Meter.Summary(broker.PublishMessageLatencyMicroseconds, "endpoint", r.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Histogram(broker.PublishMessageDurationSeconds, "endpoint", r.Topic).Update(te.Seconds())
|
||||
if err != nil {
|
||||
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "failure").Inc()
|
||||
k.opts.Meter.Counter(broker.PublishMessageTotal, "endpoint", r.Topic, "status", "failure").Inc()
|
||||
} else {
|
||||
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc()
|
||||
k.opts.Meter.Counter(broker.PublishMessageTotal, "endpoint", r.Topic, "status", "success").Inc()
|
||||
}
|
||||
promise(r, err)
|
||||
})
|
||||
@ -309,14 +275,14 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br
|
||||
results := k.c.ProduceSync(ctx, records...)
|
||||
te := time.Since(ts)
|
||||
for _, result := range results {
|
||||
k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec()
|
||||
k.opts.Meter.Summary(broker.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Histogram(broker.PublishMessageDurationSeconds, "endpoint", result.Record.Topic).Update(te.Seconds())
|
||||
k.opts.Meter.Counter(broker.PublishMessageInflight, "endpoint", result.Record.Topic).Dec()
|
||||
if result.Err != nil {
|
||||
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc()
|
||||
k.opts.Meter.Counter(broker.PublishMessageTotal, "endpoint", result.Record.Topic, "status", "failure").Inc()
|
||||
errs = append(errs, result.Err.Error())
|
||||
} else {
|
||||
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc()
|
||||
k.opts.Meter.Counter(broker.PublishMessageTotal, "endpoint", result.Record.Topic, "status", "success").Inc()
|
||||
}
|
||||
}
|
||||
|
||||
@ -327,22 +293,6 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k *Broker) TopicExists(ctx context.Context, topic string) error {
|
||||
mdreq := kmsg.NewMetadataRequest()
|
||||
mdreq.Topics = []kmsg.MetadataRequestTopic{
|
||||
{Topic: &topic},
|
||||
}
|
||||
|
||||
mdrsp, err := mdreq.RequestWith(ctx, k.c)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if mdrsp.Topics[0].ErrorCode != 0 {
|
||||
return fmt.Errorf("topic %s not exists or permission error", topic)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k *Broker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||
return nil, nil
|
||||
}
|
||||
@ -351,11 +301,11 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
|
||||
options := broker.NewSubscribeOptions(opts...)
|
||||
|
||||
if options.Group == "" {
|
||||
uid, err := uuid.NewRandom()
|
||||
uid, err := id.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options.Group = uid.String()
|
||||
options.Group = uid
|
||||
}
|
||||
|
||||
commitInterval := DefaultCommitInterval
|
||||
@ -365,7 +315,7 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
|
||||
}
|
||||
}
|
||||
|
||||
sub := &Subscriber{
|
||||
sub := &subscriber{
|
||||
topic: topic,
|
||||
opts: options,
|
||||
handler: handler,
|
||||
@ -392,7 +342,7 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
|
||||
}
|
||||
}
|
||||
|
||||
c, htracer, err := k.connect(ctx, kopts...)
|
||||
c, err := k.connect(ctx, kopts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -410,8 +360,6 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
|
||||
}
|
||||
|
||||
sub.c = c
|
||||
sub.htracer = htracer
|
||||
|
||||
go sub.poll(ctx)
|
||||
|
||||
k.Lock()
|
||||
@ -437,13 +385,14 @@ func NewBroker(opts ...broker.Option) *Broker {
|
||||
kgo.DialTimeout(3 * time.Second),
|
||||
kgo.DisableIdempotentWrite(),
|
||||
kgo.ProducerBatchCompression(kgo.NoCompression()),
|
||||
kgo.WithLogger(&mlogger{l: options.Logger.Clone(logger.WithAddCallerSkipCount(2)), ctx: options.Context}),
|
||||
kgo.WithLogger(&mlogger{l: options.Logger, ctx: options.Context}),
|
||||
// kgo.WithLogger(kgo.BasicLogger(os.Stderr, kgo.LogLevelDebug, func() string { return time.Now().Format(time.StampMilli) })),
|
||||
kgo.WithHooks(&metrics{meter: options.Meter}),
|
||||
kgo.SeedBrokers(kaddrs...),
|
||||
kgo.RetryBackoffFn(DefaultRetryBackoffFn),
|
||||
kgo.BlockRebalanceOnPoll(),
|
||||
kgo.Balancers(kgo.CooperativeStickyBalancer()),
|
||||
kgo.FetchIsolationLevel(kgo.ReadUncommitted()),
|
||||
kgo.UnknownTopicRetries(0),
|
||||
}
|
||||
|
||||
if options.Context != nil {
|
||||
|
10
kgo_test.go
10
kgo_test.go
@ -10,10 +10,10 @@ import (
|
||||
"time"
|
||||
|
||||
kg "github.com/twmb/franz-go/pkg/kgo"
|
||||
kgo "go.unistack.org/micro-broker-kgo/v3"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
kgo "go.unistack.org/micro-broker-kgo/v4"
|
||||
"go.unistack.org/micro/v4/broker"
|
||||
"go.unistack.org/micro/v4/logger"
|
||||
"go.unistack.org/micro/v4/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -50,7 +50,7 @@ func TestPubSub(t *testing.T) {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil {
|
||||
if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel), logger.WithCallerSkipCount(3)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v4/logger"
|
||||
)
|
||||
|
||||
type mlogger struct {
|
||||
@ -28,8 +28,11 @@ func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) {
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
l.l.Log(l.ctx, mlvl, msg, args...)
|
||||
if len(args) > 0 {
|
||||
l.l.Log(l.ctx, mlvl, append([]interface{}{msg}, args...)...)
|
||||
} else {
|
||||
l.l.Log(l.ctx, mlvl, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *mlogger) Level() kgo.LogLevel {
|
||||
|
@ -6,29 +6,57 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v4/meter"
|
||||
)
|
||||
|
||||
type hookMeter struct {
|
||||
/*
|
||||
func NewServerSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
return handler.SubscriberFunc
|
||||
}
|
||||
|
||||
func (w *wrapper) SubscriberFunc(fn server.SubscriberFunc) server.SubscriberFunc {
|
||||
return func(ctx context.Context, msg server.Message) error {
|
||||
endpoint := msg.Topic()
|
||||
|
||||
labels := make([]string, 0, 4)
|
||||
labels = append(labels, labelEndpoint, endpoint)
|
||||
|
||||
w.opts.Meter.Counter(SubscribeMessageInflight, labels...).Inc()
|
||||
ts := time.Now()
|
||||
err := fn(ctx, msg)
|
||||
te := time.Since(ts)
|
||||
w.opts.Meter.Counter(SubscribeMessageInflight, labels...).Dec()
|
||||
|
||||
w.opts.Meter.Summary(SubscribeMessageLatencyMicroseconds, labels...).Update(te.Seconds())
|
||||
w.opts.Meter.Histogram(SubscribeMessageDurationSeconds, labels...).Update(te.Seconds())
|
||||
|
||||
if err == nil {
|
||||
labels = append(labels, labelStatus, labelSuccess)
|
||||
} else {
|
||||
labels = append(labels, labelStatus, labelFailure)
|
||||
}
|
||||
w.opts.Meter.Counter(SubscribeMessageTotal, labels...).Inc()
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
*/
|
||||
type metrics struct {
|
||||
meter meter.Meter
|
||||
}
|
||||
|
||||
var (
|
||||
_ kgo.HookBrokerConnect = &hookMeter{}
|
||||
_ kgo.HookBrokerDisconnect = &hookMeter{}
|
||||
// HookBrokerE2E
|
||||
_ kgo.HookBrokerRead = &hookMeter{}
|
||||
_ kgo.HookBrokerThrottle = &hookMeter{}
|
||||
_ kgo.HookBrokerWrite = &hookMeter{}
|
||||
_ kgo.HookFetchBatchRead = &hookMeter{}
|
||||
// HookFetchRecordBuffered
|
||||
// HookFetchRecordUnbuffered
|
||||
_ kgo.HookGroupManageError = &hookMeter{}
|
||||
// HookNewClient
|
||||
_ kgo.HookProduceBatchWritten = &hookMeter{}
|
||||
// HookProduceRecordBuffered
|
||||
// HookProduceRecordPartitioned
|
||||
// HookProduceRecordUnbuffered
|
||||
_ kgo.HookBrokerConnect = &metrics{}
|
||||
_ kgo.HookBrokerDisconnect = &metrics{}
|
||||
_ kgo.HookBrokerRead = &metrics{}
|
||||
_ kgo.HookBrokerThrottle = &metrics{}
|
||||
_ kgo.HookBrokerWrite = &metrics{}
|
||||
_ kgo.HookFetchBatchRead = &metrics{}
|
||||
_ kgo.HookProduceBatchWritten = &metrics{}
|
||||
_ kgo.HookGroupManageError = &metrics{}
|
||||
)
|
||||
|
||||
const (
|
||||
@ -61,11 +89,11 @@ const (
|
||||
labelTopic = "topic"
|
||||
)
|
||||
|
||||
func (m *hookMeter) OnGroupManageError(err error) {
|
||||
func (m *metrics) OnGroupManageError(err error) {
|
||||
m.meter.Counter(metricBrokerGroupErrors).Inc()
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
|
||||
func (m *metrics) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
if err != nil {
|
||||
m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelFaulure).Inc()
|
||||
@ -74,12 +102,12 @@ func (m *hookMeter) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _
|
||||
m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelSuccess).Inc()
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) {
|
||||
func (m *metrics) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
m.meter.Counter(metricBrokerDisconnects, labelNode, node).Inc()
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) {
|
||||
func (m *metrics) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
if err != nil {
|
||||
m.meter.Counter(metricBrokerWriteErrors, labelNode, node).Inc()
|
||||
@ -90,7 +118,7 @@ func (m *hookMeter) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten
|
||||
m.meter.Histogram(metricBrokerWriteLatencies, labelNode, node).Update(timeToWrite.Seconds())
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) {
|
||||
func (m *metrics) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
if err != nil {
|
||||
m.meter.Counter(metricBrokerReadErrors, labelNode, node).Inc()
|
||||
@ -102,18 +130,18 @@ func (m *hookMeter) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int
|
||||
m.meter.Histogram(metricBrokerReadLatencies, labelNode, node).Update(timeToRead.Seconds())
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) {
|
||||
func (m *metrics) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
m.meter.Histogram(metricBrokerThrottleLatencies, labelNode, node).Update(throttleInterval.Seconds())
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) {
|
||||
func (m *metrics) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
m.meter.Counter(metricBrokerProduceBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes)
|
||||
m.meter.Counter(metricBrokerProduceBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes)
|
||||
}
|
||||
|
||||
func (m *hookMeter) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) {
|
||||
func (m *metrics) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) {
|
||||
node := strconv.Itoa(int(meta.NodeID))
|
||||
m.meter.Counter(metricBrokerFetchBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes)
|
||||
m.meter.Counter(metricBrokerFetchBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes)
|
29
options.go
29
options.go
@ -5,21 +5,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v4/broker"
|
||||
"go.unistack.org/micro/v4/client"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
// DefaultCommitInterval specifies how fast send commit offsets to kafka
|
||||
DefaultCommitInterval = 5 * time.Second
|
||||
|
||||
// DefaultStatsInterval specifies how fast check consumer lag
|
||||
DefaultStatsInterval = 5 * time.Second
|
||||
|
||||
// DefaultSubscribeMaxInflight specifies how much messages keep inflight
|
||||
DefaultSubscribeMaxInflight = 100
|
||||
)
|
||||
var DefaultCommitInterval = 5 * time.Second
|
||||
|
||||
type subscribeContextKey struct{}
|
||||
|
||||
@ -72,18 +63,6 @@ func SubscribeOptions(opts ...kgo.Opt) broker.SubscribeOption {
|
||||
}
|
||||
}
|
||||
|
||||
type clientIDKey struct{}
|
||||
|
||||
func ClientID(id string) broker.Option {
|
||||
return broker.SetOption(clientIDKey{}, id)
|
||||
}
|
||||
|
||||
type groupKey struct{}
|
||||
|
||||
func Group(id string) broker.Option {
|
||||
return broker.SetOption(groupKey{}, id)
|
||||
}
|
||||
|
||||
type commitIntervalKey struct{}
|
||||
|
||||
// CommitInterval specifies interval to send commits
|
||||
@ -91,6 +70,8 @@ func CommitInterval(td time.Duration) broker.Option {
|
||||
return broker.SetOption(commitIntervalKey{}, td)
|
||||
}
|
||||
|
||||
var DefaultSubscribeMaxInflight = 10
|
||||
|
||||
type subscribeMaxInflightKey struct{}
|
||||
|
||||
// SubscribeMaxInFlight max queued messages
|
||||
|
162
subscriber.go
162
subscriber.go
@ -2,18 +2,13 @@ package kgo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kadm"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/semconv"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
"go.unistack.org/micro/v4/broker"
|
||||
"go.unistack.org/micro/v4/logger"
|
||||
"go.unistack.org/micro/v4/metadata"
|
||||
)
|
||||
|
||||
type tp struct {
|
||||
@ -25,7 +20,6 @@ type consumer struct {
|
||||
c *kgo.Client
|
||||
topic string
|
||||
partition int32
|
||||
htracer *hookTracer
|
||||
opts broker.SubscribeOptions
|
||||
kopts broker.Options
|
||||
handler broker.Handler
|
||||
@ -34,10 +28,9 @@ type consumer struct {
|
||||
recs chan kgo.FetchTopicPartition
|
||||
}
|
||||
|
||||
type Subscriber struct {
|
||||
type subscriber struct {
|
||||
c *kgo.Client
|
||||
topic string
|
||||
htracer *hookTracer
|
||||
opts broker.SubscribeOptions
|
||||
kopts broker.Options
|
||||
handler broker.Handler
|
||||
@ -47,28 +40,23 @@ type Subscriber struct {
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Subscriber) Client() *kgo.Client {
|
||||
return s.c
|
||||
}
|
||||
|
||||
func (s *Subscriber) Options() broker.SubscribeOptions {
|
||||
func (s *subscriber) Options() broker.SubscribeOptions {
|
||||
return s.opts
|
||||
}
|
||||
|
||||
func (s *Subscriber) Topic() string {
|
||||
func (s *subscriber) Topic() string {
|
||||
return s.topic
|
||||
}
|
||||
|
||||
func (s *Subscriber) Unsubscribe(ctx context.Context) error {
|
||||
func (s *subscriber) Unsubscribe(ctx context.Context) error {
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
// case <-ctx.Done():
|
||||
// return ctx.Err()
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
s.c.PauseFetchTopics(s.topic)
|
||||
s.c.CloseAllowingRebalance()
|
||||
kc := make(map[string][]int32)
|
||||
for ctp := range s.consumers {
|
||||
kc[ctp.t] = append(kc[ctp.t], ctp.p)
|
||||
@ -76,59 +64,24 @@ func (s *Subscriber) Unsubscribe(ctx context.Context) error {
|
||||
s.killConsumers(ctx, kc)
|
||||
close(s.done)
|
||||
s.closed = true
|
||||
s.c.ResumeFetchTopics(s.topic)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Subscriber) poll(ctx context.Context) {
|
||||
func (s *subscriber) poll(ctx context.Context) {
|
||||
maxInflight := DefaultSubscribeMaxInflight
|
||||
if s.opts.Context != nil {
|
||||
if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok {
|
||||
maxInflight = n
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
ac := kadm.NewClient(s.c)
|
||||
ticker := time.NewTicker(DefaultStatsInterval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
ticker.Stop()
|
||||
return
|
||||
case <-ticker.C:
|
||||
dgls, err := ac.Lag(ctx, s.opts.Group)
|
||||
if err != nil || !dgls.Ok() {
|
||||
continue
|
||||
}
|
||||
|
||||
dgl, ok := dgls[s.opts.Group]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
lmap, ok := dgl.Lag[s.topic]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
for p, l := range lmap {
|
||||
s.kopts.Meter.Counter(semconv.BrokerGroupLag, "topic", s.topic, "group", s.opts.Group, "partition", strconv.Itoa(int(p)), "lag", strconv.Itoa(int(l.Lag)))
|
||||
}
|
||||
s.Unlock()
|
||||
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
s.c.CloseAllowingRebalance()
|
||||
return
|
||||
case <-s.done:
|
||||
s.c.CloseAllowingRebalance()
|
||||
return
|
||||
default:
|
||||
fetches := s.c.PollRecords(ctx, maxInflight)
|
||||
@ -137,7 +90,7 @@ func (s *Subscriber) poll(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
fetches.EachError(func(t string, p int32, err error) {
|
||||
s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err)
|
||||
s.kopts.Logger.Fatalf(ctx, "[kgo] fetch topic %s partition %d err: %v", t, p, err)
|
||||
})
|
||||
|
||||
fetches.EachPartition(func(p kgo.FetchTopicPartition) {
|
||||
@ -149,7 +102,7 @@ func (s *Subscriber) poll(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32) {
|
||||
func (s *subscriber) killConsumers(ctx context.Context, lost map[string][]int32) {
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
|
||||
@ -159,50 +112,42 @@ func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32)
|
||||
pc := s.consumers[tp]
|
||||
delete(s.consumers, tp)
|
||||
close(pc.quit)
|
||||
if s.kopts.Logger.V(logger.DebugLevel) {
|
||||
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] waiting for work to finish topic %s partition %d", topic, partition))
|
||||
}
|
||||
s.kopts.Logger.Debugf(ctx, "[kgo] waiting for work to finish topic %s partition %d", topic, partition)
|
||||
wg.Add(1)
|
||||
go func() { <-pc.done; wg.Done() }()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) {
|
||||
if s.kopts.Logger.V(logger.DebugLevel) {
|
||||
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] lost %#+v", lost))
|
||||
}
|
||||
func (s *subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) {
|
||||
s.kopts.Logger.Debugf(ctx, "[kgo] lost %#+v", lost)
|
||||
s.killConsumers(ctx, lost)
|
||||
}
|
||||
|
||||
func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) {
|
||||
if s.kopts.Logger.V(logger.DebugLevel) {
|
||||
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] revoked %#+v", revoked))
|
||||
}
|
||||
func (s *subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) {
|
||||
s.kopts.Logger.Debugf(ctx, "[kgo] revoked %#+v", revoked)
|
||||
s.killConsumers(ctx, revoked)
|
||||
if err := c.CommitMarkedOffsets(ctx); err != nil {
|
||||
s.kopts.Logger.Error(ctx, "[kgo] revoked CommitMarkedOffsets error", err)
|
||||
s.kopts.Logger.Errorf(ctx, "[kgo] revoked CommitMarkedOffsets err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[string][]int32) {
|
||||
func (s *subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[string][]int32) {
|
||||
for topic, partitions := range assigned {
|
||||
for _, partition := range partitions {
|
||||
pc := &consumer{
|
||||
c: c,
|
||||
topic: topic,
|
||||
partition: partition,
|
||||
htracer: s.htracer,
|
||||
|
||||
quit: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
recs: make(chan kgo.FetchTopicPartition, 100),
|
||||
recs: make(chan kgo.FetchTopicPartition, 4),
|
||||
handler: s.handler,
|
||||
kopts: s.kopts,
|
||||
opts: s.opts,
|
||||
}
|
||||
s.Lock()
|
||||
s.consumers[tp{topic, partition}] = pc
|
||||
s.Unlock()
|
||||
go pc.consume()
|
||||
}
|
||||
}
|
||||
@ -210,10 +155,8 @@ func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[str
|
||||
|
||||
func (pc *consumer) consume() {
|
||||
defer close(pc.done)
|
||||
if pc.kopts.Logger.V(logger.DebugLevel) {
|
||||
pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("starting, topic %s partition %d", pc.topic, pc.partition))
|
||||
defer pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("killing, topic %s partition %d", pc.topic, pc.partition))
|
||||
}
|
||||
pc.kopts.Logger.Debugf(pc.kopts.Context, "starting, topic %s partition %d", pc.topic, pc.partition)
|
||||
defer pc.kopts.Logger.Debugf(pc.kopts.Context, "killing, topic %s partition %d", pc.topic, pc.partition)
|
||||
|
||||
eh := pc.kopts.ErrorHandler
|
||||
if pc.opts.ErrorHandler != nil {
|
||||
@ -226,99 +169,86 @@ func (pc *consumer) consume() {
|
||||
return
|
||||
case p := <-pc.recs:
|
||||
for _, record := range p.Records {
|
||||
ctx, sp := pc.htracer.WithProcessSpan(record)
|
||||
ts := time.Now()
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Inc()
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageInflight, "endpoint", record.Topic).Inc()
|
||||
p := eventPool.Get().(*event)
|
||||
p.msg.Header = nil
|
||||
p.msg.Body = nil
|
||||
p.topic = record.Topic
|
||||
p.err = nil
|
||||
p.ack = false
|
||||
if pc.kopts.Codec.String() == "noop" {
|
||||
p.msg.Header = metadata.New(len(record.Headers))
|
||||
p.ctx = ctx
|
||||
for _, hdr := range record.Headers {
|
||||
p.msg.Header.Set(hdr.Key, string(hdr.Value))
|
||||
}
|
||||
if pc.kopts.Codec.String() == "noop" {
|
||||
p.msg.Body = record.Value
|
||||
} else if pc.opts.BodyOnly {
|
||||
p.msg.Body = record.Value
|
||||
} else {
|
||||
sp.AddEvent("codec unmarshal start")
|
||||
err := pc.kopts.Codec.Unmarshal(record.Value, p.msg)
|
||||
sp.AddEvent("codec unmarshal stop")
|
||||
if err != nil {
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc()
|
||||
if err := pc.kopts.Codec.Unmarshal(record.Value, p.msg); err != nil {
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageTotal, "endpoint", record.Topic, "status", "failure").Inc()
|
||||
p.err = err
|
||||
p.msg.Body = record.Value
|
||||
if eh != nil {
|
||||
_ = eh(p)
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageInflight, "endpoint", record.Topic).Dec()
|
||||
if p.ack {
|
||||
pc.c.MarkCommitRecords(record)
|
||||
} else {
|
||||
eventPool.Put(p)
|
||||
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
|
||||
pc.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
|
||||
return
|
||||
}
|
||||
eventPool.Put(p)
|
||||
te := time.Since(ts)
|
||||
pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Summary(broker.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Histogram(broker.SubscribeMessageDurationSeconds, "endpoint", record.Topic).Update(te.Seconds())
|
||||
continue
|
||||
} else {
|
||||
pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: unmarshal error", err)
|
||||
if pc.kopts.Logger.V(logger.ErrorLevel) {
|
||||
pc.kopts.Logger.Errorf(pc.kopts.Context, "[kgo]: failed to unmarshal: %v", err)
|
||||
}
|
||||
}
|
||||
te := time.Since(ts)
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
|
||||
pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageInflight, "endpoint", record.Topic).Dec()
|
||||
pc.kopts.Meter.Summary(broker.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Histogram(broker.SubscribeMessageDurationSeconds, "endpoint", record.Topic).Update(te.Seconds())
|
||||
eventPool.Put(p)
|
||||
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?")
|
||||
sp.Finish()
|
||||
pc.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?")
|
||||
return
|
||||
}
|
||||
}
|
||||
sp.AddEvent("handler start")
|
||||
err := pc.handler(p)
|
||||
sp.AddEvent("handler stop")
|
||||
if err == nil {
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc()
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageTotal, "endpoint", record.Topic, "status", "success").Inc()
|
||||
} else {
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc()
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageTotal, "endpoint", record.Topic, "status", "failure").Inc()
|
||||
}
|
||||
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
|
||||
pc.kopts.Meter.Counter(broker.SubscribeMessageInflight, "endpoint", record.Topic).Dec()
|
||||
if err == nil && pc.opts.AutoAck {
|
||||
p.ack = true
|
||||
} else if err != nil {
|
||||
p.err = err
|
||||
if eh != nil {
|
||||
sp.AddEvent("error handler start")
|
||||
_ = eh(p)
|
||||
sp.AddEvent("error handler stop")
|
||||
} else {
|
||||
if pc.kopts.Logger.V(logger.ErrorLevel) {
|
||||
pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: subscriber error", err)
|
||||
pc.kopts.Logger.Errorf(pc.kopts.Context, "[kgo]: subscriber error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
te := time.Since(ts)
|
||||
pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Summary(broker.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic).Update(te.Seconds())
|
||||
pc.kopts.Meter.Histogram(broker.SubscribeMessageDurationSeconds, "endpoint", record.Topic).Update(te.Seconds())
|
||||
if p.ack {
|
||||
eventPool.Put(p)
|
||||
pc.c.MarkCommitRecords(record)
|
||||
} else {
|
||||
eventPool.Put(p)
|
||||
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
|
||||
sp.SetStatus(tracer.SpanStatusError, "ErrLostMessage")
|
||||
sp.Finish()
|
||||
pc.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
|
||||
return
|
||||
}
|
||||
sp.Finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
204
tracer.go
204
tracer.go
@ -1,204 +0,0 @@
|
||||
package kgo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
type hookTracer struct {
|
||||
clientID string
|
||||
group string
|
||||
tracer tracer.Tracer
|
||||
}
|
||||
|
||||
var messagingSystem = semconv.MessagingSystemKey.String("kafka")
|
||||
|
||||
var (
|
||||
_ kgo.HookProduceRecordBuffered = (*hookTracer)(nil)
|
||||
_ kgo.HookProduceRecordUnbuffered = (*hookTracer)(nil)
|
||||
_ kgo.HookFetchRecordBuffered = (*hookTracer)(nil)
|
||||
_ kgo.HookFetchRecordUnbuffered = (*hookTracer)(nil)
|
||||
)
|
||||
|
||||
// OnProduceRecordBuffered starts a new span for the "publish" operation on a
|
||||
// buffered record.
|
||||
//
|
||||
// It sets span options and injects the span context into record and updates
|
||||
// the record's context, so it can be ended in the OnProduceRecordUnbuffered
|
||||
// hook.
|
||||
func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) {
|
||||
// Set up span options.
|
||||
attrs := []interface{}{
|
||||
messagingSystem,
|
||||
semconv.MessagingDestinationKindTopic,
|
||||
semconv.MessagingDestinationName(r.Topic),
|
||||
semconv.MessagingOperationPublish,
|
||||
}
|
||||
attrs = maybeKeyAttr(attrs, r)
|
||||
if m.clientID != "" {
|
||||
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
|
||||
}
|
||||
opts := []tracer.SpanOption{
|
||||
tracer.WithSpanLabels(attrs...),
|
||||
tracer.WithSpanKind(tracer.SpanKindProducer),
|
||||
}
|
||||
|
||||
if r.Context == nil {
|
||||
r.Context = context.Background()
|
||||
}
|
||||
|
||||
omd, ok := metadata.FromOutgoingContext(r.Context)
|
||||
if !ok {
|
||||
omd = metadata.New(len(r.Headers))
|
||||
}
|
||||
|
||||
md := metadata.Copy(omd)
|
||||
for _, h := range r.Headers {
|
||||
md.Set(h.Key, string(h.Value))
|
||||
}
|
||||
|
||||
if !ok {
|
||||
r.Context, _ = m.tracer.Start(metadata.NewOutgoingContext(r.Context, md), "sdk.broker", opts...)
|
||||
} else {
|
||||
r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...)
|
||||
}
|
||||
|
||||
setHeaders(r, omd)
|
||||
}
|
||||
|
||||
// OnProduceRecordUnbuffered continues and ends the "publish" span for an
|
||||
// unbuffered record.
|
||||
//
|
||||
// It sets attributes with values unset when producing and records any error
|
||||
// that occurred during the publish operation.
|
||||
func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) {
|
||||
if span, ok := tracer.SpanFromContext(r.Context); ok {
|
||||
span.AddLabels(
|
||||
semconv.MessagingKafkaDestinationPartition(int(r.Partition)),
|
||||
)
|
||||
if err != nil {
|
||||
span.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
span.Finish()
|
||||
}
|
||||
}
|
||||
|
||||
// OnFetchRecordBuffered starts a new span for the "receive" operation on a
|
||||
// buffered record.
|
||||
//
|
||||
// It sets the span options and extracts the span context from the record,
|
||||
// updates the record's context to ensure it can be ended in the
|
||||
// OnFetchRecordUnbuffered hook and can be used in downstream consumer
|
||||
// processing.
|
||||
func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) {
|
||||
// Set up the span options.
|
||||
attrs := []interface{}{
|
||||
messagingSystem,
|
||||
semconv.MessagingSourceKindTopic,
|
||||
semconv.MessagingSourceName(r.Topic),
|
||||
semconv.MessagingOperationReceive,
|
||||
semconv.MessagingKafkaSourcePartition(int(r.Partition)),
|
||||
}
|
||||
attrs = maybeKeyAttr(attrs, r)
|
||||
if m.clientID != "" {
|
||||
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
|
||||
}
|
||||
if m.group != "" {
|
||||
attrs = append(attrs, semconv.MessagingKafkaConsumerGroupKey.String(m.group))
|
||||
}
|
||||
opts := []tracer.SpanOption{
|
||||
tracer.WithSpanLabels(attrs...),
|
||||
tracer.WithSpanKind(tracer.SpanKindConsumer),
|
||||
}
|
||||
|
||||
if r.Context == nil {
|
||||
r.Context = context.Background()
|
||||
}
|
||||
omd, ok := metadata.FromIncomingContext(r.Context)
|
||||
if !ok {
|
||||
omd = metadata.New(len(r.Headers))
|
||||
}
|
||||
|
||||
md := metadata.Copy(omd)
|
||||
for _, h := range r.Headers {
|
||||
md.Set(h.Key, string(h.Value))
|
||||
}
|
||||
|
||||
if !ok {
|
||||
r.Context, _ = m.tracer.Start(metadata.NewIncomingContext(r.Context, md), "sdk.broker", opts...)
|
||||
} else {
|
||||
r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...)
|
||||
}
|
||||
|
||||
setHeaders(r, omd)
|
||||
}
|
||||
|
||||
// OnFetchRecordUnbuffered continues and ends the "receive" span for an
|
||||
// unbuffered record.
|
||||
func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) {
|
||||
span, _ := tracer.SpanFromContext(r.Context)
|
||||
span.Finish()
|
||||
}
|
||||
|
||||
// WithProcessSpan starts a new span for the "process" operation on a consumer
|
||||
// record.
|
||||
//
|
||||
// It sets up the span options. The user's application code is responsible for
|
||||
// ending the span.
|
||||
//
|
||||
// This should only ever be called within a polling loop of a consumed record and
|
||||
// not a record which has been created for producing, so call this at the start of each
|
||||
// iteration of your processing for the record.
|
||||
func (m *hookTracer) WithProcessSpan(r *kgo.Record) (context.Context, tracer.Span) {
|
||||
// Set up the span options.
|
||||
attrs := []interface{}{
|
||||
messagingSystem,
|
||||
semconv.MessagingSourceKindTopic,
|
||||
semconv.MessagingSourceName(r.Topic),
|
||||
semconv.MessagingOperationProcess,
|
||||
semconv.MessagingKafkaSourcePartition(int(r.Partition)),
|
||||
semconv.MessagingKafkaMessageOffset(int(r.Offset)),
|
||||
}
|
||||
attrs = maybeKeyAttr(attrs, r)
|
||||
if m.clientID != "" {
|
||||
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
|
||||
}
|
||||
if m.group != "" {
|
||||
attrs = append(attrs, semconv.MessagingKafkaConsumerGroupKey.String(m.group))
|
||||
}
|
||||
opts := []tracer.SpanOption{
|
||||
tracer.WithSpanLabels(attrs...),
|
||||
tracer.WithSpanKind(tracer.SpanKindConsumer),
|
||||
}
|
||||
|
||||
if r.Context == nil {
|
||||
r.Context = context.Background()
|
||||
}
|
||||
md, ok := metadata.FromIncomingContext(r.Context)
|
||||
if !ok {
|
||||
md = metadata.New(len(r.Headers))
|
||||
}
|
||||
for _, h := range r.Headers {
|
||||
md.Set(h.Key, string(h.Value))
|
||||
}
|
||||
|
||||
// Start a new span using the provided context and options.
|
||||
return m.tracer.Start(r.Context, "sdk.broker", opts...)
|
||||
}
|
||||
|
||||
func maybeKeyAttr(attrs []interface{}, r *kgo.Record) []interface{} {
|
||||
if r.Key == nil {
|
||||
return attrs
|
||||
}
|
||||
var keykey string
|
||||
if !utf8.Valid(r.Key) {
|
||||
return attrs
|
||||
}
|
||||
keykey = string(r.Key)
|
||||
return append(attrs, semconv.MessagingKafkaMessageKeyKey.String(keykey))
|
||||
}
|
Loading…
Reference in New Issue
Block a user