SwiftConcurrency.md

This commit is contained in:
Gwendal Roué committed 2024-09-27 17:34:32 +02:00
1 parent 9b6a3b9ec6
commit 8dbce53ec5
1 file changed
+74 -73
+74 -73
View File
@@ -4,18 +4,18 @@ How to best integrate GRDB and Swift Concurrency
## Overview
GRDB’s primary goal is to leverage SQLite’s concurrency features, for the benefit of application developers. Swift 6 makes it possible to achieve this goal while ensuring data-race safety.
GRDB’s primary goal is to leverage SQLite’s concurrency features for the benefit of application developers. Swift 6 makes it possible to achieve this goal while ensuring data-race safety.
For example, the ``DatabasePool`` connection allows applications to read and display database values on screen, even while a background task is writing the results of a network request to disk.
For example, the ``DatabasePool`` connection allows applications to fetch and display database values on screen, even while a background task is writing the results of a network request to disk.
Application previews and tests prefer to use an in-memory ``DatabaseQueue`` connection, which avoids writing to disk. For examples of such an integration, see the [demo apps].
Application previews and tests prefer to use an in-memory ``DatabaseQueue`` connection.
Both connection types provide identical database accesses through closures, as shown with the `db` argument below:
Both connection types provide the same database access methods:
```swift
// Read
let player = try await writer.read { db in
try Player.find(db, id: 42)
let playerCount = try await writer.read { db in
try Player.fetchCount(db)
}
// Write
@@ -24,7 +24,7 @@ let newPlayerCount = try await writer.write { db in
return try Player.fetchCount(db)
}
// Observe the database
// Observe database changes
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
@@ -33,9 +33,11 @@ for try await players in observation.values(in: writer) {
}
```
GRDB optimally schedules those database access closures, in the best interest of the application. With a `DatabaseQueue`, all accesses are serialized. With a `DatabasePool`, reads and writes can occur in parallel, improving throughput. The differences between these two modes are minimized by the common ``DatabaseWriter`` protocol, which provides the runtime guarantees described in the <doc:Concurrency> guide.
`DatabaseQueue` serializes all database accesses, when `DatabasePool` allows parallel reads and writes. The common ``DatabaseWriter`` protocol provides the [SQLite isolation guarantees](https://www.sqlite.org/isolation.html) that abstract away the differences between the two connection types, without sacrificing data integrity. See the <doc:Concurrency> guide for more information.
Depending of the language mode and level of concurrency checkings used by your application (see [Migrating to Swift 6]), you may see warnings or errors. We will address these issues, and provide general guidance in the following sections.
All safety guarantees of Swift 6 are enforced during database accesses. They are controlled by the language mode and level of concurrency checkings used by your application, as described in [Migrating to Swift 6] on swift.org.
The following sections describe, with more details, how GRDB interacts with Swift Concurrency.
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Shorthand-Closure-Notation>
@@ -44,11 +46,12 @@ Depending of the language mode and level of concurrency checkings used by your a
### Non-Sendable Record Types
#### The problem
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-Sendable type such as record *classes*:
By default, Swift classes are not Sendable. They are not thread-safe. With GRDB, record classes will typically trigger compiler diagnostics:
```swift
// A non-Sendable record type
final class Player: Codable, Identifiable {
var id: Int64
var name: String
@@ -78,7 +81,7 @@ let observation = ValueObservation.tracking { db in
The solution is to have the record type conform to `Sendable`.
The easiest way to do so is to replace classes, which are difficult to make `Sendable`, with structs composed of `Sendable` properties:
Since classes are difficult to make `Sendable`, the easiest way to is to replace classes with structs composed of `Sendable` properties:
```swift
// This struct is Sendable
@@ -93,67 +96,69 @@ extension Player: FetchableRecord, PersistableRecord { }
You do not need to perform this refactoring right away: you can compile your application in the Swift 5 language mode, with minimal concurrency checkings. Take your time, and only when your application is ready, enable strict concurrency checkings or the Swift 6 language mode.
#### FAQ
#### FAQ: My application defines record classes, because…
> Question: **Can I mark my record classes as `@unchecked Sendable`?**
>
> **Answer**: This is a bad idea, because all humans and machines who will read your code will think that the class is thread-safe, when it is actually not. Instead, use the Swift 5 language mode, with minimal concurrency checkings, until your code is refactored.
- **Question: My record types are subclasses of the built-in GRDB `Record` class.**
Consider refactoring them as structs. The ``Record`` class was present in GRDB 1.0, in 2017. It has served its purpose. It is not `Sendable`, and its use is actively discouraged since GRDB 7.
> Question: **I can use locks to make my class safely Sendable.**
>
> **Answer**: Indeed you can put a lock on the whole instance, or on each individual property, or on multiple subgroups of properties, as needed. But structs are simpler, because they do not need locks and the compiler does all the hard work for you.
- **Question: I need a hierarchy of record classes because I use inheritance.**
It should be possible to refactor the class hiearchy with Swift protocols. See <doc:RecordTimestamps> for a practical example. Protocols make it possible to define records as structs.
> Question: **My record types are subclasses of the built-in GRDB `Record` class.**
>
> **Answer**: The ``Record`` class was present in GRDB 1.0, in 2017. It has served its purpose. It is not `Sendable`, and its use is actively discouraged since GRDB 7.
- **Question: I use the `@Observable` macro for my record types, and this macro requires a class.**
> Question: **I need a hierarchy of record classes because I use inheritance.**
>
> **Answer**: It should be possible to refactor the class hiearchy with Swift protocols. See for example <doc:RecordTimestamps> for an example of a protocol that grants database timestamps features.
A possible solution is to define two types: an `@Observable` class that drives your SwiftUI views, and a plain record struct for database work. An indirect advantage is that you will be able to make them evolve independently.
> Question: **I use the `@Observable` macro for my record types, and this macro requires a class.**
>
> **Answer**: Your solution is to define two types: an `@Observable` one that drives your SwiftUI views, and a plain record struct for database work. An indirect advantage is that you will be able to make them evolve independently.
- **Question: I use classes instead of structs because I monitored my application and classes have a lower CPU/memory footprint.**
Now that's tricky. Please do not think the `Sendable` requirement is a whim: see the following questions.
> Question: **I use classes instead of structs because I monitored my application and classes have a lower CPU/memory footprint.**
>
> **Answer**: Pick your poison: refactor those classes into structs, or make them Sendable, or avoid raising the Swift concurrency checkings. Please do not think the `Sendable` requirement is a whim: see the next question.
#### FAQ: How to make classes Sendable?
> Question: **Can I wait until GRDB learns how to deal with non-Sendable record types?**
>
> **Answer**: This can't happen without new features in the Swift language and the SDKs.
>
> [SE-0430: `sending` parameter and result values](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0430-transferring-parameters-and-results.md) looks like the language feature we need, but:
>
> - `DispatchQueue.async` does not accept a `sending` closure. GRDB needs this in order to accept non-Sendable records to be sent to the database, as below:
>
> ```swift
> let nonSendableRecord: Player
> try await writer.write { db in
> try nonSendableRecord.insert(db)
> }
> ```
>
> Please [file a feedback](http://feedbackassistant.apple.com) for requesting this DispatchQueue improvement. The more the merrier. I personally filed FB15270949.
>
> - Database access methods taint the values they fetch, making it impossible to "send" them back to the caller.
>
> In the code below, the `db` argument is not Sendable, on purpose. It taints the fetched player, according to the rules of [SE-0414: Region based Isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md), and has the compiler refuse that the player crosses isolation domains, back to the caller:
>
> ```swift
> let player = try await writer.read { db in
> try Player.fetchOne(db, id: 42)
> }
> ```
>
> The compiler diagnostic is correct: one can copy the `db` argument into the fetched `Player` instance. Doing so is a programmer error, though: GRDB promptly raises a fatal error whenever that copied `db` is later used. In practice, nobody does that. But there is no way to tell the compiler about this practice.
>
> For all those reasons, which are entirely beyond our control, GRDB has to require values that are asynchronously written and read from the database to be `Sendable`.
- **Question: Can I mark my record classes as `@unchecked Sendable`?**
Take care that all humans and machines who will read your code will think that the class is thread-safe, so make sure it really is. See the following questions.
- **Question: I can use locks to make my class safely Sendable.**
You can indeed put a lock on the whole instance, or on each individual property, or on multiple subgroups of properties, as needed by your application. Remember that structs are simpler, because they do not need locks and the compiler does all the hard work for you.
- **Question: Can I make my record classes immutable?**
Yes. Classes that can not be modified, made of constant `let` properties, are Sendable. Those immutable classes will not make it easy to modify the database, though.
#### FAQ: Why this Sendable requirement?
**GRDB needs new features in the Swift language and the SDKs in order to deal with non-Sendable types.**
[SE-0430: `sending` parameter and result values](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0430-transferring-parameters-and-results.md) looks like the language feature we need, but:
- `DispatchQueue.async` does not accept a `sending` closure. GRDB needs this in order to accept non-Sendable records to be sent to the database, as below:
```swift
let nonSendableRecord: Player
try await writer.write { db in
try nonSendableRecord.insert(db)
}
```
Please [file a feedback](http://feedbackassistant.apple.com) for requesting this DispatchQueue improvement. The more the merrier. I personally filed FB15270949.
- Database access methods taint the values they fetch. In the code below, the rules of [SE-0414: Region based Isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md) have the compiler refuse that the fetched player is sent back to the caller:
```swift
let player = try await writer.read { db in
try Player.fetchOne(db, id: 42)
}
```
Strictly speaking, the compiler diagnostic is correct: one could copy the non-Sendable `db` argument into the fetched `Player` instance, making it unsuitable for later use. In practice, nobody does that. Copying `db` is a programmer error, and GRDB promptly raises a fatal error whenever a `db` copy would be improperly used. But there is no way to tell the compiler about this practice.
For all those reasons, GRDB has to require values that are asynchronously written and read from the database to be `Sendable`.
### Shorthand Closure Notation
#### The problem
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
```swift
@@ -168,9 +173,7 @@ let count = try await writer.read { db in
let count = try await writer.read(Player.fetchCount)
```
#### The solution
You can remove this warning by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
- **Using Xcode**
@@ -178,7 +181,7 @@ You can remove this warning by enabling [SE-0418: Inferring `Sendable` for metho
- **In a SwiftPM package manifest**
Enable the "InferSendableFromCaptures" upcoming feature:
Enable the `InferSendableFromCaptures` upcoming feature:
```swift
.target(
@@ -193,8 +196,6 @@ This language feature is not enabled by default, because it can potentially [aff
### Non-Sendable Configuration of Record Types
#### The problem
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
```swift
@@ -208,9 +209,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
}
```
#### The solution
Replace the stored property with a computed property:
**To fix this error**, replace the stored property with a computed property:
```swift
extension Player: FetchableRecord, MutablePersistableRecord {
@@ -232,7 +231,9 @@ try writer.write { ... }
await try writer.write { ... }
```
**It is a good idea to prefer the asynchronous version whenever the application accesses the database from Swift tasks.** This is not a hard requirement, because performing synchronous database accesses from tasks is not incorrect. But this may slow down other tasks that run on the cooperative thread pool.
Synchronous accesses are handy. They avoid introducing undesired delays, flashes of missing content in the user interface, or `async` functions. There is no problem performing fast database accesses synchronously, even from the main thread.
**It is a good idea to prefer the asynchronous version (`await`) whenever the application accesses the database from Swift tasks.** This is not a hard requirement, because performing synchronous database accesses from tasks is not incorrect. The only problem is that other tasks may have to wait until datababase accesses are completed. When you `await` for database accesses, this problem does not happen.
In many occasions, the compiler will guide you. In the sample code below, the compiler requires the `await` keyword: