From 80c15c6ef60b7aa746562de84350daeb06efa4cb Mon Sep 17 00:00:00 2001 From: Renaud Lienhart Date: Thu, 31 Mar 2022 10:55:00 +1100 Subject: [PATCH] Fix a crash when an observation is quickly cancelled --- .../ValueWriteOnlyObserver.swift | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift index 2856c0b01..46c884a6a 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -198,7 +198,10 @@ extension ValueWriteOnlyObserver { // from a database access. try writer.unsafeReentrantWrite { db in // Fetch & Start observing the database - let fetchedValue = try fetchAndStartObservation(db) + guard let fetchedValue = try fetchAndStartObservation(db) else { + // Likely a GRDB bug + fatalError("can't start a cancelled or failed observation") + } // Reduce return reduceQueue.sync { @@ -218,12 +221,11 @@ extension ValueWriteOnlyObserver { // Start from a write access, so that self can register as a // transaction observer. writer.asyncWriteWithoutTransaction { db in - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } - do { // Fetch & Start observing the database - let fetchedValue = try self.fetchAndStartObservation(db) + guard let fetchedValue = try self.fetchAndStartObservation(db) else { + return /* Cancelled */ + } // Reduce // @@ -260,14 +262,13 @@ extension ValueWriteOnlyObserver { /// By grouping the initial fetch and the beginning of observation in a /// single database access, we are sure that no concurrent write can happen /// during the initial fetch, and that we won't miss any future change. - private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched { + private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? { // TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+ let (eventsOpt, fetchOpt) = lock.synchronized { (notificationCallbacks?.events, databaseAccess?.fetch) } guard let events = eventsOpt, let fetch = fetchOpt else { - // Likely a GRDB bug - fatalError("can't start a cancelled or failed observation") + return nil /* Cancelled */ } switch trackingMode {