From 00ccab06bd4e63fa517c229291a5f772df13d3a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 11 Feb 2024 15:29:14 +0100 Subject: [PATCH] Rename LockedBox to Mutex Maybe we'll be able to plug in the standard one eventually: https://forums.swift.org/t/pitch-synchronous-mutual-exclusion-lock/69889 --- GRDB.xcodeproj/project.pbxproj | 8 +-- GRDB/Core/Database.swift | 42 ++++++----- GRDB/Core/DatabasePool.swift | 6 +- GRDB/Core/DatabaseRegionObservation.swift | 8 +-- GRDB/Utils/LockedBox.swift | 72 ------------------- GRDB/Utils/Mutex.swift | 45 ++++++++++++ .../Observers/ValueConcurrentObserver.swift | 6 +- GRDB/ValueObservation/ValueObservation.swift | 37 +++++----- GRDBCustom.xcodeproj/project.pbxproj | 8 +-- Tests/GRDBTests/GRDBTestCase.swift | 11 ++- .../ValueObservationPrintTests.swift | 5 +- Tests/GRDBTests/ValueObservationTests.swift | 5 +- 12 files changed, 120 insertions(+), 133 deletions(-) delete mode 100644 GRDB/Utils/LockedBox.swift create mode 100644 GRDB/Utils/Mutex.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 213fe83be..6063d809e 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -186,7 +186,7 @@ 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; }; - 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; + 566BE71E2342542F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* Mutex.swift */; }; 566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; }; 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; }; @@ -628,7 +628,7 @@ 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; - 566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; + 566BE7172342542F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 566DDE0C288D763C0000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = ""; }; 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = ""; }; @@ -1318,7 +1318,7 @@ 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */, 563EF4492161F179007DAACD /* Inflections.swift */, 569BBA482291707D00478429 /* Inflections+English.swift */, - 566BE7172342542F00A8254B /* LockedBox.swift */, + 566BE7172342542F00A8254B /* Mutex.swift */, 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */, 563EF414215F87EB007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, @@ -2265,7 +2265,7 @@ 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */, - 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, + 566BE71E2342542F00A8254B /* Mutex.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */, 56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index baf21cc1f..3fb55e600 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -292,7 +292,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib var isInsideTransactionBlock = false /// Support for `checkForSuspensionViolation(from:)` - @LockedBox var isSuspended = false + let isSuspendedMutex = Mutex(false) /// Support for `checkForSuspensionViolation(from:)` /// This cache is never cleared: we assume journal mode never changes. @@ -1125,22 +1125,25 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// Suspension ends with `resume()`. func suspend() { - $isSuspended.update { isSuspended in + let needsInterrupt = isSuspendedMutex.withLock { isSuspended in if isSuspended { - return + return false } - // Prevent future lock acquisition isSuspended = true - - // Interrupt the database because this may trigger an - // SQLITE_INTERRUPT error which may itself abort a transaction and - // release a lock. See + return true + } + + if needsInterrupt { + // Interrupting the database can trigger an SQLITE_INTERRUPT + // error which may itself abort a transaction and + // release a database lock, which is our goal. + // See + // + // Maybe interrupt will not release any lock. To address this, + // we'll issue a rollback on next database access which requires + // a lock. See `checkForSuspensionViolation(from:).` interrupt() - - // Now what about the eventual remaining lock? We'll issue a - // rollback on next database access which requires a lock, in - // checkForSuspensionViolation(from:). } } @@ -1152,7 +1155,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// See suspend(). func resume() { - isSuspended = false + isSuspendedMutex.value = false } /// Support for `checkForSuspensionViolation(from:)` @@ -1182,9 +1185,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// See `suspend()` and ``Configuration/observesSuspensionNotifications``. func checkForSuspensionViolation(from statement: Statement) throws { - try $isSuspended.read { isSuspended in + let needsAbort = try isSuspendedMutex.withLock { isSuspended in guard isSuspended else { - return + return false } if try journalMode() == "wal" && statement.isReadonly { @@ -1195,7 +1198,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Those are not read-only: // - INSERT ... // - BEGIN IMMEDIATE TRANSACTION - return + return false } if statement.releasesDatabaseLock { @@ -1204,9 +1207,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // - ROLLBACK // - ROLLBACK TRANSACTION TO SAVEPOINT // - RELEASE SAVEPOINT - return + return false } + // Assume statement can acquire a write lock: abort. + return true + } + + if needsAbort { // Attempt at releasing an eventual lock with ROLLBACk, // as explained in Database.suspend(). // diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index d8f9b165f..1362135f4 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -11,7 +11,7 @@ public final class DatabasePool { /// It is constant, until close() sets it to nil. private var readerPool: Pool? - @LockedBox var databaseSnapshotCount = 0 + let databaseSnapshotCountMutex = Mutex(0) /// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers. private var suspensionObservers: [NSObjectProtocol] = [] @@ -144,7 +144,7 @@ public final class DatabasePool { } } -// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers +// @unchecked because of readerPool and suspensionObservers extension DatabasePool: @unchecked Sendable { } extension DatabasePool { @@ -863,7 +863,7 @@ extension DatabasePool { path: path, configuration: DatabasePool.readerConfiguration(writer.configuration), defaultLabel: "GRDB.DatabasePool", - purpose: "snapshot.\($databaseSnapshotCount.increment())") + purpose: "snapshot.\(databaseSnapshotCountMutex.increment())") } #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index c3ba4486a..1077895ca 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -89,16 +89,16 @@ extension DatabaseRegionObservation { onChange: @escaping (Database) -> Void) -> AnyDatabaseCancellable { - let stateMutex = LockedBox(wrappedValue: ObservationState.pending) + let stateMutex = Mutex(ObservationState.pending) // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. writer.unsafeReentrantWrite { db in do { let region = try observedRegion(db).observableRegion(db) - stateMutex.update { state in + stateMutex.withLock { state in let observer = DatabaseRegionObserver(region: region, onChange: { - if case .cancelled = stateMutex.wrappedValue { + if case .cancelled = stateMutex.value { return } onChange($0) @@ -122,7 +122,7 @@ extension DatabaseRegionObservation { // Deallocates the transaction observer. This makes sure that the // `onChange` callback will never be called again, because the // observation was started with the `.observerLifetime` extent. - stateMutex.wrappedValue = .cancelled + stateMutex.value = .cancelled } } } diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift deleted file mode 100644 index aef512604..000000000 --- a/GRDB/Utils/LockedBox.swift +++ /dev/null @@ -1,72 +0,0 @@ -import Foundation - -/// A LockedBox protects a value with an NSLock. -@propertyWrapper -final class LockedBox { - private var _wrappedValue: T - private var lock = NSLock() - - var wrappedValue: T { - get { read { $0 } } - set { update { $0 = newValue } } - } - - var projectedValue: LockedBox { self } - - init(wrappedValue: T) { - _wrappedValue = wrappedValue - } - - /// Runs the provided closure while holding a lock on the value. - /// - /// For example: - /// - /// // Prints "0" - /// @LockedBox var count = 0 - /// $count.read { print($0) } - /// - /// - parameter block: A closure that accepts the value. - @inline(__always) - @usableFromInline - func read(_ block: (T) throws -> U) rethrows -> U { - lock.lock() - defer { lock.unlock() } - return try block(_wrappedValue) - } - - /// Runs the provided closure while holding a lock on the value. - /// - /// For example: - /// - /// // Prints "1" - /// @LockedBox var count = 0 - /// $count.update { $0 += 1 } - /// print(count) - /// - /// - parameter block: A closure that can modify the value. - func update(_ block: (inout T) throws -> U) rethrows -> U { - lock.lock() - defer { lock.unlock() } - return try block(&_wrappedValue) - } -} - -extension LockedBox where T: Numeric { - @discardableResult - func increment() -> T { - update { n in - n += 1 - return n - } - } - - @discardableResult - func decrement() -> T { - update { n in - n -= 1 - return n - } - } -} - -extension LockedBox: @unchecked Sendable where T: Sendable { } diff --git a/GRDB/Utils/Mutex.swift b/GRDB/Utils/Mutex.swift new file mode 100644 index 000000000..c9bf304b4 --- /dev/null +++ b/GRDB/Utils/Mutex.swift @@ -0,0 +1,45 @@ +import Foundation + +/// A Mutex protects a value with an NSLock. +final class Mutex { + private var _value: T + private var lock = NSLock() + + var value: T { + get { withLock { $0 } } + set { withLock { $0 = newValue } } + } + + init(_ value: T) { + _value = value + } + + /// Runs the provided closure while holding a lock on the value. + /// + /// - parameter body: A closure that can modify the value. + func withLock(_ body: (inout T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try body(&_value) + } +} + +extension Mutex where T: Numeric { + @discardableResult + func increment() -> T { + withLock { n in + n += 1 + return n + } + } + + @discardableResult + func decrement() -> T { + withLock { n in + n -= 1 + return n + } + } +} + +extension Mutex: @unchecked Sendable where T: Sendable { } diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index a72c4aba8..e57aef098 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -146,7 +146,7 @@ final class ValueConcurrentObserver ValueObservation> { - let lock = NSLock() + let streamMutex = Mutex(stream ?? PrintOutputStream()) let prefix = prefix.isEmpty ? "" : "\(prefix): " - var stream = stream ?? PrintOutputStream() return handleEvents( willStart: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)start") }, + streamMutex.withLock { $0.write("\(prefix)start") } + }, willFetch: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)fetch") }, - willTrackRegion: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)tracked region: \($0)") }, + streamMutex.withLock { $0.write("\(prefix)fetch") } + }, + willTrackRegion: { region in + streamMutex.withLock { $0.write("\(prefix)tracked region: \(region)") } + }, databaseDidChange: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)database did change") }, - didReceiveValue: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)value: \($0)") }, - didFail: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)failure: \($0)") }, + streamMutex.withLock { $0.write("\(prefix)database did change") } + }, + didReceiveValue: { value in + streamMutex.withLock { $0.write("\(prefix)value: \(value)") } + }, + didFail: { error in + streamMutex.withLock { $0.write("\(prefix)failure: \(error)") } + }, didCancel: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)cancel") }) + streamMutex.withLock { $0.write("\(prefix)cancel") } + }) } // MARK: - Fetching Values diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7a9c12418..4b0b34668 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -185,7 +185,7 @@ 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */; }; 566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */; }; - 566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; + 566BE7152342541F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* Mutex.swift */; }; 566DDE12288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; }; 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; @@ -655,7 +655,7 @@ 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; }; 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = ""; }; - 566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; + 566BE7132342541F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 566DDE11288D76400000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = ""; }; 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; @@ -1339,7 +1339,7 @@ 564D4F91261E1D3300F55856 /* CaseInsensitiveIdentifier.swift */, 563EF44C2161F196007DAACD /* Inflections.swift */, 569BBA4B229170B300478429 /* Inflections+English.swift */, - 566BE7132342541F00A8254B /* LockedBox.swift */, + 566BE7132342541F00A8254B /* Mutex.swift */, 563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */, 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, @@ -2097,7 +2097,7 @@ 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86D2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, 56894FE3260658A400268F4D /* Decimal.swift in Sources */, - 566BE7152342541F00A8254B /* LockedBox.swift in Sources */, + 566BE7152342541F00A8254B /* Mutex.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index e2ad23760..b172189e6 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -64,10 +64,15 @@ class GRDBTestCase: XCTestCase { // The default path for database pool directory private var dbDirectoryPath: String! - // Populated by default configuration - @LockedBox var sqlQueries: [String] = [] + let _sqlQueriesMutex: Mutex<[String]> = Mutex([]) - // Populated by default configuration + // Automatically updated by default dbConfiguration + var sqlQueries: [String] { + get { _sqlQueriesMutex.value } + set { _sqlQueriesMutex.value = newValue } + } + + // Automatically updated by default dbConfiguration var lastSQLQuery: String? { sqlQueries.last } override func setUp() { diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 74e2450be..3f3c74548 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -4,9 +4,10 @@ import Dispatch class ValueObservationPrintTests: GRDBTestCase { class TestStream: TextOutputStream { - @LockedBox var strings: [String] = [] + private var stringsMutex: Mutex<[String]> = Mutex([]) + var strings: [String] { stringsMutex.value } func write(_ string: String) { - strings.append(string) + stringsMutex.value.append(string) } } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index d45d6e145..b757aa26a 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -174,9 +174,10 @@ class ValueObservationTests: GRDBTestCase { func testTrackingExplicitRegion() throws { class TestStream: TextOutputStream { - @LockedBox var strings: [String] = [] + private var stringsMutex: Mutex<[String]> = Mutex([]) + var strings: [String] { stringsMutex.value } func write(_ string: String) { - strings.append(string) + stringsMutex.value.append(string) } }