Files
Kymo/kymo/Core/Services/PublicIPAddressService.swift

77 lines
3.5 KiB
Swift

import Foundation
import Darwin
/// The address observed by an external HTTPS service, not a per-interface address.
actor PublicIPAddressService {
static let shared = PublicIPAddressService()
private let session: URLSession
private let ownsSession: Bool
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? = nil, cacheLifetime: TimeInterval = 600, retryInterval: TimeInterval = 30,
now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
precondition(cacheLifetime.isFinite && cacheLifetime > 0 && retryInterval.isFinite && retryInterval > 0)
self.ownsSession = session == nil
self.session = session ?? URLSession(configuration: Self.sessionConfiguration())
self.cacheLifetime = cacheLifetime
self.retryInterval = retryInterval
self.now = now
}
/// No HTTP cache, cookies or credentials are persisted; only `cached` above retains results.
static func sessionConfiguration() -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.ephemeral
configuration.urlCache = nil
configuration.httpCookieStorage = nil
configuration.urlCredentialStorage = nil
configuration.httpShouldSetCookies = false
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
return configuration
}
deinit {
if ownsSession { session.invalidateAndCancel() }
}
/// 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? {
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
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()
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
}
} catch {
if Task.isCancelled || (error as? URLError)?.code == .cancelled { return nil }
}
// 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
}
}