feat: Adds MQTTConnectionServiceTests

This commit is contained in:
2024-11-09 10:30:25 -05:00
parent 6c5115dcde
commit e2683d3f06
3 changed files with 46 additions and 23 deletions

View File

@@ -9,7 +9,7 @@ public actor MQTTConnectionService: Service {
private let cleanSession: Bool
public let client: MQTTClient
private var shuttingDown = false
var logger: Logger { client.logger }
nonisolated var logger: Logger { client.logger }
public init(
cleanSession: Bool = true,
@@ -25,32 +25,52 @@ public actor MQTTConnectionService: Service {
/// It will attempt to gracefully shutdown the connection upon receiving
/// `sigterm` signals.
public func run() async throws {
await withGracefulShutdownHandler {
await self.connect()
} onGracefulShutdown: {
Task { await self.shutdown() }
await withDiscardingTaskGroup { group in
await withGracefulShutdownHandler {
group.addTask { await self.connect() }
} onGracefulShutdown: {
// try? self.client.syncShutdownGracefully()
Task { await self.shutdown() }
}
}
}
private func shutdown() async {
func shutdown() async {
shuttingDown = true
try? await client.disconnect()
try? await client.shutdown()
}
private func connect() async {
func connect() async {
do {
try await client.connect(cleanSession: cleanSession)
client.addCloseListener(named: "SensorsClient") { [self] _ in
Task {
self.logger.debug("Connection closed.")
self.logger.debug("Reconnecting...")
await self.connect()
try await withThrowingDiscardingTaskGroup { group in
group.addTask {
try await self.client.connect(cleanSession: self.cleanSession)
}
client.addCloseListener(named: "SensorsClient") { [self] _ in
Task {
self.logger.debug("Connection closed.")
self.logger.debug("Reconnecting...")
await self.connect()
}
}
self.logger.debug("Connection successful.")
}
logger.debug("Connection successful.")
} catch {
logger.trace("Connection Failed.\n\(error)")
logger.trace("Failed to connect.")
}
// do {
// try await client.connect(cleanSession: cleanSession)
// client.addCloseListener(named: "SensorsClient") { [self] _ in
// Task {
// self.logger.debug("Connection closed.")
// self.logger.debug("Reconnecting...")
// await self.connect()
// }
// }
// logger.debug("Connection successful.")
// } catch {
// logger.trace("Connection Failed.\(error)")
// }
}
}