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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! mongodb-handshake/handshake.md ยงยง Connection Handshake, Speculative Authentication.
//! Events are pull-based. A token is accepted only on successful `command`, and
//! is settled exactly once before reuse: by a Failed or Unacknowledged event, or
//! by `release_reply()` after its Reply event. `fail()` before that release
//! revokes the reply and settles the token with Failed instead; `close()` keeps
//! a received reply readable until it is released.
use crate::Instant;
use crate::{
    Error, ErrorKind, Result,
    auth::{Mechanism, Scram},
    uri::Options,
    wire::{self, Decoder, Message},
};
use bson::{Document, doc, raw::RawDocument};
use std::collections::VecDeque;
#[derive(Debug)]
pub enum ConnectionEvent {
    UpgradeTls,
    Ready,
    Reply { token: u64 },
    Unacknowledged { token: u64 },
    Failed { token: Option<u64>, error: Error },
    Closed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
    New,
    Tls,
    Handshake,
    Auth,
    Ready,
    Command,
    UnackSending,
    Reply,
    Closed,
}
pub struct Connection {
    options: Options,
    state: State,
    tx: Vec<u8>,
    tx_at: usize,
    decoder: Decoder,
    expanded: Vec<u8>,
    compressed: Vec<u8>,
    compressor: flate2::Compress,
    decompressor: flate2::Decompress,
    zlib: bool,
    events: VecDeque<ConnectionEvent>,
    request_id: i32,
    expected: i32,
    token: Option<u64>,
    deadline: Option<Instant>,
    scram: Option<Scram>,
    nonce: String,
    pub hello: Option<Document>,
    pub max_message_size: usize,
    pub max_bson_size: usize,
    pub max_write_batch_size: usize,
}
impl Connection {
    pub fn new(options: Options) -> Self {
        Self {
            options,
            state: State::New,
            tx: Vec::with_capacity(8192),
            tx_at: 0,
            decoder: Decoder::new(wire::DEFAULT_MAX_MESSAGE),
            expanded: Vec::with_capacity(8192),
            compressed: Vec::with_capacity(8192),
            // Raw deflate: zlib.rs writes the RFC 1950 wrapper per message.
            compressor: flate2::Compress::new(flate2::Compression::default(), false),
            decompressor: flate2::Decompress::new(true),
            zlib: false,
            events: VecDeque::with_capacity(8),
            request_id: 0,
            expected: 0,
            token: None,
            deadline: None,
            scram: None,
            nonce: String::new(),
            hello: None,
            max_message_size: wire::DEFAULT_MAX_MESSAGE,
            max_bson_size: 16 * 1024 * 1024,
            max_write_batch_size: 100_000,
        }
    }
    /// `nonce` must come from a host CSPRNG if credentials are configured: at least
    /// 16 printable bytes, fresh per connection. See the crate's
    /// [host entropy](crate#host-entropy) obligations.
    pub fn connected(&mut self, now: Instant, nonce: &str) -> Result<()> {
        if self.state != State::New {
            return Err(Error::protocol("Connection already started"));
        }
        self.nonce.push_str(nonce);
        self.deadline = if self.options.connect_timeout.is_zero() {
            None
        } else {
            Some(now + self.options.connect_timeout)
        };
        if self.options.tls {
            self.state = State::Tls;
            self.events.push_back(ConnectionEvent::UpgradeTls);
            Ok(())
        } else {
            self.handshake()
        }
    }
    pub fn tls_established(&mut self) -> Result<()> {
        if self.state != State::Tls {
            return Err(Error::protocol("Unexpected TLS completion"));
        }
        self.handshake()
    }
    fn handshake(&mut self) -> Result<()> {
        let mut d = doc! {"isMaster":1,"helloOk":true,"client":{"driver":{"name":"turnloop-mongodb","version":env!("CARGO_PKG_VERSION")},"os":{"type":std::env::consts::OS}},"compression":self.options.compressors.clone(),"$db":"admin"};
        if let Some(app) = &self.options.app_name {
            d.get_document_mut("client")
                .unwrap()
                .insert("application", doc! {"name":app});
        }
        if let Some(c) = &self.options.credential {
            if c.mechanism.is_none() {
                d.insert("saslSupportedMechs", format!("{}.{}", c.source, c.username));
            }
            let mut scram = Scram::new(c, c.mechanism.unwrap_or(Mechanism::Sha256), &self.nonce)?;
            d.insert("speculativeAuthenticate", scram.start(&c.source, true));
            self.scram = Some(scram);
        }
        self.state = State::Handshake;
        self.send_document(&d)?;
        Ok(())
    }
    fn send_document(&mut self, d: &Document) -> Result<()> {
        let raw = bson::raw::RawDocumentBuf::try_from(d)
            .map_err(|_| Error::protocol("Cannot encode BSON command"))?;
        self.send(&raw, &[], 0)
    }
    fn send(
        &mut self,
        body: &RawDocument,
        seq: &[(&str, &[&RawDocument])],
        flags: u32,
    ) -> Result<()> {
        let id = self.request_id.wrapping_add(1).max(1);
        wire::encode(&mut self.tx, id, 0, flags, body, seq, self.max_message_size)?;
        self.request_id = id;
        self.expected = id;
        self.tx_at = 0;
        let command = body
            .iter_elements()
            .next()
            .transpose()
            .map_err(|_| Error::protocol("Invalid command"))?
            .ok_or_else(|| Error::protocol("Empty command"))?;
        self.compress(command.key().as_str())
    }
    fn compress(&mut self, command: &str) -> Result<()> {
        // Compression spec ยง Commands Not to Compress: includes authentication secrets.
        if self.zlib
            && !matches!(
                command,
                "hello"
                    | "isMaster"
                    | "ismaster"
                    | "saslStart"
                    | "saslContinue"
                    | "authenticate"
                    | "getnonce"
                    | "createUser"
                    | "updateUser"
                    | "copydbSaslStart"
                    | "copydbgetnonce"
                    | "copydb"
            )
        {
            self.compressed.clear();
            self.compressed.extend_from_slice(&self.tx[..16]);
            self.compressed[12..16].copy_from_slice(&wire::OP_COMPRESSED.to_le_bytes());
            self.compressed
                .extend_from_slice(&wire::OP_MSG.to_le_bytes());
            self.compressed
                .extend_from_slice(&((self.tx.len() - 16) as i32).to_le_bytes());
            self.compressed.push(2);
            // One retained deflate state, one zlib stream per message; see zlib.rs.
            crate::zlib::append_stream(&mut self.compressor, &self.tx[16..], &mut self.compressed)
                .map_err(Error::protocol)?;
            let n = self.compressed.len() as i32;
            self.compressed[..4].copy_from_slice(&n.to_le_bytes());
            std::mem::swap(&mut self.tx, &mut self.compressed);
        }
        Ok(())
    }
    pub fn is_ready(&self) -> bool {
        self.state == State::Ready
    }
    pub fn transmit(&self) -> &[u8] {
        &self.tx[self.tx_at..]
    }
    pub fn consume_transmit(&mut self, n: usize) -> Result<()> {
        if n > self.tx.len() - self.tx_at {
            return Err(Error::protocol("Transmit consumption exceeds bytes"));
        }
        self.tx_at += n;
        if self.tx_at == self.tx.len() {
            self.tx.clear();
            self.tx_at = 0;
            if self.state == State::UnackSending {
                self.state = State::Ready;
                self.deadline = None;
                self.events.push_back(ConnectionEvent::Unacknowledged {
                    token: self.token.take().unwrap(),
                });
            }
        }
        Ok(())
    }
    /// Whether `receive` would accept bytes now: a handshake, authentication or
    /// command reply is outstanding. This is the exact check `receive` makes, so
    /// a host need not shadow the state machine to decide when to read. It is
    /// false before `connected`, during a TLS upgrade, when idle, while an
    /// unacknowledged write drains, while a reply is unreleased and after close.
    pub fn accepts_receive(&self) -> bool {
        matches!(self.state, State::Handshake | State::Auth | State::Command)
    }
    /// Feed may consume only a frame prefix; retain and feed the remaining bytes.
    pub fn receive(&mut self, input: &[u8]) -> Result<usize> {
        if !self.accepts_receive() {
            return Err(Error::protocol("Connection is not expecting a reply"));
        }
        let result = self.receive_inner(input);
        if let Err(e) = &result {
            self.fail(e.clone());
        }
        result
    }
    fn receive_inner(&mut self, input: &[u8]) -> Result<usize> {
        let n = self.decoder.feed(input)?;
        if !self.decoder.complete() {
            return Ok(n);
        }
        self.expanded.clear();
        if wire::i32_at(self.decoder.bytes(), 12)? == wire::OP_COMPRESSED {
            if !self.zlib {
                return Err(Error::protocol("Unnegotiated compressed reply"));
            }
            let b = self.decoder.bytes();
            if b.len() < 25 || wire::i32_at(b, 16)? != wire::OP_MSG || b[24] != 2 {
                return Err(Error::protocol("Invalid compressed envelope"));
            }
            let size = wire::i32_at(b, 20)?;
            if size < 10 || size as usize > self.max_message_size - 16 {
                return Err(Error::protocol("Decompressed size out of range"));
            }
            self.expanded.extend_from_slice(&b[..16]);
            self.expanded[..4].copy_from_slice(&(size + 16).to_le_bytes());
            self.expanded[12..16].copy_from_slice(&wire::OP_MSG.to_le_bytes());
            self.expanded.resize(16 + size as usize, 0);
            self.decompressor.reset(true);
            let status = self
                .decompressor
                .decompress(
                    &b[25..],
                    &mut self.expanded[16..],
                    flate2::FlushDecompress::Finish,
                )
                .map_err(|_| Error::protocol("Invalid zlib reply"))?;
            if status != flate2::Status::StreamEnd
                || self.decompressor.total_out() != size as u64
                || self.decompressor.total_in() != b.len() as u64 - 25
            {
                return Err(Error::protocol("Compressed reply size mismatch"));
            }
        }
        let m = Message::parse(self.frame(), self.max_message_size)?;
        if m.response_to != self.expected {
            return Err(Error::protocol("MongoDB responseTo does not match request"));
        }
        if m.flags & wire::MORE_TO_COME != 0 {
            return Err(Error::protocol("Unexpected exhaust reply"));
        }
        if self.state == State::Command {
            self.state = State::Reply;
            self.deadline = None;
            self.events.push_back(ConnectionEvent::Reply {
                token: self.token.unwrap(),
            });
            return Ok(n);
        }
        Error::from_response(m.body)?;
        let d: Document = m
            .body
            .try_into()
            .map_err(|_| Error::protocol("Malformed handshake BSON"))?;
        self.decoder.clear();
        self.expanded.clear();
        if self.state == State::Handshake {
            let wire_version = d.get_i32("maxWireVersion").unwrap_or(0);
            if wire_version < 6 || d.get_i32("minWireVersion").unwrap_or(0) > 27 {
                return Err(Error::protocol(
                    "MongoDB server wire version is incompatible (client supports 6 through 27)",
                ));
            }
            for (key, target, min) in [
                ("maxMessageSizeBytes", &mut self.max_message_size, 26),
                ("maxBsonObjectSize", &mut self.max_bson_size, 5),
                ("maxWriteBatchSize", &mut self.max_write_batch_size, 1),
            ] {
                if let Ok(v) = d.get_i32(key) {
                    if v < min {
                        return Err(Error::protocol("Invalid handshake size limit"));
                    }
                    *target = v as usize;
                }
            }
            self.max_message_size = self.max_message_size.min(wire::DEFAULT_MAX_MESSAGE);
            self.decoder.set_max(self.max_message_size);
            self.zlib = self.options.compressors.iter().any(|c| c == "zlib")
                && d.get_array("compression")
                    .ok()
                    .is_some_and(|a| a.iter().any(|b| b.as_str() == Some("zlib")));
            self.hello = Some(d.clone());
            if let Some(c) = &self.options.credential
                && !d.get_bool("arbiterOnly").unwrap_or(false)
            {
                self.state = State::Auth;
                let next = if let Ok(spec) = d.get_document("speculativeAuthenticate") {
                    self.scram.as_mut().unwrap().receive(spec, &c.source)?
                } else {
                    let mechanism = c.mechanism.unwrap_or_else(|| {
                        if d.get_array("saslSupportedMechs")
                            .ok()
                            .is_some_and(|a| a.iter().any(|b| b.as_str() == Some("SCRAM-SHA-256")))
                        {
                            Mechanism::Sha256
                        } else {
                            Mechanism::Sha1
                        }
                    });
                    let mut scram = Scram::new(c, mechanism, &self.nonce)?;
                    let start = scram.start(&c.source, false);
                    self.scram = Some(scram);
                    Some(start)
                };
                if let Some(next) = next {
                    self.send_document(&next)?;
                    return Ok(n);
                }
            }
        } else if self.state == State::Auth {
            let source = &self.options.credential.as_ref().unwrap().source;
            let next = self.scram.as_mut().unwrap().receive(&d, source)?;
            if let Some(next) = next {
                self.send_document(&next)?;
                return Ok(n);
            }
        }
        self.scram = None;
        self.nonce.clear();
        self.state = State::Ready;
        self.deadline = None;
        self.events.push_back(ConnectionEvent::Ready);
        Ok(n)
    }
    fn frame(&self) -> &[u8] {
        if self.expanded.is_empty() {
            self.decoder.bytes()
        } else {
            &self.expanded
        }
    }
    pub fn reply(&self) -> Result<&RawDocument> {
        if self.state != State::Reply
            && !(self.state == State::Closed && self.token.is_some() && self.decoder.complete())
        {
            return Err(Error::protocol("No reply available"));
        }
        Ok(Message::parse(self.frame(), self.max_message_size)?.body)
    }
    pub fn release_reply(&mut self) -> Result<()> {
        if self.state != State::Reply
            && !(self.state == State::Closed && self.token.is_some() && self.decoder.complete())
        {
            return Err(Error::protocol("No reply to release"));
        }
        self.token = None;
        self.decoder.clear();
        self.expanded.clear();
        if self.state != State::Closed {
            self.state = State::Ready;
        }
        Ok(())
    }
    pub fn poll_event(&mut self) -> Option<ConnectionEvent> {
        self.events.pop_front()
    }
    pub fn command(
        &mut self,
        token: u64,
        body: &RawDocument,
        sequences: &[(&str, &[&RawDocument])],
        now: Instant,
    ) -> Result<()> {
        if self.state != State::Ready || !self.tx.is_empty() {
            return Err(Error::protocol("Connection busy"));
        }
        if body.get_str("$db").is_err() {
            return Err(Error::protocol("Command requires $db"));
        }
        if body.as_bytes().len() > self.max_bson_size
            || sequences.iter().any(|(_, docs)| {
                docs.len() > self.max_write_batch_size
                    || docs.iter().any(|d| d.as_bytes().len() > self.max_bson_size)
            })
        {
            return Err(Error::protocol(
                "Command exceeds negotiated BSON or batch size",
            ));
        }
        let unack = body
            .get("writeConcern")
            .ok()
            .flatten()
            .and_then(|v| v.as_document())
            .is_some_and(|d| {
                matches!(
                    d.get("w"),
                    Ok(Some(
                        bson::raw::RawBsonRef::Int32(0) | bson::raw::RawBsonRef::Int64(0)
                    ))
                )
            });
        self.send(body, sequences, if unack { wire::MORE_TO_COME } else { 0 })?;
        if unack {
            self.token = Some(token);
            self.state = State::UnackSending;
            self.deadline = if self.options.socket_timeout.is_zero() {
                None
            } else {
                Some(now + self.options.socket_timeout)
            };
        } else {
            self.token = Some(token);
            self.state = State::Command;
            self.deadline = if self.options.socket_timeout.is_zero() {
                None
            } else {
                Some(now + self.options.socket_timeout)
            };
        }
        Ok(())
    }
    /// Sends an already encoded OP_MSG template with a fresh wire request id.
    /// Used by Operation to retain sequence storage and session identity on retries.
    pub fn command_encoded(&mut self, token: u64, frame: &[u8], now: Instant) -> Result<()> {
        if self.state != State::Ready || !self.tx.is_empty() {
            return Err(Error::protocol("Connection busy"));
        }
        let message = Message::parse(frame, self.max_message_size)?;
        if message.flags != 0 || message.body.get_str("$db").is_err() {
            return Err(Error::protocol(
                "Operation template requires $db and no wire flags",
            ));
        }
        if message
            .body
            .get("writeConcern")
            .ok()
            .flatten()
            .and_then(|v| v.as_document())
            .is_some_and(|d| {
                matches!(
                    d.get("w"),
                    Ok(Some(
                        bson::raw::RawBsonRef::Int32(0) | bson::raw::RawBsonRef::Int64(0)
                    ))
                )
            })
        {
            return Err(Error::protocol(
                "Unacknowledged writes require Connection::command",
            ));
        }
        if message.body.as_bytes().len() > self.max_bson_size {
            return Err(Error::protocol("Command exceeds maxBsonObjectSize"));
        }
        for seq in message.sequences() {
            let mut n = 0;
            for d in seq.documents() {
                n += 1;
                if n > self.max_write_batch_size || d.as_bytes().len() > self.max_bson_size {
                    return Err(Error::protocol("Write sequence exceeds server limits"));
                }
            }
        }
        let command = message
            .body
            .iter_elements()
            .next()
            .transpose()
            .map_err(|_| Error::protocol("Invalid command"))?
            .ok_or_else(|| Error::protocol("Empty command"))?;
        self.tx.clear();
        self.tx.extend_from_slice(frame);
        self.request_id = self.request_id.wrapping_add(1).max(1);
        self.expected = self.request_id;
        self.tx[4..8].copy_from_slice(&self.request_id.to_le_bytes());
        self.tx_at = 0;
        if let Err(e) = self.compress(command.key().as_str()) {
            self.tx.clear();
            return Err(e);
        }
        self.token = Some(token);
        self.state = State::Command;
        self.deadline = if self.options.socket_timeout.is_zero() {
            None
        } else {
            Some(now + self.options.socket_timeout)
        };
        Ok(())
    }
    pub fn next_timeout(&self) -> Option<Instant> {
        self.deadline
    }
    pub fn handle_timeout(&mut self, now: Instant) {
        if self.deadline.is_some_and(|d| now >= d) {
            self.fail(Error::new(
                ErrorKind::Timeout,
                "MongoDB connection timed out",
            ));
        }
    }
    /// Closes the connection after a transport or protocol failure. An
    /// outstanding command, or a reply not yet released, settles with `Failed`.
    /// Such a reply is revoked: `reply()` and `release_reply()` then fail, and
    /// its `Reply` event is withdrawn if the host has not yet polled it.
    pub fn fail(&mut self, error: Error) {
        if self.state == State::Closed {
            return;
        }
        let token = self.token.take();
        if self.state == State::Reply {
            self.decoder.clear();
            self.expanded.clear();
            self.events
                .retain(|e| !matches!(e, ConnectionEvent::Reply { token: t } if Some(*t) == token));
        }
        self.events
            .push_back(ConnectionEvent::Failed { token, error });
        self.state = State::Closed;
        self.deadline = None;
        self.tx.clear();
        self.tx_at = 0;
        self.events.push_back(ConnectionEvent::Closed);
    }
    pub fn close(&mut self) {
        if self.state == State::Closed {
            return;
        }
        if self.token.is_some() && self.state != State::Reply {
            self.events.push_back(ConnectionEvent::Failed {
                token: self.token.take(),
                error: Error::new(
                    ErrorKind::Cancelled,
                    "Operation cancelled by connection close",
                ),
            });
        }
        self.state = State::Closed;
        self.deadline = None;
        self.tx.clear();
        self.tx_at = 0;
        self.events.push_back(ConnectionEvent::Closed);
    }
}