JSONImporter.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import CoreData
  2. import Foundation
  3. /// Migration-specific errors that might happen during migration
  4. enum JSONImporterError: Error {
  5. case missingGlucoseValueInGlucoseEntry
  6. case tempBasalAndDurationMismatch
  7. }
  8. // MARK: - JSONImporter Class
  9. /// Responsible for importing JSON data into Core Data.
  10. ///
  11. /// The importer handles two important states:
  12. /// - JSON files stored in the file system that contain data to import
  13. /// - Existing entries in CoreData that should not be duplicated
  14. ///
  15. /// Imports are performed when a JSON file exists. The importer checks
  16. /// CoreData for existing entries to avoid duplicating records from partial imports.
  17. class JSONImporter {
  18. private let context: NSManagedObjectContext
  19. private let coreDataStack: CoreDataStack
  20. /// Initializes the importer with a Core Data context.
  21. init(context: NSManagedObjectContext, coreDataStack: CoreDataStack) {
  22. self.context = context
  23. self.coreDataStack = coreDataStack
  24. }
  25. /// Reads and parses a JSON file from the file system.
  26. ///
  27. /// - Parameters:
  28. /// - url: The URL of the JSON file to read.
  29. /// - Returns: A decoded object of the specified type.
  30. /// - Throws: An error if the file cannot be read or decoded.
  31. private func readJsonFile<T: Decodable>(url: URL) throws -> T {
  32. let data = try Data(contentsOf: url)
  33. let decoder = JSONCoding.decoder
  34. return try decoder.decode(T.self, from: data)
  35. }
  36. /// Retrieves the set of dates for all glucose values currently stored in CoreData.
  37. ///
  38. /// - Parameters: the start and end dates to fetch glucose values, inclusive
  39. /// - Returns: A set of dates corresponding to existing glucose readings.
  40. /// - Throws: An error if the fetch operation fails.
  41. private func fetchGlucoseDates(start: Date, end: Date) async throws -> Set<Date> {
  42. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  43. ofType: GlucoseStored.self,
  44. onContext: context,
  45. predicate: .predicateForDateBetween(start: start, end: end),
  46. key: "date",
  47. ascending: false
  48. ) as? [GlucoseStored] ?? []
  49. return Set(allReadings.compactMap(\.date))
  50. }
  51. /// Retrieves the set of timestamps for all pump evets currently stored in CoreData.
  52. ///
  53. /// - Parameters: the start and end dates to fetch pump events, inclusive
  54. /// - Returns: A set of dates corresponding to existing pump events.
  55. /// - Throws: An error if the fetch operation fails.
  56. private func fetchPumpTimestamps(start: Date, end: Date) async throws -> Set<Date> {
  57. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  58. ofType: PumpEventStored.self,
  59. onContext: context,
  60. predicate: .predicateForTimestampBetween(start: start, end: end),
  61. key: "timestamp",
  62. ascending: false
  63. ) as? [PumpEventStored] ?? []
  64. return Set(allReadings.compactMap(\.timestamp))
  65. }
  66. /// Imports glucose history from a JSON file into CoreData.
  67. ///
  68. /// The function reads glucose data from the provided JSON file and stores new entries
  69. /// in CoreData, skipping entries with dates that already exist in the database.
  70. ///
  71. /// - Parameters:
  72. /// - url: The URL of the JSON file containing glucose history.
  73. /// - now: The current time, used to skip old entries
  74. /// - Throws:
  75. /// - JSONImporterError.missingGlucoseValueInGlucoseEntry if a glucose entry is missing a value.
  76. /// - An error if the file cannot be read or decoded.
  77. /// - An error if the CoreData operation fails.
  78. func importGlucoseHistory(url: URL, now: Date) async throws {
  79. let twentyFourHoursAgo = now - 24.hours.timeInterval
  80. let glucoseHistoryFull: [BloodGlucose] = try readJsonFile(url: url)
  81. let existingDates = try await fetchGlucoseDates(start: twentyFourHoursAgo, end: now)
  82. // only import glucose values from the last 24 hours that don't exist
  83. let glucoseHistory = glucoseHistoryFull
  84. .filter { $0.dateString >= twentyFourHoursAgo && $0.dateString <= now && !existingDates.contains($0.dateString) }
  85. // Create a background context for batch processing
  86. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  87. backgroundContext.parent = context
  88. try await backgroundContext.perform {
  89. for glucoseEntry in glucoseHistory {
  90. try glucoseEntry.store(in: backgroundContext)
  91. }
  92. try backgroundContext.save()
  93. }
  94. try await context.perform {
  95. try self.context.save()
  96. }
  97. }
  98. /// combines tempBasal and tempBasalDuration events into one PumpHistoryEvent
  99. private func combineTempBasalAndDuration(pumpHistory: [PumpHistoryEvent]) throws -> [PumpHistoryEvent] {
  100. let tempBasal = pumpHistory.filter({ $0.type == .tempBasal }).sorted { $0.timestamp < $1.timestamp }
  101. let tempBasalDuration = pumpHistory.filter({ $0.type == .tempBasalDuration }).sorted { $0.timestamp < $1.timestamp }
  102. let nonTempBasal = pumpHistory.filter { $0.type != .tempBasal && $0.type != .tempBasalDuration }
  103. guard tempBasal.count == tempBasalDuration.count else {
  104. throw JSONImporterError.tempBasalAndDurationMismatch
  105. }
  106. let combinedTempBasal = try zip(tempBasal, tempBasalDuration).map { rate, duration in
  107. guard rate.timestamp == duration.timestamp else {
  108. throw JSONImporterError.tempBasalAndDurationMismatch
  109. }
  110. return PumpHistoryEvent(
  111. id: duration.id,
  112. type: .tempBasal,
  113. timestamp: duration.timestamp,
  114. duration: duration.durationMin,
  115. rate: rate.rate,
  116. temp: rate.temp
  117. )
  118. }
  119. return (combinedTempBasal + nonTempBasal).sorted { $0.timestamp < $1.timestamp }
  120. }
  121. /// Imports pump history from a JSON file into CoreData.
  122. ///
  123. /// The function reads pump history data from the provided JSON file and stores new entries
  124. /// in CoreData, skipping entries with timestamps that already exist in the database.
  125. ///
  126. /// - Parameters:
  127. /// - url: The URL of the JSON file containing pump history.
  128. /// - now: The current time, used to skip old entries
  129. /// - Throws:
  130. /// - JSONImporterError.tempBasalAndDurationMismatch if we can't match tempBasals with their duration.
  131. /// - An error if the file cannot be read or decoded.
  132. /// - An error if the CoreData operation fails.
  133. func importPumpHistory(url: URL, now: Date) async throws {
  134. let twentyFourHoursAgo = now - 24.hours.timeInterval
  135. let pumpHistoryRaw: [PumpHistoryEvent] = try readJsonFile(url: url)
  136. let existingTimestamps = try await fetchPumpTimestamps(start: twentyFourHoursAgo, end: now)
  137. let pumpHistoryFiltered = pumpHistoryRaw
  138. .filter { $0.timestamp >= twentyFourHoursAgo && $0.timestamp <= now && !existingTimestamps.contains($0.timestamp) }
  139. let pumpHistory = try combineTempBasalAndDuration(pumpHistory: pumpHistoryFiltered)
  140. // Create a background context for batch processing
  141. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  142. backgroundContext.parent = context
  143. try await backgroundContext.perform {
  144. for pumpEntry in pumpHistory {
  145. try pumpEntry.store(in: backgroundContext)
  146. }
  147. try backgroundContext.save()
  148. }
  149. try await context.perform {
  150. try self.context.save()
  151. }
  152. }
  153. }
  154. // MARK: - Extension for Specific Import Functions
  155. extension BloodGlucose {
  156. /// Helper function to convert `BloodGlucose` to `GlucoseStored` while importing JSON glucose entries
  157. func store(in context: NSManagedObjectContext) throws {
  158. guard let glucoseValue = glucose ?? sgv else {
  159. throw JSONImporterError.missingGlucoseValueInGlucoseEntry
  160. }
  161. let glucoseEntry = GlucoseStored(context: context)
  162. glucoseEntry.id = _id.flatMap({ UUID(uuidString: $0) }) ?? UUID()
  163. glucoseEntry.date = dateString
  164. glucoseEntry.glucose = Int16(glucoseValue)
  165. glucoseEntry.direction = direction?.rawValue
  166. glucoseEntry.isManual = type == "Manual"
  167. glucoseEntry.isUploadedToNS = true
  168. glucoseEntry.isUploadedToHealth = true
  169. glucoseEntry.isUploadedToTidepool = true
  170. }
  171. }
  172. extension PumpHistoryEvent {
  173. /// Helper function to convert `PumpHistoryEvent` to `PumpEventStored` while importing JSON pump histories
  174. func store(in context: NSManagedObjectContext) throws {
  175. let pumpEntry = PumpEventStored(context: context)
  176. pumpEntry.id = id
  177. pumpEntry.timestamp = timestamp
  178. pumpEntry.type = type.rawValue
  179. pumpEntry.isUploadedToNS = true
  180. pumpEntry.isUploadedToHealth = true
  181. pumpEntry.isUploadedToTidepool = true
  182. if type == .bolus {
  183. let bolusEntry = BolusStored(context: context)
  184. bolusEntry.amount = amount.flatMap { NSDecimalNumber(decimal: $0) }
  185. bolusEntry.isSMB = isSMB ?? false
  186. bolusEntry.isExternal = isExternal ?? false
  187. pumpEntry.bolus = bolusEntry
  188. } else if type == .tempBasal {
  189. let tempEntry = TempBasalStored(context: context)
  190. tempEntry.rate = rate.flatMap { NSDecimalNumber(decimal: $0) }
  191. tempEntry.duration = duration.flatMap({ Int16($0) }) ?? 0
  192. tempEntry.tempType = temp?.rawValue
  193. pumpEntry.tempBasal = tempEntry
  194. }
  195. }
  196. }
  197. extension JSONImporter {
  198. func importGlucoseHistoryIfNeeded() async {}
  199. }