Branchwell

Graphley / app · graphley.ai / Sources / OwnerMetricsKit / MetricsClient.swift

1import Foundation
2
3public struct MetricsClient: Sendable {
4 struct Reply: Sendable {
5 let code: Int
6 let contentType: String?
7 let data: Data
8 }
9 let transport: @Sendable (URLRequest) async throws -> Reply
10 static let limit = 768 * 1024
11
12 public init() { transport = Self.send }
13 init(transport: @escaping @Sendable (URLRequest) async throws -> Reply) { self.transport = transport }
14
15 /// A passkey session from projectatom.ai: 32 random bytes, base64url without padding.
16 public static func isValidSession(_ session: String) -> Bool {
17 session.utf8.count == 43 && session.utf8.allSatisfy {
18 (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 95
19 }
20 }
21
22 public func read(session: String, window: MetricWindow) async throws -> OwnerMetricsSnapshot {
23 guard Self.isValidSession(session) else { throw MetricsError.unauthorizedOrDisabled }
24 var endpoint = URLComponents(string: "https://projectatom.ai/api/visits")!
25 endpoint.queryItems = [.init(name: "private", value: "graphley"), .init(name: "days", value: String(window.rawValue))]
26 var request = URLRequest(url: endpoint.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 25)
27 request.httpMethod = "GET"
28 request.setValue("Bearer " + session, forHTTPHeaderField: "Authorization")
29 request.setValue("application/json", forHTTPHeaderField: "Accept")
30 let result: Reply
31 do { result = try await transport(request) }
32 catch is CancellationError { throw CancellationError() }
33 catch let error as MetricsError { throw error }
34 catch { throw MetricsError.unavailable }
35 switch result.code {
36 case 200: break
37 case 401, 403, 404: throw MetricsError.unauthorizedOrDisabled
38 default: throw MetricsError.unavailable
39 }
40 guard result.contentType?.lowercased().split(separator: ";").first == "application/json",
41 result.data.count <= Self.limit else { throw MetricsError.invalidResponse }
42 return try OwnerMetricsSnapshot.validated(result.data, window: window)
43 }
44
45 static func send(_ request: URLRequest) async throws -> Reply {
46 let configuration = URLSessionConfiguration.ephemeral
47 configuration.httpCookieStorage = nil
48 configuration.urlCache = nil
49 configuration.urlCredentialStorage = nil
50 configuration.timeoutIntervalForResource = 30
51 let session = URLSession(configuration: configuration, delegate: NoRedirects(), delegateQueue: nil)
52 defer { session.invalidateAndCancel() }
53 let (bytes, response) = try await session.bytes(for: request)
54 guard let http = response as? HTTPURLResponse else { throw MetricsError.invalidResponse }
55 guard http.statusCode == 200 else { return Reply(code: http.statusCode, contentType: nil, data: Data()) }
56 guard http.expectedContentLength <= limit else { throw MetricsError.invalidResponse }
57 var data = Data()
58 for try await byte in bytes {
59 guard data.count < limit else { throw MetricsError.invalidResponse }
60 data.append(byte)
61 }
62 return Reply(code: http.statusCode, contentType: http.value(forHTTPHeaderField: "Content-Type"), data: data)
63 }
64}
65
66final class NoRedirects: NSObject, URLSessionTaskDelegate {
67 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
68 newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
69 completionHandler(nil)
70 }
71}