-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathGauge.swift
228 lines (206 loc) · 7.34 KB
/
Gauge.swift
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
import struct Foundation.Date
import Dispatch
import NIOConcurrencyHelpers
/// Prometheus Gauge metric
///
/// See https://prometheus.io/docs/concepts/metric_types/#gauge
public class PromGauge<NumType: DoubleRepresentable>: PromMetric {
/// Name of the Gauge, required
public let name: String
/// Help text of the Gauge, optional
public let help: String?
/// Type of the metric, used for formatting
public let _type: PromMetricType = .gauge
/// Current value of the counter
private var value: NumType
/// Initial value of the Gauge
private let initialValue: NumType
/// Indicates wether or not metric has been used without labels
private var usedWithoutLabels: Bool
/// Storage of values that have labels attached
private var metrics: [DimensionLabels: NumType] = [:]
/// Lock used for thread safety
private let lock: Lock
/// Creates a new instance of a Gauge
///
/// - Parameters:
/// - name: Name of the Gauge
/// - help: Help text of the Gauge
/// - initialValue: Initial value to set the Gauge to
/// - p: Prometheus instance that created this Gauge
///
internal init(_ name: String, _ help: String? = nil, _ initialValue: NumType = 0) {
self.name = name
self.help = help
self.initialValue = initialValue
self.value = initialValue
self.usedWithoutLabels = initialValue != 0
self.lock = Lock()
}
/// Gets the metric string for this Gauge
///
/// - Returns:
/// Newline separated Prometheus formatted metric string
public func collect() -> String {
let (value, metrics, usedWithoutLabels) = self.lock.withLock {
(self.value, self.metrics, self.usedWithoutLabels)
}
var output = [String]()
if let help = self.help {
output.append("# HELP \(self.name) \(help)")
}
output.append("# TYPE \(self.name) \(self._type)")
if usedWithoutLabels {
output.append("\(self.name) \(value)")
}
metrics.forEach { (labels, value) in
let labelsString = encodeLabels(labels)
output.append("\(self.name)\(labelsString) \(value)")
}
return output.joined(separator: "\n")
}
/// Sets the Gauge to the current unix-time in seconds
///
/// - Parameters:
/// - labels: Labels to attach to the value
///
/// - Returns: The value of the Gauge attached to the provided labels
@discardableResult
public func setToCurrentTime(_ labels: DimensionLabels? = nil) -> NumType {
return self.set(.init(Date().timeIntervalSince1970), labels)
}
/// Tracks in progress blocks of code or functions.
///
/// func someFunc() -> String { return "ABC" }
/// let newFunc = myGauge.trackInProgress(someFunc)
/// newFunc() // returns "ABC" and increments & decrements Gauge
///
/// - Parameters:
/// - labels: Labels to attach to the value
/// - body: Function to wrap progress tracker around
///
/// - Returns: The same type of function passed in for `body`, but wrapped to track progress.
@inlinable
public func trackInProgress<T>(_ labels: DimensionLabels? = nil, _ body: @escaping () throws -> T) -> (() throws -> T) {
return {
self.inc()
defer {
self.dec()
}
return try body()
}
}
/// Time the execution duration of a closure and observe the resulting time in seconds.
///
/// - parameters:
/// - labels: Labels to attach to the resulting value.
/// - body: Closure to run & record execution time of.
@inlinable
public func time<T>(_ labels: DimensionLabels? = nil, _ body: @escaping () throws -> T) rethrows -> T {
let start = DispatchTime.now().uptimeNanoseconds
defer {
let delta = Double(DispatchTime.now().uptimeNanoseconds - start)
self.set(.init(delta / 1_000_000_000), labels)
}
return try body()
}
/// Sets the Gauge
///
/// - Parameters:
/// - amount: Amount to set the gauge to
/// - labels: Labels to attach to the value
///
/// - Returns: The value of the Gauge attached to the provided labels
@discardableResult
public func set(_ amount: NumType, _ labels: DimensionLabels? = nil) -> NumType {
return self.lock.withLock {
if let labels = labels {
self.metrics[labels] = amount
return amount
} else {
self.usedWithoutLabels = true
self.value = amount
return self.value
}
}
}
/// Increments the Gauge
///
/// - Parameters:
/// - amount: Amount to increment the Gauge with
/// - labels: Labels to attach to the value
///
/// - Returns: The value of the Gauge attached to the provided labels
@discardableResult
public func inc(_ amount: NumType, _ labels: DimensionLabels? = nil) -> NumType {
return self.lock.withLock {
if let labels = labels {
var val = self.metrics[labels] ?? self.initialValue
val += amount
self.metrics[labels] = val
return val
} else {
self.usedWithoutLabels = true
self.value += amount
return self.value
}
}
}
/// Increments the Gauge
///
/// - Parameters:
/// - labels: Labels to attach to the value
///
/// - Returns: The value of the Gauge attached to the provided labels
@discardableResult
public func inc(_ labels: DimensionLabels? = nil) -> NumType {
return self.inc(1, labels)
}
/// Decrements the Gauge
///
/// - Parameters:
/// - amount: Amount to decrement the Gauge with
/// - labels: Labels to attach to the value
///
/// - Returns: The value of the Gauge attached to the provided labels
@discardableResult
public func dec(_ amount: NumType, _ labels: DimensionLabels? = nil) -> NumType {
return self.lock.withLock {
if let labels = labels {
var val = self.metrics[labels] ?? self.initialValue
val -= amount
self.metrics[labels] = val
return val
} else {
self.usedWithoutLabels = true
self.value -= amount
return self.value
}
}
}
/// Decrements the Gauge
///
/// - Parameters:
/// - labels: Labels to attach to the value
///
/// - Returns: The value of the Gauge attached to the provided labels
@discardableResult
public func dec(_ labels: DimensionLabels? = nil) -> NumType {
return self.dec(1, labels)
}
/// Gets the value of the Gauge
///
/// - Parameters:
/// - labels: Labels to get the value for
///
/// - Returns: The value of the Gauge attached to the provided labels
public func get(_ labels: DimensionLabels? = nil) -> NumType {
return self.lock.withLock {
if let labels = labels {
return self.metrics[labels] ?? initialValue
} else {
return self.value
}
}
}
}