-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobservability.go
More file actions
608 lines (490 loc) · 12.6 KB
/
Copy pathobservability.go
File metadata and controls
608 lines (490 loc) · 12.6 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
package sdk
import (
"context"
"encoding/json"
"fmt"
"maps"
"runtime"
"strconv"
"sync"
"time"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// Tracer provides distributed tracing capabilities.
type TracerImpl struct {
logger logger.Logger
metrics metrics.Metrics
mu sync.RWMutex
spans map[string]*SpanImpl
active map[string]*SpanImpl
}
// SpanImpl represents a trace span.
type SpanImpl struct {
TraceID string
SpanID string
ParentID string
Name string
StartTime time.Time
EndTime time.Time
Tags map[string]string
Logs []SpanLog
Status SpanStatus
Error error
mu sync.Mutex
}
// SpanLog represents a log entry in a span.
type SpanLog struct {
Timestamp time.Time
Level string
Message string
Fields map[string]any
}
// SpanStatus represents the status of a span.
type SpanStatus string
const (
SpanStatusOK SpanStatus = "ok"
SpanStatusError SpanStatus = "error"
)
// NewTracer creates a new tracer.
func NewTracer(logger logger.Logger, metrics metrics.Metrics) *TracerImpl {
return &TracerImpl{
logger: logger,
metrics: metrics,
spans: make(map[string]*SpanImpl),
active: make(map[string]*SpanImpl),
}
}
// StartSpan starts a new trace span.
func (t *TracerImpl) StartSpan(ctx context.Context, name string) *SpanImpl {
span := &SpanImpl{
TraceID: generateID(),
SpanID: generateID(),
Name: name,
StartTime: time.Now(),
Tags: make(map[string]string),
Logs: make([]SpanLog, 0),
Status: SpanStatusOK,
}
// Check for parent span in context
if parentSpan := SpanFromContext(ctx); parentSpan != nil {
span.ParentID = parentSpan.SpanID
span.TraceID = parentSpan.TraceID
}
t.mu.Lock()
t.spans[span.SpanID] = span
t.active[span.SpanID] = span
t.mu.Unlock()
if t.logger != nil {
t.logger.Debug("Span started",
logger.String("trace_id", span.TraceID),
logger.String("span_id", span.SpanID),
logger.String("name", name),
)
}
if t.metrics != nil {
t.metrics.Counter("forge.ai.sdk.trace.spans_started", metrics.WithLabel("name", name)).Inc()
}
return span
}
// Finish completes a span.
func (s *SpanImpl) Finish() {
s.mu.Lock()
defer s.mu.Unlock()
s.EndTime = time.Now()
// Log span completion
if s.Error != nil {
s.Status = SpanStatusError
}
}
// SetTag sets a tag on the span.
func (s *SpanImpl) SetTag(key, value string) {
s.mu.Lock()
defer s.mu.Unlock()
s.Tags[key] = value
}
// SetError sets an error on the span.
func (s *SpanImpl) SetError(err error) {
s.mu.Lock()
defer s.mu.Unlock()
s.Error = err
s.Status = SpanStatusError
}
// LogEvent logs an event in the span.
func (s *SpanImpl) LogEvent(level, message string, fields map[string]any) {
s.mu.Lock()
defer s.mu.Unlock()
s.Logs = append(s.Logs, SpanLog{
Timestamp: time.Now(),
Level: level,
Message: message,
Fields: fields,
})
}
// Duration returns the span duration.
func (s *SpanImpl) Duration() time.Duration {
s.mu.Lock()
defer s.mu.Unlock()
if s.EndTime.IsZero() {
return time.Since(s.StartTime)
}
return s.EndTime.Sub(s.StartTime)
}
// SpanFromContext retrieves a span from context.
func SpanFromContext(ctx context.Context) *SpanImpl {
if span, ok := ctx.Value(spanKey).(*SpanImpl); ok {
return span
}
return nil
}
// ContextWithSpan adds a span to context.
func ContextWithSpan(ctx context.Context, span *SpanImpl) context.Context {
return context.WithValue(ctx, spanKey, span)
}
type contextKey string
const spanKey contextKey = "span"
// generateID generates a unique ID.
func generateID() string {
return strconv.FormatInt(time.Now().UnixNano(), 10)
}
// DebugInfo provides debugging information.
type DebugInfo struct {
Timestamp time.Time
Goroutines int
MemoryStats RuntimeMemoryStats
ActiveSpans int
RecentErrors []ErrorInfo
RequestStats RequestStats
}
// RuntimeMemoryStats provides memory usage statistics.
type RuntimeMemoryStats struct {
Alloc uint64
TotalAlloc uint64
Sys uint64
NumGC uint32
}
// ErrorInfo represents error information.
type ErrorInfo struct {
Timestamp time.Time
Message string
Stack string
Context map[string]any
}
// RequestStats provides request statistics.
type RequestStats struct {
Total int64
Success int64
Failed int64
AvgDuration time.Duration
P50Duration time.Duration
P95Duration time.Duration
P99Duration time.Duration
}
// Debugger provides debugging capabilities.
type Debugger struct {
logger logger.Logger
mu sync.RWMutex
recentErrors []ErrorInfo
maxErrors int
}
// NewDebugger creates a new debugger.
func NewDebugger(logger logger.Logger) *Debugger {
return &Debugger{
logger: logger,
recentErrors: make([]ErrorInfo, 0),
maxErrors: 100,
}
}
// GetDebugInfo retrieves current debug information.
func (d *Debugger) GetDebugInfo() *DebugInfo {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
d.mu.RLock()
errorCount := len(d.recentErrors)
recentErrors := make([]ErrorInfo, 0)
if errorCount > 0 {
// Get last 10 errors
start := 0
if errorCount > 10 {
start = errorCount - 10
}
recentErrors = d.recentErrors[start:]
}
d.mu.RUnlock()
return &DebugInfo{
Timestamp: time.Now(),
Goroutines: runtime.NumGoroutine(),
MemoryStats: RuntimeMemoryStats{
Alloc: memStats.Alloc,
TotalAlloc: memStats.TotalAlloc,
Sys: memStats.Sys,
NumGC: memStats.NumGC,
},
RecentErrors: recentErrors,
}
}
// RecordError records an error for debugging.
func (d *Debugger) RecordError(err error, context map[string]any) {
if err == nil {
return
}
errorInfo := ErrorInfo{
Timestamp: time.Now(),
Message: err.Error(),
Stack: getStackTrace(),
Context: context,
}
d.mu.Lock()
defer d.mu.Unlock()
d.recentErrors = append(d.recentErrors, errorInfo)
// Keep only last N errors
if len(d.recentErrors) > d.maxErrors {
d.recentErrors = d.recentErrors[1:]
}
}
// GetRecentErrors retrieves recent errors.
func (d *Debugger) GetRecentErrors(count int) []ErrorInfo {
d.mu.RLock()
defer d.mu.RUnlock()
if count <= 0 || count > len(d.recentErrors) {
count = len(d.recentErrors)
}
start := len(d.recentErrors) - count
errors := make([]ErrorInfo, count)
copy(errors, d.recentErrors[start:])
return errors
}
// ClearErrors clears all recorded errors.
func (d *Debugger) ClearErrors() {
d.mu.Lock()
defer d.mu.Unlock()
d.recentErrors = make([]ErrorInfo, 0)
}
// getStackTrace captures the current stack trace.
func getStackTrace() string {
buf := make([]byte, 4096)
n := runtime.Stack(buf, false)
return string(buf[:n])
}
// Profiler provides performance profiling.
type Profiler struct {
logger logger.Logger
metrics metrics.Metrics
mu sync.RWMutex
profiles map[string]*Profile
}
// Profile represents a performance profile.
type Profile struct {
Name string
Count int64
TotalTime time.Duration
MinTime time.Duration
MaxTime time.Duration
AvgTime time.Duration
Percentiles map[int]time.Duration
mu sync.Mutex
durations []time.Duration
}
// NewProfiler creates a new profiler.
func NewProfiler(logger logger.Logger, metrics metrics.Metrics) *Profiler {
return &Profiler{
logger: logger,
metrics: metrics,
profiles: make(map[string]*Profile),
}
}
// StartProfile starts profiling an operation.
func (p *Profiler) StartProfile(name string) *ProfileSession {
return &ProfileSession{
profiler: p,
name: name,
startTime: time.Now(),
}
}
// ProfileSession represents an active profiling session.
type ProfileSession struct {
profiler *Profiler
name string
startTime time.Time
}
// End ends the profiling session.
func (ps *ProfileSession) End() {
duration := time.Since(ps.startTime)
ps.profiler.recordDuration(ps.name, duration)
}
// recordDuration records a duration for a profile.
func (p *Profiler) recordDuration(name string, duration time.Duration) {
p.mu.Lock()
profile, exists := p.profiles[name]
if !exists {
profile = &Profile{
Name: name,
MinTime: duration,
MaxTime: duration,
Percentiles: make(map[int]time.Duration),
durations: make([]time.Duration, 0),
}
p.profiles[name] = profile
}
p.mu.Unlock()
profile.mu.Lock()
defer profile.mu.Unlock()
profile.Count++
profile.TotalTime += duration
profile.AvgTime = time.Duration(int64(profile.TotalTime) / profile.Count)
if duration < profile.MinTime {
profile.MinTime = duration
}
if duration > profile.MaxTime {
profile.MaxTime = duration
}
profile.durations = append(profile.durations, duration)
if p.metrics != nil {
p.metrics.Histogram("forge.ai.sdk.profile.duration", metrics.WithLabel("operation", name)).Observe(duration.Seconds())
}
}
// GetProfile retrieves a profile by name.
func (p *Profiler) GetProfile(name string) *Profile {
p.mu.RLock()
defer p.mu.RUnlock()
if profile, exists := p.profiles[name]; exists {
// Return a copy without the mutex
profile.mu.Lock()
defer profile.mu.Unlock()
// Copy only the public fields to avoid copying the mutex
profileCopy := &Profile{
Name: profile.Name,
Count: profile.Count,
TotalTime: profile.TotalTime,
MinTime: profile.MinTime,
MaxTime: profile.MaxTime,
AvgTime: profile.AvgTime,
Percentiles: profile.Percentiles,
// Don't copy mu or durations as they're private implementation details
}
return profileCopy
}
return nil
}
// GetAllProfiles returns all profiles.
func (p *Profiler) GetAllProfiles() map[string]*Profile {
p.mu.RLock()
defer p.mu.RUnlock()
profiles := make(map[string]*Profile)
for name, profile := range p.profiles {
profile.mu.Lock()
// Copy only the public fields to avoid copying the mutex
profileCopy := &Profile{
Name: profile.Name,
Count: profile.Count,
TotalTime: profile.TotalTime,
MinTime: profile.MinTime,
MaxTime: profile.MaxTime,
AvgTime: profile.AvgTime,
Percentiles: profile.Percentiles,
// Don't copy mu or durations as they're private implementation details
}
profile.mu.Unlock()
profiles[name] = profileCopy
}
return profiles
}
// Reset resets all profiles.
func (p *Profiler) Reset() {
p.mu.Lock()
defer p.mu.Unlock()
p.profiles = make(map[string]*Profile)
}
// ExportJSON exports profiles as JSON.
func (p *Profiler) ExportJSON() (string, error) {
profiles := p.GetAllProfiles()
data, err := json.MarshalIndent(profiles, "", " ")
if err != nil {
return "", fmt.Errorf("export failed: %w", err)
}
return string(data), nil
}
// HealthChecker provides health check capabilities.
type HealthChecker struct {
logger logger.Logger
mu sync.RWMutex
checks map[string]HealthCheckFunc
}
// HealthCheckFunc is a function that performs a health check.
type HealthCheckFunc func(context.Context) error
// HealthCheckResult represents the result of a health check.
type HealthCheckResult struct {
Name string
Status string // "healthy", "degraded", "unhealthy"
Message string
Timestamp time.Time
Duration time.Duration
Error error
}
// NewHealthChecker creates a new health checker.
func NewHealthChecker(logger logger.Logger) *HealthChecker {
return &HealthChecker{
logger: logger,
checks: make(map[string]HealthCheckFunc),
}
}
// RegisterCheck registers a health check.
func (hc *HealthChecker) RegisterCheck(name string, check HealthCheckFunc) {
hc.mu.Lock()
defer hc.mu.Unlock()
hc.checks[name] = check
}
// RunChecks runs all registered health checks.
func (hc *HealthChecker) RunChecks(ctx context.Context) map[string]*HealthCheckResult {
hc.mu.RLock()
checks := make(map[string]HealthCheckFunc)
maps.Copy(checks, hc.checks)
hc.mu.RUnlock()
results := make(map[string]*HealthCheckResult)
var (
wg sync.WaitGroup
resultsMu sync.Mutex
)
for name, check := range checks {
wg.Add(1)
go func(n string, c HealthCheckFunc) {
defer wg.Done()
result := &HealthCheckResult{
Name: n,
Timestamp: time.Now(),
}
start := time.Now()
err := c(ctx)
result.Duration = time.Since(start)
if err != nil {
result.Status = "unhealthy"
result.Error = err
result.Message = err.Error()
} else {
result.Status = "healthy"
result.Message = "OK"
}
resultsMu.Lock()
results[n] = result
resultsMu.Unlock()
}(name, check)
}
wg.Wait()
return results
}
// GetOverallHealth returns the overall health status.
func (hc *HealthChecker) GetOverallHealth(ctx context.Context) string {
results := hc.RunChecks(ctx)
unhealthy := 0
for _, result := range results {
if result.Status == "unhealthy" {
unhealthy++
}
}
if unhealthy == 0 {
return "healthy"
} else if unhealthy < len(results) {
return "degraded"
}
return "unhealthy"
}