fabric_cache_client/
client.rs

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
use crate::Error;
use serde::Serialize;
use serde_json::Value;
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpStream,
};

/// Client for interacting with your fabric server
pub struct FabricClient {
    stream: TcpStream,
}
impl FabricClient {
    /// Open a connection to your fabric server.
    pub async fn connect(addr: &str) -> tokio::io::Result<Self> {
        let stream = TcpStream::connect(addr).await?;
        Ok(FabricClient { stream })
    }

    /// Perform the SET command on a provided key to
    /// either insert, or update the value of the key.
    ///
    /// NOTE: That any data structure `T` for the value
    /// must implement the `serde::Serialize` trait.
    pub async fn set<T: Serialize>(&mut self, key: &str, value: &T) -> Result<(), Error> {
        let serialized_data = serde_json::to_string(value).map_err(Error::BadDataStructure)?;

        let command = format!("SET {} {}\n", key, serialized_data);
        self.stream.write_all(command.as_bytes()).await?;
        self.stream.flush().await?;

        let mut buffer = vec![0; 512];
        let n = self.stream.read(&mut buffer).await?;

        let resp = String::from_utf8_lossy(&buffer[..n]);
        if resp.contains("OK") {
            Ok(())
        } else {
            Err(Error::Unknown(resp.to_string()))
        }
    }

    /// Perform the GET command on a provided key to
    /// grab the current value of the key.
    pub async fn get<S: Into<String>>(&mut self, key: S) -> Result<Value, Error> {
        let command = format!("GET {}\n", key.into());
        self.stream.write_all(command.as_bytes()).await?;
        self.stream.flush().await?;

        let mut buffer = vec![0; 512];
        let n = self.stream.read(&mut buffer).await?;
        let response = String::from_utf8_lossy(&buffer[..n]).to_string();

        let value = serde_json::from_str(&response)?;
        Ok(value)
    }

    /// Perform the REMOVE command on a provided key to
    /// remove the key/value pair from cache.
    pub async fn remove(&mut self, key: &str) -> Result<(), Error> {
        let command = format!("REMOVE {}\n", key);
        self.stream.write_all(command.as_bytes()).await?;
        self.stream.flush().await?;

        let mut buffer = vec![0; 512];
        let n = self.stream.read(&mut buffer).await?;

        let resp = String::from_utf8_lossy(&buffer[..n]);
        if resp.contains("OK") {
            Ok(())
        } else {
            Err(Error::Unknown(resp.to_string()))
        }
    }
}