-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtracing.go
More file actions
830 lines (745 loc) · 26.4 KB
/
tracing.go
File metadata and controls
830 lines (745 loc) · 26.4 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tracing
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"sync"
"sync/atomic"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
// Note: Option type and functional options are defined in options.go
const (
// DefaultServiceName is the default service name used for tracing when none is provided.
DefaultServiceName = "rivaas-service"
// DefaultServiceVersion is the default service version when none is provided.
DefaultServiceVersion = "1.0.0"
// DefaultSampleRate is the default sampling rate (100% of requests).
DefaultSampleRate = 1.0
)
// Attribute key prefixes for string building
const (
attrPrefixParam = "http.request.param."
attrPrefixHeader = "http.request.header."
)
// samplingMultiplier is used for sampling decisions.
//
// The value 2654435761 is 2^32/φ (where φ is the golden ratio ≈ 1.618),
// rounded to the nearest odd number. This constant is from Knuth's
// "The Art of Computer Programming, Vol. 3, Section 6.4" on multiplicative
// hashing. Being coprime to 2^64, it ensures the sequence (counter * multiplier)
// cycles through all values before repeating.
const samplingMultiplier = 2654435761
// Provider represents the available tracing providers.
type Provider string
const (
// NoopProvider is a no-op provider that doesn't export anything (default).
NoopProvider Provider = "noop"
// StdoutProvider exports traces to stdout (development/testing).
StdoutProvider Provider = "stdout"
// OTLPProvider exports traces via OTLP gRPC protocol.
OTLPProvider Provider = "otlp"
// OTLPHTTPProvider exports traces via OTLP HTTP protocol.
OTLPHTTPProvider Provider = "otlp-http"
)
// Tracer holds OpenTelemetry tracing configuration and runtime state.
// All operations on Tracer are thread-safe.
//
// It implements request tracing for integration with HTTP frameworks.
//
// Important: Tracer is immutable after creation via New(). All configuration
// must be done through functional options passed to New().
//
// Global State:
// By default, this package does NOT set the global OpenTelemetry tracer provider.
// Use WithGlobalTracerProvider() option if you want global registration.
// This allows multiple tracing configurations to coexist in the same process.
type Tracer struct {
// Core tracing components
tracer trace.Tracer
propagator propagation.TextMapPropagator
tracerProvider trace.TracerProvider
sdkProvider *sdktrace.TracerProvider // SDK provider for shutdown (nil if custom)
logger *slog.Logger // Logger for internal operational events; never nil (uses DiscardHandler when not set)
serviceName string
serviceVersion string
provider Provider
otlpEndpoint string
// Lifecycle hooks
spanStartHook SpanStartHook
spanFinishHook SpanFinishHook
// Tracing behavior settings
sampleRate float64
// Atomic types (must be 8-byte aligned)
samplingCounter atomic.Uint64 // Sampling counter
samplingThreshold uint64 // Precomputed sampling threshold
// Shutdown synchronization
shutdownOnce sync.Once
shutdownErr error
// One-time warning when OTLP is used without calling Start(ctx)
otlpNotStartedWarnOnce sync.Once
// Small types and booleans at end
otlpInsecure bool
enabled bool
customTracerProvider bool
registerGlobal bool // If true, sets otel.SetTracerProvider()
providerSet bool // Tracks if a provider option was explicitly configured
isStarted atomic.Bool // Tracks if Start() has been called
// String pool for reusable string builders
spanNamePool sync.Pool
}
// New creates a new Tracer with the given options.
// Returns an error if the tracing provider fails to initialize.
// For a version that panics on error, use MustNew.
//
// When using OTLP options (WithOTLP, WithOTLPHTTP), callers must call Start(ctx)
// before any traces are exported. Forgetting to call Start results in no traces and
// no error from New(); only a one-time log warning is emitted when the first span is created.
//
// By default, this function does NOT set the global OpenTelemetry tracer provider.
// Use WithGlobalTracerProvider() if you want to register the tracer provider as the global default.
//
// Default configuration:
// - Service name: DefaultServiceName ("rivaas-service")
// - Service version: DefaultServiceVersion ("1.0.0")
// - Sample rate: DefaultSampleRate (1.0 = 100%)
// - Provider: NoopProvider (no traces exported)
//
// Example:
//
// tracer, err := tracing.New(
// tracing.WithServiceName("my-api"),
// tracing.WithOTLP("localhost:4317"),
// tracing.WithSampleRate(0.1),
// )
// if err != nil {
// log.Fatal(err)
// }
// defer tracer.Shutdown(context.Background())
func New(opts ...Option) (*Tracer, error) {
cfg := defaultConfig()
for i, opt := range opts {
if opt == nil {
return nil, fmt.Errorf("tracing: option at index %d cannot be nil", i)
}
opt(cfg)
}
if err := cfg.validate(); err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
t, err := newTracerFromConfig(cfg)
if err != nil {
return nil, err
}
if !t.requiresNetworkInit() {
if initErr := t.initializeProvider(); initErr != nil {
return nil, fmt.Errorf("failed to initialize tracing: %w", initErr)
}
}
return t, nil
}
// defaultConfig returns a config with default values.
func defaultConfig() *config {
return &config{
serviceName: DefaultServiceName,
serviceVersion: DefaultServiceVersion,
sampleRate: DefaultSampleRate,
provider: NoopProvider,
propagator: otel.GetTextMapPropagator(),
}
}
// validate checks the config and sets samplingThreshold and OTLP default endpoint if needed.
func (c *config) validate() error {
if len(c.validationErrors) > 0 {
var errMsgs []string
for _, err := range c.validationErrors {
errMsgs = append(errMsgs, err.Error())
}
return fmt.Errorf("validation errors: %s", strings.Join(errMsgs, "; "))
}
if c.customTracerProvider && c.tracerProvider == nil {
return errors.New("tracerProvider: cannot be nil when using WithTracerProvider")
}
if c.customTracerProvider && c.providerSet {
return errors.New("cannot combine WithTracerProvider with provider options (WithOTLP, WithStdout, WithNoop, WithOTLPHTTP): provider options are ignored when using WithTracerProvider; use only one")
}
if c.serviceName == "" {
return errors.New("serviceName: cannot be empty")
}
if c.serviceVersion == "" {
return errors.New("serviceVersion: cannot be empty")
}
if c.sampleRate < 0.0 || c.sampleRate > 1.0 {
return fmt.Errorf("sampleRate: must be between 0.0 and 1.0, got %f", c.sampleRate)
}
if c.sampleRate > 0.0 && c.sampleRate < 1.0 {
c.samplingThreshold = uint64(c.sampleRate * float64(^uint64(0)))
} else if c.sampleRate == 1.0 {
c.samplingThreshold = ^uint64(0)
} else {
c.samplingThreshold = 0
}
switch c.provider {
case NoopProvider, StdoutProvider:
// no-op
case OTLPProvider, OTLPHTTPProvider:
if c.otlpEndpoint == "" {
c.otlpEndpointDefaulted = true
c.otlpEndpoint = "localhost:4317"
}
default:
return fmt.Errorf("provider: unsupported tracing provider %q", c.provider)
}
return nil
}
// newTracerFromConfig builds a Tracer from a validated config.
func newTracerFromConfig(cfg *config) (*Tracer, error) {
logger := cfg.logger
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
t := &Tracer{
tracerProvider: cfg.tracerProvider,
customTracerProvider: cfg.customTracerProvider,
registerGlobal: cfg.registerGlobal,
serviceName: cfg.serviceName,
serviceVersion: cfg.serviceVersion,
sampleRate: cfg.sampleRate,
samplingThreshold: cfg.samplingThreshold,
tracer: cfg.tracer,
propagator: cfg.propagator,
logger: logger,
spanStartHook: cfg.spanStartHook,
spanFinishHook: cfg.spanFinishHook,
provider: cfg.provider,
otlpEndpoint: cfg.otlpEndpoint,
otlpInsecure: cfg.otlpInsecure,
providerSet: cfg.providerSet,
enabled: true,
spanNamePool: sync.Pool{
New: func() any {
return &strings.Builder{}
},
},
}
if cfg.otlpEndpointDefaulted {
t.logger.Warn("OTLP endpoint not specified, will use default", "default", "localhost:4317")
}
return t, nil
}
// MustNew creates a new Tracer with the given options.
// It panics with an error if the tracing provider fails to initialize.
// Callers that recover from the panic get an error they can unwrap with errors.Is/errors.As.
// Use this for convenience when you want to panic on initialization errors.
//
// Example:
//
// tracer := tracing.MustNew(
// tracing.WithServiceName("my-api"),
// tracing.WithStdout(),
// )
// defer tracer.Shutdown(context.Background())
func MustNew(opts ...Option) *Tracer {
t, err := New(opts...)
if err != nil {
panic(err)
}
return t
}
// IsEnabled returns true if tracing is enabled.
func (t *Tracer) IsEnabled() bool {
return t.enabled
}
// ServiceName returns the service name.
func (t *Tracer) ServiceName() string {
return t.serviceName
}
// ServiceVersion returns the service version.
func (t *Tracer) ServiceVersion() string {
return t.serviceVersion
}
// GetTracer returns the OpenTelemetry tracer.
func (t *Tracer) GetTracer() trace.Tracer {
return t.tracer
}
// GetPropagator returns the OpenTelemetry propagator.
func (t *Tracer) GetPropagator() propagation.TextMapPropagator {
return t.propagator
}
// GetProvider returns the current tracing provider.
func (t *Tracer) GetProvider() Provider {
if !t.enabled {
return ""
}
return t.provider
}
// RequiresStart returns true if the tracer uses an OTLP provider and therefore
// requires Start(ctx) to be called before traces are exported. Use in tests or
// wiring code to assert that Start must be called.
func (t *Tracer) RequiresStart() bool {
return t.requiresNetworkInit()
}
// IsStarted returns true after Start() has been called. Use in tests or wiring code
// to assert that the tracer was started when required (e.g. when RequiresStart() is true).
func (t *Tracer) IsStarted() bool {
return t.isStarted.Load()
}
// requiresNetworkInit returns true if the provider requires network initialization.
// OTLP providers need network connections and should be initialized in Start(ctx).
func (t *Tracer) requiresNetworkInit() bool {
return t.provider == OTLPProvider || t.provider == OTLPHTTPProvider
}
// logOtlpNotStartedWarning logs a one-time warning when OTLP is used without calling Start(ctx).
func (t *Tracer) logOtlpNotStartedWarning() {
t.otlpNotStartedWarnOnce.Do(func() {
t.logger.Warn("OTLP tracer not started: call Start(ctx) before creating spans; traces will not be exported")
})
}
// Start initializes OTLP providers that require network connections.
// When using OTLP options (WithOTLP, WithOTLPHTTP), callers must call Start(ctx)
// before traces are exported; forgetting it will result in no traces (and no error at New).
// The context is used for the OTLP connection establishment.
// This method is idempotent; calling it multiple times is safe.
//
// For non-OTLP providers (Noop, Stdout), this is a no-op since they
// are initialized in New().
//
// Example:
//
// ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
// defer cancel()
//
// tracer, _ := tracing.New(tracing.WithOTLP("localhost:4317"))
// if err := tracer.Start(ctx); err != nil {
// log.Fatal(err)
// }
func (t *Tracer) Start(ctx context.Context) error {
if !t.enabled {
return nil
}
// Idempotent: only start once
if !t.isStarted.CompareAndSwap(false, true) {
return nil // Already started
}
// Initialize OTLP providers with the provided context
if t.requiresNetworkInit() {
if err := t.initializeProviderWithContext(ctx); err != nil {
return fmt.Errorf("failed to initialize tracing: %w", err)
}
}
return nil
}
// Shutdown gracefully shuts down the tracing system, flushing any pending spans.
// This should be called before the application exits to ensure all spans are exported.
// It shuts down the tracer provider if one was initialized.
// This method is idempotent - calling it multiple times is safe and will only perform shutdown once.
//
// Example:
//
// tracer, _ := tracing.New(tracing.WithStdout())
// defer func() {
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
// if err := tracer.Shutdown(ctx); err != nil {
// log.Printf("Error shutting down tracer: %v", err)
// }
// }()
func (t *Tracer) Shutdown(ctx context.Context) error {
if !t.enabled {
return nil
}
t.shutdownOnce.Do(func() {
// Shutdown the SDK tracer provider if it exists and is NOT a custom provider
if t.sdkProvider != nil && !t.customTracerProvider {
t.logger.Debug("Shutting down tracer provider")
if err := t.sdkProvider.Shutdown(ctx); err != nil {
t.logger.Error("Error shutting down tracer provider", "error", err)
t.shutdownErr = fmt.Errorf("tracer provider shutdown: %w", err)
return
}
t.logger.Debug("Tracer provider shut down successfully")
} else if t.customTracerProvider {
t.logger.Debug("Skipping shutdown of custom tracer provider (managed by user)")
}
})
return t.shutdownErr
}
// StartSpan starts a new span with the given name and options.
// Returns a new context with the span attached and the span itself.
//
// If tracing is disabled, returns the original context and a non-recording span.
// The returned span should always be ended, even if tracing is disabled.
//
// Example:
//
// ctx, span := tracer.StartSpan(ctx, "database-query")
// defer tracer.FinishSpan(span)
func (t *Tracer) StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
if !t.enabled {
return ctx, trace.SpanFromContext(ctx)
}
// Check if context is already canceled
select {
case <-ctx.Done():
return ctx, trace.SpanFromContext(ctx)
default:
}
if t.requiresNetworkInit() && !t.isStarted.Load() {
t.logOtlpNotStartedWarning()
}
return t.tracer.Start(ctx, name, opts...) //nolint:spancheck // span is returned to caller who manages its lifecycle
}
// FinishSpan ends the span with status Ok. Use for child spans that complete
// successfully and have no HTTP status. Safe to call multiple times; subsequent
// calls are no-ops.
//
// Example:
//
// defer tracer.FinishSpan(span)
func (t *Tracer) FinishSpan(span trace.Span) {
if !t.enabled || span == nil || !span.IsRecording() {
return
}
span.SetStatus(codes.Ok, "")
span.End()
}
// FinishSpanWithHTTPStatus ends the span and sets status from the HTTP status code:
// 2xx-3xx → Ok, 4xx-5xx → Error. Use for request-level spans or when you have
// an HTTP status. Safe to call multiple times; subsequent calls are no-ops.
//
// Example:
//
// defer tracer.FinishSpanWithHTTPStatus(span, rw.Status())
func (t *Tracer) FinishSpanWithHTTPStatus(span trace.Span, statusCode int) {
if !t.enabled || span == nil || !span.IsRecording() {
return
}
setStatusFromHTTPCodeAndEnd(span, statusCode)
}
// FinishSpanWithError marks the span as failed with the given error, sets standard
// error attributes (exception.type, exception.message, error), and ends the span.
// Status description is err.Error(). Safe to call multiple times; subsequent calls
// are no-ops.
//
// Example:
//
// if err != nil {
// tracer.FinishSpanWithError(span, err)
// return err
// }
// tracer.FinishSpan(span)
func (t *Tracer) FinishSpanWithError(span trace.Span, err error) {
if !t.enabled || span == nil || !span.IsRecording() {
return
}
if err != nil {
setErrorAttributes(span, err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Error, "")
}
span.End()
}
// RecordError records an error on the span without ending it. Sets exception.type,
// exception.message, and the legacy "error" attribute, and sets span status to Error.
// Use when an error occurs mid-span and you want to record it but continue (e.g. retry).
// Call FinishSpan or FinishSpanWithError when the span ends.
func (t *Tracer) RecordError(span trace.Span, err error) {
if !t.enabled || span == nil || !span.IsRecording() || err == nil {
return
}
setErrorAttributes(span, err)
span.SetStatus(codes.Error, err.Error())
}
// WithSpan runs fn under a new span with the given name. The span is finished with
// success (FinishSpan) if fn returns nil, or with error (FinishSpanWithError) if fn
// returns a non-nil error. Returns the error from fn.
//
// Example:
//
// err := tracer.WithSpan(ctx, "process-order", func(ctx context.Context) error {
// return processOrder(ctx, id)
// })
func (t *Tracer) WithSpan(ctx context.Context, name string, fn func(context.Context) error) error {
ctx, span := t.StartSpan(ctx, name)
var err error
defer func() {
if err != nil {
t.FinishSpanWithError(span, err)
} else {
t.FinishSpan(span)
}
}()
err = fn(ctx)
return err
}
// SetSpanAttribute adds an attribute to the span with type-safe handling.
//
// Supported types:
// - string, int, int64, float64, bool: native OpenTelemetry handling
// - Other types: converted to string using fmt.Sprintf
//
// This is a no-op if tracing is disabled, span is nil, or span is not recording.
//
// Example:
//
// tracer.SetSpanAttribute(span, "user.id", 12345)
// tracer.SetSpanAttribute(span, "user.premium", true)
func (t *Tracer) SetSpanAttribute(span trace.Span, key string, value any) {
if !t.enabled || span == nil || !span.IsRecording() {
return
}
span.SetAttributes(buildAttribute(key, value))
}
// AddSpanEvent adds an event to the span with optional attributes.
// Events represent important moments in a span's lifetime.
//
// This is a no-op if tracing is disabled, span is nil, or span is not recording.
//
// Example:
//
// tracer.AddSpanEvent(span, "cache_hit", attribute.String("key", "user:123"))
func (t *Tracer) AddSpanEvent(span trace.Span, name string, attrs ...attribute.KeyValue) {
if !t.enabled || span == nil || !span.IsRecording() {
return
}
span.AddEvent(name, trace.WithAttributes(attrs...))
}
// ExtractTraceContext extracts trace context from HTTP request headers.
// Returns a new context with the extracted trace information.
//
// If no trace context is found in headers, returns the original context.
// Uses W3C Trace Context format by default.
//
// Example:
//
// ctx := tracer.ExtractTraceContext(ctx, req.Header)
func (t *Tracer) ExtractTraceContext(ctx context.Context, headers http.Header) context.Context {
if !t.enabled {
return ctx
}
return t.propagator.Extract(ctx, propagation.HeaderCarrier(headers))
}
// InjectTraceContext injects trace context into HTTP headers.
// This allows trace context to propagate across service boundaries.
//
// Uses W3C Trace Context format by default.
// This is a no-op if tracing is disabled.
//
// Example:
//
// tracer.InjectTraceContext(ctx, resp.Header)
func (t *Tracer) InjectTraceContext(ctx context.Context, headers http.Header) {
if !t.enabled {
return
}
t.propagator.Inject(ctx, propagation.HeaderCarrier(headers))
}
// StartRequestSpan starts a span for an HTTP request.
// This is used by the middleware to create request spans with standard attributes.
func (t *Tracer) StartRequestSpan(ctx context.Context, req *http.Request, path string, isStatic bool) (context.Context, trace.Span) {
if !t.enabled {
return ctx, trace.SpanFromContext(ctx)
}
// Check if context is already canceled
select {
case <-ctx.Done():
t.logger.Debug("Context canceled before span creation", "path", path, "method", req.Method)
return ctx, trace.SpanFromContext(ctx)
default:
}
// Extract trace context from headers
ctx = t.ExtractTraceContext(ctx, req.Header)
// Sampling decision using integer arithmetic
if t.sampleRate < 1.0 {
if t.sampleRate == 0.0 {
t.logger.Debug("Request not sampled (0% sample rate)", "path", path, "method", req.Method)
return ctx, trace.SpanFromContext(ctx)
}
counter := t.samplingCounter.Add(1)
hash := counter * samplingMultiplier
if hash > t.samplingThreshold {
t.logger.Debug("Request not sampled (probabilistic)", "path", path, "method", req.Method, "sample_rate", t.sampleRate)
return ctx, trace.SpanFromContext(ctx)
}
}
// Build span name from method and path
var spanName string
sb, ok := t.spanNamePool.Get().(*strings.Builder)
if !ok {
sb = &strings.Builder{}
}
sb.Reset()
_, _ = sb.WriteString(req.Method)
_ = sb.WriteByte(' ')
_, _ = sb.WriteString(path)
spanName = sb.String()
t.spanNamePool.Put(sb)
// Start span
ctx, span := t.tracer.Start(ctx, spanName, trace.WithSpanKind(trace.SpanKindServer))
// Set standard attributes
attrs := []attribute.KeyValue{
attribute.String("http.method", req.Method),
attribute.String("http.url", req.URL.String()),
attribute.String("http.scheme", req.URL.Scheme),
attribute.String("http.host", req.Host),
attribute.String("http.route", path),
attribute.String("http.user_agent", req.UserAgent()),
attribute.String("service.name", t.serviceName),
attribute.String("service.version", t.serviceVersion),
attribute.Bool("rivaas.router.static_route", isStatic),
}
span.SetAttributes(attrs...)
// Invoke span start hook if configured
if t.spanStartHook != nil {
t.spanStartHook(ctx, span, req)
}
return ctx, span
}
// FinishRequestSpan completes the span for an HTTP request.
func (t *Tracer) FinishRequestSpan(span trace.Span, statusCode int) {
if !t.enabled || span == nil || !span.IsRecording() {
return
}
// Set status code attribute
span.SetAttributes(attribute.Int("http.status_code", statusCode))
// Invoke span finish hook if configured
if t.spanFinishHook != nil {
t.spanFinishHook(span, statusCode)
}
setStatusFromHTTPCodeAndEnd(span, statusCode)
}
// setStatusFromHTTPCodeAndEnd sets span status from HTTP status code (2xx-3xx → Ok,
// 4xx-5xx → Error) and ends the span. Shared by FinishSpanWithHTTPStatus and FinishRequestSpan.
func setStatusFromHTTPCodeAndEnd(span trace.Span, statusCode int) {
if statusCode >= 400 {
span.SetStatus(codes.Error, fmt.Sprintf("HTTP %d", statusCode))
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
}
// setErrorAttributes sets standard error attributes on the span (exception.type,
// exception.message, and legacy "error"). Used by FinishSpanWithError and RecordError.
func setErrorAttributes(span trace.Span, err error) {
if span == nil || !span.IsRecording() || err == nil {
return
}
msg := err.Error()
typ := fmt.Sprintf("%T", err)
span.SetAttributes(
attribute.String("exception.type", typ),
attribute.String("exception.message", msg),
attribute.String("error", msg),
)
}
// buildAttribute creates an OpenTelemetry attribute from a key-value pair.
func buildAttribute(key string, value any) attribute.KeyValue {
switch v := value.(type) {
case string:
return attribute.String(key, v)
case int:
return attribute.Int(key, v)
case int64:
return attribute.Int64(key, v)
case float64:
return attribute.Float64(key, v)
case bool:
return attribute.Bool(key, v)
default:
return attribute.String(key, fmt.Sprintf("%v", v))
}
}
// CopyTraceContext returns a new context that carries the current trace (span context)
// from ctx but has no active span. Use when starting goroutines or background work
// so that new spans created in that context are linked to the same trace.
//
// If ctx has no valid span context, returns context.Background().
//
// Example:
//
// traceCtx := tracing.CopyTraceContext(r.Context())
// go func() {
// _, span := tracer.StartSpan(traceCtx, "async-job")
// defer tracer.FinishSpan(span)
// doAsyncWork(ctx)
// }()
func CopyTraceContext(ctx context.Context) context.Context {
span := trace.SpanFromContext(ctx)
if !span.SpanContext().IsValid() {
return context.Background()
}
return trace.ContextWithRemoteSpanContext(context.Background(), span.SpanContext())
}
// TraceID returns the current trace ID from the active span in the context.
// Returns an empty string if no active span or span context is invalid.
func TraceID(ctx context.Context) string {
span := trace.SpanFromContext(ctx)
if span.SpanContext().IsValid() {
return span.SpanContext().TraceID().String()
}
return ""
}
// SpanID returns the current span ID from the active span in the context.
// Returns an empty string if no active span or span context is invalid.
func SpanID(ctx context.Context) string {
span := trace.SpanFromContext(ctx)
if span.SpanContext().IsValid() {
return span.SpanContext().SpanID().String()
}
return ""
}
// SetSpanAttributeFromContext adds an attribute to the current span from context.
// It is a convenience for when you only have a context (e.g. in HTTP handlers that
// receive context from the tracing middleware). It operates on the span in context
// and is the context-based equivalent of tracer.SetSpanAttribute(span, key, value).
// This is a no-op if tracing is not active.
func SetSpanAttributeFromContext(ctx context.Context, key string, value any) {
span := trace.SpanFromContext(ctx)
if !span.IsRecording() {
return
}
span.SetAttributes(buildAttribute(key, value))
}
// AddSpanEventFromContext adds an event to the current span from context.
// It is a convenience for when you only have a context (e.g. in HTTP handlers that
// receive context from the tracing middleware). It operates on the span in context
// and is the context-based equivalent of tracer.AddSpanEvent(span, name, attrs...).
// This is a no-op if tracing is not active.
func AddSpanEventFromContext(ctx context.Context, name string, attrs ...attribute.KeyValue) {
span := trace.SpanFromContext(ctx)
if span.IsRecording() {
span.AddEvent(name, trace.WithAttributes(attrs...))
}
}
// RecordErrorFromContext records an error on the current span in ctx without ending it.
// Sets exception.type, exception.message, and span status to Error. No-op if ctx has
// no recording span or err is nil.
func RecordErrorFromContext(ctx context.Context, err error) {
span := trace.SpanFromContext(ctx)
if !span.IsRecording() || err == nil {
return
}
setErrorAttributes(span, err)
span.SetStatus(codes.Error, err.Error())
}