use cap_sdk_core::transaction::IndefiniteEvent;
use std::cell::RefCell;
use crate::{env::CapEnv, InsertTransactionError, TransactionId};
thread_local! {
pub(crate) static PENDING: RefCell<Vec<IndefiniteEvent>> = RefCell::new(vec![]);
pub(crate) static FLUSH_IN_PROGRESS: RefCell<u32> = RefCell::new(0);
}
pub async fn insert(
transaction: impl Into<IndefiniteEvent>,
) -> Result<TransactionId, InsertTransactionError> {
insert_many(vec![transaction].into_iter()).await
}
pub async fn insert_many<T: Into<IndefiniteEvent>>(
events: impl Iterator<Item = T>,
) -> Result<TransactionId, InsertTransactionError> {
let events = events.map(|x| x.into()).collect::<Vec<_>>();
let (events, offset) = PENDING.with(|p| {
let mut r = p.borrow_mut();
if r.is_empty() {
(Some(events), 0)
} else {
r.extend(events.into_iter());
(None, r.len() as u64)
}
});
if offset > 0 {
match flush_to_cap().await {
Ok(id) => Ok(id + offset - 1),
Err(e) => {
PENDING.with(|p| {
p.borrow_mut().remove(offset as usize - 1);
});
Err(e)
}
}
} else {
CapEnv::get()
.await
.root
.insert_many(&events.unwrap())
.await
.map_err(|(code, details)| match details.as_str() {
"The method can only be invoked by one of the writers." => {
InsertTransactionError::CantWrite
}
_ => InsertTransactionError::Unexpected(code, details),
})
}
}
pub fn insert_sync(event: impl Into<IndefiniteEvent>) {
PENDING.with(|p| {
p.borrow_mut().push(event.into());
});
ic_cdk::spawn(async {
let _ = flush_to_cap().await;
});
}
pub fn insert_many_sync<T: Into<IndefiniteEvent>>(events: impl Iterator<Item = T>) {
PENDING.with(|p| {
p.borrow_mut().extend(events.map(|e| e.into()));
});
ic_cdk::spawn(async {
let _ = flush_to_cap().await;
});
}
pub fn pending_transactions() -> Vec<IndefiniteEvent> {
if FLUSH_IN_PROGRESS.with(|e| *e.borrow()) > 0 {
panic!("There is a flush in progress.");
}
PENDING.with(|p| p.borrow().iter().cloned().collect::<Vec<_>>())
}
pub fn restore_pending_transactions(mut events: Vec<IndefiniteEvent>) {
PENDING.with(|p| {
events.extend(p.take());
p.replace(events);
});
}
pub async fn flush_to_cap() -> Result<TransactionId, InsertTransactionError> {
let context = CapEnv::get().await;
FLUSH_IN_PROGRESS.with(|e| *e.borrow_mut() += 1);
let mut events = PENDING.with(|p| p.take());
let res = context
.root
.insert_many(&events)
.await
.map_err(|(code, details)| match details.as_str() {
"The method can only be invoked by one of the writers." => {
InsertTransactionError::CantWrite
}
_ => InsertTransactionError::Unexpected(code, details),
})
.map_err(|e| {
PENDING.with(|p| {
events.extend(p.take());
p.replace(events);
});
e
});
FLUSH_IN_PROGRESS.with(|e| *e.borrow_mut() -= 1);
res
}
#[cfg(test)]
mod test {
use super::*;
use cap_sdk_core::{RootBucket, Router};
use ic_kit::{MockContext, Principal, RawHandler};
fn t(x: &str) -> IndefiniteEvent {
IndefiniteEvent {
caller: Principal::anonymous(),
operation: x.to_string(),
details: vec![],
}
}
#[async_std::test]
async fn insert_ordering() {
MockContext::new()
.with_handler(RawHandler::raw(Box::new(move |_, _, _, _| {
Err((ic_kit::RejectionCode::CanisterError, "X".into()))
})))
.with_data(CapEnv {
root: RootBucket(Principal::anonymous()),
router: Router(Principal::anonymous()),
})
.inject();
insert_sync(t("A"));
assert!(insert(t("B",)).await.is_err());
insert_sync(t("C"));
let tx = pending_transactions()
.into_iter()
.map(|x| x.operation)
.collect::<Vec<_>>();
assert_eq!(tx, vec!["A".to_string(), "C".to_string()])
}
}