Repository Public
1import Foundation2import os34/// A typed event of `GET /api/v1/events`, decoded from the contract's payload schemas.5public enum ServerEvent: Sendable, Hashable {6 case nodeState(API.NodeStateEvent)7 case nodeUpdated(API.NodeUpdatedEvent)8 case alertChanged(API.AlertChangedEvent)9 case incidentChanged(API.IncidentChangedEvent)10 case actionChanged(API.ActionChangedEvent)11 case actionOutput(API.ActionOutputEvent)12 case serviceChanged(API.ServiceChangedEvent)13 case jobChanged(API.JobChangedEvent)14 case maintenanceChanged(API.MaintenanceChangedEvent)15 case auditAppended(API.AuditAppendedEvent)16 /// The server no longer retains the position asked for (or restarted): reload every read model.17 case resync18 /// A topic this client version does not know, or a payload it could not decode: reload to stay correct.19 case unknown(topic: String)2021 public var topic: String {22 switch self {23 case .nodeState: "node.state"24 case .nodeUpdated: "node.updated"25 case .alertChanged: "alert.changed"26 case .incidentChanged: "incident.changed"27 case .actionChanged: "action.changed"28 case .actionOutput: "action.output"29 case .serviceChanged: "service.changed"30 case .jobChanged: "job.changed"31 case .maintenanceChanged: "maintenance.changed"32 case .auditAppended: "audit.appended"33 case .resync: "resync"34 case .unknown(let t): t35 }36 }3738 static func decode(topic: String, data: String) -> ServerEvent {39 let decoder = JSONDecoder()40 decoder.dateDecodingStrategy = .custom { d in41 let s = try d.singleValueContainer().decode(String.self)42 guard let date = FlexibleDateTranscoder.parse(s) else {43 throw DecodingError.dataCorrupted(.init(codingPath: d.codingPath, debugDescription: "bad date-time \(s)"))44 }45 return date46 }47 let bytes = Data(data.utf8)48 func parse<T: Decodable>(_ type: T.Type, _ make: (T) -> ServerEvent) -> ServerEvent {49 (try? decoder.decode(T.self, from: bytes)).map(make) ?? .unknown(topic: topic)50 }51 switch topic {52 case "node.state": return parse(API.NodeStateEvent.self, ServerEvent.nodeState)53 case "node.updated": return parse(API.NodeUpdatedEvent.self, ServerEvent.nodeUpdated)54 case "alert.changed": return parse(API.AlertChangedEvent.self, ServerEvent.alertChanged)55 case "incident.changed": return parse(API.IncidentChangedEvent.self, ServerEvent.incidentChanged)56 case "action.changed": return parse(API.ActionChangedEvent.self, ServerEvent.actionChanged)57 case "action.output": return parse(API.ActionOutputEvent.self, ServerEvent.actionOutput)58 case "service.changed": return parse(API.ServiceChangedEvent.self, ServerEvent.serviceChanged)59 case "job.changed": return parse(API.JobChangedEvent.self, ServerEvent.jobChanged)60 case "maintenance.changed": return parse(API.MaintenanceChangedEvent.self, ServerEvent.maintenanceChanged)61 case "audit.appended": return parse(API.AuditAppendedEvent.self, ServerEvent.auditAppended)62 case "resync": return .resync63 default: return .unknown(topic: topic)64 }65 }66}6768public struct EventEnvelope: Sendable, Hashable {69 /// Sequence of the event in the server's outbox (`id:` of the SSE frame).70 public var id: Int6471 public var event: ServerEvent72}7374public enum StreamState: Sendable, Equatable {75 case idle76 case connecting77 case connected(since: Date)78 /// Waiting before the next attempt. `attempt` counts consecutive failures.79 case reconnecting(attempt: Int, retryAt: Date, lastError: String)80 case paused81 /// The session ended (refresh rejected): the stream will not reconnect.82 case stopped8384 public var isConnected: Bool { if case .connected = self { return true }; return false }85}8687/// SSE client for `/api/v1/events` on `URLSession.bytes`.88///89/// - Resumes with `Last-Event-ID`, so nothing is lost across a reconnection, and drops any event whose id is not90/// greater than the last one delivered, so nothing is delivered twice.91/// - `resync` (position no longer retained) is forwarded: consumers reload their state.92/// - Reconnects with exponential backoff and jitter; a silent connection (no byte, not even the 15 s ping, for93/// `heartbeatTimeout`) is treated as dead.94/// - `pause()` / `resume()` follow the app lifecycle and the network path.95public actor EventStream {96 public struct Configuration: Sendable {97 public var heartbeatTimeout: TimeInterval = 4098 public var backoff = Backoff(base: 0.5, cap: 30)99 /// Topics to subscribe to; nil = everything the session may read.100 public var topics: [String]?101 public init() {}102 }103104 private let url: URL105 private let session: URLSession106 private let tokens: TokenManager107 private let connectivity: Connectivity?108 private let config: Configuration109110 private var runner: Task<Void, Never>?111 private var paused = false112 private var lastID: Int64?113 private var state: StreamState = .idle114 private var eventObservers: [UUID: AsyncStream<EventEnvelope>.Continuation] = [:]115 private var stateObservers: [UUID: AsyncStream<StreamState>.Continuation] = [:]116 private var connections = 0117 private var failures = 0118119 public init(apiURL: URL, session: URLSession? = nil, tokens: TokenManager, connectivity: Connectivity? = nil,120 configuration: Configuration = .init(), protocolClasses: [AnyClass]? = nil) {121 self.url = apiURL.appendingPathComponent("events")122 self.tokens = tokens123 self.connectivity = connectivity124 self.config = configuration125 if let session {126 self.session = session127 } else {128 let c = URLSessionConfiguration.ephemeral129 c.httpCookieAcceptPolicy = .never130 c.httpShouldSetCookies = false131 c.urlCache = nil132 c.timeoutIntervalForRequest = 3600 // the heartbeat watchdog below decides, not URLSession's idle timer133 c.timeoutIntervalForResource = 24 * 3600134 c.waitsForConnectivity = false135 if let protocolClasses { c.protocolClasses = protocolClasses }136 self.session = URLSession(configuration: c)137 }138 }139140 public init(api: APIClient, configuration: Configuration = .init(), protocolClasses: [AnyClass]? = nil) {141 self.init(apiURL: api.apiURL, session: nil, tokens: api.tokens, connectivity: api.connectivity, configuration: configuration,142 protocolClasses: protocolClasses)143 }144145 // MARK: Public surface146147 public var currentState: StreamState { state }148 public var lastEventID: Int64? { lastID }149 /// Number of HTTP connections opened so far (tests).150 public var connectionCount: Int { connections }151152 /// Typed events, in server order, each exactly once.153 public func events() -> AsyncStream<EventEnvelope> {154 AsyncStream(bufferingPolicy: .unbounded) { cont in155 let id = UUID()156 eventObservers[id] = cont157 cont.onTermination = { [weak self] _ in Task { await self?.dropEventObserver(id) } }158 }159 }160161 public func states() -> AsyncStream<StreamState> {162 AsyncStream(bufferingPolicy: .bufferingNewest(16)) { cont in163 let id = UUID()164 stateObservers[id] = cont165 cont.yield(state)166 cont.onTermination = { [weak self] _ in Task { await self?.dropStateObserver(id) } }167 }168 }169170 public func start() {171 paused = false172 guard runner == nil else { return }173 runner = Task { [weak self] in await self?.run() }174 }175176 /// Closes the connection and keeps the position: `resume()` continues from the last event received.177 public func pause() {178 paused = true179 runner?.cancel()180 runner = nil181 setState(.paused)182 }183184 public func resume() {185 guard paused || runner == nil else { return }186 start()187 }188189 /// Drops the connection and reconnects immediately (network path changed).190 public func reconnectNow() {191 guard !paused, runner != nil else { return }192 runner?.cancel()193 runner = Task { [weak self] in await self?.run() }194 }195196 /// Stops for good and forgets the position (sign-out).197 public func stop() {198 runner?.cancel()199 runner = nil200 paused = false201 lastID = nil202 setState(.idle)203 }204205 // MARK: Loop206207 private func run() async {208 failures = 0209 while !Task.isCancelled {210 setState(.connecting)211 do {212 try await connectOnce()213 // The server closed the stream normally (it bounds a stream to 30 min): reconnect right away.214 failures = 0215 try await Task.sleep(for: .milliseconds(200))216 } catch {217 if Task.isCancelled { return }218 let e = APIError.from(error)219 if e.isSignedOut {220 setState(.stopped)221 return222 }223 if e.isTransport { connectivity?.recordTransportFailure() }224 failures += 1225 let attempt = failures226 var delay = config.backoff.delay(attempt: attempt)227 if let ra = e.retryAfter { delay = max(delay, ra) }228 setState(.reconnecting(attempt: attempt, retryAt: Date().addingTimeInterval(delay), lastError: e.code))229 do { try await Task.sleep(for: .seconds(delay)) } catch { return }230 }231 }232 }233234 private struct HeartbeatTimeout: Error {}235236 private func connectOnce() async throws {237 guard let token = try await tokens.accessToken() else { throw APIError.signedOut }238 var comps = URLComponents(url: url, resolvingAgainstBaseURL: false)!239 if let topics = config.topics, !topics.isEmpty {240 comps.queryItems = [URLQueryItem(name: "topics", value: topics.joined(separator: ","))]241 }242 var request = URLRequest(url: comps.url!)243 request.setValue("text/event-stream", forHTTPHeaderField: "Accept")244 request.setValue("no-store", forHTTPHeaderField: "Cache-Control")245 request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")246 if let lastID { request.setValue(String(lastID), forHTTPHeaderField: "Last-Event-ID") }247248 connections += 1249 let (bytes, response) = try await session.bytes(for: request)250 let http = response as! HTTPURLResponse251 if http.statusCode == 401 {252 // Expired or revoked access token: one shared refresh, then the loop reconnects without backoff.253 _ = try await tokens.refreshAfterRejection(of: token)254 return255 }256 guard http.statusCode == 200 else {257 var data = Data()258 for try await b in bytes.prefix(1 << 16) { data.append(b) }259 var fields = HTTPFieldsBox()260 fields.correlation = http.value(forHTTPHeaderField: "X-Correlation-Id")261 fields.retryAfter = http.value(forHTTPHeaderField: "Retry-After")262 throw fields.error(status: http.statusCode, body: data)263 }264 connectivity?.recordResponse()265 failures = 0266 setState(.connected(since: Date()))267268 let lastByte = OSAllocatedUnfairLock(initialState: Date())269 let timeout = config.heartbeatTimeout270 try await withThrowingTaskGroup(of: Void.self) { group in271 group.addTask { [weak self] in272 var parser = SSEParser()273 for try await byte in bytes {274 lastByte.withLock { $0 = Date() }275 if let message = parser.feed(byte) { await self?.handle(message) }276 }277 }278 group.addTask {279 while true {280 try await Task.sleep(for: .seconds(min(5, timeout / 4)))281 let idle = Date().timeIntervalSince(lastByte.withLock { $0 })282 if idle > timeout { throw HeartbeatTimeout() }283 }284 }285 defer { group.cancelAll() }286 do {287 try await group.next()288 } catch is HeartbeatTimeout {289 throw APIError(code: APIError.codeTimeout, message: "No heartbeat from the event stream")290 }291 }292 }293294 private func handle(_ message: SSEMessage) {295 guard message.event != "hello", message.event != "message" else { return }296 guard let idText = message.id, let id = Int64(idText) else { return }297 if message.event == "resync" {298 lastID = id299 emit(EventEnvelope(id: id, event: .resync))300 return301 }302 // Exactly-once delivery: after a reconnection the server replays from Last-Event-ID; anything at or below the303 // last delivered sequence is a duplicate.304 if let last = lastID, id <= last { return }305 lastID = id306 emit(EventEnvelope(id: id, event: ServerEvent.decode(topic: message.event, data: message.data)))307 }308309 private func emit(_ envelope: EventEnvelope) {310 eventObservers.values.forEach { $0.yield(envelope) }311 }312313 private func setState(_ new: StreamState) {314 guard new != state else { return }315 state = new316 stateObservers.values.forEach { $0.yield(new) }317 }318319 private func dropEventObserver(_ id: UUID) { eventObservers[id] = nil }320 private func dropStateObserver(_ id: UUID) { stateObservers[id] = nil }321}322323/// Small helper to reuse the error envelope decoding outside the generated client.324private struct HTTPFieldsBox {325 var correlation: String?326 var retryAfter: String?327 func error(status: Int, body: Data) -> APIError {328 var e = ErrorMappingMiddleware.decode(status: status, headers: .init(), body: body)329 if e.correlationID == nil { e.correlationID = correlation }330 if e.retryAfter == nil { e.retryAfter = retryAfter.flatMap(TimeInterval.init) }331 return e332 }333}334