From afcac0102f779399655b44aaa58bcf7c47bffa35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 23 Jun 2024 12:35:20 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9A=A0=EF=B8=8F=20EXPERIMENTAL=20-=20SE-0430?= =?UTF-8?q?=20`sending`=20parameter=20and=20result=20values?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GRDB/Core/Concurrency/DatabasePool.swift | 38 +++++-- GRDB/Core/Concurrency/DatabaseQueue.swift | 16 ++- GRDB/Core/Concurrency/DatabaseReader.swift | 48 ++++++--- GRDB/Core/Concurrency/DatabaseSnapshot.swift | 8 +- .../Concurrency/DatabaseSnapshotPool.swift | 9 +- GRDB/Core/Concurrency/DatabaseWriter.swift | 100 +++++++++++++----- .../Core/Concurrency/SerializedDatabase.swift | 11 +- .../Concurrency/WALSnapshotTransaction.swift | 26 ++--- GRDB/Migration/DatabaseMigrator.swift | 2 +- GRDB/Utils/Pool.swift | 22 +++- GRDB/Utils/Utils.swift | 5 + GRDB/ValueObservation/Reducers/Fetch.swift | 8 +- GRDB/ValueObservation/ValueObservation.swift | 8 +- .../ValueObservationScheduler.swift | 26 +++-- Package.swift | 2 + SQLiteCustom/GRDBBase.xcconfig | 2 + Support/GRDBBase.xcconfig | 2 + 17 files changed, 240 insertions(+), 93 deletions(-) diff --git a/GRDB/Core/Concurrency/DatabasePool.swift b/GRDB/Core/Concurrency/DatabasePool.swift index b88e5925f..95a8cb694 100644 --- a/GRDB/Core/Concurrency/DatabasePool.swift +++ b/GRDB/Core/Concurrency/DatabasePool.swift @@ -365,7 +365,9 @@ extension DatabasePool: DatabaseReader { } } - public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -375,6 +377,9 @@ extension DatabasePool: DatabaseReader { do { let (reader, releaseReader) = try result.get() // Second async jump because that's how `Pool.async` has to be used. + // Prevent compiler warning with an unchecked Sendable wrapper, due + // to . + let valueWrapper = UncheckedSendableWrapper(value: value) reader.async { db in defer { try? db.commit() // Ignore commit error @@ -384,9 +389,9 @@ extension DatabasePool: DatabaseReader { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) try db.clearSchemaCacheIfNeeded() - value(.success(db)) + valueWrapper.value(.success(db)) } catch { - value(.failure(error)) + valueWrapper.value(.failure(error)) } } } catch { @@ -409,7 +414,9 @@ extension DatabasePool: DatabaseReader { } } - public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -419,15 +426,18 @@ extension DatabasePool: DatabaseReader { do { let (reader, releaseReader) = try result.get() // Second async jump because that's how `Pool.async` has to be used. + // Prevent compiler warning with an unchecked Sendable wrapper, due + // to . + let valueWrapper = UncheckedSendableWrapper(value: value) reader.async { db in defer { releaseReader(.reuse) } do { try db.clearSchemaCacheIfNeeded() - value(.success(db)) + valueWrapper.value(.success(db)) } catch { - value(.failure(error)) + valueWrapper.value(.failure(error)) } } } catch { @@ -454,7 +464,9 @@ extension DatabasePool: DatabaseReader { } } - public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { + public func spawnConcurrentRead( + _ value: sending @escaping (Result) -> Void + ) { asyncConcurrentRead(value) } @@ -495,7 +507,9 @@ extension DatabasePool: DatabaseReader { /// ``` /// /// - parameter value: A function that accesses the database. - public func asyncConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncConcurrentRead( + _ value: sending @escaping (Result) -> Void + ) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -747,7 +761,9 @@ extension DatabasePool: DatabaseWriter { } } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction( + _ updates: sending @escaping (Result) -> Void + ) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) return @@ -801,7 +817,9 @@ extension DatabasePool: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { + public func asyncWriteWithoutTransaction( + _ updates: sending @escaping (Database) -> Void + ) { writer.async(updates) } } diff --git a/GRDB/Core/Concurrency/DatabaseQueue.swift b/GRDB/Core/Concurrency/DatabaseQueue.swift index 6a65b11c3..49625d8be 100644 --- a/GRDB/Core/Concurrency/DatabaseQueue.swift +++ b/GRDB/Core/Concurrency/DatabaseQueue.swift @@ -247,7 +247,9 @@ extension DatabaseQueue: DatabaseReader { } } - public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { writer.async { db in defer { // Ignore error because we can not notify it. @@ -272,7 +274,9 @@ extension DatabaseQueue: DatabaseReader { try writer.sync(value) } - public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) { writer.async { value(.success($0)) } } @@ -381,7 +385,9 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction( + _ updates: sending @escaping (Result) -> Void + ) { writer.async { updates(.success($0)) } } @@ -427,7 +433,9 @@ extension DatabaseQueue: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { + public func asyncWriteWithoutTransaction( + _ updates: sending @escaping (Database) -> Void + ) { writer.async(updates) } } diff --git a/GRDB/Core/Concurrency/DatabaseReader.swift b/GRDB/Core/Concurrency/DatabaseReader.swift index eaa8be0d5..202af833a 100644 --- a/GRDB/Core/Concurrency/DatabaseReader.swift +++ b/GRDB/Core/Concurrency/DatabaseReader.swift @@ -214,7 +214,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. Its argument /// 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) + func asyncRead( + _ value: sending @escaping (Result) -> Void + ) /// Executes database operations, and returns their result after they have /// finished executing. @@ -285,7 +287,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. Its argument /// 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) + func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) /// Executes database operations, and returns their result after they have /// finished executing. @@ -459,11 +463,18 @@ extension DatabaseReader { /// - 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(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in + public func read( + _ value: 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 value: (Database) throws -> T = value + let valueWrapper = UncheckedSendableWrapper(value: value) + return try await withUnsafeThrowingContinuation { continuation in asyncRead { result in do { - try continuation.resume(returning: value(result.get())) + try continuation.resume(returning: valueWrapper.value(result.get())) } catch { continuation.resume(throwing: error) } @@ -505,11 +516,18 @@ extension DatabaseReader { /// - 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(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in + public func unsafeRead( + _ value: 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 value: (Database) throws -> T = value + let valueWrapper = UncheckedSendableWrapper(value: value) + return try await withUnsafeThrowingContinuation { continuation in asyncUnsafeRead { result in do { - try continuation.resume(returning: value(result.get())) + try continuation.resume(returning: valueWrapper.value(result.get())) } catch { continuation.resume(throwing: error) } @@ -552,7 +570,7 @@ extension DatabaseReader { @available(iOS 13, macOS 10.15, tvOS 13, *) public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping @Sendable (Database) throws -> Output) + value: @escaping @Sendable (Database) throws -> sending Output) -> DatabasePublishers.Read { OnDemandFuture { fulfill in @@ -678,7 +696,9 @@ extension AnyDatabaseReader: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { base.asyncRead(value) } @@ -687,7 +707,9 @@ extension AnyDatabaseReader: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) { base.asyncUnsafeRead(value) } @@ -758,7 +780,9 @@ extension DatabaseSnapshotReader { } // There is no such thing as an unsafe access to a snapshot. - public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) { asyncRead(value) } } diff --git a/GRDB/Core/Concurrency/DatabaseSnapshot.swift b/GRDB/Core/Concurrency/DatabaseSnapshot.swift index 25c7cf05b..929ab355a 100644 --- a/GRDB/Core/Concurrency/DatabaseSnapshot.swift +++ b/GRDB/Core/Concurrency/DatabaseSnapshot.swift @@ -150,7 +150,9 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { try reader.sync(block) } - public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { reader.async { value(.success($0)) } } @@ -158,7 +160,9 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { try reader.sync(value) } - public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) { reader.async { value(.success($0)) } } diff --git a/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift b/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift index 083f52532..7760d1286 100644 --- a/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift +++ b/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift @@ -293,7 +293,9 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } - public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -303,8 +305,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { do { let (reader, releaseReader) = try result.get() // Second async jump because that's how `Pool.async` has to be used. + // Prevent compiler warning with an unchecked Sendable wrapper, due + // to . + let valueWrapper = UncheckedSendableWrapper(value: value) reader.async { db in - value(.success(db)) + valueWrapper.value(.success(db)) releaseReader(self.poolCompletion(db)) } } catch { diff --git a/GRDB/Core/Concurrency/DatabaseWriter.swift b/GRDB/Core/Concurrency/DatabaseWriter.swift index 34a9d4290..a388350a1 100644 --- a/GRDB/Core/Concurrency/DatabaseWriter.swift +++ b/GRDB/Core/Concurrency/DatabaseWriter.swift @@ -179,7 +179,9 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: A closure which accesses the database. Its argument /// 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) + func asyncBarrierWriteWithoutTransaction( + _ updates: sending @escaping (Result) -> Void + ) /// Schedules database operations for execution, and returns immediately. /// @@ -211,7 +213,9 @@ public protocol DatabaseWriter: DatabaseReader { /// for more information. /// /// - parameter updates: A closure which accesses the database. - func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) + func asyncWriteWithoutTransaction( + _ updates: sending @escaping (Database) -> Void + ) /// Executes database operations, and returns their result after they have /// finished executing. @@ -295,7 +299,9 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter value: A closure which accesses the database. Its argument /// 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) + func spawnConcurrentRead( + _ value: sending @escaping (Result) -> Void + ) } extension DatabaseWriter { @@ -381,9 +387,9 @@ 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 -> sending T, + completion: sending @escaping (Database, Result) -> Void + ) { asyncWriteWithoutTransaction { db in do { var result: T? @@ -563,11 +569,20 @@ extension DatabaseWriter { /// would happen while establishing the database access or committing /// the transaction. @available(iOS 13, macOS 10.15, tvOS 13, *) - public func write(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncWrite(updates, completion: { _, result in + public func write( + _ updates: 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 updates: (Database) throws -> T = updates + let updatesWrapper = UncheckedSendableWrapper(value: updates) + return try await withUnsafeThrowingContinuation { continuation in + asyncWrite { db in + try updatesWrapper.value(db) + } completion: { _, result in continuation.resume(with: result) - }) + } } } @@ -601,11 +616,18 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, *) - public func writeWithoutTransaction(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in + public func writeWithoutTransaction( + _ updates: 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 updates: (Database) throws -> T = updates + let updatesWrapper = UncheckedSendableWrapper(value: updates) + return try await withUnsafeThrowingContinuation { continuation in asyncWriteWithoutTransaction { db in do { - try continuation.resume(returning: updates(db)) + try continuation.resume(returning: updatesWrapper.value(db)) } catch { continuation.resume(throwing: error) } @@ -654,12 +676,19 @@ extension DatabaseWriter { /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, *) public func barrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) throws -> T) - async throws -> T + _ updates: sending @escaping (Database) throws -> sending T) + async throws -> sending T { - try await withUnsafeThrowingContinuation { continuation in + // Prevent compiler warning with an unchecked Sendable wrapper, due + // to . + // FIXME: remove the closure copy when is fixed. + let updates: (Database) throws -> T = updates + let updatesWrapper = UncheckedSendableWrapper(value: updates) + return try await withUnsafeThrowingContinuation { continuation in asyncBarrierWriteWithoutTransaction { dbResult in - continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } }) + continuation.resume(with: dbResult.flatMap { db in + Result { try updatesWrapper.value(db) } + }) } } } @@ -758,7 +787,7 @@ extension DatabaseWriter { @available(iOS 13, macOS 10.15, tvOS 13, *) public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - updates: @escaping @Sendable (Database) throws -> Output) + updates: @escaping @Sendable (Database) throws -> sending Output) -> DatabasePublishers.Write { OnDemandFuture { fulfill in @@ -772,7 +801,6 @@ extension DatabaseWriter { .eraseToWritePublisher() } - // TODO: GRDB7 Can SE-0430 avoid the T: Sendable constraint? /// Returns a publisher that publishes one value and completes. /// /// The database is not accessed until subscription. Value and completion @@ -824,10 +852,10 @@ extension DatabaseWriter { @available(iOS 13, macOS 10.15, tvOS 13, *) public func writePublisher( receiveOn scheduler: S = DispatchQueue.main, - updates: @escaping @Sendable (Database) throws -> T, - thenRead value: @escaping @Sendable (Database, T) throws -> Output) + updates: @escaping @Sendable (Database) throws -> sending T, + thenRead value: @escaping @Sendable (Database, T) throws -> sending Output) -> DatabasePublishers.Write - where S: Scheduler, T: Sendable + where S: Scheduler { OnDemandFuture { fulfill in self.asyncWriteWithoutTransaction { db in @@ -841,8 +869,12 @@ extension DatabaseWriter { fulfill(.failure(error)) return } - self.spawnConcurrentRead { [updatesValue] dbResult in - fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } }) + + // Safe because result is not used beyond its transfer + let updatesValueWrapper = UncheckedSendableWrapper(value: updatesValue!) + + self.spawnConcurrentRead { [updatesValueWrapper] dbResult in + fulfill(dbResult.flatMap { db in Result { try value(db, updatesValueWrapper.value) } }) } } } @@ -916,7 +948,9 @@ extension AnyDatabaseWriter: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { base.asyncRead(value) } @@ -925,7 +959,9 @@ extension AnyDatabaseWriter: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { + public func asyncUnsafeRead( + _ value: sending @escaping (Result) -> Void + ) { base.asyncUnsafeRead(value) } @@ -957,11 +993,15 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.barrierWriteWithoutTransaction(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction( + _ updates: sending @escaping (Result) -> Void + ) { base.asyncBarrierWriteWithoutTransaction(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { + public func asyncWriteWithoutTransaction( + _ updates: sending @escaping (Database) -> Void + ) { base.asyncWriteWithoutTransaction(updates) } @@ -969,7 +1009,9 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { + public func spawnConcurrentRead( + _ value: sending @escaping (Result) -> Void + ) { base.spawnConcurrentRead(value) } } diff --git a/GRDB/Core/Concurrency/SerializedDatabase.swift b/GRDB/Core/Concurrency/SerializedDatabase.swift index fa5f86dc0..30ac568b1 100644 --- a/GRDB/Core/Concurrency/SerializedDatabase.swift +++ b/GRDB/Core/Concurrency/SerializedDatabase.swift @@ -223,9 +223,16 @@ 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 + ) { + // DispatchQueue does not accept a sending closure yet, as + // discussed at . + // So let's wrap the closure in a Sendable wrapper. + let block = UncheckedSendableWrapper(value: block) + queue.async { - block(self.db) + block.value(self.db) self.preconditionNoUnsafeTransactionLeft(self.db) } } diff --git a/GRDB/Core/Concurrency/WALSnapshotTransaction.swift b/GRDB/Core/Concurrency/WALSnapshotTransaction.swift index eb6597fe1..995ab99fe 100644 --- a/GRDB/Core/Concurrency/WALSnapshotTransaction.swift +++ b/GRDB/Core/Concurrency/WALSnapshotTransaction.swift @@ -97,21 +97,21 @@ final class WALSnapshotTransaction: @unchecked Sendable { /// Schedules database operations for execution, and /// returns immediately. - func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { - databaseAccessMutex.withLock { databaseAccess in - guard let databaseAccess else { + func asyncRead( + _ value: sending @escaping (Result) -> Void + ) { + guard let databaseAccess = databaseAccessMutex.load() else { + value(.failure(DatabaseError.snapshotIsLost())) + return + } + + databaseAccess.reader.async { db in + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. + // At least check if self was closed: + if self.databaseAccessMutex.load() == nil { value(.failure(DatabaseError.snapshotIsLost())) - return - } - - databaseAccess.reader.async { db in - // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - // At least check if self was closed: - if self.databaseAccessMutex.load() == nil { - value(.failure(DatabaseError.snapshotIsLost())) - } - value(.success(db)) } + value(.success(db)) } } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 700c7085f..62695d55c 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -264,7 +264,7 @@ public struct DatabaseMigrator: Sendable { /// from succeeding. public func asyncMigrate( _ writer: some DatabaseWriter, - completion: @escaping @Sendable (Result) -> Void) + completion: sending @escaping (Result) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in do { diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 0f20f4584..d245456a2 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -121,7 +121,14 @@ 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 + ) { + // DispatchQueue does not accept a sending closure yet, as + // discussed at . + // So let's wrap the closure in a Sendable wrapper. + let execute = UncheckedSendableWrapper(value: execute) + // 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 @@ -129,7 +136,7 @@ final class Pool: Sendable { // > enqueues will sit inertly on the serial queue waiting to be // > executed, and won’t cause new threads to be started. semaphoreWaitingQueue.async { - execute(Result { try self.get() }) + execute.value(Result { try self.get() }) } } @@ -186,10 +193,17 @@ 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 + ) { + // DispatchQueue does not accept a sending closure yet, as + // discussed at . + // So let's wrap the closure in a Sendable wrapper. + let barrier = UncheckedSendableWrapper(value: barrier) + barrierQueue.async(flags: [.barrier]) { self.itemsGroup.wait() - barrier() + barrier.value() } } } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 2d592fb7e..578def5af 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -206,3 +206,8 @@ class StrongReference: @unchecked Sendable { self.value = value } } + +/// Helps compiler accept valid code it can't validate. +struct UncheckedSendableWrapper: @unchecked Sendable { + let value: Value +} diff --git a/GRDB/ValueObservation/Reducers/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift index 6ab2f1583..0d77edc4a 100644 --- a/GRDB/ValueObservation/Reducers/Fetch.swift +++ b/GRDB/ValueObservation/Reducers/Fetch.swift @@ -2,18 +2,18 @@ extension ValueReducers { /// A `ValueReducer` that perform database fetches. public struct Fetch: ValueReducer { public struct _Fetcher: _ValueReducerFetcher { - let _fetch: @Sendable (Database) throws -> Value + let _fetch: @Sendable (Database) throws -> sending Value - public func fetch(_ db: Database) throws -> Value { + public func fetch(_ db: Database) throws -> sending Value { assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") return try _fetch(db) } } - private let _fetch: @Sendable (Database) throws -> Value + private let _fetch: @Sendable (Database) throws -> sending Value /// Creates a reducer which passes raw fetched values through. - init(fetch: @escaping @Sendable (Database) throws -> Value) { + init(fetch: @escaping @Sendable (Database) throws -> sending Value) { self._fetch = fetch } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 93f4cc2dc..15ec91786 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -737,7 +737,7 @@ extension ValueObservation { /// /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( - _ fetch: @escaping @Sendable (Database) throws -> Value) + _ fetch: @escaping @Sendable (Database) throws -> sending Value) -> Self where Reducer == ValueReducers.Fetch { @@ -811,7 +811,7 @@ extension ValueObservation { public static func tracking( region: any DatabaseRegionConvertible, _ otherRegions: any DatabaseRegionConvertible..., - fetch: @escaping @Sendable (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> sending Value) -> Self where Reducer == ValueReducers.Fetch { @@ -880,7 +880,7 @@ extension ValueObservation { /// - parameter fetch: The closure that fetches the observed value. public static func tracking( regions: [any DatabaseRegionConvertible], - fetch: @escaping @Sendable (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> sending Value) -> Self where Reducer == ValueReducers.Fetch { @@ -937,7 +937,7 @@ extension ValueObservation { /// /// - parameter fetch: The closure that fetches the observed value. public static func tracking( - _ fetch: @escaping @Sendable (Database) throws -> Value) + _ fetch: @escaping @Sendable (Database) throws -> sending Value) -> Self where Reducer == ValueReducers.Fetch { diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 3e4d9fdce..54e7ed129 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -17,11 +17,11 @@ public protocol ValueObservationScheduler: Sendable { /// If the result is true, then this method was called on the main thread. func immediateInitialValue() -> Bool - func schedule(_ action: @escaping @Sendable () -> Void) + func schedule(_ action: sending @escaping () -> Void) } extension ValueObservationScheduler { - func scheduleInitial(_ action: @escaping @Sendable () -> Void) { + func scheduleInitial(_ action: sending @escaping () -> Void) { if immediateInitialValue() { action() } else { @@ -42,8 +42,15 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler { public func immediateInitialValue() -> Bool { false } - public func schedule(_ action: @escaping @Sendable () -> Void) { - queue.async(execute: action) + public func schedule(_ action: sending @escaping () -> Void) { + // DispatchQueue does not accept a sending closure yet, as + // discussed at . + // So let's wrap the closure in a Sendable wrapper. + let action = UncheckedSendableWrapper(value: action) + + queue.async { + action.value() + } } } @@ -90,8 +97,15 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sen return true } - public func schedule(_ action: @escaping @Sendable () -> Void) { - DispatchQueue.main.async(execute: action) + public func schedule(_ action: sending @escaping () -> Void) { + // DispatchQueue does not accept a sending closure yet, as + // discussed at . + // So let's wrap the closure in a Sendable wrapper. + let action = UncheckedSendableWrapper(value: action) + + DispatchQueue.main.async { + action.value() + } } } diff --git a/Package.swift b/Package.swift index 9a769b1d7..9dd47aeed 100644 --- a/Package.swift +++ b/Package.swift @@ -7,6 +7,8 @@ import PackageDescription var swiftSettings: [SwiftSetting] = [ .define("SQLITE_ENABLE_FTS5"), .enableUpcomingFeature("StrictConcurrency"), + .enableExperimentalFeature("RegionBasedIsolation"), + .enableExperimentalFeature("TransferringArgsAndResults"), ] var cSettings: [CSetting] = [] var dependencies: [PackageDescription.Package.Dependency] = [] diff --git a/SQLiteCustom/GRDBBase.xcconfig b/SQLiteCustom/GRDBBase.xcconfig index cbb18003f..ac61b26eb 100644 --- a/SQLiteCustom/GRDBBase.xcconfig +++ b/SQLiteCustom/GRDBBase.xcconfig @@ -5,3 +5,5 @@ WATCHOS_DEPLOYMENT_TARGET = 7.0 XROS_DEPLOYMENT_TARGET = 1.0 SWIFT_STRICT_CONCURRENCY = complete +SWIFT_UPCOMING_FEATURE_REGION_BASED_ISOLATION = YES +OTHER_SWIFT_FLAGS = $(inherited) -enable-experimental-feature TransferringArgsAndResults diff --git a/Support/GRDBBase.xcconfig b/Support/GRDBBase.xcconfig index 191f7b76f..157e0cd6b 100644 --- a/Support/GRDBBase.xcconfig +++ b/Support/GRDBBase.xcconfig @@ -15,3 +15,5 @@ OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 // OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks SWIFT_STRICT_CONCURRENCY = complete +SWIFT_UPCOMING_FEATURE_REGION_BASED_ISOLATION = YES +OTHER_SWIFT_FLAGS = $(inherited) -enable-experimental-feature TransferringArgsAndResults