WatchHealthObserverUploader.swift 28.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
import Foundation
import HealthKit

enum WatchHealthUploadConfiguration {
    /// Process-lifetime throttle. Each health data type can start at most one
    /// upload request during this interval.
    static let minimumTriggerInterval: TimeInterval = 60
}

private actor WatchHealthUploadQueue {
    func run(_ operation: @escaping () async throws -> Void) async throws {
        try await operation()
    }
}

private actor WatchHealthUploadThrottle {
    private var lastTriggerDates: [Int: Date] = [:]

    func acquire(dataType: Int, now: Date = Date()) -> Bool {
        if let lastDate = lastTriggerDates[dataType],
           now.timeIntervalSince(lastDate) < WatchHealthUploadConfiguration.minimumTriggerInterval {
            return false
        }
        lastTriggerDates[dataType] = now
        return true
    }
}

/// Owns Watch HealthKit observers and keeps the observer completion alive until
/// the corresponding server upload has finished.
final class WatchHealthObserverUploader {
    static let shared = WatchHealthObserverUploader()

    private let healthStore = HKHealthStore()
    private let healthService = HealthService()
    private var observers: [HKObserverQuery] = []
    private var uploadHandlers: [() async throws -> Void] = []
    private let uploadQueue = WatchHealthUploadQueue()
    private var uploadTimeCache: WatchHealthUploadTimeList?
    private var uploadTimeCacheDate: Date?
    private var uploadTimeCacheUserId: Int?
    private var hasStarted = false
    private let uploadThrottle = WatchHealthUploadThrottle()

    private init() {}

    @MainActor
    func startObserversIfNeeded() {
        guard HKHealthStore.isHealthDataAvailable() else { return }
        guard !hasStarted else { return }
        hasStarted = true

        registerQuantity(.heartRate, dataType: .heartRate,
                         unit: HKUnit.count().unitDivided(by: .minute()))
        registerQuantity(.heartRateVariabilitySDNN, dataType: .hrv,
                         unit: .secondUnit(with: .milli))
        registerDailyCumulative(.stepCount, dataType: .steps, unit: .count())
        registerQuantity(.oxygenSaturation, dataType: .spo2, unit: .percent(), multiplier: 100)
        registerDailyCumulative(.activeEnergyBurned, dataType: .move, unit: .kilocalorie(), uploadsTarget: true)
        registerDailyCumulative(.appleExerciseTime, dataType: .exercise, unit: .second(), uploadsTarget: true)
        registerStand()
        registerQuantity(.walkingHeartRateAverage, dataType: .walkingHeartRate,
                         unit: HKUnit.count().unitDivided(by: .minute()))
        registerQuantity(.restingHeartRate, dataType: .restingHeartRate,
                         unit: HKUnit.count().unitDivided(by: .minute()))
        registerQuantity(.appleSleepingWristTemperature, dataType: .sleepingWristTemperature,
                         unit: .degreeCelsius())
        registerQuantity(.respiratoryRate, dataType: .respiratoryRate,
                         unit: HKUnit.count().unitDivided(by: .minute()))
        registerIrregularRhythm()
        registerSleep()
    }

    func performFullUpload() {
        Task { await uploadPendingChanges() }
    }

    private func registerQuantity(
        _ identifier: HKQuantityTypeIdentifier,
        dataType: HealthDataType,
        unit: HKUnit,
        multiplier: Double = 1
    ) {
        guard let sampleType = HKObjectType.quantityType(forIdentifier: identifier) else { return }
        register(sampleType, widgetDataType: dataType) { [weak self] in
            guard let self else { return }
            try await self.processQuantityChanges(type: sampleType, dataType: dataType.rawValue) { samples in
                samples.forEach { sample in
                    self.debugLogCommonUpload(
                        dataType: dataType.rawValue,
                        time: sample.endDate,
                        value: sample.quantity.doubleValue(for: unit) * multiplier
                    )
                }
                let body = samples.map {
                    [
                        "data_type": dataType.rawValue,
                        "time": $0.endDate.timeIntervalSince1970,
                        "value": $0.quantity.doubleValue(for: unit) * multiplier,
                    ] as [String: Any]
                }
                try await self.uploadCommonBatches(body)
            }
            await MainActor.run {
                switch dataType {
                case .hrv:
                    WatchDataManager.share.getLatestHealthData()
                default:
                    break
                }
            }
        }
    }

    private func registerDailyCumulative(
        _ identifier: HKQuantityTypeIdentifier,
        dataType: HealthDataType,
        unit: HKUnit,
        uploadsTarget: Bool = false
    ) {
        guard let sampleType = HKObjectType.quantityType(forIdentifier: identifier) else { return }
        register(sampleType, widgetDataType: dataType) { [weak self] in
            guard let self else { return }
            let days = try await self.cumulativeUploadDays(
                type: sampleType,
                dataType: dataType.rawValue
            )
            var body: [[String: Any]] = []
            var uploadLogs: [(time: Date, value: Double)] = []
            for day in days {
                let value = try await self.dailyCumulative(type: sampleType, unit: unit, day: day.day)
                uploadLogs.append((day.latestSampleTime, value))
                body.append([
                    "data_type": dataType.rawValue,
                    "time": day.latestSampleTime.timeIntervalSince1970,
                    "value": value,
                ])
            }
            guard !body.isEmpty,
                  await self.allowUploadTrigger(for: dataType.rawValue) else { return }
            uploadLogs.forEach {
                self.debugLogCommonUpload(dataType: dataType.rawValue, time: $0.time, value: $0.value)
            }
            try await self.uploadCommonBatches(body)
            if uploadsTarget {
                try await self.uploadTodayActivityTarget()
            }
        }
    }

    private func registerStand() {
        guard let type = HKObjectType.quantityType(forIdentifier: .appleStandTime) else { return }
        register(type, widgetDataType: .stand) { [weak self] in
            guard let self else { return }
            let days = try await self.cumulativeUploadDays(
                type: type,
                dataType: HealthDataType.stand.rawValue
            )
            var body: [[String: Any]] = []
            var uploadLogs: [(time: Date, value: Double)] = []
            for day in days {
                guard let summary = try await self.activitySummary(for: day.day) else { continue }
                let value = summary.appleStandHours.doubleValue(for: .count())
                uploadLogs.append((day.latestSampleTime, value))
                body.append([
                    "data_type": HealthDataType.stand.rawValue,
                    "time": day.latestSampleTime.timeIntervalSince1970,
                    "value": value,
                ])
            }
            guard !body.isEmpty,
                  await self.allowUploadTrigger(for: HealthDataType.stand.rawValue) else { return }
            uploadLogs.forEach {
                self.debugLogCommonUpload(
                    dataType: HealthDataType.stand.rawValue,
                    time: $0.time,
                    value: $0.value
                )
            }
            try await self.uploadCommonBatches(body)
            try await self.uploadTodayActivityTarget()
        }
    }

    private func registerIrregularRhythm() {
        guard let type = HKObjectType.categoryType(forIdentifier: .irregularHeartRhythmEvent) else { return }
        register(type) { [weak self] in
            guard let self else { return }
            let dataType = HealthDataType.irregularHeartRhythm.rawValue
            try await self.processCategoryChanges(type: type, dataType: dataType) { samples in
                samples.forEach { sample in
                    self.debugLogCommonUpload(
                        dataType: dataType,
                        time: sample.endDate,
                        value: Double(sample.value)
                    )
                }
                let body = samples.map {
                    [
                        "data_type": HealthDataType.irregularHeartRhythm.rawValue,
                        "time": $0.endDate.timeIntervalSince1970,
                        "value": $0.value,
                    ] as [String: Any]
                }
                try await self.uploadCommonBatches(body)
            }
        }
    }

    private func registerSleep() {
        guard let type = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else { return }
        register(type) { [weak self] in
            guard let self else { return }
            try await self.processCategoryChanges(type: type, dataType: 100) { samples in
                samples.forEach { sample in
                    self.debugLogSleepUpload(sample)
                }
                let body = samples.map {
                    [
                        "data_type": $0.value,
                        "from_time": $0.startDate.timeIntervalSince1970,
                        "to_time": $0.endDate.timeIntervalSince1970,
                    ] as [String: Any]
                }
                try await self.uploadSleepBatches(body)
                try await self.uploadSleepingHeartRates(for: samples)
            }
            await MainActor.run { WatchDataManager.share.fetchMyTodayData() }
        }
    }

    private func register(
        _ sampleType: HKSampleType,
        widgetDataType: HealthDataType? = nil,
        handler: @escaping () async throws -> Void
    ) {
        uploadHandlers.append(handler)
        let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { _, completion, error in
            guard error == nil else {
                #if DEBUG
                DebugLogger.debugLog("[WatchHealthObserver] \(sampleType.identifier) observer error: \(error!.localizedDescription)")
                #endif
                completion()
                return
            }

            Task {
                if let widgetDataType {
                    await MainActor.run {
                        WatchHealthWidgetRefreshCoordinator.shared.refresh(for: widgetDataType)
                    }
                }
                guard self.hasValidLogin else {
                    #if DEBUG
                    DebugLogger.debugLog("[WatchHealthObserver] \(sampleType.identifier) widget refreshed; upload skipped because user is not logged in")
                    #endif
                    completion()
                    return
                }
                do {
                    try await self.uploadQueue.run(handler)
                    #if DEBUG
                    DebugLogger.debugLog("[WatchHealthObserver] \(sampleType.identifier) upload completed")
                    #endif
                } catch {
                    DebugLogger.debugLog("[WatchHealthObserver] \(sampleType.identifier) upload failed: \(error.localizedDescription)")
                }
                completion()
            }
        }
        observers.append(query)
        healthStore.execute(query)
        healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { success, error in
            if let error {
                DebugLogger.debugLog("[WatchHealthObserver] \(sampleType.identifier) background delivery failed: \(error.localizedDescription)")
            } else if !success {
                DebugLogger.debugLog("[WatchHealthObserver] \(sampleType.identifier) background delivery was not enabled")
            }
        }
    }

    private func uploadPendingChanges() async {
        guard hasValidLogin else {
            #if DEBUG
            DebugLogger.debugLog("[WatchHealthObserver] pending upload skipped, user is not logged in")
            #endif
            return
        }
        for handler in uploadHandlers {
            do {
                try await uploadQueue.run(handler)
            } catch {
                DebugLogger.debugLog("[WatchHealthObserver] pending upload failed: \(error.localizedDescription)")
            }
        }
    }

    private func processQuantityChanges(
        type: HKQuantityType,
        dataType: Int,
        upload: @escaping ([HKQuantitySample]) async throws -> Void
    ) async throws {
        let startDate = try await serverUploadStartDate(for: dataType)
        let predicate = uploadPredicate(startDate: startDate)
        // The anchor is intentionally in-memory only and is used solely to
        // page this query. The next upload boundary always comes from server.
        var anchor: HKQueryAnchor?
        var acquiredTrigger = false
        while true {
            let page: ([HKQuantitySample], HKQueryAnchor) = try await anchoredPage(
                type: type,
                predicate: predicate,
                anchor: anchor
            )
            let newSamples = page.0.filter { $0.endDate > startDate }
            debugLogTimeComparison(
                dataType: dataType,
                serverTime: startDate,
                newestTime: newSamples.map(\.endDate).max()
            )
            if !newSamples.isEmpty {
                if !acquiredTrigger {
                    guard await allowUploadTrigger(for: dataType) else { return }
                    acquiredTrigger = true
                }
                try await upload(newSamples)
            }
            anchor = page.1
            if page.0.count < 200 { return }
        }
    }

    private struct CumulativeUploadDay {
        let day: Date
        let latestSampleTime: Date
    }

    private func cumulativeUploadDays(
        type: HKQuantityType,
        dataType: Int
    ) async throws -> [CumulativeUploadDay] {
        let calendar = Calendar.current
        let serverStartDate = try await serverUploadStartDate(for: dataType)
        let queryStartDate = calendar.startOfDay(for: serverStartDate)
        let predicate = uploadPredicate(startDate: queryStartDate)
        var latestSampleTimeByDay: [Date: Date] = [:]
        var anchor: HKQueryAnchor?

        while true {
            let page: ([HKQuantitySample], HKQueryAnchor) = try await anchoredPage(
                type: type,
                predicate: predicate,
                anchor: anchor
            )
            for sample in page.0 where sample.endDate > serverStartDate {
                let day = calendar.startOfDay(for: sample.startDate)
                latestSampleTimeByDay[day] = max(
                    latestSampleTimeByDay[day] ?? .distantPast,
                    sample.endDate
                )
            }
            anchor = page.1
            if page.0.count < 200 { break }
        }

        // Upload chronologically. If a later batch fails, the server cursor
        // remains on the last successful historical day instead of jumping to
        // today and permanently skipping the remaining backlog.
        let result = latestSampleTimeByDay
            .map { CumulativeUploadDay(day: $0.key, latestSampleTime: $0.value) }
            .sorted { $0.latestSampleTime < $1.latestSampleTime }
        debugLogTimeComparison(
            dataType: dataType,
            serverTime: serverStartDate,
            newestTime: result.map(\.latestSampleTime).max()
        )
        return result
    }

    private func processCategoryChanges(
        type: HKCategoryType,
        dataType: Int,
        upload: @escaping ([HKCategorySample]) async throws -> Void
    ) async throws {
        let startDate = try await serverUploadStartDate(for: dataType)
        let predicate = uploadPredicate(startDate: startDate)
        // The anchor is intentionally in-memory only and is used solely to
        // page this query. The next upload boundary always comes from server.
        var anchor: HKQueryAnchor?
        var acquiredTrigger = false
        while true {
            let page: ([HKCategorySample], HKQueryAnchor) = try await anchoredPage(
                type: type,
                predicate: predicate,
                anchor: anchor
            )
            let newSamples = page.0.filter { $0.endDate > startDate }
            debugLogTimeComparison(
                dataType: dataType,
                serverTime: startDate,
                newestTime: newSamples.map(\.endDate).max()
            )
            if !newSamples.isEmpty {
                if !acquiredTrigger {
                    guard await allowUploadTrigger(for: dataType) else { return }
                    acquiredTrigger = true
                }
                try await upload(newSamples)
            }
            anchor = page.1
            if page.0.count < 200 { return }
        }
    }

    private func anchoredPage<T: HKSample>(
        type: HKSampleType,
        predicate: NSPredicate,
        anchor: HKQueryAnchor?
    ) async throws -> ([T], HKQueryAnchor) {
        try await withCheckedThrowingContinuation { continuation in
            let query = HKAnchoredObjectQuery(
                type: type,
                predicate: predicate,
                anchor: anchor,
                limit: 200
            ) { _, samples, _, newAnchor, error in
                if let error { continuation.resume(throwing: error) }
                else if let newAnchor {
                    continuation.resume(returning: (samples as? [T] ?? [], newAnchor))
                } else {
                    continuation.resume(throwing: WatchHealthObserverError.missingAnchor)
                }
            }
            healthStore.execute(query)
        }
    }

    private func dailyCumulative(type: HKQuantityType, unit: HKUnit, day: Date) async throws -> Double {
        let calendar = Calendar.current
        let start = calendar.startOfDay(for: day)
        let nextDay = calendar.date(byAdding: .day, value: 1, to: start) ?? Date()
        let end = min(nextDay, Date())
        let predicate = HKQuery.predicateForSamples(
            withStart: start, end: end, options: .strictStartDate
        )
        return try await withCheckedThrowingContinuation { continuation in
            let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: .cumulativeSum) {
                _, result, error in
                if let error { continuation.resume(throwing: error) }
                else { continuation.resume(returning: result?.sumQuantity()?.doubleValue(for: unit) ?? 0) }
            }
            healthStore.execute(query)
        }
    }

    private func todayActivitySummary() async throws -> HKActivitySummary? {
        try await activitySummary(for: Date())
    }

    private func activitySummary(for date: Date) async throws -> HKActivitySummary? {
        let calendar = Calendar.current
        var day = calendar.dateComponents([.era, .year, .month, .day], from: date)
        day.calendar = calendar
        let predicate = HKQuery.predicate(forActivitySummariesBetweenStart: day, end: day)
        return try await withCheckedThrowingContinuation { continuation in
            let query = HKActivitySummaryQuery(predicate: predicate) { _, summaries, error in
                if let error { continuation.resume(throwing: error) }
                else { continuation.resume(returning: summaries?.last) }
            }
            healthStore.execute(query)
        }
    }

    private func uploadTodayActivityTarget() async throws {
        guard let summary = try await todayActivitySummary() else { return }
        try await uploadActivityTarget(summary)
    }

    private func uploadSleepingHeartRates(for sleepSamples: [HKCategorySample]) async throws {
        let dataType = HealthDataType.sleepingHeartRate.rawValue
        let serverStartDate = try await serverUploadStartDate(for: dataType)
        let asleepIntervals = sleepSamples.filter {
            guard let value = HKCategoryValueSleepAnalysis(rawValue: $0.value) else { return false }
            switch value {
            case .asleepUnspecified, .asleepCore, .asleepDeep, .asleepREM:
                return true
            default:
                return false
            }
        }
        guard let start = asleepIntervals.map(\.startDate).min(),
              let end = asleepIntervals.map(\.endDate).max(),
              let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate) else {
            return
        }

        let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: [])
        let heartRates: [HKQuantitySample] = try await withCheckedThrowingContinuation { continuation in
            let query = HKSampleQuery(
                sampleType: heartRateType,
                predicate: predicate,
                limit: HKObjectQueryNoLimit,
                sortDescriptors: nil
            ) { _, samples, error in
                if let error { continuation.resume(throwing: error) }
                else { continuation.resume(returning: samples as? [HKQuantitySample] ?? []) }
            }
            healthStore.execute(query)
        }
        let sleepingHeartRates = heartRates.filter { sample in
            sample.endDate > serverStartDate && asleepIntervals.contains { interval in
                sample.startDate < interval.endDate && sample.endDate > interval.startDate
            }
        }.sorted { $0.endDate < $1.endDate }
        guard !sleepingHeartRates.isEmpty else { return }
        guard await allowUploadTrigger(for: dataType) else { return }
        let unit = HKUnit.count().unitDivided(by: .minute())
        let body = sleepingHeartRates.map {
            [
                "data_type": HealthDataType.sleepingHeartRate.rawValue,
                "time": $0.endDate.timeIntervalSince1970,
                "value": $0.quantity.doubleValue(for: unit),
            ] as [String: Any]
        }
        sleepingHeartRates.forEach { sample in
            debugLogCommonUpload(
                dataType: dataType,
                time: sample.endDate,
                value: sample.quantity.doubleValue(for: unit)
            )
        }
        try await uploadCommonBatches(body)
    }

    private func uploadActivityTarget(_ summary: HKActivitySummary) async throws {
        var body: [String: Any] = [
            "move": Int(summary.activeEnergyBurnedGoal.doubleValue(for: .kilocalorie())),
            "stand": Int(summary.appleStandHoursGoal.doubleValue(for: .count())),
            "active_energy_burned": summary.activeEnergyBurned.doubleValue(for: .kilocalorie()),
            "active_energy_burned_goal": summary.activeEnergyBurnedGoal.doubleValue(for: .kilocalorie()),
            "apple_exercise_time": summary.appleExerciseTime.doubleValue(for: .second()),
            "apple_exercise_time_goal": summary.appleExerciseTimeGoal.doubleValue(for: .second()),
            "apple_stand_hours": summary.appleStandHours.doubleValue(for: .count()),
            "apple_stand_hours_goal": summary.appleStandHoursGoal.doubleValue(for: .count()),
        ]
        body["activity_move_mode"] = summary.activityMoveMode.rawValue
        body["apple_move_time"] = summary.appleMoveTime.doubleValue(for: .second())
        body["apple_move_time_goal"] = summary.appleMoveTimeGoal.doubleValue(for: .second())
        body["exercise_time_goal"] = summary.exerciseTimeGoal?.doubleValue(for: .second())
        body["stand_hours_goal"] = summary.standHoursGoal?.doubleValue(for: .count())
        _ = try await healthService.uploadActivityTarget(data: body)
    }

    private func serverUploadStartDate(for dataType: Int) async throws -> Date {
        let list = try await serverUploadTimes()
        if let date = list.latestDate(for: dataType) {
            #if DEBUG
            DebugLogger.debugLog("[WatchHealthUpload][server-time] dataType=\(dataType), time=\(debugTimestamp(date)), unix=\(Int64(date.timeIntervalSince1970))")
            #endif
            return date
        }

        let fallback = Calendar.current.date(byAdding: .year, value: -2, to: Date())
            ?? Date(timeIntervalSinceNow: -2 * 365 * 24 * 60 * 60)
        let date = Calendar.current.startOfDay(for: fallback)
        #if DEBUG
            DebugLogger.debugLog("[WatchHealthUpload][server-time] dataType=\(dataType), missing=true, fallback=\(debugTimestamp(date)), unix=\(Int64(date.timeIntervalSince1970))")
        #endif
        return date
    }

    private func serverUploadTimes() async throws -> WatchHealthUploadTimeList {
        let userId = currentUserId
        if let uploadTimeCache,
           let uploadTimeCacheDate,
           uploadTimeCacheUserId == userId,
           Date().timeIntervalSince(uploadTimeCacheDate) < 5 {
            return uploadTimeCache
        }
        let result = try await healthService.getUploadTimes()
        uploadTimeCache = result
        uploadTimeCacheDate = Date()
        uploadTimeCacheUserId = userId
        return result
    }

    private func uploadPredicate(startDate: Date) -> NSPredicate {
        HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: [])
    }

    private func uploadCommonBatches(_ data: [[String: Any]]) async throws {
        for start in stride(from: 0, to: data.count, by: 200) {
            _ = try await healthService.uploadBatch(data: Array(data[start..<min(start + 200, data.count)]))
        }
    }

    private func allowUploadTrigger(for dataType: Int) async -> Bool {
        let allowed = await uploadThrottle.acquire(dataType: dataType)
        #if DEBUG
        if !allowed {
            DebugLogger.debugLog(
                "[WatchHealthUpload][throttle] dataType=\(dataType), skipped=true, interval=\(Int(WatchHealthUploadConfiguration.minimumTriggerInterval))s, now=\(debugTimestamp(Date()))"
            )
        }
        #endif
        return allowed
    }

    private func uploadSleepBatches(_ data: [[String: Any]]) async throws {
        for start in stride(from: 0, to: data.count, by: 200) {
            _ = try await healthService.uploadSleep(data: Array(data[start..<min(start + 200, data.count)]))
        }
    }

    private static let debugDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter
    }()
    private static let debugDateFormatterLock = NSLock()

    private func debugTimestamp(_ date: Date) -> String {
        Self.debugDateFormatterLock.lock()
        defer { Self.debugDateFormatterLock.unlock() }
        return Self.debugDateFormatter.string(from: date)
    }

    private func debugLogTimeComparison(
        dataType: Int,
        serverTime: Date,
        newestTime: Date?
    ) {
        #if DEBUG || CI_ENV
        let newestDescription = newestTime.map {
            "\(debugTimestamp($0)) (unix=\(Int64($0.timeIntervalSince1970)))"
        } ?? "<none>"
        DebugLogger.debugLog(
            "[WatchHealthUpload][time-check] dataType=\(dataType), server=\(debugTimestamp(serverTime)) (unix=\(Int64(serverTime.timeIntervalSince1970))), newest=\(newestDescription), shouldUpload=\(newestTime.map { $0 > serverTime } ?? false)"
        )
        #endif
    }

    private func debugLogCommonUpload(dataType: Int, time: Date, value: Double) {
        #if DEBUG || CI_ENV
        DebugLogger.debugLog(
            "[WatchHealthUpload][upload] dataType=\(dataType), time=\(debugTimestamp(time)), unix=\(Int64(time.timeIntervalSince1970)), value=\(value)"
        )
        #endif
    }

    private func debugLogSleepUpload(_ sample: HKCategorySample) {
        #if DEBUG || CI_ENV
        DebugLogger.debugLog(
            "[WatchHealthUpload][upload][sleep] dataType=\(sample.value), from=\(debugTimestamp(sample.startDate)), fromUnix=\(Int64(sample.startDate.timeIntervalSince1970)), to=\(debugTimestamp(sample.endDate)), toUnix=\(Int64(sample.endDate.timeIntervalSince1970))"
        )
        #endif
    }

    private var hasValidLogin: Bool {
        guard let data = AppGroupConstants.defaults?.data(forKey: AppGroupConstants.Key.myUserInfo),
              let login = try? JSONDecoder().decode(UserInfoModel.self, from: data),
              let token = login.token else {
            return false
        }
        return !token.isEmpty
    }

    private var currentUserId: Int {
        guard let data = AppGroupConstants.defaults?.data(forKey: AppGroupConstants.Key.myUserInfo),
              let login = try? JSONDecoder().decode(UserInfoModel.self, from: data) else {
            return 0
        }
        return login.userId ?? 0
    }
}

private enum WatchHealthObserverError: Error {
    case missingAnchor
}