SPB Git

Repository Public

EventsIntegrationTests.swift 9.1 KB 146 lines swift

1import Foundation2import Testing3@testable import MCCCore45extension Integration {6@Suite("events and live endpoints")7struct EventsIntegrationTests {8    private func nodeState(_ alias: String) -> String {9        #"{"node_id":"0199aaaa-0000-7000-8000-0000000000d1","alias":"\#(alias)","freshness":"fresh","maintenance":false}"#10    }1112    @Test("SSE against the real server: events inserted while disconnected are delivered once, in order; then resync")13    func resumeAndResync() async throws {14        let seat = try await IT.sharedOwner.seat()15        let stream = EventStream(api: seat.api)16        let received = Box<[EventEnvelope]>([])17        let events = await stream.events()18        let collector = Task { for await e in events { received.update { $0.append(e) } } }19        defer { collector.cancel() }20        await stream.start()21        #expect(await eventually(timeout: 10) { await stream.currentState.isConnected })22        try await Task.sleep(for: .milliseconds(300))2324        try IT.publish(topic: "node.state", payload: nodeState("live-1"))25        #expect(await eventually(timeout: 10) { received.value.count == 1 })26        let firstID = try #require(received.value.first?.id)2728        // Disconnected: three events are committed meanwhile.29        await stream.pause()30        try await Task.sleep(for: .milliseconds(200))31        for alias in ["missed-1", "missed-2", "missed-3"] { try IT.publish(topic: "node.state", payload: nodeState(alias)) }32        try await Task.sleep(for: .milliseconds(300))33        #expect(received.value.count == 1)34        await stream.resume()35        #expect(await eventually(timeout: 10) { received.value.count == 4 })36        try await Task.sleep(for: .milliseconds(500))37        let all = received.value38        #expect(all.count == 4)                                                    // no duplicate39        #expect(all.map(\.id) == all.map(\.id).sorted() && Set(all.map(\.id)).count == 4)40        #expect(all.map(\.id) == [firstID, firstID + 1, firstID + 2, firstID + 3]) // no loss41        let aliases = all.compactMap { e -> String? in if case .nodeState(let n) = e.event { return n.alias }; return nil }42        #expect(aliases == ["live-1", "missed-1", "missed-2", "missed-3"])43        #expect(await stream.connectionCount == 2)4445        // The position is no longer retained (pruned): the server answers resync and the client repositions.46        await stream.pause()47        for alias in ["pruned-1", "pruned-2"] { try IT.publish(topic: "node.state", payload: nodeState(alias)) }48        let head = try #require(Int64(try IT.psql("select max(seq) from events_outbox")))49        try IT.psql("delete from events_outbox where seq <= \(head)")50        try IT.psql("insert into settings(key, value) values ('events.pruned', jsonb_build_object('pruned_through', \(head)::bigint)) on conflict (key) do update set value = excluded.value")51        try IT.publish(topic: "node.state", payload: nodeState("after-prune"))52        await stream.resume()53        #expect(await eventually(timeout: 10) { received.value.count >= 5 })54        #expect(received.value[4].event == .resync)55        #expect(received.value[4].id == head + 1)56        // After the resync the stream is live again.57        try IT.publish(topic: "node.state", payload: nodeState("after-resync"))58        #expect(await eventually(timeout: 10) { received.value.count >= 6 })59        if case .nodeState(let n) = received.value[5].event { #expect(n.alias == "after-resync") } else { Issue.record("expected a live event") }60        await stream.stop()61    }6263    @Test("the stream of a signed-out client is refused; health and version are public")64    func publicEndpoints() async throws {65        let anon = IT.seat()66        let live = try await IT.patiently { try await anon.api.call { try await $0.getLiveness().ok.body.json } }67        #expect(live.status == .ok)68        let version = try await IT.patiently { try await anon.api.call { try await $0.getVersion().ok.body.json } }69        #expect(!version.version.isEmpty && !version.apiVersion.isEmpty)70        do { _ = try await anon.api.call { try await $0.getMe().ok.body.json }; Issue.record("must be 401") } catch {71            let e = APIError.from(error)72            #expect(e.status == 401 && e.correlationID != nil)73        }74    }7576    /// Calls every parameterless read of the contract as the owner and reports what is live. An endpoint is either77    /// implemented (and then its payload must decode with the generated types — a contract check) or it answers an78    /// explicit 501/503, which the client maps to an "unavailable" state. Anything else fails the test.79    @Test("live probe of the read endpoints: implemented ones decode, the others are explicit 501/503")80    func liveProbe() async throws {81        let seat = try await IT.sharedOwner.seat()82        let api = seat.api83        let now = Date()84        let probes: [(String, @Sendable (Client) async throws -> Void)] = [85            ("getMe", { _ = try await $0.getMe().ok.body.json }),86            ("listMyPasskeys", { _ = try await $0.listMyPasskeys().ok.body.json }),87            ("listMySessions", { _ = try await $0.listMySessions().ok.body.json }),88            ("listMyDevices", { _ = try await $0.listMyDevices().ok.body.json }),89            ("getPermissionCatalog", { _ = try await $0.getPermissionCatalog().ok.body.json }),90            ("listInvitations", { _ = try await $0.listInvitations().ok.body.json }),91            ("listUsers", { _ = try await $0.listUsers().ok.body.json }),92            ("listPolicyGrants", { _ = try await $0.listPolicyGrants().ok.body.json }),93            ("listAgents", { _ = try await $0.listAgents().ok.body.json }),94            ("listEnrollmentTokens", { _ = try await $0.listEnrollmentTokens().ok.body.json }),95            ("listSettings", { _ = try await $0.listSettings().ok.body.json }),96            ("getAdminStatus", { _ = try await $0.getAdminStatus().ok.body.json }),97            ("getClusterOverview", { _ = try await $0.getClusterOverview().ok.body.json }),98            ("getClusterTrends", { _ = try await $0.getClusterTrends(query: .init(metric: "cpu.usage", range: ._1h)).ok.body.json }),99            ("listNodes", { _ = try await $0.listNodes().ok.body.json }),100            ("getMetricCatalog", { _ = try await $0.getMetricCatalog().ok.body.json }),101            ("listServices", { _ = try await $0.listServices().ok.body.json }),102            ("listInferenceServers", { _ = try await $0.listInferenceServers().ok.body.json }),103            ("listJobTemplates", { _ = try await $0.listJobTemplates().ok.body.json }),104            ("listJobs", { _ = try await $0.listJobs().ok.body.json }),105            ("listJobSchedules", { _ = try await $0.listJobSchedules().ok.body.json }),106            ("listAlerts", { _ = try await $0.listAlerts().ok.body.json }),107            ("listAlertRules", { _ = try await $0.listAlertRules().ok.body.json }),108            ("listSilences", { _ = try await $0.listSilences().ok.body.json }),109            ("listIncidents", { _ = try await $0.listIncidents().ok.body.json }),110            ("listMaintenanceWindows", { _ = try await $0.listMaintenanceWindows(query: .init(from: now.addingTimeInterval(-86_400), to: now.addingTimeInterval(30 * 86_400))).ok.body.json }),111            ("listMaintenanceNotes", { _ = try await $0.listMaintenanceNotes().ok.body.json }),112            ("getNetworkTopology", { _ = try await $0.getNetworkTopology().ok.body.json }),113            ("listNetworkInterfaces", { _ = try await $0.listNetworkInterfaces().ok.body.json }),114            ("listVolumes", { _ = try await $0.listVolumes().ok.body.json }),115            ("listNasTargets", { _ = try await $0.listNasTargets().ok.body.json }),116            ("listBackups", { _ = try await $0.listBackups().ok.body.json }),117            ("listActionTypes", { _ = try await $0.listActionTypes().ok.body.json }),118            ("listActions", { _ = try await $0.listActions().ok.body.json }),119            ("listAudit", { _ = try await $0.listAudit().ok.body.json }),120            ("verifyAudit", { _ = try await $0.verifyAudit().ok.body.json }),121            ("listMyDashboards", { _ = try await $0.listMyDashboards().ok.body.json }),122            ("listActivity", { _ = try await $0.listActivity().ok.body.json }),123            ("search", { _ = try await $0.search(query: .init(q: "m4")).ok.body.json }),124        ]125        var live: [String] = [], unavailable: [String] = []126        for (name, probe) in probes {127            do {128                try await api.call(probe)129                live.append(name)130            } catch {131                let e = APIError.from(error)132                if e.isNotImplemented || e.isServiceUnavailable {133                    #expect(e.correlationID != nil, "\(name): the unavailable state must carry a correlation id")134                    unavailable.append("\(name)=\(e.status ?? 0)")135                } else {136                    Issue.record("\(name): unexpected \(e.status.map(String.init) ?? "-") \(e.code): \(e.message.prefix(300))")137                }138            }139        }140        print("LIVE-PROBE live(\(live.count)): \(live.joined(separator: " "))")141        print("LIVE-PROBE unavailable(\(unavailable.count)): \(unavailable.joined(separator: " "))")142        #expect(live.contains("getMe"))143    }144}145}146
Files main
Menu

Theme