FetchedRecordsController: properly serialize computations, require client access from main thread, fix known crashers

This commit is contained in:
Gwendal Roué committed 2016-03-21 14:08:36 +01:00
1 parent 5e6dd56933
commit e3ee49a868
6 files changed
+57 -108

No files matched your search

@@ -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() {
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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<Void>.self)
+1 -1
View File
@@ -168,7 +168,7 @@ final class Pool<T> {
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)
}
+47 -23
View File
@@ -23,14 +23,22 @@ public class FetchedRecordsController<T: RowConvertible> {
private init(database: DatabaseWriter, source: Source<T>) {
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<T>.fetchAll(statement)
self.mainItems = Item<T>.fetchAll(statement)
}
dispatch_sync(self.diffQueue) {
self.diffItems = self.mainItems
}
}
@@ -65,12 +73,17 @@ public class FetchedRecordsController<T: RowConvertible> {
private let source: Source<T>
/// The observed tables. Set in performFetch()
private var observedTables: Set<String>? = nil
private var observedTables: Set<String>? = 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<T>]?
/// Dedicated to fetchedRecords, recordAtIndexPath
private var mainItems: [Item<T>]? // protected by main thread
/// Dedicated to change computation
private var diffItems: [Item<T>]? // protected by diffQueue
private var diffQueue: dispatch_queue_t
// MARK: - Accessing records
@@ -78,8 +91,9 @@ public class FetchedRecordsController<T: RowConvertible> {
/// 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<T: RowConvertible> {
/// 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<T>.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?()
}
}
@@ -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