Crossmate/Services/DebuggingMonitors.swift (17997B)
1import CloudKit
2import Foundation
3import Observation
4import os
5
6struct PerformanceDiagnosticEntry: Identifiable, Sendable {
7 let id = UUID()
8 let timestamp: Date
9 let name: String
10 let durationMS: Double
11 let detail: String
12}
13
14@MainActor
15@Observable
16final class PerformanceMonitor {
17 private(set) var entries: [PerformanceDiagnosticEntry] = []
18 private(set) var totalEvents = 0
19 private(set) var suppressedEvents = 0
20
21 private let maxEntries = 120
22 private var nextRenderProbeID = 1
23 private var pendingRenderProbes: [Int: RenderProbe] = [:]
24 @ObservationIgnored private var viewBodyCounts: [String: Int] = [:]
25 @ObservationIgnored private var viewBodyDetails: [String: String] = [:]
26 @ObservationIgnored private var scheduledViewBodyReports: Set<String> = []
27
28 private struct RenderProbe {
29 let name: String
30 let position: GridPosition
31 let expectedEntry: String
32 let startedAt: ContinuousClock.Instant
33 let detail: String
34 }
35
36 func record(
37 _ name: String,
38 durationMS: Double,
39 detail: String = "",
40 thresholdMS: Double = 8
41 ) {
42 totalEvents += 1
43 guard durationMS >= thresholdMS else {
44 suppressedEvents += 1
45 return
46 }
47 entries.append(PerformanceDiagnosticEntry(
48 timestamp: Date(),
49 name: name,
50 durationMS: durationMS,
51 detail: detail
52 ))
53 if entries.count > maxEntries {
54 entries.removeFirst(entries.count - maxEntries)
55 }
56 }
57
58 func note(_ name: String, detail: String = "") {
59 entries.append(PerformanceDiagnosticEntry(
60 timestamp: Date(),
61 name: name,
62 durationMS: 0,
63 detail: detail
64 ))
65 if entries.count > maxEntries {
66 entries.removeFirst(entries.count - maxEntries)
67 }
68 }
69
70 func clear() {
71 entries.removeAll()
72 totalEvents = 0
73 suppressedEvents = 0
74 pendingRenderProbes.removeAll()
75 viewBodyCounts.removeAll()
76 viewBodyDetails.removeAll()
77 scheduledViewBodyReports.removeAll()
78 }
79
80 func beginRenderProbe(
81 name: String,
82 position: GridPosition,
83 expectedEntry: String,
84 detail: String = ""
85 ) -> Int {
86 let id = nextRenderProbeID
87 nextRenderProbeID += 1
88 pendingRenderProbes[id] = RenderProbe(
89 name: name,
90 position: position,
91 expectedEntry: expectedEntry,
92 startedAt: .now,
93 detail: detail
94 )
95 return id
96 }
97
98 func renderProbeDetailPrefix(for id: Int) -> String? {
99 guard let probe = pendingRenderProbes[id] else { return nil }
100 return "probe=\(id) row=\(probe.position.row) col=\(probe.position.col)"
101 }
102
103 func completeRenderProbe(id: Int, position: GridPosition, entry: String) {
104 guard let probe = pendingRenderProbes[id],
105 probe.position == position,
106 probe.expectedEntry == entry
107 else { return }
108 pendingRenderProbes.removeValue(forKey: id)
109 let duration = probe.startedAt.duration(to: .now)
110 let milliseconds = Double(duration.components.seconds) * 1000
111 + Double(duration.components.attoseconds) / 1_000_000_000_000_000
112 let baseDetail = "probe=\(id) row=\(probe.position.row) col=\(probe.position.col)"
113 let detail = probe.detail.isEmpty ? baseDetail : "\(baseDetail) \(probe.detail)"
114 record(
115 probe.name,
116 durationMS: milliseconds,
117 detail: detail,
118 thresholdMS: 6
119 )
120 }
121
122 func recordDeferred(
123 _ name: String,
124 start: ContinuousClock.Instant,
125 detail: String = "",
126 thresholdMS: Double = 8
127 ) {
128 let milliseconds = Self.milliseconds(from: start.duration(to: .now))
129 guard milliseconds >= thresholdMS else { return }
130 Task { @MainActor [weak self] in
131 self?.record(
132 name,
133 durationMS: milliseconds,
134 detail: detail,
135 thresholdMS: thresholdMS
136 )
137 }
138 }
139
140 func markViewBodyDeferred(
141 _ name: String,
142 key: String = "",
143 detail: String = ""
144 ) {
145 Task { @MainActor [weak self] in
146 self?.markViewBody(name, key: key, detail: detail)
147 }
148 }
149
150 private func markViewBody(_ name: String, key: String, detail: String) {
151 let reportKey = key.isEmpty ? name : "\(name)|\(key)"
152 viewBodyCounts[reportKey, default: 0] += 1
153 viewBodyDetails[reportKey] = detail
154
155 guard !scheduledViewBodyReports.contains(reportKey) else { return }
156 scheduledViewBodyReports.insert(reportKey)
157 Task { @MainActor [weak self] in
158 try? await Task.sleep(for: .milliseconds(50))
159 self?.flushViewBodyReport(name: name, reportKey: reportKey)
160 }
161 }
162
163 private func flushViewBodyReport(name: String, reportKey: String) {
164 scheduledViewBodyReports.remove(reportKey)
165 let count = viewBodyCounts.removeValue(forKey: reportKey) ?? 0
166 guard count > 0 else { return }
167 let detail = viewBodyDetails.removeValue(forKey: reportKey) ?? ""
168 let countDetail = detail.isEmpty ? "count=\(count)" : "count=\(count) \(detail)"
169 note("\(name).body", detail: countDetail)
170 }
171
172 private static func milliseconds(from duration: Duration) -> Double {
173 Double(duration.components.seconds) * 1000
174 + Double(duration.components.attoseconds) / 1_000_000_000_000_000
175 }
176}
177
178struct EventLogEntry: Identifiable, Sendable, Codable {
179 var id = UUID()
180 let timestamp: Date
181 let level: String
182 let message: String
183}
184
185
186
187
188
189
190
191
192
193
194@MainActor
195enum LogScrubber {
196 private static let uuid =
197 /[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/
198
199
200
201
202
203 private static let hexToken = /_?[0-9A-Fa-f]{32,}/
204
205
206 private static let shareURLToken = /(icloud\.com\/share\/)([A-Za-z0-9._~-]{9,})/
207
208 static func scrub(_ message: String) -> String {
209 var result = message
210 result = result.replacing(uuid) { "\($0.output.prefix(8))…" }
211 result = result.replacing(hexToken) { match in
212 let keep = match.output.hasPrefix("_") ? 9 : 8
213 return "\(match.output.prefix(keep))…"
214 }
215 result = result.replacing(shareURLToken) { "\($0.output.1)\($0.output.2.prefix(8))…" }
216 return result
217 }
218}
219
220
221
222
223
224
225actor EventLogStore {
226 private let fileURL: URL
227
228 init(filename: String = "event-log.json") {
229 let dir = FileManager.default
230 .urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
231 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
232 self.fileURL = dir.appendingPathComponent(filename)
233 }
234
235 func load() -> [EventLogEntry] {
236 guard let data = try? Data(contentsOf: fileURL),
237 let entries = try? JSONDecoder().decode([EventLogEntry].self, from: data)
238 else { return [] }
239 return entries
240 }
241
242
243
244
245
246 func persist(_ entries: [EventLogEntry]) {
247 guard let data = try? JSONEncoder().encode(entries) else { return }
248 try? data.write(to: fileURL, options: .atomic)
249 }
250}
251
252
253
254
255
256
257
258
259
260@MainActor
261@Observable
262final class EventLog {
263 private(set) var entries: [EventLogEntry] = []
264
265
266
267
268
269
270
271
272
273 private let retention: TimeInterval = 60 * 60 * 24
274
275
276
277
278
279 private let maxEntries = 30_000
280
281 private let store: EventLogStore
282
283
284
285
286
287
288
289
290 @ObservationIgnored private let systemLog = Logger(
291 subsystem: Bundle.main.bundleIdentifier ?? "Crossmate",
292 category: "events"
293 )
294
295
296
297
298 private var hydrated = false
299 private var flushTask: Task<Void, Never>?
300
301 init(store: EventLogStore = EventLogStore()) {
302 self.store = store
303 }
304
305
306
307
308 func loadPersisted() async {
309 let persisted = await store.load()
310 entries = (persisted + entries).sorted { $0.timestamp < $1.timestamp }
311 prune(now: Date())
312 hydrated = true
313 scheduleFlush()
314 }
315
316 func note(_ message: String, level: String = "info") {
317 append(level: level, message)
318 }
319
320 fileprivate func append(level: String, _ message: String) {
321 let message = LogScrubber.scrub(message)
322 switch level {
323 case "error":
324 systemLog.error("\(message, privacy: .public)")
325 case "warn":
326 systemLog.warning("\(message, privacy: .public)")
327 default:
328 systemLog.info("\(message, privacy: .public)")
329 }
330 let now = Date()
331 entries.append(EventLogEntry(timestamp: now, level: level, message: message))
332 prune(now: now)
333 scheduleFlush()
334 }
335
336
337
338
339 private func scheduleFlush() {
340 guard hydrated else { return }
341 flushTask?.cancel()
342 flushTask = Task { [weak self] in
343 try? await Task.sleep(for: .seconds(2))
344 guard !Task.isCancelled, let self else { return }
345 await self.store.persist(self.entries)
346 }
347 }
348
349
350
351 func flush() async {
352 guard hydrated else { return }
353 flushTask?.cancel()
354 await store.persist(entries)
355 }
356
357
358
359
360
361
362
363 private func prune(now: Date) {
364 let cutoff = now.addingTimeInterval(-retention)
365 if let firstFresh = entries.firstIndex(where: { $0.timestamp >= cutoff }), firstFresh > 0 {
366 entries.removeFirst(firstFresh)
367 }
368 if entries.count > maxEntries {
369 entries.removeFirst(entries.count - maxEntries)
370 }
371 }
372}
373
374@MainActor
375@Observable
376final class SyncMonitor {
377 private(set) var lastSuccessAt: Date?
378 private(set) var lastErrorPhase: String?
379 private(set) var lastErrorDomain: String?
380 private(set) var lastErrorCode: Int?
381 private(set) var lastErrorDescription: String?
382 private(set) var snapshot: SyncEngine.DiagnosticSnapshot?
383
384 private let log: EventLog
385
386 init(log: EventLog) {
387 self.log = log
388 }
389
390 func recordStart(_ phase: String) {
391 log.append(level: "info", "starting \(phase)")
392 }
393
394 func recordSuccess(_ phase: String) {
395 lastSuccessAt = Date()
396
397
398
399
400 if lastErrorPhase == phase {
401 clearLastError()
402 }
403 log.append(level: "info", "\(phase) succeeded")
404 }
405
406 func recordError(_ phase: String, _ error: Error) {
407 let nsError = error as NSError
408 lastErrorPhase = phase
409 lastErrorDomain = nsError.domain
410 lastErrorCode = nsError.code
411
412
413
414 lastErrorDescription = LogScrubber.scrub(nsError.localizedDescription)
415 let userInfoSummary = nsError.userInfo
416 .map { "\($0.key)=\($0.value)" }
417 .joined(separator: " | ")
418 let message = "\(phase) failed: domain=\(nsError.domain) code=\(nsError.code) \(nsError.localizedDescription) | userInfo: \(userInfoSummary)"
419 log.append(level: "error", message)
420 }
421
422 func note(_ message: String) {
423 log.note(message)
424 }
425
426
427
428
429
430
431
432
433 func noteSuccess() {
434 lastSuccessAt = Date()
435 clearLastError()
436 }
437
438 func updateSnapshot(_ snapshot: SyncEngine.DiagnosticSnapshot) {
439 self.snapshot = snapshot
440 }
441
442 func clearLastError() {
443 lastErrorPhase = nil
444 lastErrorDomain = nil
445 lastErrorCode = nil
446 lastErrorDescription = nil
447 }
448
449 func run(_ phase: String, _ body: @Sendable () async throws -> Void) async {
450 recordStart(phase)
451 do {
452 try await body()
453 recordSuccess(phase)
454 } catch {
455 recordError(phase, error)
456 }
457 }
458
459 func run<T: Sendable>(_ phase: String, _ body: @Sendable () async throws -> T) async -> T? {
460 recordStart(phase)
461 do {
462 let result = try await body()
463 recordSuccess(phase)
464 return result
465 } catch {
466 recordError(phase, error)
467 return nil
468 }
469 }
470}