AnchoredHealthDataUploader.swift 24.6 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
import Foundation
import HealthKit

struct AnchoredHealthUploadSummary {
  let commonUploadSuccess: Bool
  let sleepUploadSuccess: Bool
  let errorMessage: String?
  let commonCount: Int
  let sleepCount: Int
}

struct AnchoredHealthUploadAnchorStore {
  static let sleepAnchorKey = "sleep_all"
  static let activityAnchorKey = "activity_all"

  private let defaults: UserDefaults
  private let keyPrefix = "health_upload_query_anchor_all_v1"

  init(defaults: UserDefaults? = AppGroupConstants.defaults) {
    self.defaults = defaults ?? .standard
  }

  func anchor(userId: Int, dataType: NativeHealthDataType) -> HKQueryAnchor? {
    guard let data = data(userId: userId, dataType: dataType) else { return nil }
    return try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data)
  }

  func anchor(userId: Int, anchorKey: String) -> HKQueryAnchor? {
    guard let data = data(userId: userId, anchorKey: anchorKey) else { return nil }
    return try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data)
  }

  func activityAnchors(userId: Int) -> AnchoredHealthActivityAnchorBundle? {
    guard let data = data(userId: userId, anchorKey: Self.activityAnchorKey) else { return nil }
    return try? PropertyListDecoder().decode(AnchoredHealthActivityAnchorBundle.self, from: data)
  }

  func data(userId: Int, dataType: NativeHealthDataType) -> Data? {
    guard userId > 0 else { return nil }
    return defaults.data(forKey: key(userId: userId, dataType: dataType))
  }

  func data(userId: Int, anchorKey: String) -> Data? {
    guard userId > 0 else { return nil }
    return defaults.data(forKey: key(userId: userId, anchorKey: anchorKey))
  }

  func save(_ data: Data, userId: Int, dataType: NativeHealthDataType) {
    guard userId > 0 else { return }
    defaults.set(data, forKey: key(userId: userId, dataType: dataType))
  }

  func save(_ data: Data, userId: Int, anchorKey: String) {
    guard userId > 0 else { return }
    defaults.set(data, forKey: key(userId: userId, anchorKey: anchorKey))
  }

  func saveActivityAnchors(_ anchors: AnchoredHealthActivityAnchorBundle, userId: Int) throws {
    guard userId > 0 else { return }
    let data = try PropertyListEncoder().encode(anchors)
    save(data, userId: userId, anchorKey: Self.activityAnchorKey)
  }

  private func key(userId: Int, dataType: NativeHealthDataType) -> String {
    "\(keyPrefix).user_\(userId).type_\(dataType.rawValue)"
  }

  private func key(userId: Int, anchorKey: String) -> String {
    "\(keyPrefix).user_\(userId).anchor_\(anchorKey)"
  }
}

/// A fully separate upload path for testing the all-types anchored strategy.
actor AnchoredHealthDataUploader {
  static let shared = AnchoredHealthDataUploader()

  private let session: URLSession
  private let reader: AnchoredHealthDataReader
  private let anchorStore: AnchoredHealthUploadAnchorStore
  private let userIdProvider: () -> Int?
  private let uploadBatchSize = 300
  private(set) var isUploadingAll = false
  private var uploadAllPending = false
  private var pendingUploadAllTypes = false
  private var pendingUploadDataTypes = Set<NativeHealthDataType>()
  private var uploadAllWaiters: [CheckedContinuation<AnchoredHealthUploadSummary, Never>] = []

  init(
    session: URLSession = .shared,
    anchorStore: AnchoredHealthUploadAnchorStore = AnchoredHealthUploadAnchorStore(),
    userIdProvider: @escaping () -> Int? = { AppShared.shared.userId }
  ) {
    self.session = session
    self.anchorStore = anchorStore
    self.userIdProvider = userIdProvider
    self.reader = AnchoredHealthDataReader(anchorStore: anchorStore, userIdProvider: userIdProvider)
  }

  func uploadAll(
    dataTypes: Set<NativeHealthDataType>? = nil
  ) async -> AnchoredHealthUploadSummary {
    await runUploadAll(
      dataTypes: dataTypes,
      queueAnotherRunIfUploading: false
    )
  }

  func uploadAllAfterObservedChange(sampleTypeIdentifiers: Set<String>) async {
    let mappedDataTypes = Self.uploadDataTypes(for: sampleTypeIdentifiers)
    let shouldFallbackForMissingAnchor: Bool
    if let mappedDataTypes,
       let userId = userIdProvider(), userId > 0 {
      shouldFallbackForMissingAnchor = hasMissingAnchor(dataTypes: mappedDataTypes, userId: userId)
    } else {
      shouldFallbackForMissingAnchor = mappedDataTypes != nil
    }
    let dataTypes = shouldFallbackForMissingAnchor ? nil : mappedDataTypes
    let sources = sampleTypeIdentifiers.isEmpty
      ? "unknown"
      : sampleTypeIdentifiers.sorted().joined(separator: ",")
    if shouldFallbackForMissingAnchor {
      Self.log(
        "uploader.observer.fallback reason=missingAnchor userId=\(userIdProvider() ?? -1)"
      )
    }
    Self.log(
      "uploader.observer.received userId=\(userIdProvider() ?? -1) sources=\(sources) dataTypes=\(Self.describeRequestedDataTypes(dataTypes))"
    )
    _ = await runUploadAll(
      dataTypes: dataTypes,
      queueAnotherRunIfUploading: true
    )
  }

  func uploadAllCommon(
    dataTypes: Set<NativeHealthDataType>? = nil
  ) async throws -> Int {
    let result = try await reader.readCommon(dataTypes: dataTypes)
    Self.log(
      "uploader.common.read userId=\(userIdProvider() ?? -1) count=\(result.data.count) range=\(Self.describeCommonRange(result.data)) anchors=\(Self.describeAnchors(result.anchors))"
    )
    Self.logCommonPoints(result.data, userId: userIdProvider() ?? -1, prefix: "uploader.common.read.item")
    return try await uploadCommon(result.data, anchors: result.anchors)
  }

  func uploadAllSeelp() async throws -> Int {
    try await uploadAllSleep()
  }

  func uploadAllSleep() async throws -> Int {
    let result = try await reader.readAllSleep()
    Self.log(
      "uploader.sleep.read userId=\(userIdProvider() ?? -1) count=\(result.data.count) range=\(Self.describeSleepRange(result.data)) anchorKey=\(AnchoredHealthUploadAnchorStore.sleepAnchorKey) \(Self.describeAnchorData(result.anchor))"
    )
    Self.logSleepIntervals(result.data, userId: userIdProvider() ?? -1, prefix: "uploader.sleep.read.item")
    return try await uploadSleep(result.data, anchor: result.anchor)
  }

  func uploadAllActivity() async throws -> Int {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }
    let result = try await reader.readActivity()
    Self.log(
      "uploader.activity.read userId=\(userId) count=\(result.data.count) targetCount=\(result.targets.count) range=\(Self.describeCommonRange(result.data)) targetRange=\(Self.describeActivityTargetRange(result.targets)) anchors=\(Self.describeActivityAnchors(result.anchors))"
    )
    Self.logCommonPoints(result.data, userId: userId, prefix: "uploader.activity.read.item")
    Self.logActivityTargets(result.targets, userId: userId, prefix: "uploader.activity.target.read.item")
    let commonCount = try await uploadCommon(result.data, anchors: [:])
    try await uploadActivityTargets(result.targets)
    try anchorStore.saveActivityAnchors(result.anchors, userId: userId)
    Self.log(
      "uploader.anchor.saved userId=\(userId) anchorKey=\(AnchoredHealthUploadAnchorStore.activityAnchorKey) reason=activityFinished \(Self.describeActivityAnchors(result.anchors)) uploadedRange=\(Self.describeCommonRange(result.data)) targetRange=\(Self.describeActivityTargetRange(result.targets))"
    )
    return commonCount
  }
}

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

  static func uploadDataTypes(
    for sampleTypeIdentifiers: Set<String>
  ) -> Set<NativeHealthDataType>? {
    guard !sampleTypeIdentifiers.isEmpty else { return nil }
    var dataTypes = Set<NativeHealthDataType>()

    for identifier in sampleTypeIdentifiers {
      switch identifier {
      case HKQuantityTypeIdentifier.heartRateVariabilitySDNN.rawValue:
        dataTypes.insert(.hrv)
      case HKQuantityTypeIdentifier.heartRate.rawValue:
        dataTypes.formUnion([.heartRate, .sleepingHeartRate])
      case HKQuantityTypeIdentifier.stepCount.rawValue:
        dataTypes.insert(.steps)
      case HKQuantityTypeIdentifier.oxygenSaturation.rawValue:
        dataTypes.insert(.oxygenSaturation)
      case HKQuantityTypeIdentifier.activeEnergyBurned.rawValue:
        dataTypes.insert(.activeEnergy)
      case HKQuantityTypeIdentifier.appleExerciseTime.rawValue:
        dataTypes.insert(.exercise)
      case HKQuantityTypeIdentifier.appleStandTime.rawValue:
        dataTypes.insert(.stand)
      case HKQuantityTypeIdentifier.walkingHeartRateAverage.rawValue:
        dataTypes.insert(.walkingHeartRate)
      case HKQuantityTypeIdentifier.restingHeartRate.rawValue:
        dataTypes.insert(.restingHeartRate)
      case HKQuantityTypeIdentifier.appleSleepingWristTemperature.rawValue:
        dataTypes.insert(.sleepingWristTemperature)
      case HKQuantityTypeIdentifier.respiratoryRate.rawValue:
        dataTypes.insert(.respiratoryRate)
      case HKCategoryTypeIdentifier.irregularHeartRhythmEvent.rawValue:
        dataTypes.insert(.irregularHeartRhythm)
      case HKCategoryTypeIdentifier.sleepAnalysis.rawValue:
        dataTypes.insert(.sleep)
      default:
        return nil
      }
    }
    return dataTypes
  }

  static func describeRequestedDataTypes(
    _ dataTypes: Set<NativeHealthDataType>?
  ) -> String {
    dataTypes.map { types in
      types.map(\.rawValue).sorted().map(String.init).joined(separator: ",")
    } ?? "all"
  }

  func hasMissingAnchor(dataTypes: Set<NativeHealthDataType>, userId: Int) -> Bool {
    dataTypes.contains { dataType in
      if dataType == .sleep {
        return anchorStore.anchor(
          userId: userId,
          anchorKey: AnchoredHealthUploadAnchorStore.sleepAnchorKey
        ) == nil
      }
      if Self.activityDataTypes.contains(dataType) {
        return anchorStore.activityAnchors(userId: userId) == nil
      }
      return anchorStore.anchor(userId: userId, dataType: dataType) == nil
    }
  }

  func runUploadAll(
    dataTypes: Set<NativeHealthDataType>?,
    queueAnotherRunIfUploading: Bool
  ) async -> AnchoredHealthUploadSummary {
    if isUploadingAll {
      if queueAnotherRunIfUploading {
        uploadAllPending = true
        if let dataTypes {
          if !pendingUploadAllTypes {
            pendingUploadDataTypes.formUnion(dataTypes)
          }
        } else {
          pendingUploadAllTypes = true
          pendingUploadDataTypes.removeAll()
        }
        Self.log(
          "uploader.all.pending userId=\(userIdProvider() ?? -1) dataTypes=\(Self.describeRequestedDataTypes(dataTypes))"
        )
      } else {
        Self.log("uploader.all.skip reason=alreadyUploading userId=\(userIdProvider() ?? -1)")
      }
      return await withCheckedContinuation { continuation in
        uploadAllWaiters.append(continuation)
      }
    }

    isUploadingAll = true
    var summary: AnchoredHealthUploadSummary
    var requestedDataTypes = dataTypes
    while true {
      uploadAllPending = false
      pendingUploadAllTypes = false
      pendingUploadDataTypes.removeAll()
      Self.log(
        "uploader.all.start userId=\(userIdProvider() ?? -1) dataTypes=\(Self.describeRequestedDataTypes(requestedDataTypes))"
      )
      summary = await performUploadAll(dataTypes: requestedDataTypes)
      Self.log(
        "uploader.all.end userId=\(userIdProvider() ?? -1) commonSuccess=\(summary.commonUploadSuccess) sleepSuccess=\(summary.sleepUploadSuccess) commonCount=\(summary.commonCount) sleepCount=\(summary.sleepCount) error=\(summary.errorMessage ?? "nil")"
      )
      guard uploadAllPending else { break }
      requestedDataTypes = pendingUploadAllTypes ? nil : pendingUploadDataTypes
    }
    isUploadingAll = false

    let waiters = uploadAllWaiters
    uploadAllWaiters.removeAll()
    waiters.forEach { $0.resume(returning: summary) }
    return summary
  }

  func performUploadAll(
    dataTypes: Set<NativeHealthDataType>?
  ) async -> AnchoredHealthUploadSummary {
    guard AppShared.shared.token?.isEmpty == false else {
      let message = NativeHealthUploadError.missingAccessToken.localizedDescription
      return AnchoredHealthUploadSummary(
        commonUploadSuccess: false,
        sleepUploadSuccess: false,
        errorMessage: message,
        commonCount: 0,
        sleepCount: 0
      )
    }

    var commonCount = 0
    var sleepCount = 0
    var commonUploadSuccess = true
    var sleepUploadSuccess = true
    var errorMessages: [String] = []
    let commonTypes = dataTypes.map { types in
      Set(types.filter {
        $0 != .sleep && $0 != .unknown && !Self.activityDataTypes.contains($0)
      })
    }
    let includesCommon = commonTypes == nil || commonTypes?.isEmpty == false
    let includesActivity = dataTypes == nil || dataTypes?.contains(where: { Self.activityDataTypes.contains($0) }) == true
    let includesSleep = dataTypes == nil || dataTypes?.contains(.sleep) == true

    if includesCommon {
      do {
        commonCount = try await uploadAllCommon(dataTypes: commonTypes)
      } catch {
        commonUploadSuccess = false
        errorMessages.append("common 上传失败:\(error.localizedDescription)")
      }
    }

    if includesActivity {
      do {
        commonCount += try await uploadAllActivity()
      } catch {
        commonUploadSuccess = false
        errorMessages.append("activity 上传失败:\(error.localizedDescription)")
      }
    }

    if includesSleep {
      do {
        sleepCount = try await uploadAllSleep()
      } catch {
        sleepUploadSuccess = false
        errorMessages.append("sleep 上传失败:\(error.localizedDescription)")
      }
    }

    return AnchoredHealthUploadSummary(
      commonUploadSuccess: commonUploadSuccess,
      sleepUploadSuccess: sleepUploadSuccess,
      errorMessage: errorMessages.isEmpty ? nil : errorMessages.joined(separator: "\n"),
      commonCount: commonCount,
      sleepCount: sleepCount
    )
  }

  func uploadCommon(
    _ data: [NativeHealthDataPoint],
    anchors: [NativeHealthDataType: Data]
  ) async throws -> Int {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }
    guard !data.isEmpty else {
      Self.log(
        "uploader.common.empty userId=\(userId) anchors=\(Self.describeAnchors(anchors))"
      )
      anchors.forEach { anchorStore.save($0.value, userId: userId, dataType: $0.key) }
      anchors.forEach {
        Self.log(
          "uploader.anchor.saved userId=\(userId) dataType=\($0.key.rawValue) reason=emptyCommon \(Self.describeAnchorData($0.value))"
        )
      }
      return 0
    }

    Self.log(
      "uploader.common.start userId=\(userId) count=\(data.count) range=\(Self.describeCommonRange(data)) batchSize=\(uploadBatchSize) anchors=\(Self.describeAnchors(anchors))"
    )
    var uploadedCount = 0
    var remainingCountByType = anchors.keys.reduce(into: [NativeHealthDataType: Int]()) { result, type in
      result[type] = 0
    }
    data.forEach { point in
      remainingCountByType[point.dataType, default: 0] += 1
    }

    for (batchIndex, batch) in SharedHealthAnchoredUploadSupport.batches(data, size: uploadBatchSize).enumerated() {
      let list = batch.map {
        [
          "data_type": $0.dataType.rawValue,
          "time": $0.time,
          "value": $0.value,
        ] as [String: Any]
      }
      try await request(
        path: "/client/doublefeel/health/v2/data_upload/common/",
        method: "POST",
        body: ["data_list": list]
      )

      uploadedCount += batch.count
      for point in batch {
        remainingCountByType[point.dataType, default: 0] -= 1
      }
      Self.log(
        "uploader.common.batch.success userId=\(userId) batch=\(batchIndex + 1) count=\(batch.count) range=\(Self.describeCommonRange(batch)) uploadedCount=\(uploadedCount)/\(data.count)"
      )
      saveFinishedAnchors(
        anchors,
        userId: userId,
        finishedTypes: remainingCountByType.filter { $0.value <= 0 }.map(\.key)
      )
      batch.forEach { point in
        DebugLogger.debugLog(
          "[ArchUploader] uploader.common.batch.success.item userId=\(userId) dataType=\(point.dataType.rawValue) time=\(Self.debugTimestamp(point.time)) unix=\(Int64(point.time)) value=\(point.value)"
        )
      }
    }

    return uploadedCount
  }

  func uploadActivityTargets(_ targets: [NativeActivityTarget]) async throws {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }
    guard !targets.isEmpty else {
      Self.log("uploader.activityTarget.empty userId=\(userId)")
      return
    }

    for (index, target) in targets.enumerated() {
      try await request(
        path: "/client/doublefeel/health/v2/activity_target/",
        method: "POST",
        body: target.uploadBody
      )
      let timestamp = target.healthValueTimestamp ?? 0
      Self.log(
        "uploader.activityTarget.success userId=\(userId) index=\(index + 1)/\(targets.count) time=\(Self.debugTimestamp(timestamp)) unix=\(Int64(timestamp)) body=\(target.uploadBodyForDebug)"
      )
    }
  }

  func uploadSleep(
    _ data: [NativeSleepInterval],
    anchor: Data
  ) async throws -> Int {
    guard let userId = userIdProvider(), userId > 0 else {
      throw NativeHealthUploadError.missingUserId
    }
    guard !data.isEmpty else {
      Self.log(
        "uploader.sleep.empty userId=\(userId) anchorKey=\(AnchoredHealthUploadAnchorStore.sleepAnchorKey) \(Self.describeAnchorData(anchor))"
      )
      anchorStore.save(anchor, userId: userId, anchorKey: AnchoredHealthUploadAnchorStore.sleepAnchorKey)
      Self.log(
        "uploader.anchor.saved userId=\(userId) anchorKey=\(AnchoredHealthUploadAnchorStore.sleepAnchorKey) reason=emptySleep \(Self.describeAnchorData(anchor))"
      )
      return 0
    }

    Self.log(
      "uploader.sleep.start userId=\(userId) count=\(data.count) range=\(Self.describeSleepRange(data)) batchSize=\(uploadBatchSize) anchorKey=\(AnchoredHealthUploadAnchorStore.sleepAnchorKey) \(Self.describeAnchorData(anchor))"
    )
    var uploadedCount = 0
    for (batchIndex, batch) in SharedHealthAnchoredUploadSupport.batches(data, size: uploadBatchSize).enumerated() {
      let list = batch.map {
        [
          "data_type": $0.dataType,
          "from_time": $0.fromTime,
          "to_time": $0.toTime,
        ] as [String: Any]
      }
      try await request(
        path: "/client/doublefeel/health/v2/data_upload/sleep/",
        method: "POST",
        body: ["data_list": list]
      )

      uploadedCount += batch.count
      Self.log(
        "uploader.sleep.batch.success userId=\(userId) batch=\(batchIndex + 1) count=\(batch.count) range=\(Self.describeSleepRange(batch)) uploadedCount=\(uploadedCount)/\(data.count)"
      )
      if uploadedCount == data.count {
        anchorStore.save(anchor, userId: userId, anchorKey: AnchoredHealthUploadAnchorStore.sleepAnchorKey)
        Self.log(
          "uploader.anchor.saved userId=\(userId) anchorKey=\(AnchoredHealthUploadAnchorStore.sleepAnchorKey) reason=sleepFinished \(Self.describeAnchorData(anchor)) uploadedRange=\(Self.describeSleepRange(data))"
        )
      }
      batch.forEach { interval in
        DebugLogger.debugLog(
          "[ArchUploader] uploader.sleep.batch.success.item userId=\(userId) dataType=\(interval.dataType) from=\(Self.debugTimestamp(interval.fromTime)) fromUnix=\(Int64(interval.fromTime)) to=\(Self.debugTimestamp(interval.toTime)) toUnix=\(Int64(interval.toTime))"
        )
      }
    }

    return uploadedCount
  }

  func saveFinishedAnchors(
    _ anchors: [NativeHealthDataType: Data],
    userId: Int,
    finishedTypes: [NativeHealthDataType]
  ) {
    for type in finishedTypes {
      guard let anchor = anchors[type] else { continue }
      anchorStore.save(anchor, userId: userId, dataType: type)
      Self.log(
        "uploader.anchor.saved userId=\(userId) dataType=\(type.rawValue) reason=commonTypeFinished \(Self.describeAnchorData(anchor))"
      )
    }
  }

  @discardableResult
  func request(path: String, method: String, body: [String: Any]? = nil) async throws -> Data {
    guard let baseURL = URL(string: AppShared.shared.baseUrl),
          let url = URL(string: path, relativeTo: baseURL)?.absoluteURL else {
      throw NativeHealthUploadError.invalidServerURL
    }
    guard let accessToken = AppShared.shared.token, !accessToken.isEmpty else {
      throw NativeHealthUploadError.missingAccessToken
    }

    var request = URLRequest(url: url)
    request.httpMethod = method
    request.timeoutInterval = 60
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue(accessToken, forHTTPHeaderField: "access_token")
    request.setValue(AppShared.shared.agent.finalUA, forHTTPHeaderField: "User-Agent")

    if let body {
      request.setValue("application/json", forHTTPHeaderField: "Content-Type")
      request.httpBody = try JSONSerialization.data(withJSONObject: body)
    }

    let (data, response) = try await session.data(for: request)
    guard let httpResponse = response as? HTTPURLResponse else {
      throw NativeHealthUploadError.invalidResponse
    }
    guard (200..<300).contains(httpResponse.statusCode) else {
      if httpResponse.statusCode == 401 {
        await MainActor.run {
          AppShared.shared.logout()
        }
      }
      throw NativeHealthUploadError.requestFailed(
        path: path,
        statusCode: httpResponse.statusCode,
        body: String(data: data, encoding: .utf8)
      )
    }
    return data
  }

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

  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 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 describeAnchors(_ anchors: [NativeHealthDataType: Data]) -> String {
    anchors
      .map { "type:\($0.key.rawValue)=\(describeAnchorData($0.value))" }
      .sorted()
      .joined(separator: ",")
  }

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

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

  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)
  }
}