WALSnapshotTransaction is Sendable

This commit is contained in:
Gwendal Roué committed 2024-07-27 16:37:33 +02:00
1 parent 2aabc4c10e
commit 7fd34012b4
5 files changed
+70 -34

No files matched your search

+4
View File
@@ -415,6 +415,10 @@ extension DatabaseError {
static func connectionIsClosed() -> Self { static func connectionIsClosed() -> Self {
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed") DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
} }
static func snapshotIsLost() -> Self {
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
} }
// Support for `catch DatabaseError.SQLITE_XXX` // Support for `catch DatabaseError.SQLITE_XXX`
+1 -1
View File
@@ -318,7 +318,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return try reader.reentrantSync { db in return try reader.reentrantSync { db in
let result = try value(db) let result = try value(db)
if snapshotIsLost(db) { if snapshotIsLost(db) {
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") throw DatabaseError.snapshotIsLost()
} }
return result return result
} }
+56 -24
View File
@@ -3,9 +3,28 @@
/// ///
/// `WALSnapshotTransaction` **takes ownership** of its reader /// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually). /// `SerializedDatabase` (TODO: make it a move-only type eventually).
class WALSnapshotTransaction { final class WALSnapshotTransaction: @unchecked Sendable {
private let reader: SerializedDatabase // @unchecked because `databaseAccess` is protected by a mutex.
private let release: (_ isInsideTransaction: Bool) -> Void
private struct DatabaseAccess {
let reader: SerializedDatabase
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
func commitAndRelease() {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
}
}
// TODO: consider using the serialized DispatchQueue of reader instead of a lock.
/// nil when closed
private let databaseAccessMutex: Mutex<DatabaseAccess?>
/// The state of the database at the beginning of the transaction. /// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot let walSnapshot: WALSnapshot
@@ -36,10 +55,11 @@ class WALSnapshotTransaction {
/// is no longer used. /// is no longer used.
init( init(
onReader reader: SerializedDatabase, onReader reader: SerializedDatabase,
release: @escaping (_ isInsideTransaction: Bool) -> Void) release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws throws
{ {
assert(reader.configuration.readonly) assert(reader.configuration.readonly)
let databaseAccess = DatabaseAccess(reader: reader, release: release)
do { do {
// Open a long-lived transaction, and enter snapshot isolation // Open a long-lived transaction, and enter snapshot isolation
@@ -50,44 +70,56 @@ class WALSnapshotTransaction {
try db.clearSchemaCacheIfNeeded() try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db) return try WALSnapshot(db)
} }
self.reader = reader self.databaseAccessMutex = Mutex(databaseAccess)
self.release = release
} catch { } catch {
// self is not initialized, so deinit will not run. // self is not initialized, so deinit will not run.
Self.commitAndRelease(reader: reader, release: release) databaseAccess.commitAndRelease()
throw error throw error
} }
} }
deinit { deinit {
Self.commitAndRelease(reader: reader, release: release) close()
} }
/// Executes database operations in the snapshot transaction, and /// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing. /// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) rethrows -> T { func read<T>(_ value: (Database) throws -> T) throws -> T {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does. try databaseAccessMutex.withLock { databaseAccess in
try reader.sync(value) guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
return try databaseAccess.reader.sync(value)
}
} }
/// Schedules database operations for execution, and /// Schedules database operations for execution, and
/// returns immediately. /// returns immediately.
func asyncRead(_ value: @escaping (Database) -> Void) { func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does. databaseAccessMutex.withLock { databaseAccess in
reader.async(value) guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
databaseAccess.reader.async { db in
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
// At least check if self was closed:
if self.databaseAccessMutex.value == nil {
value(.failure(DatabaseError.snapshotIsLost()))
}
value(.success(db))
}
}
} }
private static func commitAndRelease( func close() {
reader: SerializedDatabase, databaseAccessMutex.withLock { databaseAccess in
release: (_ isInsideTransaction: Bool) -> Void) databaseAccess?.commitAndRelease()
{ databaseAccess = nil
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
} }
release(isInsideTransaction)
} }
} }
#endif #endif
@@ -352,10 +352,11 @@ extension ValueConcurrentObserver {
let initialFetchTransaction = try result.get() let initialFetchTransaction = try result.get()
// Second async jump because that's how // Second async jump because that's how
// `DatabasePool.asyncWALSnapshotTransaction` has to be used. // `DatabasePool.asyncWALSnapshotTransaction` has to be used.
initialFetchTransaction.asyncRead { db in initialFetchTransaction.asyncRead { dbResult in
do { do {
let fetchedValue: Reducer.Fetched let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion let initialRegion: DatabaseRegion
let db = try dbResult.get()
switch self.trackingMode { switch self.trackingMode {
case let .constantRegion(regions): case let .constantRegion(regions):
@@ -429,11 +430,9 @@ extension ValueConcurrentObserver {
// checkpointed. That's why we'll keep `initialFetchTransaction` // checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done. // alive until the comparison is done.
// //
// However, we want to release `initialFetchTransaction` as soon as // However, we want to close `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes // possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional // available for other reads.
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
let events = self.lock.synchronized { self.notificationCallbacks?.events } let events = self.lock.synchronized { self.notificationCallbacks?.events }
@@ -446,7 +445,7 @@ extension ValueConcurrentObserver {
// Was the database modified since the initial fetch? // Was the database modified since the initial fetch?
let isModified: Bool let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) { if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot) let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering") assert(ordering <= 0, "Unexpected snapshot ordering")
isModified = ordering < 0 isModified = ordering < 0
} else { } else {
@@ -454,9 +453,9 @@ extension ValueConcurrentObserver {
isModified = true isModified = true
} }
// Comparison done: end the WAL snapshot transaction // Comparison done: close the WAL snapshot transaction
// and release its reader connection. // and release its reader connection.
initialFetchTransaction = nil initialFetchTransaction.close()
if isModified { if isModified {
events.databaseDidChange?() events.databaseDidChange?()
+2 -1
View File
@@ -96,10 +96,11 @@
- [ ] GRDB7: Consider putting a Task cancellation handler on async methods. - [ ] GRDB7: Consider putting a Task cancellation handler on async methods.
- [X] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553 - [X] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553
- [X] GRDB7: Remove concurrenRead and DatabaseFuture - [X] GRDB7: Remove concurrenRead and DatabaseFuture
- [ ] GRDB7: Merge `_ValueReducer` into `ValueReducer`
- [ ] GRDB7: Sendable conformances - [ ] GRDB7: Sendable conformances
- [ ] SerializedDatabase Sendable async closure - [ ] SerializedDatabase Sendable async closure
- [X] OnDemandFuture Sendable async closure - [X] OnDemandFuture Sendable async closure
- [ ] WALSnapshotTransaction refactor - [X] WALSnapshotTransaction refactor
- [X] anydatabasecancellable - [X] anydatabasecancellable
- [ ] anydatabaseregionconvertible - [ ] anydatabaseregionconvertible
- [ ] anyfetchrequest - [ ] anyfetchrequest