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
//! The oplog module is responsible for building an iterator over a MongoDB replica set oplog with
//! any optional filtering criteria applied.

use bson::Document;
use mongodb::coll::options::{FindOptions, CursorType};
use mongodb::cursor::Cursor;
use mongodb::db::ThreadedDatabase;
use mongodb::{Client, ThreadedClient};

use {Operation, Result};

/// Oplog represents a MongoDB replica set oplog.
///
/// It implements the `Iterator` trait so it can be iterated over, yielding successive `Operation`s
/// as they are read from the server. This will effectively iterate forever as it will await new
/// operations.
///
/// Any errors raised while tailing the oplog (e.g. a connectivity issue) will cause the iteration
/// to end.
pub struct Oplog {
    /// The internal MongoDB cursor for the current position in the oplog.
    cursor: Cursor,
}

impl Iterator for Oplog {
    type Item = Operation;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.cursor.next() {
                Some(Ok(document)) => return Operation::new(&document).ok(),
                Some(Err(_)) => return None,
                None => continue,
            }
        }
    }
}

impl Oplog {
    /// Returns a new `Oplog` for the given MongoDB client with the default options.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # extern crate mongodb;
    /// # extern crate oplog;
    /// use mongodb::{Client, ThreadedClient};
    /// use oplog::Oplog;
    ///
    /// # fn main() {
    /// let client = Client::connect("localhost", 27017).expect("Failed to connect to MongoDB.");
    ///
    /// if let Ok(oplog) = Oplog::new(&client) {
    ///     // Do something with oplog.
    /// }
    /// # }
    /// ```
    pub fn new(client: &Client) -> Result<Oplog> {
        OplogBuilder::new(client).build()
    }
}

/// A builder for an `Oplog`.
///
/// This builder enables configuring a filter on the oplog so that only operations matching a given
/// criteria are returned (e.g. to set a start time or filter out unwanted operation types).
///
/// The lifetime `'a` refers to the lifetime of the MongoDB client.
#[derive(Clone)]
pub struct OplogBuilder<'a> {
    client: &'a Client,
    filter: Option<Document>,
}

impl<'a> OplogBuilder<'a> {
    /// Create a new builder for the given MongoDB client.
    ///
    /// The oplog is not built until `build` is called.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # extern crate mongodb;
    /// # extern crate oplog;
    /// use mongodb::{Client, ThreadedClient};
    /// use oplog::OplogBuilder;
    ///
    /// # fn main() {
    /// let client = Client::connect("localhost", 27017).expect("Failed to connect to MongoDB.");
    ///
    /// if let Ok(oplog) = OplogBuilder::new(&client).build() {
    ///     // Do something with oplog.
    /// }
    /// # }
    /// ```
    pub fn new(client: &'a Client) -> OplogBuilder<'a> {
        OplogBuilder {
            client: client,
            filter: None,
        }
    }

    /// Executes the query and builds the `Oplog`.
    pub fn build(&self) -> Result<Oplog> {
        let coll = self.client.db("local").collection("oplog.rs");

        let mut opts = FindOptions::new();
        opts.cursor_type = CursorType::TailableAwait;
        opts.no_cursor_timeout = true;

        let cursor = coll.find(self.filter.clone(), Some(opts))?;

        Ok(Oplog { cursor: cursor })
    }

    /// Provide an optional filter for the oplog.
    ///
    /// This is empty by default so all operations are returned.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # #[macro_use]
    /// # extern crate bson;
    /// # extern crate mongodb;
    /// # extern crate oplog;
    /// use mongodb::{Client, ThreadedClient};
    /// use oplog::OplogBuilder;
    ///
    /// # fn main() {
    /// let client = Client::connect("localhost", 27017).expect("Failed to connect to MongoDB.");
    ///
    /// if let Ok(oplog) = OplogBuilder::new(&client).filter(Some(doc! { "op" => "i" })).build() {
    ///     // Do something with filtered oplog.
    /// }
    /// # }
    /// ```
    #[allow(dead_code)]
    pub fn filter(&mut self, filter: Option<Document>) -> &mut OplogBuilder<'a> {
        self.filter = filter;
        self
    }
}