diff --git a/GRDB/Core/Concurrency/SerializedDatabase.swift b/GRDB/Core/Concurrency/SerializedDatabase.swift index 30ac568b1..e55323e22 100644 --- a/GRDB/Core/Concurrency/SerializedDatabase.swift +++ b/GRDB/Core/Concurrency/SerializedDatabase.swift @@ -250,6 +250,32 @@ final class SerializedDatabase { return try block(db) } + /// Asynchrously executes the block. + @available(iOS 13, macOS 10.15, tvOS 13, *) + func execute( + _ block: sending @escaping (Database) throws -> sending T + ) async throws -> sending T { + // Prevent compiler warning with an unchecked Sendable wrapper, due + // to . + // FIXME: remove the closure copy when is fixed. + let block: (Database) throws -> T = block + let blockWrapper = UncheckedSendableWrapper(value: block) + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + self.async { db in + do { + let result = try dbAccess.inDatabase(db) { + try blockWrapper.value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + func interrupt() { // Intentionally not scheduled in our serial queue db.interrupt() @@ -293,3 +319,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() + } +}