From e96b85b1cca675860bf279082157d421b2f2c4ae Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Mon, 6 Feb 2023 21:57:42 +0100 Subject: [PATCH] Log more metrics --- Sources/App/DeviceManager.swift | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Sources/App/DeviceManager.swift b/Sources/App/DeviceManager.swift index fab03ad..f4cc5a0 100644 --- a/Sources/App/DeviceManager.swift +++ b/Sources/App/DeviceManager.swift @@ -1,6 +1,7 @@ import Foundation import WebSocketKit import Vapor +import Clairvoyant final class DeviceManager { @@ -19,6 +20,10 @@ final class DeviceManager { private var isOpeningNewConnection = false private let deviceTimeout: Int64 + + private let deviceConnectedMetric: Metric + + private let messagesToDeviceMetric: Metric /// Indicator for device availability var deviceIsConnected: Bool { @@ -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