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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

pub mod dummy_storage;
pub mod file_storage;
pub mod memory_storage;

use thiserror::Error;

/// A trait for giving a type a custom storage implementation
///
/// The `Storage` is used to store the collection content locally.
/// # How can I implement ```Storage```?
/// ```rust
/// # use remote_settings_client::{SignatureError, Verification, Storage, StorageError};
/// # use remote_settings_client::client::Collection;
/// struct MyStore {}
///
/// impl Storage for MyStore {
///     fn store(&mut self, key: &str, value: Vec<u8>) -> Result<(), StorageError> {
///         Ok(())
///     }
///
///     fn retrieve(&self, key: &str) -> Result<Vec<u8>, StorageError> {
///         Ok(Vec::new())
///     }
/// }
/// ```
pub trait Storage: Send + Sync {
    /// Store a key, value pair.
    ///
    /// # Errors
    /// If an error occurs while storing, a [`StorageError::WriteError`] is returned.
    fn store(&mut self, key: &str, value: Vec<u8>) -> Result<(), StorageError>;

    /// Retrieve a value for a given key.
    ///
    /// # Errors
    /// If the specified key does not exist, a [`StorageError::KeyNotFound`] is returned.
    ///
    /// If an error occurs while reading, a [`StorageError::ReadError`] is returned.
    fn retrieve(&self, key: &str) -> Result<Vec<u8>, StorageError>;
}

#[derive(Debug, PartialEq, Error)]
pub enum StorageError {
    #[error("cannot write to storage: {0}")]
    WriteError(String),
    #[error("cannot read from storage: {0}")]
    ReadError(String),
    #[error("key could not be found: {key}")]
    KeyNotFound { key: String },
}