From 8b49360af123c60f8902c88b55fda5ddb2e37dcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 23 Apr 2024 17:45:02 +0200 Subject: [PATCH] StrictConcurrency: ValueObservation change callback is Sendable --- GRDB/Core/Concurrency/DatabasePool.swift | 4 +- GRDB/Core/Concurrency/DatabaseQueue.swift | 2 +- GRDB/Core/Concurrency/DatabaseReader.swift | 6 +- GRDB/Core/Concurrency/DatabaseSnapshot.swift | 2 +- .../Concurrency/DatabaseSnapshotPool.swift | 2 +- GRDB/Core/Concurrency/DatabaseWriter.swift | 4 +- .../Observers/ValueConcurrentObserver.swift | 4 +- .../Observers/ValueWriteOnlyObserver.swift | 4 +- .../SharedValueObservation.swift | 6 +- GRDB/ValueObservation/ValueObservation.swift | 4 +- .../SharedValueObservationTests.swift | 115 +++++++------- ...ValueObservationRegionRecordingTests.swift | 12 +- Tests/GRDBTests/ValueObservationTests.swift | 149 +++++++++--------- 13 files changed, 159 insertions(+), 155 deletions(-) diff --git a/GRDB/Core/Concurrency/DatabasePool.swift b/GRDB/Core/Concurrency/DatabasePool.swift index 7f41ae125..b88e5925f 100644 --- a/GRDB/Core/Concurrency/DatabasePool.swift +++ b/GRDB/Core/Concurrency/DatabasePool.swift @@ -682,7 +682,7 @@ extension DatabasePool: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if configuration.readonly { @@ -713,7 +713,7 @@ extension DatabasePool: DatabaseReader { private func _addConcurrent( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") diff --git a/GRDB/Core/Concurrency/DatabaseQueue.swift b/GRDB/Core/Concurrency/DatabaseQueue.swift index a71e7ce13..6a65b11c3 100644 --- a/GRDB/Core/Concurrency/DatabaseQueue.swift +++ b/GRDB/Core/Concurrency/DatabaseQueue.swift @@ -310,7 +310,7 @@ extension DatabaseQueue: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if configuration.readonly { diff --git a/GRDB/Core/Concurrency/DatabaseReader.swift b/GRDB/Core/Concurrency/DatabaseReader.swift index 9f7dc4eab..03c8e2b4b 100644 --- a/GRDB/Core/Concurrency/DatabaseReader.swift +++ b/GRDB/Core/Concurrency/DatabaseReader.swift @@ -343,7 +343,7 @@ public protocol DatabaseReader: AnyObject, Sendable { func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable } @@ -600,7 +600,7 @@ extension DatabaseReader { func _addReadOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { @@ -696,7 +696,7 @@ extension AnyDatabaseReader: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { base._add( diff --git a/GRDB/Core/Concurrency/DatabaseSnapshot.swift b/GRDB/Core/Concurrency/DatabaseSnapshot.swift index 3c6b2b8f9..25c7cf05b 100644 --- a/GRDB/Core/Concurrency/DatabaseSnapshot.swift +++ b/GRDB/Core/Concurrency/DatabaseSnapshot.swift @@ -171,7 +171,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { _addReadOnly( diff --git a/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift b/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift index fc6099bd0..083f52532 100644 --- a/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift +++ b/GRDB/Core/Concurrency/DatabaseSnapshotPool.swift @@ -331,7 +331,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { _addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange) diff --git a/GRDB/Core/Concurrency/DatabaseWriter.swift b/GRDB/Core/Concurrency/DatabaseWriter.swift index 75c99ee30..34a9d4290 100644 --- a/GRDB/Core/Concurrency/DatabaseWriter.swift +++ b/GRDB/Core/Concurrency/DatabaseWriter.swift @@ -512,7 +512,7 @@ extension DatabaseWriter { func _addWriteOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") @@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable { base._add( diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index 21ffd5b5a..c4e4483c4 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -122,7 +122,7 @@ final class ValueConcurrentObserver< /// Ability to notify observation events private struct NotificationCallbacks { let events: ValueObservationEvents - let onChange: (Reducer.Value) -> Void + let onChange: @Sendable (Reducer.Value) -> Void } /// Relationship with the `TransactionObserver` protocol @@ -166,7 +166,7 @@ final class ValueConcurrentObserver< trackingMode: ValueObservationTrackingMode, reducer: Reducer, events: ValueObservationEvents, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) { // Configuration self.scheduler = scheduler diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index e1cecca09..e2c311b26 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -114,7 +114,7 @@ final class ValueWriteOnlyObserver< /// Ability to notify observation events private struct NotificationCallbacks { let events: ValueObservationEvents - let onChange: (Reducer.Value) -> Void + let onChange: @Sendable (Reducer.Value) -> Void } /// Relationship with the `TransactionObserver` protocol @@ -152,7 +152,7 @@ final class ValueWriteOnlyObserver< trackingMode: ValueObservationTrackingMode, reducer: Reducer, events: ValueObservationEvents, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) { // Configuration self.scheduler = scheduler diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index e58d01885..115a15b60 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -181,9 +181,9 @@ public final class SharedValueObservation { private final class Client { var onError: (Error) -> Void - var onChange: (Element) -> Void + var onChange: @Sendable (Element) -> Void - init(onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) { + init(onError: @escaping (Error) -> Void, onChange: @escaping @Sendable (Element) -> Void) { self.onError = onError self.onChange = onChange } @@ -225,7 +225,7 @@ public final class SharedValueObservation { /// - returns: A DatabaseCancellable that can stop the observation. public func start( onError: @escaping (Error) -> Void, - onChange: @escaping (Element) -> Void) + onChange: @escaping @Sendable (Element) -> Void) -> AnyDatabaseCancellable { synchronized { diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index e4801d3bf..517246707 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -83,7 +83,7 @@ struct ValueObservationEvents: Refinable { typealias ValueObservationStart = ( _ onError: @escaping @Sendable (Error) -> Void, - _ onChange: @escaping (T) -> Void) + _ onChange: @escaping @Sendable (T) -> Void) -> AnyDatabaseCancellable extension ValueObservation: Refinable { @@ -139,7 +139,7 @@ extension ValueObservation: Refinable { in reader: some DatabaseReader, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), onError: @escaping @Sendable (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index d5b291a00..6f34c85f1 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -39,12 +39,12 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value: Int? + let valueMutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { valueMutex.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -52,12 +52,12 @@ class SharedValueObservationTests: GRDBTestCase { } do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { valueMutex.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.value, 0) XCTAssertEqual(log.flush(), []) cancellable.cancel() @@ -91,21 +91,21 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value1: Int? - var value2: Int? + let value1Mutex: Mutex = Mutex(nil) + let value2Mutex: Mutex = Mutex(nil) let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value1 = value + value1Mutex.value = value _ = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value2 = value + value2Mutex.value = value }) }) - XCTAssertEqual(value1, 0) - XCTAssertEqual(value2, 0) + XCTAssertEqual(value1Mutex.value, 0) + XCTAssertEqual(value2Mutex.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable1.cancel() @@ -175,12 +175,12 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { valueMutex.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -188,12 +188,12 @@ class SharedValueObservationTests: GRDBTestCase { } do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { valueMutex.value = $0 }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -226,21 +226,21 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in - var value1: Int? - var value2: Int? + let value1Mutex: Mutex = Mutex(nil) + let value2Mutex: Mutex = Mutex(nil) let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value1 = value + value1Mutex.value = value _ = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value2 = value + value2Mutex.value = value }) }) - XCTAssertEqual(value1, 0) - XCTAssertEqual(value2, 0) + XCTAssertEqual(value1Mutex.value, 0) + XCTAssertEqual(value2Mutex.value, 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable1.cancel() @@ -273,40 +273,40 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated try withExtendedLifetime(sharedObservation) { sharedObservation in // --- Start observation 1 - var values1: [Int] = [] + let values1Mutex: Mutex<[Int]> = Mutex([]) let exp1 = expectation(description: "") exp1.expectedFulfillmentCount = 2 exp1.assertForOverFulfill = false let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values1.append($0) + onChange: { value in + values1Mutex.withLock { $0.append(value) } exp1.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp1], timeout: 1) - XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(values1Mutex.value, [0, 1]) XCTAssertEqual(log.flush(), [ "start", "fetch", "tracked region: player(*)", "value: 0", "database did change", "fetch", "value: 1"]) // --- Start observation 2 - var values2: [Int] = [] + let values2Mutex: Mutex<[Int]> = Mutex([]) let exp2 = expectation(description: "") exp2.expectedFulfillmentCount = 2 exp2.assertForOverFulfill = false let cancellable2 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values2.append($0) + onChange: { value in + values2Mutex.withLock { $0.append(value) } exp2.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp2], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(values1Mutex.value, [0, 1, 2]) + XCTAssertEqual(values2Mutex.value, [1, 2]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) // --- Stop observation 1 @@ -314,22 +314,22 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) // --- Start observation 3 - var values3: [Int] = [] + let values3Mutex: Mutex<[Int]> = Mutex([]) let exp3 = expectation(description: "") exp3.expectedFulfillmentCount = 2 exp3.assertForOverFulfill = false let cancellable3 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values3.append($0) + onChange: { value in + values3Mutex.withLock { $0.append(value) } exp3.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp3], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2, 3]) - XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(values1Mutex.value, [0, 1, 2]) + XCTAssertEqual(values2Mutex.value, [1, 2, 3]) + XCTAssertEqual(values3Mutex.value, [2, 3]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) // --- Stop observation 2 @@ -355,7 +355,8 @@ class SharedValueObservationTests: GRDBTestCase { } let log = Log() - var sharedObservation: SharedValueObservation? = ValueObservation + let sharedObservationMutex: Mutex?> = Mutex(nil) + sharedObservationMutex.value = ValueObservation .tracking(Table("player").fetchCount) .print(to: log) .shared( @@ -367,11 +368,11 @@ class SharedValueObservationTests: GRDBTestCase { // --- let exp = expectation(description: "") exp.expectedFulfillmentCount = 3 - let cancellable = sharedObservation!.start( + let cancellable = sharedObservationMutex.value!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in // Early release - sharedObservation = nil + sharedObservationMutex.value = nil switch value { case 0: @@ -452,40 +453,40 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated try withExtendedLifetime(sharedObservation) { sharedObservation in // --- Start observation 1 - var values1: [Int] = [] + let values1Mutex: Mutex<[Int]> = Mutex([]) let exp1 = expectation(description: "") exp1.expectedFulfillmentCount = 2 exp1.assertForOverFulfill = false let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values1.append($0) + onChange: { value in + values1Mutex.withLock { $0.append(value) } exp1.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp1], timeout: 1) - XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(values1Mutex.value, [0, 1]) XCTAssertEqual(log.flush(), [ "start", "fetch", "tracked region: player(*)", "value: 0", "database did change", "fetch", "value: 1"]) // --- Start observation 2 - var values2: [Int] = [] + let values2Mutex: Mutex<[Int]> = Mutex([]) let exp2 = expectation(description: "") exp2.expectedFulfillmentCount = 2 exp2.assertForOverFulfill = false let cancellable2 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values2.append($0) + onChange: { value in + values2Mutex.withLock { $0.append(value) } exp2.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp2], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(values1Mutex.value, [0, 1, 2]) + XCTAssertEqual(values2Mutex.value, [1, 2]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) // --- Stop observation 1 @@ -493,22 +494,22 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) // --- Start observation 3 - var values3: [Int] = [] + let values3Mutex: Mutex<[Int]> = Mutex([]) let exp3 = expectation(description: "") exp3.expectedFulfillmentCount = 2 exp3.assertForOverFulfill = false let cancellable3 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values3.append($0) + onChange: { value in + values3Mutex.withLock { $0.append(value) } exp3.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp3], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2, 3]) - XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(values1Mutex.value, [0, 1, 2]) + XCTAssertEqual(values2Mutex.value, [1, 2, 3]) + XCTAssertEqual(values3Mutex.value, [2, 3]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) // --- Stop observation 2 diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 5809d394e..51923ebaa 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -130,7 +130,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { """) } - var results: [Int] = [] + let resultsMutex: Mutex<[Int]> = Mutex([]) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 @@ -151,7 +151,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) + resultsMutex.withLock { $0.append(count) } notificationExpectation.fulfill() }) @@ -166,7 +166,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) + XCTAssertEqual(resultsMutex.value, [0, 1, 2, 3]) XCTAssertEqual(regionsMutex.value.map(\.description), [ "a(value),source(name)", @@ -185,7 +185,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { """) } - var results: [Int] = [] + let resultsMutex: Mutex<[Int]> = Mutex([]) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 @@ -207,7 +207,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) + resultsMutex.withLock { $0.append(count) } notificationExpectation.fulfill() }) @@ -222,7 +222,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) + XCTAssertEqual(resultsMutex.value, [0, 1, 2, 3]) XCTAssertEqual(regionsMutex.value.map(\.description), [ "a(value),source(name)", diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 34b19cb96..4fae782fe 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -368,18 +368,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0]) + XCTAssertEqual(observedCountsMutex.value, [0, 0]) } } @@ -407,18 +407,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0]) + XCTAssertEqual(observedCountsMutex.value, [0, 0]) } } @@ -456,18 +456,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, expectedCounts) + XCTAssertEqual(observedCountsMutex.value, expectedCounts) } } @@ -505,18 +505,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, expectedCounts) + XCTAssertEqual(observedCountsMutex.value, expectedCounts) } } @@ -598,7 +598,7 @@ class ValueObservationTests: GRDBTestCase { try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } // Track reducer process - var changesCount = 0 + let changesCountMutex = Mutex(0) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 @@ -609,65 +609,21 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and deallocate cancellable after second change - var cancellable: (any DatabaseCancellable)? - cancellable = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - changesCount += 1 - if changesCount == 2 { - cancellable = nil - } - notificationExpectation.fulfill() - }) - - // notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - // not notified - try dbQueue.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - // Avoid "Variable 'cancellable' was written to, but never read" warning - _ = cancellable - - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(changesCount, 2) - } - - func testCancellableExplicitCancellation() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer process - var changesCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - // Create an observation - let observation = ValueObservation.trackingConstantRegion { - try Int.fetchOne($0, sql: "SELECT * FROM t") - } - - // Start observation and cancel cancellable after second change - var cancellable: (any DatabaseCancellable)! - cancellable = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { _ in - changesCount += 1 - if changesCount == 2 { - cancellable.cancel() - } - notificationExpectation.fulfill() - }) - - try withExtendedLifetime(cancellable) { + let cancellableMutex: Mutex<(any DatabaseCancellable)?> = Mutex(nil) + try withExtendedLifetime(cancellableMutex) { + cancellableMutex.value = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + changesCountMutex.withLock { changesCount in + changesCount += 1 + if changesCount == 2 { + cancellableMutex.value = nil + } + } + notificationExpectation.fulfill() + }) + // notified try dbQueue.write { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") @@ -679,7 +635,54 @@ class ValueObservationTests: GRDBTestCase { } waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(changesCount, 2) + } + XCTAssertEqual(changesCountMutex.value, 2) + } + + func testCancellableExplicitCancellation() throws { + // We need something to change + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + let changesCountMutex = Mutex(0) + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // Create an observation + let observation = ValueObservation.trackingConstantRegion { + try Int.fetchOne($0, sql: "SELECT * FROM t") + } + + // Start observation and cancel cancellable after second change + let cancellableMutex: Mutex<(any DatabaseCancellable)?> = Mutex(nil) + try withExtendedLifetime(cancellableMutex) { + cancellableMutex.value = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + changesCountMutex.withLock { changesCount in + changesCount += 1 + if changesCount == 2 { + cancellableMutex.value?.cancel() + } + } + notificationExpectation.fulfill() + }) + + // notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + + // not notified + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(changesCountMutex.value, 2) } }