referrerpolicy=no-referrer-when-downgrade

sp_state_machine/overlayed_changes/
offchain.rs

1// This file is part of Substrate.
2
3// Copyright (C) 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//! Overlayed changes for offchain indexing.
19
20use super::changeset::OverlayedMap;
21use alloc::vec::Vec;
22use sp_core::offchain::OffchainOverlayedChange;
23
24/// In-memory storage for offchain workers recoding changes for the actual offchain storage
25/// implementation.
26#[derive(Debug, Clone, Default)]
27pub struct OffchainOverlayedChanges(OverlayedMap<(Vec<u8>, Vec<u8>), OffchainOverlayedChange>);
28
29/// Item for iterating over offchain changes.
30///
31/// First element i a tuple of `(prefix, key)`, second element ist the actual change
32/// (remove or set value).
33type OffchainOverlayedChangesItem<'i> = (&'i (Vec<u8>, Vec<u8>), &'i OffchainOverlayedChange);
34
35/// Iterator over offchain changes, owned memory version.
36type OffchainOverlayedChangesItemOwned = ((Vec<u8>, Vec<u8>), OffchainOverlayedChange);
37
38impl OffchainOverlayedChanges {
39	/// Consume the offchain storage and iterate over all key value pairs.
40	pub fn into_iter(self) -> impl Iterator<Item = OffchainOverlayedChangesItemOwned> {
41		self.0.into_changes().map(|kv| (kv.0, kv.1.into_value()))
42	}
43
44	/// Iterate over all key value pairs by reference.
45	pub fn iter(&mut self) -> impl Iterator<Item = OffchainOverlayedChangesItem> {
46		self.0.changes().map(|kv| (kv.0, kv.1.value_ref()))
47	}
48
49	/// Drain all elements of changeset.
50	pub fn drain(&mut self) -> impl Iterator<Item = OffchainOverlayedChangesItemOwned> {
51		core::mem::take(self).into_iter()
52	}
53
54	/// Remove a key and its associated value from the offchain database.
55	pub fn remove(&mut self, prefix: &[u8], key: &[u8]) {
56		let _ = self.0.set_offchain(
57			(prefix.to_vec(), key.to_vec()),
58			OffchainOverlayedChange::Remove,
59			None,
60		);
61	}
62
63	/// Set the value associated with a key under a prefix to the value provided.
64	pub fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8]) {
65		let _ = self.0.set_offchain(
66			(prefix.to_vec(), key.to_vec()),
67			OffchainOverlayedChange::SetValue(value.to_vec()),
68			None,
69		);
70	}
71
72	/// Obtain a associated value to the given key in storage with prefix.
73	pub fn get(&mut self, prefix: &[u8], key: &[u8]) -> Option<OffchainOverlayedChange> {
74		let key = (prefix.to_vec(), key.to_vec());
75		self.0.get(&key).map(|entry| entry.value_ref()).cloned()
76	}
77
78	/// Reference to inner change set.
79	pub fn overlay(&self) -> &OverlayedMap<(Vec<u8>, Vec<u8>), OffchainOverlayedChange> {
80		&self.0
81	}
82
83	/// Mutable reference to inner change set.
84	pub fn overlay_mut(
85		&mut self,
86	) -> &mut OverlayedMap<(Vec<u8>, Vec<u8>), OffchainOverlayedChange> {
87		&mut self.0
88	}
89}
90
91#[cfg(test)]
92mod test {
93	use super::*;
94	use sp_core::offchain::STORAGE_PREFIX;
95
96	#[test]
97	fn test_drain() {
98		let mut ooc = OffchainOverlayedChanges::default();
99		ooc.set(STORAGE_PREFIX, b"kkk", b"vvv");
100		let drained = ooc.drain().count();
101		assert_eq!(drained, 1);
102		let leftover = ooc.iter().count();
103		assert_eq!(leftover, 0);
104
105		ooc.set(STORAGE_PREFIX, b"a", b"v");
106		ooc.set(STORAGE_PREFIX, b"b", b"v");
107		ooc.set(STORAGE_PREFIX, b"c", b"v");
108		ooc.set(STORAGE_PREFIX, b"d", b"v");
109		ooc.set(STORAGE_PREFIX, b"e", b"v");
110		assert_eq!(ooc.iter().count(), 5);
111	}
112
113	#[test]
114	fn test_accumulated_set_remove_set() {
115		let mut ooc = OffchainOverlayedChanges::default();
116		ooc.set(STORAGE_PREFIX, b"ppp", b"qqq");
117		ooc.remove(STORAGE_PREFIX, b"ppp");
118		// keys are equiv, so it will overwrite the value and the overlay will contain
119		// one item
120		assert_eq!(ooc.iter().count(), 1);
121
122		ooc.set(STORAGE_PREFIX, b"ppp", b"rrr");
123		let mut iter = ooc.into_iter();
124		assert_eq!(
125			iter.next(),
126			Some((
127				(STORAGE_PREFIX.to_vec(), b"ppp".to_vec()),
128				OffchainOverlayedChange::SetValue(b"rrr".to_vec())
129			))
130		);
131		assert_eq!(iter.next(), None);
132	}
133}