Attempt socket bugfix

This commit is contained in:
Christoph Hagen 2023-11-10 15:01:37 +01:00
parent 9f20563877
commit 1369a621ad
2 changed files with 16 additions and 22 deletions

View File

@ -35,8 +35,6 @@ final class DeviceManager {
private let messagesToDeviceMetric: Metric<Int>
private let scheduler: AsyncScheduler
var deviceState: DeviceState {
guard let connection, !connection.isClosed else {
return .disconnected
@ -55,22 +53,21 @@ final class DeviceManager {
/// A promise to finish the request once the device responds or times out
private var requestInProgress: CheckedContinuation<Data, Error>?
init(deviceKey: Data, remoteKey: Data, deviceTimeout: Int64, scheduler: AsyncScheduler) {
init(deviceKey: Data, remoteKey: Data, deviceTimeout: Int64) {
self.deviceKey = deviceKey
self.remoteKey = remoteKey
self.deviceTimeout = deviceTimeout
self.deviceStateMetric = .init(
"sesame.device",
name: "Device connected",
description: "Shows if the device is connected via WebSocket")
name: "Device status",
description: "Shows if the device is connected and authenticated via WebSocket")
self.messagesToDeviceMetric = .init(
"sesame.messages",
name: "Forwarded Messages",
description: "The number of messages transmitted to the device")
self.scheduler = scheduler
}
private func updateDeviceConnectionMetric() async {
func updateDeviceConnectionMetric() async {
_ = try? await deviceStateMetric.update(deviceState)
}
@ -166,18 +163,18 @@ final class DeviceManager {
func createNewDeviceConnection(_ socket: WebSocket) async {
await removeDeviceConnection()
socket.eventLoop.execute {
socket.onBinary { [weak self] _, data in
self?.processDeviceResponse(data)
}
socket.onText { [weak self] _, text async in
await self?.authenticateDevice(hash: text)
}
socket.onBinary { [weak self] _, data in
self?.processDeviceResponse(data)
_ = socket.onClose.always { [weak self] _ in
self?.didCloseDeviceSocket()
}
}
socket.onText { [weak self] _, text async in
await self?.authenticateDevice(hash: text)
}
_ = socket.onClose.always { [weak self] _ in
self?.didCloseDeviceSocket()
}
connection = socket
await updateDeviceConnectionMetric()
}

View File

@ -35,11 +35,7 @@ public func configure(_ app: Application) throws {
let keyFile = storageFolder.appendingPathComponent(config.keyFileName)
let (deviceKey, remoteKey) = try loadKeys(at: keyFile)
deviceManager = DeviceManager(
deviceKey: deviceKey,
remoteKey: remoteKey,
deviceTimeout: config.deviceTimeout,
scheduler: asyncScheduler)
deviceManager = DeviceManager(deviceKey: deviceKey, remoteKey: remoteKey, deviceTimeout: config.deviceTimeout)
try routes(app)
@ -49,6 +45,7 @@ public func configure(_ app: Application) throws {
asyncScheduler.schedule {
_ = try await status.update(.nominal)
await deviceManager.updateDeviceConnectionMetric()
}
let df = DateFormatter()