use super::Announcement;
use crate::envelope::{Domain, Signed};
use crate::root::{Root, RootPin};
use crate::{Error, Result, Timestamp};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Topic {
pub pin: RootPin,
#[serde(default)]
pub app: String,
#[serde(default)]
pub channel: String,
}
impl Topic {
pub fn matches(&self, a: &Announcement) -> bool {
self.pin == a.pin && (self.app.is_empty() || self.app == a.app) && (self.channel.is_empty() || self.channel == a.channel)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Offered {
New,
Same,
Stale,
Root,
}
type Key = (RootPin, String, String);
#[derive(Debug, Default)]
pub struct Carrier {
roots: HashMap<RootPin, (Root, Vec<Signed>)>,
latest: HashMap<Key, (Announcement, Signed)>,
max: usize,
}
impl Carrier {
pub fn new(max: usize) -> Self {
Self { roots: HashMap::new(), latest: HashMap::new(), max: max.max(1) }
}
pub fn trust(&mut self, pin: RootPin, chain: &[Signed], now: Timestamp) -> Result<()> {
let (first, rest) = chain.split_first().ok_or_else(|| Error::invalid("root chain", "empty"))?;
let mut root = Root::verify_initial(&pin, first, now)?;
for env in rest {
root = root.verify_next(env, now)?;
}
self.roots.insert(pin, (root, chain.to_vec()));
Ok(())
}
pub fn pins(&self) -> Vec<RootPin> {
self.roots.keys().copied().collect()
}
pub fn chain(&self, pin: &RootPin) -> Option<&[Signed]> {
self.roots.get(pin).map(|(_, c)| c.as_slice())
}
pub fn offer(&mut self, env: &Signed, now: Timestamp) -> Result<Offered> {
if env.domain == Domain::Root {
for (root, chain) in self.roots.values_mut() {
if chain.iter().any(|c| c == env) {
return Ok(Offered::Same);
}
if let Ok(next) = root.verify_next(env, now) {
*root = next;
chain.push(env.clone());
return Ok(Offered::Root);
}
}
return Err(Error::invalid("root rotation", "does not follow any trusted root"));
}
let claimed: Announcement = if env.domain == Domain::Announcement {
env.decode()?
} else {
return Err(Error::WrongDomain { expected: Domain::Announcement, found: env.domain });
};
let (root, _) = self.roots.get(&claimed.pin).ok_or(Error::PinMismatch)?;
let a = Announcement::verify(env, claimed.pin, root, now)?;
let key = (a.pin, a.app.clone(), a.channel.clone());
if let Some((held, held_env)) = self.latest.get(&key) {
if held_env == env {
return Ok(Offered::Same);
}
if a.seq <= held.seq && held.expires > now {
return Ok(Offered::Stale);
}
}
self.latest.insert(key, (a, env.clone()));
if self.latest.len() > self.max {
self.prune(now);
while self.latest.len() > self.max {
let oldest = self.latest.iter().min_by_key(|(_, (a, _))| a.published).map(|(k, _)| k.clone());
if let Some(k) = oldest {
self.latest.remove(&k);
}
}
}
Ok(Offered::New)
}
pub fn matching(&self, topics: &[Topic], now: Timestamp) -> Vec<Signed> {
self.latest.values().filter(|(a, _)| a.expires > now && topics.iter().any(|t| t.matches(a))).map(|(_, e)| e.clone()).collect()
}
pub fn all(&self, now: Timestamp) -> Vec<Signed> {
self.latest.values().filter(|(a, _)| a.expires > now).map(|(_, e)| e.clone()).collect()
}
pub fn matches(env: &Signed, topics: &[Topic]) -> bool {
env.decode::<Announcement>().is_ok_and(|a| topics.iter().any(|t| t.matches(&a)))
}
pub fn prune(&mut self, now: Timestamp) {
self.latest.retain(|_, (a, _)| a.expires > now);
}
pub fn len(&self) -> usize {
self.latest.len()
}
pub fn is_empty(&self) -> bool {
self.latest.is_empty()
}
}