tp_runtime/offchain/
storage.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! A set of storage helpers for offchain workers.
19
20use tet_core::offchain::StorageKind;
21
22/// A storage value with a static key.
23pub type StorageValue = StorageValueRef<'static>;
24
25/// An abstraction over local storage value.
26pub struct StorageValueRef<'a> {
27	key: &'a [u8],
28	kind: StorageKind,
29}
30
31impl<'a> StorageValueRef<'a> {
32	/// Create a new reference to a value in the persistent local storage.
33	pub fn persistent(key: &'a [u8]) -> Self {
34		Self { key, kind: StorageKind::PERSISTENT }
35	}
36
37	/// Create a new reference to a value in the fork-aware local storage.
38	pub fn local(key: &'a [u8]) -> Self {
39		Self { key, kind: StorageKind::LOCAL }
40	}
41
42	/// Set the value of the storage to encoding of given parameter.
43	///
44	/// Note that the storage may be accessed by workers running concurrently,
45	/// if you happen to write a `get-check-set` pattern you should most likely
46	/// be using `mutate` instead.
47	pub fn set(&self, value: &impl codec::Encode) {
48		value.using_encoded(|val| {
49			tet_io::offchain::local_storage_set(self.kind, self.key, val)
50		})
51	}
52
53	/// Remove the associated value from the storage.
54	pub fn clear(&mut self) {
55		tet_io::offchain::local_storage_clear(self.kind, self.key)
56	}
57
58	/// Retrieve & decode the value from storage.
59	///
60	/// Note that if you want to do some checks based on the value
61	/// and write changes after that you should rather be using `mutate`.
62	///
63	/// The function returns `None` if the value was not found in storage,
64	/// otherwise a decoding of the value to requested type.
65	pub fn get<T: codec::Decode>(&self) -> Option<Option<T>> {
66		tet_io::offchain::local_storage_get(self.kind, self.key)
67			.map(|val| T::decode(&mut &*val).ok())
68	}
69
70	/// Retrieve & decode the value and set it to a new one atomically.
71	///
72	/// Function `f` should return a new value that we should attempt to write to storage.
73	/// This function returns:
74	/// 1. `Ok(Ok(T))` in case the value has been successfully set.
75	/// 2. `Ok(Err(T))` in case the value was calculated by the passed closure `f`,
76	///    but it could not be stored.
77	/// 3. `Err(_)` in case `f` returns an error.
78	pub fn mutate<T, E, F>(&self, f: F) -> Result<Result<T, T>, E> where
79		T: codec::Codec,
80		F: FnOnce(Option<Option<T>>) -> Result<T, E>
81	{
82		let value = tet_io::offchain::local_storage_get(self.kind, self.key);
83		let decoded = value.as_deref().map(|mut v| T::decode(&mut v).ok());
84		let val = f(decoded)?;
85		let set = val.using_encoded(|new_val| {
86			tet_io::offchain::local_storage_compare_and_set(
87				self.kind,
88				self.key,
89				value,
90				new_val,
91			)
92		});
93
94		if set {
95			Ok(Ok(val))
96		} else {
97			Ok(Err(val))
98		}
99	}
100}
101
102#[cfg(test)]
103mod tests {
104	use super::*;
105	use tet_io::TestExternalities;
106	use tet_core::offchain::{
107		OffchainExt,
108		testing,
109	};
110
111	#[test]
112	fn should_set_and_get() {
113		let (offchain, state) = testing::TestOffchainExt::new();
114		let mut t = TestExternalities::default();
115		t.register_extension(OffchainExt::new(offchain));
116
117		t.execute_with(|| {
118			let val = StorageValue::persistent(b"testval");
119
120			assert_eq!(val.get::<u32>(), None);
121
122			val.set(&15_u32);
123
124			assert_eq!(val.get::<u32>(), Some(Some(15_u32)));
125			assert_eq!(val.get::<Vec<u8>>(), Some(None));
126			assert_eq!(
127				state.read().persistent_storage.get(b"testval"),
128				Some(vec![15_u8, 0, 0, 0])
129			);
130		})
131	}
132
133	#[test]
134	fn should_mutate() {
135		let (offchain, state) = testing::TestOffchainExt::new();
136		let mut t = TestExternalities::default();
137		t.register_extension(OffchainExt::new(offchain));
138
139		t.execute_with(|| {
140			let val = StorageValue::persistent(b"testval");
141
142			let result = val.mutate::<u32, (), _>(|val| {
143				assert_eq!(val, None);
144
145				Ok(16_u32)
146			});
147			assert_eq!(result, Ok(Ok(16_u32)));
148			assert_eq!(val.get::<u32>(), Some(Some(16_u32)));
149			assert_eq!(
150				state.read().persistent_storage.get(b"testval"),
151				Some(vec![16_u8, 0, 0, 0])
152			);
153
154			// mutate again, but this time early-exit.
155			let res = val.mutate::<u32, (), _>(|val| {
156				assert_eq!(val, Some(Some(16_u32)));
157				Err(())
158			});
159			assert_eq!(res, Err(()));
160		})
161	}
162}