-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathlib.rs
99 lines (73 loc) · 2.23 KB
/
lib.rs
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
use std::cell::RefCell;
use std::rc::Rc;
use ic_canister::{generate_idl, update, Canister, MethodType, PreUpdate};
use ic_exports::candid::{CandidType, Deserialize, Principal};
use ic_metrics::{Metrics, MetricsStorage};
use ic_storage::stable::Versioned;
use ic_storage::IcStorage;
#[derive(Default, CandidType, Deserialize, IcStorage)]
pub struct State {
counter: u32,
}
impl Versioned for State {
type Previous = ();
fn upgrade((): ()) -> Self {
Self::default()
}
}
#[derive(CandidType, Deserialize, IcStorage, Default, Clone)]
pub struct MetricsSnapshot {
pub cycles: u64,
}
#[derive(Clone, Canister)]
pub struct CanisterC {
#[id]
principal: Principal,
#[state]
state: Rc<RefCell<State>>,
}
impl CanisterC {
#[update]
fn inc_counter(&mut self, value: u32) {
self.state.borrow_mut().counter += value;
}
}
impl Metrics for CanisterC {
fn metrics(&self) -> Rc<RefCell<MetricsStorage>> {
MetricsStorage::get()
}
}
impl PreUpdate for CanisterC {
fn pre_update(&self, _method_name: &str, _method_type: MethodType) {
self.update_metrics();
}
}
pub fn idl() -> String {
use ic_canister::Idl;
let canister_c_idl = generate_idl!();
let mut metrics_idl = <CanisterC as Metrics>::get_idl();
metrics_idl.merge(&canister_c_idl);
candid::pretty::candid::compile(&metrics_idl.env.env, &Some(metrics_idl.actor))
}
#[cfg(test)]
mod tests {
use ic_canister::canister_call;
use ic_exports::ic_kit::MockContext;
use super::*;
#[tokio::test]
async fn get_metrics() {
let ctx = MockContext::new().inject();
let mut canister_c = CanisterC::init_instance();
let _ = canister_call!(canister_c.inc_counter(5), ()).await;
ctx.add_time(6e+10 as u64 * 60 * 3); // 3 hours
let _ = canister_call!(canister_c.inc_counter(5), ()).await;
let metrics = canister_call!(canister_c.get_metrics(), ())
.await
.unwrap()
.metrics;
assert_eq!(metrics.map.len(), 2);
let metrics_snapshot = metrics.map.into_iter().next().unwrap().1;
assert_eq!(metrics_snapshot.cycles, 1e+14 as u128);
assert_eq!(metrics_snapshot.stable_memory_size, 0);
}
}