diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 83cb6d17a..0081aef17 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -21,9 +21,17 @@ import Dispatch /// /// - preconditionValidQueue() crashes whenever a database is used in an invalid /// dispatch queue. -final class SchedulingWatchdog { +final class SchedulingWatchdog: @unchecked Sendable { + // @unchecked Sendable because mutable `allowedDatabases` is only + // accessed from the serial dispatch queue the instance is attached to. + private static let watchDogKey = DispatchSpecificKey() + + /// The databases allowed in the current dispatch queue. + /// + /// MUST be accessed from the serial dispatch queue the instance is attached to. private(set) var allowedDatabases: [Database] + var databaseObservationBroker: DatabaseObservationBroker? private init(allowedDatabase database: Database) { @@ -36,10 +44,12 @@ final class SchedulingWatchdog { queue.setSpecific(key: watchDogKey, value: watchdog) } - func inheritingAllowedDatabases(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T { - let backup = allowedDatabases - allowedDatabases.append(contentsOf: other.allowedDatabases) - defer { allowedDatabases = backup } + /// Must be called from a DispatchQueue with an attached SchedulingWatchdog. + static func inheritingAllowedDatabases(_ allowedDatabases: [Database], execute body: () throws -> T) rethrows -> T { + let watchdog = current! + let backup = watchdog.allowedDatabases + watchdog.allowedDatabases.append(contentsOf: allowedDatabases) + defer { watchdog.allowedDatabases = backup } return try body() } @@ -58,11 +68,11 @@ final class SchedulingWatchdog { current?.allows(db) ?? false } - static var current: SchedulingWatchdog? { - DispatchQueue.getSpecific(key: watchDogKey) - } - func allows(_ db: Database) -> Bool { allowedDatabases.contains { $0 === db } } + + static var current: SchedulingWatchdog? { + DispatchQueue.getSpecific(key: watchDogKey) + } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 031de4592..bcd5c953a 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -133,7 +133,7 @@ final class SerializedDatabase { // Case 3 return try queue.sync { - try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { + try SchedulingWatchdog.inheritingAllowedDatabases(watchdog.allowedDatabases) { defer { preconditionNoUnsafeTransactionLeft(db) } return try block(db) } @@ -209,7 +209,7 @@ final class SerializedDatabase { // Case 3 return try queue.sync { - try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { + try SchedulingWatchdog.inheritingAllowedDatabases(watchdog.allowedDatabases) { // Since we are reentrant, a transaction may already be opened. // In this case, don't check for unsafe transaction at the end. if db.isInsideTransaction {