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
//! MongoDB specifications: message/OP_MSG.md ยงยง OP_MSG, flagBits, sections;
//! compression/OP_COMPRESSED.md. Integer arithmetic is checked before slicing.
use crate::{Error, Result};
use bson::raw::RawDocument;
use std::ops::Range;
pub const OP_MSG: i32 = 2013;
pub const OP_COMPRESSED: i32 = 2012;
pub const CHECKSUM: u32 = 1;
pub const MORE_TO_COME: u32 = 2;
pub const EXHAUST_ALLOWED: u32 = 1 << 16;
pub const DEFAULT_MAX_MESSAGE: usize = 48_000_000;
pub fn i32_at(bytes: &[u8], at: usize) -> Result<i32> {
    Ok(i32::from_le_bytes(
        bytes
            .get(at..at + 4)
            .ok_or_else(|| Error::protocol("Truncated int32"))?
            .try_into()
            .unwrap(),
    ))
}
fn length(bytes: &[u8], at: usize, min: usize) -> Result<usize> {
    let n = i32_at(bytes, at)?;
    if n < min as i32 {
        return Err(Error::protocol("Invalid BSON or message length"));
    }
    Ok(n as usize)
}
pub fn crc32c(bytes: &[u8]) -> u32 {
    let mut c = !0u32;
    for &v in bytes {
        c ^= v as u32;
        for _ in 0..8 {
            c = (c >> 1) ^ (0x82f63b78u32.wrapping_mul(c & 1));
        }
    }
    !c
}
#[derive(Debug)]
pub struct Message<'a> {
    pub request_id: i32,
    pub response_to: i32,
    pub flags: u32,
    pub body: &'a RawDocument,
    sections: &'a [u8],
}
impl<'a> Message<'a> {
    pub fn parse(bytes: &'a [u8], max: usize) -> Result<Self> {
        let n = length(bytes, 0, 26)?;
        if n != bytes.len() || n > max {
            return Err(Error::protocol("Invalid OP_MSG length"));
        }
        if i32_at(bytes, 12)? != OP_MSG {
            return Err(Error::protocol("Expected OP_MSG"));
        }
        let flags = i32_at(bytes, 16)? as u32;
        if flags & 0xffff & !3 != 0 {
            return Err(Error::protocol("Unknown required OP_MSG flag"));
        }
        let end = if flags & CHECKSUM != 0 {
            if n < 30 {
                return Err(Error::protocol("Missing checksum"));
            }
            let end = n - 4;
            if crc32c(&bytes[..end]) != i32_at(bytes, end)? as u32 {
                return Err(Error::protocol("OP_MSG checksum mismatch"));
            }
            end
        } else {
            n
        };
        let sections = &bytes[20..end];
        let mut body = None;
        let mut at = 0;
        while at < sections.len() {
            let start = at;
            let kind = sections[at];
            at += 1;
            let size = length(sections, at, 5)?;
            let stop = at
                .checked_add(size)
                .filter(|&s| s <= sections.len())
                .ok_or_else(|| Error::protocol("Truncated section"))?;
            match kind {
                0 => {
                    if body.is_some() {
                        return Err(Error::protocol("Duplicate OP_MSG body"));
                    }
                    let d = RawDocument::from_bytes(&sections[at..stop])
                        .map_err(|_| Error::protocol("Invalid BSON body"))?;
                    validate(d, 0)?;
                    body = Some(d);
                }
                1 => {
                    let name_end = sections[at + 4..stop]
                        .iter()
                        .position(|&v| v == 0)
                        .map(|p| p + at + 4)
                        .ok_or_else(|| Error::protocol("Unterminated sequence identifier"))?;
                    let name = std::str::from_utf8(&sections[at + 4..name_end])
                        .map_err(|_| Error::protocol("Invalid sequence identifier"))?;
                    // No per-section identifier allocation: bounded re-scan of previous sections.
                    let mut prev = 0;
                    while prev < start {
                        let k = sections[prev];
                        prev += 1;
                        let sz = length(sections, prev, 5)?;
                        if k == 1 {
                            let e = sections[prev + 4..prev + sz]
                                .iter()
                                .position(|&b| b == 0)
                                .unwrap()
                                + prev
                                + 4;
                            if &sections[prev + 4..e] == name.as_bytes() {
                                return Err(Error::protocol("Duplicate sequence identifier"));
                            }
                        }
                        prev += sz;
                    }
                    let mut p = name_end + 1;
                    while p < stop {
                        let len = length(sections, p, 5)?;
                        let e = p
                            .checked_add(len)
                            .filter(|&e| e <= stop)
                            .ok_or_else(|| Error::protocol("Truncated sequence BSON"))?;
                        let d = RawDocument::from_bytes(&sections[p..e])
                            .map_err(|_| Error::protocol("Invalid sequence BSON"))?;
                        validate(d, 0)?;
                        p = e;
                    }
                }
                _ => return Err(Error::protocol("Unknown OP_MSG section type")),
            }
            at = stop;
        }
        let body = body.ok_or_else(|| Error::protocol("Missing OP_MSG body"))?;
        Ok(Self {
            request_id: i32_at(bytes, 4)?,
            response_to: i32_at(bytes, 8)?,
            flags,
            body,
            sections,
        })
    }
    /// Replaces only the body; document sequences retain their original bytes/order.
    pub fn encode_with_body(
        &self,
        out: &mut Vec<u8>,
        body: &RawDocument,
        max: usize,
    ) -> Result<()> {
        encode(out, self.request_id, 0, 0, body, &[], max)?;
        let mut at = 0;
        while at < self.sections.len() {
            let start = at;
            let kind = self.sections[at];
            at += 1;
            let n = i32_at(self.sections, at)? as usize;
            at += n;
            if kind == 1 {
                out.extend_from_slice(&self.sections[start..at]);
            }
        }
        if out.len() > max || out.len() > i32::MAX as usize {
            out.clear();
            return Err(Error::protocol("Message exceeds maxMessageSizeBytes"));
        }
        let n = out.len() as i32;
        out[..4].copy_from_slice(&n.to_le_bytes());
        Ok(())
    }
    pub fn sequences(&self) -> Sequences<'a> {
        Sequences {
            bytes: self.sections,
            at: 0,
        }
    }
}
fn validate(doc: &RawDocument, depth: usize) -> Result<()> {
    if depth > 100 {
        return Err(Error::protocol("BSON nesting exceeds 100"));
    }
    for el in doc {
        let (_, v) = el.map_err(|_| Error::protocol("Malformed BSON element"))?;
        match v {
            bson::raw::RawBsonRef::Document(d) => validate(d, depth + 1)?,
            bson::raw::RawBsonRef::Array(a) => {
                let d = RawDocument::from_bytes(a.as_bytes())
                    .map_err(|_| Error::protocol("Malformed BSON array"))?;
                validate(d, depth + 1)?;
            }
            _ => {}
        }
    }
    Ok(())
}
pub struct Sequence<'a> {
    pub identifier: &'a str,
    bytes: &'a [u8],
}
impl<'a> Sequence<'a> {
    pub fn documents(&self) -> impl Iterator<Item = &'a RawDocument> {
        let mut b = self.bytes;
        std::iter::from_fn(move || {
            if b.is_empty() {
                return None;
            }
            let n = i32_at(b, 0).unwrap() as usize;
            let d = RawDocument::from_bytes(&b[..n]).unwrap();
            b = &b[n..];
            Some(d)
        })
    }
}
pub struct Sequences<'a> {
    bytes: &'a [u8],
    at: usize,
}
impl<'a> Iterator for Sequences<'a> {
    type Item = Sequence<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        while self.at < self.bytes.len() {
            let k = self.bytes[self.at];
            self.at += 1;
            let n = i32_at(self.bytes, self.at).unwrap() as usize;
            let b = &self.bytes[self.at..self.at + n];
            self.at += n;
            if k == 1 {
                let e = b[4..].iter().position(|&v| v == 0).unwrap() + 4;
                return Some(Sequence {
                    identifier: std::str::from_utf8(&b[4..e]).unwrap(),
                    bytes: &b[e + 1..],
                });
            }
        }
        None
    }
}
/// Encodes raw documents into a reusable output buffer. No allocations after capacity warms.
pub fn encode(
    out: &mut Vec<u8>,
    request: i32,
    response: i32,
    flags: u32,
    body: &RawDocument,
    sequences: &[(&str, &[&RawDocument])],
    max: usize,
) -> Result<()> {
    out.clear();
    out.extend_from_slice(&[0; 16]);
    out[4..8].copy_from_slice(&request.to_le_bytes());
    out[8..12].copy_from_slice(&response.to_le_bytes());
    out[12..16].copy_from_slice(&OP_MSG.to_le_bytes());
    out.extend_from_slice(&flags.to_le_bytes());
    out.push(0);
    out.extend_from_slice(body.as_bytes());
    for (name, docs) in sequences {
        if name.as_bytes().contains(&0) {
            out.clear();
            return Err(Error::protocol("NUL in sequence identifier"));
        }
        out.push(1);
        let at = out.len();
        out.extend_from_slice(&[0; 4]);
        out.extend_from_slice(name.as_bytes());
        out.push(0);
        for doc in *docs {
            out.extend_from_slice(doc.as_bytes());
        }
        let n = out.len() - at;
        if n > i32::MAX as usize {
            out.clear();
            return Err(Error::protocol("Sequence too large"));
        }
        out[at..at + 4].copy_from_slice(&(n as i32).to_le_bytes());
    }
    let n = out.len() + if flags & CHECKSUM != 0 { 4 } else { 0 };
    if n > max || n > i32::MAX as usize {
        out.clear();
        return Err(Error::protocol("Message exceeds maxMessageSizeBytes"));
    }
    out[..4].copy_from_slice(&(n as i32).to_le_bytes());
    if flags & CHECKSUM != 0 {
        let c = crc32c(out);
        out.extend_from_slice(&c.to_le_bytes());
    }
    Ok(())
}
/// Bounded incremental frame buffer; the host drains a reply before feeding another.
#[derive(Debug)]
pub struct Decoder {
    bytes: Vec<u8>,
    max: usize,
}
impl Decoder {
    pub fn new(max: usize) -> Self {
        Self {
            bytes: Vec::with_capacity(8192),
            max,
        }
    }
    pub fn feed(&mut self, input: &[u8]) -> Result<usize> {
        let target = if self.bytes.len() < 4 {
            4
        } else {
            length(&self.bytes, 0, 16)?
        };
        if target > self.max {
            return Err(Error::protocol("Message exceeds maxMessageSizeBytes"));
        }
        let n = input.len().min(target - self.bytes.len());
        self.bytes.extend_from_slice(&input[..n]);
        if self.bytes.len() >= 4 && length(&self.bytes, 0, 16)? > self.max {
            return Err(Error::protocol("Message exceeds maxMessageSizeBytes"));
        }
        Ok(n)
    }
    pub fn complete(&self) -> bool {
        self.bytes.len() >= 4
            && i32_at(&self.bytes, 0).is_ok_and(|n| n as usize == self.bytes.len())
    }
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }
    pub fn clear(&mut self) {
        self.bytes.clear();
    }
    pub fn set_max(&mut self, max: usize) {
        self.max = max;
    }
}
/// Raw BSON command builder with a retained backing buffer. Nesting uses offsets,
/// so arrays/documents can be built without temporary Documents or key Strings.
#[derive(Debug, Default)]
pub struct BsonWriter {
    bytes: Vec<u8>,
}
impl BsonWriter {
    pub fn new() -> Self {
        Self {
            bytes: Vec::with_capacity(1024),
        }
    }
    pub fn clear(&mut self) {
        self.bytes.clear();
        self.bytes.extend_from_slice(&[0; 4]);
    }
    fn key(&mut self, kind: u8, key: &str) -> Result<()> {
        if key.as_bytes().contains(&0) {
            return Err(Error::protocol("NUL in BSON key"));
        }
        self.bytes.push(kind);
        self.bytes.extend_from_slice(key.as_bytes());
        self.bytes.push(0);
        Ok(())
    }
    pub fn string(&mut self, k: &str, v: &str) -> Result<()> {
        self.key(2, k)?;
        let n = i32::try_from(v.len() + 1).map_err(|_| Error::protocol("BSON string too large"))?;
        self.bytes.extend_from_slice(&n.to_le_bytes());
        self.bytes.extend_from_slice(v.as_bytes());
        self.bytes.push(0);
        Ok(())
    }
    pub fn int32(&mut self, k: &str, v: i32) -> Result<()> {
        self.key(16, k)?;
        self.bytes.extend_from_slice(&v.to_le_bytes());
        Ok(())
    }
    pub fn int64(&mut self, k: &str, v: i64) -> Result<()> {
        self.key(18, k)?;
        self.bytes.extend_from_slice(&v.to_le_bytes());
        Ok(())
    }
    pub fn boolean(&mut self, k: &str, v: bool) -> Result<()> {
        self.key(8, k)?;
        self.bytes.push(u8::from(v));
        Ok(())
    }
    pub fn document(&mut self, k: &str, d: &RawDocument) -> Result<()> {
        self.key(3, k)?;
        self.bytes.extend_from_slice(d.as_bytes());
        Ok(())
    }
    pub fn object_id(&mut self, key: &str, id: bson::oid::ObjectId) -> Result<()> {
        self.key(7, key)?;
        self.bytes.extend_from_slice(&id.bytes());
        Ok(())
    }
    pub fn timestamp(&mut self, key: &str, t: bson::Timestamp) -> Result<()> {
        self.key(17, key)?;
        self.bytes.extend_from_slice(&t.increment.to_le_bytes());
        self.bytes.extend_from_slice(&t.time.to_le_bytes());
        Ok(())
    }
    pub fn binary(&mut self, k: &str, subtype: u8, b: &[u8]) -> Result<()> {
        self.key(5, k)?;
        let n = i32::try_from(b.len()).map_err(|_| Error::protocol("Binary too large"))?;
        self.bytes.extend_from_slice(&n.to_le_bytes());
        self.bytes.push(subtype);
        self.bytes.extend_from_slice(b);
        Ok(())
    }
    pub fn start_document(&mut self, k: &str, array: bool) -> Result<usize> {
        self.key(if array { 4 } else { 3 }, k)?;
        let p = self.bytes.len();
        self.bytes.extend_from_slice(&[0; 4]);
        Ok(p)
    }
    pub fn end_document(&mut self, at: usize) -> Result<()> {
        if at.checked_add(4).is_none_or(|end| end > self.bytes.len()) {
            return Err(Error::protocol("Invalid BSON builder offset"));
        }
        self.bytes.push(0);
        let n =
            i32::try_from(self.bytes.len() - at).map_err(|_| Error::protocol("BSON too large"))?;
        self.bytes[at..at + 4].copy_from_slice(&n.to_le_bytes());
        Ok(())
    }
    pub fn finish(&mut self) -> Result<&RawDocument> {
        self.end_document(0)?;
        self.as_raw()
    }
    pub fn as_raw(&self) -> Result<&RawDocument> {
        RawDocument::from_bytes(&self.bytes).map_err(|_| Error::protocol("Unfinished BSON builder"))
    }
    pub fn append_fields(&mut self, doc: &RawDocument, omit: &[&str]) -> Result<()> {
        let b = doc.as_bytes();
        let mut start = 4;
        for el in doc.iter_elements() {
            let el = el.map_err(|_| Error::protocol("Malformed BSON options"))?;
            let range: Range<usize> = start..start + 1 + el.key().as_str().len() + 1 + el.size();
            if !omit.contains(&el.key().as_str()) {
                self.bytes.extend_from_slice(&b[range.clone()]);
            }
            start = range.end;
        }
        Ok(())
    }
}