Debian Codegraph @

bridge/opentracing/mock.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package opentracing // import "go.opentelemetry.io/otel/bridge/opentracing"
5
6 import (
7 "context"
8 "math/rand/v2"
9 "reflect"
10 "sync"
11 "time"
12
13 "go.opentelemetry.io/otel/attribute"
14 "go.opentelemetry.io/otel/bridge/opentracing/migration"
15 "go.opentelemetry.io/otel/codes"
16 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
17 "go.opentelemetry.io/otel/trace"
18 "go.opentelemetry.io/otel/trace/embedded"
19 "go.opentelemetry.io/otel/trace/noop"
20 )
21
22 //nolint:revive // ignoring missing comments for unexported global variables in an internal package.
23 var (
24 statusCodeKey = attribute.Key("status.code")
25 statusMessageKey = attribute.Key("status.message")
26 errorKey = attribute.Key("error")
27 nameKey = attribute.Key("name")
28 )
29
30 type mockContextKeyValue struct {
31 Key any
32 Value any
33 }
34
35 type mockTracer struct {
36 embedded.Tracer
37
38 FinishedSpans []*mockSpan
39 SpareTraceIDs []trace.TraceID
40 SpareSpanIDs []trace.SpanID
41 SpareContextKeyValues []mockContextKeyValue
42 TraceFlags trace.TraceFlags
43
44 randLock sync.Mutex
45 rand *rand.ChaCha8
46 }
47
48 var (
49 _ trace.Tracer = &mockTracer{}
50 _ migration.DeferredContextSetupTracerExtension = &mockTracer{}
51 )
52
53 func newMockTracer() *mockTracer {
54 u := rand.Uint32()
55 // nolint:gosec // Intentional byte extraction from uint32
56 seed := [32]byte{byte(u), byte(u >> 8), byte(u >> 16), byte(u >> 24)}
57 return &mockTracer{
58 FinishedSpans: nil,
59 SpareTraceIDs: nil,
60 SpareSpanIDs: nil,
61 SpareContextKeyValues: nil,
62
63 rand: rand.NewChaCha8(seed),
64 }
65 }
66
67 // Start returns a new trace span with the given name and options.
68 func (t *mockTracer) Start(
69 ctx context.Context,
70 _ string,
71 opts ...trace.SpanStartOption,
72 ) (context.Context, trace.Span) {
73 config := trace.NewSpanStartConfig(opts...)
74 startTime := config.Timestamp()
75 if startTime.IsZero() {
76 startTime = time.Now()
77 }
78 spanContext := trace.NewSpanContext(trace.SpanContextConfig{
79 TraceID: t.getTraceID(ctx, &config),
80 SpanID: t.getSpanID(),
81 TraceFlags: t.TraceFlags,
82 })
83 span := &mockSpan{
84 mockTracer: t,
85 officialTracer: t,
86 spanContext: spanContext,
87 Attributes: config.Attributes(),
88 StartTime: startTime,
89 EndTime: time.Time{},
90 ParentSpanID: t.getParentSpanID(ctx, &config),
91 Events: nil,
92 SpanKind: trace.ValidateSpanKind(config.SpanKind()),
93 }
94 if !migration.SkipContextSetup(ctx) {
95 ctx = trace.ContextWithSpan(ctx, span)
96 ctx = t.addSpareContextValue(ctx)
97 }
98 return ctx, span
99 }
100
101 func (t *mockTracer) addSpareContextValue(ctx context.Context) context.Context {
102 if len(t.SpareContextKeyValues) > 0 {
103 pair := t.SpareContextKeyValues[0]
104 t.SpareContextKeyValues[0] = mockContextKeyValue{}
105 t.SpareContextKeyValues = t.SpareContextKeyValues[1:]
106 if len(t.SpareContextKeyValues) == 0 {
107 t.SpareContextKeyValues = nil
108 }
109 ctx = context.WithValue(ctx, pair.Key, pair.Value)
110 }
111 return ctx
112 }
113
114 func (t *mockTracer) getTraceID(ctx context.Context, config *trace.SpanConfig) trace.TraceID {
115 if parent := t.getParentSpanContext(ctx, config); parent.IsValid() {
116 return parent.TraceID()
117 }
118 if len(t.SpareTraceIDs) > 0 {
119 traceID := t.SpareTraceIDs[0]
120 t.SpareTraceIDs = t.SpareTraceIDs[1:]
121 if len(t.SpareTraceIDs) == 0 {
122 t.SpareTraceIDs = nil
123 }
124 return traceID
125 }
126 return t.getRandTraceID()
127 }
128
129 func (t *mockTracer) getParentSpanID(ctx context.Context, config *trace.SpanConfig) trace.SpanID {
130 if parent := t.getParentSpanContext(ctx, config); parent.IsValid() {
131 return parent.SpanID()
132 }
133 return trace.SpanID{}
134 }
135
136 func (*mockTracer) getParentSpanContext(ctx context.Context, config *trace.SpanConfig) trace.SpanContext {
137 if !config.NewRoot() {
138 return trace.SpanContextFromContext(ctx)
139 }
140 return trace.SpanContext{}
141 }
142
143 func (t *mockTracer) getSpanID() trace.SpanID {
144 if len(t.SpareSpanIDs) > 0 {
145 spanID := t.SpareSpanIDs[0]
146 t.SpareSpanIDs = t.SpareSpanIDs[1:]
147 if len(t.SpareSpanIDs) == 0 {
148 t.SpareSpanIDs = nil
149 }
150 return spanID
151 }
152 return t.getRandSpanID()
153 }
154
155 func (t *mockTracer) getRandSpanID() trace.SpanID {
156 t.randLock.Lock()
157 defer t.randLock.Unlock()
158
159 sid := trace.SpanID{}
160 _, _ = t.rand.Read(sid[:])
161
162 return sid
163 }
164
165 func (t *mockTracer) getRandTraceID() trace.TraceID {
166 t.randLock.Lock()
167 defer t.randLock.Unlock()
168
169 tid := trace.TraceID{}
170 _, _ = t.rand.Read(tid[:])
171
172 return tid
173 }
174
175 // DeferredContextSetupHook implements the DeferredContextSetupTracerExtension interface.
176 func (t *mockTracer) DeferredContextSetupHook(ctx context.Context, _ trace.Span) context.Context {
177 return t.addSpareContextValue(ctx)
178 }
179
180 type mockEvent struct {
181 Timestamp time.Time
182 Name string
183 Attributes []attribute.KeyValue
184 }
185
186 type mockLink struct {
187 SpanContext trace.SpanContext
188 Attributes []attribute.KeyValue
189 }
190
191 type mockSpan struct {
192 embedded.Span
193
194 mockTracer *mockTracer
195 officialTracer trace.Tracer
196 spanContext trace.SpanContext
197 SpanKind trace.SpanKind
198 recording bool
199
200 Attributes []attribute.KeyValue
201 StartTime time.Time
202 EndTime time.Time
203 ParentSpanID trace.SpanID
204 Events []mockEvent
205 Links []mockLink
206 }
207
208 var (
209 _ trace.Span = &mockSpan{}
210 _ migration.OverrideTracerSpanExtension = &mockSpan{}
211 )
212
213 func (s *mockSpan) SpanContext() trace.SpanContext {
214 return s.spanContext
215 }
216
217 func (s *mockSpan) IsRecording() bool {
218 return s.recording
219 }
220
221 func (s *mockSpan) SetStatus(code codes.Code, msg string) {
222 s.SetAttributes(statusCodeKey.Int(int(code)), statusMessageKey.String(msg))
223 }
224
225 func (s *mockSpan) SetName(name string) {
226 s.SetAttributes(nameKey.String(name))
227 }
228
229 func (s *mockSpan) SetError(v bool) {
230 s.SetAttributes(errorKey.Bool(v))
231 }
232
233 func (s *mockSpan) SetAttributes(attributes ...attribute.KeyValue) {
234 s.applyUpdate(attributes)
235 }
236
237 func (s *mockSpan) applyUpdate(update []attribute.KeyValue) {
238 updateM := make(map[attribute.Key]attribute.Value, len(update))
239 for _, kv := range update {
240 updateM[kv.Key] = kv.Value
241 }
242
243 seen := make(map[attribute.Key]struct{})
244 for i, kv := range s.Attributes {
245 if v, ok := updateM[kv.Key]; ok {
246 s.Attributes[i].Value = v
247 seen[kv.Key] = struct{}{}
248 }
249 }
250
251 for k, v := range updateM {
252 if _, ok := seen[k]; ok {
253 continue
254 }
255 s.Attributes = append(s.Attributes, attribute.KeyValue{Key: k, Value: v})
256 }
257 }
258
259 func (s *mockSpan) End(options ...trace.SpanEndOption) {
260 if !s.EndTime.IsZero() {
261 return // already finished
262 }
263 config := trace.NewSpanEndConfig(options...)
264 endTime := config.Timestamp()
265 if endTime.IsZero() {
266 endTime = time.Now()
267 }
268 s.EndTime = endTime
269 s.mockTracer.FinishedSpans = append(s.mockTracer.FinishedSpans, s)
270 }
271
272 func (s *mockSpan) RecordError(err error, opts ...trace.EventOption) {
273 if err == nil {
274 return // no-op on nil error
275 }
276
277 if !s.EndTime.IsZero() {
278 return // already finished
279 }
280
281 s.SetStatus(codes.Error, "")
282 opts = append(opts, trace.WithAttributes(
283 semconv.ExceptionType(reflect.TypeOf(err).String()),
284 semconv.ExceptionMessage(err.Error()),
285 ))
286 s.AddEvent(semconv.ExceptionEventName, opts...)
287 }
288
289 func (s *mockSpan) Tracer() trace.Tracer {
290 return s.officialTracer
291 }
292
293 func (s *mockSpan) AddEvent(name string, o ...trace.EventOption) {
294 c := trace.NewEventConfig(o...)
295 s.Events = append(s.Events, mockEvent{
296 Timestamp: c.Timestamp(),
297 Name: name,
298 Attributes: c.Attributes(),
299 })
300 }
301
302 func (s *mockSpan) AddLink(link trace.Link) {
303 s.Links = append(s.Links, mockLink{
304 SpanContext: link.SpanContext,
305 Attributes: link.Attributes,
306 })
307 }
308
309 func (s *mockSpan) OverrideTracer(tracer trace.Tracer) {
310 s.officialTracer = tracer
311 }
312
313 func (*mockSpan) TracerProvider() trace.TracerProvider { return noop.NewTracerProvider() }