DatabaseReader async methods support Task cancellation

This commit is contained in:
Gwendal Roué committed 2024-07-28 13:59:38 +02:00
1 parent a52265016a
commit 10c9d31149
8 files changed
+499 -109

No files matched your search

+5 -1
View File
@@ -10,4 +10,8 @@
// Warning: Converting non-sendable function value to '@Sendable (Database) throws -> sending [Player]' may introduce data races
ValueObservation.tracking(Player.fetchAll())
-> Enable `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` in Build Settings
-> Enable `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` in Build Settings
---
Task cancellation is now honored (exclusively in async accesses)
+85
View File
@@ -365,6 +365,50 @@ extension DatabasePool: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// 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 value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
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 valueWrapper.value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
@@ -414,6 +458,47 @@ extension DatabasePool: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// 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 value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
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 valueWrapper.value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
+18
View File
@@ -247,6 +247,17 @@ extension DatabaseQueue: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
try value(db)
}
}
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
@@ -274,6 +285,13 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await writer.execute(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
+84 -104
View File
@@ -188,6 +188,38 @@ public protocol DatabaseReader: AnyObject, Sendable {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func read<T>(_ 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<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T
/// Schedules read-only database operations for execution, and
/// returns immediately.
///
@@ -256,6 +288,44 @@ public protocol DatabaseReader: AnyObject, Sendable {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func unsafeRead<T>(_ 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
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> 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<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T
/// Schedules database operations for execution, and returns immediately.
///
/// This method is "unsafe" because the database reader does nothing more
@@ -432,110 +502,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<T>(
_ value: 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 value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
return try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
try continuation.resume(returning: valueWrapper.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
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> 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<T>(
_ value: 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 value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
return try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
try continuation.resume(returning: valueWrapper.value(result.get()))
} catch {
continuation.resume(throwing: error)
}
}
}
}
}
#if canImport(Combine)
extension DatabaseReader {
// MARK: - Publishing Database Values
@@ -696,6 +662,13 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.read(value)
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
@@ -707,6 +680,13 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
+16 -4
View File
@@ -150,6 +150,13 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await reader.execute(value)
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
@@ -160,10 +167,15 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
reader.async { value(.success($0)) }
// 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
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
@@ -293,6 +293,46 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// 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 value: (Database) throws -> T = value
let valueWrapper = UncheckedSendableWrapper(value: value)
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 valueWrapper.value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
@@ -318,6 +358,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
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync { db in
@@ -915,6 +915,13 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.read(value)
}
public func asyncRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
@@ -926,6 +933,13 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: sending @escaping (Database) throws -> sending T
) async throws -> sending T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: sending @escaping (Result<Database, Error>) -> Void
) {
+226
View File
@@ -344,6 +344,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<Task<Void, any Error>?>(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<Task<Void, any Error>?>(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<Task<Void, any Error>?>(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<Task<Void, any Error>?>(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
}
}