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
use cap_sdk_core::{Index, RootBucket, Router};
use futures::{future::LocalBoxFuture, task::AtomicWaker, Future};
use ic_kit::candid::CandidType;
use ic_kit::ic::{get_maybe, store};
use serde::{Deserialize, Serialize};
use std::{
    cell::RefCell,
    pin::Pin,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    task::{Context, Poll},
};

/// Contains data about the cap environment.
#[derive(Clone, Serialize, Deserialize, CandidType)]
pub struct CapEnv {
    pub(crate) root: RootBucket,
    pub(crate) router: Router,
}

thread_local! {
    pub(crate) static FUTURES: RefCell<Vec<LocalBoxFuture<'static, ()>>> = RefCell::new(vec![]);
}

impl CapEnv {
    /// Creates a new [`CapEnv`] with the index canister's [`Principal`] set to `index`.
    pub(crate) fn create(root: RootBucket, router: Router) -> Self {
        CapEnv { root, router }
    }

    /// Stores the [`CapEnv`] in the canister.
    pub(crate) fn store(&self) {
        store(self.clone());
    }

    pub(crate) async fn get<'a>() -> &'a Self {
        if let Some(data) = get_maybe::<CapEnv>() {
            data
        } else {
            CapEnv::await_futures().await;
            get_maybe::<CapEnv>().expect("No context created.")
        }
    }

    pub(crate) fn index(&self) -> Index {
        self.router.into()
    }

    pub(crate) async fn await_futures() {
        let futures = FUTURES.with(|futures| futures.take());

        if futures.is_empty() {
            return;
        }

        let flag = Flag::new();
        let f2 = flag.clone();

        let closure = async {
            flag.await;
        };

        CapEnv::insert_future(Box::pin(closure));

        for future in futures {
            future.await;
        }

        f2.signal();
    }

    pub(crate) fn insert_future(future: LocalBoxFuture<'static, ()>) {
        FUTURES.with(|futures| {
            futures.borrow_mut().push(future);
        });
    }

    /// Sets the [`CapEnv`] using the provided value.
    ///
    /// Used to restore the generated canister's ID after an upgrade.
    #[deprecated(note = "Use the safer cap_sdk::from_archive")]
    pub fn load_from_archive(env: CapEnv) {
        env.store();
    }

    /// Gets the [`CapEnv`].
    ///
    /// Should be used during the upgrade process of a contract canister.
    /// Call it during `pre_upgrade` to write it somewhere in stable storage.
    ///
    /// Afterwards, write it back with [`CapEnv::load_from_archive`]
    #[deprecated(note = "Use the safer cap_sdk::archive")]
    pub fn to_archive() -> Self {
        get_maybe::<CapEnv>().expect("No context created.").clone()
    }
}

struct Inner {
    waker: AtomicWaker,
    set: AtomicBool,
}

#[derive(Clone)]
struct Flag(Arc<Inner>);

impl Flag {
    pub fn new() -> Self {
        Self(Arc::new(Inner {
            waker: AtomicWaker::new(),
            set: AtomicBool::new(false),
        }))
    }

    pub fn signal(&self) {
        self.0.set.store(true, Ordering::Relaxed);
        self.0.waker.wake();
    }
}

impl Future for Flag {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        // quick check to avoid registration if already done.
        if self.0.set.load(Ordering::Relaxed) {
            return Poll::Ready(());
        }

        self.0.waker.register(cx.waker());

        // Need to check condition **after** `register` to avoid a race
        // condition that would result in lost notifications.
        if self.0.set.load(Ordering::Relaxed) {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }
}