Skip to content

Commit 42edfe0

Browse files
authored
Add fix and test for MetricsSystem.prometheus() (#49)
1 parent efab3ae commit 42edfe0

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

Sources/Prometheus/PrometheusMetrics.swift

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,13 +139,21 @@ public struct PrometheusLabelSanitizer: LabelSanitizer {
139139
}
140140
}
141141

142+
/// Defines the base for a bridge between PrometheusClient and swift-metrics.
143+
/// Used by `SwiftMetrics.prometheus()` to get an instance of `PromtheusClient` from `MetricsSystem`
144+
///
145+
/// Any custom implementation of `MetricsFactory` using `PrometheusClient` should conform to this implementation.
146+
public protocol PrometheusWrappedMetricsFactory: MetricsFactory {
147+
var client: PrometheusClient { get }
148+
}
149+
142150
/// A bridge between PrometheusClient and swift-metrics. Prometheus types don't map perfectly on swift-metrics API,
143151
/// which makes bridge implementation non trivial. This class defines how exactly swift-metrics types should be backed
144152
/// with Prometheus types, e.g. how to sanitize labels, what buckets/quantiles to use for recorder/timer, etc.
145-
public struct PrometheusMetricsFactory: MetricsFactory {
153+
public struct PrometheusMetricsFactory: PrometheusWrappedMetricsFactory {
146154

147155
/// Prometheus client to bridge swift-metrics API to.
148-
private let client: PrometheusClient
156+
public let client: PrometheusClient
149157

150158
/// Bridge configuration.
151159
private let configuration: Configuration
@@ -262,10 +270,10 @@ public extension MetricsSystem {
262270
/// - Throws: `PrometheusError.PrometheusFactoryNotBootstrapped`
263271
/// if no `PrometheusClient` was used to bootstrap `MetricsSystem`
264272
static func prometheus() throws -> PrometheusClient {
265-
guard let prom = self.factory as? PrometheusClient else {
273+
guard let prom = self.factory as? PrometheusWrappedMetricsFactory else {
266274
throw PrometheusError.prometheusFactoryNotBootstrapped(bootstrappedWith: "\(self.factory)")
267275
}
268-
return prom
276+
return prom.client
269277
}
270278
}
271279

Tests/SwiftPrometheusTests/PrometheusMetricsTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ final class PrometheusMetricsTests: XCTestCase {
2121
self.prom = nil
2222
try! self.group.syncShutdownGracefully()
2323
}
24+
25+
func testGetPrometheus() {
26+
MetricsSystem.bootstrapInternal(NOOPMetricsHandler.instance)
27+
XCTAssertThrowsError(try MetricsSystem.prometheus())
28+
MetricsSystem.bootstrapInternal(PrometheusMetricsFactory(client: self.prom))
29+
XCTAssertNoThrow(try MetricsSystem.prometheus())
30+
}
2431

2532
func testCounter() {
2633
let counter = Counter(label: "my_counter")

0 commit comments

Comments
 (0)