Log more metrics

This commit is contained in:
Christoph Hagen 2023-02-06 21:57:42 +01:00
parent b3c58ce4c7
commit e96b85b1cc

View File

@ -1,6 +1,7 @@
import Foundation
import WebSocketKit
import Vapor
import Clairvoyant
final class DeviceManager {
@ -20,6 +21,10 @@ final class DeviceManager {
private let deviceTimeout: Int64
private let deviceConnectedMetric: Metric<Bool>
private let messagesToDeviceMetric: Metric<Int>
/// Indicator for device availability
var deviceIsConnected: Bool {
deviceIsAuthenticated && !(connection?.isClosed ?? true)
@ -32,6 +37,23 @@ final class DeviceManager {
self.deviceKey = deviceKey
self.remoteKey = remoteKey
self.deviceTimeout = deviceTimeout
self.deviceConnectedMetric = .init(
"sesame.connected",
name: "Device connected",
description: "Shows if the device is connected via WebSocket")
self.messagesToDeviceMetric = .init(
"sesame.messages",
name: "Forwarded Messages",
description: "The number of messages transmitted to the device")
}
private func updateDeviceConnectionMetric() {
deviceConnectedMetric.update(deviceIsConnected)
}
private func updateMessageCountMetric() {
let lastValue = messagesToDeviceMetric.lastValue()?.value ?? 0
messagesToDeviceMetric.update(lastValue + 1)
}
// MARK: API
@ -50,6 +72,7 @@ final class DeviceManager {
}
requestInProgress = eventLoop.makePromise(of: DeviceResponse.self)
socket.send(message.bytes, promise: nil)
updateMessageCountMetric()
eventLoop.scheduleTask(in: .seconds(deviceTimeout)) { [weak self] in
guard let promise = self?.requestInProgress else {
return
@ -61,6 +84,7 @@ final class DeviceManager {
}
func authenticateDevice(hash: String) {
defer { updateDeviceConnectionMetric() }
guard let key = Data(fromHexEncodedString: hash),
SHA256.hash(data: key) == self.deviceKey else {
log("Invalid device key")
@ -86,6 +110,7 @@ final class DeviceManager {
}
func didCloseDeviceSocket() {
defer { updateDeviceConnectionMetric() }
guard !isOpeningNewConnection else {
return
}
@ -99,6 +124,7 @@ final class DeviceManager {
}
func removeDeviceConnection() {
defer { updateDeviceConnectionMetric() }
deviceIsAuthenticated = false
guard let socket = connection else {
return
@ -109,6 +135,7 @@ final class DeviceManager {
}
func createNewDeviceConnection(_ socket: WebSocket) {
defer { updateDeviceConnectionMetric() }
isOpeningNewConnection = true
removeDeviceConnection()
connection = socket