AnchoredHealthDataUploader.swift
10.5 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
import Foundation
import HealthKit
struct AnchoredHealthUploadSummary {
let sleepUploadSuccess: Bool
let errorMessage: String?
let sleepCount: Int
}
struct AnchoredHealthUploadAnchorStore {
static let sleepAnchorKey = "sleep_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, anchorKey: String) -> HKQueryAnchor? {
guard let data = data(userId: userId, anchorKey: anchorKey) else { return nil }
return try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data)
}
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, anchorKey: String) {
guard userId > 0 else { return }
defaults.set(data, forKey: key(userId: userId, anchorKey: anchorKey))
}
private func key(userId: Int, anchorKey: String) -> String {
"\(keyPrefix).user_\(userId).anchor_\(anchorKey)"
}
}
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 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() async -> AnchoredHealthUploadSummary {
await runUploadAll(queueAnotherRunIfUploading: false)
}
func uploadAllAfterObservedChange(sampleTypeIdentifiers: Set<String>) async {
guard sampleTypeIdentifiers.isEmpty
|| sampleTypeIdentifiers.contains(HKCategoryTypeIdentifier.sleepAnalysis.rawValue) else {
let sources = sampleTypeIdentifiers.sorted().joined(separator: ",")
Self.log("uploader.observer.skip reason=nonSleep sources=\(sources)")
return
}
let sources = sampleTypeIdentifiers.isEmpty
? "unknown"
: sampleTypeIdentifiers.sorted().joined(separator: ",")
Self.log("uploader.observer.received userId=\(userIdProvider() ?? -1) sources=\(sources) dataTypes=sleep")
_ = await runUploadAll(queueAnotherRunIfUploading: true)
}
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)
}
}
private extension AnchoredHealthDataUploader {
func runUploadAll(
queueAnotherRunIfUploading: Bool
) async -> AnchoredHealthUploadSummary {
if isUploadingAll {
if queueAnotherRunIfUploading {
uploadAllPending = true
Self.log("uploader.all.pending userId=\(userIdProvider() ?? -1) dataTypes=sleep")
} else {
Self.log("uploader.all.skip reason=alreadyUploading userId=\(userIdProvider() ?? -1)")
}
return await withCheckedContinuation { continuation in
uploadAllWaiters.append(continuation)
}
}
isUploadingAll = true
var summary: AnchoredHealthUploadSummary
repeat {
uploadAllPending = false
Self.log("uploader.all.start userId=\(userIdProvider() ?? -1) dataTypes=sleep")
summary = await performUploadAll()
Self.log(
"uploader.all.end userId=\(userIdProvider() ?? -1) sleepSuccess=\(summary.sleepUploadSuccess) sleepCount=\(summary.sleepCount) error=\(summary.errorMessage ?? "nil")"
)
} while uploadAllPending
isUploadingAll = false
let waiters = uploadAllWaiters
uploadAllWaiters.removeAll()
waiters.forEach { $0.resume(returning: summary) }
return summary
}
func performUploadAll() async -> AnchoredHealthUploadSummary {
guard AppShared.shared.token?.isEmpty == false else {
return AnchoredHealthUploadSummary(
sleepUploadSuccess: false,
errorMessage: NativeHealthUploadError.missingAccessToken.localizedDescription,
sleepCount: 0
)
}
do {
let sleepCount = try await uploadAllSleep()
return AnchoredHealthUploadSummary(
sleepUploadSuccess: true,
errorMessage: nil,
sleepCount: sleepCount
)
} catch {
return AnchoredHealthUploadSummary(
sleepUploadSuccess: false,
errorMessage: "sleep 上传失败:\(error.localizedDescription)",
sleepCount: 0
)
}
}
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))"
)
}
Self.logSleepIntervals(batch, userId: userId, prefix: "uploader.sleep.batch.success.item")
}
return uploadedCount
}
@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 {
debugDateFormatter.string(from: Date(timeIntervalSince1970: timeInterval))
}
static func log(_ message: String) {
DebugLogger.debugLog("[ArchUploader] \(message)")
}
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 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 describeAnchorData(_ data: Data) -> String {
"anchor=size:\(data.count),hash:\(data.stableDebugHash)"
}
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)
}
}