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 enum_dispatch::enum_dispatch;
10use serde::{de::DeserializeOwned, Deserialize, Serialize};
11
12/// A secure key/value storage engine. Create takes a policy that is enforced
13/// internally by the actual backend. The policy contains public identities that
14/// the backend can translate into a unique and private token for another
15/// service. Hence get and set internally will pass the current service private
16/// token to the backend to gain its permissions.
17#[enum_dispatch]
18pub trait KVStorage {
19 /// Returns an error if the backend service is not online and available.
20 fn available(&self) -> Result<(), Error>;
21
22 /// Retrieves a value from storage and fails if the backend is unavailable
23 /// or the process has invalid permissions.
24 fn get<T: DeserializeOwned>(
25 &self, key: &str,
26 ) -> Result<GetResponse<T>, Error>;
27
28 /// Sets a value in storage and fails if the backend is unavailable or the
29 /// process has invalid permissions.
30 fn set<T: Serialize>(&mut self, key: &str, value: T) -> Result<(), Error>;
31
32 /// Resets and clears all data held in the storage engine.
33 /// Note: this should only be exposed and used for testing. Resetting the
34 /// storage engine is not something that should be supported in
35 /// production.
36 #[cfg(any(test, feature = "testing"))]
37 fn reset_and_clear(&mut self) -> Result<(), Error>;
38}
39
40/// A container for a get response that contains relevant metadata and the value
41/// stored at the given key.
42#[derive(Debug, Deserialize, PartialEq, Serialize)]
43#[serde(tag = "data")]
44pub struct GetResponse<T> {
45 /// Time since Unix Epoch in seconds.
46 pub last_update: u64,
47 /// Value stored at the provided key
48 pub value: T,
49}
50
51impl<T> GetResponse<T> {
52 /// Creates a GetResponse
53 pub fn new(value: T, last_update: u64) -> Self {
54 Self { value, last_update }
55 }
56}