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
use async_trait::async_trait;
use log::debug;
use std::{
    env,
    ffi::OsStr,
    fs,
    io::{self, BufReader, BufWriter, ErrorKind, Read, Write},
    path::{Path, PathBuf},
    str,
};
use tokio::task::spawn_blocking;
use uuid::Uuid;

use crate::{pairing::Pairing, storage::Storage, Config, Error, Result};

/// [`FileStorage`](FileStorage) is an implementor of the [`Storage`](Storage) trait that stores data to the file
/// system.
#[derive(Debug)]
pub struct FileStorage {
    dir_path: PathBuf,
}

impl FileStorage {
    /// Creates a new [`FileStorage`](FileStorage).
    pub async fn new<D: AsRef<OsStr> + ?Sized>(dir: &D) -> Result<Self> {
        let dir_path = Path::new(dir).to_path_buf();
        let dir_path = spawn_blocking(move || -> Result<PathBuf> {
            fs::create_dir_all(&dir_path)?;

            Ok(dir_path)
        })
        .await??;

        Ok(FileStorage { dir_path })
    }

    /// Creates a new [`FileStorage`](FileStorage) with the current directory as storage path.
    pub async fn current_dir() -> Result<Self> {
        let current_dir =
            spawn_blocking(move || -> Result<PathBuf> { env::current_dir().map_err(Error::from) }).await??;
        let current_dir = current_dir.to_str().expect("couldn't stringify current_dir");
        let data_path = format!("{}/data", current_dir);

        Self::new(&data_path).await
    }

    fn path_to_file(&self, file: &str) -> PathBuf {
        let mut file_path = self.dir_path.clone();
        file_path.push(file);
        file_path
    }

    async fn get_reader(&self, file: &str) -> Result<BufReader<fs::File>> {
        let file_path = self.path_to_file(file);
        let reader = spawn_blocking(move || -> Result<BufReader<fs::File>> {
            let file = fs::OpenOptions::new().read(true).open(file_path)?;
            let reader = BufReader::new(file);

            Ok(reader)
        })
        .await??;

        Ok(reader)
    }

    async fn get_writer(&self, file: &str) -> Result<BufWriter<fs::File>> {
        let file_path = self.path_to_file(file);
        let writer = spawn_blocking(move || -> Result<BufWriter<fs::File>> {
            let file = fs::OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(file_path)?;
            let writer = BufWriter::new(file);

            Ok(writer)
        })
        .await??;

        Ok(writer)
    }

    async fn read_bytes(&self, key: &str) -> Result<Vec<u8>> {
        let mut reader = self.get_reader(key).await?;
        let value = spawn_blocking(move || -> Result<Vec<u8>> {
            let mut value = Vec::new();
            reader.read_to_end(&mut value)?;

            Ok(value)
        })
        .await??;

        Ok(value)
    }

    async fn write_bytes(&self, key: &str, value: Vec<u8>) -> Result<()> {
        let mut writer = self.get_writer(key).await?;
        spawn_blocking(move || -> Result<()> {
            writer.write_all(&value)?;

            Ok(())
        })
        .await??;

        Ok(())
    }

    async fn remove_file(&self, key: &str) -> Result<()> {
        let file_path = self.path_to_file(key);
        spawn_blocking(move || -> Result<()> {
            fs::remove_file(file_path)?;

            Ok(())
        })
        .await??;

        Ok(())
    }

    async fn keys_with_suffix(&self, suffix: &'static str) -> Result<Vec<String>> {
        let dir_path = self.dir_path.clone();
        let extension = Some(OsStr::new(suffix));
        let keys = spawn_blocking(move || -> Result<Vec<String>> {
            let mut keys = Vec::new();
            for entry in fs::read_dir(&dir_path)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension() == extension {
                    let key = path
                        .file_stem()
                        .ok_or(Error::from(io::Error::from(ErrorKind::NotFound)))?
                        .to_os_string()
                        .into_string()
                        .or(Err(Error::from(io::Error::from(ErrorKind::NotFound))))?;
                    keys.push(key);
                }
            }

            Ok(keys)
        })
        .await??;

        Ok(keys)
    }
}

#[async_trait]
impl Storage for FileStorage {
    async fn load_config(&self) -> Result<Config> {
        let config_bytes = self.read_bytes("config.json").await?;
        let config = serde_json::from_slice(&config_bytes)?;

        debug!("loaded Config: {:?}", &config);

        Ok(config)
    }

    async fn save_config(&mut self, config: &Config) -> Result<()> {
        let config_bytes = serde_json::to_vec(&config)?;
        self.write_bytes("config.json", config_bytes).await
    }

    async fn delete_config(&mut self) -> Result<()> {
        let key = format!("config.json");
        self.remove_file(&key).await
    }

    async fn load_aid_cache(&self) -> Result<Vec<u64>> {
        let aid_cache_bytes = self.read_bytes("aid_cache.json").await?;
        let aid_cache = serde_json::from_slice(&aid_cache_bytes)?;

        debug!("loaded AID cache: {:?}", &aid_cache);

        Ok(aid_cache)
    }

    async fn save_aid_cache(&mut self, aid_cache: &Vec<u64>) -> Result<()> {
        let aid_cache_bytes = serde_json::to_vec(&aid_cache)?;
        self.write_bytes("aid_cache.json", aid_cache_bytes).await
    }

    async fn delete_aid_cache(&mut self) -> Result<()> {
        let key = format!("aid_cache.json");
        self.remove_file(&key).await
    }

    async fn load_pairing(&self, id: &Uuid) -> Result<Pairing> {
        let key = format!("{}.json", id.to_string());
        let pairing_bytes = self.read_bytes(&key).await?;

        let pairing = Pairing::from_bytes(&pairing_bytes)?;

        debug!("loaded Pairing: {:?}", &pairing);

        Ok(pairing)
    }

    async fn save_pairing(&mut self, pairing: &Pairing) -> Result<()> {
        let key = format!("{}.json", pairing.id.to_string());
        let pairing_bytes = pairing.as_bytes()?;
        self.write_bytes(&key, pairing_bytes).await
    }

    async fn delete_pairing(&mut self, id: &Uuid) -> Result<()> {
        let key = format!("{}.json", id.to_string());
        self.remove_file(&key).await
    }

    async fn list_pairings(&self) -> Result<Vec<Pairing>> {
        let mut pairings = Vec::new();
        for key in self.keys_with_suffix("json").await? {
            if &key != "config" && &key != "identifier_cache" {
                let pairing_bytes = self.read_bytes(&key).await?;
                let pairing = Pairing::from_bytes(&pairing_bytes)?;
                pairings.push(pairing);
            }
        }

        Ok(pairings)
    }

    async fn count_pairings(&self) -> Result<usize> {
        let mut count = 0;
        for key in self.keys_with_suffix("json").await? {
            if &key != "config" && &key != "identifier_cache" {
                count += 1;
            }
        }

        Ok(count)
    }
}

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

    use crate::BonjourStatusFlag;

    #[tokio::test]
    /// Ensure we can write a config, then a shorter one, without corrupting data.
    async fn test_shorten_config() {
        let mut config = Default::default();
        let mut storage = FileStorage::new(&std::env::temp_dir()).await.unwrap();

        storage.save_config(&config).await.unwrap();
        config.status_flag = BonjourStatusFlag::Zero;
        storage.save_config(&config).await.unwrap();

        assert_eq!(
            storage.load_config().await.unwrap().status_flag,
            BonjourStatusFlag::Zero
        )
    }
}