diem_secure_storage/kv_storage.rs
1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use crate::Error;
9use serde::{de::DeserializeOwned, Deserialize, Serialize};
10
11/// A secure key/value storage engine. Create takes a policy that is enforced
12/// internally by the actual backend. The policy contains public identities that
13/// the backend can translate into a unique and private token for another
14/// service. Hence get and set internally will pass the current service private
15/// token to the backend to gain its permissions.
16pub trait KVStorage {
17 /// Returns an error if the backend service is not online and available.
18 fn available(&self) -> Result<(), Error>;
19
20 /// Retrieves a value from storage and fails if the backend is unavailable
21 /// or the process has invalid permissions.
22 fn get<T: DeserializeOwned>(
23 &self, key: &str,
24 ) -> Result<GetResponse<T>, Error>;
25
26 /// Sets a value in storage and fails if the backend is unavailable or the
27 /// process has invalid permissions.
28 fn set<T: Serialize>(&mut self, key: &str, value: T) -> Result<(), Error>;
29
30 /// Resets and clears all data held in the storage engine.
31 /// Note: this should only be exposed and used for testing. Resetting the
32 /// storage engine is not something that should be supported in
33 /// production.
34 #[cfg(any(test, feature = "testing"))]
35 fn reset_and_clear(&mut self) -> Result<(), Error>;
36}
37
38/// A container for a get response that contains relevant metadata and the value
39/// stored at the given key.
40#[derive(Debug, Deserialize, PartialEq, Serialize)]
41#[serde(tag = "data")]
42pub struct GetResponse<T> {
43 /// Time since Unix Epoch in seconds.
44 pub last_update: u64,
45 /// Value stored at the provided key
46 pub value: T,
47}
48
49impl<T> GetResponse<T> {
50 /// Creates a GetResponse
51 pub fn new(value: T, last_update: u64) -> Self {
52 Self { value, last_update }
53 }
54}