154 lines
8.0 KiB
Swift
154 lines
8.0 KiB
Swift
import Foundation
|
|
|
|
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() {
|
|
precondition(request.url?.scheme == "https" && request.timeoutInterval == 5)
|
|
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() { 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 throws {
|
|
let config = PublicIPAddressService.sessionConfiguration()
|
|
precondition(config.urlCache == nil && config.httpCookieStorage == nil && config.urlCredentialStorage == nil)
|
|
precondition(!config.httpShouldSetCookies && config.requestCachePolicy == .reloadIgnoringLocalCacheData)
|
|
config.protocolClasses = [IPResponse.self]
|
|
let session = URLSession(configuration: config)
|
|
defer { session.invalidateAndCancel() }
|
|
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.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.state.configure(.success("<html>invalid</html>"))
|
|
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.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)
|
|
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")
|
|
}
|
|
}
|