SerializedDatabase async access requires a Sendable closure

This commit is contained in:
Gwendal Roué committed 2024-07-27 16:37:33 +02:00
1 parent 7fd34012b4
commit 7d7dc8ea72
11 files changed
+75 -72

No files matched your search

+12 -8
View File
@@ -251,7 +251,9 @@ extension DatabasePool {
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -351,7 +353,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -395,7 +397,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -440,7 +442,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncConcurrentRead(value)
}
@@ -481,7 +483,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -640,7 +642,9 @@ extension DatabasePool: DatabaseReader {
///
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
func asyncWALSnapshotTransaction(
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -731,7 +735,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -785,7 +789,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+8 -6
View File
@@ -169,7 +169,9 @@ extension DatabaseQueue {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -233,7 +235,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -258,7 +260,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -266,7 +268,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -367,7 +369,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -413,7 +415,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+8 -8
View File
@@ -214,7 +214,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -285,7 +285,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -459,7 +459,7 @@ extension DatabaseReader {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func read<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
@@ -505,7 +505,7 @@ extension DatabaseReader {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func unsafeRead<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
@@ -552,7 +552,7 @@ extension DatabaseReader {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
value: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
OnDemandFuture { fulfill in
@@ -676,7 +676,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -685,7 +685,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -756,7 +756,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncRead(value)
}
}
+2 -2
View File
@@ -150,7 +150,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -158,7 +158,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
+1 -1
View File
@@ -293,7 +293,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
+17 -17
View File
@@ -179,7 +179,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -211,7 +211,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -295,7 +295,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
}
extension DatabaseWriter {
@@ -381,8 +381,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -563,7 +563,7 @@ extension DatabaseWriter {
/// would happen while establishing the database access or committing
/// the transaction.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func write<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
@@ -601,7 +601,7 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func writeWithoutTransaction<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
@@ -654,7 +654,7 @@ extension DatabaseWriter {
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T)
_ updates: @escaping @Sendable (Database) throws -> T)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
@@ -758,7 +758,7 @@ extension DatabaseWriter {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping (Database) throws -> Output)
updates: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -823,8 +823,8 @@ extension DatabaseWriter {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
{
@@ -840,7 +840,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
self.spawnConcurrentRead { [updatesValue] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -915,7 +915,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -924,7 +924,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -956,11 +956,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -968,7 +968,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
+1 -1
View File
@@ -223,7 +223,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping (Database) -> Void) {
func async(_ block: @escaping @Sendable (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+1 -1
View File
@@ -98,7 +98,7 @@
- [X] GRDB7: Remove concurrenRead and DatabaseFuture
- [ ] GRDB7: Merge `_ValueReducer` into `ValueReducer`
- [ ] GRDB7: Sendable conformances
- [ ] SerializedDatabase Sendable async closure
- [X] SerializedDatabase Sendable async closure
- [X] OnDemandFuture Sendable async closure
- [X] WALSnapshotTransaction refactor
- [X] anydatabasecancellable
@@ -1078,13 +1078,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testAsyncConcurrentReadOpensATransaction() throws {
let dbPool = try makeDatabasePool()
var isInsideTransaction: Bool? = nil
let isInsideTransactionMutex: Mutex<Bool?> = Mutex(nil)
let expectation = self.expectation(description: "read")
dbPool.writeWithoutTransaction { db in
dbPool.asyncConcurrentRead { dbResult in
do {
let db = try dbResult.get()
isInsideTransaction = db.isInsideTransaction
isInsideTransactionMutex.value = db.isInsideTransaction
do {
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
XCTFail("Expected error")
@@ -1097,7 +1097,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(isInsideTransaction, true)
XCTAssertEqual(isInsideTransactionMutex.value, true)
}
func testAsyncConcurrentReadOutsideOfTransaction() throws {
@@ -1120,14 +1120,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// <
// }
var count: Int? = nil
let countMutex: Mutex<Int?> = Mutex(nil)
let expectation = self.expectation(description: "read")
try dbPool.writeWithoutTransaction { db in
dbPool.asyncConcurrentRead { dbResult in
do {
_ = s1.wait(timeout: .distantFuture)
let db = try dbResult.get()
count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
countMutex.value = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
} catch {
XCTFail("Unexpected error: \(error)")
}
@@ -1137,14 +1137,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
s1.signal()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 0)
XCTAssertEqual(countMutex.value, 0)
}
func testAsyncConcurrentReadError() throws {
// Necessary for this test to run as quickly as possible
dbConfiguration.readonlyBusyMode = .immediateError
let dbPool = try makeDatabasePool()
var readError: DatabaseError? = nil
let readErrorMutex: Mutex<DatabaseError?> = Mutex(nil)
let expectation = self.expectation(description: "read")
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
@@ -1156,12 +1156,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTFail("Unexpected result: \(dbResult)")
return
}
readError = dbError
readErrorMutex.value = dbError
expectation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY)
XCTAssertEqual(readError!.message!, "database is locked")
let readError = try XCTUnwrap(readErrorMutex.value)
XCTAssertEqual(readError.resultCode, .SQLITE_BUSY)
XCTAssertEqual(readError.message, "database is locked")
}
}
+11 -15
View File
@@ -237,9 +237,7 @@ class DatabasePoolTests: GRDBTestCase {
let group = DispatchGroup()
// The maximum number of threads we could witness
var maxThreadCount: CInt = 0
let lock = NSLock()
let maxThreadCountMutex: Mutex<CInt> = Mutex(0)
for _ in (0..<numberOfConcurrentReads) {
group.enter()
pool.asyncUnsafeRead { result in
@@ -248,15 +246,15 @@ class DatabasePoolTests: GRDBTestCase {
}
let threadsCount = getThreadsCount()
lock.lock()
maxThreadCount = max(maxThreadCount, threadsCount)
lock.unlock()
maxThreadCountMutex.withLock { count in
count = max(count, threadsCount)
}
group.leave()
}
}
group.wait()
XCTAssert(maxThreadCount < 50)
XCTAssert(maxThreadCountMutex.value < 50)
#endif
}
@@ -279,9 +277,7 @@ class DatabasePoolTests: GRDBTestCase {
let group = DispatchGroup()
// The maximum number of threads we could witness
var maxThreadCount: CInt = 0
let lock = NSLock()
let maxThreadCountMutex: Mutex<CInt> = Mutex(0)
for _ in (0..<numberOfConcurrentReads) {
group.enter()
pool.asyncRead { result in
@@ -290,15 +286,15 @@ class DatabasePoolTests: GRDBTestCase {
}
let threadsCount = getThreadsCount()
lock.lock()
maxThreadCount = max(maxThreadCount, threadsCount)
lock.unlock()
maxThreadCountMutex.withLock { count in
count = max(count, threadsCount)
}
group.leave()
}
}
group.wait()
XCTAssert(maxThreadCount < 50)
XCTAssert(maxThreadCountMutex.value < 50)
#endif
}
+3 -3
View File
@@ -224,12 +224,12 @@ class DatabaseReaderTests : GRDBTestCase {
func test(_ dbReader: some DatabaseReader) throws {
let expectation = self.expectation(description: "updates")
let semaphore = DispatchSemaphore(value: 0)
var count: Int?
let countMutex: Mutex<Int?> = Mutex(nil)
dbReader.asyncRead { dbResult in
// Make sure this block executes asynchronously
semaphore.wait()
do {
count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
countMutex.value = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
} catch {
XCTFail("Unexpected error: \(error)")
}
@@ -238,7 +238,7 @@ class DatabaseReaderTests : GRDBTestCase {
semaphore.signal()
waitForExpectations(timeout: 1, handler: nil)
XCTAssertNotNil(count)
XCTAssertNotNil(countMutex.value)
}
try test(makeDatabaseQueue())