mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Sendable annotations for ValueObservation
This commit is contained in:
1 parent
133cc2e6e9
commit
1fe410de69
12 files changed
+189
-134
No files matched your search
@@ -416,7 +416,7 @@ private struct TableRegion: Equatable {
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseRegionConvertible``
|
||||
public protocol DatabaseRegionConvertible {
|
||||
public protocol DatabaseRegionConvertible: Sendable {
|
||||
/// Returns a database region.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -437,14 +437,15 @@ extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
|
||||
/// A type-erased DatabaseRegionConvertible
|
||||
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
let _region: (Database) throws -> DatabaseRegion
|
||||
let _region: @Sendable (Database) throws -> DatabaseRegion
|
||||
|
||||
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
|
||||
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
|
||||
_region = region
|
||||
}
|
||||
|
||||
public init(_ region: some DatabaseRegionConvertible) {
|
||||
_region = region.databaseRegion
|
||||
// https://github.com/apple/swift/issues/71541
|
||||
_region = { try region.databaseRegion($0) }
|
||||
}
|
||||
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
|
||||
@@ -3,11 +3,28 @@
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
class WALSnapshotTransaction {
|
||||
// nil when closed
|
||||
private var reader: SerializedDatabase?
|
||||
// nil when closed
|
||||
private var release: ((_ isInsideTransaction: Bool) -> Void)?
|
||||
final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
// @unchecked because `databaseAccess` is protected its mutex.
|
||||
|
||||
private struct DatabaseAccess {
|
||||
let reader: SerializedDatabase
|
||||
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
|
||||
|
||||
// MUST be called only once
|
||||
func commitAndRelease() {
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
try? db.commit()
|
||||
return db.isInsideTransaction
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: consider using the serialized DispatchQueue of reader instead of a lock.
|
||||
/// nil when closed
|
||||
@Mutex private var databaseAccess: DatabaseAccess?
|
||||
|
||||
/// The state of the database at the beginning of the transaction.
|
||||
let walSnapshot: WALSnapshot
|
||||
@@ -38,10 +55,11 @@ class WALSnapshotTransaction {
|
||||
/// is no longer used.
|
||||
init(
|
||||
onReader reader: SerializedDatabase,
|
||||
release: @escaping (_ isInsideTransaction: Bool) -> Void)
|
||||
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
|
||||
throws
|
||||
{
|
||||
assert(reader.configuration.readonly)
|
||||
let databaseAccess = DatabaseAccess(reader: reader, release: release)
|
||||
|
||||
do {
|
||||
// Open a long-lived transaction, and enter snapshot isolation
|
||||
@@ -50,11 +68,10 @@ class WALSnapshotTransaction {
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
self.reader = reader
|
||||
self.release = release
|
||||
self.databaseAccess = databaseAccess
|
||||
} catch {
|
||||
// self is not initialized, so deinit will not run.
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
databaseAccess.commitAndRelease()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -66,46 +83,41 @@ class WALSnapshotTransaction {
|
||||
/// Executes database operations in the snapshot transaction, and
|
||||
/// returns their result after they have finished executing.
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
guard let reader else {
|
||||
throw DatabaseError.snapshotIsLost()
|
||||
try $databaseAccess.withLock { databaseAccess in
|
||||
guard let databaseAccess else {
|
||||
throw DatabaseError.snapshotIsLost()
|
||||
}
|
||||
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
return try databaseAccess.reader.sync(value)
|
||||
}
|
||||
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
return try reader.sync(value)
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and
|
||||
/// returns immediately.
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
guard let reader else {
|
||||
value(.failure(DatabaseError.snapshotIsLost()))
|
||||
return
|
||||
}
|
||||
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
reader.async { db in
|
||||
value(.success(db))
|
||||
$databaseAccess.withLock { databaseAccess in
|
||||
guard let databaseAccess 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.databaseAccess == nil {
|
||||
value(.failure(DatabaseError.snapshotIsLost()))
|
||||
}
|
||||
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(
|
||||
reader: SerializedDatabase,
|
||||
release: (_ isInsideTransaction: Bool) -> Void)
|
||||
{
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
try? db.commit()
|
||||
return db.isInsideTransaction
|
||||
$databaseAccess.withLock { databaseAccess in
|
||||
databaseAccess?.commitAndRelease()
|
||||
databaseAccess = nil
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -118,14 +118,14 @@ func throwingFirstError<T>(execute: () throws -> T, finally: () throws -> Void)
|
||||
return result!
|
||||
}
|
||||
|
||||
struct PrintOutputStream: TextOutputStream {
|
||||
struct PrintOutputStream: TextOutputStream, Sendable {
|
||||
func write(_ string: String) {
|
||||
Swift.print(string)
|
||||
}
|
||||
}
|
||||
|
||||
/// Concatenates two functions
|
||||
func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
|
||||
/// Concatenates two @Sendable functions
|
||||
func concat(_ rhs: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (@Sendable () -> Void)? {
|
||||
switch (rhs, lhs) {
|
||||
case let (rhs, nil):
|
||||
return rhs
|
||||
@@ -139,8 +139,8 @@ func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
|
||||
}
|
||||
}
|
||||
|
||||
/// Concatenates two functions
|
||||
func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
|
||||
/// Concatenates two @Sendable functions
|
||||
func concat<T>(_ rhs: (@Sendable (T) -> Void)?, _ lhs: (@Sendable (T) -> Void)?) -> (@Sendable (T) -> Void)? {
|
||||
switch (rhs, lhs) {
|
||||
case let (rhs, nil):
|
||||
return rhs
|
||||
|
||||
@@ -18,7 +18,10 @@ import Foundation
|
||||
/// reducing stage.
|
||||
///
|
||||
/// **Notify** is calling user callbacks, in case of database change or error.
|
||||
final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObservationScheduler> {
|
||||
final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObservationScheduler>: @unchecked Sendable {
|
||||
// @unchecked because mutable state is protected by various locks and
|
||||
// serial dispatch queues. See "Mutable State" below.
|
||||
|
||||
// MARK: - Configuration
|
||||
//
|
||||
// Configuration is not mutable.
|
||||
@@ -72,7 +75,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
|
||||
// be notified. See error catching clauses.
|
||||
|
||||
/// Ability to access the database
|
||||
private struct DatabaseAccess {
|
||||
private struct DatabaseAccess: Sendable {
|
||||
/// The observed DatabasePool.
|
||||
let dbPool: DatabasePool
|
||||
|
||||
@@ -102,7 +105,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
|
||||
}
|
||||
|
||||
/// The fetching state for observation of constant regions.
|
||||
enum FetchingState {
|
||||
enum FetchingState: Sendable {
|
||||
/// No need to fetch.
|
||||
case idle
|
||||
|
||||
@@ -115,13 +118,13 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
private struct NotificationCallbacks: Sendable {
|
||||
let events: ValueObservationEvents
|
||||
let onChange: (Reducer.Value) -> Void
|
||||
let onChange: @Sendable (Reducer.Value) -> Void
|
||||
}
|
||||
|
||||
/// Relationship with the `TransactionObserver` protocol
|
||||
private struct ObservationState {
|
||||
private struct ObservationState: Sendable {
|
||||
var region: DatabaseRegion?
|
||||
var isModified = false
|
||||
|
||||
@@ -161,7 +164,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
reducer: Reducer,
|
||||
events: ValueObservationEvents,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
{
|
||||
// Configuration
|
||||
self.scheduler = scheduler
|
||||
|
||||
@@ -21,8 +21,11 @@ import Foundation
|
||||
final class ValueWriteOnlyObserver<
|
||||
Writer: DatabaseWriter,
|
||||
Reducer: ValueReducer,
|
||||
Scheduler: ValueObservationScheduler>
|
||||
Scheduler: ValueObservationScheduler>: @unchecked Sendable
|
||||
{
|
||||
// @unchecked because mutable state is protected by various locks and
|
||||
// serial dispatch queues. See "Mutable State" below.
|
||||
|
||||
// MARK: - Configuration
|
||||
//
|
||||
// Configuration is not mutable.
|
||||
@@ -76,7 +79,7 @@ final class ValueWriteOnlyObserver<
|
||||
// be notified. See error catching clauses.
|
||||
|
||||
/// Ability to access the database
|
||||
private struct DatabaseAccess {
|
||||
private struct DatabaseAccess: Sendable {
|
||||
/// The observed DatabaseWriter.
|
||||
let writer: Writer
|
||||
|
||||
@@ -110,13 +113,13 @@ final class ValueWriteOnlyObserver<
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
private struct NotificationCallbacks: Sendable {
|
||||
let events: ValueObservationEvents
|
||||
let onChange: (Reducer.Value) -> Void
|
||||
let onChange: @Sendable (Reducer.Value) -> Void
|
||||
}
|
||||
|
||||
/// Relationship with the `TransactionObserver` protocol
|
||||
private struct ObservationState {
|
||||
private struct ObservationState: Sendable {
|
||||
var region: DatabaseRegion?
|
||||
var isModified = false
|
||||
|
||||
@@ -150,7 +153,7 @@ final class ValueWriteOnlyObserver<
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
reducer: Reducer,
|
||||
events: ValueObservationEvents,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
{
|
||||
// Configuration
|
||||
self.scheduler = scheduler
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
extension ValueReducers {
|
||||
/// A `ValueReducer` that perform database fetches.
|
||||
public struct Fetch<Value>: ValueReducer {
|
||||
private let __fetch: (Database) throws -> Value
|
||||
public struct Fetch<Value: Sendable>: ValueReducer {
|
||||
private let __fetch: @Sendable (Database) throws -> Value
|
||||
|
||||
/// Creates a reducer which passes raw fetched values through.
|
||||
init(fetch: @escaping (Database) throws -> Value) {
|
||||
init(fetch: @escaping @Sendable (Database) throws -> Value) {
|
||||
self.__fetch = fetch
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// - parameter transform: A closure that takes one value as its parameter
|
||||
/// and returns a new value.
|
||||
public func map<T>(_ transform: @escaping (Reducer.Value) throws -> T)
|
||||
public func map<T>(_ transform: @escaping @Sendable (Reducer.Value) throws -> T)
|
||||
-> ValueObservation<ValueReducers.Map<Reducer, T>>
|
||||
{
|
||||
mapReducer { ValueReducers.Map($0, transform) }
|
||||
@@ -30,11 +30,11 @@ 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
|
||||
private let transform: @Sendable (Base.Value) throws -> Value
|
||||
|
||||
init(_ base: Base, _ transform: @escaping (Base.Value) throws -> Value) {
|
||||
init(_ base: Base, _ transform: @escaping @Sendable (Base.Value) throws -> Value) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ extension ValueObservation {
|
||||
/// - parameter predicate: A closure to evaluate whether two values are
|
||||
/// equivalent, for purposes of filtering. Return true from this closure
|
||||
/// to indicate that the second element is a duplicate of the first.
|
||||
public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool)
|
||||
public func removeDuplicates(by predicate: @escaping @Sendable (Reducer.Value, Reducer.Value) -> Bool)
|
||||
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
|
||||
{
|
||||
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) }
|
||||
@@ -58,7 +58,10 @@ extension ValueObservation where Reducer.Value: Equatable {
|
||||
public func removeDuplicates()
|
||||
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
|
||||
{
|
||||
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: ==) }
|
||||
mapReducer { base in
|
||||
// https://github.com/apple/swift/issues/71541
|
||||
ValueReducers.RemoveDuplicates(base, predicate: { $0 == $1 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,9 +73,9 @@ extension ValueReducers {
|
||||
public struct RemoveDuplicates<Base: _ValueReducer>: _ValueReducer {
|
||||
private var base: Base
|
||||
private var previousValue: Base.Value?
|
||||
private var predicate: (Base.Value, Base.Value) -> Bool
|
||||
private var predicate: @Sendable (Base.Value, Base.Value) -> Bool
|
||||
|
||||
init(_ base: Base, predicate: @escaping (Base.Value, Base.Value) -> Bool) {
|
||||
init(_ base: Base, predicate: @escaping @Sendable (Base.Value, Base.Value) -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ extension ValueReducers {
|
||||
/// and ``ValueObservation/print(_:to:)``.
|
||||
public struct Trace<Base: _ValueReducer>: _ValueReducer {
|
||||
var base: Base
|
||||
let willFetch: () -> Void
|
||||
let didReceiveValue: (Base.Value) -> Void
|
||||
let willFetch: @Sendable () -> Void
|
||||
let didReceiveValue: @Sendable (Base.Value) -> Void
|
||||
|
||||
public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? {
|
||||
guard let value = try base._value(fetched) else {
|
||||
|
||||
@@ -36,7 +36,7 @@ public protocol _ValueReducer {
|
||||
/// ### Support
|
||||
///
|
||||
/// - ``ValueReducers``
|
||||
public protocol ValueReducer: _ValueReducer {
|
||||
public protocol ValueReducer: _ValueReducer, Sendable {
|
||||
/// Fetches database values upon changes in an observed database region.
|
||||
///
|
||||
/// This method must does not depend on the state of the reducer.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// The extent of the shared subscription to a ``SharedValueObservation``.
|
||||
public enum SharedValueObservationExtent {
|
||||
public enum SharedValueObservationExtent: Sendable {
|
||||
/// The ``SharedValueObservation`` starts a single database observation,
|
||||
/// which stops when the `SharedValueObservation` is deallocated and all
|
||||
/// subscriptions terminated.
|
||||
@@ -167,7 +167,8 @@ extension ValueObservation {
|
||||
/// 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> {
|
||||
public final class SharedValueObservation<Element: Sendable>: @unchecked Sendable {
|
||||
// @unchecked because `clients` is protected by `lock`.
|
||||
private let scheduler: any ValueObservationScheduler
|
||||
private let extent: SharedValueObservationExtent
|
||||
private let startObservation: ValueObservationStart<Element>
|
||||
@@ -179,11 +180,11 @@ public final class SharedValueObservation<Element> {
|
||||
private var cancellable: AnyDatabaseCancellable?
|
||||
private var lastResult: Result<Element, Error>?
|
||||
|
||||
private final class Client {
|
||||
var onError: (Error) -> Void
|
||||
var onChange: (Element) -> Void
|
||||
private final class Client: Sendable {
|
||||
let onError: @Sendable (Error) -> Void
|
||||
let onChange: @Sendable (Element) -> Void
|
||||
|
||||
init(onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) {
|
||||
init(onError: @escaping @Sendable (Error) -> Void, onChange: @escaping @Sendable (Element) -> Void) {
|
||||
self.onError = onError
|
||||
self.onChange = onChange
|
||||
}
|
||||
@@ -224,8 +225,8 @@ public final class SharedValueObservation<Element> {
|
||||
/// fresh value.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
public func start(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Element) -> Void)
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (Element) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
synchronized {
|
||||
|
||||
@@ -4,7 +4,7 @@ import Combine
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
public struct ValueObservation<Reducer: _ValueReducer>: Sendable {
|
||||
var events = ValueObservationEvents()
|
||||
|
||||
/// A boolean value indicating whether the observation requires write access
|
||||
@@ -30,10 +30,10 @@ public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
|
||||
/// The reducer is created when observation starts, and is triggered upon
|
||||
/// each database change.
|
||||
var makeReducer: () -> Reducer
|
||||
var makeReducer: @Sendable () -> Reducer
|
||||
|
||||
/// Returns a ValueObservation with a transformed reducer.
|
||||
func mapReducer<R>(_ transform: @escaping (Reducer) -> R) -> ValueObservation<R> {
|
||||
func mapReducer<R>(_ transform: @escaping @Sendable (Reducer) -> R) -> ValueObservation<R> {
|
||||
let makeReducer = self.makeReducer
|
||||
return ValueObservation<R>(
|
||||
events: events,
|
||||
@@ -44,7 +44,7 @@ public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
}
|
||||
|
||||
/// Configures the tracked region
|
||||
enum ValueObservationTrackingMode {
|
||||
enum ValueObservationTrackingMode: Sendable {
|
||||
/// The tracked region is constant and explicit.
|
||||
///
|
||||
/// Use case:
|
||||
@@ -73,17 +73,17 @@ enum ValueObservationTrackingMode {
|
||||
case nonConstantRegionRecordedFromSelection
|
||||
}
|
||||
|
||||
struct ValueObservationEvents: Refinable {
|
||||
var willStart: (() -> Void)?
|
||||
var willTrackRegion: ((DatabaseRegion) -> Void)?
|
||||
var databaseDidChange: (() -> Void)?
|
||||
var didFail: ((Error) -> Void)?
|
||||
var didCancel: (() -> Void)?
|
||||
struct ValueObservationEvents: Refinable, Sendable {
|
||||
var willStart: (@Sendable () -> Void)?
|
||||
var willTrackRegion: (@Sendable (DatabaseRegion) -> Void)?
|
||||
var databaseDidChange: (@Sendable () -> Void)?
|
||||
var didFail: (@Sendable (Error) -> Void)?
|
||||
var didCancel: (@Sendable () -> Void)?
|
||||
}
|
||||
|
||||
typealias ValueObservationStart<T> = (
|
||||
_ onError: @escaping (Error) -> Void,
|
||||
_ onChange: @escaping (T) -> Void)
|
||||
typealias ValueObservationStart<T: Sendable> = @Sendable (
|
||||
_ onError: @escaping @Sendable (Error) -> Void,
|
||||
_ onChange: @escaping @Sendable (T) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
|
||||
extension ValueObservation: Refinable {
|
||||
@@ -138,8 +138,8 @@ extension ValueObservation: Refinable {
|
||||
public func start(
|
||||
in reader: some DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
@@ -175,13 +175,13 @@ extension ValueObservation: Refinable {
|
||||
/// - returns: A `ValueObservation` that performs the specified closures
|
||||
/// when ValueObservation events occur.
|
||||
public func handleEvents(
|
||||
willStart: (() -> Void)? = nil,
|
||||
willFetch: (() -> Void)? = nil,
|
||||
willTrackRegion: ((DatabaseRegion) -> Void)? = nil,
|
||||
databaseDidChange: (() -> Void)? = nil,
|
||||
didReceiveValue: ((Reducer.Value) -> Void)? = nil,
|
||||
didFail: ((Error) -> Void)? = nil,
|
||||
didCancel: (() -> Void)? = nil)
|
||||
willStart: (@Sendable () -> Void)? = nil,
|
||||
willFetch: (@Sendable () -> Void)? = nil,
|
||||
willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? = nil,
|
||||
databaseDidChange: (@Sendable () -> Void)? = nil,
|
||||
didReceiveValue: (@Sendable (Reducer.Value) -> Void)? = nil,
|
||||
didFail: (@Sendable (Error) -> Void)? = nil,
|
||||
didCancel: (@Sendable () -> Void)? = nil)
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
self
|
||||
@@ -229,36 +229,66 @@ extension ValueObservation: Refinable {
|
||||
/// - parameter stream: A stream for text output that receives messages, and
|
||||
/// which directs output to the console by default. A custom stream can be
|
||||
/// used to log messages to other destinations.
|
||||
public func print(
|
||||
_ prefix: String = "",
|
||||
to stream: TextOutputStream? = nil)
|
||||
public func print(_ prefix: String = "")
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
let lock = NSLock()
|
||||
print(prefix, to: PrintOutputStream())
|
||||
}
|
||||
|
||||
/// Prints log messages for all observation events.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = ValueObservation
|
||||
/// .tracking(Player.fetchCount)
|
||||
/// .print("Observe player count")
|
||||
/// .start(in: dbQueue, onError: { _ in }, onChange: { _ in })
|
||||
///
|
||||
/// // Prints:
|
||||
/// // Observe player count: start
|
||||
/// // Observe player count: fetch
|
||||
/// // Observe player count: tracked region: player(*)
|
||||
/// // Observe player count: value: 0
|
||||
/// // Observe player count: database did change
|
||||
/// // Observe player count: fetch
|
||||
/// // Observe player count: value: 1
|
||||
/// ```
|
||||
///
|
||||
/// - parameter prefix: A string —- which defaults to empty -— with which to
|
||||
/// prefix all log messages.
|
||||
/// - parameter stream: A stream for text output that receives messages, and
|
||||
/// which directs output to the console by default. A custom stream can be
|
||||
/// used to log messages to other destinations.
|
||||
public func print<Stream: TextOutputStream & Sendable>(
|
||||
_ prefix: String = "",
|
||||
to stream: Stream)
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
let stream = LockedBox(wrappedValue: stream)
|
||||
let prefix = prefix.isEmpty ? "" : "\(prefix): "
|
||||
var stream = stream ?? PrintOutputStream()
|
||||
return handleEvents(
|
||||
willStart: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)start") },
|
||||
stream.update { $0.write("\(prefix)start") }
|
||||
},
|
||||
willFetch: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)fetch") },
|
||||
willTrackRegion: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)tracked region: \($0)") },
|
||||
stream.update { $0.write("\(prefix)fetch") }
|
||||
},
|
||||
willTrackRegion: { region in
|
||||
stream.update { $0.write("\(prefix)tracked region: \(region)") }
|
||||
},
|
||||
databaseDidChange: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)database did change") },
|
||||
didReceiveValue: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)value: \($0)") },
|
||||
didFail: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)failure: \($0)") },
|
||||
stream.update { $0.write("\(prefix)database did change") }
|
||||
},
|
||||
didReceiveValue: { value in
|
||||
stream.update { $0.write("\(prefix)value: \(value)") }
|
||||
},
|
||||
didFail: { error in
|
||||
stream.update { $0.write("\(prefix)failure: \(error)") }
|
||||
},
|
||||
didCancel: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)cancel") })
|
||||
stream.update { $0.write("\(prefix)cancel") }
|
||||
})
|
||||
}
|
||||
|
||||
// MARK: - Fetching Values
|
||||
@@ -333,7 +363,7 @@ extension ValueObservation {
|
||||
/// You build an `AsyncValueObservation` from ``ValueObservation`` or
|
||||
/// ``SharedValueObservation``.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public struct AsyncValueObservation<Element>: AsyncSequence {
|
||||
public struct AsyncValueObservation<Element: Sendable>: AsyncSequence {
|
||||
public typealias BufferingPolicy = AsyncThrowingStream<Element, Error>.Continuation.BufferingPolicy
|
||||
public typealias AsyncIterator = Iterator
|
||||
|
||||
@@ -457,7 +487,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>
|
||||
|
||||
@@ -473,9 +503,11 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
private class ValueSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error
|
||||
private final class ValueSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
|
||||
where Downstream.Input: Sendable, Downstream.Failure == Error
|
||||
{
|
||||
// @unchecked because `cancellable` and `state` are protected by `lock`.
|
||||
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
let start: ValueObservationStart<Downstream.Input>
|
||||
@@ -704,7 +736,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func trackingConstantRegion<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
_ fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
@@ -765,7 +797,7 @@ extension ValueObservation {
|
||||
public static func tracking<Value>(
|
||||
region: any DatabaseRegionConvertible,
|
||||
_ otherRegions: any DatabaseRegionConvertible...,
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
@@ -821,7 +853,7 @@ extension ValueObservation {
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
regions: [any DatabaseRegionConvertible],
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
@@ -878,7 +910,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
_ fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user