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
use std::time::{Duration, Instant};
use crate::{
action::{action_impl, AbortTransaction, CommitTransaction, StartTransaction},
bson_util::round_clamp,
client::options::TransactionOptions,
error::{
Error,
ErrorKind,
Result,
TRANSIENT_TRANSACTION_ERROR,
UNKNOWN_TRANSACTION_COMMIT_RESULT,
},
operation::{self, Operation},
sdam::TransactionSupportStatus,
BoxFuture,
ClientSession,
};
use super::TransactionState;
const MAX_CONVENIENT_TRANSACTION_TIME: Duration = Duration::from_secs(120);
impl ClientSession {
async fn start_transaction_impl(&mut self, options: Option<TransactionOptions>) -> Result<()> {
if self
.options
.as_ref()
.and_then(|o| o.snapshot)
.unwrap_or(false)
{
return Err(ErrorKind::Transaction {
message: "Transactions are not supported in snapshot sessions".into(),
}
.into());
}
match self.transaction.state {
TransactionState::Starting | TransactionState::InProgress => {
return Err(ErrorKind::Transaction {
message: "transaction already in progress".into(),
}
.into());
}
TransactionState::Committed { .. } => {
self.unpin(); // Unpin session if previous transaction is committed.
}
_ => {}
}
match self.client.transaction_support_status().await? {
TransactionSupportStatus::Supported => {
let mut options = match options {
Some(mut options) => {
if let Some(defaults) = self.default_transaction_options() {
merge_options!(
defaults,
options,
[
read_concern,
write_concern,
selection_criteria,
max_commit_time
]
);
}
Some(options)
}
None => self.default_transaction_options().cloned(),
};
// Manually resolve inherited options since this doesn't go through the operation
// executor.
if let Some(rc) = self.client.read_concern() {
options
.get_or_insert_default()
.read_concern
.get_or_insert_with(|| rc.clone());
}
if let Some(wc) = self.client.write_concern() {
options
.get_or_insert_default()
.write_concern
.get_or_insert_with(|| wc.clone());
}
if let Some(sc) = self.client.selection_criteria() {
options
.get_or_insert_default()
.selection_criteria
.get_or_insert_with(|| sc.clone());
}
if let Some(ref options) = options {
if !options
.write_concern
.as_ref()
.map(|wc| wc.is_acknowledged())
.unwrap_or(true)
{
return Err(ErrorKind::Transaction {
message: "transactions do not support unacknowledged write concerns"
.into(),
}
.into());
}
}
self.increment_txn_number();
self.transaction.start(
options,
#[cfg(feature = "opentelemetry")]
self.client.start_transaction_span(),
);
Ok(())
}
_ => Err(ErrorKind::Transaction {
message: "Transactions are not supported by this deployment".into(),
}
.into()),
}
}
}
#[action_impl]
impl<'a> Action for StartTransaction<&'a mut ClientSession> {
type Future = StartTransactionFuture;
async fn execute(self) -> Result<()> {
self.session.start_transaction_impl(self.options).await
}
}
macro_rules! convenient_run {
(
$session:expr,
$start_transaction:expr,
$callback:expr,
$abort_transaction:expr,
$commit_transaction:expr,
$sleep:expr,
$await:ident,
) => {{
let start_time = Instant::now();
let max_time = MAX_CONVENIENT_TRANSACTION_TIME;
#[cfg(test)]
let max_time = $session.convenient_transaction_timeout.unwrap_or(max_time);
let mut attempt = 0;
let mut last_error = Error::internal("no error recorded for convenient transaction");
'transaction: loop {
if attempt > 0 {
let backoff = compute_backoff(
attempt,
#[cfg(test)]
$session.convenient_transaction_jitter,
);
if start_time.elapsed() + backoff >= max_time {
return Err(last_error);
}
$sleep(backoff).$await;
}
$start_transaction?;
attempt += 1;
let ret = match $callback {
Ok(v) => v,
Err(e) => {
if matches!(
$session.transaction.state,
TransactionState::Starting | TransactionState::InProgress
) {
$abort_transaction?;
}
if e.contains_label(TRANSIENT_TRANSACTION_ERROR)
&& start_time.elapsed() < max_time
{
last_error = e;
continue 'transaction;
}
return Err(e);
}
};
if matches!(
$session.transaction.state,
TransactionState::None
| TransactionState::Aborted
| TransactionState::Committed { .. }
) {
return Ok(ret);
}
'commit: loop {
match $commit_transaction {
Ok(()) => return Ok(ret),
Err(e) => {
if e.is_max_time_ms_expired_error() || start_time.elapsed() >= max_time {
return Err(e);
}
if e.contains_label(UNKNOWN_TRANSACTION_COMMIT_RESULT) {
continue 'commit;
}
if e.contains_label(TRANSIENT_TRANSACTION_ERROR) {
last_error = e;
continue 'transaction;
}
return Err(e);
}
}
}
}
}};
}
fn compute_backoff(attempt: u32, #[cfg(test)] test_jitter: Option<f64>) -> Duration {
const BACKOFF_INITIAL_MS: f64 = 5f64;
const BACKOFF_MAX_MS: f64 = 500f64;
const RETRY_BASE: f64 = 1.5f64;
let jitter = rand::random_range(0f64..1f64);
#[cfg(test)]
let jitter = test_jitter.unwrap_or(jitter);
let computed_backoff = jitter * BACKOFF_INITIAL_MS * RETRY_BASE.powf(f64::from(attempt - 1));
let max_backoff = jitter * BACKOFF_MAX_MS;
let backoff: u64 = std::cmp::min(round_clamp(computed_backoff), round_clamp(max_backoff));
Duration::from_millis(backoff)
}
// convenient_run needs an ident to access on the result from std::thread::sleep, so we use a dummy
// struct with a field
#[cfg(feature = "sync")]
struct SleepResult {
_r: (),
}
#[cfg(feature = "sync")]
fn sleep_sync(duration: Duration) -> SleepResult {
std::thread::sleep(duration);
SleepResult { _r: () }
}
impl StartTransaction<&mut ClientSession> {
/// Starts a transaction, runs the given callback, and commits or aborts the transaction. In
/// most circumstances, [`and_run2`](StartTransaction::and_run2) will be more convenient.
///
/// Transient transaction errors will cause the callback or the commit to be retried;
/// other errors will cause the transaction to be aborted and the error returned to the
/// caller. If the callback needs to provide its own error information, the
/// [`Error::custom`](crate::error::Error::custom) method can accept an arbitrary payload that
/// can be retrieved via [`Error::get_custom`](crate::error::Error::get_custom).
///
/// If a command inside the callback fails, it may cause the transaction on the server to be
/// aborted. This situation is normally handled transparently by the driver. However, if the
/// application does not return that error from the callback, the driver will not be able to
/// determine whether the transaction was aborted or not. The driver will then retry the
/// callback indefinitely. To avoid this situation, the application MUST NOT silently handle
/// errors within the callback. If the application needs to handle errors within the
/// callback, it MUST return them after doing so.
///
/// Because the callback can be repeatedly executed and because it returns a future, the rust
/// closure borrowing rules for captured values can be overly restrictive. As a
/// convenience, `and_run` accepts a context argument that will be passed to the
/// callback along with the session:
///
/// ```no_run
/// # use mongodb::{bson::{doc, Document}, error::Result, Client};
/// # use futures::FutureExt;
/// # async fn wrapper() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://example.com").await?;
/// # let mut session = client.start_session().await?;
/// let coll = client.database("mydb").collection::<Document>("mycoll");
/// let my_data = "my data".to_string();
/// // This works:
/// session.start_transaction().and_run(
/// (&coll, &my_data),
/// |session, (coll, my_data)| async move {
/// coll.insert_one(doc! { "data": *my_data }).session(session).await
/// }.boxed()
/// ).await?;
/// /* This will not compile with a "variable moved due to use in generator" error:
/// session.start_transaction().and_run(
/// (),
/// |session, _| async move {
/// coll.insert_one(doc! { "data": my_data }).session(session).await
/// }.boxed()
/// ).await?;
/// */
/// # Ok(())
/// # }
/// ```
pub async fn and_run<R, C, F>(self, mut context: C, mut callback: F) -> Result<R>
where
F: for<'b> FnMut(&'b mut ClientSession, &'b mut C) -> BoxFuture<'b, Result<R>>,
{
convenient_run!(
self.session,
self.session
.start_transaction()
.with_options(self.options.clone())
.await,
callback(self.session, &mut context).await,
self.session.abort_transaction().await,
self.session.commit_transaction().await,
tokio::time::sleep,
await,
)
}
/// Starts a transaction, runs the given callback, and commits or aborts the transaction.
///
/// Transient transaction errors will cause the callback or the commit to be retried;
/// other errors will cause the transaction to be aborted and the error returned to the
/// caller. If the callback needs to provide its own error information, the
/// [`Error::custom`](crate::error::Error::custom) method can accept an arbitrary payload that
/// can be retrieved via [`Error::get_custom`](crate::error::Error::get_custom).
///
/// If a command inside the callback fails, it may cause the transaction on the server to be
/// aborted. This situation is normally handled transparently by the driver. However, if the
/// application does not return that error from the callback, the driver will not be able to
/// determine whether the transaction was aborted or not. The driver will then retry the
/// callback indefinitely. To avoid this situation, the application MUST NOT silently handle
/// errors within the callback. If the application needs to handle errors within the
/// callback, it MUST return them after doing so.
///
/// This version of the method uses an async closure, which means it's both more convenient and
/// avoids the lifetime issues of `and_run`, but is only available in Rust versions 1.85 and
/// above.
///
/// In some circumstances, using this method can trigger a
/// [compiler bug](https://github.com/rust-lang/rust/issues/96865) that results in
/// `implementation of Send is not general enough` errors. If this is encountered, we
/// recommend these workarounds:
/// * Avoid capturing references in the transaction closure (e.g. by cloning)
/// * Use the `context` parameter of [`and_run`](StartTransaction::and_run).
///
/// Because the callback can be repeatedly executed, code within the callback cannot consume
/// owned values, even values owned by the callback itself:
///
/// ```no_run
/// # use mongodb::{bson::{doc, Document}, error::Result, Client};
/// # use futures::FutureExt;
/// # async fn wrapper() -> Result<()> {
/// # let client = Client::with_uri_str("mongodb://example.com").await?;
/// # let mut session = client.start_session().await?;
/// let coll = client.database("mydb").collection::<Document>("mycoll");
/// let my_data = "my data".to_string();
/// // This works:
/// session.start_transaction().and_run2(
/// async move |session| {
/// coll.insert_one(doc! { "data": my_data.clone() }).session(session).await
/// }
/// ).await?;
/// /* This will not compile:
/// session.start_transaction().and_run2(
/// async move |session| {
/// coll.insert_one(doc! { "data": my_data }).session(session).await
/// }
/// ).await?;
/// */
/// # Ok(())
/// # }
/// ```
#[rustversion::since(1.85)]
pub async fn and_run2<R, F>(self, mut callback: F) -> Result<R>
where
F: for<'b> AsyncFnMut(&'b mut ClientSession) -> Result<R>,
{
convenient_run!(
self.session,
self.session
.start_transaction()
.with_options(self.options.clone())
.await,
callback(self.session).await,
self.session.abort_transaction().await,
self.session.commit_transaction().await,
tokio::time::sleep,
await,
)
}
}
#[cfg(feature = "sync")]
impl StartTransaction<&mut crate::sync::ClientSession> {
/// Synchronously execute this action.
pub fn run(self) -> Result<()> {
crate::sync::TOKIO_RUNTIME.block_on(
self.session
.async_client_session
.start_transaction_impl(self.options),
)
}
/// Starts a transaction, runs the given callback, and commits or aborts the transaction.
/// Transient transaction errors will cause the callback or the commit to be retried;
/// other errors will cause the transaction to be aborted and the error returned to the
/// caller. If the callback needs to provide its own error information, the
/// [`Error::custom`](crate::error::Error::custom) method can accept an arbitrary payload that
/// can be retrieved via [`Error::get_custom`](crate::error::Error::get_custom).
///
/// If a command inside the callback fails, it may cause the transaction on the server to be
/// aborted. This situation is normally handled transparently by the driver. However, if the
/// application does not return that error from the callback, the driver will not be able to
/// determine whether the transaction was aborted or not. The driver will then retry the
/// callback indefinitely. To avoid this situation, the application MUST NOT silently handle
/// errors within the callback. If the application needs to handle errors within the
/// callback, it MUST return them after doing so.
pub fn and_run<R, F>(self, mut callback: F) -> Result<R>
where
F: for<'b> FnMut(&'b mut crate::sync::ClientSession) -> Result<R>,
{
convenient_run!(
self.session.async_client_session,
self.session
.start_transaction()
.with_options(self.options.clone())
.run(),
callback(self.session),
self.session.abort_transaction().run(),
self.session.commit_transaction().run(),
sleep_sync,
_r,
)
}
}
#[action_impl]
impl<'a> Action for CommitTransaction<'a> {
type Future = CommitTransactionFuture;
async fn execute(self) -> Result<()> {
match &mut self.session.transaction.state {
TransactionState::None => Err(ErrorKind::Transaction {
message: "no transaction started".into(),
}
.into()),
TransactionState::Aborted => Err(ErrorKind::Transaction {
message: "Cannot call commitTransaction after calling abortTransaction".into(),
}
.into()),
TransactionState::Starting => {
self.session.transaction.commit(false);
self.session.transaction.drop_span();
Ok(())
}
TransactionState::InProgress => {
let commit_transaction = operation::CommitTransaction::new(
&self.session.client(),
self.session.transaction.options.clone(),
);
self.session.transaction.commit(true);
let out = self
.session
.client
.clone()
.execute_operation(commit_transaction, &mut *self.session)
.await;
self.session.transaction.drop_span();
out
}
TransactionState::Committed {
data_committed: true,
} => {
let mut commit_transaction = operation::CommitTransaction::new(
&self.session.client(),
self.session.transaction.options.clone(),
);
commit_transaction.update_for_retry(None);
self.session
.client
.clone()
.execute_operation(commit_transaction, self.session)
.await
}
TransactionState::Committed {
data_committed: false,
} => Ok(()),
}
}
}
#[action_impl]
impl<'a> Action for AbortTransaction<'a> {
type Future = AbortTransactionFuture;
async fn execute(self) -> Result<()> {
match self.session.transaction.state {
TransactionState::None => Err(ErrorKind::Transaction {
message: "no transaction started".into(),
}
.into()),
TransactionState::Committed { .. } => Err(ErrorKind::Transaction {
message: "Cannot call abortTransaction after calling commitTransaction".into(),
}
.into()),
TransactionState::Aborted => Err(ErrorKind::Transaction {
message: "cannot call abortTransaction twice".into(),
}
.into()),
TransactionState::Starting => {
self.session.transaction.abort();
self.session.transaction.drop_span();
Ok(())
}
TransactionState::InProgress => {
let write_concern = self
.session
.transaction
.options
.as_ref()
.and_then(|options| options.write_concern.as_ref())
.cloned();
let abort_transaction = operation::AbortTransaction::new(
&self.session.client(),
write_concern,
self.session.transaction.pinned.take(),
);
self.session.transaction.abort();
// Errors returned from running an abortTransaction command should be ignored.
let _result = self
.session
.client
.clone()
.execute_operation(abort_transaction, &mut *self.session)
.await;
self.session.transaction.drop_span();
Ok(())
}
}
}
}