|
| 1 | +// |
| 2 | +// AnalyticsHeartbeatService.swift |
| 3 | +// TableProAnalytics |
| 4 | +// |
| 5 | + |
| 6 | +import CryptoKit |
| 7 | +import Foundation |
| 8 | +import os |
| 9 | + |
| 10 | +/// Shared heartbeat service for macOS and iOS. Sends anonymous usage data to the analytics API. |
| 11 | +/// |
| 12 | +/// Platform-specific data is injected via `AnalyticsEnvironmentProvider`. The service handles: |
| 13 | +/// encoding, HMAC-SHA256 signing, HTTP transport, heartbeat scheduling, and cooldown persistence. |
| 14 | +@MainActor |
| 15 | +public final class AnalyticsHeartbeatService { |
| 16 | + private static let logger = Logger(subsystem: "com.TablePro", category: "AnalyticsHeartbeat") |
| 17 | + |
| 18 | + private let provider: AnalyticsEnvironmentProvider |
| 19 | + |
| 20 | + // swiftlint:disable:next force_unwrapping |
| 21 | + private let analyticsUrl: URL |
| 22 | + |
| 23 | + private let heartbeatInterval: TimeInterval |
| 24 | + private let initialDelay: TimeInterval |
| 25 | + |
| 26 | + /// Minimum elapsed time before sending another heartbeat. |
| 27 | + /// Prevents duplicate sends on iOS when the app cycles between foreground/background. |
| 28 | + private let cooldownInterval: TimeInterval |
| 29 | + |
| 30 | + private static let lastHeartbeatKey = "com.TablePro.analytics.lastHeartbeatDate" |
| 31 | + |
| 32 | + private let session: URLSession = { |
| 33 | + let config = URLSessionConfiguration.default |
| 34 | + config.timeoutIntervalForRequest = 15 |
| 35 | + config.timeoutIntervalForResource = 30 |
| 36 | + config.waitsForConnectivity = true |
| 37 | + return URLSession(configuration: config) |
| 38 | + }() |
| 39 | + |
| 40 | + private let encoder: JSONEncoder = { |
| 41 | + let encoder = JSONEncoder() |
| 42 | + encoder.keyEncodingStrategy = .convertToSnakeCase |
| 43 | + return encoder |
| 44 | + }() |
| 45 | + |
| 46 | + public init( |
| 47 | + provider: AnalyticsEnvironmentProvider, |
| 48 | + analyticsUrl: URL = URL(string: "https://api.tablepro.app/v1/analytics")!, // swiftlint:disable:this force_unwrapping |
| 49 | + heartbeatInterval: TimeInterval = 24 * 60 * 60, |
| 50 | + initialDelay: TimeInterval = 10, |
| 51 | + cooldownInterval: TimeInterval = 20 * 60 * 60 |
| 52 | + ) { |
| 53 | + self.provider = provider |
| 54 | + self.analyticsUrl = analyticsUrl |
| 55 | + self.heartbeatInterval = heartbeatInterval |
| 56 | + self.initialDelay = initialDelay |
| 57 | + self.cooldownInterval = cooldownInterval |
| 58 | + } |
| 59 | + |
| 60 | + // MARK: - Public API |
| 61 | + |
| 62 | + /// Start the periodic heartbeat loop. Returns a cancellable Task. |
| 63 | + /// The caller owns the Task lifecycle (cancel on deinit or background). |
| 64 | + public func startPeriodicHeartbeat() -> Task<Void, Never> { |
| 65 | + Task { [weak self] in |
| 66 | + guard let delay = self?.initialDelay else { return } |
| 67 | + try? await Task.sleep(for: .seconds(delay)) |
| 68 | + |
| 69 | + while !Task.isCancelled { |
| 70 | + guard let target = self else { return } |
| 71 | + await target.sendHeartbeat() |
| 72 | + try? await Task.sleep(for: .seconds(target.heartbeatInterval)) |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// Send a single heartbeat. Respects opt-out and cooldown. |
| 78 | + public func sendHeartbeat() async { |
| 79 | + guard provider.isAnalyticsEnabled else { |
| 80 | + Self.logger.trace("Analytics disabled by user, skipping heartbeat") |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + guard isCooldownElapsed() else { |
| 85 | + Self.logger.trace("Analytics cooldown not elapsed, skipping heartbeat") |
| 86 | + return |
| 87 | + } |
| 88 | + |
| 89 | + let payload = buildPayload() |
| 90 | + |
| 91 | + do { |
| 92 | + var request = URLRequest(url: analyticsUrl) |
| 93 | + request.httpMethod = "POST" |
| 94 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 95 | + request.httpBody = try encoder.encode(payload) |
| 96 | + |
| 97 | + if let body = request.httpBody, |
| 98 | + let secret = provider.hmacSecret, !secret.isEmpty { |
| 99 | + let key = SymmetricKey(data: Data(secret.utf8)) |
| 100 | + let signature = HMAC<SHA256>.authenticationCode(for: body, using: key) |
| 101 | + let signatureHex = signature.map { String(format: "%02x", $0) }.joined() |
| 102 | + request.setValue(signatureHex, forHTTPHeaderField: "X-Signature") |
| 103 | + } |
| 104 | + |
| 105 | + let (_, response) = try await session.data(for: request) |
| 106 | + |
| 107 | + if let httpResponse = response as? HTTPURLResponse { |
| 108 | + Self.logger.trace("Analytics heartbeat sent, status: \(httpResponse.statusCode)") |
| 109 | + } |
| 110 | + |
| 111 | + recordHeartbeatTimestamp() |
| 112 | + } catch { |
| 113 | + Self.logger.trace("Analytics heartbeat failed: \(error.localizedDescription)") |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + // MARK: - Private |
| 118 | + |
| 119 | + private func buildPayload() -> AnalyticsPayload { |
| 120 | + let types = provider.activeDatabaseTypes |
| 121 | + return AnalyticsPayload( |
| 122 | + machineId: provider.machineId, |
| 123 | + platform: provider.platform, |
| 124 | + appVersion: provider.appVersion, |
| 125 | + osVersion: provider.osVersion, |
| 126 | + architecture: provider.architecture, |
| 127 | + locale: provider.locale, |
| 128 | + databaseTypes: types.isEmpty ? nil : types, |
| 129 | + connectionCount: provider.activeConnectionCount, |
| 130 | + hasLicense: provider.hasLicense |
| 131 | + ) |
| 132 | + } |
| 133 | + |
| 134 | + private func isCooldownElapsed() -> Bool { |
| 135 | + guard let last = UserDefaults.standard.object(forKey: Self.lastHeartbeatKey) as? Date else { |
| 136 | + return true |
| 137 | + } |
| 138 | + return Date().timeIntervalSince(last) >= cooldownInterval |
| 139 | + } |
| 140 | + |
| 141 | + private func recordHeartbeatTimestamp() { |
| 142 | + UserDefaults.standard.set(Date(), forKey: Self.lastHeartbeatKey) |
| 143 | + } |
| 144 | +} |
0 commit comments