AnchoredHealthDataReader.swift 19 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
import Foundation
import HealthKit

struct AnchoredHealthCommonReadResult {
  let data: [NativeHealthDataPoint]
  let anchors: [NativeHealthDataType: Data]
}

struct AnchoredHealthSleepReadResult {
  let data: [NativeSleepInterval]
  let anchor: Data
}

struct AnchoredHealthActivityAnchorBundle: Codable {
  let activeEnergy: Data
  let exercise: Data
  let stand: Data
}

struct AnchoredHealthActivityReadResult {
  let data: [NativeHealthDataPoint]
  let targets: [NativeActivityTarget]
  let anchors: AnchoredHealthActivityAnchorBundle
}

/// Reads HealthKit changes with HKQueryAnchor and converts them to the same
/// upload payload models used by the existing uploader.
final class AnchoredHealthDataReader {
  private let service: HealthKitService
  private let anchorStore: AnchoredHealthUploadAnchorStore
  private let userIdProvider: () -> Int?

  init(
    service: HealthKitService = .shared,
    anchorStore: AnchoredHealthUploadAnchorStore = AnchoredHealthUploadAnchorStore(),
    userIdProvider: @escaping () -> Int? = { AppShared.shared.userId }
  ) {
    self.service = service
    self.anchorStore = anchorStore
    self.userIdProvider = userIdProvider
  }

  func readAllCommon() async throws -> AnchoredHealthCommonReadResult {
    try await readCommon(dataTypes: nil)
  }

  func readCommon(
    dataTypes requestedTypes: Set<NativeHealthDataType>?
  ) async throws -> AnchoredHealthCommonReadResult {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }

    var data: [NativeHealthDataPoint] = []
    var anchors: [NativeHealthDataType: Data] = [:]
    let types = requestedTypes.map { requestedTypes in
      Self.commonDataTypes.filter { requestedTypes.contains($0) }
    } ?? Self.commonDataTypes

    for type in types {
      let storedAnchorData = anchorStore.data(userId: userId, dataType: type)
      Self.log(
        "reader.common.anchor.before userId=\(userId) dataType=\(type.rawValue) \(Self.describeAnchorData(storedAnchorData)) initialStart=\(Self.debugTimestamp(firstUploadStartDate().timeIntervalSince1970))"
      )
      let anchor = anchorStore.anchor(userId: userId, dataType: type)
      let changes = try await service.fetchAnchoredChanges(
        for: type,
        sourceIdentifier: Self.sourceIdentifier(for: type),
        anchor: anchor,
        initialStartDate: firstUploadStartDate()
      )
      let archivedAnchor = try SharedHealthAnchoredUploadSupport.archive(changes.newAnchor)
      anchors[type] = archivedAnchor
      Self.log(
        "reader.common.anchor.query userId=\(userId) dataType=\(type.rawValue) source=\(changes.sourceIdentifier) deleted=\(changes.deletedObjectCount) samples=\(changes.samples.count) sampleRange=\(Self.describeSamples(changes.samples)) newAnchor=\(Self.describeAnchorData(archivedAnchor))"
      )

      guard !changes.samples.isEmpty else { continue }
      let startDate = queryStartDate(for: changes.samples)
      let endDate = Date()
      Self.log(
        "reader.common.fetchRange userId=\(userId) dataType=\(type.rawValue) start=\(Self.debugTimestamp(startDate.timeIntervalSince1970)) end=\(Self.debugTimestamp(endDate.timeIntervalSince1970))"
      )
      let points = try await fetchData(type: type, startDate: startDate, endDate: endDate)
      Self.log(
        "reader.common.data userId=\(userId) dataType=\(type.rawValue) count=\(points.count) range=\(Self.describeCommonRange(points))"
      )
      Self.logCommonPoints(points, userId: userId, prefix: "reader.common.data.item")
      data.append(contentsOf: points)
    }

    let sortedData = Self.deduplicateCommon(data).sorted { lhs, rhs in
      if lhs.time == rhs.time {
        return lhs.dataType.rawValue < rhs.dataType.rawValue
      }
      return lhs.time < rhs.time
    }
    Self.log(
      "reader.common.all userId=\(userId) count=\(sortedData.count) range=\(Self.describeCommonRange(sortedData))"
    )
    return AnchoredHealthCommonReadResult(
      data: sortedData,
      anchors: anchors
    )
  }

  func readAllSeelp() async throws -> AnchoredHealthSleepReadResult {
    try await readAllSleep()
  }

  func readActivity() async throws -> AnchoredHealthActivityReadResult {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }

    let storedAnchors = anchorStore.activityAnchors(userId: userId)
    let startLimit = firstUploadStartDate()
    let activeEnergyChanges = try await activityAnchoredChanges(
      userId: userId,
      dataType: .activeEnergy,
      storedAnchorData: storedAnchors?.activeEnergy,
      initialStartDate: startLimit
    )
    let exerciseChanges = try await activityAnchoredChanges(
      userId: userId,
      dataType: .exercise,
      storedAnchorData: storedAnchors?.exercise,
      initialStartDate: startLimit
    )
    let standChanges = try await activityAnchoredChanges(
      userId: userId,
      dataType: .stand,
      storedAnchorData: storedAnchors?.stand,
      initialStartDate: startLimit
    )

    let newAnchors = AnchoredHealthActivityAnchorBundle(
      activeEnergy: try SharedHealthAnchoredUploadSupport.archive(activeEnergyChanges.newAnchor),
      exercise: try SharedHealthAnchoredUploadSupport.archive(exerciseChanges.newAnchor),
      stand: try SharedHealthAnchoredUploadSupport.archive(standChanges.newAnchor)
    )
    let samples = activeEnergyChanges.samples + exerciseChanges.samples + standChanges.samples
    guard !samples.isEmpty else {
      Self.log(
        "reader.activity.all userId=\(userId) count=0 targetCount=0 range=empty anchors=\(Self.describeActivityAnchors(newAnchors))"
      )
      return AnchoredHealthActivityReadResult(data: [], targets: [], anchors: newAnchors)
    }

    let startDate = queryStartDate(for: samples)
    let endDate = Date()
    Self.log(
      "reader.activity.fetchRange userId=\(userId) start=\(Self.debugTimestamp(startDate.timeIntervalSince1970)) end=\(Self.debugTimestamp(endDate.timeIntervalSince1970))"
    )
    let points = try await fetchActivityData(startDate: startDate, endDate: endDate)
    let targets = try await service.fetchActivityTargetDataList(startDate: startDate, endDate: endDate)
    let sortedPoints = Self.deduplicateCommon(points).sorted { lhs, rhs in
      if lhs.time == rhs.time {
        return lhs.dataType.rawValue < rhs.dataType.rawValue
      }
      return lhs.time < rhs.time
    }
    let sortedTargets = targets.sorted {
      ($0.healthValueTimestamp ?? 0) < ($1.healthValueTimestamp ?? 0)
    }
    Self.log(
      "reader.activity.all userId=\(userId) count=\(sortedPoints.count) targetCount=\(sortedTargets.count) range=\(Self.describeCommonRange(sortedPoints)) targetRange=\(Self.describeActivityTargetRange(sortedTargets)) anchors=\(Self.describeActivityAnchors(newAnchors))"
    )
    Self.logCommonPoints(sortedPoints, userId: userId, prefix: "reader.activity.data.item")
    Self.logActivityTargets(sortedTargets, userId: userId, prefix: "reader.activity.target.item")
    return AnchoredHealthActivityReadResult(data: sortedPoints, targets: sortedTargets, anchors: newAnchors)
  }

  func readAllSleep() async throws -> AnchoredHealthSleepReadResult {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }

    let type = NativeHealthDataType.sleep
    let sleepAnchorKey = AnchoredHealthUploadAnchorStore.sleepAnchorKey
    let storedAnchorData = anchorStore.data(userId: userId, anchorKey: sleepAnchorKey)
    Self.log(
      "reader.sleep.anchor.before userId=\(userId) anchorKey=\(sleepAnchorKey) \(Self.describeAnchorData(storedAnchorData)) initialStart=\(Self.debugTimestamp(firstUploadStartDate().timeIntervalSince1970))"
    )
    let anchor = anchorStore.anchor(userId: userId, anchorKey: sleepAnchorKey)
    let changes = try await service.fetchAnchoredChanges(
      for: type,
      sourceIdentifier: Self.sourceIdentifier(for: type),
      anchor: anchor,
      initialStartDate: firstUploadStartDate()
    )

    let archivedAnchor = try SharedHealthAnchoredUploadSupport.archive(changes.newAnchor)
    Self.log(
      "reader.sleep.anchor.query userId=\(userId) anchorKey=\(sleepAnchorKey) source=\(changes.sourceIdentifier) deleted=\(changes.deletedObjectCount) samples=\(changes.samples.count) sampleRange=\(Self.describeSamples(changes.samples)) newAnchor=\(Self.describeAnchorData(archivedAnchor))"
    )
    guard !changes.samples.isEmpty else {
      Self.log("reader.sleep.all userId=\(userId) count=0 range=empty")
      return AnchoredHealthSleepReadResult(data: [], anchor: archivedAnchor)
    }

    let startDate = queryStartDate(for: changes.samples)
    let endDate = Date()
    Self.log(
      "reader.sleep.fetchRange userId=\(userId) start=\(Self.debugTimestamp(startDate.timeIntervalSince1970)) end=\(Self.debugTimestamp(endDate.timeIntervalSince1970))"
    )
    let intervals = try await service.fetchSleepData(startDate: startDate, endDate: endDate)

    let sortedIntervals = Self.deduplicateSleep(intervals).sorted {
      if $0.toTime == $1.toTime {
        return $0.fromTime < $1.fromTime
      }
      return $0.toTime < $1.toTime
    }
    Self.log(
      "reader.sleep.all userId=\(userId) count=\(sortedIntervals.count) range=\(Self.describeSleepRange(sortedIntervals))"
    )
    Self.logSleepIntervals(sortedIntervals, userId: userId, prefix: "reader.sleep.data.item")
    return AnchoredHealthSleepReadResult(
      data: sortedIntervals,
      anchor: archivedAnchor
    )
  }
}

private extension AnchoredHealthDataReader {
  static let commonDataTypes: [NativeHealthDataType] = [
    .hrv,
    .heartRate,
    .walkingHeartRate,
    .restingHeartRate,
    .sleepingHeartRate,
    .oxygenSaturation,
    .steps,
    .sleepingWristTemperature,
    .respiratoryRate,
    .irregularHeartRhythm,
  ]

  static let activityDataTypes: Set<NativeHealthDataType> = [
    .activeEnergy,
    .exercise,
    .stand,
  ]

  func firstUploadStartDate() -> Date {
    let years = NativeHealthUploadConfiguration.firstUploadLookbackYears
    let date = Calendar.current.date(byAdding: .year, value: -years, to: Date())
      ?? Date(timeIntervalSinceNow: -TimeInterval(years * 365 * 24 * 60 * 60))
    return Calendar.current.startOfDay(for: date)
  }

  func queryStartDate(for samples: [HKSample]) -> Date {
    let earliest = samples.map(\.startDate).min() ?? firstUploadStartDate()
    return max(Calendar.current.startOfDay(for: earliest), firstUploadStartDate())
  }

  func fetchData(
    type: NativeHealthDataType,
    startDate: Date,
    endDate: Date
  ) async throws -> [NativeHealthDataPoint] {
    switch type {
    case .hrv:
      return try await service.fetchHrvData(startDate: startDate, endDate: endDate)
    case .heartRate:
      return try await service.fetchHeartRateData(startDate: startDate, endDate: endDate)
    case .walkingHeartRate:
      return try await service.fetchWalkingHeartRateData(startDate: startDate, endDate: endDate)
    case .restingHeartRate:
      return try await service.fetchRestingHeartRateData(startDate: startDate, endDate: endDate)
    case .sleepingHeartRate:
      return try await service.fetchSleepingHeartRateData(startDate: startDate, endDate: endDate)
    case .oxygenSaturation:
      return try await service.fetchOxygenSaturationData(startDate: startDate, endDate: endDate)
    case .activeEnergy:
      return try await service.fetchActiveEnergyData(startDate: startDate, endDate: endDate)
    case .exercise:
      return try await service.fetchExerciseData(startDate: startDate, endDate: endDate)
    case .stand:
      return try await service.fetchStandData(startDate: startDate, endDate: endDate)
    case .steps:
      return try await service.fetchStepCountData(startDate: startDate, endDate: endDate)
    case .sleepingWristTemperature:
      return try await service.fetchSleepingWristTemperatureData(startDate: startDate, endDate: endDate)
    case .respiratoryRate:
      return try await service.fetchRespiratoryRateData(startDate: startDate, endDate: endDate)
    case .irregularHeartRhythm:
      return try await service.fetchIrregularHeartRhythmData(startDate: startDate, endDate: endDate)
    case .unknown, .sleep:
      return []
    }
  }

  func fetchActivityData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
    let activeEnergy = try await service.fetchActiveEnergyData(startDate: startDate, endDate: endDate)
    let exercise = try await service.fetchExerciseData(startDate: startDate, endDate: endDate)
    let stand = try await service.fetchStandData(startDate: startDate, endDate: endDate)
    return activeEnergy + exercise + stand
  }

  func activityAnchoredChanges(
    userId: Int,
    dataType: NativeHealthDataType,
    storedAnchorData: Data?,
    initialStartDate: Date
  ) async throws -> HealthKitService.AnchoredChanges {
    Self.log(
      "reader.activity.anchor.before userId=\(userId) sourceDataType=\(dataType.rawValue) anchorKey=\(AnchoredHealthUploadAnchorStore.activityAnchorKey) \(Self.describeAnchorData(storedAnchorData)) initialStart=\(Self.debugTimestamp(initialStartDate.timeIntervalSince1970))"
    )
    let anchor = storedAnchorData.flatMap {
      try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: $0)
    }
    let changes = try await service.fetchAnchoredChanges(
      for: dataType,
      sourceIdentifier: Self.sourceIdentifier(for: dataType),
      anchor: anchor,
      initialStartDate: initialStartDate
    )
    let archivedAnchor = try SharedHealthAnchoredUploadSupport.archive(changes.newAnchor)
    Self.log(
      "reader.activity.anchor.query userId=\(userId) sourceDataType=\(dataType.rawValue) source=\(changes.sourceIdentifier) deleted=\(changes.deletedObjectCount) samples=\(changes.samples.count) sampleRange=\(Self.describeSamples(changes.samples)) newAnchor=\(Self.describeAnchorData(archivedAnchor))"
    )
    return changes
  }

  static func sourceIdentifier(for type: NativeHealthDataType) -> String {
    switch type {
    case .hrv: return HKQuantityTypeIdentifier.heartRateVariabilitySDNN.rawValue
    case .heartRate, .sleepingHeartRate: return HKQuantityTypeIdentifier.heartRate.rawValue
    case .walkingHeartRate: return HKQuantityTypeIdentifier.walkingHeartRateAverage.rawValue
    case .restingHeartRate: return HKQuantityTypeIdentifier.restingHeartRate.rawValue
    case .oxygenSaturation: return HKQuantityTypeIdentifier.oxygenSaturation.rawValue
    case .activeEnergy: return HKQuantityTypeIdentifier.activeEnergyBurned.rawValue
    case .exercise: return HKQuantityTypeIdentifier.appleExerciseTime.rawValue
    case .stand: return HKQuantityTypeIdentifier.appleStandTime.rawValue
    case .steps: return HKQuantityTypeIdentifier.stepCount.rawValue
    case .sleepingWristTemperature: return HKQuantityTypeIdentifier.appleSleepingWristTemperature.rawValue
    case .respiratoryRate: return HKQuantityTypeIdentifier.respiratoryRate.rawValue
    case .irregularHeartRhythm: return HKCategoryTypeIdentifier.irregularHeartRhythmEvent.rawValue
    case .sleep: return HKCategoryTypeIdentifier.sleepAnalysis.rawValue
    case .unknown: return "unknown"
    }
  }

  static func deduplicateCommon(_ data: [NativeHealthDataPoint]) -> [NativeHealthDataPoint] {
    var seen = Set<String>()
    return data.filter { point in
      let key = "\(point.dataType.rawValue)-\(point.time)-\(point.value)"
      return seen.insert(key).inserted
    }
  }

  static func deduplicateSleep(_ data: [NativeSleepInterval]) -> [NativeSleepInterval] {
    var seen = Set<String>()
    return data.filter { interval in
      let key = "\(interval.dataType)-\(interval.fromTime)-\(interval.toTime)"
      return seen.insert(key).inserted
    }
  }

  static func log(_ message: String) {
    DebugLogger.debugLog("[ArchUploader] \(message)")
  }

  static func logCommonPoints(
    _ points: [NativeHealthDataPoint],
    userId: Int,
    prefix: String
  ) {
    points.forEach { point in
      log(
        "\(prefix) userId=\(userId) dataType=\(point.dataType.rawValue) time=\(debugTimestamp(point.time)) unix=\(Int64(point.time)) value=\(point.value)"
      )
    }
  }

  static func logSleepIntervals(
    _ intervals: [NativeSleepInterval],
    userId: Int,
    prefix: String
  ) {
    intervals.forEach { interval in
      log(
        "\(prefix) userId=\(userId) dataType=\(interval.dataType) from=\(debugTimestamp(interval.fromTime)) fromUnix=\(Int64(interval.fromTime)) to=\(debugTimestamp(interval.toTime)) toUnix=\(Int64(interval.toTime))"
      )
    }
  }

  static func logActivityTargets(
    _ targets: [NativeActivityTarget],
    userId: Int,
    prefix: String
  ) {
    targets.forEach { target in
      let timestamp = target.healthValueTimestamp ?? 0
      log(
        "\(prefix) userId=\(userId) time=\(debugTimestamp(timestamp)) unix=\(Int64(timestamp)) body=\(target.uploadBodyForDebug)"
      )
    }
  }

  static func describeSamples(_ samples: [HKSample]) -> String {
    guard !samples.isEmpty else { return "empty" }
    let minStart = samples.map(\.startDate).min() ?? .distantPast
    let maxEnd = samples.map(\.endDate).max() ?? .distantPast
    return "\(debugTimestamp(minStart.timeIntervalSince1970))...\(debugTimestamp(maxEnd.timeIntervalSince1970))"
  }

  static func describeCommonRange(_ points: [NativeHealthDataPoint]) -> String {
    guard let minTime = points.map(\.time).min(),
          let maxTime = points.map(\.time).max() else {
      return "empty"
    }
    return "\(debugTimestamp(minTime))...\(debugTimestamp(maxTime))"
  }

  static func describeSleepRange(_ intervals: [NativeSleepInterval]) -> String {
    guard let minTime = intervals.map(\.fromTime).min(),
          let maxTime = intervals.map(\.toTime).max() else {
      return "empty"
    }
    return "\(debugTimestamp(minTime))...\(debugTimestamp(maxTime))"
  }

  static func describeActivityTargetRange(_ targets: [NativeActivityTarget]) -> String {
    let times = targets.compactMap(\.healthValueTimestamp)
    guard let minTime = times.min(), let maxTime = times.max() else {
      return "empty"
    }
    return "\(debugTimestamp(minTime))...\(debugTimestamp(maxTime))"
  }

  static func describeActivityAnchors(_ anchors: AnchoredHealthActivityAnchorBundle) -> String {
    [
      "activeEnergy=\(describeAnchorData(anchors.activeEnergy))",
      "exercise=\(describeAnchorData(anchors.exercise))",
      "stand=\(describeAnchorData(anchors.stand))",
    ].joined(separator: ",")
  }

  static func describeAnchorData(_ data: Data?) -> String {
    guard let data else { return "anchor=none" }
    return "anchor=size:\(data.count),hash:\(data.stableDebugHash)"
  }

  static func debugTimestamp(_ timeInterval: TimeInterval) -> String {
    debugDateFormatter.string(from: Date(timeIntervalSince1970: timeInterval))
  }

  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 extension Data {
  var stableDebugHash: String {
    let hash = reduce(UInt64(14_695_981_039_346_656_037)) { result, byte in
      (result ^ UInt64(byte)).multipliedReportingOverflow(by: 1_099_511_628_211).partialValue
    }
    return String(hash, radix: 16)
  }
}