use super::{Lifecycle, MemoryError, MemoryReceiver};
use crate::receiver_policy::{SessionFacts, SessionPolicyError};
use ic_auth_protocol_types::Principal;
use std::ops::Bound::{Excluded, Unbounded};
pub const MAX_INSPECTION_PAGE: u16 = 32;
pub const MAX_INSPECTION_SCAN: u16 = 128;
#[derive(Debug)]
pub struct SessionPage<'a> {
pub observed_at_ns: u64,
pub generation: u64,
pub sessions: Vec<SessionFacts<'a>>,
pub next_after: Option<Principal>,
pub scanned: u16,
}
impl MemoryReceiver {
pub fn inspect_sessions(
&self,
after: Option<Principal>,
limit: u16,
scan_budget: u16,
now_ns: u64,
) -> Result<SessionPage<'_>, MemoryError> {
if self.lifecycle == Lifecycle::Closed {
return Err(MemoryError::Closed);
}
if limit == 0
|| limit > MAX_INSPECTION_PAGE
|| scan_budget < limit
|| scan_budget > MAX_INSPECTION_SCAN
{
return Err(SessionPolicyError::InvalidContext.into());
}
if now_ns < self.observed_at_ns {
return Err(SessionPolicyError::ClockRollback.into());
}
let rows = self
.callers
.range((after.map_or(Unbounded, Excluded), Unbounded));
Ok(collect(
rows.map(|(caller, row)| (*caller, row.session_facts())),
limit,
scan_budget,
now_ns,
self.generation,
))
}
}
fn collect<'a>(
mut rows: impl Iterator<Item = (Principal, Option<SessionFacts<'a>>)>,
limit: u16,
scan_budget: u16,
now_ns: u64,
generation: u64,
) -> SessionPage<'a> {
let mut page = SessionPage {
observed_at_ns: now_ns,
generation,
sessions: Vec::with_capacity(usize::from(limit)),
next_after: None,
scanned: 0,
};
let mut last = None;
while page.scanned < scan_budget && page.sessions.len() < usize::from(limit) {
let Some((caller, session)) = rows.next() else {
return page;
};
page.scanned += 1;
last = Some(caller);
if let Some(session) = session {
page.sessions.push(session);
}
}
if rows.next().is_some() {
page.next_after = last;
}
page
}
#[cfg(test)]
mod tests;