| 46 | |
| 47 | impl<T: Clone + Ord + Debug> CallerGuard<T> { |
| 48 | pub fn new(state: Rc<RefCell<State<T>>>, lock: T, params: CallerGuardParams) -> Option<Self> { |
| 49 | { |
| 50 | let pending_requests = &mut state.borrow_mut().pending_requests; |
| 51 | if let Some(existing_request) = pending_requests.get(&lock) { |
| 52 | if let Some(expires_at_ns) = existing_request { |
| 53 | if expires_at_ns > &time() { |
| 54 | // Lock is already held by another caller and has not expired. |
| 55 | return None; |
| 56 | } else { |
| 57 | // Lock has expired, fall through to update the lock. |
| 58 | crate::cdk::api::print(format!("Lock has expired for {lock:?}")); |
| 59 | pending_requests.remove(&lock); |
| 60 | } |
| 61 | } else { |
| 62 | // Lock is held indefinitely. |
| 63 | return None; |
| 64 | } |
| 65 | } |
| 66 | if let Some(max_concurrency) = params.max_concurrency { |
| 67 | if pending_requests.len() >= max_concurrency { |
| 68 | return None; |
| 69 | } |
| 70 | } |
| 71 | pending_requests.insert(lock.clone(), params.expires_at_ns); |
| 72 | } |
| 73 | |
| 74 | Some(Self { state, lock }) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | impl<T: Ord> Drop for CallerGuard<T> { |