1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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);
}

/// Inserts a transaction into the contract's history.
///
/// # Examples
///
/// ### Inserting an event from a builder.
///
/// See also: [`IndefiniteEventBuilder`][crate::IndefiniteEventBuilder], [`IntoDetails`][crate::IntoDetails], [`TryFromDetails`][crate::TryFromDetails].
/// ```rust
/// use cap_sdk_core::transaction::EventStatus;
//# use ic_kit::Principal;
//# use crate::{insert, IndefiniteEventBuilder, IntoDetails, TryFromDetails};
/// pub struct TransactionDetails {
///     foo: String,
///     bar: u64,
/// }
//# impl TryFromDetails for TransactionDetails {
//# fn try_from_details(
//#    details: &Vec<(String, cap_sdk_core::transaction::DetailValue)>,
//# ) -> Result<Self, ()> {
//#    Ok(Self {
//#        foo: String::from(
//#            "Peek behind the curtain and you might regret what you find...",
//#        ),
//#        bar: 42,
//#    })
//# }
//# }
//# impl IntoDetails for TransactionDetails {
//# fn into_details(self) -> Vec<(String, cap_sdk_core::transaction::DetailValue)> {
//#     vec![]
//# }
//# }
///
/// let transaction_details = TransactionDetails {
///     foo: String::from("foo"),
///     bar: 42
/// };
///
/// // Construct the event which accompanies our details.
/// // `IndefiniteEventBuilder` allows any `IntoDetails` type
/// // to be used in a call to `IndefiniteEventBuilder::details`.
/// //
/// // This is useful when dealing with the `cap-standards` types,
/// // but also works with a dynamically-constructed details vec with
/// // the type signature of `Vec<(String, DetailValue)>`.
/// let event = IndefiniteEventBuilder::new()
///     .caller(Principal::anonymous())
///     .operation(String::from("transfer"))
///     .status(EventStatus::Completed)
///     .details(transaction_details)
///     .build()
///     .unwrap();
///
///
/// // Insert the transaction with `insert`. It takes any type
/// // that implements `Into<IndefiniteEvent>`, this includes
/// // types like `TypedIndefiniteEvent` as well as `Vec<(String, DetailValue)>`
/// insert(event).await.unwrap();
/// ```
pub async fn insert(
    transaction: impl Into<IndefiniteEvent>,
) -> Result<TransactionId, InsertTransactionError> {
    insert_many(vec![transaction].into_iter()).await
}

/// Insert many transactions using one write to Cap.
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),
            })
    }
}

/// Insert a transaction into Cap without needing an await, this method guarantees finality of
/// the transactions and can handle insertion errors that might happen on the root bucket. (e.g
/// if the root bucket has gone out of cycles)
///
/// It works by having a local pending transactions buffer, in the heap storage, which it uses
/// to track failed transactions.
///
/// If you're using this method, be sure you store/restore the pending transactions during
/// upgrades. You can use [pending_transactions] and [restore_pending_transactions].
pub fn insert_sync(event: impl Into<IndefiniteEvent>) {
    PENDING.with(|p| {
        p.borrow_mut().push(event.into());
    });

    ic_cdk::block_on(async {
        let _ = flush_to_cap().await;
    });
}

/// Like [insert_sync], but allows you to insert more than one transaction at a time.
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::block_on(async {
        let _ = flush_to_cap().await;
    });
}

/// Return the array of pending transactions. Can be used in a pre-upgrade hook.
///
/// # Panics
/// If there is an ongoing flush that is not finalized yet.
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<_>>())
}

/// Restore the transactions, it keeps the previous pending transactions as well.
pub fn restore_pending_transactions(mut events: Vec<IndefiniteEvent>) {
    PENDING.with(|p| {
        events.extend(p.take());
        p.replace(events);
    });
}

/// Force a flush of pending transactions to Cap.
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| {
            // TODO(qti3e) Is ordering preserved this way?
            // need to be double checked.
            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_cdk::api::call::RejectionCode;
    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((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()])
    }
}