import Dependencies import Logging import Models import MQTTManager import ServiceLifecycle public struct MQTTConnectionService: Service { private let logger: Logger? public init( logger: Logger? = nil ) { var logger = logger logger?[metadataKey: "type"] = "mqtt-connection-service" self.logger = logger } /// The entry-point of the service which starts the connection /// to the MQTT broker and handles graceful shutdown of the /// connection. public func run() async throws { @Dependency(\.mqtt) var mqtt try await mqtt.connect() try await withGracefulShutdownHandler { for await event in try mqtt.connectionStream().cancelOnGracefulShutdown() { // We don't really need to do anything with the events, so just logging // for now. But we need to iterate on an async stream for the service to // continue to run and handle graceful shutdowns. logger?.trace("Received connection event: \(event)") } } onGracefulShutdown: { self.logger?.trace("Received graceful shutdown.") mqtt.shutdown() } } }