mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
015c4db2b0 | ||
|
|
9eb2b98ae8 |
No files matched your search
@@ -9,6 +9,9 @@ Migrating From GRDB 7 to GRDB 8
|
||||
- [SQLCipher](#sqlcipher)
|
||||
- [Shorthand Closure Notation in Asynchronous Database Accesses](#shorthand-closure-notation-in-asynchronous-database-accesses)
|
||||
- [Removing Duplicate Observed Values](#removing-duplicate-observed-values)
|
||||
- [Starting a ValueObservation](#starting-a-valueobservation)
|
||||
- [Asynchronous Sequences of Observed Values](#asynchronous-sequences-of-observed-values)
|
||||
- [Sharing a ValueObservation](#sharing-a-valueobservation)
|
||||
- [Cached Statements](#cached-statements)
|
||||
- [JSON User Info](#json-user-info)
|
||||
|
||||
@@ -70,6 +73,100 @@ The `ValueObservation.removeDuplicates(by:)` method now requires a `Sendable` pr
|
||||
|
||||
`ValueObservation.removeDuplicates()`, which compares `Equatable` values, is not affected.
|
||||
|
||||
## Starting a ValueObservation
|
||||
|
||||
In GRDB 7, `ValueObservation.start(in:onError:onChange:)` had to be called from the main actor, and notified fresh values on the main actor. In GRDB 8, it can be called from any actor, and notifies fresh values on this actor. The `onError` and `onChange` callbacks do not need to be `Sendable`:
|
||||
|
||||
```swift
|
||||
actor PlayerTracker {
|
||||
var playerCount = 0
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
func start(in reader: any DatabaseReader) {
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
// GRDB 8: notifies fresh values on the PlayerTracker actor.
|
||||
cancellable = observation.start(in: reader) { error in
|
||||
// handle error
|
||||
} onChange: { [unowned self] count in
|
||||
self.playerCount = count
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `.immediate` scheduling, which notifies the initial value immediately, is no longer restricted to the main actor: it is available on all actors.
|
||||
|
||||
`ValueObservation.start` no longer accepts a `ValueObservationScheduler`. When the observation is started from an actor, remove this `scheduling` argument: fresh values are notified on this actor.
|
||||
|
||||
`ValueObservation.start` must now be called from an actor. In nonisolated code, it no longer compiles, with or without a `scheduling` argument. Without one, the compiler reports `'nil' is not compatible with expected argument type 'any Actor'`.
|
||||
|
||||
Synchronous nonisolated code that runs on the main thread can start the observation from `MainActor.assumeIsolated`:
|
||||
|
||||
```swift
|
||||
// GRDB 7
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate)
|
||||
{ error in
|
||||
// handle error
|
||||
} onChange: { value in
|
||||
print("Fresh value", value)
|
||||
}
|
||||
|
||||
// GRDB 8
|
||||
let cancellable = MainActor.assumeIsolated {
|
||||
observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// handle error
|
||||
} onChange: { value in
|
||||
print("Fresh value", value)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Other nonisolated code can start the observation from an actor, or iterate the asynchronous sequence of observed values:
|
||||
|
||||
```swift
|
||||
// GRDB 8
|
||||
for try await value in observation.values(in: dbQueue) {
|
||||
print("Fresh value", value)
|
||||
}
|
||||
```
|
||||
|
||||
The `ValueObservationMainActorScheduler` protocol and the `DelayedMainActorValueObservationScheduler` type were removed. Custom schedulers adopt `ValueObservationScheduler` instead, and implement `schedule(_:)` instead of `scheduleOnMainActor(_:)`.
|
||||
|
||||
## Asynchronous Sequences of Observed Values
|
||||
|
||||
`ValueObservation.values(in:)` no longer accepts a `scheduling` argument: the loop that iterates the sequence runs with the isolation of its surrounding code, regardless of any scheduler. Remove this argument:
|
||||
|
||||
```swift
|
||||
// GRDB 7
|
||||
for try await players in observation.values(in: dbQueue, scheduling: .immediate) { ... }
|
||||
|
||||
// GRDB 8
|
||||
for try await players in observation.values(in: dbQueue) { ... }
|
||||
```
|
||||
|
||||
## Sharing a ValueObservation
|
||||
|
||||
`SharedValueObservation.start(onError:onChange:)` changes like `ValueObservation.start` (see [Starting a ValueObservation](#starting-a-valueobservation)): it notifies each client on the actor that starts it, its callbacks do not need to be `Sendable`, and it must be called from an actor.
|
||||
|
||||
`ValueObservation.shared(in:scheduling:extent:)` now accepts the same scheduling as `ValueObservation.start`: `.async` (the default) or `.immediate`. The `.immediate` scheduling is no longer restricted to the main actor: each client, on any actor, is notified of its initial value immediately when it starts.
|
||||
|
||||
Other schedulers, such as `.task` or `.async(onQueue:)`, are no longer accepted. Remove them:
|
||||
|
||||
```swift
|
||||
// GRDB 7
|
||||
let sharedObservation = observation.shared(in: dbQueue, scheduling: .task)
|
||||
for try await players in sharedObservation.values() { ... }
|
||||
|
||||
// GRDB 8
|
||||
let sharedObservation = observation.shared(in: dbQueue)
|
||||
for try await players in sharedObservation.values() { ... }
|
||||
```
|
||||
|
||||
## Cached Statements
|
||||
|
||||
The statements returned by `Database.cachedStatement(sql:)` and `Database.cachedStatement(literal:)` no longer preserve their arguments between two calls. You must set the arguments of a cached statement each time you load it from the cache:
|
||||
|
||||
@@ -145,7 +145,7 @@ No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rolled back.
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). GRDB makes sure notifications happen in the same order as database transactions.
|
||||
Next, notifications happen on the actor that starts the observation. GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
|
||||
@@ -405,7 +405,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
|
||||
/// Starts a value observation.
|
||||
///
|
||||
/// Use the ``ValueObservation/start(in:scheduling:onError:onChange:)``
|
||||
/// Use the ``ValueObservation/start(in:scheduling:isolation:onError:onChange:)``
|
||||
/// method instead.
|
||||
///
|
||||
/// - parameter observation: a ValueObservation.
|
||||
|
||||
@@ -259,7 +259,7 @@ All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
Does this mean you can't rely on anything? Of course not:
|
||||
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value is fetched, and soon notified on the main thread where the screen can be updated.
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value is fetched, and soon notified on the actor that started the observation, such as the main actor where the screen can be updated.
|
||||
|
||||
- As said above, the moment of truth is the next write access!
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the li
|
||||
|
||||
By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see <doc:ValueObservation#Specifying-the-Tracked-Region>.
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, asynchronously, on the actor that starts the observation. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
@@ -98,81 +98,50 @@ The database observation stops when the cancellable returned by the `start` meth
|
||||
|
||||
## ValueObservation Scheduling
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously:
|
||||
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, asynchronously, on the actor that starts the observation. In a graphical application, this is usually the main actor:
|
||||
|
||||
```swift
|
||||
// The default scheduling
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// This closure is MainActor-isolated.
|
||||
} onChange: { value in
|
||||
// This closure is MainActor-isolated.
|
||||
print("Fresh value", value)
|
||||
@MainActor func startObservation() {
|
||||
cancellable = observation.start(in: dbQueue) { error in
|
||||
// Called on the main actor
|
||||
} onChange: { value in
|
||||
// Called on the main actor
|
||||
print("Fresh value", value)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can change this behavior by adding a `scheduling` argument to the `start()` method.
|
||||
The callbacks are called in order, on the actor that starts the observation, so they can access its state, and they do not need to be `Sendable`.
|
||||
|
||||
For example, the ``ValueObservationMainActorScheduler/immediate`` scheduler notifies all values on the main actor, and notifies the first one immediately when the observation starts.
|
||||
The `start()` method must be called from an actor. Synchronous nonisolated code that runs on the main thread can call it from `MainActor.assumeIsolated`. Other nonisolated code can iterate the asynchronous sequence returned by ``values(in:bufferingPolicy:)``.
|
||||
|
||||
You can change the default scheduling by adding a `scheduling` argument to the `start()` method.
|
||||
|
||||
For example, the ``IsolatedValueObservationScheduling/immediate`` scheduling notifies all values on the actor that starts the observation, and notifies the first one immediately when the observation starts.
|
||||
|
||||
It is very useful in graphical applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Be aware that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests!
|
||||
|
||||
```swift
|
||||
// Immediate scheduling notifies
|
||||
// the initial value right on subscription.
|
||||
let cancellable = observation
|
||||
.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// Called on the main actor
|
||||
} onChange: { value in
|
||||
// Called on the main actor
|
||||
print("Fresh value", value)
|
||||
}
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
```
|
||||
|
||||
The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispatchQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
|
||||
|
||||
```swift
|
||||
// Async scheduling notifies all values
|
||||
// on the specified dispatch queue.
|
||||
let myQueue: DispatchQueue
|
||||
let cancellable = observation
|
||||
.start(in: dbQueue, scheduling: .async(myQueue)) { error in
|
||||
// Called asynchronously on myQueue
|
||||
} onChange: { value in
|
||||
// Called asynchronously on myQueue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
```
|
||||
|
||||
The ``ValueObservationScheduler/task`` scheduler asynchronously schedules values and errors on the cooperative thread pool. It is implicitly used when you turn a ValueObservation into an async sequence. You can specify it explicitly when you intend to consume a shared observation as an async sequence:
|
||||
|
||||
```swift
|
||||
do {
|
||||
for try await players in observation.values(in: dbQueue) {
|
||||
// Called on the cooperative thread pool
|
||||
print("Fresh players", players)
|
||||
}
|
||||
} catch {
|
||||
// Handle error
|
||||
@MainActor func startObservation() {
|
||||
cancellable = observation
|
||||
.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// Called on the main actor
|
||||
} onChange: { value in
|
||||
// Called on the main actor
|
||||
print("Fresh value", value)
|
||||
}
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
}
|
||||
|
||||
let sharedObservation = observation.shared(in: dbQueue, scheduling: .task)
|
||||
do {
|
||||
for try await players in sharedObservation.values() {
|
||||
// Called on the cooperative thread pool
|
||||
print("Fresh players", players)
|
||||
}
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control over the execution of the database fetch:
|
||||
|
||||
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main actor, when the observation starts, so that the initial value can be notified immediately.
|
||||
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the actor that starts the observation, so that the initial value can be notified immediately.
|
||||
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronously. It never blocks the main thread.
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronously. It never blocks the actor that starts the observation.
|
||||
|
||||
- By default, fresh values are fetched immediately after the database was changed. In particular, modifying the database on the main thread triggers a fetch on the main thread as well.
|
||||
|
||||
@@ -194,13 +163,16 @@ let sharedObservation = ValueObservation
|
||||
.shared(in: dbQueue)
|
||||
```
|
||||
|
||||
`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. As a replacement, you may for example use Combine apis:
|
||||
Like `ValueObservation`, a shared observation notifies each client on the actor that starts it with ``SharedValueObservation/start(isolation:onError:onChange:)``, so that clients on distinct actors can share a single observation. The `scheduling` argument of ``shared(in:scheduling:extent:)`` applies to all clients: with the `.immediate` scheduling, each client is notified of its initial value immediately when it starts.
|
||||
|
||||
`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. Apply such operators to the `ValueObservation`, before it is shared:
|
||||
|
||||
```swift
|
||||
let cancellable = try sharedObservation
|
||||
.publisher() // Turn shared observation into a Combine Publisher
|
||||
.map { ... } // The map operator from Combine
|
||||
.sink(...)
|
||||
// SharedValueObservation<Int>
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.map { players in players.count }
|
||||
.shared(in: dbQueue)
|
||||
```
|
||||
|
||||
|
||||
@@ -315,13 +287,12 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
|
||||
### Accessing Observed Values
|
||||
|
||||
- ``start(in:scheduling:onError:onChange:)-t62r``
|
||||
- ``start(in:scheduling:onError:onChange:)-4mqbs``
|
||||
- ``start(in:scheduling:isolation:onError:onChange:)``
|
||||
- ``publisher(in:scheduling:)``
|
||||
- ``values(in:scheduling:bufferingPolicy:)``
|
||||
- ``values(in:bufferingPolicy:)``
|
||||
- ``DatabaseCancellable``
|
||||
- ``IsolatedValueObservationScheduling``
|
||||
- ``ValueObservationScheduler``
|
||||
- ``ValueObservationMainActorScheduler``
|
||||
|
||||
### Mapping Values
|
||||
|
||||
|
||||
@@ -83,16 +83,14 @@ extension ValueObservation {
|
||||
/// .shared(in: dbQueue, extent: .observationLifetime)
|
||||
/// ```
|
||||
///
|
||||
/// By default, fresh values are dispatched asynchronously on the
|
||||
/// main dispatch queue. You can change this behavior by providing a
|
||||
/// scheduler.
|
||||
///
|
||||
/// For example, the ``ValueObservationMainActorScheduler/immediate``
|
||||
/// scheduler notifies all values on the main dispatch queue, and
|
||||
/// notifies the first one immediately when the
|
||||
/// ``SharedValueObservation/start(onError:onChange:)`` method is called.
|
||||
/// The `immediate` scheduling requires that the observation starts from the
|
||||
/// main thread (a fatal error is raised otherwise):
|
||||
/// A client started with
|
||||
/// ``SharedValueObservation/start(isolation:onError:onChange:)`` is
|
||||
/// notified on the actor that starts it, so that clients on distinct
|
||||
/// actors can share a single observation. By default, each client is
|
||||
/// notified of its initial value asynchronously. The
|
||||
/// ``IsolatedValueObservationScheduling/immediate`` scheduling
|
||||
/// notifies each client of its initial value immediately, when
|
||||
/// it starts:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
@@ -103,30 +101,48 @@ extension ValueObservation {
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .immediate)
|
||||
///
|
||||
/// let cancellable = sharedObservation.start { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players: \(players)")
|
||||
/// @MainActor func startObservation() {
|
||||
/// cancellable = sharedObservation.start { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// // <- here "Fresh players" is already printed.
|
||||
/// }
|
||||
/// // <- here "Fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A Scheduler. By default, fresh values are
|
||||
/// dispatched asynchronously on the main queue.
|
||||
/// - parameter scheduling: Determines when the initial value is
|
||||
/// notified. By default, it is notified asynchronously.
|
||||
/// - parameter extent: The extent of the shared database observation.
|
||||
/// - returns: A `SharedValueObservation`
|
||||
public func shared(
|
||||
in reader: any DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
|
||||
scheduling: IsolatedValueObservationScheduling = .async,
|
||||
extent: SharedValueObservationExtent = .whileObserved)
|
||||
-> SharedValueObservation<Reducer.Value>
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
SharedValueObservation(scheduling: scheduler, extent: extent) { onError, onChange in
|
||||
// The upstream observation notifies the clients of the shared
|
||||
// observation directly: each client notifies values with its
|
||||
// own scheduler.
|
||||
let scheduler = DirectValueObservationScheduler(
|
||||
immediate: scheduling.immediateInitialValue)
|
||||
return SharedValueObservation(scheduling: scheduling, extent: extent) { onError, onChange in
|
||||
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable, message: "Use IsolatedValueObservationScheduling: .async or .immediate.")
|
||||
public func shared(
|
||||
in reader: any DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
extent: SharedValueObservationExtent = .whileObserved)
|
||||
-> SharedValueObservation<Reducer.Value>
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
fatalError("unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared value observation saves database resources by sharing a single
|
||||
@@ -165,15 +181,21 @@ extension ValueObservation {
|
||||
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
/// ```
|
||||
public final class SharedValueObservation<Element: Sendable>: @unchecked Sendable {
|
||||
// @unchecked Sendable because state is protected by `lock`.
|
||||
private let scheduler: any ValueObservationScheduler
|
||||
// @unchecked Sendable because state is protected by `condition`.
|
||||
private let scheduling: IsolatedValueObservationScheduling
|
||||
private let extent: SharedValueObservationExtent
|
||||
private let startObservation: ValueObservationStart<Element>
|
||||
// Clients are notified outside of the lock, so that a client can be
|
||||
// cancelled from any thread during a notification without deadlock.
|
||||
private let lock = NSLock()
|
||||
|
||||
// protected by lock
|
||||
// Protects the state below. Clients are notified outside of the
|
||||
// lock, so that a client can be cancelled from any thread during a
|
||||
// notification without deadlock.
|
||||
//
|
||||
// A condition lets a client that needs an immediate initial value
|
||||
// wait until the upstream observation, started by another client
|
||||
// from another thread, has fetched its initial value.
|
||||
private let condition = NSCondition()
|
||||
|
||||
// protected by condition
|
||||
private var clients: [Client]
|
||||
private var currentSubscription: ValueObservationSubscription? // nil when not observing
|
||||
private var lastResult: Result<Element, Error>?
|
||||
@@ -188,49 +210,68 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
}
|
||||
|
||||
/// A client receives the events of the shared observation, and
|
||||
/// notifies them with its own scheduler.
|
||||
///
|
||||
/// The events received while the client is starting are notified
|
||||
/// when the client finishes starting, so that the first one can be
|
||||
/// notified synchronously, from the caller of `start`.
|
||||
private final class Client: Sendable {
|
||||
private let scheduler: any ValueObservationScheduler
|
||||
private let onError: @Sendable (Error) -> Void
|
||||
private let onChange: @Sendable (Element) -> Void
|
||||
private let stateMutex = Mutex(State())
|
||||
|
||||
private struct State {
|
||||
var isCancelled = false
|
||||
/// True when a ValueObservation event was notified, and we must
|
||||
/// not notify the last result of the shared observation as the
|
||||
/// initial event.
|
||||
var shouldDiscardInitialResult = false
|
||||
var isStarting = true
|
||||
/// The events received while the client is starting.
|
||||
var pendingEvents: [Result<Element, Error>] = []
|
||||
}
|
||||
|
||||
init(
|
||||
scheduler: some ValueObservationScheduler,
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (Element) -> Void
|
||||
) {
|
||||
self.scheduler = scheduler
|
||||
self.onError = onError
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
/// Notifies the last result of the shared observation as the initial
|
||||
/// value, unless a ValueObservation event was already notified.
|
||||
func notifyInitial(_ result: Result<Element, Error>) {
|
||||
guard shouldNotifyInitialResult() else { return }
|
||||
switch result {
|
||||
case let .failure(error):
|
||||
onError(error)
|
||||
case let .success(value):
|
||||
onChange(value)
|
||||
/// Notifies an event, unless the client is starting. In this case,
|
||||
/// the event is notified when the client finishes starting.
|
||||
func receive(_ result: Result<Element, Error>) {
|
||||
let shouldSchedule = stateMutex.withLock { state in
|
||||
if state.isCancelled {
|
||||
return false
|
||||
}
|
||||
if state.isStarting {
|
||||
state.pendingEvents.append(result)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if shouldSchedule {
|
||||
scheduler.schedule { self.notify(result) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Notifies a ValueObservation event.
|
||||
func notifyChange(_ value: Element) {
|
||||
guard shouldNotifyValueObservationEvent() else { return }
|
||||
onChange(value)
|
||||
}
|
||||
|
||||
/// Notifies a ValueObservation event.
|
||||
func notifyError(_ error: Error) {
|
||||
guard shouldNotifyValueObservationEvent() else { return }
|
||||
onError(error)
|
||||
/// Notifies the events received while the client was starting.
|
||||
/// The first one is the initial event of the client.
|
||||
///
|
||||
/// After this method returns, events are notified as soon as they
|
||||
/// are received.
|
||||
func finishStart() {
|
||||
var isInitialEvent = true
|
||||
while let result = nextPendingEvent() {
|
||||
if isInitialEvent {
|
||||
isInitialEvent = false
|
||||
scheduler.scheduleInitial { self.notify(result) }
|
||||
} else {
|
||||
scheduler.schedule { self.notify(result) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After this method returns, no new notification starts.
|
||||
@@ -238,32 +279,35 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
stateMutex.withLock { $0.isCancelled = true }
|
||||
}
|
||||
|
||||
/// Returns whether a ValueObservation event should be notified.
|
||||
private func shouldNotifyValueObservationEvent() -> Bool {
|
||||
/// Returns the next pending event, or stops the starting phase
|
||||
/// if there is none.
|
||||
private func nextPendingEvent() -> Result<Element, Error>? {
|
||||
stateMutex.withLock { state in
|
||||
if state.isCancelled { return false }
|
||||
// After a ValueObservation event, we must ignore the
|
||||
// initial result.
|
||||
state.shouldDiscardInitialResult = true
|
||||
return true
|
||||
if state.pendingEvents.isEmpty {
|
||||
state.isStarting = false
|
||||
return nil
|
||||
}
|
||||
return state.pendingEvents.removeFirst()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether the initial result should be notified: the client
|
||||
/// is not cancelled, and the initial result should not be discarded.
|
||||
private func shouldNotifyInitialResult() -> Bool {
|
||||
stateMutex.withLock { state in
|
||||
!state.isCancelled && !state.shouldDiscardInitialResult
|
||||
private func notify(_ result: Result<Element, Error>) {
|
||||
if stateMutex.withLock({ $0.isCancelled }) { return }
|
||||
switch result {
|
||||
case let .failure(error):
|
||||
onError(error)
|
||||
case let .success(value):
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate init(
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
scheduling: IsolatedValueObservationScheduling,
|
||||
extent: SharedValueObservationExtent,
|
||||
startObservation: @escaping ValueObservationStart<Element>)
|
||||
{
|
||||
self.scheduler = scheduler
|
||||
self.scheduling = scheduling
|
||||
self.extent = extent
|
||||
self.startObservation = startObservation
|
||||
self.clients = []
|
||||
@@ -288,32 +332,77 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `onError` and `onChange` closures are called on the actor
|
||||
/// that starts the observation (`isolation`). The first value is
|
||||
/// notified immediately, before this method returns, if the shared
|
||||
/// observation was created with the
|
||||
/// ``IsolatedValueObservationScheduling/immediate`` scheduling.
|
||||
///
|
||||
/// This method must be called from an actor. In synchronous code that
|
||||
/// runs on the main thread, start the observation from the main actor
|
||||
/// with `MainActor.assumeIsolated`. Elsewhere, consider iterating
|
||||
/// ``values(bufferingPolicy:)``.
|
||||
///
|
||||
/// - parameter isolation: The actor that starts the observation.
|
||||
/// - parameter onError: The closure to execute when the observation fails.
|
||||
/// - parameter onChange: The closure to execute on receipt of a
|
||||
/// fresh value.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
@preconcurrency public func start(
|
||||
public func start(
|
||||
isolation: isolated any Actor = #isolation,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Element) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
let scheduler = ActorValueObservationScheduler(
|
||||
scheduling: scheduling,
|
||||
isolation: isolation)
|
||||
// Safe because the scheduler calls the closures on the actor.
|
||||
nonisolated(unsafe) let onError = onError
|
||||
nonisolated(unsafe) let onChange = onChange
|
||||
return start(
|
||||
scheduler: scheduler,
|
||||
onError: { error in onError(error) },
|
||||
onChange: { value in onChange(value) })
|
||||
}
|
||||
|
||||
/// Starts observing the database, and notifies events with
|
||||
/// the provided scheduler.
|
||||
func start(
|
||||
scheduler: some ValueObservationScheduler,
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (Element) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
let client = Client(onError: onError, onChange: onChange)
|
||||
let (newSubscription, lastResult) = lock.withLock {
|
||||
let client = Client(scheduler: scheduler, onError: onError, onChange: onChange)
|
||||
let newSubscription: ValueObservationSubscription? = condition.withLock {
|
||||
// An immediate initial value requires the result of the initial
|
||||
// fetch. When the upstream observation is being started by
|
||||
// another thread, wait for this result.
|
||||
//
|
||||
// The upstream observation is never being started by the
|
||||
// current thread, because clients are not notified until the
|
||||
// upstream observation has started.
|
||||
while scheduling.immediateInitialValue
|
||||
&& currentSubscription != nil
|
||||
&& lastResult == nil
|
||||
{
|
||||
condition.wait()
|
||||
}
|
||||
|
||||
// State change
|
||||
clients.append(client)
|
||||
|
||||
// Support for reentrancy: a shared immediate observation is
|
||||
// started from the first value notification of that same shared
|
||||
// immediate observation. Yeah, users are nasty.
|
||||
// In this case, self.currentSubscription has no cancellable yet,
|
||||
// because we are still waiting for the upstream ValueObservation
|
||||
// to start. But we must not start another one.
|
||||
if currentSubscription != nil {
|
||||
return (ValueObservationSubscription?.none, self.lastResult)
|
||||
// Notify the last result as the initial event, if any.
|
||||
if let lastResult {
|
||||
client.receive(lastResult)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
let newSubscription = ValueObservationSubscription()
|
||||
currentSubscription = newSubscription
|
||||
return (newSubscription, nil)
|
||||
return newSubscription
|
||||
}
|
||||
|
||||
// Side effect
|
||||
@@ -335,7 +424,9 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
// The upstream observation may have been stopped, and maybe
|
||||
// replaced, while it was starting (for example, if the initial
|
||||
// fetch fails). In this case, discard its cancellable.
|
||||
let discardedCancellable: AnyDatabaseCancellable? = lock.withLock {
|
||||
let discardedCancellable: AnyDatabaseCancellable? = condition.withLock {
|
||||
// Wake up clients that wait for the initial result.
|
||||
defer { condition.broadcast() }
|
||||
guard currentSubscription === newSubscription else {
|
||||
return cancellable
|
||||
}
|
||||
@@ -343,15 +434,10 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
return nil
|
||||
}
|
||||
discardedCancellable?.cancel()
|
||||
} else if let lastResult {
|
||||
// Notify last result as an initial value. A fresher result may
|
||||
// have been scheduled before, and already delivered to the
|
||||
// client: in this case, the last result is not notified.
|
||||
scheduler.scheduleInitial {
|
||||
client.notifyInitial(lastResult)
|
||||
}
|
||||
}
|
||||
|
||||
client.finishStart()
|
||||
|
||||
return AnyDatabaseCancellable {
|
||||
// Retain shared observation (self) until client cancels
|
||||
self.handleCancel(client)
|
||||
@@ -376,15 +462,22 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
/// print("fresh players: \(players)")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The publisher notifies values on the main dispatch queue. The first
|
||||
/// value is notified immediately, on subscription, if the shared
|
||||
/// observation was created with the
|
||||
/// ``IsolatedValueObservationScheduling/immediate`` scheduling.
|
||||
public func publisher() -> DatabasePublishers.Value<Element> {
|
||||
DatabasePublishers.Value { onError, onChange in
|
||||
self.start(onError: onError, onChange: onChange)
|
||||
let scheduler = MainQueueValueObservationScheduler(
|
||||
immediate: scheduling.immediateInitialValue)
|
||||
return DatabasePublishers.Value { onError, onChange in
|
||||
self.start(scheduler: scheduler, onError: onError, onChange: onChange)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func handleError(_ error: Error, from source: ValueObservationSubscription) {
|
||||
let (notifiedClients, stoppedCancellable) = lock.withLock {
|
||||
let (notifiedClients, stoppedCancellable) = condition.withLock {
|
||||
guard source === currentSubscription else {
|
||||
return ([Client](), AnyDatabaseCancellable?.none)
|
||||
}
|
||||
@@ -405,12 +498,12 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
// Side effects
|
||||
stoppedCancellable?.cancel()
|
||||
for client in notifiedClients {
|
||||
client.notifyError(error)
|
||||
client.receive(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
private func handleChange(_ value: Element, from source: ValueObservationSubscription) {
|
||||
let notifiedClients = lock.withLock {
|
||||
let notifiedClients = condition.withLock {
|
||||
guard source === currentSubscription else {
|
||||
return [Client]()
|
||||
}
|
||||
@@ -422,7 +515,7 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
|
||||
// Side effect
|
||||
for client in notifiedClients {
|
||||
client.notifyChange(value)
|
||||
client.receive(.success(value))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -431,7 +524,7 @@ public final class SharedValueObservation<Element: Sendable>: @unchecked Sendabl
|
||||
// is currently in progress.
|
||||
client.cancel()
|
||||
|
||||
let stoppedCancellable = lock.withLock {
|
||||
let stoppedCancellable = condition.withLock {
|
||||
// State change
|
||||
clients.removeFirst(where: { $0 === client })
|
||||
if clients.isEmpty && extent == .whileObserved {
|
||||
@@ -475,7 +568,12 @@ extension SharedValueObservation {
|
||||
-> AsyncValueObservation<Element>
|
||||
{
|
||||
AsyncValueObservation(bufferingPolicy: bufferingPolicy) { onError, onChange in
|
||||
self.start(onError: onError, onChange: onChange)
|
||||
// The callbacks only feed an AsyncThrowingStream: perform
|
||||
// them directly, without any extra thread hop.
|
||||
self.start(
|
||||
scheduler: DirectValueObservationScheduler(),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,36 +90,12 @@ extension ValueObservation: Refinable {
|
||||
|
||||
// MARK: - Starting Observation
|
||||
|
||||
/// Starts observing the database.
|
||||
/// Starts observing the database, and notifies fresh values
|
||||
/// according to the scheduler.
|
||||
///
|
||||
/// The observation lasts until the returned cancellable is cancelled
|
||||
/// or deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .async(onQueue: .main))
|
||||
/// { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A ValueObservationScheduler.
|
||||
/// - parameter onError: The closure to execute when the
|
||||
/// observation fails.
|
||||
/// - parameter onChange: The closure to execute on receipt of a
|
||||
/// fresh value.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
@preconcurrency public func start(
|
||||
func start(
|
||||
in reader: any DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
@@ -138,7 +114,7 @@ extension ValueObservation: Refinable {
|
||||
}
|
||||
|
||||
/// Starts observing the database and notifies fresh values on the
|
||||
/// main actor.
|
||||
/// actor that starts the observation.
|
||||
///
|
||||
/// The observation lasts until the returned cancellable is cancelled
|
||||
/// or deallocated.
|
||||
@@ -146,23 +122,37 @@ extension ValueObservation: Refinable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// @MainActor final class PlayerModel {
|
||||
/// var players: [Player] = []
|
||||
/// private var cancellable: AnyDatabaseCancellable?
|
||||
///
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players: \(players)")
|
||||
/// func observePlayers(in reader: any DatabaseReader) {
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// cancellable = observation.start(in: reader) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { [unowned self] players in
|
||||
/// self.players = players
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// By default, fresh values are dispatched asynchronously on the
|
||||
/// main actor. Pass `.immediate` if the first value should be notified
|
||||
/// immediately when the observation starts:
|
||||
/// The `onError` and `onChange` closures are called in order, on the
|
||||
/// actor that starts the observation, so they can access the state of
|
||||
/// this actor. They do not need to be `Sendable`.
|
||||
///
|
||||
/// By default, fresh values are notified asynchronously. Pass
|
||||
/// `.immediate` if the first value should be notified immediately,
|
||||
/// before this method returns:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .immediate)
|
||||
/// { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players: \(players)")
|
||||
@@ -170,37 +160,45 @@ extension ValueObservation: Refinable {
|
||||
/// // <- here "Fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// This method must be called from an actor. Synchronous nonisolated
|
||||
/// code that runs on the main thread can call it from
|
||||
/// `MainActor.assumeIsolated`. Other nonisolated code can iterate the
|
||||
/// asynchronous sequence returned by
|
||||
/// ``values(in:bufferingPolicy:)``.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A ValueObservationMainActorScheduler.
|
||||
/// By default, fresh values are dispatched asynchronously on the
|
||||
/// main actor.
|
||||
/// - parameter scheduling: Determines when fresh values are notified.
|
||||
/// By default, they are notified asynchronously.
|
||||
/// - parameter isolation: The actor on which `onError` and `onChange`
|
||||
/// are called. By default, it is the caller's actor.
|
||||
/// - parameter onError: The closure to execute when the
|
||||
/// observation fails.
|
||||
/// - parameter onChange: The closure to execute on receipt of a
|
||||
/// fresh value.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
@preconcurrency @MainActor public func start(
|
||||
public func start(
|
||||
in reader: any DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationMainActorScheduler = .mainActor,
|
||||
onError: @escaping @MainActor (Error) -> Void,
|
||||
onChange: @escaping @MainActor (Reducer.Value) -> Void)
|
||||
scheduling: IsolatedValueObservationScheduling = .async,
|
||||
isolation: isolated any Actor = #isolation,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
let regularScheduler: some ValueObservationScheduler = scheduler
|
||||
let scheduler = ActorValueObservationScheduler(
|
||||
scheduling: scheduling,
|
||||
isolation: isolation)
|
||||
|
||||
// The callbacks are only called from the actor: either
|
||||
// synchronously, from this method (immediate scheduling), or
|
||||
// from the actions of the scheduler.
|
||||
nonisolated(unsafe) let onError = onError
|
||||
nonisolated(unsafe) let onChange = onChange
|
||||
return start(
|
||||
in: reader,
|
||||
scheduling: regularScheduler,
|
||||
onError: { error in
|
||||
MainActor.assumeIsolated {
|
||||
onError(error)
|
||||
}
|
||||
},
|
||||
onChange: { value in
|
||||
MainActor.assumeIsolated {
|
||||
onChange(value)
|
||||
}
|
||||
})
|
||||
scheduling: scheduler,
|
||||
onError: { error in onError(error) },
|
||||
onChange: { value in onChange(value) })
|
||||
}
|
||||
|
||||
// MARK: - Debugging
|
||||
@@ -343,21 +341,35 @@ extension ValueObservation {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A ValueObservationScheduler. By default,
|
||||
/// fresh values are dispatched on the cooperative thread pool.
|
||||
/// - parameter bufferingPolicy: see the documentation
|
||||
/// of `AsyncThrowingStream`.
|
||||
public func values(
|
||||
in reader: any DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler = .task,
|
||||
bufferingPolicy: AsyncValueObservation<Reducer.Value>.BufferingPolicy = .unbounded)
|
||||
-> AsyncValueObservation<Reducer.Value>
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
AsyncValueObservation(bufferingPolicy: bufferingPolicy) { onError, onChange in
|
||||
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
|
||||
// The callbacks only feed an AsyncThrowingStream: perform
|
||||
// them directly, without any extra thread hop.
|
||||
self.start(
|
||||
in: reader,
|
||||
scheduling: DirectValueObservationScheduler(),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable, message: "Remove the scheduling argument.")
|
||||
public func values(
|
||||
in reader: any DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
bufferingPolicy: AsyncValueObservation<Reducer.Value>.BufferingPolicy = .unbounded)
|
||||
-> AsyncValueObservation<Reducer.Value>
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
fatalError("unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
/// An asynchronous sequence of values observed by a ``ValueObservation``.
|
||||
@@ -472,7 +484,7 @@ extension ValueObservation {
|
||||
/// main dispatch queue. You can change this behavior by providing a
|
||||
/// scheduler.
|
||||
///
|
||||
/// For example, the ``ValueObservationMainActorScheduler/immediate``
|
||||
/// For example, the ``ValueObservationScheduler/immediate``
|
||||
/// scheduler notifies all values on the main dispatch queue, and
|
||||
/// notifies the first one immediately when the observation starts. The
|
||||
/// `immediate` scheduling requires that the observation starts from the
|
||||
|
||||
@@ -3,6 +3,12 @@ import Foundation
|
||||
|
||||
/// A type that determines when `ValueObservation` notifies its fresh values.
|
||||
///
|
||||
/// Schedulers are used by
|
||||
/// ``ValueObservation/publisher(in:scheduling:)``. The
|
||||
/// ``ValueObservation/start(in:scheduling:isolation:onError:onChange:)``
|
||||
/// and ``ValueObservation/shared(in:scheduling:extent:)`` methods accept
|
||||
/// an ``IsolatedValueObservationScheduling`` instead.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Built-In Schedulers
|
||||
@@ -13,11 +19,11 @@ import Foundation
|
||||
/// - ``task``
|
||||
/// - ``task(priority:)``
|
||||
/// - ``AsyncValueObservationScheduler``
|
||||
/// - ``ImmediateValueObservationScheduler``
|
||||
/// - ``TaskValueObservationScheduler``
|
||||
public protocol ValueObservationScheduler: Sendable {
|
||||
/// Returns whether the initial value should be immediately notified.
|
||||
///
|
||||
/// If the result is true, then this method was called on the main thread.
|
||||
/// Returns whether the initial value should be immediately notified,
|
||||
/// synchronously, when the observation starts.
|
||||
func immediateInitialValue() -> Bool
|
||||
|
||||
func schedule(_ action: @escaping @Sendable () -> Void)
|
||||
@@ -33,26 +39,148 @@ extension ValueObservationScheduler {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ValueObservationMainActorScheduler
|
||||
// MARK: - IsolatedValueObservationScheduling
|
||||
|
||||
/// A type that determines when `ValueObservation` notifies its fresh
|
||||
/// values, on the main actor.
|
||||
/// A value that determines when a `ValueObservation` notifies its fresh
|
||||
/// values, on the actor that starts the observation.
|
||||
///
|
||||
/// See ``ValueObservation/start(in:scheduling:isolation:onError:onChange:)``
|
||||
/// and ``ValueObservation/shared(in:scheduling:extent:)``.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Built-In Schedulers
|
||||
/// ### Built-In Scheduling
|
||||
///
|
||||
/// - ``async``
|
||||
/// - ``immediate``
|
||||
/// - ``ValueObservationScheduler/mainActor``
|
||||
/// - ``ImmediateValueObservationScheduler``
|
||||
/// - ``DelayedMainActorValueObservationScheduler``
|
||||
public protocol ValueObservationMainActorScheduler: ValueObservationScheduler {
|
||||
func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void)
|
||||
public struct IsolatedValueObservationScheduling: Sendable {
|
||||
var immediateInitialValue: Bool
|
||||
|
||||
/// All values are asynchronously notified on the actor that starts
|
||||
/// the observation.
|
||||
public static var async: Self {
|
||||
IsolatedValueObservationScheduling(immediateInitialValue: false)
|
||||
}
|
||||
|
||||
/// All values are notified on the actor that starts the observation.
|
||||
/// The first value is immediately notified when the observation starts.
|
||||
///
|
||||
/// The actor is blocked until the first value is fetched: use this
|
||||
/// scheduling for fast database requests only.
|
||||
public static var immediate: Self {
|
||||
IsolatedValueObservationScheduling(immediateInitialValue: true)
|
||||
}
|
||||
|
||||
/// All values are asynchronously notified on the actor that starts
|
||||
/// the observation.
|
||||
@available(*, deprecated, renamed: "async")
|
||||
public static var mainActor: Self { .async }
|
||||
}
|
||||
|
||||
extension ValueObservationMainActorScheduler {
|
||||
public func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
scheduleOnMainActor(action)
|
||||
// MARK: - ActorValueObservationScheduler
|
||||
|
||||
/// A scheduler that notifies values on an actor.
|
||||
///
|
||||
/// It must be created from the actor, because the initial value is
|
||||
/// notified synchronously, from the caller of `ValueObservation.start`,
|
||||
/// when `immediateInitialValue` is true.
|
||||
final class ActorValueObservationScheduler: ValueObservationScheduler {
|
||||
typealias Action = @Sendable () -> Void
|
||||
|
||||
private enum Target {
|
||||
case mainQueue
|
||||
case task(AsyncStream<Action>.Continuation)
|
||||
}
|
||||
|
||||
private let immediate: Bool
|
||||
private let target: Target
|
||||
|
||||
init(
|
||||
scheduling: IsolatedValueObservationScheduling,
|
||||
isolation: isolated any Actor)
|
||||
{
|
||||
self.immediate = scheduling.immediateInitialValue
|
||||
if isolation === MainActor.shared {
|
||||
// Fast path
|
||||
self.target = .mainQueue
|
||||
} else {
|
||||
// A single task executes all actions, in order, on the actor.
|
||||
let (stream, continuation) = AsyncStream.makeStream(of: Action.self)
|
||||
Task {
|
||||
await Self.perform(stream, isolation: isolation)
|
||||
}
|
||||
self.target = .task(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
if case let .task(continuation) = target {
|
||||
continuation.finish()
|
||||
}
|
||||
}
|
||||
|
||||
private static func perform(
|
||||
_ actions: AsyncStream<Action>,
|
||||
isolation: isolated any Actor
|
||||
) async {
|
||||
for await action in actions {
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
func immediateInitialValue() -> Bool {
|
||||
immediate
|
||||
}
|
||||
|
||||
func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
switch target {
|
||||
case .mainQueue:
|
||||
DispatchQueue.main.async(execute: action)
|
||||
case let .task(continuation):
|
||||
continuation.yield(action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DirectValueObservationScheduler
|
||||
|
||||
/// A scheduler that performs actions on the thread that schedules them.
|
||||
///
|
||||
/// Actions are performed in the order of the `schedule(_:)` calls,
|
||||
/// because observers schedule notifications from a serial
|
||||
/// dispatch queue.
|
||||
///
|
||||
/// This scheduler is only suitable for actions that are thread-safe and
|
||||
/// do not block, such as feeding an `AsyncThrowingStream`, or dispatching
|
||||
/// values to the clients of a `SharedValueObservation`. It avoids a
|
||||
/// thread hop between the observer and the consumer of values.
|
||||
struct DirectValueObservationScheduler: ValueObservationScheduler {
|
||||
/// Whether the initial value is fetched and notified synchronously,
|
||||
/// on the thread that starts the observation.
|
||||
var immediate = false
|
||||
|
||||
func immediateInitialValue() -> Bool { immediate }
|
||||
|
||||
func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - MainQueueValueObservationScheduler
|
||||
|
||||
/// A scheduler that notifies values on the main dispatch queue.
|
||||
///
|
||||
/// Unlike `ImmediateValueObservationScheduler`, it can notify the initial
|
||||
/// value synchronously from any thread.
|
||||
struct MainQueueValueObservationScheduler: ValueObservationScheduler {
|
||||
/// Whether the initial value is notified synchronously, on the thread
|
||||
/// that starts the observation.
|
||||
var immediate: Bool
|
||||
|
||||
func immediateInitialValue() -> Bool { immediate }
|
||||
|
||||
func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
DispatchQueue.main.async(execute: action)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,13 +212,13 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .async(onQueue: .main),
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (players: [Player]) in
|
||||
/// let cancellable = observation
|
||||
/// .publisher(in: dbQueue, scheduling: .async(onQueue: .main))
|
||||
/// .sink { completion in
|
||||
/// // handle completion
|
||||
/// } receiveValue: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - warning: Make sure you provide a serial queue, because a
|
||||
@@ -99,6 +227,14 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
public static func async(onQueue queue: DispatchQueue) -> AsyncValueObservationScheduler {
|
||||
AsyncValueObservationScheduler(queue: queue)
|
||||
}
|
||||
|
||||
/// A scheduler that asynchronously notifies fresh values on the
|
||||
/// main dispatch queue.
|
||||
///
|
||||
/// It is equivalent to `.async(onQueue: .main)`.
|
||||
public static var mainActor: AsyncValueObservationScheduler {
|
||||
AsyncValueObservationScheduler(queue: .main)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ImmediateValueObservationScheduler
|
||||
@@ -106,7 +242,7 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
/// A scheduler that notifies all values on the main actor. The
|
||||
/// first value is immediately notified when the `ValueObservation`
|
||||
/// is started.
|
||||
public struct ImmediateValueObservationScheduler: ValueObservationMainActorScheduler {
|
||||
public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
|
||||
public init() { }
|
||||
|
||||
public func immediateInitialValue() -> Bool {
|
||||
@@ -116,7 +252,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationMainActorSched
|
||||
return true
|
||||
}
|
||||
|
||||
public func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) {
|
||||
public func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
DispatchQueue.main.async(execute: action)
|
||||
}
|
||||
}
|
||||
@@ -133,47 +269,18 @@ extension ValueObservationScheduler where Self == ImmediateValueObservationSched
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .immediate,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (players: [Player]) in
|
||||
/// let cancellable = observation
|
||||
/// .publisher(in: dbQueue, scheduling: .immediate)
|
||||
/// .sink { completion in
|
||||
/// // handle completion
|
||||
/// } receiveValue: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// }
|
||||
/// // <- here "fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// - important: this scheduler requires that the observation is started
|
||||
/// from the main actor. A fatal error is raised otherwise.
|
||||
public static var immediate: ImmediateValueObservationScheduler {
|
||||
ImmediateValueObservationScheduler()
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueObservationMainActorScheduler where Self == ImmediateValueObservationScheduler {
|
||||
/// A scheduler that notifies all values on the main actor. The
|
||||
/// first value is immediately notified when the `ValueObservation`
|
||||
/// is started.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .immediate,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// // <- here "fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// - important: this scheduler requires that the observation is started
|
||||
/// from the main actor. A fatal error is raised otherwise.
|
||||
/// from the main thread. A fatal error is raised otherwise.
|
||||
public static var immediate: ImmediateValueObservationScheduler {
|
||||
ImmediateValueObservationScheduler()
|
||||
}
|
||||
@@ -223,23 +330,3 @@ extension ValueObservationScheduler where Self == TaskValueObservationScheduler
|
||||
TaskValueObservationScheduler(priority: priority)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DelayedMainActorValueObservationScheduler
|
||||
|
||||
/// A scheduler that notifies all values on the cooperative thread pool.
|
||||
public final class DelayedMainActorValueObservationScheduler: ValueObservationMainActorScheduler {
|
||||
public func immediateInitialValue() -> Bool {
|
||||
false
|
||||
}
|
||||
|
||||
public func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) {
|
||||
DispatchQueue.main.async(execute: action)
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueObservationScheduler where Self == DelayedMainActorValueObservationScheduler {
|
||||
/// A scheduler that notifies all values on the main actor.
|
||||
public static var mainActor: DelayedMainActorValueObservationScheduler {
|
||||
DelayedMainActorValueObservationScheduler()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
private final class ValueRecorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
private struct TestError: Error { }
|
||||
|
||||
private let insertCount = 50
|
||||
|
||||
private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
private func createTable(_ writer: any DatabaseWriter) throws {
|
||||
try writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
private func assertIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
private func assertOrderedValues(_ values: [Int], file: StaticString = #filePath, line: UInt = #line) {
|
||||
XCTAssertEqual(values.last, insertCount, file: file, line: line)
|
||||
XCTAssertEqual(values, values.sorted(), "Values are not notified in order", file: file, line: line)
|
||||
}
|
||||
|
||||
private actor ObservingActor {
|
||||
let recorder = ValueRecorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
var errors: [any Error] { recorder.errors }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
assertIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
|
||||
let cancellable = observation.start { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Returns the errors notified when the observation starts.
|
||||
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
|
||||
let cancellable = observation.start { error in
|
||||
assertIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
XCTFail("Unexpected value")
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.errors
|
||||
}
|
||||
}
|
||||
|
||||
class SharedValueObservationIsolationTests: GRDBTestCase {
|
||||
private func writers() throws -> [any DatabaseWriter] {
|
||||
let writers: [any DatabaseWriter] = try [makeDatabaseQueue(), makeDatabasePool()]
|
||||
for writer in writers {
|
||||
try createTable(writer)
|
||||
}
|
||||
return writers
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor
|
||||
func testMainActorAsyncScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let observation = countObservation.shared(in: writer)
|
||||
let recorder = ValueRecorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
XCTAssertTrue(recorder.values.isEmpty)
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable?.cancel()
|
||||
assertOrderedValues(recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testMainActorImmediateScheduling() throws {
|
||||
for writer in try writers() {
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
|
||||
// The first client starts the shared observation.
|
||||
let recorder1 = ValueRecorder()
|
||||
let cancellable1 = observation.start { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder1.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
XCTAssertEqual(recorder1.values, [0])
|
||||
|
||||
// The second client shares the observation.
|
||||
let recorder2 = ValueRecorder()
|
||||
let cancellable2 = observation.start { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder2.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
XCTAssertEqual(recorder2.values, [0])
|
||||
|
||||
cancellable1.cancel()
|
||||
cancellable2.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testMainActorImmediateError() throws {
|
||||
for writer in try writers() {
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = ValueRecorder()
|
||||
let cancellable = observation.start { error in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
XCTFail("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
XCTAssertEqual(recorder.errors.count, 1)
|
||||
XCTAssertTrue(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronous nonisolated code that runs on the main thread starts
|
||||
// observations from the main actor.
|
||||
func testNonisolatedCodeOnMainThread() throws {
|
||||
XCTAssertTrue(Thread.isMainThread)
|
||||
for writer in try writers() {
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let values = MainActor.assumeIsolated {
|
||||
let recorder = ValueRecorder()
|
||||
let cancellable = observation.start { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
XCTAssertEqual(values, [0])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
func testActorAsyncScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let observation = countObservation.shared(in: writer)
|
||||
let model = ObservingActor()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
let values = await model.values
|
||||
assertOrderedValues(values)
|
||||
}
|
||||
}
|
||||
|
||||
func testActorImmediateScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = ObservingActor()
|
||||
let values = await model.valuesNotifiedOnStart(observation)
|
||||
XCTAssertEqual(values, [0])
|
||||
}
|
||||
}
|
||||
|
||||
func testActorImmediateError() async throws {
|
||||
for writer in try writers() {
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = ObservingActor()
|
||||
let errors = await model.errorsNotifiedOnStart(observation)
|
||||
XCTAssertEqual(errors.count, 1)
|
||||
XCTAssertTrue(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Distinct Actors
|
||||
|
||||
// Clients on distinct actors share a single observation. Each one is
|
||||
// notified on its own actor.
|
||||
func testDistinctActors() async throws {
|
||||
for scheduling in [IsolatedValueObservationScheduling.async, .immediate] {
|
||||
for writer in try writers() {
|
||||
try await writer.write { try $0.execute(sql: "DELETE FROM t") }
|
||||
let observation = countObservation.shared(in: writer, scheduling: scheduling)
|
||||
let model1 = ObservingActor()
|
||||
let model2 = ObservingActor()
|
||||
async let observing1: Void = model1.observe(observation)
|
||||
async let observing2: Void = model2.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
_ = try await (observing1, observing2)
|
||||
let values1 = await model1.values
|
||||
let values2 = await model2.values
|
||||
assertOrderedValues(values1)
|
||||
assertOrderedValues(values2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clients that start an immediate shared observation concurrently,
|
||||
// from distinct actors, are all notified of the initial value.
|
||||
func testConcurrentImmediateScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let observation = countObservation.shared(
|
||||
in: writer,
|
||||
scheduling: .immediate,
|
||||
extent: .observationLifetime)
|
||||
let valuesList = await withTaskGroup(of: [Int].self) { group in
|
||||
for _ in 0..<20 {
|
||||
group.addTask {
|
||||
await ObservingActor().valuesNotifiedOnStart(observation)
|
||||
}
|
||||
}
|
||||
var valuesList: [[Int]] = []
|
||||
for await values in group {
|
||||
valuesList.append(values)
|
||||
}
|
||||
return valuesList
|
||||
}
|
||||
XCTAssertEqual(valuesList.count, 20)
|
||||
for values in valuesList {
|
||||
XCTAssertEqual(values, [0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDB // @testable ONLY for start(scheduler:onError:onChange:)
|
||||
|
||||
class SharedValueObservationTests: GRDBTestCase {
|
||||
@MainActor class SharedValueObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testInitFromAnyDatabaseReader(reader: any DatabaseReader) {
|
||||
@@ -262,7 +262,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
@@ -356,7 +356,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
@@ -437,7 +437,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
@@ -531,7 +531,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .task,
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
@@ -543,6 +542,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
scheduler: .task,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values1Mutex.withLock { $0.append(value) }
|
||||
@@ -562,6 +562,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
scheduler: .task,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values2Mutex.withLock { $0.append(value) }
|
||||
@@ -584,6 +585,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
scheduler: .task,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values3Mutex.withLock { $0.append(value) }
|
||||
@@ -611,41 +613,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
func test_task_publisher() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let publisher = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(in: dbQueue, scheduling: .task)
|
||||
.publisher()
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssert(recorder.availableElements.get().isEmpty)
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 0)
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
}
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
// Don't assert that no element is available yet: the shared
|
||||
// observation notifies its last value from the `.task`
|
||||
// scheduler, which can deliver it before the assertion runs.
|
||||
// try XCTAssert(recorder.availableElements.get().isEmpty) <- WRONG
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func test_task_whileObserved() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -660,7 +627,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .task,
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
@@ -672,6 +638,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
scheduler: .task,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values1Mutex.withLock { $0.append(value) }
|
||||
@@ -691,6 +658,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
scheduler: .task,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values2Mutex.withLock { $0.append(value) }
|
||||
@@ -713,6 +681,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
scheduler: .task,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values3Mutex.withLock { $0.append(value) }
|
||||
@@ -867,24 +836,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testAsyncAwait_task() async throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try await dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let values = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(in: dbQueue, scheduling: .task)
|
||||
.values()
|
||||
|
||||
for try await value in values {
|
||||
XCTAssertEqual(value, 0)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test: a client can be cancelled from another thread while
|
||||
// the shared observation is notifying a fresh value.
|
||||
@@ -907,13 +858,13 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
|
||||
extent: .observationLifetime)
|
||||
|
||||
let cancellableMutex: Mutex<AnyDatabaseCancellable?> = Mutex(nil)
|
||||
let cancellationDidCompleteMutex: Mutex<Bool?> = Mutex(nil)
|
||||
let exp = expectation(description: "")
|
||||
let cancellable = sharedObservation.start(
|
||||
scheduler: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
guard value == 1 else { return }
|
||||
@@ -950,7 +901,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
|
||||
extent: .observationLifetime)
|
||||
|
||||
let cancellableMutex: Mutex<AnyDatabaseCancellable?> = Mutex(nil)
|
||||
@@ -958,6 +908,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
let initialValueExp = expectation(description: "initial value")
|
||||
let errorExp = expectation(description: "error")
|
||||
let cancellable = sharedObservation.start(
|
||||
scheduler: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
|
||||
onError: { _ in
|
||||
cancellationDidCompleteMutex.store(
|
||||
Self.cancelFromOtherThreadAndWait(cancellableMutex.load()))
|
||||
@@ -990,7 +941,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: queue),
|
||||
extent: .observationLifetime)
|
||||
|
||||
let initialValuesExp = expectation(description: "initial values")
|
||||
@@ -1001,6 +951,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
// Client 1 blocks the notification of the second value until
|
||||
// client 2 is cancelled.
|
||||
let cancellable1 = sharedObservation.start(
|
||||
scheduler: .async(onQueue: queue),
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
if value == 0 {
|
||||
@@ -1013,6 +964,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
let values2Mutex: Mutex<[Int]> = Mutex([])
|
||||
let cancellable2 = sharedObservation.start(
|
||||
scheduler: .async(onQueue: queue),
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values2Mutex.withLock { $0.append(value) }
|
||||
@@ -1053,7 +1005,6 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: queue),
|
||||
extent: .observationLifetime)
|
||||
|
||||
let initialValuesExp = expectation(description: "initial values")
|
||||
@@ -1064,6 +1015,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
// Client 1 blocks the notification of the error until
|
||||
// client 2 is cancelled.
|
||||
let cancellable1 = sharedObservation.start(
|
||||
scheduler: .async(onQueue: queue),
|
||||
onError: { _ in
|
||||
notificationDidStartSemaphore.signal()
|
||||
_ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5)
|
||||
@@ -1074,6 +1026,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
let error2Mutex: Mutex<Error?> = Mutex(nil)
|
||||
let cancellable2 = sharedObservation.start(
|
||||
scheduler: .async(onQueue: queue),
|
||||
onError: { error in
|
||||
error2Mutex.store(error)
|
||||
},
|
||||
@@ -1108,11 +1061,11 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: queue),
|
||||
extent: .observationLifetime)
|
||||
|
||||
let initialValueExp = expectation(description: "initial value")
|
||||
let cancellable1 = sharedObservation.start(
|
||||
scheduler: .async(onQueue: queue),
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { _ in initialValueExp.fulfill() })
|
||||
wait(for: [initialValueExp], timeout: 5)
|
||||
@@ -1125,6 +1078,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
let values2Mutex: Mutex<[Int]> = Mutex([])
|
||||
let cancellable2 = sharedObservation.start(
|
||||
scheduler: .async(onQueue: queue),
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
values2Mutex.withLock { $0.append(value) }
|
||||
@@ -1205,12 +1159,12 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: scheduler,
|
||||
extent: .observationLifetime)
|
||||
|
||||
// Client 1 makes 0 the last value.
|
||||
let values1Mutex: Mutex<[Int]> = Mutex([])
|
||||
let cancellable1 = sharedObservation.start(
|
||||
scheduler: scheduler,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in values1Mutex.withLock { $0.append(value) } })
|
||||
XCTAssertTrue(scheduler.waitForScheduledActions(count: 1))
|
||||
@@ -1225,6 +1179,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
// value, after the fresh value 1.
|
||||
let values2Mutex: Mutex<[Int]> = Mutex([])
|
||||
let cancellable2 = sharedObservation.start(
|
||||
scheduler: scheduler,
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in values2Mutex.withLock { $0.append(value) } })
|
||||
XCTAssertTrue(scheduler.waitForScheduledActions(count: 2))
|
||||
@@ -1241,7 +1196,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
/// Waiting for the other thread models a notification callback that
|
||||
/// waits for a resource held by a thread that is cancelling the client.
|
||||
/// A timeout reveals a deadlock, without hanging the test suite.
|
||||
private static func cancelFromOtherThreadAndWait(_ cancellable: AnyDatabaseCancellable?) -> Bool {
|
||||
nonisolated private static func cancelFromOtherThreadAndWait(_ cancellable: AnyDatabaseCancellable?) -> Bool {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
DispatchQueue.global().async {
|
||||
cancellable?.cancel()
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
private final class ValueRecorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
private struct TestError: Error { }
|
||||
|
||||
private let insertCount = 50
|
||||
|
||||
private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
private func createTable(_ writer: any DatabaseWriter) throws {
|
||||
try writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
private func assertIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
private func assertOrderedValues(_ values: [Int], file: StaticString = #filePath, line: UInt = #line) {
|
||||
XCTAssertEqual(values.last, insertCount, file: file, line: line)
|
||||
XCTAssertEqual(values, values.sorted(), "Values are not notified in order", file: file, line: line)
|
||||
}
|
||||
|
||||
private actor ObservingActor {
|
||||
let recorder = ValueRecorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
var errors: [any Error] { recorder.errors }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
assertIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Returns the errors notified when the observation starts.
|
||||
func errorsNotifiedOnStart(_ writer: any DatabaseWriter) -> [any Error] {
|
||||
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
assertIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
XCTFail("Unexpected value")
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.errors
|
||||
}
|
||||
}
|
||||
|
||||
class ValueObservationIsolationTests: GRDBTestCase {
|
||||
private func writers() throws -> [any DatabaseWriter] {
|
||||
let writers: [any DatabaseWriter] = try [makeDatabaseQueue(), makeDatabasePool()]
|
||||
for writer in writers {
|
||||
try createTable(writer)
|
||||
}
|
||||
return writers
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor
|
||||
func testMainActorAsyncScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let recorder = ValueRecorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
XCTAssertTrue(recorder.values.isEmpty)
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable?.cancel()
|
||||
assertOrderedValues(recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testMainActorImmediateScheduling() throws {
|
||||
for writer in try writers() {
|
||||
let recorder = ValueRecorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
XCTAssertEqual(recorder.values, [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testMainActorImmediateError() throws {
|
||||
for writer in try writers() {
|
||||
let recorder = ValueRecorder()
|
||||
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
XCTFail("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
XCTAssertEqual(recorder.errors.count, 1)
|
||||
XCTAssertTrue(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronous nonisolated code that runs on the main thread starts
|
||||
// observations from the main actor.
|
||||
func testNonisolatedCodeOnMainThread() throws {
|
||||
XCTAssertTrue(Thread.isMainThread)
|
||||
for writer in try writers() {
|
||||
let values = MainActor.assumeIsolated {
|
||||
let recorder = ValueRecorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
assertIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
XCTAssertEqual(values, [0])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
func testActorAsyncScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let model = ObservingActor()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
let values = await model.values
|
||||
assertOrderedValues(values)
|
||||
}
|
||||
}
|
||||
|
||||
func testActorImmediateScheduling() async throws {
|
||||
for writer in try writers() {
|
||||
let model = ObservingActor()
|
||||
let values = await model.valuesNotifiedOnStart(writer)
|
||||
XCTAssertEqual(values, [0])
|
||||
}
|
||||
}
|
||||
|
||||
func testActorImmediateSchedulingThenChanges() async throws {
|
||||
for writer in try writers() {
|
||||
let model = ObservingActor()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
let values = await model.values
|
||||
XCTAssertEqual(values.first, 0)
|
||||
assertOrderedValues(values)
|
||||
}
|
||||
}
|
||||
|
||||
func testActorImmediateError() async throws {
|
||||
for writer in try writers() {
|
||||
let model = ObservingActor()
|
||||
let errors = await model.errorsNotifiedOnStart(writer)
|
||||
XCTAssertEqual(errors.count, 1)
|
||||
XCTAssertTrue(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import XCTest
|
||||
import Dispatch
|
||||
@testable import GRDB
|
||||
import GRDB
|
||||
|
||||
class ValueObservationPrintTests: GRDBTestCase {
|
||||
@MainActor class ValueObservationPrintTests: GRDBTestCase {
|
||||
class TestStream: TextOutputStream {
|
||||
private var stringsMutex: Mutex<[String]> = Mutex([])
|
||||
var strings: [String] { stringsMutex.load() }
|
||||
@@ -38,7 +38,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbReader,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
@@ -113,7 +113,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbReader,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in expectation.fulfill() },
|
||||
onChange: { _ in })
|
||||
withExtendedLifetime(cancellable) {
|
||||
@@ -192,7 +192,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
expectation.expectedFulfillmentCount = 2
|
||||
let cancellable = observation.start(
|
||||
in: dbWriter,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in
|
||||
try! dbWriter.write { db in
|
||||
@@ -270,7 +270,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbWriter,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in expectation.fulfill() },
|
||||
onChange: { _ in })
|
||||
withExtendedLifetime(cancellable) {
|
||||
@@ -329,7 +329,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbWriter,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in expectation.fulfill() },
|
||||
onChange: { _ in
|
||||
try! dbWriter.write { db in
|
||||
@@ -436,7 +436,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
expectation.expectedFulfillmentCount = 2
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
@@ -534,7 +534,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
expectation.expectedFulfillmentCount = 3
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in
|
||||
try! dbQueue.write { db in
|
||||
@@ -581,7 +581,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
@@ -617,7 +617,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
@@ -646,7 +646,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
expectation.expectedFulfillmentCount = 2
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in
|
||||
try! dbQueue.write { db in
|
||||
@@ -668,7 +668,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in expectation.fulfill() },
|
||||
onChange: { _ in
|
||||
try! dbQueue.write { db in
|
||||
@@ -692,7 +692,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
let expectation = self.expectation(description: "")
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { _ in },
|
||||
onChange: { _ in
|
||||
expectation.fulfill()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import XCTest
|
||||
@testable import GRDB
|
||||
@testable import GRDB // @testable ONLY for recordingSelection
|
||||
|
||||
class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
@MainActor class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
func testRecordingSelectedRegion() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -200,7 +200,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
|
||||
let observer = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
resultsMutex.withLock { $0.append(count) }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import XCTest
|
||||
import Dispatch
|
||||
@testable import GRDB
|
||||
@testable import GRDB // @testable ONLY for ValueObservation(trackingMode:makeReducer:)
|
||||
|
||||
class ValueObservationTests: GRDBTestCase {
|
||||
@MainActor class ValueObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testStartFromAnyDatabaseReader(reader: any DatabaseReader) {
|
||||
@@ -377,7 +377,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
let observedCountsMutex: Mutex<[Int]> = Mutex([])
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCountsMutex.withLock { $0.append(count) }
|
||||
@@ -475,7 +475,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
let observedCountsMutex: Mutex<[Int]> = Mutex([])
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .async(onQueue: .main),
|
||||
scheduling: .async,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCountsMutex.withLock { $0.append(count) }
|
||||
@@ -1055,7 +1055,10 @@ class ValueObservationTests: GRDBTestCase {
|
||||
let observationCount = 100
|
||||
dbConfiguration.maximumReaderCount = 5
|
||||
|
||||
func test(_ writer: some DatabaseWriter, scheduling scheduler: some ValueObservationScheduler) throws {
|
||||
func test(
|
||||
_ writer: some DatabaseWriter,
|
||||
scheduling scheduler: IsolatedValueObservationScheduling
|
||||
) throws {
|
||||
try writer.write {
|
||||
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
@@ -1102,9 +1105,9 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .immediate) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .immediate) }
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async(onQueue: .main)) }
|
||||
try Test(test).run { try (DatabaseQueue(), .async) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async) }
|
||||
}
|
||||
|
||||
// An attempt at finding a regression test for <https://github.com/groue/GRDB.swift/issues/1362>
|
||||
@@ -1113,7 +1116,10 @@ class ValueObservationTests: GRDBTestCase {
|
||||
let observationCount = 100
|
||||
dbConfiguration.maximumReaderCount = 5
|
||||
|
||||
func test(_ writer: some DatabaseWriter, scheduling scheduler: some ValueObservationScheduler) throws {
|
||||
func test(
|
||||
_ writer: some DatabaseWriter,
|
||||
scheduling scheduler: IsolatedValueObservationScheduling
|
||||
) throws {
|
||||
try writer.write {
|
||||
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
@@ -1163,9 +1169,9 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async(onQueue: .main)) }
|
||||
try Test(test).run { try (DatabaseQueue(), .async) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async) }
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .immediate) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .immediate) }
|
||||
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBTestSupport
|
||||
#endif
|
||||
import Testing
|
||||
|
||||
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
//
|
||||
// The callbacks of the tested observations are not Sendable: they mutate
|
||||
// non-Sendable values and actor-isolated state.
|
||||
//
|
||||
// This file is identical in all Swift 6 test targets. Declarations are
|
||||
// explicitly isolated, or explicitly nonisolated, so that they do not
|
||||
// depend on the default isolation of the test target.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
nonisolated private final class Recorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
nonisolated private struct TestError: Error { }
|
||||
|
||||
nonisolated private let insertCount = 50
|
||||
|
||||
/// Creates the observed table.
|
||||
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs `insertCount` distinct insertions.
|
||||
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the number of rows in the `t` table.
|
||||
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
/// An observation that always fails.
|
||||
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
nonisolated private func expectIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects observed values to be ordered, and to end with `insertCount`.
|
||||
nonisolated private func expectOrderedValues(_ values: [Int]) {
|
||||
#expect(values.first != nil)
|
||||
#expect(values.last == insertCount)
|
||||
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor private final class MainActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
nonisolated init() { }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @MainActor struct MainActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling_is_the_default(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer)
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
#expect(recorder.values.isEmpty)
|
||||
}
|
||||
#expect(recorder.values.first == 0)
|
||||
#expect(recorder.values.allSatisfy { $0 == 0 })
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = MainActorModel()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
|
||||
// The first client starts the shared observation.
|
||||
let recorder1 = Recorder()
|
||||
let cancellable1 = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder1.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder1.values == [0])
|
||||
|
||||
// The second client shares the observation.
|
||||
let recorder2 = Recorder()
|
||||
let cancellable2 = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder2.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder2.values == [0])
|
||||
|
||||
cancellable1.cancel()
|
||||
cancellable2.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) throws {
|
||||
try withDatabaseWriter(kind) { writer in
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = Recorder()
|
||||
let cancellable = observation.start { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
private actor Model {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
|
||||
let cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Returns the errors notified when the observation starts.
|
||||
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
|
||||
let cancellable = observation.start { error in
|
||||
expectIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.errors
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = Model()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
await expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = Model()
|
||||
let values = await model.valuesNotifiedOnStart(observation)
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = Model()
|
||||
let errors = await model.errorsNotifiedOnStart(observation)
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
// Clients that start an immediate shared observation concurrently,
|
||||
// from distinct actors, are all notified of the initial value.
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func concurrent_immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(
|
||||
in: writer,
|
||||
scheduling: .immediate,
|
||||
extent: .observationLifetime)
|
||||
let valuesList = await withTaskGroup(of: [Int].self) { group in
|
||||
for _ in 0..<20 {
|
||||
group.addTask {
|
||||
await Model().valuesNotifiedOnStart(observation)
|
||||
}
|
||||
}
|
||||
var valuesList: [[Int]] = []
|
||||
for await values in group {
|
||||
valuesList.append(values)
|
||||
}
|
||||
return valuesList
|
||||
}
|
||||
#expect(valuesList.count == 20)
|
||||
for values in valuesList {
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Global Actor
|
||||
|
||||
@globalActor actor SharedValueObservationTestGlobalActor {
|
||||
static let shared = SharedValueObservationTestGlobalActor()
|
||||
}
|
||||
|
||||
@SharedValueObservationTestGlobalActor private final class GlobalActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
nonisolated init() { }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(SharedValueObservationTestGlobalActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @SharedValueObservationTestGlobalActor struct GlobalActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = GlobalActorModel()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = Recorder()
|
||||
let cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(SharedValueObservationTestGlobalActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Distinct Actors
|
||||
|
||||
// Clients on distinct actors share a single observation. Each one is
|
||||
// notified on its own actor.
|
||||
@Suite nonisolated struct DistinctActorsSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases, [
|
||||
IsolatedValueObservationScheduling.async,
|
||||
IsolatedValueObservationScheduling.immediate,
|
||||
])
|
||||
func clients_on_distinct_actors(
|
||||
kind: WriterKind,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: scheduling)
|
||||
let mainActorModel = MainActorModel()
|
||||
let actorModel = Model()
|
||||
let globalActorModel = GlobalActorModel()
|
||||
async let observing1: Void = mainActorModel.observe(observation)
|
||||
async let observing2: Void = actorModel.observe(observation)
|
||||
async let observing3: Void = globalActorModel.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
_ = try await (observing1, observing2, observing3)
|
||||
await expectOrderedValues(mainActorModel.values)
|
||||
await expectOrderedValues(actorModel.values)
|
||||
await expectOrderedValues(globalActorModel.values)
|
||||
}
|
||||
}
|
||||
}
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBTestSupport
|
||||
#endif
|
||||
import Testing
|
||||
|
||||
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
//
|
||||
// The callbacks of the tested observations are not Sendable: they mutate
|
||||
// non-Sendable values and actor-isolated state.
|
||||
//
|
||||
// This file is identical in all Swift 6 test targets. Declarations are
|
||||
// explicitly isolated, or explicitly nonisolated, so that they do not
|
||||
// depend on the default isolation of the test target.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
nonisolated private final class Recorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
nonisolated private struct TestError: Error { }
|
||||
|
||||
nonisolated private let insertCount = 50
|
||||
|
||||
/// Creates the observed table.
|
||||
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs `insertCount` distinct insertions.
|
||||
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the number of rows in the `t` table.
|
||||
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
/// An observation that always fails.
|
||||
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
nonisolated private func expectIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects observed values to be ordered, and to end with `insertCount`.
|
||||
nonisolated private func expectOrderedValues(_ values: [Int]) {
|
||||
#expect(values.first != nil)
|
||||
#expect(values.last == insertCount)
|
||||
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor private final class MainActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @MainActor struct MainActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling_is_the_default(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
#expect(recorder.values.isEmpty)
|
||||
}
|
||||
#expect(recorder.values.first == 0)
|
||||
#expect(recorder.values.allSatisfy { $0 == 0 })
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = MainActorModel()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = MainActorModel()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
#expect(model.recorder.values.first == 0)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { continuation in
|
||||
cancellable = failingObservation.start(in: writer) { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
continuation.resume()
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no error yet.
|
||||
#expect(recorder.errors.isEmpty)
|
||||
}
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) throws {
|
||||
try withDatabaseWriter(kind) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
private actor Model {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
var errors: [any Error] { recorder.errors }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Observes until an error is notified.
|
||||
func observeError(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async {
|
||||
await withCheckedContinuation { continuation in
|
||||
cancellable = failingObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
expectIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
continuation.resume()
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
await expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
let values = await model.valuesNotifiedOnStart(writer)
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
let values = await model.values
|
||||
#expect(values.first == 0)
|
||||
expectOrderedValues(values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let model = Model()
|
||||
await model.observeError(writer, scheduling: .async)
|
||||
let errors = await model.errors
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let model = Model()
|
||||
await model.observeError(writer, scheduling: .immediate)
|
||||
let errors = await model.errors
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Global Actor
|
||||
|
||||
@globalActor actor ValueObservationTestGlobalActor {
|
||||
static let shared = ValueObservationTestGlobalActor()
|
||||
}
|
||||
|
||||
@ValueObservationTestGlobalActor private final class GlobalActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(ValueObservationTestGlobalActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @ValueObservationTestGlobalActor struct GlobalActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = GlobalActorModel()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(ValueObservationTestGlobalActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBTestSupport
|
||||
#endif
|
||||
import Testing
|
||||
|
||||
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
//
|
||||
// The callbacks of the tested observations are not Sendable: they mutate
|
||||
// non-Sendable values and actor-isolated state.
|
||||
//
|
||||
// This file is identical in all Swift 6 test targets. Declarations are
|
||||
// explicitly isolated, or explicitly nonisolated, so that they do not
|
||||
// depend on the default isolation of the test target.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
nonisolated private final class Recorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
nonisolated private struct TestError: Error { }
|
||||
|
||||
nonisolated private let insertCount = 50
|
||||
|
||||
/// Creates the observed table.
|
||||
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs `insertCount` distinct insertions.
|
||||
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the number of rows in the `t` table.
|
||||
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
/// An observation that always fails.
|
||||
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
nonisolated private func expectIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects observed values to be ordered, and to end with `insertCount`.
|
||||
nonisolated private func expectOrderedValues(_ values: [Int]) {
|
||||
#expect(values.first != nil)
|
||||
#expect(values.last == insertCount)
|
||||
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor private final class MainActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
nonisolated init() { }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @MainActor struct MainActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling_is_the_default(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer)
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
#expect(recorder.values.isEmpty)
|
||||
}
|
||||
#expect(recorder.values.first == 0)
|
||||
#expect(recorder.values.allSatisfy { $0 == 0 })
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = MainActorModel()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
|
||||
// The first client starts the shared observation.
|
||||
let recorder1 = Recorder()
|
||||
let cancellable1 = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder1.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder1.values == [0])
|
||||
|
||||
// The second client shares the observation.
|
||||
let recorder2 = Recorder()
|
||||
let cancellable2 = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder2.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder2.values == [0])
|
||||
|
||||
cancellable1.cancel()
|
||||
cancellable2.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) throws {
|
||||
try withDatabaseWriter(kind) { writer in
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = Recorder()
|
||||
let cancellable = observation.start { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
private actor Model {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
|
||||
let cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Returns the errors notified when the observation starts.
|
||||
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
|
||||
let cancellable = observation.start { error in
|
||||
expectIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.errors
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = Model()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
await expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = Model()
|
||||
let values = await model.valuesNotifiedOnStart(observation)
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = Model()
|
||||
let errors = await model.errorsNotifiedOnStart(observation)
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
// Clients that start an immediate shared observation concurrently,
|
||||
// from distinct actors, are all notified of the initial value.
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func concurrent_immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(
|
||||
in: writer,
|
||||
scheduling: .immediate,
|
||||
extent: .observationLifetime)
|
||||
let valuesList = await withTaskGroup(of: [Int].self) { group in
|
||||
for _ in 0..<20 {
|
||||
group.addTask {
|
||||
await Model().valuesNotifiedOnStart(observation)
|
||||
}
|
||||
}
|
||||
var valuesList: [[Int]] = []
|
||||
for await values in group {
|
||||
valuesList.append(values)
|
||||
}
|
||||
return valuesList
|
||||
}
|
||||
#expect(valuesList.count == 20)
|
||||
for values in valuesList {
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Global Actor
|
||||
|
||||
@globalActor actor SharedValueObservationTestGlobalActor {
|
||||
static let shared = SharedValueObservationTestGlobalActor()
|
||||
}
|
||||
|
||||
@SharedValueObservationTestGlobalActor private final class GlobalActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
nonisolated init() { }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(SharedValueObservationTestGlobalActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @SharedValueObservationTestGlobalActor struct GlobalActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = GlobalActorModel()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = Recorder()
|
||||
let cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(SharedValueObservationTestGlobalActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Distinct Actors
|
||||
|
||||
// Clients on distinct actors share a single observation. Each one is
|
||||
// notified on its own actor.
|
||||
@Suite nonisolated struct DistinctActorsSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases, [
|
||||
IsolatedValueObservationScheduling.async,
|
||||
IsolatedValueObservationScheduling.immediate,
|
||||
])
|
||||
func clients_on_distinct_actors(
|
||||
kind: WriterKind,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: scheduling)
|
||||
let mainActorModel = MainActorModel()
|
||||
let actorModel = Model()
|
||||
let globalActorModel = GlobalActorModel()
|
||||
async let observing1: Void = mainActorModel.observe(observation)
|
||||
async let observing2: Void = actorModel.observe(observation)
|
||||
async let observing3: Void = globalActorModel.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
_ = try await (observing1, observing2, observing3)
|
||||
await expectOrderedValues(mainActorModel.values)
|
||||
await expectOrderedValues(actorModel.values)
|
||||
await expectOrderedValues(globalActorModel.values)
|
||||
}
|
||||
}
|
||||
}
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBTestSupport
|
||||
#endif
|
||||
import Testing
|
||||
|
||||
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
//
|
||||
// The callbacks of the tested observations are not Sendable: they mutate
|
||||
// non-Sendable values and actor-isolated state.
|
||||
//
|
||||
// This file is identical in all Swift 6 test targets. Declarations are
|
||||
// explicitly isolated, or explicitly nonisolated, so that they do not
|
||||
// depend on the default isolation of the test target.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
nonisolated private final class Recorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
nonisolated private struct TestError: Error { }
|
||||
|
||||
nonisolated private let insertCount = 50
|
||||
|
||||
/// Creates the observed table.
|
||||
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs `insertCount` distinct insertions.
|
||||
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the number of rows in the `t` table.
|
||||
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
/// An observation that always fails.
|
||||
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
nonisolated private func expectIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects observed values to be ordered, and to end with `insertCount`.
|
||||
nonisolated private func expectOrderedValues(_ values: [Int]) {
|
||||
#expect(values.first != nil)
|
||||
#expect(values.last == insertCount)
|
||||
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor private final class MainActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @MainActor struct MainActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling_is_the_default(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
#expect(recorder.values.isEmpty)
|
||||
}
|
||||
#expect(recorder.values.first == 0)
|
||||
#expect(recorder.values.allSatisfy { $0 == 0 })
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = MainActorModel()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = MainActorModel()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
#expect(model.recorder.values.first == 0)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { continuation in
|
||||
cancellable = failingObservation.start(in: writer) { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
continuation.resume()
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no error yet.
|
||||
#expect(recorder.errors.isEmpty)
|
||||
}
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) throws {
|
||||
try withDatabaseWriter(kind) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
private actor Model {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
var errors: [any Error] { recorder.errors }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Observes until an error is notified.
|
||||
func observeError(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async {
|
||||
await withCheckedContinuation { continuation in
|
||||
cancellable = failingObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
expectIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
continuation.resume()
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
await expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
let values = await model.valuesNotifiedOnStart(writer)
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
let values = await model.values
|
||||
#expect(values.first == 0)
|
||||
expectOrderedValues(values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let model = Model()
|
||||
await model.observeError(writer, scheduling: .async)
|
||||
let errors = await model.errors
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let model = Model()
|
||||
await model.observeError(writer, scheduling: .immediate)
|
||||
let errors = await model.errors
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Global Actor
|
||||
|
||||
@globalActor actor ValueObservationTestGlobalActor {
|
||||
static let shared = ValueObservationTestGlobalActor()
|
||||
}
|
||||
|
||||
@ValueObservationTestGlobalActor private final class GlobalActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(ValueObservationTestGlobalActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @ValueObservationTestGlobalActor struct GlobalActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = GlobalActorModel()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(ValueObservationTestGlobalActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBTestSupport
|
||||
#endif
|
||||
import Testing
|
||||
|
||||
// Tests for `SharedValueObservation.start(isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
//
|
||||
// The callbacks of the tested observations are not Sendable: they mutate
|
||||
// non-Sendable values and actor-isolated state.
|
||||
//
|
||||
// This file is identical in all Swift 6 test targets. Declarations are
|
||||
// explicitly isolated, or explicitly nonisolated, so that they do not
|
||||
// depend on the default isolation of the test target.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
nonisolated private final class Recorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
nonisolated private struct TestError: Error { }
|
||||
|
||||
nonisolated private let insertCount = 50
|
||||
|
||||
/// Creates the observed table.
|
||||
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs `insertCount` distinct insertions.
|
||||
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the number of rows in the `t` table.
|
||||
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
/// An observation that always fails.
|
||||
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
nonisolated private func expectIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects observed values to be ordered, and to end with `insertCount`.
|
||||
nonisolated private func expectOrderedValues(_ values: [Int]) {
|
||||
#expect(values.first != nil)
|
||||
#expect(values.last == insertCount)
|
||||
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor private final class MainActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
nonisolated init() { }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @MainActor struct MainActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling_is_the_default(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer)
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
#expect(recorder.values.isEmpty)
|
||||
}
|
||||
#expect(recorder.values.first == 0)
|
||||
#expect(recorder.values.allSatisfy { $0 == 0 })
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = MainActorModel()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
|
||||
// The first client starts the shared observation.
|
||||
let recorder1 = Recorder()
|
||||
let cancellable1 = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder1.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder1.values == [0])
|
||||
|
||||
// The second client shares the observation.
|
||||
let recorder2 = Recorder()
|
||||
let cancellable2 = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder2.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder2.values == [0])
|
||||
|
||||
cancellable1.cancel()
|
||||
cancellable2.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) throws {
|
||||
try withDatabaseWriter(kind) { writer in
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = Recorder()
|
||||
let cancellable = observation.start { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
private actor Model {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [Int] {
|
||||
let cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Returns the errors notified when the observation starts.
|
||||
func errorsNotifiedOnStart(_ observation: SharedValueObservation<Int>) -> [any Error] {
|
||||
let cancellable = observation.start { error in
|
||||
expectIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.errors
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = Model()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
await expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = Model()
|
||||
let values = await model.valuesNotifiedOnStart(observation)
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let observation = failingObservation.shared(in: writer, scheduling: .immediate)
|
||||
let model = Model()
|
||||
let errors = await model.errorsNotifiedOnStart(observation)
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
// Clients that start an immediate shared observation concurrently,
|
||||
// from distinct actors, are all notified of the initial value.
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func concurrent_immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(
|
||||
in: writer,
|
||||
scheduling: .immediate,
|
||||
extent: .observationLifetime)
|
||||
let valuesList = await withTaskGroup(of: [Int].self) { group in
|
||||
for _ in 0..<20 {
|
||||
group.addTask {
|
||||
await Model().valuesNotifiedOnStart(observation)
|
||||
}
|
||||
}
|
||||
var valuesList: [[Int]] = []
|
||||
for await values in group {
|
||||
valuesList.append(values)
|
||||
}
|
||||
return valuesList
|
||||
}
|
||||
#expect(valuesList.count == 20)
|
||||
for values in valuesList {
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Global Actor
|
||||
|
||||
@globalActor actor SharedValueObservationTestGlobalActor {
|
||||
static let shared = SharedValueObservationTestGlobalActor()
|
||||
}
|
||||
|
||||
@SharedValueObservationTestGlobalActor private final class GlobalActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
|
||||
nonisolated init() { }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(_ observation: SharedValueObservation<Int>) async throws {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = observation.start { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(SharedValueObservationTestGlobalActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @SharedValueObservationTestGlobalActor struct GlobalActorSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .async)
|
||||
let model = GlobalActorModel()
|
||||
async let observing: Void = model.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
try await observing
|
||||
expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: .immediate)
|
||||
let recorder = Recorder()
|
||||
let cancellable = observation.start { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(SharedValueObservationTestGlobalActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Distinct Actors
|
||||
|
||||
// Clients on distinct actors share a single observation. Each one is
|
||||
// notified on its own actor.
|
||||
@Suite nonisolated struct DistinctActorsSharedValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases, [
|
||||
IsolatedValueObservationScheduling.async,
|
||||
IsolatedValueObservationScheduling.immediate,
|
||||
])
|
||||
func clients_on_distinct_actors(
|
||||
kind: WriterKind,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let observation = countObservation.shared(in: writer, scheduling: scheduling)
|
||||
let mainActorModel = MainActorModel()
|
||||
let actorModel = Model()
|
||||
let globalActorModel = GlobalActorModel()
|
||||
async let observing1: Void = mainActorModel.observe(observation)
|
||||
async let observing2: Void = actorModel.observe(observation)
|
||||
async let observing3: Void = globalActorModel.observe(observation)
|
||||
try await performInsertions(writer)
|
||||
_ = try await (observing1, observing2, observing3)
|
||||
await expectOrderedValues(mainActorModel.values)
|
||||
await expectOrderedValues(actorModel.values)
|
||||
await expectOrderedValues(globalActorModel.values)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBTestSupport
|
||||
#endif
|
||||
import Testing
|
||||
|
||||
// Tests for `ValueObservation.start(in:scheduling:isolation:onError:onChange:)`,
|
||||
// which notifies fresh values on the actor that starts the observation.
|
||||
//
|
||||
// The callbacks of the tested observations are not Sendable: they mutate
|
||||
// non-Sendable values and actor-isolated state.
|
||||
//
|
||||
// This file is identical in all Swift 6 test targets. Declarations are
|
||||
// explicitly isolated, or explicitly nonisolated, so that they do not
|
||||
// depend on the default isolation of the test target.
|
||||
|
||||
/// A non-Sendable recorder of observed values.
|
||||
nonisolated private final class Recorder {
|
||||
var values: [Int] = []
|
||||
var errors: [any Error] = []
|
||||
}
|
||||
|
||||
nonisolated private struct TestError: Error { }
|
||||
|
||||
nonisolated private let insertCount = 50
|
||||
|
||||
/// Creates the observed table.
|
||||
nonisolated private func createTable(_ writer: any DatabaseWriter) async throws {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs `insertCount` distinct insertions.
|
||||
nonisolated private func performInsertions(_ writer: any DatabaseWriter) async throws {
|
||||
for _ in 0..<insertCount {
|
||||
try await writer.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the number of rows in the `t` table.
|
||||
nonisolated private let countObservation = ValueObservation.trackingConstantRegion { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
/// An observation that always fails.
|
||||
nonisolated private let failingObservation = ValueObservation.trackingConstantRegion { _ -> Int in
|
||||
throw TestError()
|
||||
}
|
||||
|
||||
/// Crashes if the current task is not isolated to the given actor.
|
||||
nonisolated private func expectIsolation(_ actor: some Actor) {
|
||||
if #available(macOS 14, iOS 17, tvOS 17, watchOS 10, *) {
|
||||
actor.preconditionIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Expects observed values to be ordered, and to end with `insertCount`.
|
||||
nonisolated private func expectOrderedValues(_ values: [Int]) {
|
||||
#expect(values.first != nil)
|
||||
#expect(values.last == insertCount)
|
||||
#expect(values == values.sorted(), "Values are not notified in order: \(values)")
|
||||
}
|
||||
|
||||
// MARK: - Main Actor
|
||||
|
||||
@MainActor private final class MainActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @MainActor struct MainActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling_is_the_default(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no value yet.
|
||||
#expect(recorder.values.isEmpty)
|
||||
}
|
||||
#expect(recorder.values.first == 0)
|
||||
#expect(recorder.values.allSatisfy { $0 == 0 })
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = MainActorModel()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
|
||||
// Immediate scheduling: the initial value is notified.
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = MainActorModel()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
#expect(model.recorder.values.first == 0)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
await withCheckedContinuation { continuation in
|
||||
cancellable = failingObservation.start(in: writer) { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
continuation.resume()
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Asynchronous scheduling: no error yet.
|
||||
#expect(recorder.errors.isEmpty)
|
||||
}
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) throws {
|
||||
try withDatabaseWriter(kind) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = failingObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
expectIsolation(MainActor.shared)
|
||||
recorder.errors.append(error)
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
|
||||
// Immediate scheduling: the error is notified.
|
||||
#expect(recorder.errors.count == 1)
|
||||
#expect(recorder.errors.first is TestError)
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actor
|
||||
|
||||
private actor Model {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
var values: [Int] { recorder.values }
|
||||
var errors: [any Error] { recorder.errors }
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
/// Returns the values notified when the observation starts.
|
||||
func valuesNotifiedOnStart(_ writer: any DatabaseWriter) -> [Int] {
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(self)
|
||||
self.recorder.values.append(count)
|
||||
}
|
||||
cancellable.cancel()
|
||||
return recorder.values
|
||||
}
|
||||
|
||||
/// Observes until an error is notified.
|
||||
func observeError(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async {
|
||||
await withCheckedContinuation { continuation in
|
||||
cancellable = failingObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
expectIsolation(self)
|
||||
self.recorder.errors.append(error)
|
||||
continuation.resume()
|
||||
} onChange: { _ in
|
||||
Issue.record("Unexpected value")
|
||||
}
|
||||
}
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
await expectOrderedValues(model.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
let values = await model.valuesNotifiedOnStart(writer)
|
||||
#expect(values == [0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling_then_changes(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = Model()
|
||||
try await model.observe(writer, scheduling: .immediate)
|
||||
let values = await model.values
|
||||
#expect(values.first == 0)
|
||||
expectOrderedValues(values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let model = Model()
|
||||
await model.observeError(writer, scheduling: .async)
|
||||
let errors = await model.errors
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_error(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind) { writer in
|
||||
let model = Model()
|
||||
await model.observeError(writer, scheduling: .immediate)
|
||||
let errors = await model.errors
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first is TestError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Global Actor
|
||||
|
||||
@globalActor actor ValueObservationTestGlobalActor {
|
||||
static let shared = ValueObservationTestGlobalActor()
|
||||
}
|
||||
|
||||
@ValueObservationTestGlobalActor private final class GlobalActorModel {
|
||||
let recorder = Recorder()
|
||||
var cancellable: AnyDatabaseCancellable?
|
||||
|
||||
/// Observes until `insertCount` is observed.
|
||||
func observe(
|
||||
_ writer: any DatabaseWriter,
|
||||
scheduling: IsolatedValueObservationScheduling
|
||||
) async throws {
|
||||
var insertions: Task<Void, any Error>?
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
// ValueObservation may notify consecutive identical
|
||||
// values: resume the continuation only once.
|
||||
var pending = Optional(continuation)
|
||||
cancellable = countObservation.start(in: writer, scheduling: scheduling) { error in
|
||||
pending?.resume(throwing: error)
|
||||
pending = nil
|
||||
} onChange: { count in
|
||||
expectIsolation(ValueObservationTestGlobalActor.shared)
|
||||
self.recorder.values.append(count)
|
||||
if count == insertCount {
|
||||
pending?.resume()
|
||||
pending = nil
|
||||
}
|
||||
}
|
||||
|
||||
insertions = Task {
|
||||
try await performInsertions(writer)
|
||||
}
|
||||
}
|
||||
try await insertions?.value
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
|
||||
@Suite @ValueObservationTestGlobalActor struct GlobalActorValueObservationIsolationTests {
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func async_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let model = GlobalActorModel()
|
||||
try await model.observe(writer, scheduling: .async)
|
||||
expectOrderedValues(model.recorder.values)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: WriterKind.allCases)
|
||||
func immediate_scheduling(kind: WriterKind) async throws {
|
||||
try await withDatabaseWriter(kind, setup: createTable) { writer in
|
||||
let recorder = Recorder()
|
||||
let cancellable = countObservation.start(in: writer, scheduling: .immediate) { error in
|
||||
Issue.record(error)
|
||||
} onChange: { count in
|
||||
expectIsolation(ValueObservationTestGlobalActor.shared)
|
||||
recorder.values.append(count)
|
||||
}
|
||||
#expect(recorder.values == [0])
|
||||
cancellable.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user