forked from woocommerce/woocommerce-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoreDataManager.swift
263 lines (225 loc) · 10.9 KB
/
CoreDataManager.swift
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
import Foundation
import CoreData
import WooFoundation
/// CoreDataManager: Manages the entire CoreData Stack. Conforms to the StorageManager API.
///
public final class CoreDataManager: StorageManagerType {
/// Storage Identifier.
///
public let name: String
private let crashLogger: CrashLogger
private let modelsInventory: ManagedObjectModelsInventory
/// Module-private designated Initializer.
///
/// - Parameter name: Identifier to be used for: [database, data model, container].
/// - Parameter crashLogger: allows logging a message of any severity level
/// - Parameter modelsInventory: The models to load when spinning up the Core Data stack.
/// This is automatically generated if `nil`. You would probably only specify this for
/// unit tests to test migration and/or recovery scenarios.
///
/// - Important: This should *match* with your actual Data Model file!.
///
init(name: String,
crashLogger: CrashLogger,
modelsInventory: ManagedObjectModelsInventory?) {
self.name = name
self.crashLogger = crashLogger
do {
if let modelsInventory = modelsInventory {
self.modelsInventory = modelsInventory
} else {
self.modelsInventory = try .from(packageName: name, bundle: Bundle(for: type(of: self)))
}
} catch {
// We'll throw a fatalError() because we can't really proceed without a
// ManagedObjectModel.
let error = CoreDataManagerError.modelInventoryLoadingFailed(name, error)
crashLogger.logFatalErrorAndExit(error, userInfo: nil)
}
}
/// Public designated initializer.
///
/// - Parameter name: Identifier to be used for: [database, data model, container].
/// - Parameter crashLogger: allows logging a message of any severity level
///
/// - Important: This should *match* with your actual Data Model file!.
///
public convenience init(name: String, crashLogger: CrashLogger) {
self.init(name: name, crashLogger: crashLogger, modelsInventory: nil)
}
/// Returns the Storage associated with the View Thread.
///
public var viewStorage: StorageType {
return persistentContainer.viewContext
}
/// Returns a shared derived storage instance dedicated for write operations.
///
public lazy var writerDerivedStorage: StorageType = {
let childManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childManagedObjectContext.parent = persistentContainer.viewContext
childManagedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return childManagedObjectContext
}()
/// Persistent Container: Holds the full CoreData Stack
///
public lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: name, managedObjectModel: modelsInventory.currentModel)
container.persistentStoreDescriptions = [storeDescription]
let migrationDebugMessages = migrateDataModelIfNecessary(using: container.persistentStoreCoordinator)
container.loadPersistentStores { [weak self] (storeDescription, error) in
guard let `self` = self, let persistentStoreLoadingError = error else {
return
}
DDLogError("⛔️ [CoreDataManager] loadPersistentStore failed. Attempting to recover... \(persistentStoreLoadingError)")
/// Remove the old Store which is either corrupted or has an invalid model we can't migrate from
///
var persistentStoreRemovalError: Error?
do {
try container.persistentStoreCoordinator.destroyPersistentStore(at: self.storeURL,
ofType: storeDescription.type,
options: nil)
NotificationCenter.default.post(name: .StorageManagerDidResetStorage, object: self)
} catch {
persistentStoreRemovalError = error
}
/// Retry!
///
container.loadPersistentStores { [weak self] (storeDescription, underlyingError) in
guard let underlyingError = underlyingError as NSError? else {
return
}
let error = CoreDataManagerError.recoveryFailed
let logProperties: [String: Any?] = ["persistentStoreLoadingError": persistentStoreLoadingError,
"persistentStoreRemovalError": persistentStoreRemovalError,
"retryError": underlyingError,
"appState": UIApplication.shared.applicationState.rawValue,
"migrationMessages": migrationDebugMessages]
self?.crashLogger.logFatalErrorAndExit(error,
userInfo: logProperties.compactMapValues { $0 })
}
let logProperties: [String: Any?] = ["persistentStoreLoadingError": persistentStoreLoadingError,
"persistentStoreRemovalError": persistentStoreRemovalError,
"appState": UIApplication.shared.applicationState.rawValue,
"migrationMessages": migrationDebugMessages]
self.crashLogger.logMessage("[CoreDataManager] Recovered from persistent store loading error",
properties: logProperties.compactMapValues { $0 },
level: .info)
}
return container
}()
/// Performs the received closure in Background. Note that you should use the received Storage instance (BG friendly!).
///
public func performBackgroundTask(_ closure: @escaping (StorageType) -> Void) {
persistentContainer.performBackgroundTask { context in
closure(context as StorageType)
}
}
/// Saves the derived storage. Note: the closure may be called on a different thread
///
public func saveDerivedType(derivedStorage: StorageType, _ closure: @escaping () -> Void) {
derivedStorage.perform {
derivedStorage.saveIfNeeded()
self.viewStorage.perform {
self.viewStorage.saveIfNeeded()
closure()
}
}
}
/// This method effectively destroys all of the stored data, and generates a blank Persistent Store from scratch.
///
public func reset() {
let viewContext = persistentContainer.viewContext
viewContext.performAndWait {
viewContext.reset()
self.deleteAllStoredObjects()
DDLogVerbose("💣 [CoreDataManager] Stack Destroyed!")
NotificationCenter.default.post(name: .StorageManagerDidResetStorage, object: self)
}
}
private func deleteAllStoredObjects() {
let storeCoordinator = persistentContainer.persistentStoreCoordinator
let viewContext = persistentContainer.viewContext
do {
let entities = storeCoordinator.managedObjectModel.entities
for entity in entities {
guard let entityName = entity.name else {
continue
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let objects = try viewContext.fetch(fetchRequest) as? [NSManagedObject]
objects?.forEach { object in
viewContext.delete(object)
}
viewContext.saveIfNeeded()
}
} catch {
logErrorAndExit("☠️ [CoreDataManager] Cannot delete stored objects! \(error)")
}
}
/// Migrates the current persistent store to the latest data model if needed.
/// - Returns: an array of debug messages for logging. Please feel free to remove when #2371 is resolved.
private func migrateDataModelIfNecessary(using coordinator: NSPersistentStoreCoordinator) -> [String] {
var debugMessages = [String]()
let migrationCheckMessage = "ℹ️ [CoreDataManager] Checking if migration is necessary."
debugMessages.append(migrationCheckMessage)
DDLogInfo(migrationCheckMessage)
do {
let iterativeMigrator = CoreDataIterativeMigrator(coordinator: coordinator, modelsInventory: modelsInventory)
let (migrateResult, migrationDebugMessages) = try iterativeMigrator.iterativeMigrate(sourceStore: storeURL,
storeType: NSSQLiteStoreType,
to: modelsInventory.currentModel)
debugMessages += migrationDebugMessages
if migrateResult == false {
let migrationFailureMessage = "☠️ [CoreDataManager] Unable to migrate store."
debugMessages.append(migrationFailureMessage)
DDLogError(migrationFailureMessage)
}
return debugMessages
} catch {
let migrationErrorMessage = "☠️ [CoreDataManager] Unable to migrate store with error: \(error)"
debugMessages.append(migrationErrorMessage)
DDLogError(migrationErrorMessage)
return debugMessages
}
}
}
// MARK: - Descriptors
//
extension CoreDataManager {
/// Returns the PersistentStore Descriptor
///
var storeDescription: NSPersistentStoreDescription {
let description = NSPersistentStoreDescription(url: storeURL)
description.shouldAddStoreAsynchronously = false
description.shouldMigrateStoreAutomatically = false
return description
}
}
// MARK: - Stack URL's
//
extension CoreDataManager {
/// Returns the Store URL (the actual sqlite file!)
///
var storeURL: URL {
guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
logErrorAndExit("Okay: Missing Documents Folder?")
}
return url.appendingPathComponent(name + ".sqlite")
}
}
// MARK: - Errors
//
enum CoreDataManagerError: Error {
case modelInventoryLoadingFailed(String, Error)
case recoveryFailed
}
extension CoreDataManagerError: CustomStringConvertible {
var description: String {
switch self {
case .modelInventoryLoadingFailed(let name, let underlyingError):
return "Failed to load models inventory using packageName \(name). Error: \(underlyingError)"
case .recoveryFailed:
return "☠️ [CoreDataManager] Recovery Failed!"
}
}
}