Repository Public
1import Foundation2import Testing3@testable import MCCCore45@Suite("Event stream")6struct EventStreamTests {7 static func nodeState(_ alias: String, freshness: String = "fresh") -> String {8 #"{"node_id":"\#(Fixture.nodeID)","alias":"\#(alias)","freshness":"\#(freshness)","maintenance":false,"observed_at":"2026-11-18T21:00:00.5Z","headline":{"cpu_usage_pct":12.5}}"#9 }1011 private func makeStream(_ server: StubServer, store: InMemorySecureStore? = nil, heartbeat: TimeInterval = 30) -> (EventStream, APIClient) {12 let api = makeAPI(server, store: store ?? Fixture.signedInStore(for: server))13 var config = EventStream.Configuration()14 config.heartbeatTimeout = heartbeat15 config.backoff = Backoff(base: 0.05, cap: 0.2)16 return (EventStream(api: api, configuration: config, protocolClasses: server.protocolClasses), api)17 }1819 /// Collects envelopes in the background.20 private func collect(_ stream: EventStream) async -> Box<[EventEnvelope]> {21 let box = Box<[EventEnvelope]>([])22 let events = await stream.events()23 Task { for await e in events { box.update { $0.append(e) } } }24 return box25 }2627 @Test("SSE parser: fields, multi-line data, comments, CRLF, incomplete frames")28 func parser() {29 var p = SSEParser()30 #expect(p.feed(Array("retry: 3000\nevent: hello\ndata: {\"head\":4}\n\n".utf8)) == [SSEMessage(id: nil, event: "hello", data: "{\"head\":4}", retryMilliseconds: 3000)])31 #expect(p.feed(Array(": ping\n\n".utf8)).isEmpty)32 #expect(p.commentCount == 1)33 #expect(p.feed(Array("id: 5\r\nevent: node.state\r\ndata: a\r\ndata: b\r\n\r\n".utf8)) == [SSEMessage(id: "5", event: "node.state", data: "a\nb", retryMilliseconds: nil)])34 // A frame split across network chunks is delivered once, when complete.35 #expect(p.feed(Array("id: 6\nevent: job.cha".utf8)).isEmpty)36 #expect(p.feed(Array("nged\ndata:{}\n".utf8)).isEmpty)37 #expect(p.feed(Array("\n".utf8)) == [SSEMessage(id: "6", event: "job.changed", data: "{}", retryMilliseconds: nil)])38 #expect(p.feed(Array("data: no event name\n\n".utf8)).first?.event == "message")39 #expect(p.feed(Array("\n\n\n".utf8)).isEmpty)40 #expect(p.feed(Array("unknown: x\n\n".utf8)).isEmpty)41 }4243 @Test("typed decoding of every topic; unknown topics and bad payloads are reported, never guessed")44 func typedDecoding() {45 if case .nodeState(let e) = ServerEvent.decode(topic: "node.state", data: Self.nodeState("M4M64a", freshness: "stale")) {46 #expect(e.alias == "M4M64a" && e.freshness == .stale && e.headline?.cpuUsagePct == 12.5 && e.observedAt != nil)47 } else { Issue.record("node.state") }48 let samples: [(String, String)] = [49 ("node.updated", #"{"node_id":"\#(Fixture.nodeID)","change":"inventory"}"#),50 ("alert.changed", #"{"alert_id":"\#(Fixture.nodeID)","rule_id":"\#(Fixture.nodeID)","state":"firing","severity":"critical","summary":"Disk almost full"}"#),51 ("incident.changed", #"{"incident_id":"\#(Fixture.nodeID)","state":"open","severity":"warning","title":"x"}"#),52 ("action.changed", #"{"action_id":"\#(Fixture.nodeID)","type":"service.restart","state":"running","target":{"kind":"service","id":"\#(Fixture.nodeID)"},"outcome_unknown":false}"#),53 ("action.output", #"{"action_id":"\#(Fixture.nodeID)","event_id":3,"ts":"2026-11-18T21:00:00Z","stream":"stdout","data":"line\n"}"#),54 ("service.changed", #"{"service_id":"\#(Fixture.nodeID)","node_id":"\#(Fixture.nodeID)","manager":"pm2","name":"web","state":"errored","previous_state":"online"}"#),55 ("job.changed", #"{"job_id":"\#(Fixture.nodeID)","template":"t","state":"running","progress":0.4}"#),56 ("maintenance.changed", #"{"change":"note_created","note_id":"\#(Fixture.nodeID)"}"#),57 ("audit.appended", #"{"seq":12,"ts":"2026-11-18T21:00:00Z","action":"session.login","actor_label":"spb","outcome":"success"}"#),58 ]59 for (topic, data) in samples {60 let e = ServerEvent.decode(topic: topic, data: data)61 #expect(e.topic == topic)62 if case .unknown = e { Issue.record("\(topic) did not decode") }63 }64 #expect(ServerEvent.decode(topic: "resync", data: "{}") == .resync)65 #expect(ServerEvent.decode(topic: "model.changed", data: "{}") == .unknown(topic: "model.changed"))66 #expect(ServerEvent.decode(topic: "node.state", data: #"{"alias":1}"#) == .unknown(topic: "node.state"))67 }6869 @Test("reconnection resumes with Last-Event-ID: nothing lost, nothing delivered twice")70 func resumeWithoutLossOrDuplicate() async throws {71 let server = StubServer()72 let connection = Box(0)73 server.handle { r in74 guard r.path == "/api/v1/events" else { return .http(status: 404) }75 let n = connection.update { $0 += 1; return $0 }76 if n == 1 {77 return .stream(chunks: [(0, Data("retry: 3000\nevent: hello\ndata: {\"head\":0}\n\n".utf8)),78 (0.02, sse(id: 1, event: "node.state", data: Self.nodeState("a"))),79 (0.02, sse(id: 2, event: "node.state", data: Self.nodeState("b")))], close: true)80 }81 // The server replays from the position it is given; a sloppy server (or a race) may resend the last one.82 return .stream(chunks: [(0, Data("event: hello\ndata: {\"head\":4}\n\n".utf8)),83 (0.02, sse(id: 2, event: "node.state", data: Self.nodeState("b"))),84 (0.02, sse(id: 3, event: "node.state", data: Self.nodeState("c"))),85 (0.02, sse(id: 4, event: "service.changed", data: #"{"service_id":"\#(Fixture.nodeID)","node_id":"\#(Fixture.nodeID)","manager":"pm2","name":"web","state":"online"}"#))])86 }87 let (stream, _) = makeStream(server)88 let received = await collect(stream)89 await stream.start()90 #expect(await eventually { received.value.count == 4 })91 try await Task.sleep(for: .milliseconds(150))92 #expect(received.value.map(\.id) == [1, 2, 3, 4])93 #expect(await stream.lastEventID == 4)94 let requests = server.requests("GET", "/api/v1/events")95 #expect(requests.count >= 2)96 #expect(requests[0].header("Last-Event-ID") == nil)97 #expect(requests[1].header("Last-Event-ID") == "2")98 #expect(requests.allSatisfy { $0.header("Authorization") == "Bearer access-1" && $0.header("Accept") == "text/event-stream" })99 await stream.stop()100 }101102 @Test("resync is forwarded and repositions the stream")103 func resync() async throws {104 let server = StubServer()105 server.handle { r in106 guard r.path == "/api/v1/events" else { return .http(status: 404) }107 return .stream(chunks: [(0, Data("id: 50\nevent: resync\ndata: {}\n\n".utf8)), (0.02, sse(id: 51, event: "node.state", data: Self.nodeState("a")))])108 }109 let (stream, _) = makeStream(server)110 let received = await collect(stream)111 await stream.start()112 #expect(await eventually { received.value.count == 2 })113 #expect(received.value.first == EventEnvelope(id: 50, event: .resync))114 #expect(received.value.last?.id == 51)115 await stream.stop()116 #expect(await stream.lastEventID == nil) // stop forgets the position (sign-out)117 }118119 @Test("a silent connection (no heartbeat) is dropped and re-established")120 func heartbeatTimeout() async throws {121 let server = StubServer()122 server.handle { r in123 r.path == "/api/v1/events" ? .stream(chunks: [(0, Data("event: hello\ndata: {}\n\n".utf8))]) : .http(status: 404)124 }125 let (stream, _) = makeStream(server, heartbeat: 0.4)126 let states = Box<[StreamState]>([])127 let stateStream = await stream.states()128 Task { for await s in stateStream { states.update { $0.append(s) } } }129 await stream.start()130 #expect(await eventually(timeout: 4) { await stream.connectionCount >= 2 })131 #expect(states.value.contains { if case .reconnecting(_, _, let code) = $0 { return code == APIError.codeTimeout }; return false })132 #expect(states.value.contains { $0.isConnected })133 await stream.stop()134 }135136 @Test("pings keep a quiet connection alive")137 func pingsKeepAlive() async throws {138 let server = StubServer()139 server.handle { r in140 r.path == "/api/v1/events"141 ? .stream(chunks: [(0, Data("event: hello\ndata: {}\n\n".utf8))] + (0..<20).map { _ in (0.2, Data(": ping\n\n".utf8)) })142 : .http(status: 404)143 }144 // Silence would be declared after 1.5 s; the pings arrive every 0.2 s for 4 s (wide margins: loaded machines).145 let (stream, _) = makeStream(server, heartbeat: 1.5)146 await stream.start()147 try await Task.sleep(for: .seconds(3))148 #expect(await stream.connectionCount == 1)149 #expect(await stream.currentState.isConnected)150 await stream.stop()151 }152153 @Test("401 on the stream triggers the shared refresh, then reconnects with the new token")154 func refreshOnUnauthorized() async throws {155 let server = StubServer()156 server.handle { r in157 switch r.path {158 case "/api/v1/auth/refresh": return .json(200, Fixture.tokenPair(access: "access-2", refresh: "refresh-2"))159 case "/api/v1/events":160 return r.header("Authorization") == "Bearer access-2"161 ? .stream(chunks: [(0, sse(id: 1, event: "node.state", data: Self.nodeState("a")))])162 : .error(401, code: "session_expired")163 default: return .http(status: 404)164 }165 }166 let (stream, api) = makeStream(server)167 let received = await collect(stream)168 await stream.start()169 #expect(await eventually { received.value.count == 1 })170 #expect(await api.tokens.refreshRequestCount == 1)171 await stream.stop()172 }173174 @Test("a rejected refresh stops the stream for good")175 func stopsWhenSignedOut() async throws {176 let server = StubServer()177 server.handle { r in r.path == "/api/v1/auth/refresh" ? .error(401, code: "refresh_rejected") : .error(401, code: "unauthenticated") }178 let (stream, api) = makeStream(server)179 await stream.start()180 #expect(await eventually { await stream.currentState == .stopped })181 try await Task.sleep(for: .milliseconds(300))182 #expect(server.requests("GET", "/api/v1/events").count == 1) // no reconnection loop183 #expect(await api.tokens.hasSession == false)184 }185186 @Test("pause keeps the position, resume continues from it; server errors back off and recover")187 func pauseResumeAndBackoff() async throws {188 let server = StubServer()189 let connection = Box(0)190 server.handle { r in191 guard r.path == "/api/v1/events" else { return .http(status: 404) }192 let n = connection.update { $0 += 1; return $0 }193 switch n {194 case 1: return .stream(chunks: [(0, sse(id: 7, event: "node.state", data: Self.nodeState("a")))])195 case 2: return .error(503, code: "unavailable")196 case 3: return .failure(.networkConnectionLost)197 default: return .stream(chunks: [(0, sse(id: 8, event: "node.state", data: Self.nodeState("b")))])198 }199 }200 let (stream, api) = makeStream(server)201 let received = await collect(stream)202 await stream.start()203 #expect(await eventually { received.value.count == 1 })204 await stream.pause()205 #expect(await stream.currentState == .paused)206 #expect(await stream.lastEventID == 7)207 try await Task.sleep(for: .milliseconds(100))208 #expect(connection.value == 1) // paused: no reconnection209 await stream.resume()210 #expect(await eventually { received.value.count == 2 })211 #expect(received.value.map(\.id) == [7, 8])212 let requests = server.requests("GET", "/api/v1/events")213 #expect(requests.count == 4)214 #expect(requests.dropFirst().allSatisfy { $0.header("Last-Event-ID") == "7" })215 #expect(!api.connectivity.isOffline) // back online once connected216 await stream.stop()217 }218}219