Fix compiler warnings about SchedulingWatchdog concurrency

This commit is contained in:
Gwendal Roué committed 2024-09-14 17:24:00 +02:00
1 parent c2219075cf
commit 9501d1f936
2 files changed
+21 -11

No files matched your search

+19 -9
View File
@@ -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<SchedulingWatchdog>()
/// 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<T>(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<T>(_ 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)
}
}
+2 -2
View File
@@ -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 {