Skip to main content

turnloop_mongodb/
session.rs

1//! sessions/driver-sessions.md §§ Server Session, Command Decoration;
2//! transactions/transactions.md §§ State Machine, commitTransaction, abortTransaction;
3//! change-streams/change-streams.md §§ Resume Process, Resume Tokens.
4use crate::Instant;
5use crate::{Error, ErrorKind, Result, wire::BsonWriter};
6use bson::{
7    Document, Timestamp,
8    raw::{RawDocument, RawDocumentBuf},
9};
10use std::time::Duration;
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum TransactionState {
13    None,
14    Starting,
15    InProgress,
16    Committed,
17    Aborted,
18}
19#[derive(Debug)]
20pub struct Session {
21    pub id: [u8; 16],
22    pub txn_number: i64,
23    pub state: TransactionState,
24    pub dirty: bool,
25    pub operation_time: Option<Timestamp>,
26    pub cluster_time: Option<RawDocumentBuf>,
27    pub recovery_token: Option<RawDocumentBuf>,
28    pub transaction_write_concern: Option<RawDocumentBuf>,
29    pub transaction_read_concern: Option<RawDocumentBuf>,
30    pub max_commit_time_ms: Option<i64>,
31    has_operations: bool,
32    pub pinned_server: Option<String>,
33}
34impl Session {
35    /// Supply an RFC4122 UUID generated by the host. No entropy or clock reads here;
36    /// see the crate's [host entropy](crate#host-entropy) obligations.
37    pub fn new(id: [u8; 16]) -> Self {
38        Self {
39            id,
40            txn_number: 0,
41            state: TransactionState::None,
42            dirty: false,
43            operation_time: None,
44            cluster_time: None,
45            recovery_token: None,
46            transaction_write_concern: None,
47            transaction_read_concern: None,
48            max_commit_time_ms: None,
49            has_operations: false,
50            pinned_server: None,
51        }
52    }
53    pub fn start_transaction(&mut self) -> Result<()> {
54        if matches!(
55            self.state,
56            TransactionState::Starting | TransactionState::InProgress
57        ) {
58            return Err(Error::new(
59                ErrorKind::InvalidArgument,
60                "Transaction already in progress",
61            ));
62        }
63        self.txn_number = self
64            .txn_number
65            .checked_add(1)
66            .ok_or_else(|| Error::protocol("Transaction number exhausted"))?;
67        self.state = TransactionState::Starting;
68        self.recovery_token = None;
69        self.has_operations = false;
70        self.pinned_server = None;
71        Ok(())
72    }
73    pub fn next_retryable_write(&mut self) -> Result<()> {
74        if matches!(
75            self.state,
76            TransactionState::Starting | TransactionState::InProgress
77        ) {
78            return Err(Error::new(
79                ErrorKind::InvalidArgument,
80                "Retryable write is inside a transaction",
81            ));
82        }
83        self.txn_number = self
84            .txn_number
85            .checked_add(1)
86            .ok_or_else(|| Error::protocol("Transaction number exhausted"))?;
87        Ok(())
88    }
89    /// Decorates a retained writer before finish. Same txnNumber on a retry.
90    pub fn decorate(&mut self, w: &mut BsonWriter, retryable_write: bool) -> Result<()> {
91        if matches!(
92            self.state,
93            TransactionState::Committed | TransactionState::Aborted
94        ) {
95            self.state = TransactionState::None;
96            self.recovery_token = None;
97            self.pinned_server = None;
98        }
99        if let Some(t) = &self.cluster_time {
100            w.document("$clusterTime", t)?;
101        }
102        let l = w.start_document("lsid", false)?;
103        w.binary("id", 4, &self.id)?;
104        w.end_document(l)?;
105        if retryable_write
106            || matches!(
107                self.state,
108                TransactionState::Starting | TransactionState::InProgress
109            )
110        {
111            w.int64("txnNumber", self.txn_number)?;
112        }
113        if matches!(
114            self.state,
115            TransactionState::Starting | TransactionState::InProgress
116        ) {
117            w.boolean("autocommit", false)?;
118            if self.state == TransactionState::Starting {
119                w.boolean("startTransaction", true)?;
120                if let Some(c) = &self.transaction_read_concern {
121                    w.document("readConcern", c)?;
122                }
123                self.has_operations = true;
124                self.state = TransactionState::InProgress;
125            }
126        }
127        Ok(())
128    }
129    /// Returns false for an empty transaction, which completes locally.
130    pub fn commit(&mut self, w: &mut BsonWriter, retry: bool) -> Result<bool> {
131        if self.state == TransactionState::Starting
132            || (self.state == TransactionState::Committed && !self.has_operations)
133        {
134            self.state = TransactionState::Committed;
135            return Ok(false);
136        }
137        if !matches!(
138            self.state,
139            TransactionState::InProgress | TransactionState::Committed
140        ) {
141            return Err(Error::new(
142                ErrorKind::InvalidArgument,
143                if self.state == TransactionState::Aborted {
144                    "Cannot call commitTransaction after calling abortTransaction"
145                } else {
146                    "No transaction started"
147                },
148            ));
149        }
150        self.end_command(
151            w,
152            "commitTransaction",
153            retry || self.state == TransactionState::Committed,
154        )?;
155        self.state = TransactionState::Committed;
156        Ok(true)
157    }
158    pub fn abort(&mut self, w: &mut BsonWriter) -> Result<bool> {
159        if self.state == TransactionState::Starting {
160            self.state = TransactionState::Aborted;
161            return Ok(false);
162        }
163        if self.state != TransactionState::InProgress {
164            return Err(Error::new(
165                ErrorKind::InvalidArgument,
166                match self.state {
167                    TransactionState::Committed => {
168                        "Cannot call abortTransaction after calling commitTransaction"
169                    }
170                    TransactionState::Aborted => "Cannot call abortTransaction twice",
171                    _ => "No transaction started",
172                },
173            ));
174        }
175        self.end_command(w, "abortTransaction", false)?;
176        self.state = TransactionState::Aborted;
177        Ok(true)
178    }
179    fn end_command(&self, w: &mut BsonWriter, name: &str, majority: bool) -> Result<()> {
180        w.clear();
181        w.int32(name, 1)?;
182        let l = w.start_document("lsid", false)?;
183        w.binary("id", 4, &self.id)?;
184        w.end_document(l)?;
185        w.int64("txnNumber", self.txn_number)?;
186        w.boolean("autocommit", false)?;
187        if majority {
188            let c = w.start_document("writeConcern", false)?;
189            if let Some(wc) = &self.transaction_write_concern {
190                w.append_fields(wc, &["w"])?;
191            }
192            w.string("w", "majority")?;
193            if self
194                .transaction_write_concern
195                .as_ref()
196                .is_none_or(|wc| wc.get("wtimeout").ok().flatten().is_none())
197            {
198                w.int32("wtimeout", 10000)?;
199            }
200            w.end_document(c)?;
201        } else if let Some(wc) = &self.transaction_write_concern {
202            w.document("writeConcern", wc)?;
203        }
204        if let Some(token) = &self.recovery_token {
205            w.document("recoveryToken", token)?;
206        }
207        if let Some(t) = &self.cluster_time {
208            w.document("$clusterTime", t)?;
209        }
210        if name == "commitTransaction"
211            && let Some(ms) = self.max_commit_time_ms
212        {
213            w.int64("maxTimeMS", ms)?;
214        }
215        w.string("$db", "admin")?;
216        w.finish()?;
217        Ok(())
218    }
219    pub fn observe(&mut self, reply: &Document) {
220        if matches!(
221            self.state,
222            TransactionState::Starting | TransactionState::InProgress | TransactionState::Committed
223        ) && let Ok(token) = reply.get_document("recoveryToken")
224        {
225            self.recovery_token = RawDocumentBuf::try_from(token).ok();
226        }
227        if let Ok(t) = reply.get_timestamp("operationTime") {
228            self.operation_time = Some(self.operation_time.map_or(t, |old| old.max(t)));
229        }
230        if let Ok(c) = reply.get_document("$clusterTime")
231            && let Ok(t) = c.get_timestamp("clusterTime")
232            && self
233                .cluster_time
234                .as_ref()
235                .and_then(|d| d.get_timestamp("clusterTime").ok())
236                .is_none_or(|old| t > old)
237        {
238            self.cluster_time = RawDocumentBuf::try_from(c).ok();
239        }
240    }
241    /// Causal read concern for a non-transaction read. Command must not already
242    /// contain readConcern; operationTime came from an earlier server response.
243    pub fn decorate_causal_read(&mut self, w: &mut BsonWriter, level: Option<&str>) -> Result<()> {
244        if matches!(
245            self.state,
246            TransactionState::Starting | TransactionState::InProgress
247        ) {
248            return Err(Error::new(
249                ErrorKind::InvalidArgument,
250                "Use transaction readConcern for transaction operations",
251            ));
252        }
253        self.decorate(w, false)?;
254        if level.is_some() || self.operation_time.is_some() {
255            let c = w.start_document("readConcern", false)?;
256            if let Some(level) = level {
257                w.string("level", level)?;
258            }
259            if let Some(t) = self.operation_time {
260                w.timestamp("afterClusterTime", t)?;
261            }
262            w.end_document(c)?;
263        }
264        Ok(())
265    }
266    pub fn observe_recovery_token(&mut self, reply: &RawDocument) -> Result<()> {
267        if let Some(t) = reply
268            .get("recoveryToken")
269            .ok()
270            .flatten()
271            .and_then(|v| v.as_document())
272        {
273            self.recovery_token = Some(
274                RawDocumentBuf::from_bytes(t.as_bytes().to_vec())
275                    .map_err(|_| Error::protocol("Invalid recovery token"))?,
276            );
277        }
278        Ok(())
279    }
280    pub fn pin(&mut self, address: &str) -> Result<()> {
281        if self.pinned_server.as_ref().is_some_and(|a| a != address) {
282            return Err(Error::protocol("Transaction is pinned to another mongos"));
283        }
284        if self.pinned_server.is_none() {
285            self.pinned_server = Some(address.into());
286        }
287        Ok(())
288    }
289    pub fn unpin_on_error(&mut self, error: &Error) {
290        if error.has_label("TransientTransactionError")
291            || error.has_label("UnknownTransactionCommitResult")
292        {
293            self.pinned_server = None;
294        }
295    }
296    pub fn retry_abort(&self, w: &mut BsonWriter) -> Result<()> {
297        if self.state != TransactionState::Aborted {
298            return Err(Error::protocol("No abort attempt to retry"));
299        }
300        self.end_command(w, "abortTransaction", false)
301    }
302    pub fn retry_commit(error: &Error) -> bool {
303        matches!(error.kind, ErrorKind::Network | ErrorKind::Timeout)
304            || error.has_label("RetryableWriteError")
305    }
306}
307#[derive(Default, Debug)]
308pub struct ChangeStream {
309    pub resume_token: Option<Document>,
310    pub start_after: bool,
311    pub received_document: bool,
312    pub operation_time: Option<Timestamp>,
313    pub resumed: bool,
314}
315impl ChangeStream {
316    pub fn observe_document(&mut self, event: &RawDocument) -> Result<()> {
317        let id = event.get_document("_id").map_err(|_| {
318            Error::protocol("Cannot provide resume functionality when the resume token is missing")
319        })?;
320        self.resume_token = Some(
321            id.try_into()
322                .map_err(|_| Error::protocol("Invalid resume token"))?,
323        );
324        self.received_document = true;
325        self.resumed = false;
326        Ok(())
327    }
328    /// Call only after consuming every document in the batch, including an empty batch.
329    pub fn finish_batch(&mut self, token: Option<&RawDocument>) -> Result<()> {
330        self.resumed = false;
331        if let Some(t) = token {
332            self.resume_token = Some(
333                t.try_into()
334                    .map_err(|_| Error::protocol("Invalid post batch resume token"))?,
335            );
336        }
337        Ok(())
338    }
339    pub fn stage(&self) -> Document {
340        let mut options = Document::new();
341        if let Some(t) = &self.resume_token {
342            options.insert(
343                if self.start_after && !self.received_document {
344                    "startAfter"
345                } else {
346                    "resumeAfter"
347                },
348                t.clone(),
349            );
350        } else if let Some(t) = self.operation_time {
351            options.insert("startAtOperationTime", t);
352        }
353        bson::doc! {"$changeStream":options}
354    }
355    pub fn should_resume(&mut self, error: &Error, wire_version: i32) -> bool {
356        if self.resumed {
357            return false;
358        }
359        let allowed = matches!(error.kind, ErrorKind::Network | ErrorKind::Timeout)
360            || if wire_version >= 9 {
361                error.has_label("ResumableChangeStreamError")
362            } else {
363                error.code.is_some_and(|c| {
364                    matches!(
365                        c,
366                        6 | 7
367                            | 43
368                            | 63
369                            | 89
370                            | 91
371                            | 150
372                            | 189
373                            | 234
374                            | 262
375                            | 9001
376                            | 10107
377                            | 11600
378                            | 11602
379                            | 13388
380                            | 13435
381                            | 13436
382                    )
383                })
384            };
385        if allowed {
386            self.resumed = true;
387        }
388        allowed
389    }
390}
391
392/// Shared server-session identities, checked out by one operation/transaction at
393/// a time. Empty checkout requests host UUID entropy; never generates it internally.
394#[derive(Default)]
395pub struct SessionPool {
396    idle: Vec<(Session, Instant)>,
397    timeout: Duration,
398}
399impl SessionPool {
400    pub fn new(logical_timeout: Duration) -> Self {
401        Self {
402            idle: Vec::with_capacity(16),
403            timeout: logical_timeout.saturating_sub(Duration::from_secs(60)),
404        }
405    }
406    pub fn checkout(&mut self, now: Instant) -> Option<Session> {
407        self.handle_timeout(now);
408        self.idle.pop().map(|(s, _)| s)
409    }
410    /// Returns false when a dirty/active session cannot be reused. Abort an active
411    /// transaction before ending its session; the pool cannot perform that I/O.
412    pub fn checkin(&mut self, mut session: Session, now: Instant) -> bool {
413        if session.dirty
414            || matches!(
415                session.state,
416                TransactionState::Starting | TransactionState::InProgress
417            )
418            || self.timeout.is_zero()
419        {
420            return false;
421        }
422        session.state = TransactionState::None;
423        session.operation_time = None;
424        session.cluster_time = None;
425        session.recovery_token = None;
426        session.pinned_server = None;
427        session.has_operations = false;
428        session.transaction_read_concern = None;
429        session.transaction_write_concern = None;
430        session.max_commit_time_ms = None;
431        self.idle.push((session, now));
432        true
433    }
434    pub fn next_timeout(&self) -> Option<Instant> {
435        self.idle
436            .iter()
437            .filter_map(|(_, at)| at.checked_add(self.timeout))
438            .min()
439    }
440    pub fn handle_timeout(&mut self, now: Instant) {
441        self.idle
442            .retain(|(_, at)| now.saturating_duration_since(*at) < self.timeout);
443    }
444    pub fn len(&self) -> usize {
445        self.idle.len()
446    }
447    pub fn is_empty(&self) -> bool {
448        self.idle.is_empty()
449    }
450}
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub enum EndKind {
453    Commit,
454    Abort,
455}
456#[derive(Debug)]
457pub enum EndAction {
458    Retry,
459    Complete,
460    Failed(Error),
461}
462/// One automatic commit/abort retry, independent of the client's retryWrites flag.
463/// The host feeds transport/server errors; call Session commit/abort for attempt 1.
464pub struct TransactionEnd {
465    pub kind: EndKind,
466    retried: bool,
467}
468impl TransactionEnd {
469    pub fn new(kind: EndKind) -> Self {
470        Self {
471            kind,
472            retried: false,
473        }
474    }
475    pub fn failed(
476        &mut self,
477        session: &mut Session,
478        mut error: Error,
479        wire_version: i32,
480        writer: &mut BsonWriter,
481    ) -> Result<EndAction> {
482        let retry = crate::retry::Retry {
483            kind: crate::retry::RetryKind::Write,
484            enabled: true,
485            attempts: u8::from(self.retried),
486            in_transaction: false,
487            wire_version,
488            sessions_supported: true,
489            standalone: false,
490            acknowledged: true,
491        }
492        .allowed(&error);
493        if retry {
494            self.retried = true;
495            session.pinned_server = None;
496            match self.kind {
497                EndKind::Commit => {
498                    session.commit(writer, true)?;
499                }
500                EndKind::Abort => session.retry_abort(writer)?,
501            }
502            return Ok(EndAction::Retry);
503        }
504        if self.kind == EndKind::Abort {
505            session.pinned_server = None;
506            return Ok(EndAction::Complete);
507        }
508        let concern = error
509            .response
510            .as_ref()
511            .is_some_and(|r| r.contains_key("writeConcernError"))
512            && !matches!(error.code, Some(79 | 100));
513        if (matches!(
514            error.kind,
515            ErrorKind::Network
516                | ErrorKind::Timeout
517                | ErrorKind::PoolCleared
518                | ErrorKind::ServerSelectionTimeout
519        ) || error.has_label("RetryableWriteError")
520            || error.code == Some(50)
521            || concern)
522            && !error.has_label("UnknownTransactionCommitResult")
523        {
524            error.labels.push("UnknownTransactionCommitResult".into());
525        }
526        session.unpin_on_error(&error);
527        Ok(EndAction::Failed(error))
528    }
529}