ValueObservation requires Sendable values

This is required for handleEvents to do whatever it wants with observed values.
This commit is contained in:
Gwendal Roué committed 2024-07-28 13:59:38 +02:00
1 parent 7b075e6b3a
commit 5cf3b5d44b
11 files changed
+145 -225

No files matched your search

+3
View File
@@ -20,3 +20,6 @@ Task cancellation is now honored (exclusively in async accesses)
CSQLite was renamed GRDBSQLite.
---
ValueObservation requires Sendable values
@@ -360,7 +360,6 @@ extension ValueConcurrentObserver {
initialFetchTransaction.asyncRead { dbResult in
do {
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion
@@ -381,29 +380,7 @@ extension ValueConcurrentObserver {
//
// Reducing is performed asynchronously, so that we do not lock
// a database dispatch queue longer than necessary.
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
guard let _initialValue = try self.reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
// Safe because initialValue is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let initialValue = _initialValue
// Notify
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(initialValue)
}
} catch {
self.notifyError(error)
}
}
self.asyncReduceInitialFetchedValue(fetchedValue)
// Start observation
self.asyncStartObservation(
@@ -426,6 +403,28 @@ extension ValueConcurrentObserver {
}
}
private func asyncReduceInitialFetchedValue(_ fetchedValue: sending Reducer.Fetched) {
reduceQueue.asyncSending { [self] in
let isNotifying = lock.synchronized { notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
guard let initialValue = try reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
// Notify
scheduler.schedule { [self] in
let onChange = lock.synchronized { notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(initialValue)
}
} catch {
notifyError(error)
}
}
}
private func asyncStartObservation(
from databaseAccess: DatabaseAccess,
initialFetchTransaction: WALSnapshotTransaction,
@@ -474,7 +473,6 @@ extension ValueConcurrentObserver {
// Fetch
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchedValue: Reducer.Fetched
switch self.trackingMode {
@@ -497,33 +495,7 @@ extension ValueConcurrentObserver {
//
// Important: reduceQueue.async guarantees the same ordering
// between transactions and notifications!
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
let value = try self.reducer._value(fetchedValue)
// Notify
if let value {
// Safe because value is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let value = value
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(value)
}
}
} catch {
let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool }
dbPool?.asyncWriteWithoutTransaction { writerDB in
self.stopDatabaseObservation(writerDB)
}
self.notifyError(error)
}
}
self.asyncReduceFetchedValue(fetchedValue)
} else {
events.willTrackRegion?(initialRegion)
self.startObservation(writerDB, observedRegion: initialRegion)
@@ -534,6 +506,30 @@ extension ValueConcurrentObserver {
}
}
}
private func asyncReduceFetchedValue(_ fetchedValue: sending Reducer.Fetched) {
reduceQueue.asyncSending { [self] in
let isNotifying = lock.synchronized { notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
// Notify
if let value = try reducer._value(fetchedValue) {
scheduler.schedule { [self] in
let onChange = lock.synchronized { notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(value)
}
}
} catch {
let dbPool = lock.synchronized { databaseAccess?.dbPool }
dbPool?.asyncWriteWithoutTransaction { [self] writerDB in
stopDatabaseObservation(writerDB)
}
notifyError(error)
}
}
}
}
#else
extension ValueConcurrentObserver {
@@ -602,7 +598,6 @@ extension ValueConcurrentObserver {
do {
// Fetch
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion
@@ -622,29 +617,7 @@ extension ValueConcurrentObserver {
//
// Reducing is performed asynchronously, so that we do not lock
// a database dispatch queue longer than necessary.
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
guard let _initialValue = try self.reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
// Safe because initialValue is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let initialValue = _initialValue
// Notify
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(initialValue)
}
} catch {
self.notifyError(error)
}
}
self.asyncReduceInitialFetchedValue(fetchedValue)
// Start observation
self.asyncStartObservationWithoutWALSnapshot(
@@ -669,7 +642,6 @@ extension ValueConcurrentObserver {
try writerDB.isolated(readOnly: true) {
// Fetch
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchedValue: Reducer.Fetched
let observedRegion: DatabaseRegion
@@ -691,36 +663,7 @@ extension ValueConcurrentObserver {
//
// Reducing is performed asynchronously, so that we do not lock
// the writer dispatch queue longer than necessary.
//
// Important: reduceQueue.async guarantees the same ordering
// between transactions and notifications!
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
let value = try self.reducer._value(fetchedValue)
// Notify
if let value {
// Safe because value is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let value = value
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(value)
}
}
} catch {
let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool }
dbPool?.asyncWriteWithoutTransaction { writerDB in
self.stopDatabaseObservation(writerDB)
}
self.notifyError(error)
}
}
self.asyncReduceFetchedValue(fetchedValue)
}
} catch {
self.notifyError(error)
@@ -793,15 +736,18 @@ extension ValueConcurrentObserver: TransactionObserver {
// Conclusion: fetch from the writer connection, and update the
// tracked region.
do {
let (fetchedValue, observedRegion) = try databaseAccess.fetchRecordingObservedRegion(writerDB)
let (_fetchedValue, observedRegion) = try databaseAccess.fetchRecordingObservedRegion(writerDB)
// Don't spam the user with region tracking events: wait for an actual change
if let willTrackRegion = events.willTrackRegion, observedRegion != observationState.region {
willTrackRegion(observedRegion)
}
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
nonisolated(unsafe) let fetchedResult: Result<Reducer.Fetched, Error> = .success(_fetchedValue)
observationState.region = observedRegion
reduce(.success(fetchedValue))
asyncReduceFetchedResult(fetchedResult)
} catch {
stopDatabaseObservation(writerDB)
notifyError(error)
@@ -828,14 +774,16 @@ extension ValueConcurrentObserver: TransactionObserver {
private func asyncFetch(databaseAccess: DatabaseAccess) {
databaseAccess.dbPool.asyncRead { [self] dbResult in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
let isNotifying = lock.synchronized { notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
let fetchResult = dbResult.flatMap { db in
// Safe because fetchedResult is not used beyond its transfer to reduceQueue
nonisolated(unsafe) let fetchedResult: Result<Reducer.Fetched, Error>
fetchedResult = dbResult.flatMap { db in
Result { try databaseAccess.fetch(db) }
}
self.reduce(fetchResult)
asyncReduceFetchedResult(fetchedResult)
fetchingStateMutex.withLock { state in
switch state {
@@ -854,38 +802,28 @@ extension ValueConcurrentObserver: TransactionObserver {
}
}
private func reduce(_ fetchResult: Result<Reducer.Fetched, Error>) {
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchResult = fetchResult
reduceQueue.async {
private func asyncReduceFetchedResult(_ fetchedResult: sending Result<Reducer.Fetched, Error>) {
reduceQueue.asyncSending { [self] in
do {
let fetchedValue = try fetchResult.get()
let fetchedValue = try fetchedResult.get()
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
let isNotifying = lock.synchronized { notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
let value = try self.reducer._value(fetchedValue)
// Notify value
if let value {
// Safe because value is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let value = value
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
// Notify
if let value = try reducer._value(fetchedValue) {
scheduler.schedule { [self] in
let onChange = lock.synchronized { notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(value)
}
}
} catch {
let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool }
dbPool?.asyncWriteWithoutTransaction { writerDB in
self.stopDatabaseObservation(writerDB)
let dbPool = lock.synchronized { databaseAccess?.dbPool }
dbPool?.asyncWriteWithoutTransaction { [self] writerDB in
stopDatabaseObservation(writerDB)
}
self.notifyError(error)
notifyError(error)
}
}
}
@@ -130,6 +130,9 @@ final class ValueWriteOnlyObserver<
/// The dispatch queue where database values are reduced into observed
/// values before being notified. Protects `reducer`.
///
/// Important: reduceQueue.async guarantees the same ordering between
/// transactions and notifications!
private let reduceQueue: DispatchQueue
/// Access to the database, protected by `lock`.
@@ -251,51 +254,21 @@ extension ValueWriteOnlyObserver {
private func asyncStart(from writer: Writer) {
// Start from a write access, so that self can register as a
// transaction observer.
writer.asyncWriteWithoutTransaction { db in
writer.asyncWriteWithoutTransaction { [self] db in
do {
// Fetch & Start observing the database
guard let _fetchedValue = try self.fetchAndStartObservation(db) else {
guard let _fetchedValue = try fetchAndStartObservation(db) else {
return /* Cancelled */
}
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchedValue = _fetchedValue
// Reduce
//
// Reducing is performed asynchronously, so that we do not lock
// the writer dispatch queue longer than necessary.
//
// Important: reduceQueue.async guarantees the same ordering
// between transactions and notifications!
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
guard let _initialValue = try self.reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
// Safe because initialValue is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let initialValue = _initialValue
// Notify
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(initialValue)
}
} catch {
let writer = self.lock.synchronized { self.databaseAccess?.writer }
writer?.asyncWriteWithoutTransaction { db in
self.stopDatabaseObservation(db)
}
self.notifyError(error)
}
}
asyncReduceInitialFetchedValue(fetchedValue)
} catch {
self.stopDatabaseObservation(db)
self.notifyError(error)
@@ -303,6 +276,32 @@ extension ValueWriteOnlyObserver {
}
}
private func asyncReduceInitialFetchedValue(_ fetchedValue: sending Reducer.Fetched) {
reduceQueue.asyncSending { [self] in
let isNotifying = lock.synchronized { notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
guard let initialValue = try reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
// Notify
scheduler.schedule { [self] in
let onChange = lock.synchronized { notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(initialValue)
}
} catch {
let writer = lock.synchronized { databaseAccess?.writer }
writer?.asyncWriteWithoutTransaction { [self] db in
stopDatabaseObservation(db)
}
notifyError(error)
}
}
}
/// Fetches the initial value, and start observing the database.
///
/// Returns nil if the observation was cancelled before database observation
@@ -391,7 +390,6 @@ extension ValueWriteOnlyObserver: TransactionObserver {
do {
// Fetch
// Safe because fetchedValue is not used beyond its transfer to reduceQueue
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let fetchedValue: Reducer.Fetched
switch trackingMode {
@@ -415,36 +413,7 @@ extension ValueWriteOnlyObserver: TransactionObserver {
//
// Reducing is performed asynchronously, so that we do not lock
// the writer dispatch queue longer than necessary.
//
// Important: reduceQueue.async guarantees the same ordering between
// transactions and notifications!
reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
let value = try self.reducer._value(fetchedValue)
// Notify value
if let value {
// Safe because value is not used beyond its transfer to scheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let value = value
self.scheduler.schedule {
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(value)
}
}
} catch {
let writer = self.lock.synchronized { self.databaseAccess?.writer }
writer?.asyncWriteWithoutTransaction { db in
self.stopDatabaseObservation(db)
}
self.notifyError(error)
}
}
asyncReduceFetchedValue(fetchedValue)
} catch {
stopDatabaseObservation(db)
notifyError(error)
@@ -455,6 +424,30 @@ extension ValueWriteOnlyObserver: TransactionObserver {
// Reset the isModified flag until next transaction
observationState.isModified = false
}
private func asyncReduceFetchedValue(_ fetchedValue: sending Reducer.Fetched) {
reduceQueue.asyncSending { [self] in
let isNotifying = lock.synchronized { notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
// Notify
if let value = try reducer._value(fetchedValue) {
scheduler.schedule { [self] in
let onChange = lock.synchronized { notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(value)
}
}
} catch {
let writer = lock.synchronized { databaseAccess?.writer }
writer?.asyncWriteWithoutTransaction { [self] db in
stopDatabaseObservation(db)
}
notifyError(error)
}
}
}
}
// MARK: - Ending the Observation
+1 -1
View File
@@ -1,6 +1,6 @@
extension ValueReducers {
/// A `ValueReducer` that perform database fetches.
public struct Fetch<Value>: ValueReducer {
public struct Fetch<Value: Sendable>: ValueReducer {
public struct _Fetcher: _ValueReducerFetcher {
let _fetch: @Sendable (Database) throws -> sending Value
+1 -1
View File
@@ -30,7 +30,7 @@ extension ValueReducers {
/// passed through a transform function.
///
/// See ``ValueObservation/map(_:)``.
public struct Map<Base: _ValueReducer, Value>: ValueReducer {
public struct Map<Base: _ValueReducer, Value: Sendable>: ValueReducer {
private var base: Base
private let transform: (Base.Value) throws -> Value
@@ -16,7 +16,7 @@ public protocol _ValueReducer {
associatedtype Fetcher: _ValueReducerFetcher
/// The type of observed values
associatedtype Value
associatedtype Value: Sendable
/// The type of fetched database values
typealias Fetched = Fetcher.Fetched
@@ -13,13 +13,8 @@ extension ValueObservationSchedulers {
public func immediateInitialValue() -> Bool { false }
public func schedule(_ action: sending @escaping () -> Void) {
// DispatchQueue does not accept a sending closure yet, as
// discussed at <https://forums.swift.org/t/how-can-i-use-region-based-isolation/71426/5>.
// So let's wrap the closure in a Sendable wrapper.
let action = UncheckedSendableWrapper(value: action)
queue.async {
action.value()
queue.asyncSending {
action()
}
}
}
@@ -16,13 +16,8 @@ extension ValueObservationSchedulers {
}
public func schedule(_ action: sending @escaping () -> Void) {
// DispatchQueue does not accept a sending closure yet, as
// discussed at <https://forums.swift.org/t/how-can-i-use-region-based-isolation/71426/5>.
// So let's wrap the closure in a Sendable wrapper.
let action = UncheckedSendableWrapper(value: action)
DispatchQueue.main.async {
action.value()
DispatchQueue.main.asyncSending {
action()
}
}
}
@@ -172,7 +172,7 @@ typealias SendableValueObservationStart<T> = @Sendable (
/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// ```
public final class SharedValueObservation<Element>: @unchecked Sendable {
public final class SharedValueObservation<Element: Sendable>: @unchecked Sendable {
// @unchecked Sendable: mutable state is protected by `lock`.
private let scheduler: any ValueObservationScheduler
@@ -265,10 +265,6 @@ public final class SharedValueObservation<Element>: @unchecked Sendable {
} else if let lastResult {
// Notify last result as an initial value
// Safe because result is not used beyond its transfer to sheduler
// FIXME: improve when SE-0430 is shipped.
nonisolated(unsafe) let lastResult = lastResult
scheduler.scheduleInitial {
switch lastResult {
case let .failure(error):
+4 -4
View File
@@ -81,7 +81,7 @@ struct ValueObservationEvents: Refinable {
var didCancel: (@Sendable () -> Void)?
}
typealias ValueObservationStart<T> = @Sendable (
typealias ValueObservationStart<T: Sendable> = @Sendable (
_ onError: @escaping @Sendable (Error) -> Void,
_ onChange: @escaping @Sendable (T) -> Void)
-> AnyDatabaseCancellable
@@ -339,7 +339,7 @@ extension ValueObservation {
/// You build an `AsyncValueObservation` from ``ValueObservation`` or
/// ``SharedValueObservation``.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public struct AsyncValueObservation<Element>: AsyncSequence, @unchecked Sendable {
public struct AsyncValueObservation<Element: Sendable>: AsyncSequence, @unchecked Sendable {
// @unchecked Sendable because of `BufferingPolicy`.
public typealias BufferingPolicy = AsyncThrowingStream<Element, Error>.Continuation.BufferingPolicy
public typealias AsyncIterator = Iterator
@@ -464,7 +464,7 @@ extension DatabasePublishers {
///
/// You build such a publisher from ``ValueObservation``
/// or ``SharedValueObservation``.
public struct Value<Output>: Publisher {
public struct Value<Output: Sendable>: Publisher {
public typealias Failure = Error
private let start: ValueObservationStart<Output>
@@ -481,7 +481,7 @@ extension DatabasePublishers {
}
private final class ValueSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
where Downstream.Failure == Error
where Downstream.Input: Sendable, Downstream.Failure == Error
{
// @unchecked Sendable because state is protected by `lock`.
+1 -1
View File
@@ -285,7 +285,7 @@ extension FetchRequest {
}
/// A type-erased ValueReducer.
struct AnyValueReducer<Fetched, Value>: ValueReducer {
struct AnyValueReducer<Fetched, Value: Sendable>: ValueReducer {
private var __fetch: @Sendable (Database) throws -> Fetched
private var __value: (Fetched) -> Value?