-
Notifications
You must be signed in to change notification settings - Fork 12
/
metrics_collector.go
55 lines (47 loc) · 1.62 KB
/
metrics_collector.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
package enigma
import (
"context"
"fmt"
"sync"
"time"
)
type (
metricsCollectorID struct{}
// MetricsCollector is used to extract performance metrics for the last invocation in the context
MetricsCollector struct {
sync.Mutex
metrics *InvocationMetrics
}
// InvocationMetrics contains performance information about the last invocation in the context
InvocationMetrics struct {
InvocationRequestTimestamp time.Time
SocketWriteTimestamp time.Time
SocketReadTimestamp time.Time
InvocationResponseTimestamp time.Time
RequestMessageSize int
ResponseMessageSize int
}
)
// ToString returns a human-friendly string representation of elapsed times
func (m *InvocationMetrics) ToString() string {
return fmt.Sprintf("On air time: %v, Total time: %v", m.SocketReadTimestamp.Sub(m.SocketWriteTimestamp), m.InvocationResponseTimestamp.Sub(m.InvocationRequestTimestamp))
}
// Metrics extracts performance information
func (c *MetricsCollector) Metrics() *InvocationMetrics {
c.Lock()
defer c.Unlock()
return c.metrics
}
func getMetricsCollector(ctx context.Context) *MetricsCollector {
value := ctx.Value(metricsCollectorID{})
if value != nil {
return value.(*MetricsCollector)
}
return nil
}
// WithMetricsCollector provides a new context with the a MetricsCollector that records performance metrics for invocations
func WithMetricsCollector(ctx context.Context) (context.Context, *MetricsCollector) {
metricsCollector := &MetricsCollector{metrics: &InvocationMetrics{}}
ctxWithMetrics := context.WithValue(ctx, metricsCollectorID{}, metricsCollector)
return ctxWithMetrics, metricsCollector
}