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
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate rand;
extern crate websocket;

use std::error::Error;
use std::fmt;
use std::net::TcpStream;

use serde_json as json;
use websocket as ws;

mod uuid;
mod value;

pub use self::value::Value;

pub struct ClientBuilder<'a> {
    builder: ws::ClientBuilder<'a>,
}

impl<'a> ClientBuilder<'a> {
    pub fn new(addr: &str) -> Result<Self, Box<Error>> {
        let builder = ws::ClientBuilder::new(addr)?;
        Ok(ClientBuilder { builder })
    }

    pub fn connect(&mut self) -> Result<Client, Box<Error>> {
        let conn = self.builder.connect_insecure()?;
        Ok(Client { conn })
    }
}

pub struct Client {
    conn: ws::sync::Client<TcpStream>,
}

impl Client {
    const SET: &'static str = "set";
    const GET: &'static str = "get";
    const SUB: &'static str = "subscribe";

    pub fn get(&mut self, path: String) -> Result<Value, Box<Error>> {
        let res = self.req(Request {
            action: Self::GET,
            request_id: uuid::gen(),
            path,
            value: None,
        })?;

        // None is a valid value
        Value::from_json(res.value.unwrap_or(json::Value::Null))
    }

    pub fn set(&mut self, path: String, value: Value) -> Result<(), Box<Error>> {
        self.req(Request {
            action: Self::SET,
            request_id: uuid::gen(),
            path,
            value: Some(From::from(value)),
        })?;
        Ok(())
    }

    pub fn sub<F: Fn(Value)>(&mut self, path: String, handler: F) -> Result<(), Box<Error>> {
        let res = self.req(Request {
            action: Self::SUB,
            request_id: uuid::gen(),
            path,
            value: None,
        })?;

        let sid = res.subscription_id.expect("subscription_id is missing");
        loop {
            let res = self.rx()?;
            if *res.subscription_id.as_ref().unwrap() != sid {
                return Err(From::from("sid mismatch"));
            }
            handler(Value::from_json(res.value.unwrap_or(json::Value::Null))?);
        }
    }

    fn req(&mut self, req: Request) -> Result<Response, Box<Error>> {
        let msg = ws::OwnedMessage::Text(json::to_string(&req).unwrap());
        self.conn.send_message(&msg)?;

        let res = self.rx()?;
        if *res.request_id.as_ref().unwrap() != req.request_id {
            return Err(From::from("rid mismatch"));
        }
        Ok(res)
    }

    fn rx(&mut self) -> Result<Response, Box<Error>> {
        match self.conn.recv_message()? {
            ws::OwnedMessage::Text(s) => {
                let res: Response = json::from_str(s.as_str()).unwrap();
                if let Some(err) = res.error {
                    return Err(From::from(err));
                }
                Ok(res)
            }
            _ => panic!("unknown message type"),
        }
    }
}

impl Drop for Client {
    fn drop(&mut self) {
        if let Err(err) = self.conn.send_message(&ws::OwnedMessage::Close(Some(
            ws::CloseData::new(
                1000, // normal closure
                String::from("adios"),
            ),
        ))) {
            eprintln!("disconnect message error: {}", err);
        }
        if let Err(err) = self.conn.shutdown() {
            eprintln!("shutdown error: {}", err)
        }
    }
}

#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Request {
    action: &'static str,
    path: String,
    request_id: String,
    value: Option<json::Value>,
    // filters: ?
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Response {
    action: String,
    path: Option<String>,
    value: Option<json::Value>,
    request_id: Option<String>,
    timestamp: Option<f64>,
    subscription_id: Option<String>,
    error: Option<ResponseError>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ResponseError {
    number: f64,
    reason: Option<String>,
    message: Option<String>,
}

impl fmt::Display for ResponseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} {} {}",
            self.number,
            self.reason.as_ref().unwrap_or(&String::from("unknown")),
            self.message.as_ref().unwrap_or(&String::from("unknown"))
        )
    }
}

impl Error for ResponseError {
    fn description(&self) -> &str {
        "ResponseError"
    }
}