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
extern crate rand;

use crate::client_stub::DgraphClientStub;
use crate::types::Operation;
use std::error::Error;
use std::fmt;
use rand::Rng;
use crate::txn::Txn;
use std::time::SystemTime;

#[derive(Debug, Clone)]
pub struct NoClients {}

impl fmt::Display for NoClients {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ERR_NO_CLIENTS")
    }
}

impl Error for NoClients {
    fn description(&self) -> &str {
        "No clients provided in DgraphClient constructor"
    }

    fn cause(&self) -> Option<&Error> {
        // Generic error, underlying cause isn't tracked.
        None
    }
}

fn no_clients_error() -> NoClients {
    let err = NoClients {};
    err
}

pub struct DgraphClient {
    clients: Vec<DgraphClientStub>,
    debug_mode: bool,
}

impl DgraphClient {
    pub fn any_client(&self) -> &DgraphClientStub {
        let mut rng = rand::thread_rng();
        let i = rng.gen_range(0, self.clients.len());
        let client = self.clients.get(i).unwrap();
        client
    }

    pub fn new(clients: Vec<DgraphClientStub>) -> Result<DgraphClient, Box<Error>> {
        if clients.len() == 0 {
            Err(Box::new(no_clients_error()))
        } else {
            Ok(DgraphClient {
                clients,
                debug_mode: false,
            })
        }
    }

    pub fn alter(&self, op: Operation) -> Result<String, Box<Error>> {
        self.debug(format!("Alter request: {:?}", op));
        let client = self.any_client();
        let start_time = SystemTime::now();
        let result = client.alter(op);
        self.debug(format!("Alter request {:?}", start_time.elapsed()?.subsec_nanos()));
        result
    }

    pub fn new_txn(&self) -> Txn {
        Txn::new(&self)
    }

    pub fn set_debug_mode(&mut self, debug_mode: bool) {
        self.debug_mode = debug_mode;
    }

    pub fn debug(&self, message: String) {
        if self.debug_mode == true {
            println!("{}", message);
        }
    }
}