canic_core/ops/model/memory/
log.rs1use crate::{
2 Error,
3 cdk::timers::{TimerId, clear_timer, set_timer, set_timer_interval},
4 log,
5 log::{Level, Topic},
6 model::memory::log::{LogEntry, StableLog, apply_retention},
7 ops::model::{OPS_INIT_DELAY, OPS_LOG_RETENTION_INTERVAL},
8 types::PageRequest,
9};
10use candid::CandidType;
11use serde::Serialize;
12use std::{cell::RefCell, time::Duration};
13
14thread_local! {
15 static RETENTION_TIMER: RefCell<Option<TimerId>> = const { RefCell::new(None) };
16}
17
18const RETENTION_INTERVAL: Duration = OPS_LOG_RETENTION_INTERVAL;
20
21#[derive(CandidType, Clone, Debug, Serialize)]
26pub struct LogEntryDto {
27 pub index: u64,
28 pub created_at: u64,
29 pub crate_name: String,
30 pub level: Level,
31 pub topic: Option<String>,
32 pub message: String,
33}
34
35impl LogEntryDto {
36 fn from_pair(index: usize, entry: LogEntry) -> Self {
37 Self {
38 index: index as u64,
39 created_at: entry.created_at,
40 crate_name: entry.crate_name,
41 level: entry.level,
42 topic: entry.topic,
43 message: entry.message,
44 }
45 }
46}
47
48#[derive(CandidType, Serialize)]
53pub struct LogPageDto {
54 pub entries: Vec<LogEntryDto>,
55 pub total: u64,
56}
57
58pub struct LogOps;
63
64impl LogOps {
65 pub fn start_retention() {
67 RETENTION_TIMER.with_borrow_mut(|slot| {
68 if slot.is_some() {
69 return;
70 }
71
72 let init = set_timer(OPS_INIT_DELAY, async {
73 let _ = Self::retain();
74
75 let interval = set_timer_interval(RETENTION_INTERVAL, || async {
76 let _ = Self::retain();
77 });
78
79 RETENTION_TIMER.with_borrow_mut(|slot| *slot = Some(interval));
80 });
81
82 *slot = Some(init);
83 });
84 }
85
86 pub fn stop_retention() {
88 RETENTION_TIMER.with_borrow_mut(|slot| {
89 if let Some(id) = slot.take() {
90 clear_timer(id);
91 }
92 });
93 }
94
95 #[must_use]
97 pub fn retain() -> bool {
98 match apply_retention() {
99 Ok(()) => true,
100 Err(err) => {
101 log!(Topic::Memory, Warn, "log retention failed: {err}");
102 false
103 }
104 }
105 }
106
107 pub fn append<T: ToString, M: AsRef<str>>(
109 crate_name: &str,
110 topic: Option<T>,
111 level: Level,
112 message: M,
113 ) -> Result<u64, Error> {
114 StableLog::append(crate_name, topic, level, message)
115 }
116
117 #[must_use]
121 pub fn page(
122 crate_name: Option<String>,
123 topic: Option<String>,
124 min_level: Option<Level>,
125 request: PageRequest,
126 ) -> LogPageDto {
127 let request = request.clamped();
128
129 let (raw_entries, total) = StableLog::entries_page_filtered(
130 crate_name.as_deref(),
131 topic.as_deref(),
132 min_level,
133 request,
134 );
135
136 let entries = raw_entries
137 .into_iter()
138 .map(|(i, entry)| LogEntryDto::from_pair(i, entry))
139 .collect();
140
141 LogPageDto { entries, total }
142 }
143}