Struct sp_core::offchain::storage::InMemOffchainStorage
source · pub struct InMemOffchainStorage { /* private fields */ }
Expand description
In-memory storage for offchain workers.
Implementations§
source§impl InMemOffchainStorage
impl InMemOffchainStorage
sourcepub fn into_iter(self) -> impl Iterator<Item = (Vec<u8>, Vec<u8>)>
pub fn into_iter(self) -> impl Iterator<Item = (Vec<u8>, Vec<u8>)>
Consume the offchain storage and iterate over all key value pairs.
sourcepub fn iter(&self) -> impl Iterator<Item = (&Vec<u8>, &Vec<u8>)>
pub fn iter(&self) -> impl Iterator<Item = (&Vec<u8>, &Vec<u8>)>
Iterate over all key value pairs by reference.
sourcepub fn remove(&mut self, prefix: &[u8], key: &[u8])
pub fn remove(&mut self, prefix: &[u8], key: &[u8])
Remove a key and its associated value from the offchain database.
Examples found in repository?
src/offchain/testing.rs (line 85)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
pub fn apply_offchain_changes(
&mut self,
changes: impl Iterator<Item = ((Vec<u8>, Vec<u8>), OffchainOverlayedChange)>,
) {
let mut me = self.persistent.write();
for ((_prefix, key), value_operation) in changes {
match value_operation {
OffchainOverlayedChange::SetValue(val) =>
me.set(Self::PREFIX, key.as_slice(), val.as_slice()),
OffchainOverlayedChange::Remove => me.remove(Self::PREFIX, key.as_slice()),
}
}
}
/// Retrieve a key from the test backend.
pub fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
OffchainStorage::get(self, Self::PREFIX, key)
}
}
impl OffchainStorage for TestPersistentOffchainDB {
fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8]) {
self.persistent.write().set(prefix, key, value);
}
fn remove(&mut self, prefix: &[u8], key: &[u8]) {
self.persistent.write().remove(prefix, key);
}
fn get(&self, prefix: &[u8], key: &[u8]) -> Option<Vec<u8>> {
self.persistent.read().get(prefix, key)
}
fn compare_and_set(
&mut self,
prefix: &[u8],
key: &[u8],
old_value: Option<&[u8]>,
new_value: &[u8],
) -> bool {
self.persistent.write().compare_and_set(prefix, key, old_value, new_value)
}
}
/// Internal state of the externalities.
///
/// This can be used in tests to respond or assert stuff about interactions.
#[derive(Debug, Default)]
pub struct OffchainState {
/// A list of pending requests.
pub requests: BTreeMap<RequestId, PendingRequest>,
// Queue of requests that the test is expected to perform (in order).
expected_requests: VecDeque<PendingRequest>,
/// Persistent local storage
pub persistent_storage: TestPersistentOffchainDB,
/// Local storage
pub local_storage: InMemOffchainStorage,
/// A supposedly random seed.
pub seed: [u8; 32],
/// A timestamp simulating the current time.
pub timestamp: Timestamp,
}
impl OffchainState {
/// Asserts that pending request has been submitted and fills it's response.
pub fn fulfill_pending_request(
&mut self,
id: u16,
expected: PendingRequest,
response: impl Into<Vec<u8>>,
response_headers: impl IntoIterator<Item = (String, String)>,
) {
match self.requests.get_mut(&RequestId(id)) {
None => {
panic!("Missing pending request: {:?}.\n\nAll: {:?}", id, self.requests);
},
Some(req) => {
assert_eq!(*req, expected);
req.response = Some(response.into());
req.response_headers = response_headers.into_iter().collect();
},
}
}
fn fulfill_expected(&mut self, id: u16) {
if let Some(mut req) = self.expected_requests.pop_back() {
let response = req.response.take().expect("Response checked when added.");
let headers = std::mem::take(&mut req.response_headers);
self.fulfill_pending_request(id, req, response, headers);
}
}
/// Add expected HTTP request.
///
/// This method can be used to initialize expected HTTP requests and their responses
/// before running the actual code that utilizes them (for instance before calling into
/// runtime). Expected request has to be fulfilled before this struct is dropped,
/// the `response` and `response_headers` fields will be used to return results to the callers.
/// Requests are expected to be performed in the insertion order.
pub fn expect_request(&mut self, expected: PendingRequest) {
if expected.response.is_none() {
panic!("Expected request needs to have a response.");
}
self.expected_requests.push_front(expected);
}
}
impl Drop for OffchainState {
fn drop(&mut self) {
// If we panic! while we are already in a panic, the test dies with an illegal instruction.
if !self.expected_requests.is_empty() && !std::thread::panicking() {
panic!("Unfulfilled expected requests: {:?}", self.expected_requests);
}
}
}
/// Implementation of offchain externalities used for tests.
#[derive(Clone, Default, Debug)]
pub struct TestOffchainExt(pub Arc<RwLock<OffchainState>>);
impl TestOffchainExt {
/// Create new `TestOffchainExt` and a reference to the internal state.
pub fn new() -> (Self, Arc<RwLock<OffchainState>>) {
let ext = Self::default();
let state = ext.0.clone();
(ext, state)
}
/// Create new `TestOffchainExt` and a reference to the internal state.
pub fn with_offchain_db(
offchain_db: TestPersistentOffchainDB,
) -> (Self, Arc<RwLock<OffchainState>>) {
let (ext, state) = Self::new();
ext.0.write().persistent_storage = offchain_db;
(ext, state)
}
}
impl offchain::Externalities for TestOffchainExt {
fn is_validator(&self) -> bool {
true
}
fn network_state(&self) -> Result<OpaqueNetworkState, ()> {
Ok(OpaqueNetworkState { peer_id: Default::default(), external_addresses: vec![] })
}
fn timestamp(&mut self) -> Timestamp {
self.0.read().timestamp
}
fn sleep_until(&mut self, deadline: Timestamp) {
self.0.write().timestamp = deadline;
}
fn random_seed(&mut self) -> [u8; 32] {
self.0.read().seed
}
fn http_request_start(
&mut self,
method: &str,
uri: &str,
meta: &[u8],
) -> Result<RequestId, ()> {
let mut state = self.0.write();
let id = RequestId(state.requests.len() as u16);
state.requests.insert(
id,
PendingRequest {
method: method.into(),
uri: uri.into(),
meta: meta.into(),
..Default::default()
},
);
Ok(id)
}
fn http_request_add_header(
&mut self,
request_id: RequestId,
name: &str,
value: &str,
) -> Result<(), ()> {
let mut state = self.0.write();
if let Some(req) = state.requests.get_mut(&request_id) {
req.headers.push((name.into(), value.into()));
Ok(())
} else {
Err(())
}
}
fn http_request_write_body(
&mut self,
request_id: RequestId,
chunk: &[u8],
_deadline: Option<Timestamp>,
) -> Result<(), HttpError> {
let mut state = self.0.write();
let sent = {
let req = state.requests.get_mut(&request_id).ok_or(HttpError::IoError)?;
req.body.extend(chunk);
if chunk.is_empty() {
req.sent = true;
}
req.sent
};
if sent {
state.fulfill_expected(request_id.0);
}
Ok(())
}
fn http_response_wait(
&mut self,
ids: &[RequestId],
_deadline: Option<Timestamp>,
) -> Vec<RequestStatus> {
let state = self.0.read();
ids.iter()
.map(|id| match state.requests.get(id) {
Some(req) if req.response.is_none() => {
panic!("No `response` provided for request with id: {:?}", id)
},
None => RequestStatus::Invalid,
_ => RequestStatus::Finished(200),
})
.collect()
}
fn http_response_headers(&mut self, request_id: RequestId) -> Vec<(Vec<u8>, Vec<u8>)> {
let state = self.0.read();
if let Some(req) = state.requests.get(&request_id) {
req.response_headers
.clone()
.into_iter()
.map(|(k, v)| (k.into_bytes(), v.into_bytes()))
.collect()
} else {
Default::default()
}
}
fn http_response_read_body(
&mut self,
request_id: RequestId,
buffer: &mut [u8],
_deadline: Option<Timestamp>,
) -> Result<usize, HttpError> {
let mut state = self.0.write();
if let Some(req) = state.requests.get_mut(&request_id) {
let response = req
.response
.as_mut()
.unwrap_or_else(|| panic!("No response provided for request: {:?}", request_id));
if req.read >= response.len() {
// Remove the pending request as per spec.
state.requests.remove(&request_id);
Ok(0)
} else {
let read = std::cmp::min(buffer.len(), response[req.read..].len());
buffer[0..read].copy_from_slice(&response[req.read..req.read + read]);
req.read += read;
Ok(read)
}
} else {
Err(HttpError::IoError)
}
}
fn set_authorized_nodes(&mut self, _nodes: Vec<OpaquePeerId>, _authorized_only: bool) {
unimplemented!()
}
}
impl offchain::DbExternalities for TestOffchainExt {
fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) {
let mut state = self.0.write();
match kind {
StorageKind::LOCAL => state.local_storage.set(b"", key, value),
StorageKind::PERSISTENT => state.persistent_storage.set(b"", key, value),
};
}
fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) {
let mut state = self.0.write();
match kind {
StorageKind::LOCAL => state.local_storage.remove(b"", key),
StorageKind::PERSISTENT => state.persistent_storage.remove(b"", key),
};
}
Trait Implementations§
source§impl Clone for InMemOffchainStorage
impl Clone for InMemOffchainStorage
source§fn clone(&self) -> InMemOffchainStorage
fn clone(&self) -> InMemOffchainStorage
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for InMemOffchainStorage
impl Debug for InMemOffchainStorage
source§impl Default for InMemOffchainStorage
impl Default for InMemOffchainStorage
source§fn default() -> InMemOffchainStorage
fn default() -> InMemOffchainStorage
Returns the “default value” for a type. Read more
source§impl OffchainStorage for InMemOffchainStorage
impl OffchainStorage for InMemOffchainStorage
source§fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8])
fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8])
Persist a value in storage under given key and prefix.
source§fn remove(&mut self, prefix: &[u8], key: &[u8])
fn remove(&mut self, prefix: &[u8], key: &[u8])
Clear a storage entry under given key and prefix.
Auto Trait Implementations§
impl RefUnwindSafe for InMemOffchainStorage
impl Send for InMemOffchainStorage
impl Sync for InMemOffchainStorage
impl Unpin for InMemOffchainStorage
impl UnwindSafe for InMemOffchainStorage
Blanket Implementations§
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>
fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>
Convert
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
Convert
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
Convert
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Convert
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T, Outer> IsWrappedBy<Outer> for Twhere
Outer: AsRef<T> + AsMut<T> + From<T>,
T: From<Outer>,
impl<T, Outer> IsWrappedBy<Outer> for Twhere
Outer: AsRef<T> + AsMut<T> + From<T>,
T: From<Outer>,
source§impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
source§fn unchecked_into(self) -> T
fn unchecked_into(self) -> T
The counterpart to
unchecked_from
.