1use crate::{Error, ErrorKind, Result, wire::BsonWriter};
7use bson::{
8 Document,
9 raw::{RawArray, RawBsonRef, RawDocument},
10};
11#[derive(Debug, Default)]
12pub struct Command {
13 writer: BsonWriter,
14 scratch: BsonWriter,
15}
16impl Command {
17 pub fn new() -> Self {
18 Self {
19 writer: BsonWriter::new(),
20 scratch: BsonWriter::new(),
21 }
22 }
23 pub fn raw(&self) -> &RawDocument {
24 self.writer
25 .as_raw()
26 .expect("Command builder must finish successfully")
27 }
28 pub fn apply_client_options(
31 &mut self,
32 options: &crate::uri::Options,
33 write: bool,
34 ) -> Result<()> {
35 self.scratch.clear();
36 self.scratch.append_fields(self.writer.as_raw()?, &[])?;
37 if write
38 && self
39 .writer
40 .as_raw()?
41 .get("writeConcern")
42 .ok()
43 .flatten()
44 .is_none()
45 && ["w", "journal", "wtimeoutms"]
46 .iter()
47 .any(|k| options.raw.contains_key(*k))
48 {
49 let wc = self.scratch.start_document("writeConcern", false)?;
50 if let Some(w) = options.raw.get("w") {
51 if let Ok(n) = w.parse::<i32>() {
52 self.scratch.int32("w", n)?;
53 } else {
54 self.scratch.string("w", w)?;
55 }
56 }
57 if let Some(j) = options.raw.get("journal") {
58 self.scratch.boolean("j", j == "true")?;
59 }
60 if let Some(n) = options.raw.get("wtimeoutms") {
61 self.scratch.int64(
62 "wtimeout",
63 n.parse::<i64>().map_err(|_| {
64 Error::new(ErrorKind::InvalidArgument, "wtimeoutMS out of range")
65 })?,
66 )?;
67 }
68 self.scratch.end_document(wc)?;
69 }
70 if !write {
71 if let Some(level) = options.raw.get("readconcernlevel")
72 && self
73 .writer
74 .as_raw()?
75 .get("readConcern")
76 .ok()
77 .flatten()
78 .is_none()
79 {
80 let rc = self.scratch.start_document("readConcern", false)?;
81 self.scratch.string("level", level)?;
82 self.scratch.end_document(rc)?;
83 }
84 if options.read_preference != crate::uri::ReadPreference::Primary
85 && self
86 .writer
87 .as_raw()?
88 .get("$readPreference")
89 .ok()
90 .flatten()
91 .is_none()
92 {
93 let rp = self.scratch.start_document("$readPreference", false)?;
94 self.scratch
95 .string("mode", options.read_preference.as_str())?;
96 if !options.read_preference_tags.is_empty() {
97 let tags = self.scratch.start_document("tags", true)?;
98 for (i, set) in options.read_preference_tags.iter().enumerate() {
99 let mut b = [0; 20];
100 let tag = self.scratch.start_document(index(i, &mut b), false)?;
101 for (k, v) in set {
102 self.scratch.string(k, v)?;
103 }
104 self.scratch.end_document(tag)?;
105 }
106 self.scratch.end_document(tags)?;
107 }
108 if let Some(max) = options.max_staleness {
109 self.scratch
110 .int64("maxStalenessSeconds", max.as_secs() as i64)?;
111 }
112 self.scratch.end_document(rp)?;
113 }
114 }
115 self.scratch.finish()?;
116 std::mem::swap(&mut self.writer, &mut self.scratch);
117 Ok(())
118 }
119 fn begin(&mut self, name: &str, collection: Option<&str>) -> Result<()> {
120 self.writer.clear();
121 if let Some(c) = collection {
122 if c.is_empty() || c.contains('\0') {
123 return Err(Error::new(
124 ErrorKind::InvalidArgument,
125 "Invalid collection name",
126 ));
127 }
128 self.writer.string(name, c)
129 } else {
130 self.writer.int32(name, 1)
131 }
132 }
133 fn end(&mut self, db: &str, options: Option<&RawDocument>, omit: &[&str]) -> Result<()> {
134 if let Some(o) = options {
135 self.writer.append_fields(o, omit)?;
136 }
137 self.writer.string("$db", db)?;
138 self.writer.finish()?;
139 Ok(())
140 }
141 pub fn run(&mut self, db: &str, body: &RawDocument) -> Result<()> {
143 self.writer.clear();
144 self.writer.append_fields(body, &["$db"])?;
145 self.end(db, None, &[])
146 }
147 pub fn insert(
148 &mut self,
149 db: &str,
150 coll: &str,
151 ordered: bool,
152 options: Option<&RawDocument>,
153 ) -> Result<()> {
154 self.begin("insert", Some(coll))?;
155 self.writer.boolean("ordered", ordered)?;
156 self.end(db, options, &["insert", "documents", "ordered", "$db"])
157 }
158 pub fn update(
159 &mut self,
160 db: &str,
161 coll: &str,
162 ordered: bool,
163 options: Option<&RawDocument>,
164 ) -> Result<()> {
165 self.begin("update", Some(coll))?;
166 self.writer.boolean("ordered", ordered)?;
167 self.end(db, options, &["update", "updates", "ordered", "$db"])
168 }
169 pub fn delete(
170 &mut self,
171 db: &str,
172 coll: &str,
173 ordered: bool,
174 options: Option<&RawDocument>,
175 ) -> Result<()> {
176 self.begin("delete", Some(coll))?;
177 self.writer.boolean("ordered", ordered)?;
178 self.end(db, options, &["delete", "deletes", "ordered", "$db"])
179 }
180 pub fn find(
181 &mut self,
182 db: &str,
183 coll: &str,
184 filter: &RawDocument,
185 options: Option<&RawDocument>,
186 ) -> Result<()> {
187 self.begin("find", Some(coll))?;
188 self.writer.document("filter", filter)?;
189 self.end(db, options, &["find", "filter", "$db"])
190 }
191 pub fn find_one(&mut self, db: &str, coll: &str, filter: &RawDocument) -> Result<()> {
192 self.begin("find", Some(coll))?;
193 self.writer.document("filter", filter)?;
194 self.writer.int64("limit", 1)?;
195 self.writer.boolean("singleBatch", true)?;
196 self.end(db, None, &[])
197 }
198 pub fn aggregate(
199 &mut self,
200 db: &str,
201 coll: &str,
202 pipeline: &[&RawDocument],
203 options: Option<&RawDocument>,
204 ) -> Result<()> {
205 self.begin("aggregate", Some(coll))?;
206 let at = self.writer.start_document("pipeline", true)?;
207 for (i, d) in pipeline.iter().enumerate() {
208 let mut b = [0u8; 20];
209 self.writer.document(index(i, &mut b), d)?;
210 }
211 self.writer.end_document(at)?;
212 if options.is_none_or(|o| o.get_document("cursor").is_err()) {
213 let c = self.writer.start_document("cursor", false)?;
214 self.writer.end_document(c)?;
215 }
216 self.end(db, options, &["aggregate", "pipeline", "$db"])
217 }
218 pub fn count_documents(
220 &mut self,
221 db: &str,
222 coll: &str,
223 filter: &RawDocument,
224 skip: i64,
225 limit: i64,
226 ) -> Result<()> {
227 if skip < 0 || limit < 0 {
228 return Err(Error::new(
229 ErrorKind::InvalidArgument,
230 "count skip/limit must be nonnegative",
231 ));
232 }
233 self.begin("aggregate", Some(coll))?;
234 let pipeline = self.writer.start_document("pipeline", true)?;
235 let stage = self.writer.start_document("0", false)?;
236 self.writer.document("$match", filter)?;
237 self.writer.end_document(stage)?;
238 let mut i = 1;
239 for (key, n) in [("$skip", skip), ("$limit", limit)] {
240 if n > 0 {
241 let mut b = [0; 20];
242 let s = self.writer.start_document(index(i, &mut b), false)?;
243 self.writer.int64(key, n)?;
244 self.writer.end_document(s)?;
245 i += 1;
246 }
247 }
248 let mut b = [0; 20];
249 let stage = self.writer.start_document(index(i, &mut b), false)?;
250 let group = self.writer.start_document("$group", false)?;
251 self.writer.int32("_id", 1)?;
252 let n = self.writer.start_document("n", false)?;
253 self.writer.int32("$sum", 1)?;
254 self.writer.end_document(n)?;
255 self.writer.end_document(group)?;
256 self.writer.end_document(stage)?;
257 self.writer.end_document(pipeline)?;
258 let c = self.writer.start_document("cursor", false)?;
259 self.writer.end_document(c)?;
260 self.end(db, None, &[])
261 }
262 pub fn estimated_document_count(
263 &mut self,
264 db: &str,
265 coll: &str,
266 options: Option<&RawDocument>,
267 ) -> Result<()> {
268 self.begin("count", Some(coll))?;
269 self.end(db, options, &["count", "$db"])
270 }
271 pub fn distinct(
272 &mut self,
273 db: &str,
274 coll: &str,
275 key: &str,
276 filter: &RawDocument,
277 options: Option<&RawDocument>,
278 ) -> Result<()> {
279 self.begin("distinct", Some(coll))?;
280 self.writer.string("key", key)?;
281 self.writer.document("query", filter)?;
282 self.end(db, options, &["distinct", "key", "query", "$db"])
283 }
284 pub fn find_one_and_modify(
287 &mut self,
288 db: &str,
289 coll: &str,
290 filter: &RawDocument,
291 update: Option<&RawDocument>,
292 options: Option<&RawDocument>,
293 ) -> Result<()> {
294 self.begin("findAndModify", Some(coll))?;
295 self.writer.document("query", filter)?;
296 if let Some(u) = update {
297 self.writer.document("update", u)?;
298 } else {
299 self.writer.boolean("remove", true)?;
300 }
301 self.end(
302 db,
303 options,
304 &["findAndModify", "query", "update", "remove", "$db"],
305 )
306 }
307 pub fn create_indexes(
308 &mut self,
309 db: &str,
310 coll: &str,
311 indexes: &[&RawDocument],
312 options: Option<&RawDocument>,
313 ) -> Result<()> {
314 if indexes.is_empty() {
315 return Err(Error::new(
316 ErrorKind::InvalidArgument,
317 "Index list must not be empty",
318 ));
319 }
320 self.begin("createIndexes", Some(coll))?;
321 let a = self.writer.start_document("indexes", true)?;
322 for (i, d) in indexes.iter().enumerate() {
323 let mut b = [0; 20];
324 self.writer.document(index(i, &mut b), d)?;
325 }
326 self.writer.end_document(a)?;
327 self.end(db, options, &["createIndexes", "indexes", "$db"])
328 }
329 pub fn list_indexes(&mut self, db: &str, coll: &str) -> Result<()> {
330 self.begin("listIndexes", Some(coll))?;
331 self.end(db, None, &[])
332 }
333 pub fn drop_index(&mut self, db: &str, coll: &str, name: &str) -> Result<()> {
334 self.begin("dropIndexes", Some(coll))?;
335 self.writer.string("index", name)?;
336 self.end(db, None, &[])
337 }
338 pub fn list_databases(&mut self, name_only: bool) -> Result<()> {
339 self.begin("listDatabases", None)?;
340 self.writer.boolean("nameOnly", name_only)?;
341 self.end("admin", None, &[])
342 }
343 pub fn list_collections(
344 &mut self,
345 db: &str,
346 name_only: bool,
347 filter: &RawDocument,
348 ) -> Result<()> {
349 self.begin("listCollections", None)?;
350 self.writer.boolean("nameOnly", name_only)?;
351 self.writer.document("filter", filter)?;
352 self.end(db, None, &[])
353 }
354 pub fn get_more(
355 &mut self,
356 db: &str,
357 coll: &str,
358 id: i64,
359 batch_size: Option<i32>,
360 max_time_ms: Option<i64>,
361 ) -> Result<()> {
362 self.writer.clear();
363 self.writer.int64("getMore", id)?;
364 self.writer.string("collection", coll)?;
365 if let Some(n) = batch_size {
366 if n <= 0 {
367 return Err(Error::new(
368 ErrorKind::InvalidArgument,
369 "getMore batchSize must be positive",
370 ));
371 }
372 self.writer.int32("batchSize", n)?;
373 }
374 if let Some(n) = max_time_ms {
375 self.writer.int64("maxTimeMS", n)?;
376 }
377 self.end(db, None, &[])
378 }
379 pub fn kill_cursor(&mut self, db: &str, coll: &str, id: i64) -> Result<()> {
380 self.begin("killCursors", Some(coll))?;
381 let a = self.writer.start_document("cursors", true)?;
382 self.writer.int64("0", id)?;
383 self.writer.end_document(a)?;
384 self.end(db, None, &[])
385 }
386}
387fn index(mut n: usize, b: &mut [u8; 20]) -> &str {
388 let mut at = b.len();
389 loop {
390 at -= 1;
391 b[at] = b'0' + (n % 10) as u8;
392 n /= 10;
393 if n == 0 {
394 break;
395 }
396 }
397 std::str::from_utf8(&b[at..]).unwrap()
398}
399#[derive(Default)]
401pub struct WriteModel {
402 writer: BsonWriter,
403}
404impl WriteModel {
405 pub fn update(
406 &mut self,
407 filter: &RawDocument,
408 update: &RawDocument,
409 multi: bool,
410 upsert: bool,
411 options: Option<&RawDocument>,
412 ) -> Result<&RawDocument> {
413 self.writer.clear();
414 self.writer.document("q", filter)?;
415 self.writer.document("u", update)?;
416 self.writer.boolean("multi", multi)?;
417 self.writer.boolean("upsert", upsert)?;
418 if let Some(o) = options {
419 self.writer
420 .append_fields(o, &["q", "u", "multi", "upsert"])?;
421 }
422 self.writer.finish()
423 }
424 pub fn delete(
425 &mut self,
426 filter: &RawDocument,
427 many: bool,
428 options: Option<&RawDocument>,
429 ) -> Result<&RawDocument> {
430 self.writer.clear();
431 self.writer.document("q", filter)?;
432 self.writer.int32("limit", if many { 0 } else { 1 })?;
433 if let Some(o) = options {
434 self.writer.append_fields(o, &["q", "limit"])?;
435 }
436 self.writer.finish()
437 }
438}
439pub struct CursorBatch<'a> {
441 pub id: i64,
442 pub namespace: &'a str,
443 pub documents: &'a RawArray,
444 pub post_batch_resume_token: Option<&'a RawDocument>,
445}
446impl<'a> CursorBatch<'a> {
447 pub fn parse(reply: &'a RawDocument) -> Result<Self> {
448 crate::Error::from_response(reply)?;
449 let c = reply
450 .get_document("cursor")
451 .map_err(|_| Error::protocol("Missing cursor"))?;
452 Ok(Self {
453 id: c
454 .get_i64("id")
455 .map_err(|_| Error::protocol("Missing cursor id"))?,
456 namespace: c
457 .get_str("ns")
458 .map_err(|_| Error::protocol("Missing cursor namespace"))?,
459 documents: c
460 .get("firstBatch")
461 .ok()
462 .flatten()
463 .or_else(|| c.get("nextBatch").ok().flatten())
464 .and_then(|v| v.as_array())
465 .ok_or_else(|| Error::protocol("Missing cursor batch"))?,
466 post_batch_resume_token: c
467 .get("postBatchResumeToken")
468 .ok()
469 .flatten()
470 .and_then(|v| v.as_document()),
471 })
472 }
473 pub fn rows(&self) -> impl Iterator<Item = Result<&'a RawDocument>> + use<'a> {
475 self.documents.into_iter().map(|v| match v {
476 Ok(RawBsonRef::Document(d)) => Ok(d),
477 _ => Err(Error::protocol("Cursor batch contains non-document")),
478 })
479 }
480}
481#[derive(Debug)]
482pub struct Cursor {
483 pub id: i64,
484 pub database: String,
485 pub collection: String,
486 pub server: String,
487 pub batch_size: Option<i32>,
488 remaining: Option<u64>,
489}
490impl Cursor {
491 pub fn new(
492 namespace: &str,
493 server: String,
494 limit: Option<u64>,
495 batch_size: Option<i32>,
496 ) -> Result<Self> {
497 let (db, coll) = namespace
498 .split_once('.')
499 .ok_or_else(|| Error::protocol("Invalid cursor namespace"))?;
500 Ok(Self {
501 id: 0,
502 database: db.into(),
503 collection: coll.into(),
504 server,
505 batch_size,
506 remaining: limit.filter(|v| *v != 0),
507 })
508 }
509 pub fn accept(&mut self, batch: &CursorBatch<'_>) -> Result<usize> {
511 if batch.namespace.split_once('.')
512 != Some((self.database.as_str(), self.collection.as_str()))
513 {
514 return Err(Error::protocol("Cursor namespace changed"));
515 }
516 self.id = batch.id;
517 let count = batch.rows().try_fold(0usize, |n, row| row.map(|_| n + 1))?;
518 let take = self.remaining.map_or(count, |n| count.min(n as usize));
519 if let Some(n) = &mut self.remaining {
520 *n -= take as u64;
521 }
522 Ok(take)
523 }
524 pub fn needs_kill(&self) -> bool {
525 self.id != 0 && self.remaining == Some(0)
526 }
527 pub fn get_more(&self, cmd: &mut Command) -> Result<bool> {
528 if self.id == 0 || self.needs_kill() {
529 return Ok(false);
530 }
531 let size = match (self.batch_size, self.remaining) {
532 (Some(n), Some(r)) => Some(n.min(r.min(i32::MAX as u64) as i32)),
533 (n, _) => n,
534 };
535 cmd.get_more(&self.database, &self.collection, self.id, size, None)?;
536 Ok(true)
537 }
538}
539#[derive(Debug)]
550pub struct WriteResult<'a> {
551 pub count: i64,
552 pub modified_count: i64,
553 pub upserted: Option<&'a RawArray>,
554 pub write_errors: Option<&'a RawArray>,
556 pub write_concern_error: Option<&'a RawDocument>,
558}
559impl<'a> WriteResult<'a> {
560 pub fn parse(r: &'a RawDocument) -> Result<Self> {
565 Error::from_response(r)?;
566 Self::decode(r)
567 }
568 pub fn decode(r: &'a RawDocument) -> Result<Self> {
572 if crate::error::number(r, "ok").unwrap_or(0.0) == 0.0 {
573 Error::from_response(r)?;
574 }
575 Ok(Self {
576 count: integer(r, "n")?,
577 modified_count: integer(r, "nModified").unwrap_or(0),
578 upserted: r.get("upserted").ok().flatten().and_then(|v| v.as_array()),
579 write_errors: r
580 .get("writeErrors")
581 .ok()
582 .flatten()
583 .and_then(|v| v.as_array()),
584 write_concern_error: r
585 .get("writeConcernError")
586 .ok()
587 .flatten()
588 .and_then(|v| v.as_document()),
589 })
590 }
591 pub fn succeeded(&self) -> bool {
593 self.write_errors
594 .is_none_or(|a| a.into_iter().next().is_none())
595 && self.write_concern_error.is_none()
596 }
597}
598fn integer(d: &RawDocument, k: &str) -> Result<i64> {
599 match d.get(k).ok().flatten() {
600 Some(RawBsonRef::Int32(v)) => Ok(i64::from(v)),
601 Some(RawBsonRef::Int64(v)) => Ok(v),
602 _ => Err(Error::protocol("Missing integer result field")),
603 }
604}
605
606#[derive(Debug, Default)]
609pub struct BulkResult {
610 pub count: i64,
611 pub modified_count: i64,
612 pub write_errors: Vec<Document>,
613 pub write_concern_errors: Vec<Document>,
614}
615impl BulkResult {
616 pub fn accept(&mut self, reply: &RawDocument, offset: i32, ordered: bool) -> Result<bool> {
617 let result = WriteResult::decode(reply)?;
618 self.count += result.count;
619 self.modified_count += result.modified_count;
620 let mut errors = false;
621 if let Some(a) = result.write_errors {
622 for e in a {
623 let e = e.map_err(|_| Error::protocol("Invalid write error"))?;
624 let d = e
625 .as_document()
626 .ok_or_else(|| Error::protocol("Invalid write error"))?;
627 let mut d: Document = d
628 .try_into()
629 .map_err(|_| Error::protocol("Invalid write error BSON"))?;
630 d.insert(
631 "index",
632 d.get_i32("index")
633 .map_err(|_| Error::protocol("Missing write error index"))?
634 + offset,
635 );
636 self.write_errors.push(d);
637 errors = true;
638 }
639 }
640 if let Some(c) = result.write_concern_error {
641 self.write_concern_errors.push(
642 c.try_into()
643 .map_err(|_| Error::protocol("Invalid write concern error"))?,
644 );
645 }
646 Ok(!(ordered && errors))
647 }
648}
649
650pub struct BulkBatcher<'a> {
653 documents: &'a [&'a RawDocument],
654 at: usize,
655 overhead: usize,
656 max_message: usize,
657 max_bson: usize,
658 max_count: usize,
659}
660pub struct BulkBatch<'a> {
661 pub offset: usize,
662 pub documents: &'a [&'a RawDocument],
663}
664impl<'a> BulkBatcher<'a> {
665 pub fn new(
666 documents: &'a [&'a RawDocument],
667 body: &RawDocument,
668 identifier: &str,
669 max_message: usize,
670 max_bson: usize,
671 max_count: usize,
672 ) -> Result<Self> {
673 let overhead = 16 + 4 + 1 + body.as_bytes().len() + 1 + 4 + identifier.len() + 1;
674 if documents.is_empty()
675 || max_count == 0
676 || overhead >= max_message
677 || body.as_bytes().len() > max_bson
678 {
679 return Err(Error::new(
680 ErrorKind::InvalidArgument,
681 "Invalid bulk write size or empty batch",
682 ));
683 }
684 for d in documents {
685 if d.as_bytes().len() > max_bson || d.as_bytes().len() > max_message - overhead {
686 return Err(Error::new(
687 ErrorKind::InvalidArgument,
688 "Document exceeds MongoDB size limit",
689 ));
690 }
691 }
692 Ok(Self {
693 documents,
694 at: 0,
695 overhead,
696 max_message,
697 max_bson,
698 max_count,
699 })
700 }
701 pub fn next_batch(&mut self) -> Option<BulkBatch<'a>> {
702 if self.at == self.documents.len() {
703 return None;
704 }
705 let start = self.at;
706 let mut bytes = self.overhead;
707 while self.at < self.documents.len() && self.at - start < self.max_count {
708 let n = self.documents[self.at].as_bytes().len();
709 if n > self.max_bson || n > self.max_message - bytes {
710 break;
711 }
712 bytes += n;
713 self.at += 1;
714 }
715 Some(BulkBatch {
716 offset: start,
717 documents: &self.documents[start..self.at],
718 })
719 }
720}
721pub struct ObjectIdGenerator {
730 random: [u8; 5],
731 counter: u32,
732}
733impl ObjectIdGenerator {
734 pub fn new(random: [u8; 5], counter: u32) -> Self {
735 Self {
736 random,
737 counter: counter & 0x00ff_ffff,
738 }
739 }
740 pub fn generate(&mut self, unix_seconds: u32) -> bson::oid::ObjectId {
741 let mut bytes = [0; 12];
742 bytes[..4].copy_from_slice(&unix_seconds.to_be_bytes());
743 bytes[4..9].copy_from_slice(&self.random);
744 bytes[9..].copy_from_slice(&self.counter.to_be_bytes()[1..]);
745 self.counter = self.counter.wrapping_add(1) & 0x00ff_ffff;
746 bson::oid::ObjectId::from_bytes(bytes)
747 }
748}