forked from valkey-io/valkey-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trace.go
378 lines (321 loc) · 9.61 KB
/
trace.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
package valkeyotel
import (
"context"
"strings"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"github.com/valkey-io/valkey-go"
)
var (
name = "github.com/valkey-io/valkey-go"
kind = trace.WithSpanKind(trace.SpanKindClient)
dbattr = attribute.String("db.system", "valkey")
dbstmt = attribute.Key("db.statement")
)
var _ valkey.Client = (*otelclient)(nil)
// WithClient creates a new valkey.Client with OpenTelemetry tracing enabled.
//
// Deprecated: use NewClient() instead.
func WithClient(client valkey.Client, opts ...Option) valkey.Client {
cli, err := newClient(opts...)
if err != nil {
panic(err)
}
cli.client = client
return cli
}
// Option is the Functional Options interface
type Option func(o *otelclient)
// TraceAttrs set additional attributes to append to each trace.
func TraceAttrs(attrs ...attribute.KeyValue) Option {
return func(o *otelclient) {
o.tAttrs = trace.WithAttributes(attrs...)
}
}
// WithTracerProvider sets the TracerProvider for the otelclient.
func WithTracerProvider(provider trace.TracerProvider) Option {
return func(o *otelclient) {
o.tracerProvider = provider
}
}
// WithDBStatement tells the tracing hook to add raw valkey commands to db.statement attribute.
func WithDBStatement(f StatementFunc) Option {
return func(o *otelclient) {
o.dbStmtFunc = f
}
}
// StatementFunc is a the function that maps a command's tokens to a string to put in the db.statement attribute
type StatementFunc func(cmdTokens []string) string
type otelclient struct {
client valkey.Client
meterProvider metric.MeterProvider
tracerProvider trace.TracerProvider
tracer trace.Tracer
meter metric.Meter
cscMiss metric.Int64Counter
cscHits metric.Int64Counter
addOpts []metric.AddOption
recordOpts []metric.RecordOption
tAttrs trace.SpanStartEventOption
histogramOption HistogramOption
dbStmtFunc StatementFunc
}
func (o *otelclient) B() valkey.Builder {
return o.client.B()
}
func (o *otelclient) Do(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) {
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.Do(ctx, cmd)
o.end(span, resp.Error())
return
}
func (o *otelclient) DoMulti(ctx context.Context, multi ...valkey.Completed) (resp []valkey.ValkeyResult) {
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 valkey.Completed) (resp valkey.ValkeyResultStream) {
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.DoStream(ctx, cmd)
o.end(span, resp.Error())
return
}
func (o *otelclient) DoMultiStream(ctx context.Context, multi ...valkey.Completed) (resp valkey.MultiValkeyResultStream) {
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 valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) {
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.NonValkeyError() == nil {
if resp.IsCacheHit() {
o.cscHits.Add(ctx, 1, o.addOpts...)
} else {
o.cscMiss.Add(ctx, 1, o.addOpts...)
}
}
o.end(span, resp.Error())
return
}
func (o *otelclient) DoMultiCache(ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) {
ctx, span := o.start(ctx, multiCacheableFirst(multi), multiCacheableSum(multi))
resps = o.client.DoMultiCache(ctx, multi...)
for _, resp := range resps {
if resp.NonValkeyError() == nil {
if resp.IsCacheHit() {
o.cscHits.Add(ctx, 1, o.addOpts...)
} else {
o.cscMiss.Add(ctx, 1, o.addOpts...)
}
}
}
o.end(span, firstError(resps))
return
}
func (o *otelclient) Dedicated(fn func(valkey.DedicatedClient) error) (err error) {
return o.client.Dedicated(func(client valkey.DedicatedClient) error {
return fn(&dedicated{
client: client,
tAttrs: o.tAttrs,
tracer: o.tracer,
dbStmtFunc: o.dbStmtFunc,
})
})
}
func (o *otelclient) Dedicate() (valkey.DedicatedClient, func()) {
client, cancel := o.client.Dedicate()
return &dedicated{
client: client,
tAttrs: o.tAttrs,
tracer: o.tracer,
dbStmtFunc: o.dbStmtFunc,
}, cancel
}
func (o *otelclient) Receive(ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) {
ctx, span := o.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()))
if o.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(o.dbStmtFunc(subscribe.Commands())))
}
err = o.client.Receive(ctx, subscribe, fn)
o.end(span, err)
return
}
func (o *otelclient) Nodes() map[string]valkey.Client {
nodes := o.client.Nodes()
for addr, client := range nodes {
nodes[addr] = &otelclient{
client: client,
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,
}
}
return nodes
}
func (o *otelclient) Close() {
o.client.Close()
}
var _ valkey.DedicatedClient = (*dedicated)(nil)
type dedicated struct {
client valkey.DedicatedClient
tracer trace.Tracer
tAttrs trace.SpanStartEventOption
dbStmtFunc StatementFunc
}
func (d *dedicated) B() valkey.Builder {
return d.client.B()
}
func (d *dedicated) Do(ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) {
ctx, span := d.start(ctx, first(cmd.Commands()), sum(cmd.Commands()))
if d.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(d.dbStmtFunc(cmd.Commands())))
}
resp = d.client.Do(ctx, cmd)
d.end(span, resp.Error())
return
}
func (d *dedicated) DoMulti(ctx context.Context, multi ...valkey.Completed) (resp []valkey.ValkeyResult) {
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 valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) {
ctx, span := d.start(ctx, first(subscribe.Commands()), sum(subscribe.Commands()))
if d.dbStmtFunc != nil {
span.SetAttributes(dbstmt.String(d.dbStmtFunc(subscribe.Commands())))
}
err = d.client.Receive(ctx, subscribe, fn)
d.end(span, err)
return
}
func (d *dedicated) SetPubSubHooks(hooks valkey.PubSubHooks) <-chan error {
return d.client.SetPubSubHooks(hooks)
}
func (d *dedicated) Close() {
d.client.Close()
}
func first(s []string) string {
return s[0]
}
func sum(s []string) (v int) {
for _, str := range s {
v += len(str)
}
return v
}
func firstError(s []valkey.ValkeyResult) error {
for _, result := range s {
if err := result.Error(); err != nil && !valkey.IsValkeyNil(err) {
return err
}
}
return nil
}
func multiSum(multi []valkey.Completed) (v int) {
for _, cmd := range multi {
v += sum(cmd.Commands())
}
return v
}
func multiCacheableSum(multi []valkey.CacheableTTL) (v int) {
for _, cmd := range multi {
v += sum(cmd.Cmd.Commands())
}
return v
}
func multiFirst(multi []valkey.Completed) string {
if len(multi) == 0 {
return ""
}
if len(multi) > 5 {
multi = multi[:5]
}
size := 0
for _, cmd := range multi {
size += len(first(cmd.Commands()))
}
size += len(multi) - 1
sb := strings.Builder{}
sb.Grow(size)
for i, cmd := range multi {
sb.WriteString(first(cmd.Commands()))
if i != len(multi)-1 {
sb.WriteString(" ")
}
}
return sb.String()
}
func multiCacheableFirst(multi []valkey.CacheableTTL) string {
if len(multi) == 0 {
return ""
}
if len(multi) > 5 {
multi = multi[:5]
}
size := 0
for _, cmd := range multi {
size += len(first(cmd.Cmd.Commands()))
}
size += len(multi) - 1
sb := strings.Builder{}
sb.Grow(size)
for i, cmd := range multi {
sb.WriteString(first(cmd.Cmd.Commands()))
if i != len(multi)-1 {
sb.WriteString(" ")
}
}
return sb.String()
}
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) (context.Context, trace.Span) {
return startSpan(d.tracer, ctx, op, size, d.tAttrs)
}
func (d *dedicated) end(span trace.Span, err error) {
endSpan(span, err)
}
func startSpan(tracer trace.Tracer, ctx context.Context, op string, size int, attrs trace.SpanStartEventOption) (context.Context, trace.Span) {
return tracer.Start(ctx, op, kind, attr(op, size), attrs)
}
func endSpan(span trace.Span, err error) {
if err != nil && !valkey.IsValkeyNil(err) {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
}
// do not record full db.statement to avoid collecting sensitive data
func attr(op string, size int) trace.SpanStartEventOption {
return trace.WithAttributes(dbattr, attribute.String("db.operation", op), attribute.Int("db.stmt_size", size))
}