From e3ee49a868c97cc862a24547fb48be78cf54d70d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 21 Mar 2016 14:08:36 +0100 Subject: [PATCH] FetchedRecordsController: properly serialize computations, require client access from main thread, fix known crashers --- .../GRDBDemoiOS/MasterViewController.swift | 77 +------------------ GRDB/Core/DatabaseStore.swift | 2 +- GRDB/Core/SerializedDatabase.swift | 2 +- GRDB/Core/Utils.swift | 2 +- GRDB/Record/FetchedRecordsController.swift | 70 +++++++++++------ .../DatabaseQueueConcurrencyTests.swift | 12 +-- 6 files changed, 57 insertions(+), 108 deletions(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift index f39c3074b..6db8ff886 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift @@ -44,53 +44,12 @@ class MasterViewController: UITableViewController { case .Move(let indexPath, let newIndexPath, let changes): // // Technique 1 (replace) -// // -// // TODO: fix crash -// // -// // BEFORE [["id": 6, "position": 3], ["id": 5, "position": 5], ["id": 14, "position": 6], ["id": 1, "position": 9], ["id": 7, "position": 11], ["id": 9, "position": 15], ["id": 12, "position": 19], ["id": 4, "position": 22]] -// // DELETED FROM index 1 -// // DELETED FROM index 3 -// // INSERTED AT index 3 -// // MOVED FROM index 6 TO index 1 WITH CHANGES: ["position": 10] -// // DELETED FROM index 7 -// // DELETED FROM index 8 -// // DELETED FROM index 9 -// // DELETED FROM index 10 -// // DELETED FROM index 11 -// // DELETED FROM index 12 -// // MOVED FROM index 13 TO index 0 WITH CHANGES: ["position": 20] -// // INSERTED AT index 5 -// // DELETED FROM index 14 -// // MOVED FROM index 2 TO index 6 WITH CHANGES: ["position": 4] -// // DELETED FROM index 15 -// // MOVED FROM index 5 TO index 7 WITH CHANGES: ["position": 9] -// // AFTER [["id": 19, "position": 0], ["id": 3, "position": 1], ["id": 2, "position": 2], ["id": 4, "position": 5], ["id": 1, "position": 7], ["id": 7, "position": 14], ["id": 13, "position": 15], ["id": 10, "position": 21]] // self.tableView.deleteRowsAtIndexPaths([indexPath], // withRowAnimation: UITableViewRowAnimation.Fade) // self.tableView.insertRowsAtIndexPaths([newIndexPath], // withRowAnimation: UITableViewRowAnimation.Fade) // Technique 2 (move & update) - // - // TODO: fix crash - // - // BEFORE [["id": 16, "position": 2], ["id": 11, "position": 3], ["id": 9, "position": 6], ["id": 2, "position": 8], ["id": 21, "position": 9], ["id": 15, "position": 11], ["id": 22, "position": 12], ["id": 5, "position": 13], ["id": 1, "position": 17], ["id": 18, "position": 22]] - // INSERTED AT index 1 - // INSERTED AT index 2 - // INSERTED AT index 3 - // DELETED FROM index 1 - // INSERTED AT index 4 - // DELETED FROM index 3 - // MOVED FROM index 0 TO index 6 WITH CHANGES: ["position": 1] - // MOVED FROM index 4 TO index 0 WITH CHANGES: ["position": 13] - // MOVED FROM index 2 TO index 7 WITH CHANGES: ["position": 6] - // INSERTED AT index 8 - // DELETED FROM index 6 - // INSERTED AT index 9 - // DELETED FROM index 7 - // INSERTED AT index 10 - // UPDATED AT index 5 WITH CHANGES: ["position": 15] - // AFTER [["id": 21, "position": 1], ["id": 2, "position": 5], ["id": 20, "position": 6], ["id": 6, "position": 9], ["id": 23, "position": 10], ["id": 13, "position": 12], ["id": 10, "position": 15], ["id": 7, "position": 16], ["id": 1, "position": 18], ["id": 3, "position": 19], ["id": 4, "position": 21]] let cell = self.tableView.cellForRowAtIndexPath(indexPath) self.tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath) if !changes.isEmpty, let cell = cell { @@ -110,40 +69,6 @@ class MasterViewController: UITableViewController { self.tableView.endUpdates() } - // TODO: fix crash - // - // When we remove the comparison function below, the controller only - // emits deletes and inserts. - // - // This should work just as well. - // - // But sometimes it crashes: - // - // POSITIONS BEFORE [0, 4, 6, 7, 9, 12, 15, 16, 18, 19] - // INSERTED AT index 0 - // INSERTED AT index 1 - // DELETED FROM index 0 - // INSERTED AT index 2 - // DELETED FROM index 1 - // INSERTED AT index 3 - // DELETED FROM index 2 - // INSERTED AT index 4 - // DELETED FROM index 3 - // INSERTED AT index 5 - // DELETED FROM index 4 - // INSERTED AT index 6 - // DELETED FROM index 5 - // INSERTED AT index 7 - // DELETED FROM index 6 - // INSERTED AT index 8 - // DELETED FROM index 8 - // DELETED FROM index 9 - // INSERTED AT index 10 - // DELETED FROM index 10 - // INSERTED AT index 11 - // POSITIONS AFTER [1, 2, 3, 6, 7, 10, 11, 13, 15, 17, 18, 19] - // endUpdates(): crash - // Compare two persons. Returns true if controller should emit a .Move or // .Update event instead of a deletion/insertion. fetchedRecordsController.compare { (person1, person2) in @@ -165,7 +90,7 @@ class MasterViewController: UITableViewController { } func shufflePersons() { - try! dbQueue.inTransaction { (db) -> TransactionCompletion in + try! dbQueue.inTransaction { db in var persons = Person.fetchAll(db) persons.shuffleInPlace() for (i, p) in persons.enumerate() { diff --git a/GRDB/Core/DatabaseStore.swift b/GRDB/Core/DatabaseStore.swift index 502c874a9..9bc29f708 100644 --- a/GRDB/Core/DatabaseStore.swift +++ b/GRDB/Core/DatabaseStore.swift @@ -38,7 +38,7 @@ class DatabaseStore { } private init(directoryPath: String, databaseFileName: String, directoryDescriptor: CInt, attributes: [String: AnyObject]) { - let queue = dispatch_queue_create("com.groue.GRDB.DatabaseStore", nil) + let queue = dispatch_queue_create("GRDB.DatabaseStore", nil) let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(directoryDescriptor), DISPATCH_VNODE_WRITE, queue) // Configure dispatch source diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 1bc30127a..ea5cc8e03 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -40,7 +40,7 @@ final class SerializedDatabase { private init(database: Database) { self.database = database - self.queue = dispatch_queue_create("com.github.groue.GRDB", nil) + self.queue = dispatch_queue_create("GRDB.SerializedDatabase", nil) // Activate database.preconditionValidQueue() let dispatchQueueID = unsafeBitCast(database, UnsafeMutablePointer.self) diff --git a/GRDB/Core/Utils.swift b/GRDB/Core/Utils.swift index 9e8e9e926..edd019ff1 100644 --- a/GRDB/Core/Utils.swift +++ b/GRDB/Core/Utils.swift @@ -168,7 +168,7 @@ final class Pool { init(maximumCount: Int, makeElement: (() -> T)? = nil) { precondition(maximumCount > 0, "Pool size must be at least 1") self.makeElement = makeElement - self.queue = dispatch_queue_create("com.github.groue.GRDB.Pool", nil) + self.queue = dispatch_queue_create("GRDB.Pool", nil) self.semaphore = dispatch_semaphore_create(maximumCount) } diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 2268eab3a..79b26f922 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -23,14 +23,22 @@ public class FetchedRecordsController { private init(database: DatabaseWriter, source: Source) { self.source = source self.database = database + self.diffQueue = dispatch_queue_create("GRDB.FetchedRecordsController.diff", nil) database.addTransactionObserver(self) } public func performFetch() { - try! database.read { db in + precondition(NSThread.isMainThread(), "Must be called on the main thread") + + // Use database.write, so that we are serialized with transaction + // callbacks, which happen on the writing queue. + try! database.write { db in let statement = try self.source.selectStatement(db) self.observedTables = statement.sourceTables - self.fetchedItems = Item.fetchAll(statement) + self.mainItems = Item.fetchAll(statement) + } + dispatch_sync(self.diffQueue) { + self.diffItems = self.mainItems } } @@ -65,12 +73,17 @@ public class FetchedRecordsController { private let source: Source /// The observed tables. Set in performFetch() - private var observedTables: Set? = nil + private var observedTables: Set? = nil // protected by database writer queue /// True if databaseDidCommit(db) should compute changes - private var needsComputeChanges = false + private var needsComputeChanges = false // protected by database writer queue - private var fetchedItems: [Item]? + /// Dedicated to fetchedRecords, recordAtIndexPath + private var mainItems: [Item]? // protected by main thread + + /// Dedicated to change computation + private var diffItems: [Item]? // protected by diffQueue + private var diffQueue: dispatch_queue_t // MARK: - Accessing records @@ -78,8 +91,9 @@ public class FetchedRecordsController { /// Returns the records of the query. /// Returns nil if the performQuery: hasn't been called. public var fetchedRecords: [T]? { - if let fetchedItems = fetchedItems { - return fetchedItems.map { $0.record } + precondition(NSThread.isMainThread(), "Must be called on the main thread") + if let mainItems = self.mainItems { + return mainItems.map { $0.record } } return nil } @@ -87,11 +101,11 @@ public class FetchedRecordsController { /// Returns the fetched record at a given indexPath. public func recordAtIndexPath(indexPath: NSIndexPath) -> T? { - if let item = fetchedItems?[indexPath.indexAtPosition(1)] { + precondition(NSThread.isMainThread(), "Must be called on the main thread") + if let item = self.mainItems?[indexPath.indexAtPosition(1)] { return item.record - } else { - return nil } + return nil } /// Returns the indexPath of a given record. @@ -249,39 +263,49 @@ extension FetchedRecordsController : TransactionObserverType { } public func databaseDidCommit(db: Database) { + // The databaseDidCommit callback is called in a serialized dispatch + // queue: It is guaranteed to process the last database transaction. + guard needsComputeChanges else { return } needsComputeChanges = false + guard diffItems != nil else { + // performFetch() has not been called yet + return + } + let statement = try! source.selectStatement(db) let newItems = Item.fetchAll(statement) - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [weak self] in - guard let strongSelf = self else { return } + dispatch_async(diffQueue) { + // This code, submitted to the serial diffQueue, is guaranteed + // to process the last database transaction: + + // Read/write diffItems in self.diffQueue + let changes = FetchedRecordsController.computeChanges(fromRows: self.diffItems!, toRows: newItems, equalRecords: self.equalRecords) + self.diffItems = newItems - // FIXME: there is a race condition because self.fetchedItems - // will only be updated in the main queue, below. - // - // If two database transactions are committed before the main queue - // had the opportunity to update self.fetchedItems, we'll emit two - // incompatible changes sets. - let oldItems = strongSelf.fetchedItems! - let changes = FetchedRecordsController.computeChanges(fromRows: oldItems, toRows: newItems, equalRecords: strongSelf.equalRecords) guard !changes.isEmpty else { return } - - dispatch_async(dispatch_get_main_queue()) { + + dispatch_async(dispatch_get_main_queue()) { [weak self] in + // This code, submitted to the serial main queue, is guaranteed + // to process the last database transaction: + guard let strongSelf = self else { return } strongSelf.willChangeCallback?() - strongSelf.fetchedItems = newItems + strongSelf.mainItems = newItems + if let eventCallback = strongSelf.eventCallback { for change in changes { eventCallback(record: change.item.record, event: change.event) } } + strongSelf.didChangeCallback?() } } diff --git a/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift b/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift index 08d3beddb..84def3e76 100644 --- a/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift +++ b/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift @@ -97,7 +97,7 @@ class ConcurrencyTests: XCTestCase { try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)") } - let queue = dispatch_queue_create("com.github.groue.GRDB", DISPATCH_QUEUE_CONCURRENT) + let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT) let group = dispatch_group_create() // Queue 1 @@ -156,7 +156,7 @@ class ConcurrencyTests: XCTestCase { let s2 = dispatch_semaphore_create(0) // COMMIT - let queue = dispatch_queue_create("com.github.groue.GRDB", DISPATCH_QUEUE_CONCURRENT) + let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT) let group = dispatch_group_create() // Queue 1 @@ -209,7 +209,7 @@ class ConcurrencyTests: XCTestCase { let s2 = dispatch_semaphore_create(0) // COMMIT - let queue = dispatch_queue_create("com.github.groue.GRDB", DISPATCH_QUEUE_CONCURRENT) + let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT) let group = dispatch_group_create() // Queue 1 @@ -272,7 +272,7 @@ class ConcurrencyTests: XCTestCase { return true } - let queue = dispatch_queue_create("com.github.groue.GRDB", DISPATCH_QUEUE_CONCURRENT) + let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT) let group = dispatch_group_create() // Queue 1 @@ -324,7 +324,7 @@ class ConcurrencyTests: XCTestCase { try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)") } - let queue = dispatch_queue_create("com.github.groue.GRDB", DISPATCH_QUEUE_CONCURRENT) + let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT) let group = dispatch_group_create() // Queue 1 @@ -394,7 +394,7 @@ class ConcurrencyTests: XCTestCase { try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)") } - let queue = dispatch_queue_create("com.github.groue.GRDB", DISPATCH_QUEUE_CONCURRENT) + let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT) let group = dispatch_group_create() // Queue 1