-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspan.go
More file actions
250 lines (230 loc) · 5.84 KB
/
Copy pathspan.go
File metadata and controls
250 lines (230 loc) · 5.84 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
package trace
import (
"context"
"fmt"
"log"
"sync"
"time"
"github.com/cssbruno/gowdk/runtime/security"
)
type spanContextKey struct{}
const defaultSinkTimeout = 5 * time.Second
// SinkLogger receives completed-span export failures. Set it to nil to silence
// sink failure logging. It defaults to the standard log package.
var SinkLogger func(message string) = func(message string) {
log.Print(message)
}
// Span records one sampled unit of work. Methods are nil-safe so callers can
// defer span.End() even when sampling is disabled.
type Span struct {
mu sync.Mutex
tracer *Tracer
traceID TraceID
spanID SpanID
parentSpanID SpanID
traceState string
name string
surface Surface
lane Lane
source SourceRef
attributes []Attribute
events []Event
status Status
start time.Time
end time.Time
ended bool
}
// Start starts a span using the default tracer unless WithTracer is supplied.
func Start(ctx context.Context, name string, options ...StartOption) (context.Context, *Span) {
if tracer, ok := TracerFromContext(ctx); ok {
return tracer.Start(ctx, name, options...)
}
return defaultTracer.Start(ctx, name, options...)
}
// SpanFrom returns the active sampled span from ctx.
func SpanFrom(ctx context.Context) *Span {
if ctx == nil {
return nil
}
span, _ := ctx.Value(spanContextKey{}).(*Span)
return span
}
// End completes the span and sends an immutable snapshot to the configured
// sink. Calling End more than once is safe.
func (span *Span) End() {
if span == nil {
return
}
span.EndTime(time.Now().UTC())
}
// EndTime completes the span at t. It is useful for deterministic tests.
func (span *Span) EndTime(t time.Time) {
if span == nil {
return
}
var snapshot Snapshot
var sink Sink
var tracer *Tracer
span.mu.Lock()
if span.ended {
span.mu.Unlock()
return
}
span.ended = true
span.end = t
snapshot = span.snapshotLocked()
if span.tracer != nil {
tracer = span.tracer
sink = span.tracer.sink
}
span.mu.Unlock()
if sink != nil {
recordSpanAsync(tracer, sink, snapshot)
}
}
func recordSpanAsync(tracer *Tracer, sink Sink, snapshot Snapshot) {
go func() {
start := time.Now()
var exportErr error
defer func() {
if recovered := recover(); recovered != nil {
exportErr = fmt.Errorf("panic: %v", recovered)
tracer.recordExport(time.Since(start), exportErr)
logSinkFailure(exportErr)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), defaultSinkTimeout)
defer cancel()
if err := sink.RecordSpan(ctx, snapshot); err != nil {
exportErr = err
tracer.recordExport(time.Since(start), err)
logSinkFailure(err)
return
}
tracer.recordExport(time.Since(start), nil)
}()
}
func logSinkFailure(err error) {
if err == nil || SinkLogger == nil {
return
}
SinkLogger("gowdk trace: sink failed: " + security.RedactSecrets(err.Error()))
}
// Event records a timestamped event on the span.
func (span *Span) Event(level string, message string, attrs map[string]any) {
if span == nil || message == "" {
return
}
span.mu.Lock()
defer span.mu.Unlock()
if span.ended {
return
}
span.events = append(span.events, Event{
Time: time.Now().UTC(),
Level: level,
Message: message,
Attributes: attributesFromMap(attrs),
})
}
// Set records or replaces one span attribute.
func (span *Span) Set(key string, value any) {
if span == nil || key == "" {
return
}
span.mu.Lock()
defer span.mu.Unlock()
if span.ended {
return
}
for index := range span.attributes {
if span.attributes[index].Key == key {
if normalized, ok := normalizeAttribute(Attribute{Key: key, Value: value}); ok {
span.attributes[index] = normalized
}
return
}
}
if normalized, ok := normalizeAttribute(Attribute{Key: key, Value: value}); ok {
span.attributes = append(span.attributes, normalized)
}
}
// SetStatus records the final span status.
func (span *Span) SetStatus(code StatusCode, message string) {
if span == nil {
return
}
span.mu.Lock()
defer span.mu.Unlock()
if span.ended {
return
}
span.status = Status{Code: code, Message: message}
}
// TraceContext returns the span's W3C trace identity.
func (span *Span) TraceContext() TraceContext {
if span == nil {
return TraceContext{}
}
span.mu.Lock()
defer span.mu.Unlock()
return TraceContext{TraceID: span.traceID, SpanID: span.spanID, Sampled: true, TraceState: span.traceState}
}
func (span *Span) tracerRef() *Tracer {
if span == nil {
return nil
}
span.mu.Lock()
defer span.mu.Unlock()
return span.tracer
}
// Snapshot returns an immutable copy of the span's current state.
func (span *Span) Snapshot() Snapshot {
if span == nil {
return Snapshot{}
}
span.mu.Lock()
defer span.mu.Unlock()
return span.snapshotLocked()
}
func (span *Span) snapshotLocked() Snapshot {
end := span.end
if end.IsZero() {
end = time.Now().UTC()
}
duration := end.Sub(span.start)
if duration < 0 {
duration = 0
}
// Normalize the source path here, the single point every completed-span
// snapshot is created, so the viewer, JSON/SSE, console, and OTLP surfaces
// never observe an absolute local filesystem path by default.
return cloneSnapshot(Snapshot{
TraceID: span.traceID,
SpanID: span.spanID,
ParentSpanID: span.parentSpanID,
Name: span.name,
Surface: span.surface,
Lane: span.lane,
Source: span.source,
Attributes: span.attributes,
Events: span.events,
Status: span.status,
StartTime: span.start,
EndTime: end,
DurationNS: duration.Nanoseconds(),
})
}
func attributesFromMap(attrs map[string]any) []Attribute {
if len(attrs) == 0 {
return nil
}
out := make([]Attribute, 0, len(attrs))
for key, value := range attrs {
if key == "" {
continue
}
out = append(out, Attribute{Key: key, Value: value})
}
return cloneAttributes(out)
}