Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions Sources/Lifecycle/Lifecycle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import Darwin
import Glibc
#endif
import Backtrace
import CoreMetrics

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it intentional? AFAIR libraries shouldn't normally depend on CoreMetrics unless implementing a MetricFactory.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CoreMetrics is useful when you do not want to pul in Foundation

import Dispatch
import Logging
import Metrics

// MARK: - LifecycleTask

Expand Down Expand Up @@ -473,9 +473,12 @@ public class ComponentLifecycle: LifecycleTask {
guard case .idle = self.state else {
preconditionFailure("invalid state, \(self.state)")
}
self.log("starting")
self.state = .starting(queue)
}

self.log("starting")
Counter(label: "\(self.label).lifecycle.start").increment()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is label risky i.e. containing spaces etc?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm good question, do you think we should normalize it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was just thinking about it but I also just remembered that last time we said that the libs should sanitize, so we do e.g. in the prometheus one https://github.com/MrLotU/SwiftPrometheus/blob/f4d4adfeb1178e250a0ea427017fb4d1cc877de3/Sources/Prometheus/PrometheusMetrics.swift#L112 🤔

I guess it's fine 👍


if tasks.count == 0 {
self.log(level: .notice, "no tasks provided")
}
Expand Down Expand Up @@ -517,7 +520,9 @@ public class ComponentLifecycle: LifecycleTask {
return callback(index, nil)
}
self.log("starting tasks [\(tasks[index].label)]")
let startTime = DispatchTime.now()
start { error in
Timer(label: "\(self.label).\(tasks[index].label).lifecycle.start").recordNanoseconds(DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds)
Copy link
Contributor

@ktoso ktoso Mar 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could it be worth making some struct/enum with the labels such that it is easier to look in one place to see "aha, these are all the metric labels this lib exports"?

I do this in some other project, it is easier to know what metrics are exposed then.
Sure not all that much here but it's a nice pattern;

So either some Labels.start(base: self.label) or Metrics.timer(base: self.label) I guess?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have func recordInterval(since: DispatchTime, now: DispatchTime = .now()) { for this type of nanosecond recording, consider using it

Copy link
Contributor Author

@tomerd tomerd Mar 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

recordInterval is not define in the core library afaict, where did you see it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see but it's not in CoreMetrics hm

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah yes... I prefer not to introduce dependency on Foundation for low level libs if we can get away with it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah though this could live in core I guess, I'll ticketify -- it's just Dispatch dep, not foundation hm

if let error = error {
self.log(level: .error, "failed to start [\(tasks[index].label)]: \(error)")
return callback(index, error)
Expand All @@ -532,9 +537,12 @@ public class ComponentLifecycle: LifecycleTask {

private func _shutdown(on queue: DispatchQueue, tasks: [LifecycleTask], callback: @escaping () -> Void) {
self.stateLock.withLock {
log("shutting down")
self.state = .shuttingDown(queue)
}

self.log("shutting down")
Counter(label: "\(self.label).lifecycle.shutdown").increment()

self.shutdownTask(on: queue, tasks: tasks.reversed(), index: 0, errors: nil) { errors in
self.stateLock.withLock {
guard case .shuttingDown = self.state else {
Expand All @@ -555,8 +563,11 @@ public class ComponentLifecycle: LifecycleTask {
if index >= tasks.count {
return callback(errors)
}

self.log("stopping tasks [\(tasks[index].label)]")
let startTime = DispatchTime.now()
shutdown { error in
Timer(label: "\(self.label).\(tasks[index].label).lifecycle.shutdown").recordNanoseconds(DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using recordinternal(since: startTime)

var errors = errors
if let error = error {
if errors == nil {
Expand Down
1 change: 1 addition & 0 deletions Tests/LifecycleTests/ComponentLifecycleTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ extension ComponentLifecycleTests {
("testStatefulNIO", testStatefulNIO),
("testStatefulNIOStartFailure", testStatefulNIOStartFailure),
("testStatefulNIOShutdownFailure", testStatefulNIOShutdownFailure),
("testMetrics", testMetrics),
]
}
}
108 changes: 108 additions & 0 deletions Tests/LifecycleTests/ComponentLifecycleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

@testable import Lifecycle
import LifecycleNIOCompat
import Metrics
import NIO
import XCTest

Expand Down Expand Up @@ -1247,4 +1248,111 @@ final class ComponentLifecycleTests: XCTestCase {

XCTAssertFalse(item.shutdown, "expected item to be shutdown")
}

func testMetrics() {
let metrics = TestMetrics()
MetricsSystem.bootstrap(metrics)

let items = (0 ..< 3).map { _ in GoodItem(id: UUID().uuidString, startDelay: 0.1, shutdownDelay: 0.1) }
let lifecycle = ComponentLifecycle(label: "test")
lifecycle.register(items)
lifecycle.start { startError in
XCTAssertNil(startError, "not expecting error")
lifecycle.shutdown { shutdownErrors in
XCTAssertNil(shutdownErrors, "not expecting error")
}
}
lifecycle.wait()
XCTAssertEqual(metrics.counters["\(lifecycle.label).lifecycle.start"]?.value, 1, "expected start counter to be 1")
XCTAssertEqual(metrics.counters["\(lifecycle.label).lifecycle.shutdown"]?.value, 1, "expected shutdown counter to be 1")
items.forEach { XCTAssertGreaterThan(metrics.timers["\(lifecycle.label).\($0.label).lifecycle.start"]?.value ?? 0, 0, "expected start timer to be non-zero") }
items.forEach { XCTAssertGreaterThan(metrics.timers["\(lifecycle.label).\($0.label).lifecycle.shutdown"]?.value ?? 0, 0, "expected shutdown timer to be non-zero") }
}
}

class TestMetrics: MetricsFactory, RecorderHandler {
var counters = [String: TestCounter]()
var timers = [String: TestTimer]()
let lock = Lock()

public init() {}

public func makeCounter(label: String, dimensions: [(String, String)]) -> CounterHandler {
let counter = TestCounter(label: label)
self.lock.withLock {
self.counters[label] = counter
}
return counter
}

public func makeRecorder(label: String, dimensions: [(String, String)], aggregate: Bool) -> RecorderHandler {
return self
}

public func makeTimer(label: String, dimensions: [(String, String)]) -> TimerHandler {
let timer = TestTimer(label: label)
self.lock.withLock {
self.timers[label] = timer
}
return timer
}

public func destroyCounter(_: CounterHandler) {}
public func destroyRecorder(_: RecorderHandler) {}
public func destroyTimer(_: TimerHandler) {}

public func record(_: Int64) {}
public func record(_: Double) {}

class TestCounter: CounterHandler {
let label: String
var _value: Int64
let lock = Lock()

init(label: String) {
self.label = label
self._value = 0
}

public func increment(by: Int64) {
self.lock.withLock {
self._value += by
}
}

public func reset() {
self.lock.withLock {
self._value = 0
}
}

public var value: Int64 {
return self.lock.withLock {
return self._value
}
}
}

class TestTimer: TimerHandler {
let label: String
var _value: Int64
let lock = Lock()

init(label: String) {
self.label = label
self._value = 0
}

public func recordNanoseconds(_ value: Int64) {
self.lock.withLock {
self._value = value
}
}

public var value: Int64 {
return self.lock.withLock {
return self._value
}
}
}
}