HealthProbe / HealthProbe / ContentView.swift
1 contributor
74 lines | 2.624kb
import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @AppStorage(AppSettings.typeDetailCacheBackfillVersionKey)
    private var typeDetailCacheBackfillVersion: Int = 0
    @State private var didAttemptTypeDetailCacheBackfill = false

    var body: some View {
        TabView {
            Tab("Dashboard", systemImage: "waveform.path.ecg") {
                DashboardView()
            }
            Tab("Snapshots", systemImage: "clock.arrow.circlepath") {
                SnapshotsView()
            }
            Tab("Data Types", systemImage: "doc.text.magnifyingglass") {
                DataTypesView()
            }
            Tab("Settings", systemImage: "gearshape") {
                SettingsView()
            }
        }
        .task {
            await rebuildTypeDetailCachesIfNeeded()
        }
    }

    @MainActor
    private func rebuildTypeDetailCachesIfNeeded() async {
        guard !didAttemptTypeDetailCacheBackfill,
              typeDetailCacheBackfillVersion < AppSettings.currentTypeDetailCacheBackfillVersion else {
            return
        }
        didAttemptTypeDetailCacheBackfill = true

        try? await Task.sleep(for: .seconds(2))
        MemoryLog.log("typeDetailCacheBackfill.begin", metadata: [
            "storedVersion": "\(typeDetailCacheBackfillVersion)",
            "targetVersion": "\(AppSettings.currentTypeDetailCacheBackfillVersion)"
        ])
        let memoryPulse = MemoryLog.startPulse("typeDetailCacheBackfill", metadata: [
            "maxTypeCounts": "1"
        ])
        defer {
            memoryPulse.cancel()
            MemoryLog.log("typeDetailCacheBackfill.end", metadata: [
                "storedVersion": "\(typeDetailCacheBackfillVersion)"
            ])
        }

        do {
            let isComplete = try SnapshotLifecycleService.rebuildMissingDetailCaches(
                context: modelContext,
                maxTypeCounts: 1
            )
            MemoryLog.log("typeDetailCacheBackfill.result", metadata: [
                "isComplete": "\(isComplete)"
            ])
            if isComplete {
                typeDetailCacheBackfillVersion = AppSettings.currentTypeDetailCacheBackfillVersion
            }
        } catch {
            assertionFailure("Failed to rebuild type detail caches: \(error)")
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: [HealthSnapshot.self, TypeCount.self, YearlyCount.self, HealthRecord.self, TypeDistributionBin.self, DeviceProfile.self], inMemory: true)
        .environment(AppSettings())
}