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
// Copyright (c) 2021 bb8-mongodb developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! `bb8-mongodb` connection manager

use crate::error::Error;
use async_trait::async_trait;
use bb8::ManageConnection;
use mongodb::{bson::doc, options::ClientOptions, Client, Database};

/// A `bb8` connection manager for the `MongoDB` database
#[derive(Clone, Debug)]
pub struct Mongodb {
    client_options: ClientOptions,
    db_name: String,
}

impl Mongodb {
    /// Create a new `MongodbConnectionManager` given [`mongodb::options::ClientOptions`] and a database name
    pub fn new<T>(client_options: ClientOptions, db_name: T) -> Mongodb
    where
        T: Into<String>,
    {
        Mongodb {
            client_options,
            db_name: db_name.into(),
        }
    }
}

#[async_trait]
impl ManageConnection for Mongodb {
    type Connection = Database;
    type Error = Error;

    async fn connect(&self) -> Result<Self::Connection, Self::Error> {
        let client = Client::with_options(self.client_options.clone())?;
        Ok(client.database(&self.db_name))
    }

    async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
        let _doc = conn.run_command(doc! { "ping": 1 }, None).await?;
        Ok(())
    }

    fn has_broken(&self, _conn: &mut Self::Connection) -> bool {
        false
    }
}

#[cfg(test)]
mod test {
    use super::Mongodb;
    use anyhow::Result;
    use bb8::Pool;
    use mongodb::{
        bson::doc,
        options::{ClientOptions, Credential},
    };
    use std::env;

    #[tokio::test]
    async fn new_works() -> Result<()> {
        let mut client_options = ClientOptions::parse(env::var("BB8_MONGODB_URL")?).await?;
        client_options.credential = Some(
            Credential::builder()
                .username(env::var("BB8_MONGODB_USER").ok())
                .password(env::var("BB8_MONGODB_PASSWORD").ok())
                .build(),
        );

        // Setup the `bb8-mongodb` connection manager
        let connection_manager = Mongodb::new(client_options, "admin");
        // Setup the `bb8` connection pool
        let pool = Pool::builder().build(connection_manager).await?;
        // Connect
        let conn = pool.get().await?;
        assert_eq!(conn.name(), "admin");
        // Run a command
        let doc = conn.run_command(doc! { "ping": 1 }, None).await?;
        // Check the result
        assert_eq!(doc! { "ok": 1 }, doc);
        Ok(())
    }
}