From 65c803a11067ee84fa052906648b7901037d3681 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Apr 2023 13:24:46 +0200 Subject: [PATCH] Fix #1362 --- .../Observers/ValueConcurrentObserver.swift | 84 +++++++++++++++---- 1 file changed, 67 insertions(+), 17 deletions(-) diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index 87887ffdd..b880a13c2 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -101,6 +101,19 @@ final class ValueConcurrentObserver - switch trackingMode { case .constantRegion, .constantRegionRecordedFromSelection: - future = databaseAccess.dbPool.concurrentRead { db in - try databaseAccess.fetch(db) - } + setNeedsFetching(databaseAccess: databaseAccess) + case .nonConstantRegionRecordedFromSelection: // When the tracked region is not constant, we can't perform // concurrent fetches of observed values. @@ -723,26 +736,63 @@ extension ValueConcurrentObserver: TransactionObserver { } observationState.region = observedRegion - future = DatabaseFuture(.success(fetchedValue)) + reduce(.success(fetchedValue)) } catch { stopDatabaseObservation(writerDB) notifyError(error) return } } - - // Reduce - // - // Reducing is performed asynchronously, so that we do not lock - // the writer dispatch queue longer than necessary. - // - // Important: reduceQueue.async guarantees the same ordering between - // transactions and notifications! + } + + private func setNeedsFetching(databaseAccess: DatabaseAccess) { + $fetchingState.update { state in + switch state { + case .idle: + state = .fetching + asyncFetch(databaseAccess: databaseAccess) + + case .fetching: + state = .fetchingAndNeedsFetch + + case .fetchingAndNeedsFetch: + break + } + } + } + + private func asyncFetch(databaseAccess: DatabaseAccess) { + databaseAccess.dbPool.asyncRead { [self] dbResult in + let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } + guard isNotifying else { return /* Cancelled */ } + + let fetchResult = dbResult.flatMap { db in + Result { try databaseAccess.fetch(db) } + } + + self.reduce(fetchResult) + + $fetchingState.update { state in + switch state { + case .idle: + // GRDB bug + preconditionFailure() + + case .fetching: + state = .idle + + case .fetchingAndNeedsFetch: + state = .fetching + asyncFetch(databaseAccess: databaseAccess) + } + } + } + } + + private func reduce(_ fetchResult: Result) { reduceQueue.async { do { - // Wait until fetch has completed - // TODO: find a way to guarantee correct ordering without waiting for a semaphore and blocking a thread. - let fetchedValue = try future.wait() + let fetchedValue = try fetchResult.get() let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } guard isNotifying else { return /* Cancelled */ }