Skip to content

Commit 149f9a9

Browse files
taplinclaude
andcommitted
Phase 4: Codable BSON, typed collection API, async/await
- BSONEncoder/BSONDecoder over libbson: Date, Data, UUID and BSON.OID keep native BSON types; exact numeric conversions; descriptive errors - Typed, throwing collection methods: insert, insert(contentsOf:), find, findOne, replaceOne, updateOne/Many, deleteOne/Many, countDocuments - MongoError for the throwing API - MongoClientPool is final and Sendable; withClient runs blocking work on a dedicated queue (same design as Perfect-CRUD's withCRUDExecutor) - pool.find returns MongoFindSequence, an AsyncSequence that holds one pooled client per iteration and decodes in batches - 9 new tests (35 total); Phase 4 tests pass under Thread Sanitizer - README and modernization plan updated Existing API unchanged; nothing deprecated yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 46e77c5 commit 149f9a9

8 files changed

Lines changed: 1599 additions & 10 deletions

File tree

‎Documentation/modernization-plan.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Perfect-MongoDB modernization plan
22

3-
Status: **Phases 1 and 2 done (2026-09-27), except the Atlas/TLS check.** All 26 tests pass against MongoDB 8.3 locally and in CI on Linux (Swift 6.4, MongoDB 8, libmongoc 2.5.5 built from source). Captured 2026-09-27 from a research session so work can be picked up later on a laptop.
3+
Status: **Phases 1, 2 and 4 done (Phase 4 on 2026-09-29), except the Atlas/TLS check.** 35 tests pass against MongoDB 8.3 locally. The 26 from Phases 1-2 also pass in CI on Linux (Swift 6.4, MongoDB 8, libmongoc 2.5.5 built from source). Captured 2026-09-27 from a research session so work can be picked up later on a laptop.
44

55
Decision on 2026-09-27: **target libmongoc 2.x only.** Homebrew's `mongo-c-driver` is now 2.x; 1.x survives only as the deprecated, keg-only `mongo-c-driver@1`, which Homebrew disables on 2027-04-01. Phase 3's 2.x work was therefore folded into Phase 1. The catch: Linux distributions that still ship 1.x (Ubuntu's `libmongoc-dev` is 1.26) need libmongoc 2 built from source until they package it.
66

@@ -87,11 +87,14 @@ Phase 1 behaviour changes:
8787
Folded into Phase 1: the package now targets 2.x only. Linux CI builds libmongoc 2 from source (Phase 2).
8888

8989
### Phase 4: Swift-native API (added alongside the old one)
90-
- [ ] Ownership and `Sendable`: the pool is the only object shared across threads; clients, collections and cursors belong to one task.
91-
- [ ] `async` versions of the blocking calls, running on a dedicated executor like Perfect-CRUD's `AsyncExecution.swift` / `Pool.swift`.
92-
- [ ] `Codable` encode/decode for `BSON`. The archived `mongo-swift-driver` (Apache-2.0) has a working implementation to adapt.
93-
- [ ] `AsyncSequence` cursor.
94-
- [ ] Deprecate, don't remove, old methods that the new ones replace.
90+
- [x] Ownership and `Sendable`: `MongoClientPool` is `final` and `@unchecked Sendable`, since libmongoc's pool is thread-safe. It's the only shared object. Clients, collections and cursors stay non-`Sendable` and are used by one piece of work at a time. `BSON.OID`, `BSONEncoder`, `BSONDecoder` and the new `MongoError` are `Sendable`.
91+
- [x] async (`MongoAsync.swift`): `pool.withClient { client in ... }` pops a client, runs the body on a dedicated concurrent `DispatchQueue` behind a checked continuation, and pushes the client back even on throw. That's the same design as Perfect-CRUD's `withCRUDExecutor`. There are no per-method `async` overloads, so nothing collides with the sync names.
92+
- [x] Codable (`BSONCodable.swift`): `BSONEncoder`/`BSONDecoder` read and write libbson directly through an intermediate tree. I wrote them fresh rather than porting `mongo-swift-driver`, which is built on its own pure-Swift BSON type. `Date` maps to datetime, `Data` to binary, `UUID` to binary subtype 4 and `BSON.OID` to ObjectId. `Int` and 64-bit integers become int64, smaller integers int32. Decoding accepts any BSON number that converts exactly. Unsupported BSON types (decimal128, regex, timestamp) throw a descriptive `typeMismatch`. `BSON.OID` is also `Codable` as its hex string for other coders.
93+
- [x] Typed collection API (`MongoCollectionCodable.swift`): `insert(_:)`, `insert(contentsOf:)`, `find(_:filter:options:)`, `findOne`, `replaceOne`, `updateOne`, `updateMany`, `deleteOne`, `deleteMany`, `countDocuments`. They throw `MongoError` or `DecodingError` and use the `*_with_opts` APIs directly.
94+
- [x] `AsyncSequence` cursor: `pool.find(User.self, database:collection:filter:options:batchSize:)` returns `MongoFindSequence`. One pooled client is held per iteration, documents are fetched and decoded in batches (default 100) per hop to the blocking queue, cancellation is checked between batches, and the client goes back to the pool when the loop ends, throws or breaks early. This is safe here but wasn't in Perfect-CRUD, because a libmongoc client can move between threads as long as only one uses it at a time.
95+
- [x] Tests (`Phase4Tests.swift`, 9 tests): Codable round trip over every supported type, native BSON types in the output, numeric conversions and errors, typed CRUD, duplicate-key `MongoError`, 20 concurrent `withClient` tasks on a 4-client pool, and the find sequence (250 docs, early break releasing clients, decoding errors). Also passes under Thread Sanitizer; only the Swift code is instrumented, not libmongoc.
96+
- Decision: **no deprecations yet.** The typed API is a parallel layer rather than a one-for-one replacement, and deprecating the old calls now would flood existing users with warnings before anyone has used the new ones. Revisit once the community requesters have tried it.
97+
- [ ] Not done, and worth doing on request: change streams (`watch`), aggregation into Codable types, transactions/sessions, and an async GridFS.
9598

9699
## Open questions
97100

‎README.md‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,38 @@ if let cursor = users.find(query: try BSON(json: #"{"age": {"$gt": 30}}"#)) {
6969
}
7070
```
7171

72-
For concurrent use, pop clients from a `MongoClientPool` rather than sharing one `MongoClient`.
72+
### Codable and async/await
73+
74+
`BSONEncoder` and `BSONDecoder` map `Codable` types to BSON documents, keeping dates, binary data, UUIDs and
75+
ObjectIds as native BSON types. Collections have typed, throwing methods built on them. For concurrency,
76+
share one `MongoClientPool`. `withClient` runs blocking driver work off Swift's cooperative thread pool,
77+
and `find` streams results as an `AsyncSequence`:
78+
79+
```swift
80+
struct User: Codable, Sendable {
81+
var _id: BSON.OID
82+
var name: String
83+
var age: Int
84+
var joined: Date
85+
}
86+
87+
let pool = MongoClientPool(uri: "mongodb://localhost")
88+
89+
try await pool.withClient { client in
90+
let users = client.getCollection(databaseName: "app", collectionName: "users")
91+
try users.insert(User(_id: BSON.OID(), name: "Ada", age: 36, joined: Date()))
92+
try users.updateOne(filter: try BSON(json: #"{"name": "Ada"}"#),
93+
update: try BSON(json: #"{"$inc": {"age": 1}}"#))
94+
}
95+
96+
for try await user in pool.find(User.self, database: "app", collection: "users",
97+
filter: try BSON(json: #"{"age": {"$gt": 30}}"#)) {
98+
print(user.name)
99+
}
100+
```
101+
102+
A `MongoClient` and the collections and cursors made from it are not thread-safe: use each from one task at
103+
a time, which `withClient` and `find` do for you.
73104

74105
## Testing
75106

‎Sources/PerfectMongoDB/BSON.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,7 @@ public class BSON: CustomStringConvertible {
536536
}
537537

538538
/// Represents a BSON OID.
539-
public struct OID: CustomStringConvertible {
539+
public struct OID: CustomStringConvertible, Sendable {
540540
var oid: bson_oid_t
541541
public var description: String {
542542
let up = UnsafeMutablePointer<Int8>.allocate(capacity: 25)

0 commit comments

Comments
 (0)