rusty-store 0.2.4

A Rust library for managing and storing serialized data using RON (Rusty Object Notation). It provides utilities for handling various types of stores, managing their persistence, and offering abstractions for modifying and committing data.
Documentation
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, Write};
use std::path::PathBuf;
use thiserror::Error;

use log::debug;
use log::info;
use log::warn;

use crate::manager::StoreManager;

#[derive(Error, Debug)]
pub enum StoreError {
    #[error("RON parsing error: {0}")]
    RonParse(#[source] ron::error::SpannedError),

    #[error("RON error: {0}")]
    Ron(#[source] ron::error::Error),

    #[error("Failed to open file: {0}")]
    FileOpen(#[source] std::io::Error),

    #[error("Failed to read from file: {0}")]
    Read(#[source] std::io::Error),

    #[error("Failed to create directory: {0}")]
    CreateDir(#[source] std::io::Error),

    #[error("Failed to write to file: {0}")]
    Write(#[source] std::io::Error),
}

/// Represents the different types of storage locations that can be used for storing data.
///
/// The `StoringType` enum provides a way to specify where data should be stored, based on the
/// platform and the type of data. It includes variants for common storage locations such as
/// cache, data, and configuration directories, as well as a custom path option.
///
/// # Variants
///
/// - `Cache`: Path to the user's cache directory.
/// - `Data`: Path to the user's data directory.
/// - `Config`: Path to the user's configuration directory.
/// - `Custom(PathBuf)`: Custom path specified by the user.
#[derive(Debug, Default)]
pub enum StoringType {
    /// Path to the user's cache directory.
    ///
    /// |Platform | Value                               | Example                      |
    /// | ------- | ----------------------------------- | ---------------------------- |
    /// | Linux   | `$XDG_CACHE_HOME` or `$HOME`/.cache | /home/alice/.cache           |
    /// | macOS   | `$HOME`/Library/Caches              | /Users/Alice/Library/Caches  |
    /// | Windows | `{FOLDERID_LocalAppData}`           | C:\Users\Alice\AppData\Local |
    Cache,

    /// Path to the user's data directory.
    ///
    /// |Platform | Value                                    | Example                                  |
    /// | ------- | ---------------------------------------- | ---------------------------------------- |
    /// | Linux   | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share                 |
    /// | macOS   | `$HOME`/Library/Application Support      | /Users/Alice/Library/Application Support |
    /// | Windows | `{FOLDERID_RoamingAppData}`              | C:\Users\Alice\AppData\Roaming           |
    #[default]
    Data,

    /// Path to the user's config directory.
    ///
    /// |Platform | Value                                 | Example                                  |
    /// | ------- | ------------------------------------- | ---------------------------------------- |
    /// | Linux   | `$XDG_CONFIG_HOME` or `$HOME`/.config | /home/alice/.config                      |
    /// | macOS   | `$HOME`/Library/Application Support   | /Users/Alice/Library/Application Support |
    /// | Windows | `{FOLDERID_RoamingAppData}`           | C:\Users\Alice\AppData\Roaming           |
    Config,

    /// Custom path of the store save location
    Custom(PathBuf),
}

/// Trait allowing a struct to be managed by `Storage`.
///
/// The `Storing` trait provides a way to specify the type of storage location for a struct.
/// It requires the struct to implement `Serialize`, `Deserialize`, and `Default` traits.
///
/// # Example
///
/// ```
/// use rusty_store::{Storage, StoreHandle, Storing, StoringType};
/// use serde::{Deserialize, Serialize};
///
///
/// #[derive(Serialize, Deserialize, Default)]
/// struct MyStore {
///     pub count: u32,
/// }
///
/// impl Storing for MyStore {
///     fn store_type() -> StoringType {
///         StoringType::Data
///     }
/// }
/// ```
pub trait Storing: Serialize + for<'de> Deserialize<'de> + Default {
    fn store_type() -> StoringType {
        StoringType::default()
    }
}

/// `StoreHandle` acts as a container that holds store data in memory and provides methods to access
/// and modify this data. The `StoreHandle` does not manage storage directly but facilitates the read and
/// write operations by holding the data and its identifier.
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct StoreHandle<T> {
    store_id: String,
    store: T,
}

impl<T: Storing> StoreHandle<T> {
    /// Creates a new `StoreHandle` instance with the given `store_id`.
    ///
    /// # Arguments
    ///
    /// * `store_id` - A string slice that holds the identifier for the store.
    ///
    /// # Returns
    ///
    /// A new `StoreHandle` instance with the specified `store_id` and a default store.
    pub fn new(store_id: &str) -> Self {
        Self {
            store: T::default(),
            store_id: store_id.to_owned(),
        }
    }

    /// Sets the store data.
    ///
    /// # Arguments
    ///
    /// * `store` - The store data to be set.
    fn set_store(&mut self, store: T) {
        debug!("Setting store with id: {}", self.store_id);
        self.store = store;
    }

    /// Returns a mutable reference to the stored data.
    ///
    /// # Returns
    ///
    /// A mutable reference to the stored data.
    pub fn get_store_mut(&mut self) -> &mut T {
        &mut self.store
    }

    /// Returns a reference to the stored data.
    ///
    /// # Returns
    ///
    /// A reference to the stored data.
    pub fn get_store(&self) -> &T {
        &self.store
    }

    /// Returns a reference to the store identifier.
    ///
    /// # Returns
    ///
    /// A reference to the store identifier.
    pub fn store_id(&self) -> &str {
        &self.store_id
    }
}

/// Handles file system paths for reading from and writing to data storage.
///
/// The `Storage` struct provides a way to manage file paths used for storing data in different locations.
/// It simplifies the process of accessing and modifying data by providing methods for these operations.
///
/// # Example
///
/// ```
/// use rusty_store::{Storage, StoreHandle, Storing};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Default, Storing)]
/// pub struct MyStore {
///     pub count: u32,
/// }
///
/// impl MyStore {
///     fn increment_count(&mut self) {
///         self.count += 1;
///     }
/// }
///
///
/// // Initialize the Storage with the defaults
/// let storage = Storage::new("APP_ID");
///
/// // Create a handle for managing the store data.
/// let mut handle = StoreHandle::<MyStore>::new("my_store_id");
///
/// // Read existing store from storage
/// storage
///     .read(&mut handle)
///     .expect("Failed to read from storage");
///
/// // Modify the store data
/// let counter = handle.get_store_mut();
///
/// counter.increment_count();
/// counter.increment_count();
/// counter.increment_count();
///
/// // Write changes to disk
/// storage
///     .write(&mut handle)
///     .expect("Failed to write to storage");
///
/// let counter = handle.get_store();
///
/// println!("Count: {}", counter.count);
/// ```
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct Storage {
    cache_dir: PathBuf,
    data_dir: PathBuf,
    config_dir: PathBuf,
}

impl Storage {
    /// Creates a new `Storage` instance by obtaining the paths for cache, data, and configuration directories.
    ///
    /// # Panics
    ///
    /// - Panics if the cache directory, data directory, or configuration directory path cannot be determined.
    pub fn new(app_id: &str) -> Self {
        Self {
            data_dir: dirs::data_dir()
                .expect("Failed to determine cache directory path")
                .join(app_id),
            config_dir: dirs::config_dir()
                .expect("Failed to determine data directory path")
                .join(app_id),
            cache_dir: dirs::cache_dir()
                .expect("Failed to determine configuration directory path")
                .join(app_id),
        }
    }

    /// Creates a new `Storage` instance with specific cache, data, and config paths.
    ///
    /// # Arguments
    ///
    /// * `cache_dir` - A `PathBuf` representing the cache directory path.
    /// * `data_dir` - A `PathBuf` representing the data directory path.
    /// * `config_dir` - A `PathBuf` representing the configuration directory path.
    ///
    /// # Returns
    ///
    /// A new `Storage` instance with the specified cache, data, and config paths.
    ///
    /// # Example
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use rusty_store::Storage;
    ///
    /// let cache_dir = PathBuf::from("/path/to/cache");
    /// let data_dir = PathBuf::from("/path/to/data");
    /// let config_dir = PathBuf::from("/path/to/config");
    ///
    /// let storage = Storage::from_dirs(cache_dir, data_dir, config_dir);
    /// ```
    pub fn from_dirs(cache_dir: PathBuf, data_dir: PathBuf, config_dir: PathBuf) -> Self {
        Self {
            cache_dir,
            data_dir,
            config_dir,
        }
    }

    /// Returns a new StoreManager of type `T` with the given `store_id`
    pub fn new_manager<T: Storing>(&self, store_id: &str) -> Result<StoreManager<T>, StoreError> {
        StoreManager::<T>::new(self, store_id)
    }

    /// Returns a new Handle of type `T` with the given `store_id`
    pub fn new_handle<T: Storing>(&self, store_id: &str) -> StoreHandle<T> {
        StoreHandle::<T>::new(store_id)
    }

    /// Reads the store from a file and updates the provided `StoreHandle`.
    /// If the file does not exist, it creates a default store if a default is available.
    ///
    /// # Example
    ///
    /// ```
    /// use rusty_store::{Storage, StoreHandle, Storing};
    /// use serde::{Deserialize, Serialize};
    ///
    /// #[derive(Serialize, Deserialize, Default, Storing)]
    /// pub struct MyStore {
    ///     pub count: u32,
    /// }
    ///
    /// impl MyStore {
    ///     fn increment_count(&mut self) {
    ///         self.count += 1;
    ///     }
    /// }
    ///
    /// let storage = Storage::new("APP_ID");
    /// let mut handle: StoreHandle<MyStore> = StoreHandle::new("my_store_id");
    ///
    /// storage.read(&mut handle).expect("Failed to read store");
    ///
    /// ```
    pub fn read<T: Storing>(&self, handle: &mut StoreHandle<T>) -> Result<(), StoreError> {
        debug!("Reading store with id: {}", handle.store_id());
        self.open_file::<T, _>(
            |file, handle| {
                let store = Self::read_string(file).map_err(StoreError::Read)?;
                let store_data: T = ron::from_str(&store).map_err(StoreError::RonParse)?;

                handle.set_store(store_data);

                info!("Successfully read store with id: {}", handle.store_id());
                Ok(())
            },
            handle,
        )
    }

    /// Writes the current store `T` from the provided `StoreHandle` to a file.
    /// If the file does not exist, it creates a default store if a default is available.
    ///
    /// # Example
    ///
    /// ```
    /// use rusty_store::{Storage, StoreHandle, Storing};
    /// use serde::{Deserialize, Serialize};
    ///
    /// #[derive(Serialize, Deserialize, Default, Storing)]
    /// pub struct MyStore {
    ///     pub count: u32,
    /// }
    ///
    /// impl MyStore {
    ///     fn increment_count(&mut self) {
    ///         self.count += 1;
    ///     }
    /// }
    ///
    /// let storage = Storage::new("APP_ID");
    /// let mut handle: StoreHandle<MyStore> = StoreHandle::new("my_store_id");
    ///
    /// storage.write(&mut handle).expect("Failed to read store");
    ///
    /// ```
    pub fn write<T: Storing>(&self, handle: &mut StoreHandle<T>) -> Result<(), StoreError> {
        debug!("Writing store with id: {}", handle.store_id());
        self.open_file::<T, _>(
            |file: &mut File, handle| {
                let store = handle.get_store_mut();

                // Serialize current store to string
                let str =
                    ron::ser::to_string_pretty(&store, PrettyConfig::new().compact_arrays(true))
                        .map_err(StoreError::Ron)?;

                // Read current file content for comparison
                file.rewind().map_err(StoreError::Write)?;
                let existing = Self::read_string(file).map_err(StoreError::Read)?;

                // Skip writing if identical
                if existing == str {
                    debug!(
                        "Store unchanged, skipping write for id: {}",
                        handle.store_id()
                    );
                    return Ok(());
                }

                // Otherwise, overwrite file
                file.set_len(0).map_err(StoreError::Write)?;
                file.rewind().map_err(StoreError::Write)?;
                file.write_all(str.as_bytes()).map_err(StoreError::Write)?;
                file.flush().map_err(StoreError::Write)?;

                info!("Successfully wrote store with id: {}", handle.store_id());
                Ok(())
            },
            handle,
        )
    }

    /// Opens the file for reading or writing. If the file does not exist, it attempts
    /// to create a default store if a default is provided.
    fn open_file<T, F>(
        &self,
        mut operation: F,
        handle: &mut StoreHandle<T>,
    ) -> Result<(), StoreError>
    where
        T: Storing,
        F: FnMut(&mut File, &mut StoreHandle<T>) -> Result<(), StoreError>,
    {
        let mut dir_path = self.dir_path::<T>();
        dir_path.push(handle.store_id()); // i don't like this

        debug!("Opening file at path: {:?}", dir_path);

        match OpenOptions::new()
            .read(true)
            .write(true)
            .create(false)
            .truncate(false)
            .open(&dir_path)
        {
            Ok(mut config) => {
                debug!("File opened successfully at path: {:?}", dir_path);
                operation(&mut config, handle)
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                warn!(
                    "File not found at path: {:?}, creating default store",
                    dir_path
                );
                self.store_default::<T>(dir_path)?;
                self.open_file(operation, handle)
            }
            Err(err) => {
                warn!(
                    "Failed to open file at path: {:?}, error: {:?}",
                    dir_path, err
                );
                Err(StoreError::FileOpen(err))
            }
        }
    }

    fn store_default<T: Storing>(&self, path: PathBuf) -> Result<(), StoreError> {
        debug!("Storing default configuration at path: {:?}", path);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(StoreError::CreateDir)?;
            info!("Created directory for path: {:?}", parent);
        }

        let default_store = T::default();
        let str = ron::ser::to_string_pretty(&default_store, PrettyConfig::new())
            .map_err(StoreError::Ron)?;
        fs::write(&path, str).map_err(StoreError::Write)?;
        info!("Default store written at path: {:?}", &path);

        Ok(())
    }

    fn dir_path<T: Storing>(&self) -> PathBuf {
        let path = match T::store_type() {
            StoringType::Cache => self.cache_dir.clone(),
            StoringType::Data => self.data_dir.clone(),
            StoringType::Config => self.config_dir.clone(),
            StoringType::Custom(path) => path,
        };
        debug!(
            "Resolved directory path for store type: {:?} to path: {:?}",
            T::store_type(),
            path
        );
        path
    }

    fn read_string(mut file: &File) -> Result<String, std::io::Error> {
        let mut buf = String::new();
        file.read_to_string(&mut buf)?;
        debug!("Read string from file, length: {}", buf.len());
        Ok(buf)
    }
}