From b85121d456c8091e8cf6cf8f50cd4ba0d2e6311a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 16 Jun 2024 17:53:04 +0200 Subject: [PATCH 1/8] Database support for cancellation --- GRDB/Core/Database+Statements.swift | 14 +++ GRDB/Core/Database.swift | 138 ++++++++++++++++++++++------ GRDB/Core/Statement.swift | 2 +- 3 files changed, 127 insertions(+), 27 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index b83006a19..9c5119e3b 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -439,6 +439,7 @@ extension Database { // documentation of this method for more information). try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) + // Cancelled database accesses must not execute. // Suspended databases must not execute statements that create the risk // of `0xdead10cc` exception (see the documentation of this method for // more information). @@ -491,6 +492,19 @@ extension Database { // and throws the user-provided cancelled commit error. try observationBroker?.statementDidFail(statement) + if #available(iOS 13, macOS 10.15, tvOS 13, *) { + switch ResultCode(rawValue: resultCode) { + case .SQLITE_INTERRUPT, .SQLITE_ABORT: + if suspensionMutex.load().isCancelled { + // The only error that a user sees when a Task is cancelled + // is CancellationError. + throw CancellationError() + } + default: + break + } + } + // Throw statement failure throw DatabaseError( resultCode: resultCode, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index fb0715e4e..da6acb67a 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -312,18 +312,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// `isRecordingSelectedRegion` is true. var selectedRegion = DatabaseRegion() - /// Support for `checkForAbortedTransaction()` - var isInsideTransactionBlock = false - - /// Support for `checkForSuspensionViolation(from:)` - let isSuspendedMutex = Mutex(false) - /// Support for `checkForSuspensionViolation(from:)` /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? + // MARK: - Suspension + + struct Suspension { + /// If true, the database is suspended and should not acquire any + /// write lock in order to avoid the 0xDEAD10CC exception. + var isSuspended: Bool + + /// If true, the database access has been cancelled. + var isCancelled: Bool + } + + /// Support for `checkForSuspensionViolation(from:)` + let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false)) + // MARK: - Transaction Date + /// Support for `checkForAbortedTransaction()` + var isInsideTransactionBlock = false + enum AutocommitState { case off case on @@ -635,7 +646,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib guard code == SQLITE_OK else { // So there remain some unfinalized prepared statement somewhere. if let log = Self.logError { - if code == SQLITE_BUSY { + if ResultCode(rawValue: code).primaryResultCode == .SQLITE_BUSY { // Let the user know about unfinalized statements that did // prevent the connection from closing properly. var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil) @@ -1149,12 +1160,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// Suspension ends with `resume()`. func suspend() { - let needsInterrupt = isSuspendedMutex.withLock { isSuspended in - if isSuspended { + let needsInterrupt = suspensionMutex.withLock { suspension in + if suspension.isSuspended { return false } - isSuspended = true + suspension.isSuspended = true return true } @@ -1179,7 +1190,37 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// See suspend(). func resume() { - isSuspendedMutex.store(false) + suspensionMutex.withLock { + $0.isSuspended = false + } + } + + /// Cancels the current database access. All statements but ROLLBACK + /// will throw `CancellationError`, until `uncancel()` is called. + /// + /// This method can be called from any thread. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func cancel() { + let needsInterrupt = suspensionMutex.withLock { suspension in + if suspension.isCancelled { + return false + } + + suspension.isCancelled = true + return true + } + + if needsInterrupt { + interrupt() + } + } + + /// Undo `cancel()`. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func uncancel() { + suspensionMutex.withLock { + $0.isCancelled = false + } } /// Support for `checkForSuspensionViolation(from:)` @@ -1203,15 +1244,51 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return journalMode } - /// If the database is suspended, and executing the statement would lock the - /// database in a way that may trigger the [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report), - /// this method rollbacks the current transaction and throws `SQLITE_ABORT`. + /// Prevents a statement from running, if the database is suspended, or + /// if the current database access is cancelled by Task cancellation. /// - /// See `suspend()` and ``Configuration/observesSuspensionNotifications``. + /// Transaction rollbacks are always allowed. For other statements: + /// + /// - When database access is cancelled, this method + /// throws `CancellationError`. + /// + /// - When database is suspensed, and if the statement would lock the + /// database in a way that may trigger the 0xDEAD10CC exception, this + /// method rollbacks the current transaction and throws `SQLITE_ABORT`. + /// + /// See `cancel()`, `suspend()` and + /// ``Configuration/observesSuspensionNotifications``. func checkForSuspensionViolation(from statement: Statement) throws { - let needsAbort = try isSuspendedMutex.withLock { isSuspended in - guard isSuspended else { - return false + // No reason for suspension should prevent rollbacks: + // + // - A rollback releases the write lock when the database + // is interrupted, when preventing 0xDEAD10CC. + // + // - A rollback properly closes a transaction that fails because + // it runs in a Task that was cancelled. + // + // Finally, a rollback must be run by GRDB, not by a direct call + // to `sqlite3_exec`, so that transaction observers are + // properly notified. + if statement.transactionEffect == .rollbackTransaction { + return + } + + // How should we interrupt the statement? + enum Interrupt { + case abort // Rollback and throw SQLITE_ABORT + case cancel // Throw CancellationError + } + + let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in + // Check for cancellation first, so that the only error that + // a user sees when a Task is cancelled is CancellationError. + if suspension.isCancelled { + return .cancel + } + + guard suspension.isSuspended else { + return nil } if try journalMode() == "wal" && statement.isReadonly { @@ -1222,7 +1299,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Those are not read-only: // - INSERT ... // - BEGIN IMMEDIATE TRANSACTION - return false + return nil } if statement.releasesDatabaseLock { @@ -1231,20 +1308,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // - ROLLBACK // - ROLLBACK TRANSACTION TO SAVEPOINT // - RELEASE SAVEPOINT - return false + return nil } // Assume statement can acquire a write lock: abort. - return true + return .abort } - if needsAbort { + switch interrupt { + case nil: + break + + case .cancel: + if #available(iOS 13, macOS 10.15, tvOS 13, *) { + throw CancellationError() + } else { + // GRDB bug: cancellation is a Swift concurrency feature + fatalError("Can't cancel without support for Swift concurrency") + } + + case .abort: // Attempt at releasing an eventual lock with ROLLBACk, // as explained in Database.suspend(). - // - // Use sqlite3_exec instead of `try? rollback()` in order to avoid - // an infinite loop in checkForSuspensionViolation(from:) - _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + try? rollback() throw DatabaseError( resultCode: .SQLITE_ABORT, diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 395688709..ada39225a 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -35,7 +35,7 @@ extension String { } public final class Statement { - enum TransactionEffect { + enum TransactionEffect: Equatable { case beginTransaction case commitTransaction case rollbackTransaction From 40140afb8ca8ad9251361db42889659cd197b219 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 16 Jun 2024 17:53:25 +0200 Subject: [PATCH 2/8] SerializedDatabase support for async db access with support for Task cancellation --- GRDB/Core/SerializedDatabase.swift | 122 +++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index f1dfe0572..faa7b1af1 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -243,6 +243,26 @@ final class SerializedDatabase { return try block(db) } + /// Asynchrously executes the block. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func execute( + _ block: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + self.async { db in + do { + let result = try dbAccess.inDatabase(db) { + try block(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + func interrupt() { // Intentionally not scheduled in our serial queue db.interrupt() @@ -286,3 +306,105 @@ final class SerializedDatabase { // It happens the job of SerializedDatabase is precisely to provide thread-safe // access to `Database`. extension SerializedDatabase: @unchecked Sendable { } + +// MARK: - Task Cancellation Support + +@available(iOS 13, macOS 10.15, tvOS 13, *) +enum DatabaseAccessCancellationState: @unchecked Sendable { + // @unchecked Sendable because database is only accessed from its + // dispatch queue. + case notConnected + case connected(Database) + case cancelled + case expired +} + +@available(iOS 13, macOS 10.15, tvOS 13, *) +typealias CancellableDatabaseAccess = Mutex + +/// Supports Task cancellation in async database accesses. +/// +/// Usage: +/// +/// ```swift +/// let dbAccess = CancellableDatabaseAccess() +/// return try dbAccess.withCancellableContinuation { continuation in +/// asyncDatabaseAccess { db in +/// do { +/// let result = try dbAccess.inDatabase(db) { +/// // Perform database operations +/// } +/// continuation.resume(returning: result) +/// } catch { +/// continuation.resume(throwing: error) +/// } +/// } +/// } +/// ``` +@available(iOS 13, macOS 10.15, tvOS 13, *) +extension CancellableDatabaseAccess: DatabaseCancellable { + convenience init() { + self.init(.notConnected) + } + + func cancel() { + withLock { state in + switch state { + case let .connected(db): + db.cancel() + state = .cancelled + case .notConnected: + state = .cancelled + case .cancelled, .expired: + break + } + } + } + + func withCancellableContinuation( + _ fn: (UnsafeContinuation) -> Void + ) async throws -> Value { + try await withTaskCancellationHandler { + try checkCancellation() + return try await withUnsafeThrowingContinuation { continuation in + fn(continuation) + } + } onCancel: { + cancel() + } + } + + func checkCancellation() throws { + try withLock { state in + if case .cancelled = state { + throw CancellationError() + } + } + } + + /// Wraps a full database access with cancellation support. When this + /// method returns, the database is NOT cancelled. + func inDatabase(_ db: Database, _ work: () throws -> sending Value) throws -> sending Value { + try withLock { state in + switch state { + case .connected, .expired: + fatalError("Can't use a CancellableDatabaseAccess twice") + case .notConnected: + state = .connected(db) + case .cancelled: + throw CancellationError() + } + } + + defer { + withLock { state in + if case .cancelled = state { + db.uncancel() + } + state = .expired + } + } + + return try work() + } +} From 5ecf9f67fb38a946ab83f3e64e00e2f6582e29d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 12:27:52 +0200 Subject: [PATCH 3/8] Vendor AsyncSemaphore Semaphores allow tests to precisely schedule ordering of async jobs --- GRDB.xcodeproj/project.pbxproj | 4 + GRDBCustom.xcodeproj/project.pbxproj | 4 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + Tests/GRDBTests/AsyncSemaphore.swift | 256 ++++++++++++++++++ 5 files changed, 276 insertions(+) create mode 100644 Tests/GRDBTests/AsyncSemaphore.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 4185082bb..8cdbcc0aa 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -88,6 +88,7 @@ 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 563866CB2C847659004C515A /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563866CA2C847654004C515A /* AsyncSemaphore.swift */; }; 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; 563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */; }; 563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; }; @@ -518,6 +519,7 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; + 563866CA2C847654004C515A /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = ""; }; 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; @@ -1010,6 +1012,7 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( + 563866CA2C847654004C515A /* AsyncSemaphore.swift */, 56677C14241D14450050755D /* FailureTestCase.swift */, 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 563EA3E02C7B3A22001BE0D4 /* Mutex.swift */, @@ -2115,6 +2118,7 @@ 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, + 563866CB2C847659004C515A /* AsyncSemaphore.swift in Sources */, 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 04d29555f..e1b707bca 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -309,6 +309,7 @@ 56DF0015228DDB8300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF37A723D77AA0009AAA05 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF37A623D77AA0009AAA05 /* Refinable.swift */; }; + 56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */; }; 56E4F7F92392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */; }; 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */; }; 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; @@ -830,6 +831,7 @@ 56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56DF37A623D77AA0009AAA05 /* Refinable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = ""; }; + 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; @@ -1032,6 +1034,7 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( + 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */, 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */, 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 563EA3E22C7B3A3A001BE0D4 /* Mutex.swift */, @@ -2358,6 +2361,7 @@ 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */, + 56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */, 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5616B50028B5F5490052017E /* SingletonRecordTest.swift in Sources */, 56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 2058f693f..d4e67092f 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -495,6 +495,8 @@ 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; + 56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; }; + 56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; }; 56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; 56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -752,6 +754,7 @@ 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; + 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; 56F61DEF283D484700AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; @@ -884,6 +887,7 @@ 56419CAD24A54054004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419D5824A54061004967E1 /* AssociationRowScopeSearchTests.swift */, 56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */, 565A27CB27871FFF00659A62 /* BackupTestCase.swift */, 567B5C272AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift */, 56419CD424A54057004967E1 /* CGFloatTests.swift */, @@ -1493,6 +1497,7 @@ 56419ED724A54063004967E1 /* ColumnInfoTests.swift in Sources */, 56419D9F24A54062004967E1 /* CompilationSubClassTests.swift in Sources */, 567B5C3F2AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */, + 56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */, 56419DBB24A54062004967E1 /* ValueObservationRegionRecordingTests.swift in Sources */, 56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -1742,6 +1747,7 @@ 56419ED824A54063004967E1 /* ColumnInfoTests.swift in Sources */, 56419DA024A54062004967E1 /* CompilationSubClassTests.swift in Sources */, 567B5C402AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */, + 56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */, 56419DBC24A54062004967E1 /* ValueObservationRegionRecordingTests.swift in Sources */, 56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index d499535f3..1359a5a85 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -497,6 +497,8 @@ 568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; + 56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; }; + 56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; }; 56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; 56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -755,6 +757,7 @@ 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; + 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; 56F61DF5283D4AB100AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; @@ -888,6 +891,7 @@ 56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */, 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */, 565A27C827871FE500659A62 /* BackupTestCase.swift */, 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */, 56419F6B24A5409A004967E1 /* CGFloatTests.swift */, @@ -1499,6 +1503,7 @@ 5641A02424A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */, 5641A12024A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */, 5641A04224A540A1004967E1 /* FTS5TableBuilderTests.swift in Sources */, + 56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */, 5641A10624A540A1004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5641A11A24A540A1004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, 5641A05424A540A1004967E1 /* DatabaseWriterTests.swift in Sources */, @@ -1748,6 +1753,7 @@ 5641A02524A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */, 5641A12124A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */, 5641A04324A540A1004967E1 /* FTS5TableBuilderTests.swift in Sources */, + 56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */, 5641A10724A540A1004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5641A11B24A540A1004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, 5641A05524A540A1004967E1 /* DatabaseWriterTests.swift in Sources */, diff --git a/Tests/GRDBTests/AsyncSemaphore.swift b/Tests/GRDBTests/AsyncSemaphore.swift new file mode 100644 index 000000000..6e8d474b3 --- /dev/null +++ b/Tests/GRDBTests/AsyncSemaphore.swift @@ -0,0 +1,256 @@ +// Vendored from + +// Copyright (C) 2022 Gwendal RouΓ© +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import Foundation + +/// An object that controls access to a resource across multiple execution +/// contexts through use of a traditional counting semaphore. +/// +/// You increment a semaphore count by calling the ``signal()`` method, and +/// decrement a semaphore count by calling ``wait()`` or one of its variants. +/// +/// ## Topics +/// +/// ### Creating a Semaphore +/// +/// - ``init(value:)`` +/// +/// ### Signaling the Semaphore +/// +/// - ``signal()`` +/// +/// ### Waiting for the Semaphore +/// +/// - ``wait()`` +/// - ``waitUnlessCancelled()`` +@available(iOS 13, macOS 10.15, tvOS 13, *) +public final class AsyncSemaphore: @unchecked Sendable { + /// `Suspension` is the state of a task waiting for a signal. + /// + /// It is a class because instance identity helps `waitUnlessCancelled()` + /// deal with both early and late cancellation. + /// + /// We make it @unchecked Sendable in order to prevent compiler warnings: + /// instances are always protected by the semaphore's lock. + private class Suspension: @unchecked Sendable { + enum State { + /// Initial state. Next is suspendedUnlessCancelled, or cancelled. + case pending + + /// Waiting for a signal, with support for cancellation. + case suspendedUnlessCancelled(UnsafeContinuation) + + /// Waiting for a signal, with no support for cancellation. + case suspended(UnsafeContinuation) + + /// Cancelled before we have started waiting. + case cancelled + } + + var state: State + + init(state: State) { + self.state = state + } + } + + // MARK: - Internal State + + /// The semaphore value. + private var value: Int + + /// As many elements as there are suspended tasks waiting for a signal. + private var suspensions: [Suspension] = [] + + /// The lock that protects `value` and `suspensions`. + /// + /// It is recursive in order to handle cancellation (see the implementation + /// of ``waitUnlessCancelled()``). + private let _lock = NSRecursiveLock() + + // MARK: - Creating a Semaphore + + /// Creates a semaphore. + /// + /// - parameter value: The starting value for the semaphore. Do not pass a + /// value less than zero. + public init(value: Int) { + precondition(value >= 0, "AsyncSemaphore requires a value equal or greater than zero") + self.value = value + } + + deinit { + precondition(suspensions.isEmpty, "AsyncSemaphore is deallocated while some task(s) are suspended waiting for a signal.") + } + + // MARK: - Locking + + // Let's hide the locking primitive in order to avoid a compiler warning: + // + // > Instance method 'lock' is unavailable from asynchronous contexts; + // > Use async-safe scoped locking instead; this is an error in Swift 6. + // + // We're not sweeping bad stuff under the rug. We really need to protect + // our inner state (`value` and `suspension`) across the calls to + // `withUnsafeContinuation`. Unfortunately, this method introduces a + // suspension point. So we need a lock. + private func lock() { _lock.lock() } + private func unlock() { _lock.unlock() } + + // MARK: - Waiting for the Semaphore + + /// Waits for, or decrements, a semaphore. + /// + /// Decrement the counting semaphore. If the resulting value is less than + /// zero, this function suspends the current task until a signal occurs, + /// without blocking the underlying thread. Otherwise, no suspension happens. + public func wait() async { + lock() + + value -= 1 + if value >= 0 { + unlock() + return + } + + await withUnsafeContinuation { continuation in + // Register the continuation that `signal` will resume. + let suspension = Suspension(state: .suspended(continuation)) + suspensions.insert(suspension, at: 0) // FIFO + unlock() + } + } + + /// Waits for, or decrements, a semaphore, with support for cancellation. + /// + /// Decrement the counting semaphore. If the resulting value is less than + /// zero, this function suspends the current task until a signal occurs, + /// without blocking the underlying thread. Otherwise, no suspension happens. + /// + /// If the task is canceled before a signal occurs, this function + /// throws `CancellationError`. + public func waitUnlessCancelled() async throws { + lock() + + value -= 1 + if value >= 0 { + defer { unlock() } + + do { + // All code paths check for cancellation + try Task.checkCancellation() + } catch { + // Cancellation is like a signal: we don't really "consume" + // the semaphore, and restore the value. + value += 1 + throw error + } + + return + } + + // Get ready for being suspended waiting for a continuation, or for + // early cancellation. + let suspension = Suspension(state: .pending) + + try await withTaskCancellationHandler { + try await withUnsafeThrowingContinuation { (continuation: UnsafeContinuation) in + if case .cancelled = suspension.state { + // Early cancellation: waitUnlessCancelled() is called from + // a cancelled task, and the `onCancel` closure below + // has marked the suspension as cancelled. + // Resume with a CancellationError. + unlock() + continuation.resume(throwing: CancellationError()) + } else { + // Current task is not cancelled: register the continuation + // that `signal` will resume. + suspension.state = .suspendedUnlessCancelled(continuation) + suspensions.insert(suspension, at: 0) // FIFO + unlock() + } + } + } onCancel: { + // withTaskCancellationHandler may immediately call this block (if + // the current task is cancelled), or call it later (if the task is + // cancelled later). In the first case, we're still holding the lock, + // waiting for the continuation. In the second case, we do not hold + // the lock. Being able to handle both situations is the reason why + // we use a recursive lock. + lock() + + // We're no longer waiting for a signal + value += 1 + if let index = suspensions.firstIndex(where: { $0 === suspension }) { + suspensions.remove(at: index) + } + + if case let .suspendedUnlessCancelled(continuation) = suspension.state { + // Late cancellation: the task is cancelled while waiting + // from the semaphore. Resume with a CancellationError. + unlock() + continuation.resume(throwing: CancellationError()) + } else { + // Early cancellation: waitUnlessCancelled() is called from + // a cancelled task. + // + // The next step is the `withTaskCancellationHandler` + // operation closure right above. + suspension.state = .cancelled + unlock() + } + } + } + + // MARK: - Signaling the Semaphore + + /// Signals (increments) a semaphore. + /// + /// Increment the counting semaphore. If the previous value was less than + /// zero, this function resumes a task currently suspended in ``wait()`` + /// or ``waitUnlessCancelled()``. + /// + /// - returns: This function returns true if a suspended task is + /// resumed. Otherwise, the result is false, meaning that no task was + /// waiting for the semaphore. + @discardableResult + public func signal() -> Bool { + lock() + + value += 1 + + switch suspensions.popLast()?.state { // FIFO + case let .suspendedUnlessCancelled(continuation): + unlock() + continuation.resume() + return true + case let .suspended(continuation): + unlock() + continuation.resume() + return true + default: + unlock() + return false + } + } +} From fa54b74eba9380bb6a8eda428f7a4c83055d93c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 12:33:03 +0200 Subject: [PATCH 4/8] [BREAKING] DatabaseWriter async methods support Task cancellation --- GRDB/Core/DatabasePool.swift | 28 ++ GRDB/Core/DatabaseQueue.swift | 14 + GRDB/Core/DatabaseWriter.swift | 202 ++++++------- GRDB/Core/SerializedDatabase.swift | 2 +- Tests/GRDBTests/DatabaseWriterTests.swift | 333 ++++++++++++++++++++++ 5 files changed, 479 insertions(+), 100 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e6019cd72..85d1ab951 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -721,6 +721,13 @@ extension DatabasePool: DatabaseWriter { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { guard let readerPool else { @@ -731,6 +738,27 @@ extension DatabasePool: DatabaseWriter { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + asyncBarrierWriteWithoutTransaction { dbResult in + do { + try dbAccess.checkCancellation() + let db = try dbResult.get() + let result = try dbAccess.inDatabase(db) { + try updates(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b6cf6a5b2..3c34be6a8 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -362,11 +362,25 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try writer.sync(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { writer.async { updates(.success($0)) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index e92334047..a1d18fbe6 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -26,14 +26,14 @@ import Dispatch /// - ``writePublisher(receiveOn:updates:)`` /// - ``writePublisher(receiveOn:updates:thenRead:)`` /// - ``writeWithoutTransaction(_:)-4qh1w`` -/// - ``writeWithoutTransaction(_:)-tckw`` +/// - ``writeWithoutTransaction(_:)-4kzng`` /// - ``asyncWrite(_:completion:)`` /// - ``asyncWriteWithoutTransaction(_:)`` /// /// ### Exclusive Access to the Database /// /// - ``barrierWriteWithoutTransaction(_:)-280j1`` -/// - ``barrierWriteWithoutTransaction(_:)-7u4xw`` +/// - ``barrierWriteWithoutTransaction(_:)-6py5x`` /// - ``asyncBarrierWriteWithoutTransaction(_:)`` /// /// ### Reading from the Latest Committed Database State @@ -100,6 +100,40 @@ public protocol DatabaseWriter: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.writeWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T + /// Executes database operations, and returns their result after they have /// finished executing. /// @@ -140,6 +174,50 @@ public protocol DatabaseWriter: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// Database operations are not executed until all currently executing + /// database accesses performed by the database writer finish executing + /// (both reads and writes). At that point, database operations are + /// executed. Once they finish, the database writer can proceed with other + /// database accesses. + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func barrierWriteWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T) + async throws -> T + /// Schedules database operations for execution, and returns immediately. /// /// Database operations are not executed until all currently executing @@ -563,104 +641,16 @@ extension DatabaseWriter { /// would happen while establishing the database access or committing /// the transaction. @available(iOS 13, macOS 10.15, tvOS 13, *) - public func write(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncWrite(updates, completion: { _, result in - continuation.resume(with: result) - }) - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let newPlayerCount = try await writer.writeWithoutTransaction { db in - /// try Player(name: "Arthur").insert(db) - /// return try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations run in the writer dispatch queue, serialized - /// with all database updates performed by this `DatabaseWriter`. - /// - /// The ``Database`` argument to `updates` is valid only during the - /// execution of the closure. Do not store or return the database connection - /// for later use. - /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `updates` - /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. - /// - /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. - @available(iOS 13, macOS 10.15, tvOS 13, *) - public func writeWithoutTransaction(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncWriteWithoutTransaction { db in - do { - try continuation.resume(returning: updates(db)) - } catch { - continuation.resume(throwing: error) - } - } - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// Database operations are not executed until all currently executing - /// database accesses performed by the database writer finish executing - /// (both reads and writes). At that point, database operations are - /// executed. Once they finish, the database writer can proceed with other - /// database accesses. - /// - /// For example: - /// - /// ```swift - /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in - /// try Player(name: "Arthur").insert(db) - /// return try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations run in the writer dispatch queue, serialized - /// with all database updates performed by this `DatabaseWriter`. - /// - /// The ``Database`` argument to `updates` is valid only during the - /// execution of the closure. Do not store or return the database connection - /// for later use. - /// - /// It is a programmer error to call this method from another database - /// access method. Doing so raises a "Database methods are not reentrant" - /// fatal error at runtime. - /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `updates` - /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. - /// - /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. - @available(iOS 13, macOS 10.15, tvOS 13, *) - public func barrierWriteWithoutTransaction( - _ updates: @Sendable @escaping (Database) throws -> T) - async throws -> T - { - try await withUnsafeThrowingContinuation { continuation in - asyncBarrierWriteWithoutTransaction { dbResult in - continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } }) + public func write( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writeWithoutTransaction { db in + var result: T? + try db.inTransaction { + result = try updates(db) + return .commit } + return result! } } @@ -951,11 +941,25 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.writeWithoutTransaction(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func writeWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.writeWithoutTransaction(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try base.barrierWriteWithoutTransaction(updates) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func barrierWriteWithoutTransaction( + _ updates: @Sendable @escaping (Database) throws -> T) + async throws -> T { + try await base.barrierWriteWithoutTransaction(updates) + } + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { base.asyncBarrierWriteWithoutTransaction(updates) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index faa7b1af1..fed985b56 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -384,7 +384,7 @@ extension CancellableDatabaseAccess: DatabaseCancellable { /// Wraps a full database access with cancellation support. When this /// method returns, the database is NOT cancelled. - func inDatabase(_ db: Database, _ work: () throws -> sending Value) throws -> sending Value { + func inDatabase(_ db: Database, execute work: () throws -> Value) throws -> Value { try withLock { state in switch state { case .connected, .expired: diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 581f7d307..181263764 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -427,4 +427,337 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) } + + // MARK: - Task Cancellation + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_writeWithoutTransaction_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_write_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_write_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_write_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_write_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_barrierWriteWithoutTransaction_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } } From d6b91eec85afa2fa012d2e2b070b68c3db693792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 13:07:49 +0200 Subject: [PATCH 5/8] [BREAKING] DatabaseReader async methods support Task cancellation --- GRDB/Core/DatabasePool.swift | 74 +++++++ GRDB/Core/DatabaseQueue.swift | 19 ++ GRDB/Core/DatabaseReader.swift | 179 +++++++++-------- GRDB/Core/DatabaseSnapshot.swift | 20 ++ GRDB/Core/DatabaseSnapshotPool.swift | 45 +++++ GRDB/Core/DatabaseWriter.swift | 14 ++ GRDB/Documentation.docc/Concurrency.md | 2 +- Tests/GRDBTests/DatabaseReaderTests.swift | 226 ++++++++++++++++++++++ 8 files changed, 486 insertions(+), 93 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 85d1ab951..b0f5c1b1a 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -351,6 +351,45 @@ extension DatabasePool: DatabaseReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + try? db.commit() // Ignore commit error + releaseReader(.reuse) + } + do { + let result = try dbAccess.inDatabase(db) { + // The block isolation comes from the DEFERRED transaction. + try db.beginTransaction(.deferred) + try db.clearSchemaCacheIfNeeded() + return try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -395,6 +434,41 @@ extension DatabasePool: DatabaseReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + releaseReader(.reuse) + } + do { + let result = try dbAccess.inDatabase(db) { + try db.clearSchemaCacheIfNeeded() + return try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 3c34be6a8..a1175feee 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -233,6 +233,17 @@ extension DatabaseQueue: DatabaseReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute { db in + try db.isolated(readOnly: true) { + try value(db) + } + } + } + public func asyncRead(_ value: @escaping (Result) -> Void) { writer.async { db in defer { @@ -254,10 +265,18 @@ extension DatabaseQueue: DatabaseReader { } } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { try writer.sync(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await writer.execute(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { writer.async { value(.success($0)) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 2295f6f03..5c52737f7 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -22,14 +22,14 @@ import Dispatch /// ### Reading from the Database /// /// - ``read(_:)-3806d`` -/// - ``read(_:)-4w6gy`` +/// - ``read(_:)-8gyof`` /// - ``readPublisher(receiveOn:value:)`` /// - ``asyncRead(_:)`` /// /// ### Unsafe Methods /// /// - ``unsafeRead(_:)-5i7tf`` -/// - ``unsafeRead(_:)-11mk0`` +/// - ``unsafeRead(_:)-4w54s`` /// - ``unsafeReentrantRead(_:)`` /// - ``asyncUnsafeRead(_:)`` /// @@ -188,6 +188,38 @@ public protocol DatabaseReader: AnyObject, Sendable { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func read(_ value: (Database) throws -> T) throws -> T + /// Executes read-only database operations, and returns their result after + /// they have finished executing. + /// + /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let count = try await reader.read { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T + /// Schedules read-only database operations for execution, and /// returns immediately. /// @@ -254,6 +286,44 @@ public protocol DatabaseReader: AnyObject, Sendable { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func unsafeRead(_ value: (Database) throws -> T) throws -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. See + /// for + /// more information. + /// + /// For example: + /// + /// ```swift + /// let count = try await reader.unsafeRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T + /// Schedules database operations for execution, and returns immediately. /// /// This method is "unsafe" because the database reader does nothing more @@ -428,96 +498,6 @@ extension DatabaseReader { } } -extension DatabaseReader { - // MARK: - Asynchronous Database Access - - /// Executes read-only database operations, and returns their result after - /// they have finished executing. - /// - /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let count = try await reader.read { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations are isolated in a transaction: they do not see - /// changes performed by eventual concurrent writes (even writes performed - /// by other processes). - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. - @available(iOS 13, macOS 10.15, tvOS 13, *) - public func read(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncRead { result in - do { - try continuation.resume(returning: value(result.get())) - } catch { - continuation.resume(throwing: error) - } - } - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// This method is "unsafe" because the database reader does nothing more - /// than providing a database connection. When you use this method, you - /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. See - /// for - /// more information. - /// - /// For example: - /// - /// ```swift - /// let count = try await reader.unsafeRead { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - warning: Database operations may not be wrapped in a transaction. They - /// may see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `value` - /// closure may not return the same value. - /// - warning: Attempts to write in the database may succeed. - /// - /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. - @available(iOS 13, macOS 10.15, tvOS 13, *) - public func unsafeRead(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncUnsafeRead { result in - do { - try continuation.resume(returning: value(result.get())) - } catch { - continuation.resume(throwing: error) - } - } - } - } -} - #if canImport(Combine) extension DatabaseReader { // MARK: - Publishing Database Values @@ -676,6 +656,13 @@ extension AnyDatabaseReader: DatabaseReader { try base.read(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.read(value) + } + public func asyncRead(_ value: @escaping (Result) -> Void) { base.asyncRead(value) } @@ -685,6 +672,13 @@ extension AnyDatabaseReader: DatabaseReader { try base.unsafeRead(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.unsafeRead(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { base.asyncUnsafeRead(value) } @@ -751,6 +745,7 @@ extension DatabaseSnapshotReader { } // There is no such thing as an unsafe access to a snapshot. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) throws -> T { try read(value) } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 197771b24..8a868a416 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -146,18 +146,38 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { // MARK: - Reading from Database + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ block: (Database) throws -> T) rethrows -> T { try reader.sync(block) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await reader.execute(value) + } + public func asyncRead(_ value: @escaping (Result) -> Void) { reader.async { value(.success($0)) } } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { try reader.sync(value) } + // There is no such thing as an unsafe access to a snapshot. + // We can't provide this as a default implementation in + // `DatabaseSnapshotReader`, because of + // . + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await read(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { reader.async { value(.success($0)) } } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 715dabf72..1fc8e788d 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -293,6 +293,40 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + releaseReader(self.poolCompletion(db)) + } + do { + let result = try dbAccess.inDatabase(db) { + try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -313,6 +347,17 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } + // There is no such thing as an unsafe access to a snapshot. + // We can't provide this as a default implementation in + // `DatabaseSnapshotReader`, because of + // . + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await read(value) + } + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync { db in diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index a1d18fbe6..c6637f241 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -905,6 +905,13 @@ extension AnyDatabaseWriter: DatabaseReader { try base.read(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func read( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.read(value) + } + public func asyncRead(_ value: @escaping (Result) -> Void) { base.asyncRead(value) } @@ -914,6 +921,13 @@ extension AnyDatabaseWriter: DatabaseReader { try base.unsafeRead(value) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + public func unsafeRead( + _ value: @Sendable @escaping (Database) throws -> T + ) async throws -> T { + try await base.unsafeRead(value) + } + public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { base.asyncUnsafeRead(value) } diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 1b8050419..475da8262 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -99,7 +99,7 @@ try dbQueue.write { db in } ``` - See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``. + See ``DatabaseReader/read(_:)-8gyof`` and ``DatabaseWriter/write(_:)-88g7e``. Note the identical method names: `read`, `write`. The async version is only available in async Swift functions. diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 6150cd445..df74498b3 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -342,6 +342,232 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool()) +#endif + } + + // MARK: - Task Cancellation + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_read_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_read_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_unsafeRead_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_statement_execution_from_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_cursor_iteration_from_unsafeRead_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) #endif } } From cb1bd8377735a00aea18a27bf2d63647397a344b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 13:43:09 +0200 Subject: [PATCH 6/8] Document that async methods can throw CancellationError --- GRDB/Core/DatabaseReader.swift | 10 ++++++---- GRDB/Core/DatabaseWriter.swift | 14 +++++++++----- GRDB/Documentation.docc/Concurrency.md | 2 ++ GRDB/Documentation.docc/Transactions.md | 9 +++++++-- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5c52737f7..691af1fd1 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -213,8 +213,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// later use. /// /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `value`, or + /// `CancellationError` if the task is cancelled. @available(iOS 13, macOS 10.15, tvOS 13, *) func read( _ value: @Sendable @escaping (Database) throws -> T @@ -317,8 +318,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - warning: Attempts to write in the database may succeed. /// /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `value`, or + /// `CancellationError` if the task is cancelled. @available(iOS 13, macOS 10.15, tvOS 13, *) func unsafeRead( _ value: @Sendable @escaping (Database) throws -> T diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c6637f241..dd9fafb4a 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -128,7 +128,9 @@ public protocol DatabaseWriter: DatabaseReader { /// can see partial updates performed by the `updates` closure. /// /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `updates`, or + /// `CancellationError` if the task is cancelled. @available(iOS 13, macOS 10.15, tvOS 13, *) func writeWithoutTransaction( _ updates: @Sendable @escaping (Database) throws -> T @@ -212,7 +214,9 @@ public protocol DatabaseWriter: DatabaseReader { /// can see partial updates performed by the `updates` closure. /// /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `updates`, or + /// `CancellationError` if the task is cancelled. @available(iOS 13, macOS 10.15, tvOS 13, *) func barrierWriteWithoutTransaction( _ updates: @Sendable @escaping (Database) throws -> T) @@ -637,9 +641,9 @@ extension DatabaseWriter { /// for later use. /// /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`, or any ``DatabaseError`` that - /// would happen while establishing the database access or committing - /// the transaction. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `updates`, or + /// `CancellationError` if the task is cancelled. @available(iOS 13, macOS 10.15, tvOS 13, *) public func write( _ updates: @Sendable @escaping (Database) throws -> T diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 475da8262..b6eef71b6 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -102,6 +102,8 @@ try dbQueue.write { db in See ``DatabaseReader/read(_:)-8gyof`` and ``DatabaseWriter/write(_:)-88g7e``. Note the identical method names: `read`, `write`. The async version is only available in async Swift functions. + + The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rollbacked. - **Combine publishers** diff --git a/GRDB/Documentation.docc/Transactions.md b/GRDB/Documentation.docc/Transactions.md index 2067a1f09..469ffd953 100644 --- a/GRDB/Documentation.docc/Transactions.md +++ b/GRDB/Documentation.docc/Transactions.md @@ -142,16 +142,21 @@ try dbQueue.writeWithoutTransaction { db } ``` -Transactions can't be left opened unless the ``Configuration/allowsUnsafeTransactions`` configuration flag is set: +Make sure all transactions opened from a database access are committed or rollbacked from that same database access, because it is a programmer error to leave an opened transaction: ```swift -// fatal error: A transaction has been left opened at the end of a database access +// fatal error: A transaction has been left +// opened at the end of a database access. try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "BEGIN TRANSACTION") // <- no commit or rollback } ``` +In particular, since commits may throw an error, make sure you perform a rollback when a commit fails. + +This restriction can be left with the ``Configuration/allowsUnsafeTransactions`` configuration flag. + It is possible to ask if a transaction is currently opened: ```swift From 5b4b8a9065ee148af534a3a8bc6eb978fb6c3f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 13:48:00 +0200 Subject: [PATCH 7/8] Async database accesses check for cancellation before returning --- GRDB/Core/SerializedDatabase.swift | 16 ++++-- Tests/GRDBTests/DatabaseReaderTests.swift | 70 +++++++++++++++++++++++ Tests/GRDBTests/DatabaseWriterTests.swift | 62 ++++++++++++++++++++ 3 files changed, 143 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index fed985b56..ede400fce 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -396,15 +396,21 @@ extension CancellableDatabaseAccess: DatabaseCancellable { } } - defer { - withLock { state in + return try throwingFirstError { + try work() + } finally: { + let cancelled = withLock { state in if case .cancelled = state { db.uncancel() + return true + } else { + state = .expired + return false } - state = .expired + } + if cancelled { + throw CancellationError() } } - - return try work() } } diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index df74498b3..6777c08ad 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -381,6 +381,41 @@ class DatabaseReaderTests : GRDBTestCase { #endif } + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + @available(iOS 13, macOS 10.15, tvOS 13, *) func test_statement_execution_from_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { func test(_ dbReader: some DatabaseReader) async throws { @@ -493,6 +528,41 @@ class DatabaseReaderTests : GRDBTestCase { #endif } + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + } + @available(iOS 13, macOS 10.15, tvOS 13, *) func test_statement_execution_from_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { func test(_ dbReader: some DatabaseReader) async throws { diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 181263764..56fb130c6 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -460,6 +460,37 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabasePool()) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + @available(iOS 13, macOS 10.15, tvOS 13, *) func test_statement_execution_from_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { func test(_ dbWriter: some DatabaseWriter) async throws { @@ -691,6 +722,37 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabasePool()) } + @available(iOS 13, macOS 10.15, tvOS 13, *) + func test_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + } + @available(iOS 13, macOS 10.15, tvOS 13, *) func test_statement_execution_from_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { func test(_ dbWriter: some DatabaseWriter) async throws { From 71f555496203141ef8f763e6bfca2cf135115a06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2024 13:50:59 +0200 Subject: [PATCH 8/8] Test cancellation handling from AnyDatabaseReader and AnyDatabaseWriter --- Tests/GRDBTests/DatabaseReaderTests.swift | 16 ++++++++++++++++ Tests/GRDBTests/DatabaseWriterTests.swift | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 6777c08ad..364bb570c 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -379,6 +379,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -414,6 +416,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -451,6 +455,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -492,6 +498,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -526,6 +534,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -561,6 +571,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -598,6 +610,8 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -639,5 +653,7 @@ class DatabaseReaderTests : GRDBTestCase { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 56fb130c6..478cab6c5 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -458,6 +458,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -489,6 +490,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -522,6 +524,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -559,6 +562,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -589,6 +593,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -620,6 +625,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -653,6 +659,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -690,6 +697,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -720,6 +728,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -751,6 +760,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -784,6 +794,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } @available(iOS 13, macOS 10.15, tvOS 13, *) @@ -821,5 +832,6 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) } }