Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reset CoreDataManager in the background and optimize logout #14154

Open
wants to merge 4 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions Storage/Storage/CoreData/CoreDataManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -203,32 +203,33 @@ public final class CoreDataManager: StorageManagerType {
/// 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()

performAndSave({ storage in
guard let backgroundContext = storage as? NSManagedObjectContext else {
DDLogError("⛔️ CoreDataManager failed to reset due to unexpected storage type!")
return
}
/// persist self to complete deleting objects
self.deleteAllStoredObjects(in: backgroundContext)
backgroundContext.reset()
}, completion: {
DDLogVerbose("💣 [CoreDataManager] Stack Destroyed!")
NotificationCenter.default.post(name: .StorageManagerDidResetStorage, object: self)
}
}, on: .main)
}

private func deleteAllStoredObjects() {
private func deleteAllStoredObjects(in context: NSManagedObjectContext) {
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]
let objects = try context.fetch(fetchRequest) as? [NSManagedObject]
objects?.forEach { object in
viewContext.delete(object)
context.delete(object)
}
viewContext.saveIfNeeded()
}
} catch {
logErrorAndExit("☠️ [CoreDataManager] Cannot delete stored objects! \(error)")
Expand Down
19 changes: 13 additions & 6 deletions Storage/StorageTests/CoreData/CoreDataManagerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,22 @@ final class CoreDataManagerTests: XCTestCase {
let manager = CoreDataManager(name: storageIdentifier, crashLogger: MockCrashLogger())
manager.reset()
let viewContext = try XCTUnwrap(manager.viewStorage as? NSManagedObjectContext)
_ = viewContext.insertNewObject(ofType: ShippingLine.self)
viewContext.saveIfNeeded()
XCTAssertEqual(viewContext.countObjects(ofType: ShippingLine.self), 1)

// Action
manager.reset()
waitForExpectation { expectation in
manager.performAndSave({ storage in
_ = storage.insertNewObject(ofType: ShippingLine.self)
}, completion: {
XCTAssertEqual(viewContext.countObjects(ofType: ShippingLine.self), 1)
manager.reset()
expectation.fulfill()
}, on: .main)
}

// Assert
XCTAssertEqual(viewContext.countObjects(ofType: ShippingLine.self), 0)
waitUntil {
viewContext.countObjects(ofType: ShippingLine.self) == 0
}
}

func test_performAndSave_executes_changes_in_background_then_updates_viewContext() throws {
Expand All @@ -78,7 +85,7 @@ final class CoreDataManagerTests: XCTestCase {
XCTAssertEqual(viewContext.countObjects(ofType: Account.self), 0)

// Action
waitForExpectation(count: 1) { expectation in
waitForExpectation { expectation in
manager.performAndSave({ storage in
XCTAssertFalse(Thread.current.isMainThread, "Write operations should be performed in the background.")
self.insertAccount(to: storage)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,13 @@ private extension DefaultBlazeLocalNotificationScheduler {
self?.scheduleNoCampaignReminderIfNeeded()
}
blazeCampaignResultsController.onDidResetContent = { [weak self] in
self?.scheduleNoCampaignReminderIfNeeded()
/// Upon logging out, `CoreDataManager` resets the storage and triggers the reset notification
/// causing refetching data. Checking the authentication state helps avoiding reloading data
/// in the unauthenticated state.
guard let self, stores.isAuthenticated else {
return
}
scheduleNoCampaignReminderIfNeeded()
}

do {
Expand Down
12 changes: 10 additions & 2 deletions WooCommerce/Classes/ViewRelated/Dashboard/DashboardViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,9 @@ private extension DashboardViewModel {
$isEligibleForInbox)
.receive(on: DispatchQueue.main)
.sink { [weak self] combinedResult in
guard let self else { return }
guard let self, stores.isAuthenticated else {
return
}
let ((canShowOnboarding, canShowBlaze), canShowGoogle, hasOrders, isEligibleForInbox) = combinedResult
updateDashboardCards(canShowOnboarding: canShowOnboarding,
canShowBlaze: canShowBlaze,
Expand Down Expand Up @@ -529,7 +531,13 @@ private extension DashboardViewModel {
ordersResultsController.onDidChangeContent = {
refreshHasOrders()
}
ordersResultsController.onDidResetContent = {
ordersResultsController.onDidResetContent = { [weak self] in
/// Upon logging out, `CoreDataManager` resets the storage and triggers the reset notification
/// causing refetching data. Checking the authentication state helps avoiding reloading data
/// in the unauthenticated state.
guard let self, stores.isAuthenticated else {
return
}
refreshHasOrders()
}

Expand Down
2 changes: 1 addition & 1 deletion WooCommerce/Classes/Yosemite/DefaultStoresManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,9 @@ class DefaultStoresManager: StoresManager {
let resetAction = CardPresentPaymentAction.reset
dispatch(resetAction)

sessionManager.reset()
state = DeauthenticatedState()

sessionManager.reset()
ServiceLocator.analytics.refreshUserData()
ZendeskProvider.shared.reset()
ServiceLocator.storageManager.reset()
Expand Down