-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathClientSession.swift
537 lines (499 loc) · 22.3 KB
/
ClientSession.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import CLibMongoC
import Foundation
import NIO
// sourcery: skipSyncExport
/**
* A MongoDB client session.
* This class represents a logical session used for ordering sequential operations.
*
* To create a client session, use `startSession` or `withSession` on a `MongoClient`.
*
* If `causalConsistency` is not set to `false` when starting a session, read and write operations that use the session
* will be provided causal consistency guarantees depending on the read and write concerns used. Using "majority"
* read and write preferences will provide the full set of guarantees. See
* https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/#sessions for more details.
*
* e.g.
* ```
* let opts = MongoCollectionOptions(readConcern: .majority, writeConcern: .majority)
* let collection = database.collection("mycoll", options: opts)
* let futureCount = client.withSession { session in
* collection.insertOne(["x": 1], session: session).flatMap { _ in
* collection.countDocuments(session: session)
* }
* }
* ```
*
* To disable causal consistency, set `causalConsistency` to `false` in the `ClientSessionOptions` passed in to either
* `withSession` or `startSession`.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/#sessions
* - https://docs.mongodb.com/manual/core/causal-consistency-read-write-concerns/
*/
public final class ClientSession {
/// Error thrown when an inactive session is used.
internal static let SessionInactiveError = MongoError.LogicError(message: "Tried to use an inactive session")
/// Error thrown when a user attempts to use a session with a client it was not created from.
internal static let ClientMismatchError = MongoError.InvalidArgumentError(
message: "Sessions may only be used with the client used to create them"
)
/// Enum for tracking the state of a session.
private enum State {
/// Indicates that this session has not been used yet and a corresponding `mongoc_client_session_t` has not
/// yet been created. If the user sets operation time or cluster time prior to using the session, those values
/// are stored here so they can be set upon starting the session.
case notStarted(opTime: BSONTimestamp?, clusterTime: BSONDocument?)
/// Indicates that the session has been started and a corresponding `mongoc_client_session_t` exists. Stores a
/// pointer to the underlying `mongoc_client_session_t` and the source `Connection` for this session.
case started(session: OpaquePointer, connection: Connection)
/// Indicates that the session has been ended.
case ended
/**
* If this `State` is `.started`, does the necessary work to asynchronously clean up the underlying libmongoc
* session. If the `State` is not started, this method will return a succeeded future.
* This method accepts the corresponding `ClientSession`'s parent `MongoClient` and `EventLoop` in order to
* allow the `State` and its stored references to outlive the session itself. This is necessary so that we
* don't return the stored `Connection` to the pool until session cleanup (which uses it) is complete.
* Note this method does _not_ mutate `State`; it is the responsibility of the caller to update
* `ClientSession.state` if needed for bookkeeping once the returned future is fulfilled.
* We can't mutate `self` here directly because we would have to do so in an escaping closure (the call to
* `execute`) which the compiler won't allow.
*/
fileprivate func cleanup(using client: MongoClient, on eventLoop: EventLoop?) -> EventLoopFuture<Void> {
switch self {
case .notStarted, .ended:
return client.operationExecutor.makeSucceededFuture((), on: eventLoop)
case let .started(session, connection):
return client.operationExecutor.execute(on: eventLoop) {
// reference the connection so it stays alive at least until the session is done being cleaned up.
// this is required by libmongoc; we can't put the `mongoc_client_t` back in its pool until all
// sessions created from it have been destroyed.
withExtendedLifetime(connection) {
mongoc_client_session_destroy(session)
}
}
}
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
@available(macOS 10.15.0, *)
fileprivate func cleanup(using client: MongoClient, on eventLoop: EventLoop?) async throws {
try await self.cleanup(using: client, on: eventLoop).get()
}
#endif
}
/// Indicates the state of this session.
private var state: State
/// Returns whether this session is in the `started` state.
internal var active: Bool {
if case .started = self.state {
return true
}
return false
}
/// The client used to start this session.
public let client: MongoClient
/// The session ID of this session. This is internal for now because we only have a value available after we've
/// started the libmongoc session.
internal var id: BSONDocument?
/// The `EventLoop` this `ClientSession` is bound to.
public let eventLoop: EventLoop?
/// The server ID of the mongos this session is pinned to.
private var serverID: UInt32? {
switch self.state {
case .notStarted, .ended:
return nil
case let .started(session, _):
let id = mongoc_client_session_get_server_id(session)
guard id != 0 else {
return nil
}
return id
}
}
/// The address of the mongos this session is pinned to, if any.
internal var pinnedServerAddress: ServerAddress? {
guard let serverID = self.serverID, case let .started(_, connection) = self.state else {
return nil
}
return connection.withMongocConnection { client in
guard let sd = mongoc_client_get_server_description(client, serverID) else {
return nil
}
defer { mongoc_server_description_destroy(sd) }
let serverDescription = ServerDescription(sd)
return serverDescription.address
}
}
/// Enum tracking the state of the transaction associated with this session.
internal enum TransactionState: String, Decodable {
/// There is no transaction in progress.
case none
/// A transaction has been started, but no operation has been sent to the server.
case starting
/// A transaction is in progress.
case inProgress = "in_progress"
/// The transaction was committed.
case committed
/// The transaction was aborted.
case aborted
fileprivate var mongocTransactionState: mongoc_transaction_state_t {
switch self {
case .none:
return MONGOC_TRANSACTION_NONE
case .starting:
return MONGOC_TRANSACTION_STARTING
case .inProgress:
return MONGOC_TRANSACTION_IN_PROGRESS
case .committed:
return MONGOC_TRANSACTION_COMMITTED
case .aborted:
return MONGOC_TRANSACTION_ABORTED
}
}
fileprivate init(mongocTransactionState: mongoc_transaction_state_t) {
switch mongocTransactionState {
case MONGOC_TRANSACTION_NONE:
self = .none
case MONGOC_TRANSACTION_STARTING:
self = .starting
case MONGOC_TRANSACTION_IN_PROGRESS:
self = .inProgress
case MONGOC_TRANSACTION_COMMITTED:
self = .committed
case MONGOC_TRANSACTION_ABORTED:
self = .aborted
default:
fatalError("Unexpected transaction state: \(mongocTransactionState)")
}
}
}
/// The transaction state of this session.
internal var transactionState: TransactionState {
switch self.state {
case .notStarted, .ended:
return .none
case let .started(session, _):
return TransactionState(mongocTransactionState: mongoc_client_session_get_transaction_state(session))
}
}
/// Indicates whether or not the session is in a transaction.
internal var inTransaction: Bool {
self.transactionState != .none
}
/// The most recent cluster time seen by this session. This value will be nil if either of the following are true:
/// - No operations have been executed using this session and `advanceClusterTime` has not been called.
/// - This session has been ended.
public var clusterTime: BSONDocument? {
switch self.state {
case let .notStarted(_, clusterTime):
return clusterTime
case let .started(session, _):
guard let time = mongoc_client_session_get_cluster_time(session) else {
return nil
}
return BSONDocument(copying: time)
case .ended:
return nil
}
}
/// The operation time of the most recent operation performed using this session. This value will be nil if either
/// of the following are true:
/// - No operations have been performed using this session and `advanceOperationTime` has not been called.
/// - This session has been ended.
public var operationTime: BSONTimestamp? {
switch self.state {
case let .notStarted(opTime, _):
return opTime
case let .started(session, _):
var timestamp: UInt32 = 0
var increment: UInt32 = 0
mongoc_client_session_get_operation_time(session, ×tamp, &increment)
guard timestamp != 0 && increment != 0 else {
return nil
}
return BSONTimestamp(timestamp: timestamp, inc: increment)
case .ended:
return nil
}
}
/// The options used to start this session.
public let options: ClientSessionOptions?
/// Initializes a new client session.
internal init(client: MongoClient, eventLoop: EventLoop?, options: ClientSessionOptions? = nil) {
self.options = options
self.client = client
self.eventLoop = eventLoop
self.state = .notStarted(opTime: nil, clusterTime: nil)
}
/// Starts this session's corresponding libmongoc session, if it has not been started already. Throws an error if
/// this session has already been ended.
internal func startIfNeeded() -> EventLoopFuture<Void> {
switch self.state {
case let .notStarted(opTime, clusterTime):
let operation = StartSessionOperation(session: self)
return self.client.operationExecutor.execute(
operation,
client: self.client,
on: self.eventLoop,
session: nil
)
.map { sessionPtr, connection in
self.state = .started(session: sessionPtr, connection: connection)
// if we cached opTime or clusterTime, set them now
if let opTime = opTime {
self.advanceOperationTime(to: opTime)
}
if let clusterTime = clusterTime {
self.advanceClusterTime(to: clusterTime)
}
// swiftlint:disable:next force_unwrapping
self.id = BSONDocument(copying: mongoc_client_session_get_lsid(sessionPtr)!) // never returns nil
}
case .started:
return self.client.operationExecutor.makeSucceededFuture((), on: self.eventLoop)
case .ended:
return self.client.operationExecutor.makeFailedFuture(
ClientSession.SessionInactiveError,
on: self.eventLoop
)
}
}
/// Retrieves this session's underlying connection. Throws an error if the provided client was not the client used
/// to create this session, or if this session has not been started yet, or if this session has already been ended.
internal func getConnection(forUseWith client: MongoClient) throws -> Connection {
guard case let .started(_, connection) = self.state else {
throw ClientSession.SessionInactiveError
}
guard self.client == client else {
throw ClientSession.ClientMismatchError
}
return connection
}
internal func withMongocSession<T>(body: (OpaquePointer) throws -> T) throws -> T {
switch self.state {
case .notStarted:
throw MongoError.InternalError(message: "mongoc session was unexpectedly not started")
case let .started(session, _):
return try body(session)
case .ended:
throw ClientSession.SessionInactiveError
}
}
internal func isDirty() -> Bool {
switch self.state {
case .notStarted, .ended:
return false
case let .started(session, _):
return mongoc_client_session_get_dirty(session)
}
}
/**
* Ends this `ClientSession`. Call this method when you are finished using the session. You must ensure that all
* operations using this session have completed before calling this. You must ensure to hold a reference to this
* session until the returned future is fulfilled, and the future must be fulfilled before the session's parent
* `MongoClient` is closed.
*
* Note: on Swift versions and platforms where structured concurrency is available, this method will be called
* automatically upon deinitialization and does not need to be called by the user.
*/
public func end() -> EventLoopFuture<Void> {
self.state.cleanup(using: self.client, on: self.eventLoop).map { res in
self.state = .ended
return res
}
}
/// Cleans up internal state.
deinit {
#if compiler(>=5.5.2) && canImport(_Concurrency)
if #available(macOS 10.15, *) {
// Pull out all necessary values into new references to avoid referencing `self` within the `Task`, since
// the `Task` is going to outlive `self`.
switch self.state {
case .notStarted, .ended:
return
case .started:
let state = self.state
let client = self.client
let el = self.eventLoop
_ = Task {
try await state.cleanup(using: client, on: el)
// it might seem like we should make `state` mutable and mark it as `ended` here, however `state`
// is our own copy of the state no one else has access to or could inspect so there is no need to
// update it for bookkeeping purposes. also, we would then need to make a mutable copy of the state
// within the task here as the compiler won't allow us to mutate a variable declared outside the
// task.
}
}
return
}
#endif
guard case .ended = self.state else {
assertionFailure("ClientSession was not ended before going out of scope; please call ClientSession.end()")
return
}
}
/**
* Advances the clusterTime for this session to the given time, if it is greater than the current clusterTime. If
* the session has been ended, or if the provided clusterTime is less than the current clusterTime, this method has
* no effect.
*
* - Parameters:
* - clusterTime: The session's new cluster time, as a `BSONDocument` like `["cluster time": Timestamp(...)]`
*/
public func advanceClusterTime(to clusterTime: BSONDocument) {
switch self.state {
case let .notStarted(opTime, _):
self.state = .notStarted(opTime: opTime, clusterTime: clusterTime)
case let .started(session, _):
clusterTime.withBSONPointer { ptr in
mongoc_client_session_advance_cluster_time(session, ptr)
}
case .ended:
return
}
}
/**
* Advances the operationTime for this session to the given time if it is greater than the current operationTime.
* If the session has been ended, or if the provided operationTime is less than the current operationTime, this
* method has no effect.
*
* - Parameters:
* - operationTime: The session's new operationTime
*/
public func advanceOperationTime(to operationTime: BSONTimestamp) {
switch self.state {
case let .notStarted(_, clusterTime):
self.state = .notStarted(opTime: operationTime, clusterTime: clusterTime)
case let .started(session, _):
mongoc_client_session_advance_operation_time(session, operationTime.timestamp, operationTime.increment)
case .ended:
return
}
}
/// Appends this provided session to an options document for libmongoc interoperability.
/// - Throws:
/// - `MongoError.LogicError` if this session is inactive
internal func append(to doc: inout BSONDocument) throws {
guard case let .started(session, _) = self.state else {
throw ClientSession.SessionInactiveError
}
guard let bson = bson_new() else {
fatalError("failed to allocate bson_t")
}
defer { bson_destroy(bson) }
var error = bson_error_t()
guard mongoc_client_session_append(session, bson, &error) else {
throw extractMongoError(error: error)
}
let sessionDoc = BSONDocument(copying: bson)
// key that libmongoc uses to store the client session id in options documents
doc["sessionId"] = sessionDoc["sessionId"]
}
/**
* Starts a multi-document transaction for all subsequent operations in this session.
*
* Any options provided in `options` will override the default transaction options for this session and any options
* inherited from `MongoClient`.
*
* Operations executed as part of the transaction will use the options specified on the transaction, and those
* options cannot be overridden at a per-operation level. Any options that overlap with the transaction options
* which can be specified at a per operation level (e.g. write concern) _will be ignored_ if specified. This
* includes options specified at the database or collection level on the object used to execute an operation.
*
* The transaction must be completed with `commitTransaction` or `abortTransaction`. An in-progress transaction is
* automatically aborted when `ClientSession.end()` is called.
*
* - Parameters:
* - options: The options to use when starting this transaction
*
* - Returns:
* An `EventLoopFuture<Void>` that succeeds when `startTransaction` is successful.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.LogicError` if the session already has an in-progress transaction.
* - `MongoError.LogicError` if `startTransaction` is called on an ended session.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/transactions/
*/
public func startTransaction(options: TransactionOptions? = nil) -> EventLoopFuture<Void> {
switch self.state {
case .notStarted, .started:
let operation = StartTransactionOperation(options: options)
return self.client.operationExecutor.execute(
operation,
client: self.client,
on: self.eventLoop,
session: self
)
case .ended:
return self.client.operationExecutor.makeFailedFuture(
ClientSession.SessionInactiveError,
on: self.eventLoop
)
}
}
/**
* Commits a multi-document transaction for this session. Server and network errors are not ignored.
*
* - Returns:
* An `EventLoopFuture<Void>` that succeeds when `commitTransaction` is successful.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.LogicError` if the session has no in-progress transaction.
* - `MongoError.LogicError` if `commitTransaction` is called on an ended session.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/transactions/
*/
public func commitTransaction() -> EventLoopFuture<Void> {
switch self.state {
case .notStarted, .started:
let operation = CommitTransactionOperation()
return self.client.operationExecutor.execute(
operation,
client: self.client,
on: self.eventLoop,
session: self
)
case .ended:
return self.client.operationExecutor.makeFailedFuture(
ClientSession.SessionInactiveError,
on: self.eventLoop
)
}
}
/**
* Aborts a multi-document transaction for this session. Server and network errors are ignored.
*
* - Returns:
* An `EventLoopFuture<Void>` that succeeds when `abortTransaction` is successful.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.LogicError` if the session has no in-progress transaction.
* - `MongoError.LogicError` if `abortTransaction` is called on an ended session.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/transactions/
*/
public func abortTransaction() -> EventLoopFuture<Void> {
switch self.state {
case .notStarted, .started:
let operation = AbortTransactionOperation()
return self.client.operationExecutor.execute(
operation,
client: self.client,
on: self.eventLoop,
session: self
)
case .ended:
return self.client.operationExecutor.makeFailedFuture(
ClientSession.SessionInactiveError,
on: self.eventLoop
)
}
}
}