Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsKit / WorkspaceStore.swift

Raw 5.5 KB on 089159c793cd9cbff9078de2ee49995b60c6b768
1import Foundation
2
3/// The Mac's local store. The app and the `--mcp` process open the same folder, so writes are
4/// coordinated through NSFileCoordinator and each write re-reads the file first (last write never
5/// silently drops another process's change).
6public final class WorkspaceStore: @unchecked Sendable {
7 public let folder: URL
8 private var workspaceURL: URL { folder.appendingPathComponent("workspace.json") }
9 private var dataURL: URL { folder.appendingPathComponent("data.json") }
10 private let lock = NSLock()
11
12 public static var defaultFolder: URL {
13 if let override = ProcessInfo.processInfo.environment["GRAPHLEY_WORKSPACE"] { return URL(fileURLWithPath: override, isDirectory: true) }
14 let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
15 return base.appendingPathComponent("Graphley", isDirectory: true)
16 }
17
18 public init(folder: URL = WorkspaceStore.defaultFolder) throws {
19 self.folder = folder
20 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
21 }
22
23 // MARK: Workspace
24
25 public func load() throws -> Workspace {
26 try read(workspaceURL) ?? Workspace()
27 }
28
29 /// Reads, applies `change`, writes. Returns the saved workspace.
30 @discardableResult
31 public func update(_ change: (inout Workspace) throws -> Void) throws -> Workspace {
32 lock.lock(); defer { lock.unlock() }
33 var result = Workspace()
34 var failure: Error?
35 var coordinationError: NSError?
36 NSFileCoordinator().coordinate(writingItemAt: workspaceURL, options: .forMerging, error: &coordinationError) { url in
37 do {
38 var ws: Workspace = try read(url) ?? Workspace()
39 try change(&ws)
40 try write(ws, to: url)
41 result = ws
42 } catch { failure = error }
43 }
44 if let coordinationError { throw coordinationError }
45 if let failure { throw failure }
46 return result
47 }
48
49 // MARK: Data points
50
51 public func points() throws -> [DataPoint] { try read(dataURL) ?? [] }
52
53 /// When the store's files last changed on disk (by this process or the `--mcp` one), so the app
54 /// can reload only after a real write, including one that replaces values without adding any.
55 public func lastModified() -> Date? {
56 [workspaceURL, dataURL].compactMap { try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate }.max()
57 }
58
59 /// Replaces what `fresh` covers and keeps everything else, trimmed to `keepDays`. Daily points replace the same
60 /// subject, metric, breakdown family and day; window totals (top pages, channels…) replace their whole family,
61 /// so yesterday's 30-day totals never sit next to today's.
62 public func merge(_ fresh: [DataPoint], keepDays: Int = 400) throws {
63 try mutatePoints { all in Self.merge(fresh, into: &all, keepDays: keepDays) }
64 }
65
66 static func merge(_ fresh: [DataPoint], into all: inout [DataPoint], keepDays: Int = 400) {
67 let windows = Set(fresh.filter(\.isWindow).map(\.mergeKey))
68 let daily = Set(fresh.filter { !$0.isWindow }.map { $0.mergeKey + "|" + $0.day })
69 all.removeAll { $0.isWindow ? windows.contains($0.mergeKey) : daily.contains($0.mergeKey + "|" + $0.day) }
70 all.append(contentsOf: fresh)
71 let cutoff = DayKey.lastDays(keepDays).first ?? ""
72 all.removeAll { $0.day < cutoff }
73 }
74
75 /// Reads, changes and writes the data points under the store's lock (imports, migrations).
76 public func mutatePoints(_ change: (inout [DataPoint]) throws -> Void) throws {
77 lock.lock(); defer { lock.unlock() }
78 var all: [DataPoint] = try read(dataURL) ?? []
79 try change(&all)
80 try write(all, to: dataURL)
81 }
82
83 /// `refreshedAt` defaults to now (a refresh just finished). Pushes that only change the layout,
84 /// such as a new site order, pass the last refresh time so the iPhone's "Updated" line stays true.
85 public func snapshot(days: Int = 90, refreshedAt: Date? = nil) throws -> Snapshot {
86 let ws = try load()
87 let cutoff = DayKey.lastDays(days).first ?? ""
88 return Snapshot(refreshedAt: refreshedAt ?? .now, sites: ws.sites.filter { !$0.archived }, apps: ws.apps, socials: ws.socials,
89 dashboards: ws.dashboards, points: try points().filter { $0.day >= cutoff || Self.longHistory.contains($0.metric) },
90 reviews: ws.reviews, campaigns: ws.campaigns, videos: ws.videos, caveats: ws.caveats)
91 }
92
93 /// Small series the iPhone gets in full (follower growth since June, the ad history).
94 static let longHistory: Set<Metric> = [.followers, .adSpend, .adClicks, .adImpressions, .adConversions]
95
96 // MARK: Files
97
98 private func read<T: Decodable>(_ url: URL) throws -> T? {
99 guard FileManager.default.fileExists(atPath: url.path) else { return nil }
100 return try JSONDecoder.analytics.decode(T.self, from: Data(contentsOf: url))
101 }
102
103 private func write<T: Encodable>(_ value: T, to url: URL) throws {
104 try JSONEncoder.analytics.encode(value).write(to: url, options: [.atomic])
105 }
106}
107
108public extension JSONEncoder {
109 static var analytics: JSONEncoder {
110 let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.sortedKeys]; return e
111 }
112}
113public extension JSONDecoder {
114 static var analytics: JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }
115}