use heapless::Vec;
use crate::dm::meta::EventPriority;
use crate::im::{ClusterId, EndpointId, EventId, EventPath};
use crate::msg::FabricIndex;
pub const NUMBER_RESERVATION: u64 = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventNumbers {
next: u64,
reserved_through: u64,
}
impl Default for EventNumbers {
fn default() -> Self {
Self::restore(0)
}
}
impl EventNumbers {
#[must_use]
pub const fn restore(persisted: u64) -> Self {
Self {
next: persisted,
reserved_through: persisted,
}
}
#[must_use]
pub const fn reservation(&self) -> Option<u64> {
if self.next >= self.reserved_through {
Some(self.next.saturating_add(NUMBER_RESERVATION))
} else {
None
}
}
pub const fn reserved(&mut self, value: u64) {
if value > self.reserved_through {
self.reserved_through = value;
}
}
pub const fn next(&mut self) -> Option<u64> {
if self.next >= self.reserved_through {
return None;
}
let number = self.next;
self.next = self.next.saturating_add(1);
Some(number)
}
#[must_use]
pub const fn peek(&self) -> u64 {
self.next
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Timestamp {
Epoch(u64),
System(u64),
}
impl Timestamp {
#[must_use]
pub const fn millis(self) -> u64 {
match self {
Self::Epoch(value) | Self::System(value) => value,
}
}
#[must_use]
pub const fn absolute(self) -> crate::im::EventTimestamp {
match self {
Self::Epoch(value) => crate::im::EventTimestamp::Epoch(value),
Self::System(value) => crate::im::EventTimestamp::System(value),
}
}
#[must_use]
pub fn delta_from(self, previous: Self) -> Option<crate::im::EventTimestamp> {
match (self, previous) {
(Self::Epoch(now), Self::Epoch(before)) => Some(crate::im::EventTimestamp::DeltaEpoch(
now.checked_sub(before)?,
)),
(Self::System(now), Self::System(before)) => Some(
crate::im::EventTimestamp::DeltaSystem(now.checked_sub(before)?),
),
_ => None,
}
}
}
pub const EVENT_DATA_MAX: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventRecord {
pub number: u64,
pub endpoint: EndpointId,
pub cluster: ClusterId,
pub event: EventId,
pub priority: EventPriority,
pub timestamp: Timestamp,
pub fabric_index: Option<FabricIndex>,
pub data: Vec<u8, EVENT_DATA_MAX>,
}
impl EventRecord {
#[must_use]
pub const fn path(&self) -> EventPath {
EventPath::event(self.endpoint, self.cluster, self.event)
}
#[must_use]
pub fn matches(&self, path: &EventPath) -> bool {
path.endpoint.is_none_or(|wanted| wanted == self.endpoint)
&& path.cluster.is_none_or(|wanted| wanted == self.cluster)
&& path.event.is_none_or(|wanted| wanted == self.event)
}
#[must_use]
pub fn visible_to(&self, accessing: Option<FabricIndex>) -> bool {
match self.fabric_index {
None => true,
Some(fabric) => accessing == Some(fabric),
}
}
}
#[derive(Debug)]
pub struct PriorityBuffer<const N: usize> {
records: Vec<EventRecord, N>,
dropped: u64,
}
impl<const N: usize> Default for PriorityBuffer<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> PriorityBuffer<N> {
#[must_use]
pub const fn new() -> Self {
Self {
records: Vec::new(),
dropped: 0,
}
}
pub fn push(&mut self, record: EventRecord) {
if self.records.len() >= N {
if self.records.is_empty() {
self.dropped = self.dropped.saturating_add(1);
return;
}
self.records.remove(0);
self.dropped = self.dropped.saturating_add(1);
}
let _ = self.records.push(record);
}
#[must_use]
pub fn records(&self) -> &[EventRecord] {
&self.records
}
#[must_use]
pub const fn dropped(&self) -> u64 {
self.dropped
}
#[must_use]
pub fn len(&self) -> usize {
self.records.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
pub fn prune_below(&mut self, number: u64) {
self.records.retain(|record| record.number >= number);
}
}
#[derive(Debug)]
pub struct EventStore<const C: usize, const I: usize, const D: usize> {
critical: PriorityBuffer<C>,
info: PriorityBuffer<I>,
debug: PriorityBuffer<D>,
numbers: EventNumbers,
}
impl<const C: usize, const I: usize, const D: usize> Default for EventStore<C, I, D> {
fn default() -> Self {
Self::new(EventNumbers::default())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordError {
NeedsReservation(u64),
DataTooLong,
}
impl<const C: usize, const I: usize, const D: usize> EventStore<C, I, D> {
#[must_use]
pub const fn new(numbers: EventNumbers) -> Self {
Self {
critical: PriorityBuffer::new(),
info: PriorityBuffer::new(),
debug: PriorityBuffer::new(),
numbers,
}
}
#[must_use]
pub const fn numbers(&self) -> EventNumbers {
self.numbers
}
pub const fn reserved(&mut self, value: u64) {
self.numbers.reserved(value);
}
pub fn record(&mut self, event: &NewEvent<'_>) -> Result<u64, RecordError> {
let NewEvent {
endpoint,
cluster,
event: event_id,
priority,
timestamp,
fabric_index,
data,
} = *event;
let stored = Vec::from_slice(data).map_err(|_| RecordError::DataTooLong)?;
let Some(number) = self.numbers.next() else {
let owed = self
.numbers
.reservation()
.unwrap_or(self.numbers.peek().saturating_add(NUMBER_RESERVATION));
return Err(RecordError::NeedsReservation(owed));
};
let record = EventRecord {
number,
endpoint,
cluster,
event: event_id,
priority,
timestamp,
fabric_index,
data: stored,
};
match priority {
EventPriority::Critical => self.critical.push(record),
EventPriority::Info => self.info.push(record),
EventPriority::Debug => self.debug.push(record),
}
Ok(number)
}
#[must_use]
pub const fn buffer(&self, priority: EventPriority) -> &dyn BufferView {
match priority {
EventPriority::Critical => &self.critical,
EventPriority::Info => &self.info,
EventPriority::Debug => &self.debug,
}
}
pub fn matching<'a>(
&'a self,
path: &'a EventPath,
accessing: Option<FabricIndex>,
min_number: u64,
) -> impl Iterator<Item = &'a EventRecord> {
let mut all: Vec<&'a EventRecord, 64> = Vec::new();
for record in self
.critical
.records()
.iter()
.chain(self.info.records())
.chain(self.debug.records())
{
if record.number >= min_number
&& record.matches(path)
&& record.visible_to(accessing)
&& all.push(record).is_err()
{
break;
}
}
all.sort_unstable_by_key(|record| record.number);
all.into_iter()
}
#[must_use]
pub fn len(&self) -> usize {
self.critical
.len()
.saturating_add(self.info.len())
.saturating_add(self.debug.len())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn prune_below(&mut self, number: u64) {
self.critical.prune_below(number);
self.info.prune_below(number);
self.debug.prune_below(number);
}
}
#[derive(Debug, Clone, Copy)]
pub struct NewEvent<'a> {
pub endpoint: EndpointId,
pub cluster: ClusterId,
pub event: EventId,
pub priority: EventPriority,
pub timestamp: Timestamp,
pub fabric_index: Option<FabricIndex>,
pub data: &'a [u8],
}
pub trait BufferView {
fn records(&self) -> &[EventRecord];
fn dropped(&self) -> u64;
}
impl<const N: usize> BufferView for PriorityBuffer<N> {
fn records(&self) -> &[EventRecord] {
self.records()
}
fn dropped(&self) -> u64 {
self.dropped()
}
}
pub trait EventSource: core::fmt::Debug {
fn each_matching(
&self,
path: &EventPath,
accessing: Option<FabricIndex>,
min_number: u64,
each: &mut dyn FnMut(&EventRecord) -> bool,
);
fn highest_number(&self) -> Option<u64>;
}
impl<const C: usize, const I: usize, const D: usize> EventSource for EventStore<C, I, D> {
fn each_matching(
&self,
path: &EventPath,
accessing: Option<FabricIndex>,
min_number: u64,
each: &mut dyn FnMut(&EventRecord) -> bool,
) {
for record in self.matching(path, accessing, min_number) {
if !each(record) {
return;
}
}
}
fn highest_number(&self) -> Option<u64> {
self.critical
.records()
.iter()
.chain(self.info.records())
.chain(self.debug.records())
.map(|record| record.number)
.max()
}
}
impl<T: EventSource> EventSource for core::cell::RefCell<T> {
fn each_matching(
&self,
path: &EventPath,
accessing: Option<FabricIndex>,
min_number: u64,
each: &mut dyn FnMut(&EventRecord) -> bool,
) {
self.borrow()
.each_matching(path, accessing, min_number, each);
}
fn highest_number(&self) -> Option<u64> {
self.borrow().highest_number()
}
}