import Foundation public struct MetricsClient: Sendable { struct Reply: Sendable { let code: Int let contentType: String? let data: Data } let transport: @Sendable (URLRequest) async throws -> Reply static let limit = 768 * 1024 public init() { transport = Self.send } init(transport: @escaping @Sendable (URLRequest) async throws -> Reply) { self.transport = transport } /// A passkey session from projectatom.ai: 32 random bytes, base64url without padding. public static func isValidSession(_ session: String) -> Bool { session.utf8.count == 43 && session.utf8.allSatisfy { (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 95 } } public func read(session: String, window: MetricWindow) async throws -> OwnerMetricsSnapshot { guard Self.isValidSession(session) else { throw MetricsError.unauthorizedOrDisabled } var endpoint = URLComponents(string: "https://projectatom.ai/api/visits")! endpoint.queryItems = [.init(name: "private", value: "graphley"), .init(name: "days", value: String(window.rawValue))] var request = URLRequest(url: endpoint.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 25) request.httpMethod = "GET" request.setValue("Bearer " + session, forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Accept") let result: Reply do { result = try await transport(request) } catch is CancellationError { throw CancellationError() } catch let error as MetricsError { throw error } catch { throw MetricsError.unavailable } switch result.code { case 200: break case 401, 403, 404: throw MetricsError.unauthorizedOrDisabled default: throw MetricsError.unavailable } guard result.contentType?.lowercased().split(separator: ";").first == "application/json", result.data.count <= Self.limit else { throw MetricsError.invalidResponse } return try OwnerMetricsSnapshot.validated(result.data, window: window) } static func send(_ request: URLRequest) async throws -> Reply { let configuration = URLSessionConfiguration.ephemeral configuration.httpCookieStorage = nil configuration.urlCache = nil configuration.urlCredentialStorage = nil configuration.timeoutIntervalForResource = 30 let session = URLSession(configuration: configuration, delegate: NoRedirects(), delegateQueue: nil) defer { session.invalidateAndCancel() } let (bytes, response) = try await session.bytes(for: request) guard let http = response as? HTTPURLResponse else { throw MetricsError.invalidResponse } guard http.statusCode == 200 else { return Reply(code: http.statusCode, contentType: nil, data: Data()) } guard http.expectedContentLength <= limit else { throw MetricsError.invalidResponse } var data = Data() for try await byte in bytes { guard data.count < limit else { throw MetricsError.invalidResponse } data.append(byte) } return Reply(code: http.statusCode, contentType: http.value(forHTTPHeaderField: "Content-Type"), data: data) } } final class NoRedirects: NSObject, URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { completionHandler(nil) } }