Fix compiler error with DatabaseFuture

This commit is contained in:
Gwendal Roué committed 2023-11-05 15:58:17 +01:00
1 parent 6e5e7efb7b
commit bb2013501c
2 files changed
+30 -11

No files matched your search

+8 -11
View File
@@ -447,21 +447,18 @@ extension DatabasePool: DatabaseReader {
}
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T, Error>? = nil
let builder = UnsafeDatabaseFutureBuilder<T>()
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
let result = dbResult.flatMap { db in
Result {
try value(db)
}
}
builder.setResultAndReleaseFuture(result)
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
return builder.makeFuture()
}
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
+22
View File
@@ -194,3 +194,25 @@ extension NSLocking {
#if !canImport(ObjectiveC)
@inlinable func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result { try body() }
#endif
/// A helper class that builds a DatabaseFuture without compiler errors
/// regarding concurrency.
final class UnsafeDatabaseFutureBuilder<T>: @unchecked Sendable {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<T, Error>? = nil
/// - precondition: MUST be called once.
func setResultAndReleaseFuture(_ result: Result<T, Error>) {
self.result = result
semaphore.signal()
}
/// - precondition: MUST be called once.
func makeFuture() -> DatabaseFuture<T> {
DatabaseFuture { [self] in
// Block the future until results are fetched
_ = semaphore.wait(timeout: .distantFuture)
return try result!.get()
}
}
}