turnloop-mongodb 0.1.0-beta.2

Host-driven, sans-IO MongoDB protocol state machines
Documentation
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
//! sessions/driver-sessions.md §§ Server Session, Command Decoration;
//! transactions/transactions.md §§ State Machine, commitTransaction, abortTransaction;
//! change-streams/change-streams.md §§ Resume Process, Resume Tokens.
use crate::Instant;
use crate::{Error, ErrorKind, Result, wire::BsonWriter};
use bson::{
    Document, Timestamp,
    raw::{RawDocument, RawDocumentBuf},
};
use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransactionState {
    None,
    Starting,
    InProgress,
    Committed,
    Aborted,
}
#[derive(Debug)]
pub struct Session {
    pub id: [u8; 16],
    pub txn_number: i64,
    pub state: TransactionState,
    pub dirty: bool,
    pub operation_time: Option<Timestamp>,
    pub cluster_time: Option<RawDocumentBuf>,
    pub recovery_token: Option<RawDocumentBuf>,
    pub transaction_write_concern: Option<RawDocumentBuf>,
    pub transaction_read_concern: Option<RawDocumentBuf>,
    pub max_commit_time_ms: Option<i64>,
    has_operations: bool,
    pub pinned_server: Option<String>,
}
impl Session {
    /// Supply an RFC4122 UUID generated by the host. No entropy or clock reads here;
    /// see the crate's [host entropy](crate#host-entropy) obligations.
    pub fn new(id: [u8; 16]) -> Self {
        Self {
            id,
            txn_number: 0,
            state: TransactionState::None,
            dirty: false,
            operation_time: None,
            cluster_time: None,
            recovery_token: None,
            transaction_write_concern: None,
            transaction_read_concern: None,
            max_commit_time_ms: None,
            has_operations: false,
            pinned_server: None,
        }
    }
    pub fn start_transaction(&mut self) -> Result<()> {
        if matches!(
            self.state,
            TransactionState::Starting | TransactionState::InProgress
        ) {
            return Err(Error::new(
                ErrorKind::InvalidArgument,
                "Transaction already in progress",
            ));
        }
        self.txn_number = self
            .txn_number
            .checked_add(1)
            .ok_or_else(|| Error::protocol("Transaction number exhausted"))?;
        self.state = TransactionState::Starting;
        self.recovery_token = None;
        self.has_operations = false;
        self.pinned_server = None;
        Ok(())
    }
    pub fn next_retryable_write(&mut self) -> Result<()> {
        if matches!(
            self.state,
            TransactionState::Starting | TransactionState::InProgress
        ) {
            return Err(Error::new(
                ErrorKind::InvalidArgument,
                "Retryable write is inside a transaction",
            ));
        }
        self.txn_number = self
            .txn_number
            .checked_add(1)
            .ok_or_else(|| Error::protocol("Transaction number exhausted"))?;
        Ok(())
    }
    /// Decorates a retained writer before finish. Same txnNumber on a retry.
    pub fn decorate(&mut self, w: &mut BsonWriter, retryable_write: bool) -> Result<()> {
        if matches!(
            self.state,
            TransactionState::Committed | TransactionState::Aborted
        ) {
            self.state = TransactionState::None;
            self.recovery_token = None;
            self.pinned_server = None;
        }
        if let Some(t) = &self.cluster_time {
            w.document("$clusterTime", t)?;
        }
        let l = w.start_document("lsid", false)?;
        w.binary("id", 4, &self.id)?;
        w.end_document(l)?;
        if retryable_write
            || matches!(
                self.state,
                TransactionState::Starting | TransactionState::InProgress
            )
        {
            w.int64("txnNumber", self.txn_number)?;
        }
        if matches!(
            self.state,
            TransactionState::Starting | TransactionState::InProgress
        ) {
            w.boolean("autocommit", false)?;
            if self.state == TransactionState::Starting {
                w.boolean("startTransaction", true)?;
                if let Some(c) = &self.transaction_read_concern {
                    w.document("readConcern", c)?;
                }
                self.has_operations = true;
                self.state = TransactionState::InProgress;
            }
        }
        Ok(())
    }
    /// Returns false for an empty transaction, which completes locally.
    pub fn commit(&mut self, w: &mut BsonWriter, retry: bool) -> Result<bool> {
        if self.state == TransactionState::Starting
            || (self.state == TransactionState::Committed && !self.has_operations)
        {
            self.state = TransactionState::Committed;
            return Ok(false);
        }
        if !matches!(
            self.state,
            TransactionState::InProgress | TransactionState::Committed
        ) {
            return Err(Error::new(
                ErrorKind::InvalidArgument,
                if self.state == TransactionState::Aborted {
                    "Cannot call commitTransaction after calling abortTransaction"
                } else {
                    "No transaction started"
                },
            ));
        }
        self.end_command(
            w,
            "commitTransaction",
            retry || self.state == TransactionState::Committed,
        )?;
        self.state = TransactionState::Committed;
        Ok(true)
    }
    pub fn abort(&mut self, w: &mut BsonWriter) -> Result<bool> {
        if self.state == TransactionState::Starting {
            self.state = TransactionState::Aborted;
            return Ok(false);
        }
        if self.state != TransactionState::InProgress {
            return Err(Error::new(
                ErrorKind::InvalidArgument,
                match self.state {
                    TransactionState::Committed => {
                        "Cannot call abortTransaction after calling commitTransaction"
                    }
                    TransactionState::Aborted => "Cannot call abortTransaction twice",
                    _ => "No transaction started",
                },
            ));
        }
        self.end_command(w, "abortTransaction", false)?;
        self.state = TransactionState::Aborted;
        Ok(true)
    }
    fn end_command(&self, w: &mut BsonWriter, name: &str, majority: bool) -> Result<()> {
        w.clear();
        w.int32(name, 1)?;
        let l = w.start_document("lsid", false)?;
        w.binary("id", 4, &self.id)?;
        w.end_document(l)?;
        w.int64("txnNumber", self.txn_number)?;
        w.boolean("autocommit", false)?;
        if majority {
            let c = w.start_document("writeConcern", false)?;
            if let Some(wc) = &self.transaction_write_concern {
                w.append_fields(wc, &["w"])?;
            }
            w.string("w", "majority")?;
            if self
                .transaction_write_concern
                .as_ref()
                .is_none_or(|wc| wc.get("wtimeout").ok().flatten().is_none())
            {
                w.int32("wtimeout", 10000)?;
            }
            w.end_document(c)?;
        } else if let Some(wc) = &self.transaction_write_concern {
            w.document("writeConcern", wc)?;
        }
        if let Some(token) = &self.recovery_token {
            w.document("recoveryToken", token)?;
        }
        if let Some(t) = &self.cluster_time {
            w.document("$clusterTime", t)?;
        }
        if name == "commitTransaction"
            && let Some(ms) = self.max_commit_time_ms
        {
            w.int64("maxTimeMS", ms)?;
        }
        w.string("$db", "admin")?;
        w.finish()?;
        Ok(())
    }
    pub fn observe(&mut self, reply: &Document) {
        if matches!(
            self.state,
            TransactionState::Starting | TransactionState::InProgress | TransactionState::Committed
        ) && let Ok(token) = reply.get_document("recoveryToken")
        {
            self.recovery_token = RawDocumentBuf::try_from(token).ok();
        }
        if let Ok(t) = reply.get_timestamp("operationTime") {
            self.operation_time = Some(self.operation_time.map_or(t, |old| old.max(t)));
        }
        if let Ok(c) = reply.get_document("$clusterTime")
            && let Ok(t) = c.get_timestamp("clusterTime")
            && self
                .cluster_time
                .as_ref()
                .and_then(|d| d.get_timestamp("clusterTime").ok())
                .is_none_or(|old| t > old)
        {
            self.cluster_time = RawDocumentBuf::try_from(c).ok();
        }
    }
    /// Causal read concern for a non-transaction read. Command must not already
    /// contain readConcern; operationTime came from an earlier server response.
    pub fn decorate_causal_read(&mut self, w: &mut BsonWriter, level: Option<&str>) -> Result<()> {
        if matches!(
            self.state,
            TransactionState::Starting | TransactionState::InProgress
        ) {
            return Err(Error::new(
                ErrorKind::InvalidArgument,
                "Use transaction readConcern for transaction operations",
            ));
        }
        self.decorate(w, false)?;
        if level.is_some() || self.operation_time.is_some() {
            let c = w.start_document("readConcern", false)?;
            if let Some(level) = level {
                w.string("level", level)?;
            }
            if let Some(t) = self.operation_time {
                w.timestamp("afterClusterTime", t)?;
            }
            w.end_document(c)?;
        }
        Ok(())
    }
    pub fn observe_recovery_token(&mut self, reply: &RawDocument) -> Result<()> {
        if let Some(t) = reply
            .get("recoveryToken")
            .ok()
            .flatten()
            .and_then(|v| v.as_document())
        {
            self.recovery_token = Some(
                RawDocumentBuf::from_bytes(t.as_bytes().to_vec())
                    .map_err(|_| Error::protocol("Invalid recovery token"))?,
            );
        }
        Ok(())
    }
    pub fn pin(&mut self, address: &str) -> Result<()> {
        if self.pinned_server.as_ref().is_some_and(|a| a != address) {
            return Err(Error::protocol("Transaction is pinned to another mongos"));
        }
        if self.pinned_server.is_none() {
            self.pinned_server = Some(address.into());
        }
        Ok(())
    }
    pub fn unpin_on_error(&mut self, error: &Error) {
        if error.has_label("TransientTransactionError")
            || error.has_label("UnknownTransactionCommitResult")
        {
            self.pinned_server = None;
        }
    }
    pub fn retry_abort(&self, w: &mut BsonWriter) -> Result<()> {
        if self.state != TransactionState::Aborted {
            return Err(Error::protocol("No abort attempt to retry"));
        }
        self.end_command(w, "abortTransaction", false)
    }
    pub fn retry_commit(error: &Error) -> bool {
        matches!(error.kind, ErrorKind::Network | ErrorKind::Timeout)
            || error.has_label("RetryableWriteError")
    }
}
#[derive(Default, Debug)]
pub struct ChangeStream {
    pub resume_token: Option<Document>,
    pub start_after: bool,
    pub received_document: bool,
    pub operation_time: Option<Timestamp>,
    pub resumed: bool,
}
impl ChangeStream {
    pub fn observe_document(&mut self, event: &RawDocument) -> Result<()> {
        let id = event.get_document("_id").map_err(|_| {
            Error::protocol("Cannot provide resume functionality when the resume token is missing")
        })?;
        self.resume_token = Some(
            id.try_into()
                .map_err(|_| Error::protocol("Invalid resume token"))?,
        );
        self.received_document = true;
        self.resumed = false;
        Ok(())
    }
    /// Call only after consuming every document in the batch, including an empty batch.
    pub fn finish_batch(&mut self, token: Option<&RawDocument>) -> Result<()> {
        self.resumed = false;
        if let Some(t) = token {
            self.resume_token = Some(
                t.try_into()
                    .map_err(|_| Error::protocol("Invalid post batch resume token"))?,
            );
        }
        Ok(())
    }
    pub fn stage(&self) -> Document {
        let mut options = Document::new();
        if let Some(t) = &self.resume_token {
            options.insert(
                if self.start_after && !self.received_document {
                    "startAfter"
                } else {
                    "resumeAfter"
                },
                t.clone(),
            );
        } else if let Some(t) = self.operation_time {
            options.insert("startAtOperationTime", t);
        }
        bson::doc! {"$changeStream":options}
    }
    pub fn should_resume(&mut self, error: &Error, wire_version: i32) -> bool {
        if self.resumed {
            return false;
        }
        let allowed = matches!(error.kind, ErrorKind::Network | ErrorKind::Timeout)
            || if wire_version >= 9 {
                error.has_label("ResumableChangeStreamError")
            } else {
                error.code.is_some_and(|c| {
                    matches!(
                        c,
                        6 | 7
                            | 43
                            | 63
                            | 89
                            | 91
                            | 150
                            | 189
                            | 234
                            | 262
                            | 9001
                            | 10107
                            | 11600
                            | 11602
                            | 13388
                            | 13435
                            | 13436
                    )
                })
            };
        if allowed {
            self.resumed = true;
        }
        allowed
    }
}

/// Shared server-session identities, checked out by one operation/transaction at
/// a time. Empty checkout requests host UUID entropy; never generates it internally.
#[derive(Default)]
pub struct SessionPool {
    idle: Vec<(Session, Instant)>,
    timeout: Duration,
}
impl SessionPool {
    pub fn new(logical_timeout: Duration) -> Self {
        Self {
            idle: Vec::with_capacity(16),
            timeout: logical_timeout.saturating_sub(Duration::from_secs(60)),
        }
    }
    pub fn checkout(&mut self, now: Instant) -> Option<Session> {
        self.handle_timeout(now);
        self.idle.pop().map(|(s, _)| s)
    }
    /// Returns false when a dirty/active session cannot be reused. Abort an active
    /// transaction before ending its session; the pool cannot perform that I/O.
    pub fn checkin(&mut self, mut session: Session, now: Instant) -> bool {
        if session.dirty
            || matches!(
                session.state,
                TransactionState::Starting | TransactionState::InProgress
            )
            || self.timeout.is_zero()
        {
            return false;
        }
        session.state = TransactionState::None;
        session.operation_time = None;
        session.cluster_time = None;
        session.recovery_token = None;
        session.pinned_server = None;
        session.has_operations = false;
        session.transaction_read_concern = None;
        session.transaction_write_concern = None;
        session.max_commit_time_ms = None;
        self.idle.push((session, now));
        true
    }
    pub fn next_timeout(&self) -> Option<Instant> {
        self.idle
            .iter()
            .filter_map(|(_, at)| at.checked_add(self.timeout))
            .min()
    }
    pub fn handle_timeout(&mut self, now: Instant) {
        self.idle
            .retain(|(_, at)| now.saturating_duration_since(*at) < self.timeout);
    }
    pub fn len(&self) -> usize {
        self.idle.len()
    }
    pub fn is_empty(&self) -> bool {
        self.idle.is_empty()
    }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EndKind {
    Commit,
    Abort,
}
#[derive(Debug)]
pub enum EndAction {
    Retry,
    Complete,
    Failed(Error),
}
/// One automatic commit/abort retry, independent of the client's retryWrites flag.
/// The host feeds transport/server errors; call Session commit/abort for attempt 1.
pub struct TransactionEnd {
    pub kind: EndKind,
    retried: bool,
}
impl TransactionEnd {
    pub fn new(kind: EndKind) -> Self {
        Self {
            kind,
            retried: false,
        }
    }
    pub fn failed(
        &mut self,
        session: &mut Session,
        mut error: Error,
        wire_version: i32,
        writer: &mut BsonWriter,
    ) -> Result<EndAction> {
        let retry = crate::retry::Retry {
            kind: crate::retry::RetryKind::Write,
            enabled: true,
            attempts: u8::from(self.retried),
            in_transaction: false,
            wire_version,
            sessions_supported: true,
            standalone: false,
            acknowledged: true,
        }
        .allowed(&error);
        if retry {
            self.retried = true;
            session.pinned_server = None;
            match self.kind {
                EndKind::Commit => {
                    session.commit(writer, true)?;
                }
                EndKind::Abort => session.retry_abort(writer)?,
            }
            return Ok(EndAction::Retry);
        }
        if self.kind == EndKind::Abort {
            session.pinned_server = None;
            return Ok(EndAction::Complete);
        }
        let concern = error
            .response
            .as_ref()
            .is_some_and(|r| r.contains_key("writeConcernError"))
            && !matches!(error.code, Some(79 | 100));
        if (matches!(
            error.kind,
            ErrorKind::Network
                | ErrorKind::Timeout
                | ErrorKind::PoolCleared
                | ErrorKind::ServerSelectionTimeout
        ) || error.has_label("RetryableWriteError")
            || error.code == Some(50)
            || concern)
            && !error.has_label("UnknownTransactionCommitResult")
        {
            error.labels.push("UnknownTransactionCommitResult".into());
        }
        session.unpin_on_error(&error);
        Ok(EndAction::Failed(error))
    }
}