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
use std::io;
use redis::{Client, AsyncCommands, IntoConnectionInfo, RedisError, RedisResult};
use redis::aio::Connection;
use serde::{Serialize, Deserialize};
use thiserror::Error;

#[derive(Clone, Debug)]
pub struct RedisSessionStore {
    client: Client,
}

#[derive(Serialize, Deserialize)]
pub struct Session {
    pub credentials: String,
}

#[derive(Error, Debug)]
pub enum StoreError {
    #[error("io error ({0})")]
    Io(io::Error),
    #[error("json deserialization error ({0})")]
    Json(serde_json::Error),
    #[error("redis error ({0})")]
    Redis( #[from] RedisError)
}

impl From<serde_json::Error> for StoreError {
    fn from(err: serde_json::Error) -> StoreError {
        use serde_json::error::Category;
        match err.classify() {
            Category::Io => {
                StoreError::Io(err.into())
            }
            Category::Syntax | Category::Data | Category::Eof => {
                StoreError::Json(err)
            }
        }
    }
}

impl RedisSessionStore {
    pub(crate) async fn get(&self, sid: &str) -> Result<Option<Session>, StoreError> {
        let mut connection = self.connection().await?;
        let session_str: Option<String> = connection.get(sid).await?;
        match session_str {
            Some(json) => Ok(serde_json::from_str(&json)?),
            None => Ok(None)
        }
    }
    pub async fn set(&self, sid: &str, session: Session) -> Result<(), StoreError> {
        let session_str = serde_json::to_string(&session)?;
        let mut connection = self.connection().await?;
        connection.set(sid, session_str).await?;
        Ok(())
    }
    pub fn new(connection_info: impl IntoConnectionInfo) -> RedisResult<Self> {
        Ok(Self {client: Client::open(connection_info)?})
    }
    async fn connection(&self) -> RedisResult<Connection> {
        self.client.get_async_connection().await
    }
    pub async fn clear_store(&self, keys: &[&str]) -> Result<(), StoreError> {
        let mut connection = self.connection().await?;
        for key in keys {
            connection.del(key).await?
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn get_unknown_key() {
        assert!(create_store().await.get("unknown").await.unwrap().is_none())
    }

    #[tokio::test]
    async fn get_session() {
        let store = create_store().await;
        store.set("sid", Session {credentials: String::from("credentials") }).await.unwrap();

        let session = store.get("sid").await.unwrap().unwrap();

        assert_eq!(session.credentials, "credentials");
    }

    async fn create_store() -> RedisSessionStore {
        let store = RedisSessionStore::new("redis://redis/1").unwrap();
        store.clear_store(&["sid"]).await.unwrap();
        store
    }
}