From 81746c75adc2edeb93ff176dd2fbe2492f79cd95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 11 Feb 2024 12:18:22 +0100 Subject: [PATCH] Sendable annotations in DatabaseReader and DatabaseWriter Also, we make sure to always resume UnsafeContinuation with Sendable values. See https://forums.swift.org/t/advice-regarding-sendable-constraints-on-generic-async-apis/69969/3 --- GRDB/Core/DatabaseError.swift | 4 + GRDB/Core/DatabasePool.swift | 47 +++++------ GRDB/Core/DatabaseQueue.swift | 14 ++-- GRDB/Core/DatabaseReader.swift | 46 +++++------ GRDB/Core/DatabaseRegionObservation.swift | 18 ++-- GRDB/Core/DatabaseSnapshot.swift | 6 +- GRDB/Core/DatabaseSnapshotPool.swift | 23 +++--- GRDB/Core/DatabaseWriter.swift | 82 ++++++++++++------- GRDB/Core/WALSnapshotTransaction.swift | 34 ++++++-- GRDB/Documentation.docc/Concurrency.md | 2 +- GRDB/Utils/Pool.swift | 47 +++++++---- .../Observers/ValueConcurrentObserver.swift | 15 ++-- 12 files changed, 197 insertions(+), 141 deletions(-) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 53eb009b3..74263317e 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -406,6 +406,10 @@ extension DatabaseError { static func connectionIsClosed() -> Self { DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed") } + + static func snapshotIsLost() -> Self { + DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") + } } // Support for `catch DatabaseError.SQLITE_XXX` diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 34a9e7fde..b8fc6b054 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -62,17 +62,15 @@ public final class DatabasePool { // an opened transaction. readerConfiguration.allowsUnsafeTransactions = false - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [readerConfiguration] index in return try SerializedDatabase( path: path, configuration: readerConfiguration, defaultLabel: "GRDB.DatabasePool", - purpose: "reader.\(readerCount)") + purpose: "reader.\(index)") }) // Set up journal mode unless readonly @@ -357,7 +355,7 @@ extension DatabasePool: DatabaseReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -401,7 +399,7 @@ extension DatabasePool: DatabaseReader { } } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -446,25 +444,22 @@ extension DatabasePool: DatabaseReader { } } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - // The semaphore that blocks until futureResult is defined: - let futureSemaphore = DispatchSemaphore(value: 0) - var futureResult: Result? = nil + public func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture { + let builder = UnsafeDatabaseFutureBuilder() asyncConcurrentRead { dbResult in - // Fetch and release the future - futureResult = dbResult.flatMap { db in Result { try value(db) } } - futureSemaphore.signal() + let result = dbResult.flatMap { db in + Result { + try value(db) + } + } + builder.setResultAndReleaseFuture(result) } - return DatabaseFuture { - // Block the future until results are fetched - _ = futureSemaphore.wait(timeout: .distantFuture) - return try futureResult!.get() - } + return builder.makeFuture() } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { asyncConcurrentRead(value) } @@ -505,7 +500,7 @@ extension DatabasePool: DatabaseReader { /// ``` /// /// - parameter value: A function that accesses the database. - public func asyncConcurrentRead(_ value: @escaping (Result) -> Void) { + public func asyncConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -664,7 +659,9 @@ extension DatabasePool: DatabaseReader { /// /// - important: The `completion` argument is executed in a serial /// dispatch queue, so make sure you use the transaction asynchronously. - func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { + func asyncWALSnapshotTransaction( + _ completion: @escaping @Sendable (Result) -> Void + ) { guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) return @@ -690,7 +687,7 @@ extension DatabasePool: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if configuration.readonly { @@ -721,7 +718,7 @@ extension DatabasePool: DatabaseReader { private func _addConcurrent( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -755,7 +752,7 @@ extension DatabasePool: DatabaseWriter { } } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) return @@ -808,7 +805,7 @@ extension DatabasePool: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { writer.async(updates) } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ae763f694..933653e1c 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -233,7 +233,7 @@ extension DatabaseQueue: DatabaseReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { writer.async { db in defer { // Ignore error because we can not notify it. @@ -258,7 +258,7 @@ extension DatabaseQueue: DatabaseReader { try writer.sync(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { writer.async { value(.success($0)) } } @@ -266,7 +266,7 @@ extension DatabaseQueue: DatabaseReader { try writer.reentrantSync(value) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { + public func concurrentRead(_ value: (Database) throws -> T) -> DatabaseFuture { // DatabaseQueue can't perform parallel reads. // Perform a blocking read instead. return DatabaseFuture(Result { @@ -279,7 +279,7 @@ extension DatabaseQueue: DatabaseReader { }) } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -309,7 +309,7 @@ extension DatabaseQueue: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if configuration.readonly { @@ -379,7 +379,7 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { writer.async { updates(.success($0)) } } @@ -425,7 +425,7 @@ extension DatabaseQueue: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { writer.async(updates) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index a07abf9ec..a53cd0276 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -22,14 +22,14 @@ import Dispatch /// ### Reading from the Database /// /// - ``read(_:)-3806d`` -/// - ``read(_:)-4w6gy`` +/// - ``read(_:)-7a20l`` /// - ``readPublisher(receiveOn:value:)`` /// - ``asyncRead(_:)`` /// /// ### Unsafe Methods /// /// - ``unsafeRead(_:)-5i7tf`` -/// - ``unsafeRead(_:)-11mk0`` +/// - ``unsafeRead(_:)-3arn0`` /// - ``unsafeReentrantRead(_:)`` /// - ``asyncUnsafeRead(_:)`` /// @@ -213,7 +213,7 @@ 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 (Result) -> Void) + func asyncRead(_ value: @escaping @Sendable (Result) -> Void) /// Executes database operations, and returns their result after they have /// finished executing. @@ -284,7 +284,7 @@ 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 (Result) -> Void) + func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) /// Executes database operations, and returns their result after they have /// finished executing. @@ -342,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable { func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable } @@ -458,7 +458,7 @@ 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, watchOS 6, *) - public func read(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func read(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncRead { result in do { @@ -504,7 +504,7 @@ 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, watchOS 6, *) - public func unsafeRead(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func unsafeRead(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncUnsafeRead { result in do { @@ -549,18 +549,18 @@ extension DatabaseReader { /// - parameter scheduler: A Combine Scheduler. /// - parameter value: A closure which accesses the database. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func readPublisher( + public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping (Database) throws -> Output) + value: @escaping @Sendable (Database) throws -> Output) -> DatabasePublishers.Read { - Deferred { - Future { fulfill in - self.asyncRead { dbResult in - fulfill(dbResult.flatMap { db in Result { try value(db) } }) - } + OnDemandFuture { fulfill in + self.asyncRead { dbResult in + fulfill(dbResult.flatMap { db in Result { try value(db) } }) } } + // We don't want users to process emitted values on a + // database dispatch queue. .receiveValues(on: scheduler) .eraseToReadPublisher() } @@ -601,7 +601,7 @@ extension DatabaseReader { func _addReadOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { @@ -619,16 +619,16 @@ extension DatabaseReader { } return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ }) } else { - var isCancelled = false + let cancellable = AnyDatabaseCancellable { } asyncRead { dbResult in - guard !isCancelled else { return } + if cancellable.isCancelled { return } let result = dbResult.flatMap { db in Result { try observation.fetchInitialValue(db) } } scheduler.schedule { - guard !isCancelled else { return } + if cancellable.isCancelled { return } do { try onChange(result.get()) } catch { @@ -636,7 +636,7 @@ extension DatabaseReader { } } } - return AnyDatabaseCancellable(cancel: { isCancelled = true }) + return cancellable } } } @@ -677,7 +677,7 @@ extension AnyDatabaseReader: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncRead(value) } @@ -686,7 +686,7 @@ extension AnyDatabaseReader: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncUnsafeRead(value) } @@ -697,7 +697,7 @@ extension AnyDatabaseReader: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { base._add( @@ -757,7 +757,7 @@ extension DatabaseSnapshotReader { } // There is no such thing as an unsafe access to a snapshot. - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { asyncRead(value) } } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 4f1e1473c..4fc1b5b36 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -43,7 +43,9 @@ extension DatabaseRegionObservation { extension DatabaseRegionObservation { /// The state of a started DatabaseRegionObservation - private enum ObservationState { + private enum ObservationState: @unchecked Sendable { + // @unchecked because we don't use DatabaseRegionObserver outside of + // the writer dispatch queue. case cancelled case pending case started(DatabaseRegionObserver) @@ -85,20 +87,20 @@ extension DatabaseRegionObservation { /// - returns: A DatabaseCancellable that can stop the observation. public func start( in writer: some DatabaseWriter, - onError: @escaping (Error) -> Void, - onChange: @escaping (Database) -> Void) + onError: @escaping @Sendable (Error) -> Void, + onChange: @escaping @Sendable (Database) -> Void) -> AnyDatabaseCancellable { - @LockedBox var state = ObservationState.pending + let stateBox = LockedBox(wrappedValue: ObservationState.pending) // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. writer.unsafeReentrantWrite { db in do { let region = try observedRegion(db).observableRegion(db) - $state.update { + stateBox.update { let observer = DatabaseRegionObserver(region: region, onChange: { - if case .cancelled = state { + if case .cancelled = stateBox.wrappedValue { return } onChange($0) @@ -122,7 +124,7 @@ extension DatabaseRegionObservation { // Deallocates the transaction observer. This makes sure that the // `onChange` callback will never be called again, because the // observation was started with the `.observerLifetime` extent. - state = .cancelled + stateBox.wrappedValue = .cancelled } } } @@ -152,7 +154,7 @@ private class DatabaseRegionObserver: TransactionObserver { let onChange: (Database) -> Void var isChanged = false - init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) { + init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) { self.region = region self.onChange = onChange } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 1381c1871..bbeaac7e0 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { try reader.sync(block) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { reader.async { value(.success($0)) } } @@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { try reader.sync(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { reader.async { value(.success($0)) } } @@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { _addReadOnly( diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 35fec5a2d..61d35f81f 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -121,6 +121,7 @@ public final class DatabaseSnapshotPool { /// `db` is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(_ db: Database, configuration: Configuration? = nil) throws { + let path = db.path var configuration = Self.configure(configuration ?? db.configuration) // Acquire and hold WAL snapshot @@ -129,7 +130,7 @@ public final class DatabaseSnapshotPool { } var holderConfig = Configuration() holderConfig.allowsUnsafeTransactions = true - snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig) + snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig) try snapshotHolder.inDatabase { db in try db.beginTransaction(.deferred) try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") @@ -149,20 +150,18 @@ public final class DatabaseSnapshotPool { } self.configuration = configuration - self.path = db.path + self.path = path self.walSnapshot = walSnapshot - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [configuration] index in return try SerializedDatabase( - path: db.path, + path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseSnapshotPool", - purpose: "snapshot.\(readerCount)") + purpose: "snapshot.\(index)") }) } @@ -210,17 +209,15 @@ public final class DatabaseSnapshotPool { self.path = path self.walSnapshot = walSnapshot - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [configuration] index in return try SerializedDatabase( path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseSnapshotPool", - purpose: "snapshot.\(readerCount)") + purpose: "snapshot.\(index)") }) } @@ -291,7 +288,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -329,7 +326,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { _addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index b4de8f6fd..3a6c7db6b 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -22,18 +22,18 @@ import Dispatch /// ### Writing into the Database /// /// - ``write(_:)-76inz`` -/// - ``write(_:)-88g7e`` +/// - ``write(_:)-3db50`` /// - ``writePublisher(receiveOn:updates:)`` /// - ``writePublisher(receiveOn:updates:thenRead:)`` /// - ``writeWithoutTransaction(_:)-4qh1w`` -/// - ``writeWithoutTransaction(_:)-tckw`` +/// - ``writeWithoutTransaction(_:)-5h4vs`` /// - ``asyncWrite(_:completion:)`` /// - ``asyncWriteWithoutTransaction(_:)`` /// /// ### Exclusive Access to the Database /// /// - ``barrierWriteWithoutTransaction(_:)-280j1`` -/// - ``barrierWriteWithoutTransaction(_:)-7u4xw`` +/// - ``barrierWriteWithoutTransaction(_:)-1ctl7`` /// - ``asyncBarrierWriteWithoutTransaction(_:)`` /// /// ### Reading from the Latest Committed Database State @@ -181,7 +181,7 @@ 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 (Result) -> Void) + func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) /// Schedules database operations for execution, and returns immediately. /// @@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader { /// for more information. /// /// - parameter updates: A closure which accesses the database. - func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) /// Executes database operations, and returns their result after they have /// finished executing. @@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader { /// returned ``DatabaseFuture`` blocks a thread. You may prefer /// ``spawnConcurrentRead(_:)`` instead. /// - parameter value: A closure which accesses the database. - func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture + func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture // Exposed for RxGRDB and GRBCombine. Naming is not stabilized. /// Schedules read-only database operations for execution. @@ -340,7 +340,7 @@ 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 (Result) -> Void) + func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) } extension DatabaseWriter { @@ -426,8 +426,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 (Database) throws -> T, - completion: @escaping (Database, Result) -> Void) + _ updates: @escaping @Sendable (Database) throws -> T, + completion: @escaping @Sendable (Database, Result) -> Void) { asyncWriteWithoutTransaction { db in do { @@ -557,7 +557,7 @@ extension DatabaseWriter { func _addWriteOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -608,7 +608,7 @@ extension DatabaseWriter { /// would happen while establishing the database access or committing /// the transaction. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func write(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func write(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncWrite(updates, completion: { _, result in continuation.resume(with: result) @@ -646,7 +646,9 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func writeWithoutTransaction(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { + public func writeWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncWriteWithoutTransaction { db in do { @@ -698,8 +700,8 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func barrierWriteWithoutTransaction( - _ updates: @Sendable @escaping (Database) throws -> T) + public func barrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -801,9 +803,9 @@ extension DatabaseWriter { /// - parameter scheduler: A Combine Scheduler. /// - parameter updates: A closure which accesses the database. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func writePublisher( + public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - updates: @escaping (Database) throws -> Output) + updates: @escaping @Sendable (Database) throws -> Output) -> DatabasePublishers.Write { OnDemandFuture { fulfill in @@ -868,10 +870,10 @@ extension DatabaseWriter { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func writePublisher( receiveOn scheduler: S = DispatchQueue.main, - updates: @escaping (Database) throws -> T, - thenRead value: @escaping (Database, T) throws -> Output) + updates: @escaping @Sendable (Database) throws -> T, + thenRead value: @escaping @Sendable (Database, T) throws -> Output) -> DatabasePublishers.Write - where S: Scheduler + where S: Scheduler, T: Sendable, Output: Sendable { OnDemandFuture { fulfill in self.asyncWriteWithoutTransaction { db in @@ -885,7 +887,7 @@ extension DatabaseWriter { fulfill(.failure(error)) return } - self.spawnConcurrentRead { dbResult in + self.spawnConcurrentRead { [updatesValue] dbResult in fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } }) } } @@ -941,11 +943,11 @@ extension Publisher where Failure == Error { /// /// let count: Int = try futureCount.wait() /// ``` -public class DatabaseFuture { +public class DatabaseFuture { private var consumed = false private let _wait: () throws -> Value - init(_ wait: @escaping () throws -> Value) { + init(_ wait: @escaping @Sendable () throws -> Value) { _wait = wait } @@ -967,6 +969,28 @@ public class DatabaseFuture { } } +/// A helper class that builds a DatabaseFuture without compiler errors +/// regarding concurrency. +final class UnsafeDatabaseFutureBuilder: @unchecked Sendable { + let semaphore = DispatchSemaphore(value: 0) + var result: Result? = nil + + /// - precondition: MUST be called once. + func setResultAndReleaseFuture(_ result: Result) { + self.result = result + semaphore.signal() + } + + /// - precondition: MUST be called once. + func makeFuture() -> DatabaseFuture { + DatabaseFuture { [self] in + // Block the future until results are fetched + _ = semaphore.wait(timeout: .distantFuture) + return try result!.get() + } + } +} + /// A type-erased database writer. /// /// An instance of `AnyDatabaseWriter` forwards its operations to an underlying @@ -1003,7 +1027,7 @@ extension AnyDatabaseWriter: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncRead(value) } @@ -1012,7 +1036,7 @@ extension AnyDatabaseWriter: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead(_ value: @escaping @Sendable (Result) -> Void) { base.asyncUnsafeRead(value) } @@ -1023,7 +1047,7 @@ extension AnyDatabaseWriter: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { base._add( @@ -1044,11 +1068,11 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.barrierWriteWithoutTransaction(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result) -> Void) { base.asyncBarrierWriteWithoutTransaction(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) { base.asyncWriteWithoutTransaction(updates) } @@ -1056,11 +1080,11 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { + public func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture { base.concurrentRead(value) } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { base.spawnConcurrentRead(value) } } diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index 70982db9c..c431123e2 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -4,8 +4,10 @@ /// `WALSnapshotTransaction` **takes ownership** of its reader /// `SerializedDatabase` (TODO: make it a move-only type eventually). class WALSnapshotTransaction { - private let reader: SerializedDatabase - private let release: (_ isInsideTransaction: Bool) -> Void + // nil when closed + private var reader: SerializedDatabase? + // nil when closed + private var release: ((_ isInsideTransaction: Bool) -> Void)? /// The state of the database at the beginning of the transaction. let walSnapshot: WALSnapshot @@ -58,21 +60,39 @@ class WALSnapshotTransaction { } deinit { - Self.commitAndRelease(reader: reader, release: release) + close() } /// Executes database operations in the snapshot transaction, and /// returns their result after they have finished executing. - func read(_ value: (Database) throws -> T) rethrows -> T { + func read(_ value: (Database) throws -> T) throws -> T { + guard let reader else { + throw DatabaseError.snapshotIsLost() + } + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - try reader.sync(value) + return try reader.sync(value) } /// Schedules database operations for execution, and /// returns immediately. - func asyncRead(_ value: @escaping (Database) -> Void) { + func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + guard let reader else { + value(.failure(DatabaseError.snapshotIsLost())) + return + } + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - reader.async(value) + reader.async { db in + value(.success(db)) + } + } + + func close() { + guard let reader, let release else { return } + self.reader = nil + self.release = nil + Self.commitAndRelease(reader: reader, release: release) } private static func commitAndRelease( diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 4c5f7e908..8318d9459 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -99,7 +99,7 @@ try dbQueue.write { db in } ``` - See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``. + See ``DatabaseReader/read(_:)-7a20l`` and ``DatabaseWriter/write(_:)-3db50``. 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 1af095366..2e993717f 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -37,7 +37,7 @@ import Dispatch /// got 3 final class Pool: Sendable { private class Item: @unchecked Sendable { - // @unchecked because `isAvailable` is protected by `items`. + // @unchecked because `isAvailable` is protected by `content`. let element: T var isAvailable: Bool @@ -47,8 +47,19 @@ final class Pool: Sendable { } } - private let makeElement: @Sendable () throws -> T - private let items: ReadWriteBox<[Item]> = ReadWriteBox(wrappedValue: []) + private struct Content { + var items: [Item] + + /// The number of created items. May become greater than the number + /// of elements in items, as some items are destroyed and other + /// are created. + var createdCount = 0 + } + + typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void) + + private let makeElement: @Sendable (Int) throws -> T + private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0)) private let itemsSemaphore: DispatchSemaphore // limits the number of elements private let itemsGroup: DispatchGroup // knows when no element is used private let barrierQueue: DispatchQueue @@ -60,11 +71,12 @@ final class Pool: Sendable { /// - maximumCount: The maximum number of elements. /// - qos: The quality of service of asynchronous accesses. /// - makeElement: A function that creates an element. It is called - /// on demand. + /// on demand. Its argument is the index of the created elements + /// (1, then 2, etc). init( maximumCount: Int, qos: DispatchQoS = .unspecified, - makeElement: @escaping @Sendable () throws -> T) + makeElement: @escaping @Sendable (_ index: Int) throws -> T) { GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1") self.makeElement = makeElement @@ -76,19 +88,20 @@ final class Pool: Sendable { /// Returns a tuple (element, release) /// Client must call release(), only once, after the element has been used. - func get() throws -> (element: T, release: @Sendable (PoolCompletion) -> Void) { + func get() throws -> ElementAndRelease { try barrierQueue.sync { itemsSemaphore.wait() itemsGroup.enter() do { - let item = try items.update { items -> Item in - if let item = items.first(where: \.isAvailable) { + let item = try content.update { content -> Item in + if let item = content.items.first(where: \.isAvailable) { item.isAvailable = false return item } else { - let element = try makeElement() + content.createdCount += 1 + let element = try makeElement(content.createdCount) let item = Item(element: element, isAvailable: false) - items.append(item) + content.items.append(item) return item } } @@ -108,7 +121,7 @@ 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<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) { + func asyncGet(_ execute: @escaping @Sendable (Result) -> Void) { // 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 +142,7 @@ final class Pool: Sendable { } private func release(_ item: Item, completion: PoolCompletion) { - items.update { items in + content.update { content in switch completion { case .reuse: // This is why Item is a class, not a struct: so that we can @@ -137,8 +150,8 @@ final class Pool: Sendable { item.isAvailable = true case .discard: // Discard should be rare: perform lookup. - if let index = items.firstIndex(where: { $0 === item }) { - items.remove(at: index) + if let index = content.items.firstIndex(where: { $0 === item }) { + content.items.remove(at: index) } } } @@ -149,8 +162,8 @@ final class Pool: Sendable { /// Performs a block on each pool element, available or not. /// The block is run is some arbitrary dispatch queue. func forEach(_ body: (T) throws -> Void) rethrows { - try items.read { items in - for item in items { + try content.read { content in + for item in content.items { try body(item.element) } } @@ -159,7 +172,7 @@ final class Pool: Sendable { /// Removes all elements from the pool. /// Currently used elements won't be reused. func removeAll() { - items.update { $0.removeAll() } + content.update { $0.items.removeAll() } } /// Blocks until no element is used, and runs the `barrier` function before diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index ac38965c6..2686a5379 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -352,10 +352,11 @@ extension ValueConcurrentObserver { let initialFetchTransaction = try result.get() // Second async jump because that's how // `DatabasePool.asyncWALSnapshotTransaction` has to be used. - initialFetchTransaction.asyncRead { db in + initialFetchTransaction.asyncRead { dbResult in do { let fetchedValue: Reducer.Fetched let initialRegion: DatabaseRegion + let db = try dbResult.get() switch self.trackingMode { case let .constantRegion(regions): @@ -429,11 +430,9 @@ extension ValueConcurrentObserver { // checkpointed. That's why we'll keep `initialFetchTransaction` // alive until the comparison is done. // - // However, we want to release `initialFetchTransaction` as soon as + // However, we want to close `initialFetchTransaction` as soon as // possible, so that the reader connection it holds becomes - // available for other reads. It will be released when this optional - // is set to nil: - var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction + // available for other reads. databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in let events = self.lock.synchronized { self.notificationCallbacks?.events } @@ -446,7 +445,7 @@ extension ValueConcurrentObserver { // Was the database modified since the initial fetch? let isModified: Bool if let currentWALSnapshot = try? WALSnapshot(writerDB) { - let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot) + let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot) assert(ordering <= 0, "Unexpected snapshot ordering") isModified = ordering < 0 } else { @@ -454,9 +453,9 @@ extension ValueConcurrentObserver { isModified = true } - // Comparison done: end the WAL snapshot transaction + // Comparison done: close the WAL snapshot transaction // and release its reader connection. - initialFetchTransaction = nil + initialFetchTransaction.close() if isModified { events.databaseDidChange?()