# filestore.rs - source
Source of the Rust file `src/defs/filestore.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
    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
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368

    use async_session::{Result, Session, SessionStore};
    use anyhow::anyhow;
    use async_trait::async_trait;
    use std::{
        fs,
        path::Path,
    };
    use walkdir::{DirEntry, WalkDir};
    use binascii::bin2hex;

    #[allow(unused)]
    fn is_hidden(entry: &DirEntry) -> bool {
        entry.file_name()
            .to_str()
            .map(|s| s.starts_with("."))
            .unwrap_or(false)
    }
    #[derive(Debug, Clone)]
    pub struct FileStore {
        pub sess_path: String,
        pub ses_file: String,
    }
    #[async_trait]
    impl SessionStore for FileStore {
        async fn load_session(&self, cookie_value: String) -> Result<Option<Session>> {
            let id = Session::id_from_cookie_value(&cookie_value)?;
            log::trace!("loading session by id `{}`", &id);
            //dbg!("loading session by id `{}`", &id);
            self.load_session_file(&id).await
        }
        async fn store_session(&self, session: Session) -> Result<Option<String>> {
            log::trace!("storing session by id `{}`", session.id());
            let id_filename = match self.get_path(session.id()) {
                Ok(res) => res,
                Err(e) => {
                    return Err(e);
                }
            };
            // let mut out_buffer = [0u8; 100];
            // let id_filename = if let Ok(res) = bin2hex(session.id().as_bytes(),&mut out_buffer) {
            //    std::str::from_utf8(res)?.to_owned()
            // } else {
            //    return Ok(None);
            // };
            let sess_id_path = format!("{}/{}", self.sess_path, &id_filename);
            if ! Path::new(&sess_id_path).exists() {
                fs::create_dir(&sess_id_path)?;
            }
            let content_session = serde_json::to_string(&session)?;
            fs::write(&format!("{}/{}",&sess_id_path, self.ses_file), content_session)?;
            //session.reset_data_changed(); // do not need is it is serialized in file write
            Ok(session.into_cookie_value())
        }
        async fn destroy_session(&self, session: Session) -> Result {
            log::trace!("destroying session by id `{}`", session.id());
            match self.get_path(session.id()) {
                Ok(res) => match self.get_session_id_path(&res) {
                    Ok(session_id_path) => Ok(fs::remove_file(&session_id_path)?),
                    Err(e) => Err(e),
                },
                Err(e) => Err(e)
            }
            // let mut out_buffer = [0u8; 100];
            // if let Ok(res) = bin2hex(session.id().as_bytes(),&mut out_buffer) {
            //     let id_filename = std::str::from_utf8(res)?.to_owned();
            //     Ok(fs::remove_file(
            //         &format!("{}/{}/{}",self.sess_path, &id_filename, self.ses_file)
            //     )?)
            // } else {
            //     Ok(())
            // }
        }
        async fn clear_store(&self) -> Result {
            log::trace!("clearing memory store");
            let sess_path = format!("{}", self.sess_path);
            fs::remove_dir_all(&sess_path)?;
            fs::create_dir(&sess_path)?;
            Ok(())
        }
    }
    impl FileStore {
        /// Create a new instance of FilesStore
        pub fn check_paths(&self) -> Result {
            if ! Path::new(&self.sess_path).exists() {
                fs::create_dir(&self.sess_path)?;
            }
            Ok(())
        }
        pub fn get_path(&self,id: &str) -> Result<String> {
            let mut out_buffer = [0u8; 100];
            match bin2hex(&id.as_bytes(),&mut out_buffer) {
                Ok(res) => Ok(std::str::from_utf8(res)?.to_owned()),
                Err(e) => {
                    Err(anyhow!("Filename path {} not generated: {:?}", &id, &e))
                }
            }
        }
        pub fn get_session_id_path(&self,id_filename: &str) -> Result<String> {
            let session_id_path = format!("{}/{}/{}",self.sess_path, id_filename, &self.ses_file);
            if ! Path::new(&session_id_path).exists() {
               Err(anyhow!("Filename path {} not found: {}", id_filename, &session_id_path ))
            } else {
                Ok(session_id_path)
            }
        }
        /// As session Id from `async_session` comes in base64 it will be not valid for OS filename
        /// `bin2hex` pass id to hex as bytes and from there to string or viceversa
        pub async fn load_session_file(&self, id: &str) -> Result<Option<Session>> {
            let session_id_path = match self.get_path(id) {
                Ok(res) => match self.get_session_id_path(&res) {
                    Ok(path) => path,
                    Err(e) => return Err(e),
                },
                Err(e) => {
                    return Err(e);
                }
            };
            // let mut out_buffer = [0u8; 100];
            // let id_filename = if let Ok(res) = bin2hex(&id.as_bytes(),&mut out_buffer) {
            //    std::str::from_utf8(res)?.to_owned()
            // } else {
            //    return Ok(None);
            // };
            // let session_id_path = format!("{}/{}/{}",self.sess_path, &id_filename, &self.ses_file);
            // dbg!(&session_id_path);
            if ! Path::new(&session_id_path).exists() {
                dbg!("No path: {}", &session_id_path);
                // let sess_id_path = format!("{}/{}", self.sess_path, &id_filename);
                // if ! Path::new(&sess_id_path).exists() {
                //     fs::create_dir(&sess_id_path)?;
                // }
                // create
            }
            if let Ok(session_content) = fs::read_to_string(&session_id_path) {
                // match serde_json::from_str::<serde_json::Value>(&session_content) {
                match serde_json::from_str::<Session>(&session_content) {
                    Ok(session) => {
                        Ok(session.validate())
                    },
                    Err(e) => {
                        dbg!("Error loading session content from {}: {}",&session_id_path, e);
                        //log::error!("Error loading session content from {}: {}",&session_id_path, e);
                        Ok(None)
                    }
                }
            } else {
                Ok(None)
            }
        }
        #[allow(dead_code)]
        pub async fn cleanup(&self) -> Result {
            log::trace!("cleaning up file store...");
            let mut count: usize = 0;
            let sess_path = format!("{}", self.sess_path);
            let walker = WalkDir::new(&sess_path).into_iter();
            for entry in walker.filter_entry(|e| !is_hidden(e)) {
                match entry {
                    Ok(dir_entry) => {
                        // println!("{}", &dir_entry.path().display());
                        if ! Path::new(&dir_entry.path()).is_dir() {
                            continue;
                        }
                        let session_file = format!("{}/{}",&dir_entry.path().display(), &self.ses_file);
                        let id_path = format!("{}",&dir_entry.path().display());
                        let id = id_path.replace(&sess_path,"");
                        if let Some(session) = self.load_session_file(&id).await.unwrap_or_default() {
                            if session.is_expired() {
                                let _ = fs::remove_file(&session_file);
                                log::trace!("found {} expired session",&id_path);
                                count +=1;
                            }
                        }
                    },
                    Err(e) =>  println!("Error on {}: {}", &sess_path, e)
                }
            }
            log::trace!("found {} expired session {} cleaned",&sess_path, count);
            Ok(())
        }
        #[allow(dead_code)]
        pub async fn count(&self) -> usize {
            let mut count: usize = 0;
            let sess_path = format!("{}", self.sess_path);
            let walker = WalkDir::new(&sess_path).into_iter();
            for entry in walker.filter_entry(|e| !is_hidden(e)) {
                match entry {
                    Ok(dir_entry) => {
                        // println!("{}", &dir_entry.path().display());
                        if ! Path::new(&dir_entry.path()).is_dir() {
                            continue;
                        }
                        let session_file = format!("{}/{}",&dir_entry.path().display(), &self.ses_file);
                        if Path::new(&session_file).exists() {
                            count +=1;
                        }
                    },
                    Err(e) =>  println!("Error on {}: {}", &sess_path, e)
                }
            }
            count
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use async_std::task;
        use std::time::Duration;
        const TEST_SESS_FILESTORE: &str = "/tmp/test_sess_filestore";
        const TEST_IDS_FILESTORE: &str = "/tmp/test_ids_filestore";

        #[async_std::test]
        async fn creating_a_new_session_with_no_expiry() -> Result {
            let sess_path_store = format!("{}_0", TEST_SESS_FILESTORE);
            let ids_path_store = format!("{}_0", TEST_IDS_FILESTORE);
            let _ = fs::remove_dir_all(&sess_path_store);
            let _ = fs::remove_dir_all(&ids_path_store);
            let store = FileStore {
                sess_path: sess_path_store.to_owned(),
                ses_file: String::from("session"),
            };
            store.check_paths()?;
            let mut session = Session::new();
            session.insert("key", "Hello")?;
            let cloned = session.clone();
            let cookie_value = store.store_session(session).await?.unwrap();
            assert!(true);
            let loaded_session = store.load_session(cookie_value).await?.unwrap();
            assert_eq!(cloned.id(), loaded_session.id());
            assert_eq!("Hello", &loaded_session.get::<String>("key").unwrap());
            assert!(!loaded_session.is_expired());
            assert!(loaded_session.validate().is_some());
            let _ = fs::remove_dir_all(&sess_path_store);
            let _ = fs::remove_dir_all(&ids_path_store);
            Ok(())
        }
        #[async_std::test]
        async fn updating_a_session() -> Result {
            let sess_path_store = format!("{}_1", TEST_SESS_FILESTORE);
            let _ = fs::remove_dir_all(&sess_path_store);
            let store = FileStore {
                sess_path: sess_path_store.to_owned(),
                ses_file: String::from("session"),
            };
            store.check_paths()?;

            let mut session = Session::new();

            session.insert("key", "value")?;
            let cookie_value = store.store_session(session).await?.unwrap();

            let mut session = store.load_session(cookie_value.clone()).await?.unwrap();
            session.insert("key", "other value")?;

            assert_eq!(store.store_session(session).await?, None);
            let session = store.load_session(cookie_value).await?.unwrap();
            assert_eq!(&session.get::<String>("key").unwrap(), "other value");
            fs::remove_dir_all(&sess_path_store)?;
            Ok(())
        }

        #[async_std::test]
        async fn updating_a_session_extending_expiry() -> Result {
            let sess_path_store = format!("{}_2", TEST_SESS_FILESTORE);
            let _ = fs::remove_dir_all(&sess_path_store);
            let store = FileStore {
                sess_path: sess_path_store.to_owned(),
                ses_file: String::from("session"),
            };
            store.check_paths()?;

            let mut session = Session::new();
            session.expire_in(Duration::from_secs(1));
            let original_expires = session.expiry().unwrap().clone();
            let cookie_value = store.store_session(session).await?.unwrap();

            let mut session = store.load_session(cookie_value.clone()).await?.unwrap();

            assert_eq!(session.expiry().unwrap(), &original_expires);
            session.expire_in(Duration::from_secs(3));
            let new_expires = session.expiry().unwrap().clone();
            assert_eq!(None, store.store_session(session).await?);

            let session = store.load_session(cookie_value.clone()).await?.unwrap();
            assert_eq!(session.expiry().unwrap(), &new_expires);

            task::sleep(Duration::from_secs(3)).await;
            assert_eq!(None, store.load_session(cookie_value).await?);
            fs::remove_dir_all(&sess_path_store)?;
            Ok(())
        }

        #[async_std::test]
        async fn creating_a_new_session_with_expiry() -> Result {
            let sess_path_store = format!("{}_3", TEST_SESS_FILESTORE);
            let _ = fs::remove_dir_all(&sess_path_store);
            let store = FileStore {
                sess_path: sess_path_store.to_owned(),
                ses_file: String::from("session"),
            };
            store.check_paths()?;

            let mut session = Session::new();
            session.expire_in(Duration::from_secs(3));
            session.insert("key", "value")?;
            let cloned = session.clone();

            let cookie_value = store.store_session(session).await?.unwrap();

            let loaded_session = store.load_session(cookie_value.clone()).await?.unwrap();
            assert_eq!(cloned.id(), loaded_session.id());
            assert_eq!("value", &*loaded_session.get::<String>("key").unwrap());

            assert!(!loaded_session.is_expired());

            task::sleep(Duration::from_secs(3)).await;
            assert_eq!(None, store.load_session(cookie_value).await?);
            fs::remove_dir_all(&sess_path_store)?;
            Ok(())
        }

        #[async_std::test]
        async fn destroying_a_single_session() -> Result {
            let sess_path_store = format!("{}_4", TEST_SESS_FILESTORE);
            let _ = fs::remove_dir_all(&sess_path_store);
            let store = FileStore {
                sess_path: sess_path_store.to_owned(),
                ses_file: String::from("session"),
            };
            store.check_paths()?;

            for _ in 0..3i8 {
                store.store_session(Session::new()).await?;
            }
            let cookie = store.store_session(Session::new()).await?.unwrap();
            assert_eq!(4, store.count().await);
            let session = store.load_session(cookie.clone()).await?.unwrap();
            store.destroy_session(session.clone()).await?;
            assert!(store.load_session(cookie).await.is_err());
            assert_eq!(3, store.count().await);

            // attempting to destroy the session again IS an ERROR, file should be deleted before
            assert!(store.destroy_session(session).await.is_err());
            fs::remove_dir_all(&sess_path_store)?;
            Ok(())
        }

        #[async_std::test]
        async fn clearing_the_whole_store() -> Result {
            let sess_path_store = format!("{}_5", TEST_SESS_FILESTORE);
            let _ = fs::remove_dir_all(&sess_path_store);
            let store = FileStore {
                sess_path: sess_path_store.to_owned(),
                ses_file: String::from("session"),
            };
            store.check_paths()?;

            for _ in 0..3i8 {
                store.store_session(Session::new()).await?;
            }
            assert_eq!(3, store.count().await);
            store.clear_store().await.unwrap();
            assert_eq!(0, store.count().await);
            fs::remove_dir_all(&sess_path_store)?;
            Ok(())
        }
    }