diff --git a/docs/architecture.md b/docs/architecture.md index f25b841..1d251a4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -46,7 +46,7 @@ SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢 `SystemSampler` actor 持有 CPU、网络、磁盘 IO 差分基线。CPU / 内存每次 Mach 查询取得的 host 发送权在调用结束(含失败路径)释放。卷列表与进程读取放入 utility detached Task;温度、磁盘健康、电池健康独立更新缓存,各类慢任务最多一个在途。慢指标可晚于快照更新,周期详见[监控指标](monitoring.md)。 -进程只在面板可见且未暂停时读取。进程结果可异步单独发布,不必等下一轮资源快照。可见性代次和调度代次阻止过期结果回写;隐藏时清除已发布进程,重新打开重建基线。同步系统调用即使不能及时取消,也会占用原在途槽,避免重叠读取。 +进程只在面板可见且未暂停时读取。进程结果可异步单独发布,不必等下一轮资源快照。可见性代次和调度代次阻止过期结果回写;隐藏时清除已发布进程,重新打开重建基线。同步系统调用即使不能及时取消,也会占用原在途槽,避免重叠读取。进程退出提示以原始成功快照中的完整身份为准,搜索过滤和枚举失败不作为退出证据。 暂停取消采样发布、停用进程更新,保留当前快照和历史;已启动慢读取可能自行结束。恢复时重置 CPU / 网络 / IO 基线,历史标记断点。全局及每接口历史各最多 60 点,接口移除时清理其历史;实际覆盖时长由采样间隔决定。图表按真实时间和缺失值处理间断。GPU 平均统计仅累计有效且连续的时间区间。 @@ -56,10 +56,10 @@ SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢 客户端按包内服务的实际指定签名设置连接要求;服务端要求同 UID,并按所在主应用的实际指定签名校验调用方。温度 / 风扇请求超时 2 秒,SMART 请求超时 15 秒;中断、错误、超时与正常响应统一通过一次性 continuation 完成并关闭连接。 -公网 IP 由 `PublicIPAddressService` 在面板网络任务中访问外部 HTTPS 服务,和本地接口采样分开。保持唤醒通过两个进程级 IOPM 断言阻止用户空闲息屏与系统空闲睡眠,开关不持久化,失败时释放已取得断言,关闭或退出时释放。 +公网 IP 由 `PublicIPAddressService` 在面板网络任务中访问外部 HTTPS 服务,和本地接口采样分开。任务可见时持续刷新:成功缓存 600 秒,失败 30 秒后重试,超时 5 秒;有效期使用单调时间。路由键变化或面板隐藏取消旧任务的请求及等待,取消结果不缓存、不发布。保持唤醒通过两个进程级 IOPM 断言阻止用户空闲息屏与系统空闲睡眠,开关不持久化,失败时释放已取得断言,关闭或退出时释放。 ## 状态与资源 -外观、语言和双采样间隔写入 UserDefaults。图钉、暂停、保持唤醒和进程表交互状态不作为持久化偏好。`AppLanguageScope` 将语言环境注入 AppKit 承载的 SwiftUI 内容,并处理即时刷新;原生菜单文案通过 `AppLocalization` 读取。 +外观、语言和双采样间隔写入 UserDefaults。图钉、暂停、保持唤醒和进程表交互状态不作为持久化偏好。`AppLanguageScope` 将语言环境注入 AppKit 承载的 SwiftUI 内容,并处理即时刷新;原生菜单文案通过 `AppLocalization` 读取;编号风扇等 SwiftUI 文案保留为带参数的 `Text`,由当前应用语言环境解析。 面板和资源卡片使用颜色资产中的不透明背景,顶部操作组使用玻璃效果;不再以全窗口液态玻璃概念图作为实现依据。品牌图标与颜色以 Assets 为运行时来源。 diff --git a/docs/development.md b/docs/development.md index 9fab07f..413b142 100644 --- a/docs/development.md +++ b/docs/development.md @@ -9,7 +9,7 @@ open kymo.xcodeproj xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build ``` -工程有 `kymo` 应用和 `SMARTService` XPC 两个 Target。应用依赖并嵌入 XPC,应用 Info.plist 由构建系统生成,服务使用 `SMARTService/Info.plist`。主应用启用沙盒;工程中未显式配置出站网络 entitlement,公网 IP 的实际可达性需在签名沙盒应用中核对。服务的安全边界见[架构](architecture.md)。 +工程有 `kymo` 应用和 `SMARTService` XPC 两个 Target。应用依赖并嵌入 XPC,应用 Info.plist 由构建系统生成,服务使用 `SMARTService/Info.plist`。主应用启用沙盒,并在 Debug / Release 显式启用出站网络客户端权限(`ENABLE_OUTGOING_NETWORK_CONNECTIONS`);统一检查入口核对实际签名 entitlement,`--network` 额外验证隔离签名沙盒包访问公网端点。服务的安全边界见[架构](architecture.md)。 `kymo/` 使用文件系统同步组,新增源码自动纳入应用 Target。非源码文件必须配置成员例外;已有模块 README 与占位文件已列入例外。XPC 源码和共享文件由工程显式列举,修改共享协议 / 模型时检查服务 Target 是否包含所需文件。 diff --git a/docs/monitoring.md b/docs/monitoring.md index 07d8983..24a0625 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -42,7 +42,7 @@ | CPU / GPU 温度、风扇 | 读取结束后至少 5 秒再试;三类全部不可用时至少 60 秒 | | 卷列表 | 读取结束后至少 30 秒 | | SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 | -| 公网 IP | 同一路由键缓存 600 秒(含失败),请求超时 5 秒;面板网络任务启动或路由键变化时查询,无独立轮询计时器 | +| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;面板可见时按缓存到期持续刷新,路由键变化或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 | | 趋势 | 全局与每接口最多各 60 点,仅内存保存 | 慢指标只在常规采样轮次检查是否到期,后台间隔较长时实际刷新更慢。快照中的慢指标可能来自之前的缓存;磁盘 / 电池健康快照带读取日期。暂停停止发布,不保证取消已进入系统调用的工作。 diff --git a/kymo/Core/Services/PublicIPAddressService.swift b/kymo/Core/Services/PublicIPAddressService.swift index 40b1010..beb5c94 100644 --- a/kymo/Core/Services/PublicIPAddressService.swift +++ b/kymo/Core/Services/PublicIPAddressService.swift @@ -5,36 +5,55 @@ import Darwin actor PublicIPAddressService { static let shared = PublicIPAddressService() private let session: URLSession + private let cacheLifetime: TimeInterval + private let retryInterval: TimeInterval + private let now: @Sendable () -> TimeInterval + private var cached: (route: String, expiresAt: TimeInterval, address: String?)? - init(session: URLSession = .shared) { self.session = session } + init(session: URLSession = .shared, cacheLifetime: TimeInterval = 600, retryInterval: TimeInterval = 30, + now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) { + precondition(cacheLifetime.isFinite && cacheLifetime > 0 && retryInterval.isFinite && retryInterval > 0) + self.session = session + self.cacheLifetime = cacheLifetime + self.retryInterval = retryInterval + self.now = now + } - private var cached: (route: String, date: Date, address: String?)? + /// The caller owns the task lifetime; route changes and hidden views cancel both HTTP and sleep. + func refreshContinuously(route: String, onUpdate: @Sendable (String?) async -> Void) async { + while !Task.isCancelled { + let value = await address(route: route) + guard !Task.isCancelled else { return } + await onUpdate(value) + let delay = cached.flatMap { $0.route == route ? $0.expiresAt - now() : nil } ?? retryInterval + do { try await Task.sleep(for: .seconds(max(0.01, delay))) } + catch { return } + } + } func address(route: String) async -> String? { - if let cached, cached.route == route, Date().timeIntervalSince(cached.date) < 600 { - return cached.address - } + guard !Task.isCancelled else { return nil } + if let cached, cached.route == route, now() < cached.expiresAt { return cached.address } var request = URLRequest(url: URL(string: "https://api.ipify.org")!) request.timeoutInterval = 5 request.cachePolicy = .reloadIgnoringLocalCacheData - let address: String? + var address: String? do { let (data, response) = try await session.data(for: request) let value = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" var ipv4 = in_addr() var ipv6 = in6_addr() - guard (response as? HTTPURLResponse)?.statusCode == 200, - value.utf8.count <= 45, - inet_pton(AF_INET, value, &ipv4) == 1 || inet_pton(AF_INET6, value, &ipv6) == 1 else { - cached = (route, Date(), nil) - return nil + if (response as? HTTPURLResponse)?.statusCode == 200, + value.utf8.count <= 45, + inet_pton(AF_INET, value, &ipv4) == 1 || inet_pton(AF_INET6, value, &ipv6) == 1 { + address = value } - address = value } catch { - if Task.isCancelled { return nil } - address = nil + if Task.isCancelled || (error as? URLError)?.code == .cancelled { return nil } } - cached = (route, Date(), address) + // A cancelled old route must neither publish nor replace the cache during a route switch. + guard !Task.isCancelled else { return nil } + cached = (route, now() + (address == nil ? retryInterval : cacheLifetime), address) return address } } diff --git a/kymo/Features/MenuBar/MenuPanelView+Network.swift b/kymo/Features/MenuBar/MenuPanelView+Network.swift index c0d98ff..04be7b6 100644 --- a/kymo/Features/MenuBar/MenuPanelView+Network.swift +++ b/kymo/Features/MenuBar/MenuPanelView+Network.swift @@ -55,9 +55,12 @@ extension MenuPanelView { .task(id: publicIPRoute) { publicIPAddress = nil guard snapshot.networkPath == .available else { return } - let address = await PublicIPAddressService.shared.address(route: publicIPRoute) - guard !Task.isCancelled else { return } - publicIPAddress = address + await PublicIPAddressService.shared.refreshContinuously(route: publicIPRoute) { address in + await MainActor.run { + guard !Task.isCancelled else { return } + publicIPAddress = address + } + } } } var publicIPRoute: String { diff --git a/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift b/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift index 77dc03a..6d32d52 100644 --- a/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift +++ b/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift @@ -96,8 +96,8 @@ extension MenuPanelView { ForEach(fans) { fan in FanSpeedIndicator( title: fans.count == 2 - ? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight") - : LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm) + ? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight")) + : Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm) } } .modifier(CardInset()) diff --git a/kymo/Features/MenuBar/ProcessTableProjection.swift b/kymo/Features/MenuBar/ProcessTableProjection.swift index e9ef1f3..e04209d 100644 --- a/kymo/Features/MenuBar/ProcessTableProjection.swift +++ b/kymo/Features/MenuBar/ProcessTableProjection.swift @@ -2,6 +2,13 @@ import Foundation /// Compute once per data/filter/sort event, never from row rendering or scroll position. nonisolated enum ProcessTableProjection { + /// Filtering hides rows without terminating processes. A failed read proves no departure. + static func exitedSelection(_ selected: ProcessIdentity?, in snapshot: ProcessSnapshot?) -> ProcessIdentity? { + guard let selected, let snapshot, !snapshot.failed, + !snapshot.rows.contains(where: { $0.id == selected }) else { return nil } + return selected + } + static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], order: [ProcessIdentity]) -> [ProcessMetrics] { let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) }) return input.filter { diff --git a/kymo/Features/MenuBar/ProcessTableView.swift b/kymo/Features/MenuBar/ProcessTableView.swift index 87bda56..0c2b5c0 100644 --- a/kymo/Features/MenuBar/ProcessTableView.swift +++ b/kymo/Features/MenuBar/ProcessTableView.swift @@ -14,10 +14,9 @@ struct ProcessTableView: View { @State private var searchFocused = false private var held: Bool { hovering || selected != nil || !search.isEmpty } - private var selectedRow: ProcessMetrics? { rows.first { $0.id == selected } } + private var selectedRow: ProcessMetrics? { snapshot?.rows.first { $0.id == selected } } private var exitedSelection: ProcessIdentity? { - guard let selected, snapshot != nil, !rows.contains(where: { $0.id == selected }) else { return nil } - return selected + ProcessTableProjection.exitedSelection(selected, in: snapshot) } var body: some View { @@ -74,7 +73,7 @@ struct ProcessTableView: View { .task(id: exitedSelection) { guard let id = exitedSelection else { return } do { try await Task.sleep(for: .seconds(3)) } catch { return } - if selected == id { selected = nil; departed = nil } + if exitedSelection == id { selected = nil; departed = nil } } .onExitCommand { if !search.isEmpty { search = "" } diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings index 4523c0f..c2e82a8 100644 --- a/kymo/Resources/Localizable.xcstrings +++ b/kymo/Resources/Localizable.xcstrings @@ -1733,6 +1733,28 @@ } } }, + "gpu.fanNumber %lld" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fan %lld" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "风扇 %lld" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "風扇 %lld" + } + } + } + }, "gpu.memoryComparisonHelp" : { "extractionState" : "stale", "localizations" : { diff --git a/kymo/UI/Components/FanSpeedIndicator.swift b/kymo/UI/Components/FanSpeedIndicator.swift index c8814ec..41b68d6 100644 --- a/kymo/UI/Components/FanSpeedIndicator.swift +++ b/kymo/UI/Components/FanSpeedIndicator.swift @@ -28,7 +28,7 @@ nonisolated struct FanRotation { } struct FanSpeedIndicator: View { - let title: LocalizedStringKey + let title: Text let rpm: Double? @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var rotation = FanRotation() @@ -40,7 +40,7 @@ struct FanSpeedIndicator: View { .rotationEffect(.degrees(rotation.angle(at: context.date.timeIntervalSinceReferenceDate))) .foregroundStyle(.secondary) }.frame(width: 14, height: 14).accessibilityHidden(true) - Text(title).foregroundStyle(.secondary) + title.foregroundStyle(.secondary) Spacer(minLength: 2) AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM") .monospacedDigit().fontWeight(.medium) diff --git a/kymoTests/LocalizationChecks.swift b/kymoTests/LocalizationChecks.swift index 74f2d68..cbd0c6d 100644 --- a/kymoTests/LocalizationChecks.swift +++ b/kymoTests/LocalizationChecks.swift @@ -30,6 +30,12 @@ import Foundation let value = AppLocalization.string(key, locale: locale, bundle: bundle, table: table) precondition(!value.isEmpty && value != key, "Missing built translation: \(language)/\(table)/\(key)") } + for number in [1, 3, 10] { + let format = AppLocalization.string("gpu.fanNumber %lld", locale: locale, bundle: bundle) + let title = String(format: format, Int64(number)) + let expected = ["en": "Fan", "zh-Hans": "风扇", "zh-Hant": "風扇"][language]! + precondition(title == "\(expected) \(number)", "Numbered fan must use the selected app locale") + } let average = AppLocalization.string("gpu.recentAverage", locale: locale, bundle: bundle) precondition(average == ["en": "Last-minute average", "zh-Hans": "近 1 分钟平均", "zh-Hant": "近 1 分鐘平均"][language]) } diff --git a/kymoTests/ProcessSelectionChecks.swift b/kymoTests/ProcessSelectionChecks.swift new file mode 100644 index 0000000..4d8fe6b --- /dev/null +++ b/kymoTests/ProcessSelectionChecks.swift @@ -0,0 +1,26 @@ +import Foundation + +@main struct ProcessSelectionChecks { + static func main() { + let id = ProcessIdentity(pid: 42, seconds: 100, microseconds: 0) + let row = ProcessMetrics(id: id, name: "worker", path: "/test/worker", cpu: 0.2, + residentBytes: 10, threads: 1, restricted: false) + let live = ProcessSnapshot(date: Date(), enumerated: 1, readable: 1, rows: [row], failed: false) + let filtered = ProcessTableProjection.rows(live.rows, query: "does-not-match", sorting: [], order: []) + precondition(filtered.isEmpty) + precondition(ProcessTableProjection.exitedSelection(id, in: live) == nil, "Filtered selection is still alive") + precondition(ProcessTableProjection.exitedSelection(nil, in: live) == nil) + precondition(ProcessTableProjection.exitedSelection(id, in: nil) == nil) + let failed = ProcessSnapshot(date: Date(), enumerated: 0, readable: 0, rows: [], failed: true) + precondition(ProcessTableProjection.exitedSelection(id, in: failed) == nil, "A failed read cannot prove exit") + let exited = ProcessSnapshot(date: Date(), enumerated: 0, readable: 0, rows: [], failed: false) + precondition(ProcessTableProjection.exitedSelection(id, in: exited) == id) + let reused = ProcessIdentity(pid: 42, seconds: 101, microseconds: 0) + let replacement = ProcessMetrics(id: reused, name: row.name, path: row.path, cpu: nil, + residentBytes: nil, threads: nil, restricted: true) + let recycled = ProcessSnapshot(date: Date(), enumerated: 1, readable: 0, rows: [replacement], failed: false) + precondition(ProcessTableProjection.exitedSelection(id, in: recycled) == id, "PID reuse cannot keep the previous process alive") + precondition(ProcessTableProjection.exitedSelection(reused, in: recycled) == nil) + print("PASS: filtered/live selection, absent selection/snapshot, failed enumeration, actual exit and PID reuse") + } +} diff --git a/kymoTests/PublicIPAddressChecks.swift b/kymoTests/PublicIPAddressChecks.swift index e978ca7..71c6421 100644 --- a/kymoTests/PublicIPAddressChecks.swift +++ b/kymoTests/PublicIPAddressChecks.swift @@ -1,44 +1,151 @@ import Foundation -final class IPResponse: URLProtocol, @unchecked Sendable { - nonisolated(unsafe) static var payload = "203.0.113.4" - nonisolated(unsafe) static var status = 200 - nonisolated(unsafe) static var count = 0 +private final class ResponseState: @unchecked Sendable { + enum Response { case success(String), httpFailure, timeout, pending } + private let lock = NSLock() + private var response = Response.success("203.0.113.4") + private var requests = 0 + private var stops = 0 + func configure(_ value: Response) { lock.lock(); defer { lock.unlock() }; response = value } + func begin() -> Response { lock.lock(); defer { lock.unlock() }; requests += 1; return response } + func stopped() { lock.lock(); defer { lock.unlock() }; stops += 1 } + var count: Int { lock.lock(); defer { lock.unlock() }; return requests } + var cancellations: Int { lock.lock(); defer { lock.unlock() }; return stops } +} + +private final class IPResponse: URLProtocol, @unchecked Sendable { + static let state = ResponseState() override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { - Self.count += 1 precondition(request.url?.scheme == "https" && request.timeoutInterval == 5) - client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: Self.status, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed) - client?.urlProtocol(self, didLoad: Data(Self.payload.utf8)) + let response = Self.state.begin() + switch response { + case .pending: return + case .timeout: + client?.urlProtocol(self, didFailWithError: URLError(.timedOut)) + case .success(let payload): deliver(payload, status: 200) + case .httpFailure: deliver("unavailable", status: 503) + } + } + private func deliver(_ payload: String, status: Int) { + client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data(payload.utf8)) client?.urlProtocolDidFinishLoading(self) } - override func stopLoading() {} + override func stopLoading() { Self.state.stopped() } +} + +private final class TestClock: @unchecked Sendable { + private let lock = NSLock() + private var value: TimeInterval = 0 + func advance(_ seconds: TimeInterval) { lock.lock(); defer { lock.unlock() }; value += seconds } + func now() -> TimeInterval { lock.lock(); defer { lock.unlock() }; return value } +} + +private actor Deliveries { + private var values: [String?] = [] + func receive(_ value: String?) { values.append(value) } + var count: Int { values.count } + var last: String? { values.last ?? nil } } @main struct PublicIPAddressChecks { - static func main() async { + static func main() async throws { let config = URLSessionConfiguration.ephemeral config.protocolClasses = [IPResponse.self] let session = URLSession(configuration: config) defer { session.invalidateAndCancel() } - let service = PublicIPAddressService(session: session) + let clock = TestClock() + let service = PublicIPAddressService(session: session, now: { clock.now() }) let first = await service.address(route: "one") precondition(first == "203.0.113.4") + let initialCount = IPResponse.state.count + clock.advance(599) let cached = await service.address(route: "one") - precondition(cached == first && IPResponse.count == 1) - IPResponse.payload = "2001:db8::1" + precondition(cached == first && IPResponse.state.count == initialCount) + clock.advance(1) + IPResponse.state.configure(.success("203.0.113.5")) + let expired = await service.address(route: "one") + precondition(expired == "203.0.113.5" && IPResponse.state.count == initialCount + 1) + IPResponse.state.configure(.success("2001:db8::1")) let changed = await service.address(route: "two") - precondition(changed == "2001:db8::1" && IPResponse.count == 2) - IPResponse.payload = "invalid" + precondition(changed == "2001:db8::1") + IPResponse.state.configure(.success("invalid")) let invalid = await service.address(route: "three") precondition(invalid == nil) + let failedCount = IPResponse.state.count + IPResponse.state.configure(.success("203.0.113.4")) + clock.advance(29) let cachedFailure = await service.address(route: "three") - precondition(cachedFailure == nil && IPResponse.count == 3) - IPResponse.payload = "203.0.113.4" - IPResponse.status = 503 + precondition(cachedFailure == nil && IPResponse.state.count == failedCount) + clock.advance(1) + let recovered = await service.address(route: "three") + precondition(recovered == "203.0.113.4" && IPResponse.state.count == failedCount + 1) + IPResponse.state.configure(.httpFailure) let httpFailure = await service.address(route: "four") precondition(httpFailure == nil) - print("PASS: IPv4/IPv6, route cache, invalid payload, cached failure, HTTP failure, timeout") + IPResponse.state.configure(.timeout) + let timedOut = await service.address(route: "five") + precondition(timedOut == nil) + clock.advance(30) + IPResponse.state.configure(.success("203.0.113.6")) + let afterTimeout = await service.address(route: "five") + precondition(afterTimeout == "203.0.113.6") + + // Exercise the same continuous-refresh function used by the SwiftUI task. + // Short intervals keep this integration check fast; cache-boundary checks above use a fake clock. + let looping = PublicIPAddressService(session: session, cacheLifetime: 0.04, retryInterval: 0.02) + let deliveries = Deliveries() + IPResponse.state.configure(.timeout) + let loop = Task { await looping.refreshContinuously(route: "visible") { await deliveries.receive($0) } } + try await until { await deliveries.count >= 1 } + IPResponse.state.configure(.success("203.0.113.7")) + try await until { await deliveries.last == "203.0.113.7" } + IPResponse.state.configure(.success("203.0.113.8")) + try await until { await deliveries.last == "203.0.113.8" } + loop.cancel() + await loop.value + let stoppedCount = IPResponse.state.count + let stoppedDeliveries = await deliveries.count + try await Task.sleep(for: .milliseconds(100)) + let finalDeliveries = await deliveries.count + precondition(IPResponse.state.count == stoppedCount && finalDeliveries == stoppedDeliveries, + "Hidden/cancelled observers must stop polling and publishing") + + IPResponse.state.configure(.pending) + let beforeCancel = IPResponse.state.count + let pending = Task { await service.address(route: "cancelled-route") } + try await until { IPResponse.state.count > beforeCancel } + let previousStops = IPResponse.state.cancellations + pending.cancel() + let cancelled = await pending.value + precondition(cancelled == nil) + try await until { IPResponse.state.cancellations > previousStops } + IPResponse.state.configure(.success("203.0.113.9")) + let afterCancellation = await service.address(route: "cancelled-route") + precondition(afterCancellation == "203.0.113.9", "Cancellation must not cache a failure") + let cancelledDeliveries = Deliveries() + IPResponse.state.configure(.pending) + let beforeObserver = IPResponse.state.count + let oldRoute = Task { + await service.refreshContinuously(route: "old-visible-route") { await cancelledDeliveries.receive($0) } + } + try await until { IPResponse.state.count > beforeObserver } + oldRoute.cancel() + await oldRoute.value + let cancelledCount = await cancelledDeliveries.count + precondition(cancelledCount == 0, "A cancelled route must never publish its pending response") + IPResponse.state.configure(.success("203.0.113.10")) + let newRoute = await service.address(route: "new-visible-route") + precondition(newRoute == "203.0.113.10") + print("PASS: IPv4/IPv6, route changes, 600s expiry, 30s failure retry, invalid payload, HTTP failure, simulated transport timeout/recovery, continuous refresh and cancellation") + } + + private static func until(_ predicate: () async -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + while !(await predicate()) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) } + let passed = await predicate() + precondition(passed, "Timed out waiting for network test event") } }