DatabaseCancellable is Sendable

This commit is contained in:
Gwendal Roué committed 2024-07-27 16:37:32 +02:00
1 parent 2661ff4690
commit 2f93f00b41
4 files changed
+32 -21

No files matched your search

+4 -4
View File
@@ -620,16 +620,16 @@ extension DatabaseReader {
} }
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ }) return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else { } else {
var isCancelled = false let cancellable = AnyDatabaseCancellable()
asyncRead { dbResult in asyncRead { dbResult in
guard !isCancelled else { return } if cancellable.isCancelled { return }
let result = dbResult.flatMap { db in let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) } Result { try observation.fetchInitialValue(db) }
} }
scheduler.schedule { scheduler.schedule {
guard !isCancelled else { return } if cancellable.isCancelled { return }
do { do {
try onChange(result.get()) try onChange(result.get())
} catch { } catch {
@@ -637,7 +637,7 @@ extension DatabaseReader {
} }
} }
} }
return AnyDatabaseCancellable(cancel: { isCancelled = true }) return cancellable
} }
} }
} }
+5 -5
View File
@@ -89,16 +89,16 @@ extension DatabaseRegionObservation {
onChange: @escaping (Database) -> Void) onChange: @escaping (Database) -> Void)
-> AnyDatabaseCancellable -> AnyDatabaseCancellable
{ {
@LockedBox var state = ObservationState.pending let stateMutex = LockedBox(wrappedValue: ObservationState.pending)
// Use unsafeReentrantWrite so that observation can start from any // Use unsafeReentrantWrite so that observation can start from any
// dispatch queue. // dispatch queue.
writer.unsafeReentrantWrite { db in writer.unsafeReentrantWrite { db in
do { do {
let region = try observedRegion(db).observableRegion(db) let region = try observedRegion(db).observableRegion(db)
$state.update { stateMutex.update { state in
let observer = DatabaseRegionObserver(region: region, onChange: { let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = state { if case .cancelled = stateMutex.wrappedValue {
return return
} }
onChange($0) onChange($0)
@@ -111,7 +111,7 @@ extension DatabaseRegionObservation {
// the observer. // the observer.
db.add(transactionObserver: observer, extent: .observerLifetime) db.add(transactionObserver: observer, extent: .observerLifetime)
$0 = .started(observer) state = .started(observer)
} }
} catch { } catch {
onError(error) onError(error)
@@ -122,7 +122,7 @@ extension DatabaseRegionObservation {
// Deallocates the transaction observer. This makes sure that the // Deallocates the transaction observer. This makes sure that the
// `onChange` callback will never be called again, because the // `onChange` callback will never be called again, because the
// observation was started with the `.observerLifetime` extent. // observation was started with the `.observerLifetime` extent.
state = .cancelled stateMutex.wrappedValue = .cancelled
} }
} }
} }
+22 -11
View File
@@ -1,3 +1,5 @@
import Foundation
/// A protocol indicating that an activity or action supports cancellation. /// A protocol indicating that an activity or action supports cancellation.
/// ///
/// ## Topics /// ## Topics
@@ -5,7 +7,7 @@
/// ### Supporting Types /// ### Supporting Types
/// ///
/// - ``AnyDatabaseCancellable`` /// - ``AnyDatabaseCancellable``
public protocol DatabaseCancellable { public protocol DatabaseCancellable: Sendable {
/// Cancel the activity. /// Cancel the activity.
func cancel() func cancel()
} }
@@ -15,31 +17,40 @@ public protocol DatabaseCancellable {
/// ///
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()`` /// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized. /// when deinitialized.
public class AnyDatabaseCancellable: DatabaseCancellable { public final class AnyDatabaseCancellable: DatabaseCancellable, @unchecked Sendable {
private var _cancel: (() -> Void)? // @unchecked Sendable due to `_cancel`, which is protected by `lock`.
private let lock = NSLock()
private var _cancel: (@Sendable () -> Void)?
var isCancelled: Bool {
lock.withLock { _cancel == nil }
}
convenience init() {
self.init(cancel: { })
}
/// Initializes the cancellable object with the given cancel-time closure. /// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping () -> Void) { public init(cancel: @escaping @Sendable () -> Void) {
_cancel = cancel _cancel = cancel
} }
/// Creates a cancellable object that forwards cancellation to `base`. /// Creates a cancellable object that forwards cancellation to `base`.
public convenience init(_ base: some DatabaseCancellable) { public convenience init(_ base: some DatabaseCancellable) {
var cancellable = Optional.some(base)
self.init { self.init {
cancellable?.cancel() base.cancel()
cancellable = nil // Release memory
} }
} }
deinit { deinit {
_cancel?() cancel()
} }
public func cancel() { public func cancel() {
// Don't prevent multiple concurrent calls to _cancel, because it is lock.lock()
// pointless. But release memory! let cancel = _cancel
_cancel?()
_cancel = nil _cancel = nil
lock.unlock()
cancel?()
} }
} }
+1 -1
View File
@@ -96,7 +96,7 @@
- [ ] GRDB7: Consider putting a Task cancellation handler on async methods. - [ ] GRDB7: Consider putting a Task cancellation handler on async methods.
- [X] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553 - [X] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553
- [ ] GRDB7: Sendable conformances - [ ] GRDB7: Sendable conformances
- [ ] anydatabasecancellable - [X] anydatabasecancellable
- [ ] anydatabaseregionconvertible - [ ] anydatabaseregionconvertible
- [ ] anyfetchrequest - [ ] anyfetchrequest
- [ ] anysqljsonexpressible - [ ] anysqljsonexpressible