From 9215f88e7f4e0472771a08bcee889cfb3887c97e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 10:47:27 +0200 Subject: [PATCH] Documentation, cleanup, and checkpoint prevention --- GRDB/Core/DatabasePool.swift | 199 ++++++++++++++----------------- GRDB/Core/DatabaseSnapshot.swift | 9 +- 2 files changed, 98 insertions(+), 110 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 0315b8362..94abe37b2 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -866,131 +866,112 @@ extension DatabasePool: DatabaseReader { onError: onError, onChange: onChange) - // TODO: what about checkpoints that invalidate snapshots??? + // Starting a concurrent observation means that we'll fetch the initial + // value right away, without waiting for an access to the writer queue, + // and the opportunity to install a transaction observer. + // + // This is how DatabasePool can start an observation and promptly notify + // an initial value, even when there is a long-running write transaction + // in the background. + // + // We thus have to deal with the fact that between this initial fetch, + // and the beginning of transaction tracking, any number of untracked + // writes may occur. + // + // We must notify changes that happen during this untracked window. But + // how do we spot them, since we're not tracking database changes yet? + // + // A safe solution is to always perform a second fetch. We may fetch the + // same initial value, if no change did happen. But we don't miss + // possible changes. + // + // We can avoid this second fetch when SQLite is compiled with the + // SQLITE_ENABLE_SNAPSHOT option: + // + // 1. Perform the initial fetch in a DatabaseSnapshot. The snapshot + // acquires a lock that will prevent checkpointing until we get a writer + // access, so that we can reliably compare database versions with + // `sqlite3_snapshot`: https://www.sqlite.org/c3ref/snapshot.html. + // + // 2. Get a writer access, and compare the versions of the initial + // snapshot, and the current state of the database: if versions are + // identical, we can avoid the second fetch. If they are not, we perform + // the second fetch, even if the actual changes are unrelated to the + // tracked database region (we have no way to know). + // + // 3. Install the transaction observer. + if scheduler.immediateInitialValue() { do { - // Grab a snapshot of the state of the database and perform - // the initial fetch. - var initialValue: Reducer.Value! - var initialSnapshot: UnsafeMutablePointer? - - try unsafeReentrantRead { db in - // Transaction is needed for snapshotting - if db.isInsideTransaction { - initialSnapshot = try? db.takeVersionSnapshot() - initialValue = try observer.fetchInitialValue(db) - } else { - try db.inTransaction(.deferred) { - initialSnapshot = try? db.takeVersionSnapshot() - initialValue = try observer.fetchInitialValue(db) - return .commit - } - } - } - + let initialSnapshot = try makeSnapshot() + let initialValue = try initialSnapshot.read(observer.fetchInitialValue) onChange(initialValue) - - // Now wait for the writer - _weakAsyncWriteWithoutTransaction { db in - defer { - if let initialSnapshot = initialSnapshot { - sqlite3_snapshot_free(initialSnapshot) - } - } - - guard let db = db else { return } - if observer.isCompleted { return } - - do { - // Transaction is needed for snapshotting - try db.inTransaction(.deferred) { - var fetchNeeded = true - if let initialSnapshot = initialSnapshot { - do { - fetchNeeded = try db.wasChanged(since: initialSnapshot) - } catch { - } - } - - // Don't miss eventual changes between the - // initial fetch and the writer access. - if fetchNeeded, let value = try observer.fetchValue(db) { - observer.notifyChange(value) - } - return .commit - } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - observer.notifyErrorAndComplete(error) - } - } + add(observer: observer, from: initialSnapshot) } catch { observer.cancel() onError(error) } } else { - _weakAsyncRead { [weak self] dbResult in - guard let dbResult = dbResult else { return } - guard let self = self else { return } - if observer.isCompleted { return } - - do { - let db = try dbResult.get() + let label = configuration.identifier( + defaultLabel: "GRDB.DatabasePool", + purpose: "ValueObservation") + configuration + .makeDispatchQueue(label: label) + .async { [weak self] in + guard let self = self else { return } + if observer.isCompleted { return } - // Grab a snapshot of the state of the database and perform - // the initial fetch. - var initialSnapshot = try? db.takeVersionSnapshot() - let initialValue = try observer.fetchInitialValue(db) - - observer.notifyChange(initialValue) - - // Now wait for the writer - self._weakAsyncWriteWithoutTransaction { db in - defer { - if let initialSnapshot = initialSnapshot { - sqlite3_snapshot_free(initialSnapshot) - } - } - - guard let db = db else { return } - if observer.isCompleted { return } - - do { - // Transaction is needed for snapshotting - try db.inTransaction(.deferred) { - var fetchNeeded = true - if let initialSnapshot = initialSnapshot { - do { - fetchNeeded = try db.wasChanged(since: initialSnapshot) - } catch { - } - } - - // Don't miss eventual changes between the - // initial fetch and the writer access. - if fetchNeeded, let value = try observer.fetchValue(db) { - observer.notifyChange(value) - } - return .commit - } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - observer.notifyErrorAndComplete(error) - } + do { + let initialSnapshot = try self.makeSnapshot() + let initialValue = try initialSnapshot.read(observer.fetchInitialValue) + observer.notifyChange(initialValue) + self.add(observer: observer, from: initialSnapshot) + } catch { + observer.notifyErrorAndComplete(error) } - } catch { - observer.notifyErrorAndComplete(error) - } } } return observer } + // Support for _addConcurrent(observation:) + private func add( + observer: ValueObserver, + from initialSnapshot: DatabaseSnapshot) + { + _weakAsyncWriteWithoutTransaction { db in + guard let db = db else { return } + if observer.isCompleted { return } + + do { + // Transaction is needed for version snapshotting + try db.inTransaction(.deferred) { + var fetchNeeded = true + withExtendedLifetime(initialSnapshot) { + if let initialVersion = initialSnapshot.version { + do { + fetchNeeded = try db.wasChanged(since: initialVersion) + } catch { + // ignore: we'll just re-fetch + } + } + } + + if fetchNeeded, let value = try observer.fetchValue(db) { + observer.notifyChange(value) + } + return .commit + } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) + } catch { + observer.notifyErrorAndComplete(error) + } + } + } + // MARK: - Custom FTS5 Tokenizers #if SQLITE_ENABLE_FTS5 diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 483b8de79..85175047f 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -14,6 +14,9 @@ public class DatabaseSnapshot: DatabaseReader { serializedDatabase.configuration } + /// Not nil iff SQLite was compiled with `SQLITE_ENABLE_SNAPSHOT`. + private(set) var version: UnsafeMutablePointer? + init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = configuration configuration.readonly = true @@ -33,12 +36,16 @@ public class DatabaseSnapshot: DatabaseReader { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } try db.beginSnapshotTransaction() + version = try? db.takeVersionSnapshot() } } deinit { // Leave snapshot isolation - serializedDatabase.sync { db in + serializedDatabase.reentrantSync { db in + if let version = version { + sqlite3_snapshot_free(version) + } try? db.commit() } }