From 53c9d12d290b482fe12fc156b9c21fc58faca741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 23 Feb 2025 15:02:55 +0100 Subject: [PATCH] Async database access no longer require Sendable closures. --- GRDB/Core/DatabasePool.swift | 40 +++++++++++++++++++------- GRDB/Core/DatabaseQueue.swift | 18 ++++++------ GRDB/Core/DatabaseReader.swift | 22 +++++++------- GRDB/Core/DatabaseSnapshot.swift | 8 +++--- GRDB/Core/DatabaseSnapshotPool.swift | 14 +++++++-- GRDB/Core/DatabaseWriter.swift | 40 +++++++++++++------------- GRDB/Core/SerializedDatabase.swift | 12 ++++++-- GRDB/Documentation.docc/Concurrency.md | 2 +- GRDB/Utils/Pool.swift | 12 ++++++-- 9 files changed, 106 insertions(+), 62 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index ce1bae833..9e5a5a700 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -352,13 +352,17 @@ extension DatabasePool: DatabaseReader { } public func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") guard let readerPool else { throw DatabaseError.connectionIsClosed() } + // Avoid compiler warning. There is no data race because `value` is invoked once. + typealias SendableClosure = @Sendable (Database) throws -> T + let value = unsafeBitCast(value, to: SendableClosure.self) + let dbAccess = CancellableDatabaseAccess() return try await dbAccess.withCancellableContinuation { continuation in readerPool.asyncGet { result in @@ -390,13 +394,17 @@ extension DatabasePool: DatabaseReader { } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return } + // Avoid compiler warning. There is no data race because `value` is invoked once. + typealias SendableClosure = @Sendable (Result) -> Void + let value = unsafeBitCast(value, to: SendableClosure.self) + readerPool.asyncGet { result in do { let (reader, releaseReader) = try result.get() @@ -436,12 +444,16 @@ extension DatabasePool: DatabaseReader { } public func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() } + // Avoid compiler warning. There is no data race because `value` is invoked once. + typealias SendableClosure = @Sendable (Database) throws -> T + let value = unsafeBitCast(value, to: SendableClosure.self) + let dbAccess = CancellableDatabaseAccess() return try await dbAccess.withCancellableContinuation { continuation in readerPool.asyncGet { result in @@ -470,13 +482,17 @@ extension DatabasePool: DatabaseReader { } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return } + // Avoid compiler warning. There is no data race because `value` is invoked once. + typealias SendableClosure = @Sendable (Result) -> Void + let value = unsafeBitCast(value, to: SendableClosure.self) + readerPool.asyncGet { result in do { let (reader, releaseReader) = try result.get() @@ -517,7 +533,7 @@ extension DatabasePool: DatabaseReader { } public func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { asyncConcurrentRead(value) } @@ -560,7 +576,7 @@ extension DatabasePool: DatabaseReader { /// /// - parameter value: A function that accesses the database. public func asyncConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { // Check that we're on the writer queue... writer.execute { db in @@ -802,7 +818,7 @@ extension DatabasePool: DatabaseWriter { } public func writeWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { try await writer.execute(updates) } @@ -818,8 +834,12 @@ extension DatabasePool: DatabaseWriter { } public func barrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { + // Avoid compiler warning. There is no data race because `updates` is invoked once. + typealias SendableClosure = @Sendable (Database) throws -> T + let updates = unsafeBitCast(updates, to: SendableClosure.self) + let dbAccess = CancellableDatabaseAccess() return try await dbAccess.withCancellableContinuation { continuation in asyncBarrierWriteWithoutTransaction { dbResult in @@ -838,7 +858,7 @@ extension DatabasePool: DatabaseWriter { } public func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: sending @escaping (Result) -> Void ) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) @@ -894,7 +914,7 @@ extension DatabasePool: DatabaseWriter { } public func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: sending @escaping (Database) -> Void ) { writer.async(updates) } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 37b62fde5..007346509 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader { } public func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await writer.execute { db in try db.isolated(readOnly: true) { @@ -244,7 +244,7 @@ extension DatabaseQueue: DatabaseReader { } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { writer.async { db in defer { @@ -272,13 +272,13 @@ extension DatabaseQueue: DatabaseReader { } public func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await writer.execute(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { writer.async { value(.success($0)) } } @@ -288,7 +288,7 @@ extension DatabaseQueue: DatabaseReader { } public func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { // Check that we're on the writer queue... writer.execute { db in @@ -385,7 +385,7 @@ extension DatabaseQueue: DatabaseWriter { } public func writeWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { try await writer.execute(updates) } @@ -396,13 +396,13 @@ extension DatabaseQueue: DatabaseWriter { } public func barrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { try await writer.execute(updates) } public func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: sending @escaping (Result) -> Void ) { writer.async { updates(.success($0)) } } @@ -450,7 +450,7 @@ extension DatabaseQueue: DatabaseWriter { } public func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: sending @escaping (Database) -> Void ) { writer.async(updates) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 2c9d1cfdd..7d14f64ed 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -22,14 +22,14 @@ import Dispatch /// ### Reading from the Database /// /// - ``read(_:)-3806d`` -/// - ``read(_:)-4d1da`` +/// - ``read(_:)-4zff3`` /// - ``readPublisher(receiveOn:value:)`` /// - ``asyncRead(_:)`` /// /// ### Unsafe Methods /// /// - ``unsafeRead(_:)-5i7tf`` -/// - ``unsafeRead(_:)-5gsav`` +/// - ``unsafeRead(_:)-5b76n`` /// - ``unsafeReentrantRead(_:)`` /// - ``asyncUnsafeRead(_:)`` /// @@ -215,7 +215,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// database access, or the error thrown by `value`, or /// `CancellationError` if the task is cancelled. func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T /// Schedules read-only database operations for execution, and @@ -245,7 +245,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) /// Executes database operations, and returns their result after they have @@ -319,7 +319,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// database access, or the error thrown by `value`, or /// `CancellationError` if the task is cancelled. func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T /// Schedules database operations for execution, and returns immediately. @@ -354,7 +354,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) /// Executes database operations, and returns their result after they have @@ -652,13 +652,13 @@ extension AnyDatabaseReader: DatabaseReader { } public func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await base.read(value) } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { base.asyncRead(value) } @@ -669,13 +669,13 @@ extension AnyDatabaseReader: DatabaseReader { } public func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await base.unsafeRead(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { base.asyncUnsafeRead(value) } @@ -748,7 +748,7 @@ extension DatabaseSnapshotReader { // There is no such thing as an unsafe access to a snapshot. public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { asyncRead(value) } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 7609a3433..d7a73077b 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -152,13 +152,13 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { } public func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await reader.execute(value) } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { reader.async { value(.success($0)) } } @@ -173,13 +173,13 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { // `DatabaseSnapshotReader`, because of // . public func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await read(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { reader.async { value(.success($0)) } } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 20398c556..16a8e028f 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -294,12 +294,16 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } public func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() } + // Avoid compiler warning. There is no data race because `value` is invoked once. + typealias SendableClosure = @Sendable (Database) throws -> T + let value = unsafeBitCast(value, to: SendableClosure.self) + let dbAccess = CancellableDatabaseAccess() return try await dbAccess.withCancellableContinuation { continuation in readerPool.asyncGet { result in @@ -327,13 +331,17 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return } + // Avoid compiler warning. There is no data race because `value` is invoked once. + typealias SendableClosure = @Sendable (Result) -> Void + let value = unsafeBitCast(value, to: SendableClosure.self) + readerPool.asyncGet { result in do { let (reader, releaseReader) = try result.get() @@ -353,7 +361,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { // `DatabaseSnapshotReader`, because of // . public func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await read(value) } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index cbc2041d4..5d6126a09 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -22,18 +22,18 @@ import Dispatch /// ### Writing into the Database /// /// - ``write(_:)-76inz`` -/// - ``write(_:)-3db50`` +/// - ``write(_:)-5u4m3`` /// - ``writePublisher(receiveOn:updates:)`` /// - ``writePublisher(receiveOn:updates:thenRead:)`` /// - ``writeWithoutTransaction(_:)-4qh1w`` -/// - ``writeWithoutTransaction(_:)-67mri`` +/// - ``writeWithoutTransaction(_:)-93qim`` /// - ``asyncWrite(_:completion:)`` /// - ``asyncWriteWithoutTransaction(_:)`` /// /// ### Exclusive Access to the Database /// /// - ``barrierWriteWithoutTransaction(_:)-280j1`` -/// - ``barrierWriteWithoutTransaction(_:)-48d63`` +/// - ``barrierWriteWithoutTransaction(_:)-2xdrw`` /// - ``asyncBarrierWriteWithoutTransaction(_:)`` /// /// ### Reading from the Latest Committed Database State @@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader { /// database access, or the error thrown by `updates`, or /// `CancellationError` if the task is cancelled. func writeWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T /// Executes database operations, and returns their result after they have @@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader { /// database access, or the error thrown by `updates`, or /// `CancellationError` if the task is cancelled. func barrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T /// Schedules database operations for execution, and returns immediately. @@ -256,7 +256,7 @@ public protocol DatabaseWriter: DatabaseReader { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the barrier access to the database. func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: sending @escaping (Result) -> Void ) /// Schedules database operations for execution, and returns immediately. @@ -290,7 +290,7 @@ public protocol DatabaseWriter: DatabaseReader { /// /// - parameter updates: A closure which accesses the database. func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: sending @escaping (Database) -> Void ) /// Executes database operations, and returns their result after they have @@ -374,7 +374,7 @@ public protocol DatabaseWriter: DatabaseReader { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) } @@ -461,8 +461,8 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - parameter completion: A closure called with the transaction result. public func asyncWrite( - _ updates: @escaping @Sendable (Database) throws -> T, - completion: @escaping @Sendable (Database, Result) -> Void + _ updates: sending @escaping (Database) throws -> T, + completion: sending @escaping (Database, Result) -> Void ) { asyncWriteWithoutTransaction { db in do { @@ -640,7 +640,7 @@ extension DatabaseWriter { /// database access, or the error thrown by `updates`, or /// `CancellationError` if the task is cancelled. public func write( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { try await writeWithoutTransaction { db in var result: T? @@ -885,13 +885,13 @@ extension AnyDatabaseWriter: DatabaseReader { } public func read( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await base.read(value) } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { base.asyncRead(value) } @@ -902,13 +902,13 @@ extension AnyDatabaseWriter: DatabaseReader { } public func unsafeRead( - _ value: @escaping @Sendable (Database) throws -> T + _ value: sending @escaping (Database) throws -> T ) async throws -> T { try await base.unsafeRead(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { base.asyncUnsafeRead(value) } @@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseWriter { } public func writeWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { try await base.writeWithoutTransaction(updates) } @@ -947,19 +947,19 @@ extension AnyDatabaseWriter: DatabaseWriter { } public func barrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T + _ updates: sending @escaping (Database) throws -> T ) async throws -> T { try await base.barrierWriteWithoutTransaction(updates) } public func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: sending @escaping (Result) -> Void ) { base.asyncBarrierWriteWithoutTransaction(updates) } public func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: sending @escaping (Database) -> Void ) { base.asyncWriteWithoutTransaction(updates) } @@ -969,7 +969,7 @@ extension AnyDatabaseWriter: DatabaseWriter { } public func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: sending @escaping (Result) -> Void ) { base.spawnConcurrentRead(value) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index b794fa63e..90891adaf 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -223,7 +223,11 @@ final class SerializedDatabase { } /// Schedules database operations for execution, and returns immediately. - func async(_ block: @escaping @Sendable (Database) -> Void) { + func async(_ block: sending @escaping (Database) -> Void) { + // Avoid compiler warning. There is no data race because `block` is invoked once. + typealias SendableClosure = @Sendable (Database) -> Void + let block = unsafeBitCast(block, to: SendableClosure.self) + queue.async { block(self.db) self.preconditionNoUnsafeTransactionLeft(self.db) @@ -245,8 +249,12 @@ final class SerializedDatabase { /// Asynchrously executes the block. func execute( - _ block: @escaping @Sendable (Database) throws -> T + _ block: sending @escaping (Database) throws -> T ) async throws -> T { + // Avoid compiler warning. There is no data race because `block` is invoked once. + typealias SendableClosure = @Sendable (Database) throws -> T + let block = unsafeBitCast(block, to: SendableClosure.self) + let dbAccess = CancellableDatabaseAccess() return try await dbAccess.withCancellableContinuation { continuation in self.async { db in diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 439ce4fa5..984f31f64 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -97,7 +97,7 @@ try dbQueue.write { db in } ``` - See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``. + See ``DatabaseReader/read(_:)-4zff3`` and ``DatabaseWriter/write(_:)-5u4m3``. Note the identical method names: `read`, `write`. The async version is only available in async Swift functions. diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 661c9c4d9..c6f804d8b 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -121,7 +121,11 @@ final class Pool: Sendable { /// /// - important: The `execute` argument is executed in a serial dispatch /// queue, so make sure you use the element asynchronously. - func asyncGet(_ execute: @escaping @Sendable (Result) -> Void) { + func asyncGet(_ execute: sending @escaping (Result) -> Void) { + // Avoid compiler warning. There is no data race because `execute` is invoked once. + typealias SendableClosure = @Sendable (Result) -> Void + let execute = unsafeBitCast(execute, to: SendableClosure.self) + // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/ // > We wait on the semaphore in the serial queue, which means that // > we’ll have at most one blocked thread when we reach maximum @@ -186,7 +190,11 @@ final class Pool: Sendable { /// Asynchronously runs the `barrier` function when no element is used, and /// before any other element is dequeued. - func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) { + func asyncBarrier(execute barrier: sending @escaping () -> Void) { + // Avoid compiler warning. There is no data race because `barrier` is invoked once. + typealias SendableClosure = @Sendable () -> Void + let barrier = unsafeBitCast(barrier, to: SendableClosure.self) + barrierQueue.async(flags: [.barrier]) { self.itemsGroup.wait() barrier()