[BREAKING] DatabaseReader async methods support Task cancellation

This commit is contained in:
Gwendal Roué committed 2024-09-01 15:35:37 +02:00
1 parent fa54b74eba
commit d6b91eec85
8 files changed
+486 -93

No files matched your search

+74
View File
@@ -351,6 +351,45 @@ extension DatabasePool: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ 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<Database, Error>) -> 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<T>(
_ 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<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
+19
View File
@@ -233,6 +233,17 @@ extension DatabaseQueue: DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ 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<Database, Error>) -> 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<T>(_ value: (Database) throws -> T) rethrows -> T {
try writer.sync(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
+87 -92
View File
@@ -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<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: @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<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: @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<T>(_ 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
/// <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: @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<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> 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<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> 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<T>(_ value: (Database) throws -> T) throws -> T {
try read(value)
}
+20
View File
@@ -146,18 +146,38 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
try reader.sync(block)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ 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
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await read(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
+45
View File
@@ -293,6 +293,40 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ 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<Database, Error>) -> 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
// <https://github.com/apple/swift/issues/74469>.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> 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
+14
View File
@@ -905,6 +905,13 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> 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<T>(
_ value: @Sendable @escaping (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
+1 -1
View File
@@ -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.
+226
View File
@@ -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<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
}
}