canic_core/ops/model/memory/
log.rs

1use 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
18/// How often to enforce retention after the first sweep.
19const RETENTION_INTERVAL: Duration = OPS_LOG_RETENTION_INTERVAL;
20
21///
22/// LogEntryDto
23///
24
25#[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///
49/// LogPageDto
50///
51
52#[derive(CandidType, Serialize)]
53pub struct LogPageDto {
54    pub entries: Vec<LogEntryDto>,
55    pub total: u64,
56}
57
58///
59/// LogOps
60///
61
62pub struct LogOps;
63
64impl LogOps {
65    /// Start periodic log retention sweeps. Safe to call multiple times.
66    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    /// Stop periodic retention sweeps.
87    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    /// Run a retention sweep immediately.
96    #[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    /// Append a log entry to stable storage.
108    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    ///
118    /// Export a page of log entries and the total count.
119    ///
120    #[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}