snapshot.rs (2275B)
1 use super::{Fixture, batch, failure, key}; 2 use futures::FutureExt; 3 use radroots_storage_indexeddb::{Error, ReadSnapshot, RecordPrefix}; 4 use wasm_bindgen::prelude::*; 5 6 #[wasm_bindgen] 7 pub struct Frozen { 8 value: ReadSnapshot, 9 } 10 #[wasm_bindgen] 11 impl Frozen { 12 pub fn len(&self) -> u32 { 13 self.value.len() as u32 14 } 15 pub fn is_empty(&self) -> bool { 16 self.value.is_empty() 17 } 18 pub fn redacted(&self) -> bool { 19 format!("{:?}", self.value) == "ReadSnapshot(<redacted>)" 20 } 21 pub fn verify(&self, n: u8, actual: Option<Vec<u8>>) -> Result<(), JsValue> { 22 self.value 23 .verify(key(n), actual.as_deref()) 24 .map_err(failure) 25 } 26 } 27 #[wasm_bindgen] 28 impl Fixture { 29 pub async fn snapshot(&self, prefix: u8) -> Result<Frozen, JsValue> { 30 self.db 31 .read_snapshot(RecordPrefix::new([prefix; 16])) 32 .await 33 .map(|value| Frozen { value }) 34 .map_err(failure) 35 } 36 pub async fn guarded_write( 37 &self, 38 frozen: Frozen, 39 n: u8, 40 old: Option<Vec<u8>>, 41 new: Option<Vec<u8>>, 42 ) -> Result<usize, JsValue> { 43 self.db 44 .compare_exchange_snapshot_checked(batch(n, old, new)?, frozen.value, || true) 45 .await 46 .map(|commit| commit.records()) 47 .map_err(failure) 48 } 49 pub async fn guarded_refusal( 50 &self, 51 frozen: Frozen, 52 n: u8, 53 old: Option<Vec<u8>>, 54 new: Option<Vec<u8>>, 55 ) -> Result<(), JsValue> { 56 self.db 57 .compare_exchange_snapshot_checked(batch(n, old, new)?, frozen.value, || false) 58 .await 59 .map(|_| ()) 60 .map_err(failure) 61 } 62 pub fn abandon_snapshots(&self, prefix: u8, count: u32) -> Result<u32, JsValue> { 63 for n in 0..count { 64 if let Some(result) = self 65 .db 66 .read_snapshot(RecordPrefix::new([prefix; 16])) 67 .now_or_never() 68 { 69 return if matches!(result, Err(Error::Capacity)) { 70 Ok(n) 71 } else { 72 Err(JsValue::from_str("unexpected_immediate_snapshot")) 73 }; 74 } 75 } 76 Ok(count) 77 } 78 }