mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
Sendable annotations in DatabaseReader and DatabaseWriter
Also, we make sure to always resume UnsafeContinuation with Sendable values. See https://forums.swift.org/t/advice-regarding-sendable-constraints-on-generic-async-apis/69969/3
This commit is contained in:
1 parent
896d14ca56
commit
81746c75ad
12 files changed
+197
-141
No files matched your search
@@ -406,6 +406,10 @@ extension DatabaseError {
|
||||
static func connectionIsClosed() -> Self {
|
||||
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
|
||||
static func snapshotIsLost() -> Self {
|
||||
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
|
||||
}
|
||||
}
|
||||
|
||||
// Support for `catch DatabaseError.SQLITE_XXX`
|
||||
|
||||
@@ -62,17 +62,15 @@ public final class DatabasePool {
|
||||
// an opened transaction.
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
makeElement: { [readerConfiguration] index in
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
purpose: "reader.\(index)")
|
||||
})
|
||||
|
||||
// Set up journal mode unless readonly
|
||||
@@ -357,7 +355,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
|
||||
@@ -401,7 +399,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
|
||||
@@ -446,25 +444,22 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// The semaphore that blocks until futureResult is defined:
|
||||
let futureSemaphore = DispatchSemaphore(value: 0)
|
||||
var futureResult: Result<T, Error>? = nil
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
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 (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
@@ -505,7 +500,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.
|
||||
@@ -664,7 +659,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
|
||||
@@ -690,7 +687,7 @@ extension DatabasePool: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
@@ -721,7 +718,7 @@ extension DatabasePool: DatabaseReader {
|
||||
private func _addConcurrent<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -755,7 +752,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
|
||||
@@ -808,7 +805,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,7 +233,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 +258,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 +266,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
try writer.reentrantSync(value)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
public func concurrentRead<T>(_ value: (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(Result {
|
||||
@@ -279,7 +279,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
})
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -309,7 +309,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
@@ -379,7 +379,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)) }
|
||||
}
|
||||
|
||||
@@ -425,7 +425,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,14 +22,14 @@ import Dispatch
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``read(_:)-3806d``
|
||||
/// - ``read(_:)-4w6gy``
|
||||
/// - ``read(_:)-7a20l``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
/// - ``asyncRead(_:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-11mk0``
|
||||
/// - ``unsafeRead(_:)-3arn0``
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
@@ -213,7 +213,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.
|
||||
@@ -284,7 +284,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.
|
||||
@@ -342,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
|
||||
@@ -458,7 +458,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, watchOS 6, *)
|
||||
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func read<T: Sendable>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncRead { result in
|
||||
do {
|
||||
@@ -504,7 +504,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, watchOS 6, *)
|
||||
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func unsafeRead<T: Sendable>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncUnsafeRead { result in
|
||||
do {
|
||||
@@ -549,18 +549,18 @@ extension DatabaseReader {
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
public func readPublisher<Output: Sendable>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
value: @escaping (Database) throws -> Output)
|
||||
value: @escaping @Sendable (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
Deferred {
|
||||
Future { fulfill in
|
||||
self.asyncRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db) } })
|
||||
}
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db) } })
|
||||
}
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToReadPublisher()
|
||||
}
|
||||
@@ -601,7 +601,7 @@ extension DatabaseReader {
|
||||
func _addReadOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
@@ -619,16 +619,16 @@ extension DatabaseReader {
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
|
||||
} else {
|
||||
var isCancelled = false
|
||||
let cancellable = AnyDatabaseCancellable { }
|
||||
asyncRead { dbResult in
|
||||
guard !isCancelled else { return }
|
||||
if cancellable.isCancelled { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchInitialValue(db) }
|
||||
}
|
||||
|
||||
scheduler.schedule {
|
||||
guard !isCancelled else { return }
|
||||
if cancellable.isCancelled { return }
|
||||
do {
|
||||
try onChange(result.get())
|
||||
} catch {
|
||||
@@ -636,7 +636,7 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { isCancelled = true })
|
||||
return cancellable
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -677,7 +677,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)
|
||||
}
|
||||
|
||||
@@ -686,7 +686,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)
|
||||
}
|
||||
|
||||
@@ -697,7 +697,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
@@ -757,7 +757,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)
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,9 @@ extension DatabaseRegionObservation {
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// The state of a started DatabaseRegionObservation
|
||||
private enum ObservationState {
|
||||
private enum ObservationState: @unchecked Sendable {
|
||||
// @unchecked because we don't use DatabaseRegionObserver outside of
|
||||
// the writer dispatch queue.
|
||||
case cancelled
|
||||
case pending
|
||||
case started(DatabaseRegionObserver)
|
||||
@@ -85,20 +87,20 @@ extension DatabaseRegionObservation {
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
public func start(
|
||||
in writer: some DatabaseWriter,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Database) -> Void)
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (Database) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@LockedBox var state = ObservationState.pending
|
||||
let stateBox = LockedBox(wrappedValue: 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)
|
||||
$state.update {
|
||||
stateBox.update {
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: {
|
||||
if case .cancelled = state {
|
||||
if case .cancelled = stateBox.wrappedValue {
|
||||
return
|
||||
}
|
||||
onChange($0)
|
||||
@@ -122,7 +124,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.
|
||||
state = .cancelled
|
||||
stateBox.wrappedValue = .cancelled
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,7 +154,7 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
let onChange: (Database) -> Void
|
||||
var isChanged = false
|
||||
|
||||
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
|
||||
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
|
||||
self.region = region
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
@@ -154,7 +154,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)) }
|
||||
}
|
||||
|
||||
@@ -162,7 +162,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)) }
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
|
||||
@@ -121,6 +121,7 @@ public final class DatabaseSnapshotPool {
|
||||
/// `db` is used.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(_ db: Database, configuration: Configuration? = nil) throws {
|
||||
let path = db.path
|
||||
var configuration = Self.configure(configuration ?? db.configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
@@ -129,7 +130,7 @@ public final class DatabaseSnapshotPool {
|
||||
}
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
@@ -149,20 +150,18 @@ public final class DatabaseSnapshotPool {
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = db.path
|
||||
self.path = path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
makeElement: { [configuration] index in
|
||||
return try SerializedDatabase(
|
||||
path: db.path,
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
purpose: "snapshot.\(index)")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -210,17 +209,15 @@ public final class DatabaseSnapshotPool {
|
||||
self.path = path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
makeElement: { [configuration] index in
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
purpose: "snapshot.\(index)")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -291,7 +288,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
|
||||
@@ -329,7 +326,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
|
||||
|
||||
@@ -22,18 +22,18 @@ import Dispatch
|
||||
/// ### Writing into the Database
|
||||
///
|
||||
/// - ``write(_:)-76inz``
|
||||
/// - ``write(_:)-88g7e``
|
||||
/// - ``write(_:)-3db50``
|
||||
/// - ``writePublisher(receiveOn:updates:)``
|
||||
/// - ``writePublisher(receiveOn:updates:thenRead:)``
|
||||
/// - ``writeWithoutTransaction(_:)-4qh1w``
|
||||
/// - ``writeWithoutTransaction(_:)-tckw``
|
||||
/// - ``writeWithoutTransaction(_:)-5h4vs``
|
||||
/// - ``asyncWrite(_:completion:)``
|
||||
/// - ``asyncWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Exclusive Access to the Database
|
||||
///
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-7u4xw``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-1ctl7``
|
||||
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Reading from the Latest Committed Database State
|
||||
@@ -181,7 +181,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.
|
||||
///
|
||||
@@ -213,7 +213,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.
|
||||
@@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
|
||||
/// ``spawnConcurrentRead(_:)`` instead.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// Schedules read-only database operations for execution.
|
||||
@@ -340,7 +340,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 {
|
||||
@@ -426,8 +426,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 {
|
||||
@@ -557,7 +557,7 @@ extension DatabaseWriter {
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -608,7 +608,7 @@ extension DatabaseWriter {
|
||||
/// would happen while establishing the database access or committing
|
||||
/// the transaction.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func write<T: Sendable>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWrite(updates, completion: { _, result in
|
||||
continuation.resume(with: result)
|
||||
@@ -646,7 +646,9 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
@@ -698,8 +700,8 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: @Sendable @escaping (Database) throws -> T)
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T)
|
||||
async throws -> T
|
||||
{
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
@@ -801,9 +803,9 @@ extension DatabaseWriter {
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<Output>(
|
||||
public func writePublisher<Output: Sendable>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
updates: @escaping @Sendable (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
OnDemandFuture { fulfill in
|
||||
@@ -868,10 +870,10 @@ extension DatabaseWriter {
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
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
|
||||
where S: Scheduler, T: Sendable, Output: Sendable
|
||||
{
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWriteWithoutTransaction { db in
|
||||
@@ -885,7 +887,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!) } })
|
||||
}
|
||||
}
|
||||
@@ -941,11 +943,11 @@ extension Publisher where Failure == Error {
|
||||
///
|
||||
/// let count: Int = try futureCount.wait()
|
||||
/// ```
|
||||
public class DatabaseFuture<Value> {
|
||||
public class DatabaseFuture<Value: Sendable> {
|
||||
private var consumed = false
|
||||
private let _wait: () throws -> Value
|
||||
|
||||
init(_ wait: @escaping () throws -> Value) {
|
||||
init(_ wait: @escaping @Sendable () throws -> Value) {
|
||||
_wait = wait
|
||||
}
|
||||
|
||||
@@ -967,6 +969,28 @@ public class DatabaseFuture<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper class that builds a DatabaseFuture without compiler errors
|
||||
/// regarding concurrency.
|
||||
final class UnsafeDatabaseFutureBuilder<T: Sendable>: @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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased database writer.
|
||||
///
|
||||
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
|
||||
@@ -1003,7 +1027,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)
|
||||
}
|
||||
|
||||
@@ -1012,7 +1036,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)
|
||||
}
|
||||
|
||||
@@ -1023,7 +1047,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
@@ -1044,11 +1068,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)
|
||||
}
|
||||
|
||||
@@ -1056,11 +1080,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
base.concurrentRead(value)
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
base.spawnConcurrentRead(value)
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,10 @@
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
class WALSnapshotTransaction {
|
||||
private let reader: SerializedDatabase
|
||||
private let release: (_ isInsideTransaction: Bool) -> Void
|
||||
// nil when closed
|
||||
private var reader: SerializedDatabase?
|
||||
// nil when closed
|
||||
private var release: ((_ isInsideTransaction: Bool) -> Void)?
|
||||
|
||||
/// The state of the database at the beginning of the transaction.
|
||||
let walSnapshot: WALSnapshot
|
||||
@@ -58,21 +60,39 @@ class WALSnapshotTransaction {
|
||||
}
|
||||
|
||||
deinit {
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
close()
|
||||
}
|
||||
|
||||
/// Executes database operations in the snapshot transaction, and
|
||||
/// returns their result after they have finished executing.
|
||||
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
guard let reader else {
|
||||
throw DatabaseError.snapshotIsLost()
|
||||
}
|
||||
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
try reader.sync(value)
|
||||
return try reader.sync(value)
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and
|
||||
/// returns immediately.
|
||||
func asyncRead(_ value: @escaping (Database) -> Void) {
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
guard let reader else {
|
||||
value(.failure(DatabaseError.snapshotIsLost()))
|
||||
return
|
||||
}
|
||||
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
reader.async(value)
|
||||
reader.async { db in
|
||||
value(.success(db))
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
guard let reader, let release else { return }
|
||||
self.reader = nil
|
||||
self.release = nil
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
}
|
||||
|
||||
private static func commitAndRelease(
|
||||
|
||||
@@ -99,7 +99,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``.
|
||||
See ``DatabaseReader/read(_:)-7a20l`` and ``DatabaseWriter/write(_:)-3db50``.
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
|
||||
+30
-17
@@ -37,7 +37,7 @@ import Dispatch
|
||||
/// got 3
|
||||
final class Pool<T: Sendable>: Sendable {
|
||||
private class Item: @unchecked Sendable {
|
||||
// @unchecked because `isAvailable` is protected by `items`.
|
||||
// @unchecked because `isAvailable` is protected by `content`.
|
||||
let element: T
|
||||
var isAvailable: Bool
|
||||
|
||||
@@ -47,8 +47,19 @@ final class Pool<T: Sendable>: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
private let makeElement: @Sendable () throws -> T
|
||||
private let items: ReadWriteBox<[Item]> = ReadWriteBox(wrappedValue: [])
|
||||
private struct Content {
|
||||
var items: [Item]
|
||||
|
||||
/// The number of created items. May become greater than the number
|
||||
/// of elements in items, as some items are destroyed and other
|
||||
/// are created.
|
||||
var createdCount = 0
|
||||
}
|
||||
|
||||
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
|
||||
|
||||
private let makeElement: @Sendable (Int) throws -> T
|
||||
private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0))
|
||||
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
|
||||
private let itemsGroup: DispatchGroup // knows when no element is used
|
||||
private let barrierQueue: DispatchQueue
|
||||
@@ -60,11 +71,12 @@ final class Pool<T: Sendable>: Sendable {
|
||||
/// - maximumCount: The maximum number of elements.
|
||||
/// - qos: The quality of service of asynchronous accesses.
|
||||
/// - makeElement: A function that creates an element. It is called
|
||||
/// on demand.
|
||||
/// on demand. Its argument is the index of the created elements
|
||||
/// (1, then 2, etc).
|
||||
init(
|
||||
maximumCount: Int,
|
||||
qos: DispatchQoS = .unspecified,
|
||||
makeElement: @escaping @Sendable () throws -> T)
|
||||
makeElement: @escaping @Sendable (_ index: Int) throws -> T)
|
||||
{
|
||||
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
|
||||
self.makeElement = makeElement
|
||||
@@ -76,19 +88,20 @@ final class Pool<T: Sendable>: Sendable {
|
||||
|
||||
/// Returns a tuple (element, release)
|
||||
/// Client must call release(), only once, after the element has been used.
|
||||
func get() throws -> (element: T, release: @Sendable (PoolCompletion) -> Void) {
|
||||
func get() throws -> ElementAndRelease {
|
||||
try barrierQueue.sync {
|
||||
itemsSemaphore.wait()
|
||||
itemsGroup.enter()
|
||||
do {
|
||||
let item = try items.update { items -> Item in
|
||||
if let item = items.first(where: \.isAvailable) {
|
||||
let item = try content.update { content -> Item in
|
||||
if let item = content.items.first(where: \.isAvailable) {
|
||||
item.isAvailable = false
|
||||
return item
|
||||
} else {
|
||||
let element = try makeElement()
|
||||
content.createdCount += 1
|
||||
let element = try makeElement(content.createdCount)
|
||||
let item = Item(element: element, isAvailable: false)
|
||||
items.append(item)
|
||||
content.items.append(item)
|
||||
return item
|
||||
}
|
||||
}
|
||||
@@ -108,7 +121,7 @@ final class Pool<T: Sendable>: Sendable {
|
||||
///
|
||||
/// - important: The `execute` argument is executed in a serial dispatch
|
||||
/// queue, so make sure you use the element asynchronously.
|
||||
func asyncGet(_ execute: @escaping @Sendable (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
|
||||
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
|
||||
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
|
||||
// > We wait on the semaphore in the serial queue, which means that
|
||||
// > we’ll have at most one blocked thread when we reach maximum
|
||||
@@ -129,7 +142,7 @@ final class Pool<T: Sendable>: Sendable {
|
||||
}
|
||||
|
||||
private func release(_ item: Item, completion: PoolCompletion) {
|
||||
items.update { items in
|
||||
content.update { content in
|
||||
switch completion {
|
||||
case .reuse:
|
||||
// This is why Item is a class, not a struct: so that we can
|
||||
@@ -137,8 +150,8 @@ final class Pool<T: Sendable>: Sendable {
|
||||
item.isAvailable = true
|
||||
case .discard:
|
||||
// Discard should be rare: perform lookup.
|
||||
if let index = items.firstIndex(where: { $0 === item }) {
|
||||
items.remove(at: index)
|
||||
if let index = content.items.firstIndex(where: { $0 === item }) {
|
||||
content.items.remove(at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,8 +162,8 @@ final class Pool<T: Sendable>: Sendable {
|
||||
/// Performs a block on each pool element, available or not.
|
||||
/// The block is run is some arbitrary dispatch queue.
|
||||
func forEach(_ body: (T) throws -> Void) rethrows {
|
||||
try items.read { items in
|
||||
for item in items {
|
||||
try content.read { content in
|
||||
for item in content.items {
|
||||
try body(item.element)
|
||||
}
|
||||
}
|
||||
@@ -159,7 +172,7 @@ final class Pool<T: Sendable>: Sendable {
|
||||
/// Removes all elements from the pool.
|
||||
/// Currently used elements won't be reused.
|
||||
func removeAll() {
|
||||
items.update { $0.removeAll() }
|
||||
content.update { $0.items.removeAll() }
|
||||
}
|
||||
|
||||
/// Blocks until no element is used, and runs the `barrier` function before
|
||||
|
||||
@@ -352,10 +352,11 @@ extension ValueConcurrentObserver {
|
||||
let initialFetchTransaction = try result.get()
|
||||
// Second async jump because that's how
|
||||
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
|
||||
initialFetchTransaction.asyncRead { db in
|
||||
initialFetchTransaction.asyncRead { dbResult in
|
||||
do {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
let db = try dbResult.get()
|
||||
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
@@ -429,11 +430,9 @@ extension ValueConcurrentObserver {
|
||||
// checkpointed. That's why we'll keep `initialFetchTransaction`
|
||||
// alive until the comparison is done.
|
||||
//
|
||||
// However, we want to release `initialFetchTransaction` as soon as
|
||||
// However, we want to close `initialFetchTransaction` as soon as
|
||||
// possible, so that the reader connection it holds becomes
|
||||
// available for other reads. It will be released when this optional
|
||||
// is set to nil:
|
||||
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
|
||||
// available for other reads.
|
||||
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
let events = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
@@ -446,7 +445,7 @@ extension ValueConcurrentObserver {
|
||||
// Was the database modified since the initial fetch?
|
||||
let isModified: Bool
|
||||
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
|
||||
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
|
||||
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
|
||||
assert(ordering <= 0, "Unexpected snapshot ordering")
|
||||
isModified = ordering < 0
|
||||
} else {
|
||||
@@ -454,9 +453,9 @@ extension ValueConcurrentObserver {
|
||||
isModified = true
|
||||
}
|
||||
|
||||
// Comparison done: end the WAL snapshot transaction
|
||||
// Comparison done: close the WAL snapshot transaction
|
||||
// and release its reader connection.
|
||||
initialFetchTransaction = nil
|
||||
initialFetchTransaction.close()
|
||||
|
||||
if isModified {
|
||||
events.databaseDidChange?()
|
||||
|
||||
Reference in new issue
Block a user