|
| 1 | +//! All the required to run a transaction |
| 2 | +
|
| 3 | +use std::{ |
| 4 | + cell::{Cell, RefCell}, |
| 5 | + future::Future, |
| 6 | + pin::Pin, |
| 7 | + rc::Rc, |
| 8 | + task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, |
| 9 | +}; |
| 10 | + |
| 11 | +use futures_channel::oneshot; |
| 12 | +use scoped_tls::scoped_thread_local; |
| 13 | +use web_sys::{ |
| 14 | + js_sys::Function, |
| 15 | + wasm_bindgen::{closure::Closure, JsCast as _}, |
| 16 | + IdbRequest, IdbTransaction, |
| 17 | +}; |
| 18 | + |
| 19 | +pub enum TransactionResult<R> { |
| 20 | + PolledForbiddenThing, |
| 21 | + Done(R), |
| 22 | +} |
| 23 | + |
| 24 | +pub struct RunnableTransaction<'f> { |
| 25 | + transaction: IdbTransaction, |
| 26 | + inflight_requests: Cell<usize>, |
| 27 | + future: RefCell<Pin<Box<dyn 'f + Future<Output = ()>>>>, |
| 28 | + polled_forbidden_thing: Box<dyn 'f + Fn()>, |
| 29 | + finished: RefCell<Option<oneshot::Sender<()>>>, |
| 30 | +} |
| 31 | + |
| 32 | +impl<'f> RunnableTransaction<'f> { |
| 33 | + pub fn new<R, E>( |
| 34 | + transaction: IdbTransaction, |
| 35 | + transaction_contents: impl 'f + Future<Output = Result<R, E>>, |
| 36 | + result: &'f RefCell<Option<TransactionResult<Result<R, E>>>>, |
| 37 | + finished: oneshot::Sender<()>, |
| 38 | + ) -> RunnableTransaction<'f> |
| 39 | + where |
| 40 | + R: 'f, |
| 41 | + E: 'f, |
| 42 | + { |
| 43 | + RunnableTransaction { |
| 44 | + transaction: transaction.clone(), |
| 45 | + inflight_requests: Cell::new(0), |
| 46 | + future: RefCell::new(Box::pin(async move { |
| 47 | + let transaction_result = transaction_contents.await; |
| 48 | + if transaction_result.is_err() { |
| 49 | + // The transaction failed. We should abort it. |
| 50 | + let _ = transaction.abort(); |
| 51 | + } |
| 52 | + assert!( |
| 53 | + result |
| 54 | + .replace(Some(TransactionResult::Done(transaction_result))) |
| 55 | + .is_none(), |
| 56 | + "Transaction completed multiple times", |
| 57 | + ); |
| 58 | + })), |
| 59 | + polled_forbidden_thing: Box::new(move || { |
| 60 | + *result.borrow_mut() = Some(TransactionResult::PolledForbiddenThing); |
| 61 | + }), |
| 62 | + finished: RefCell::new(Some(finished)), |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +fn panic_waker() -> Waker { |
| 68 | + fn clone(_: *const ()) -> RawWaker { |
| 69 | + RawWaker::new( |
| 70 | + std::ptr::null(), |
| 71 | + &RawWakerVTable::new(clone, wake, wake, drop), |
| 72 | + ) |
| 73 | + } |
| 74 | + fn wake(_: *const ()) { |
| 75 | + panic!("IndexedDB transaction tried to await on something other than a request") |
| 76 | + } |
| 77 | + fn drop(_: *const ()) {} |
| 78 | + unsafe { |
| 79 | + Waker::new( |
| 80 | + std::ptr::null(), |
| 81 | + &RawWakerVTable::new(clone, wake, wake, drop), |
| 82 | + ) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +scoped_thread_local!(static CURRENT: Rc<RunnableTransaction<'static>>); |
| 87 | + |
| 88 | +pub fn poll_it(state: &Rc<RunnableTransaction<'static>>) { |
| 89 | + CURRENT.set(&state, || { |
| 90 | + // Poll once, in order to run the transaction until its next await on a request |
| 91 | + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 92 | + state |
| 93 | + .future |
| 94 | + .borrow_mut() |
| 95 | + .as_mut() |
| 96 | + .poll(&mut Context::from_waker(&panic_waker())) |
| 97 | + })); |
| 98 | + |
| 99 | + // Try catching the panic and aborting. This currently does not work in wasm due to panic=abort, but will |
| 100 | + // hopefully work some day. The transaction _should_ auto-abort if the wasm module aborts, so hopefully we're |
| 101 | + // fine around there. |
| 102 | + let res = match res { |
| 103 | + Ok(res) => res, |
| 104 | + Err(err) => { |
| 105 | + // The poll panicked, abort the transaction |
| 106 | + let _ = state.transaction.abort(); |
| 107 | + std::panic::resume_unwind(err); |
| 108 | + } |
| 109 | + }; |
| 110 | + |
| 111 | + // Finally, check the poll result |
| 112 | + match res { |
| 113 | + Poll::Pending => { |
| 114 | + // Still some work to do. Is there at least one request in flight? |
| 115 | + if state.inflight_requests.get() == 0 { |
| 116 | + // Returned `Pending` despite no request being inflight. This means there was |
| 117 | + // an `await` on something other than transaction requests. Abort in order to |
| 118 | + // avoid the default auto-commit behavior. |
| 119 | + let _ = state.transaction.abort(); |
| 120 | + let _ = (state.polled_forbidden_thing)(); |
| 121 | + } |
| 122 | + } |
| 123 | + Poll::Ready(()) => { |
| 124 | + // Everything went well! Just signal that we're done |
| 125 | + let finished = state |
| 126 | + .finished |
| 127 | + .borrow_mut() |
| 128 | + .take() |
| 129 | + .expect("Transaction finished multiple times"); |
| 130 | + if finished.send(()).is_err() { |
| 131 | + // Transaction aborted by not awaiting on it |
| 132 | + let _ = state.transaction.abort(); |
| 133 | + return; |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + }); |
| 138 | +} |
| 139 | + |
| 140 | +pub fn add_request( |
| 141 | + req: IdbRequest, |
| 142 | + result: &Rc<RefCell<Option<Result<web_sys::Event, web_sys::Event>>>>, |
| 143 | +) -> impl Sized { |
| 144 | + CURRENT.with(move |state| { |
| 145 | + state |
| 146 | + .inflight_requests |
| 147 | + .set(state.inflight_requests.get() + 1); |
| 148 | + |
| 149 | + let on_success = Closure::once({ |
| 150 | + let state = state.clone(); |
| 151 | + let result = result.clone(); |
| 152 | + move |evt: web_sys::Event| { |
| 153 | + state |
| 154 | + .inflight_requests |
| 155 | + .set(state.inflight_requests.get() - 1); |
| 156 | + assert!(result.replace(Some(Ok(evt))).is_none()); |
| 157 | + poll_it(&state); |
| 158 | + } |
| 159 | + }); |
| 160 | + |
| 161 | + let on_error = Closure::once({ |
| 162 | + let state = state.clone(); |
| 163 | + let result = result.clone(); |
| 164 | + move |evt: web_sys::Event| { |
| 165 | + evt.prevent_default(); // Do not abort the transaction, we're dealing with it ourselves |
| 166 | + state |
| 167 | + .inflight_requests |
| 168 | + .set(state.inflight_requests.get() - 1); |
| 169 | + assert!(result.replace(Some(Err(evt))).is_none()); |
| 170 | + poll_it(&state); |
| 171 | + } |
| 172 | + }); |
| 173 | + |
| 174 | + req.set_onsuccess(Some(&on_success.as_ref().dyn_ref::<Function>().unwrap())); |
| 175 | + req.set_onerror(Some(&on_error.as_ref().dyn_ref::<Function>().unwrap())); |
| 176 | + |
| 177 | + // Keep the callbacks alive until they're no longer needed |
| 178 | + (on_success, on_error) |
| 179 | + }) |
| 180 | +} |
0 commit comments