import Foundation /// The Mac's local store. The app and the `--mcp` process open the same folder, so writes are /// coordinated through NSFileCoordinator and each write re-reads the file first (last write never /// silently drops another process's change). public final class WorkspaceStore: @unchecked Sendable { public let folder: URL private var workspaceURL: URL { folder.appendingPathComponent("workspace.json") } private var dataURL: URL { folder.appendingPathComponent("data.json") } private let lock = NSLock() public static var defaultFolder: URL { if let override = ProcessInfo.processInfo.environment["GRAPHLEY_WORKSPACE"] { return URL(fileURLWithPath: override, isDirectory: true) } let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] return base.appendingPathComponent("Graphley", isDirectory: true) } public init(folder: URL = WorkspaceStore.defaultFolder) throws { self.folder = folder try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) } // MARK: Workspace public func load() throws -> Workspace { try read(workspaceURL) ?? Workspace() } /// Reads, applies `change`, writes. Returns the saved workspace. @discardableResult public func update(_ change: (inout Workspace) throws -> Void) throws -> Workspace { lock.lock(); defer { lock.unlock() } var result = Workspace() var failure: Error? var coordinationError: NSError? NSFileCoordinator().coordinate(writingItemAt: workspaceURL, options: .forMerging, error: &coordinationError) { url in do { var ws: Workspace = try read(url) ?? Workspace() try change(&ws) try write(ws, to: url) result = ws } catch { failure = error } } if let coordinationError { throw coordinationError } if let failure { throw failure } return result } // MARK: Data points public func points() throws -> [DataPoint] { try read(dataURL) ?? [] } /// When the store's files last changed on disk (by this process or the `--mcp` one), so the app /// can reload only after a real write, including one that replaces values without adding any. public func lastModified() -> Date? { [workspaceURL, dataURL].compactMap { try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate }.max() } /// Replaces what `fresh` covers and keeps everything else, trimmed to `keepDays`. Daily points replace the same /// subject, metric, breakdown family and day; window totals (top pages, channels…) replace their whole family, /// so yesterday's 30-day totals never sit next to today's. public func merge(_ fresh: [DataPoint], keepDays: Int = 400) throws { try mutatePoints { all in Self.merge(fresh, into: &all, keepDays: keepDays) } } static func merge(_ fresh: [DataPoint], into all: inout [DataPoint], keepDays: Int = 400) { let windows = Set(fresh.filter(\.isWindow).map(\.mergeKey)) let daily = Set(fresh.filter { !$0.isWindow }.map { $0.mergeKey + "|" + $0.day }) all.removeAll { $0.isWindow ? windows.contains($0.mergeKey) : daily.contains($0.mergeKey + "|" + $0.day) } all.append(contentsOf: fresh) let cutoff = DayKey.lastDays(keepDays).first ?? "" all.removeAll { $0.day < cutoff } } /// Reads, changes and writes the data points under the store's lock (imports, migrations). public func mutatePoints(_ change: (inout [DataPoint]) throws -> Void) throws { lock.lock(); defer { lock.unlock() } var all: [DataPoint] = try read(dataURL) ?? [] try change(&all) try write(all, to: dataURL) } /// `refreshedAt` defaults to now (a refresh just finished). Pushes that only change the layout, /// such as a new site order, pass the last refresh time so the iPhone's "Updated" line stays true. public func snapshot(days: Int = 90, refreshedAt: Date? = nil) throws -> Snapshot { let ws = try load() let cutoff = DayKey.lastDays(days).first ?? "" return Snapshot(refreshedAt: refreshedAt ?? .now, sites: ws.sites.filter { !$0.archived }, apps: ws.apps, socials: ws.socials, dashboards: ws.dashboards, points: try points().filter { $0.day >= cutoff || Self.longHistory.contains($0.metric) }, reviews: ws.reviews, campaigns: ws.campaigns, videos: ws.videos, caveats: ws.caveats) } /// Small series the iPhone gets in full (follower growth since June, the ad history). static let longHistory: Set = [.followers, .adSpend, .adClicks, .adImpressions, .adConversions] // MARK: Files private func read(_ url: URL) throws -> T? { guard FileManager.default.fileExists(atPath: url.path) else { return nil } return try JSONDecoder.analytics.decode(T.self, from: Data(contentsOf: url)) } private func write(_ value: T, to url: URL) throws { try JSONEncoder.analytics.encode(value).write(to: url, options: [.atomic]) } } public extension JSONEncoder { static var analytics: JSONEncoder { let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.sortedKeys]; return e } } public extension JSONDecoder { static var analytics: JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d } }