snapshot.rs (12231B)
1 //! Bounded opaque read witnesses; no crypto provider runs in a transaction. 2 use super::{ 3 Batch, Commit, Completion, Database, Error, RECORD_BYTES_MAX, RecordKey, RequestHandler, STORE, 4 State, bytes, classify, queue_batch, record_key, refuse, write_transaction, 5 }; 6 use futures::channel::oneshot; 7 use js_sys::Uint8Array; 8 use sha2::{Digest, Sha256}; 9 use std::{ 10 cell::{Cell, RefCell}, 11 fmt, 12 mem::size_of, 13 rc::{Rc, Weak}, 14 }; 15 use wasm_bindgen::{JsCast, JsValue, closure::Closure}; 16 use wasm_bindgen_futures::spawn_local; 17 use web_sys::{ 18 Event, IdbCursorWithValue, IdbKeyRange, IdbObjectStore, IdbRequest, IdbTransaction, 19 IdbTransactionMode, 20 }; 21 22 const ROWS_MAX: usize = 16_384; 23 const SCAN_RESERVATION: usize = 2 * 1024 * 1024; 24 25 /// Opaque binary-key prefix. It carries no workspace or business permission. 26 #[derive(Clone, Copy, Eq, PartialEq)] 27 pub struct RecordPrefix([u8; 16]); 28 impl RecordPrefix { 29 pub const fn new(bytes: [u8; 16]) -> Self { 30 Self(bytes) 31 } 32 fn range(self) -> Result<IdbKeyRange, Error> { 33 let lower: JsValue = Uint8Array::from(self.0.as_slice()).into(); 34 let mut upper = self.0; 35 for i in (0..upper.len()).rev() { 36 if upper[i] != u8::MAX { 37 upper[i] += 1; 38 let upper: JsValue = Uint8Array::from(upper.as_slice()).into(); 39 return IdbKeyRange::bound_with_lower_open_and_upper_open( 40 &lower, &upper, false, true, 41 ) 42 .map_err(classify); 43 } 44 upper[i] = 0; 45 } 46 IdbKeyRange::lower_bound(&lower).map_err(classify) 47 } 48 fn contains(self, key: RecordKey) -> bool { 49 key.as_bytes()[..16] == self.0 50 } 51 } 52 impl fmt::Debug for RecordPrefix { 53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 54 f.write_str("RecordPrefix(<redacted>)") 55 } 56 } 57 struct Witness { 58 key: RecordKey, 59 length: usize, 60 digest: [u8; 32], 61 } 62 // Vec growth, one bounded record, and callback scaffolding fit the reservation. 63 const _: () = assert!( 64 size_of::<Witness>() * ROWS_MAX * 3 / 2 + 2 * RECORD_BYTES_MAX + 4096 <= SCAN_RESERVATION 65 ); 66 67 /// Exact completed read set on one live connection. No serialization or clone 68 /// can turn it into a portable authorization token. Values are not retained. 69 pub struct ReadSnapshot { 70 owner: Weak<State>, 71 prefix: RecordPrefix, 72 rows: Vec<Witness>, 73 } 74 impl ReadSnapshot { 75 pub fn len(&self) -> usize { 76 self.rows.len() 77 } 78 pub fn is_empty(&self) -> bool { 79 self.rows.is_empty() 80 } 81 pub fn contains(&self, key: RecordKey) -> bool { 82 self.rows.binary_search_by_key(&key, |row| row.key).is_ok() 83 } 84 pub fn keys(&self) -> impl Iterator<Item = RecordKey> + '_ { 85 self.rows.iter().map(|row| row.key) 86 } 87 /// Binds each value decoded outside the transaction to the completed view. 88 pub fn verify(&self, key: RecordKey, actual: Option<&[u8]>) -> Result<(), Error> { 89 if !self.prefix.contains(key) { 90 return Err(Error::InvalidInput); 91 } 92 match (self.rows.binary_search_by_key(&key, |row| row.key), actual) { 93 (Err(_), None) => Ok(()), 94 (Ok(i), Some(raw)) => matches(&self.rows[i], raw), 95 _ => Err(Error::Conflict), 96 } 97 } 98 fn reservation(&self) -> usize { 99 size_of::<Self>() + self.rows.capacity() * size_of::<Witness>() 100 } 101 } 102 impl fmt::Debug for ReadSnapshot { 103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 104 f.write_str("ReadSnapshot(<redacted>)") 105 } 106 } 107 fn matches(witness: &Witness, raw: &[u8]) -> Result<(), Error> { 108 if raw.len() > RECORD_BYTES_MAX { 109 return Err(Error::CorruptRecord); 110 } 111 if raw.len() != witness.length || <[u8; 32]>::from(Sha256::digest(raw)) != witness.digest { 112 return Err(Error::Conflict); 113 } 114 Ok(()) 115 } 116 fn cursor_key(cursor: &IdbCursorWithValue, prefix: RecordPrefix) -> Result<RecordKey, Error> { 117 let key = record_key(cursor.key().map_err(classify)?)?; 118 if !prefix.contains(key) { 119 return Err(Error::CorruptRecord); 120 } 121 Ok(key) 122 } 123 fn start_cursor(store: &IdbObjectStore, prefix: RecordPrefix) -> Result<IdbRequest, Error> { 124 store 125 .open_cursor_with_range(prefix.range()?.as_ref()) 126 .map_err(classify) 127 } 128 impl Database { 129 /// Captures bounded key/length/digest witnesses, observing real completion. 130 /// Accepted scanning survives loss of its observer and participates in close. 131 pub async fn read_snapshot(&self, prefix: RecordPrefix) -> Result<ReadSnapshot, Error> { 132 let work = self.state.admit(SCAN_RESERVATION)?; 133 let (send, observe) = oneshot::channel(); 134 spawn_local(async move { 135 let owner = work; 136 let result = match owner 137 .state 138 .db 139 .transaction_with_str_and_mode(STORE, IdbTransactionMode::Readonly) 140 { 141 Ok(tx) => scan(tx, Rc::downgrade(&owner.state), prefix).await, 142 Err(error) => Err(classify(error)), 143 }; 144 let _ = send.send(result); 145 }); 146 observe.await.unwrap_or(Err(Error::CommitUnknown)) 147 } 148 /// Rechecks the complete witnessed set before any batch write, in the same 149 /// real transaction. All cursor and mutation callbacks recheck eligibility. 150 pub async fn compare_exchange_snapshot_checked( 151 &self, 152 batch: Batch, 153 snapshot: ReadSnapshot, 154 guard: impl Fn() -> bool + 'static, 155 ) -> Result<Commit, Error> { 156 if !snapshot 157 .owner 158 .upgrade() 159 .is_some_and(|owner| Rc::ptr_eq(&owner, &self.state)) 160 { 161 return Err(Error::InvalidInput); 162 } 163 let reservation = batch 164 .bytes 165 .checked_add(snapshot.reservation()) 166 .ok_or(Error::Capacity)?; 167 let work = self.state.admit(reservation)?; 168 let (send, observe) = oneshot::channel(); 169 spawn_local(async move { 170 let owner = work; 171 let result = match write_transaction(&owner.state.db) { 172 Ok(tx) => checked_exchange(tx, batch, snapshot, Rc::new(guard)).await, 173 Err(error) => Err(error), 174 }; 175 let _ = send.send(result); 176 }); 177 observe.await.unwrap_or(Err(Error::CommitUnknown)) 178 } 179 } 180 async fn scan( 181 tx: IdbTransaction, 182 owner: Weak<State>, 183 prefix: RecordPrefix, 184 ) -> Result<ReadSnapshot, Error> { 185 let failure = Rc::new(Cell::new(None)); 186 let mut completion = Completion::new(tx.clone(), failure.clone()); 187 let rows = Rc::new(RefCell::new(Vec::<Witness>::new())); 188 let done = Rc::new(Cell::new(false)); 189 let request = match tx 190 .object_store(STORE) 191 .map_err(classify) 192 .and_then(|store| start_cursor(&store, prefix)) 193 { 194 Ok(request) => request, 195 Err(error) => { 196 refuse(&tx, &failure, error); 197 completion.wait().await?; 198 return Err(Error::CommitUnknown); 199 } 200 }; 201 let success = { 202 let request = request.clone(); 203 let tx = tx.clone(); 204 let failure = failure.clone(); 205 let rows = rows.clone(); 206 let done = done.clone(); 207 Closure::new(move |_: Event| { 208 if failure.get().is_some() { 209 return; 210 } 211 let result = (|| { 212 let value = request.result().map_err(classify)?; 213 if value.is_null() { 214 done.set(true); 215 return Ok(()); 216 } 217 let cursor = value 218 .dyn_into::<IdbCursorWithValue>() 219 .map_err(|_| Error::CorruptRecord)?; 220 let key = cursor_key(&cursor, prefix)?; 221 let mut rows = rows.borrow_mut(); 222 if rows.len() >= ROWS_MAX { 223 return Err(Error::Capacity); 224 } 225 if rows.last().is_some_and(|previous| previous.key >= key) { 226 return Err(Error::CorruptRecord); 227 } 228 let raw = bytes(cursor.value().map_err(classify)?)?.ok_or(Error::CorruptRecord)?; 229 rows.push(Witness { 230 key, 231 length: raw.len(), 232 digest: Sha256::digest(&raw).into(), 233 }); 234 drop(rows); 235 cursor.continue_().map_err(classify) 236 })(); 237 if let Err(error) = result { 238 refuse(&tx, &failure, error); 239 } 240 }) 241 }; 242 request.set_onsuccess(Some(success.as_ref().unchecked_ref())); 243 let _handler = RequestHandler { 244 request, 245 _success: success, 246 }; 247 completion.wait().await?; 248 if !done.get() { 249 return Err(Error::CommitUnknown); 250 } 251 let rows = std::mem::take(&mut *rows.borrow_mut()); 252 Ok(ReadSnapshot { 253 owner, 254 prefix, 255 rows, 256 }) 257 } 258 async fn checked_exchange( 259 tx: IdbTransaction, 260 batch: Batch, 261 snapshot: ReadSnapshot, 262 guard: Rc<dyn Fn() -> bool>, 263 ) -> Result<Commit, Error> { 264 let failure = Rc::new(Cell::new(None)); 265 let mut completion = Completion::new(tx.clone(), failure.clone()); 266 let count = batch.entries.len(); 267 let store = match tx.object_store(STORE) { 268 Ok(store) => store, 269 Err(error) => { 270 refuse(&tx, &failure, classify(error)); 271 completion.wait().await?; 272 return Err(Error::CommitUnknown); 273 } 274 }; 275 let request = match start_cursor(&store, snapshot.prefix) { 276 Ok(request) => request, 277 Err(error) => { 278 refuse(&tx, &failure, error); 279 completion.wait().await?; 280 return Err(Error::CommitUnknown); 281 } 282 }; 283 let handlers = Rc::new(RefCell::new(Vec::new())); 284 let batch = Rc::new(RefCell::new(Some(batch))); 285 let queued = Rc::new(Cell::new(false)); 286 let success = { 287 let request = request.clone(); 288 let tx = tx.clone(); 289 let failure = failure.clone(); 290 let queued = queued.clone(); 291 let handlers = handlers.clone(); 292 let guard = guard.clone(); 293 let mut seen = 0; 294 Closure::new(move |_: Event| { 295 if failure.get().is_some() { 296 return; 297 } 298 let result = (|| { 299 if !guard() { 300 return Err(Error::GuardRefused); 301 } 302 let value = request.result().map_err(classify)?; 303 if value.is_null() { 304 if seen != snapshot.rows.len() { 305 return Err(Error::Conflict); 306 } 307 let batch = batch.borrow_mut().take().ok_or(Error::CorruptRecord)?; 308 queue_batch( 309 &store, 310 &tx, 311 batch, 312 Some(guard.clone()), 313 &failure, 314 &mut handlers.borrow_mut(), 315 ); 316 queued.set(true); 317 return Ok(()); 318 } 319 let cursor = value 320 .dyn_into::<IdbCursorWithValue>() 321 .map_err(|_| Error::CorruptRecord)?; 322 let key = cursor_key(&cursor, snapshot.prefix)?; 323 let expected = snapshot.rows.get(seen).ok_or(Error::Conflict)?; 324 if key != expected.key { 325 return Err(Error::Conflict); 326 } 327 let raw = bytes(cursor.value().map_err(classify)?)?.ok_or(Error::CorruptRecord)?; 328 matches(expected, &raw)?; 329 seen += 1; 330 cursor.continue_().map_err(classify) 331 })(); 332 if let Err(error) = result { 333 refuse(&tx, &failure, error); 334 } 335 }) 336 }; 337 request.set_onsuccess(Some(success.as_ref().unchecked_ref())); 338 let _cursor = RequestHandler { 339 request, 340 _success: success, 341 }; 342 completion.wait().await?; 343 if !queued.get() { 344 return Err(Error::CommitUnknown); 345 } 346 Ok(Commit { records: count }) 347 }