SerializedDatabase support for async db access with support for Task cancellation

This commit is contained in:
Gwendal Roué committed 2024-07-28 13:59:38 +02:00
1 parent 4ddf4bca5f
commit 737cb14996
1 file changed
+128
@@ -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<T>(
_ block: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
// Prevent compiler warning with an unchecked Sendable wrapper, due
// to <https://github.com/apple/swift/issues/73315>.
// FIXME: remove the closure copy when <https://github.com/apple/swift/issues/74457> 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<DatabaseAccessCancellationState>
/// 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<Value>(
_ fn: (UnsafeContinuation<Value, any Error>) -> 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<Value>(_ 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()
}
}