Skip to content

Commit

Permalink
OpenTelemetry client optimizations (#614)
Browse files Browse the repository at this point in the history
* Use metric.WithAttributeSet()

metric.WithAttributeSet(attribute.NewSet()) is more efficient than metric.WithAttributes() as it doesn't make a copy of the argument slice.

* Allocate vararg slices once, not on each call

See https://go.dev/ref/spec#Passing_arguments_to_..._parameters

* Use field directly in otelclient

* Use field directly in dedicated
  • Loading branch information
ash2k authored Aug 23, 2024
1 parent 653339c commit 1a30827
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 41 deletions.
46 changes: 26 additions & 20 deletions rueidisotel/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ var (
// MetricAttrs set additional attributes to append to each metric.
func MetricAttrs(attrs ...attribute.KeyValue) Option {
return func(o *otelclient) {
o.mAttrs = metric.WithAttributes(attrs...)
mAttrs := metric.WithAttributeSet(attribute.NewSet(attrs...))
// Allocate slices once and use many times
o.addOpts = []metric.AddOption{mAttrs}
o.recordOpts = []metric.RecordOption{mAttrs}
}
}

Expand All @@ -39,11 +42,12 @@ type HistogramOption struct {
}

type dialMetrics struct {
mAttrs metric.MeasurementOption
attempt metric.Int64Counter
success metric.Int64Counter
counts metric.Int64UpDownCounter
latency metric.Float64Histogram
addOpts []metric.AddOption
recordOpts []metric.RecordOption
attempt metric.Int64Counter
success metric.Int64Counter
counts metric.Int64UpDownCounter
latency metric.Float64Histogram
}

// WithHistogramOption sets the HistogramOption.
Expand All @@ -70,7 +74,10 @@ func NewClient(clientOption rueidis.ClientOption, opts ...Option) (rueidis.Clien
clientOption.DialFn = defaultDialFn
}

metrics := dialMetrics{mAttrs: oclient.mAttrs}
metrics := dialMetrics{
addOpts: oclient.addOpts,
recordOpts: oclient.recordOpts,
}

metrics.attempt, err = oclient.meter.Int64Counter("rueidis_dial_attempt")
if err != nil {
Expand Down Expand Up @@ -108,7 +115,6 @@ func NewClient(clientOption rueidis.ClientOption, opts ...Option) (rueidis.Clien

func newClient(opts ...Option) (*otelclient, error) {
cli := &otelclient{
mAttrs: metric.WithAttributes(),
tAttrs: trace.WithAttributes(),
}
for _, opt := range opts {
Expand Down Expand Up @@ -143,7 +149,7 @@ func newClient(opts ...Option) (*otelclient, error) {
func trackDialing(m dialMetrics, dialFn func(string, *net.Dialer, *tls.Config) (conn net.Conn, err error)) func(string, *net.Dialer, *tls.Config) (conn net.Conn, err error) {
return func(network string, dialer *net.Dialer, tlsConfig *tls.Config) (conn net.Conn, err error) {
ctx := context.Background()
m.attempt.Add(ctx, 1, m.mAttrs)
m.attempt.Add(ctx, 1, m.addOpts...)

start := time.Now()

Expand All @@ -153,29 +159,29 @@ func trackDialing(m dialMetrics, dialFn func(string, *net.Dialer, *tls.Config) (
}

// Use floating point division for higher precision (instead of Seconds method).
m.latency.Record(ctx, float64(time.Since(start))/float64(time.Second), m.mAttrs)
m.success.Add(ctx, 1, m.mAttrs)
m.counts.Add(ctx, 1, m.mAttrs)
m.latency.Record(ctx, float64(time.Since(start))/float64(time.Second), m.recordOpts...)
m.success.Add(ctx, 1, m.addOpts...)
m.counts.Add(ctx, 1, m.addOpts...)

return &connTracker{
Conn: conn,
counts: m.counts,
mAttrs: m.mAttrs,
once: 0,
Conn: conn,
counts: m.counts,
addOpts: m.addOpts,
once: 0,
}, nil
}
}

type connTracker struct {
net.Conn
counts metric.Int64UpDownCounter
mAttrs metric.MeasurementOption
once int32
counts metric.Int64UpDownCounter
addOpts []metric.AddOption
once int32
}

func (t *connTracker) Close() error {
if atomic.CompareAndSwapInt32(&t.once, 0, 1) {
t.counts.Add(context.Background(), -1, t.mAttrs)
t.counts.Add(context.Background(), -1, t.addOpts...)
}

return t.Conn.Close()
Expand Down
44 changes: 23 additions & 21 deletions rueidisotel/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ type otelclient struct {
meter metric.Meter
cscMiss metric.Int64Counter
cscHits metric.Int64Counter
mAttrs metric.MeasurementOption
addOpts []metric.AddOption
recordOpts []metric.RecordOption
tAttrs trace.SpanStartEventOption
histogramOption HistogramOption
dbStmtFunc StatementFunc
Expand All @@ -80,7 +81,7 @@ func (o *otelclient) B() rueidis.Builder {
}

func (o *otelclient) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) {
ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), o.tAttrs)
ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()))
if o.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(o.dbStmtFunc(cmd.Commands())))
}
Expand All @@ -91,14 +92,14 @@ func (o *otelclient) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidi
}

func (o *otelclient) DoMulti(ctx context.Context, multi ...rueidis.Completed) (resp []rueidis.RedisResult) {
ctx, span := o.start(ctx, multiFirst(multi), multiSum(multi), o.tAttrs)
ctx, span := o.start(ctx, multiFirst(multi), multiSum(multi))
resp = o.client.DoMulti(ctx, multi...)
o.end(span, firstError(resp))
return
}

func (o *otelclient) DoStream(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResultStream) {
ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), o.tAttrs)
ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()))
if o.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(o.dbStmtFunc(cmd.Commands())))
}
Expand All @@ -109,39 +110,39 @@ func (o *otelclient) DoStream(ctx context.Context, cmd rueidis.Completed) (resp
}

func (o *otelclient) DoMultiStream(ctx context.Context, multi ...rueidis.Completed) (resp rueidis.MultiRedisResultStream) {
ctx, span := o.start(ctx, multiFirst(multi), multiSum(multi), o.tAttrs)
ctx, span := o.start(ctx, multiFirst(multi), multiSum(multi))
resp = o.client.DoMultiStream(ctx, multi...)
o.end(span, resp.Error())
return
}

func (o *otelclient) DoCache(ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) (resp rueidis.RedisResult) {
ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), o.tAttrs)
ctx, span := o.start(ctx, first(cmd.Commands()), sum(cmd.Commands()))
if o.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(o.dbStmtFunc(cmd.Commands())))
}

resp = o.client.DoCache(ctx, cmd, ttl)
if resp.NonRedisError() == nil {
if resp.IsCacheHit() {
o.cscHits.Add(ctx, 1, o.mAttrs)
o.cscHits.Add(ctx, 1, o.addOpts...)
} else {
o.cscMiss.Add(ctx, 1, o.mAttrs)
o.cscMiss.Add(ctx, 1, o.addOpts...)
}
}
o.end(span, resp.Error())
return
}

func (o *otelclient) DoMultiCache(ctx context.Context, multi ...rueidis.CacheableTTL) (resps []rueidis.RedisResult) {
ctx, span := o.start(ctx, multiCacheableFirst(multi), multiCacheableSum(multi), o.tAttrs)
ctx, span := o.start(ctx, multiCacheableFirst(multi), multiCacheableSum(multi))
resps = o.client.DoMultiCache(ctx, multi...)
for _, resp := range resps {
if resp.NonRedisError() == nil {
if resp.IsCacheHit() {
o.cscHits.Add(ctx, 1, o.mAttrs)
o.cscHits.Add(ctx, 1, o.addOpts...)
} else {
o.cscMiss.Add(ctx, 1, o.mAttrs)
o.cscMiss.Add(ctx, 1, o.addOpts...)
}
}
}
Expand Down Expand Up @@ -171,7 +172,7 @@ func (o *otelclient) Dedicate() (rueidis.DedicatedClient, func()) {
}

func (o *otelclient) Receive(ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) {
ctx, span := o.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()), o.tAttrs)
ctx, span := o.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()))
if o.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(o.dbStmtFunc(subscribe.Commands())))
}
Expand All @@ -186,14 +187,15 @@ func (o *otelclient) Nodes() map[string]rueidis.Client {
for addr, client := range nodes {
nodes[addr] = &otelclient{
client: client,
mAttrs: o.mAttrs,
tAttrs: o.tAttrs,
meterProvider: o.meterProvider,
tracerProvider: o.tracerProvider,
tracer: o.tracer,
meter: o.meter,
cscMiss: o.cscMiss,
cscHits: o.cscHits,
addOpts: o.addOpts,
recordOpts: o.recordOpts,
tAttrs: o.tAttrs,
histogramOption: o.histogramOption,
dbStmtFunc: o.dbStmtFunc,
}
Expand All @@ -219,7 +221,7 @@ func (d *dedicated) B() rueidis.Builder {
}

func (d *dedicated) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis.RedisResult) {
ctx, span := d.start(ctx, first(cmd.Commands()), sum(cmd.Commands()), d.tAttrs)
ctx, span := d.start(ctx, first(cmd.Commands()), sum(cmd.Commands()))
if d.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(d.dbStmtFunc(cmd.Commands())))
}
Expand All @@ -230,14 +232,14 @@ func (d *dedicated) Do(ctx context.Context, cmd rueidis.Completed) (resp rueidis
}

func (d *dedicated) DoMulti(ctx context.Context, multi ...rueidis.Completed) (resp []rueidis.RedisResult) {
ctx, span := d.start(ctx, multiFirst(multi), multiSum(multi), d.tAttrs)
ctx, span := d.start(ctx, multiFirst(multi), multiSum(multi))
resp = d.client.DoMulti(ctx, multi...)
d.end(span, firstError(resp))
return
}

func (d *dedicated) Receive(ctx context.Context, subscribe rueidis.Completed, fn func(msg rueidis.PubSubMessage)) (err error) {
ctx, span := d.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()), d.tAttrs)
ctx, span := d.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()))
if d.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(d.dbStmtFunc(subscribe.Commands())))
}
Expand Down Expand Up @@ -340,16 +342,16 @@ func multiCacheableFirst(multi []rueidis.CacheableTTL) string {
return sb.String()
}

func (o *otelclient) start(ctx context.Context, op string, size int, attrs trace.SpanStartEventOption) (context.Context, trace.Span) {
return startSpan(o.tracer, ctx, op, size, attrs)
func (o *otelclient) start(ctx context.Context, op string, size int) (context.Context, trace.Span) {
return startSpan(o.tracer, ctx, op, size, o.tAttrs)
}

func (o *otelclient) end(span trace.Span, err error) {
endSpan(span, err)
}

func (d *dedicated) start(ctx context.Context, op string, size int, attrs trace.SpanStartEventOption) (context.Context, trace.Span) {
return startSpan(d.tracer, ctx, op, size, attrs)
func (d *dedicated) start(ctx context.Context, op string, size int) (context.Context, trace.Span) {
return startSpan(d.tracer, ctx, op, size, d.tAttrs)
}

func (d *dedicated) end(span trace.Span, err error) {
Expand Down

0 comments on commit 1a30827

Please sign in to comment.