use rings_core::message::MessageLimit;
use rings_core::message::ReplayWindow;
use rings_core::swarm::Swarm;
use super::Envelope;
use crate::error::Result;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Delegation {
pub(crate) admission: bool,
pub(crate) replay: bool,
}
impl Delegation {
pub(crate) fn of(protocol: &impl super::Protocol) -> Self {
Self {
admission: protocol.delegates_admission(),
replay: protocol.delegates_replay(),
}
}
}
pub(crate) fn publish<'a>(
swarm: &Swarm,
declarations: impl IntoIterator<Item = (&'a str, Delegation)>,
) -> Result<()> {
for (namespace, delegation) in declarations {
let prefix = Envelope::namespace_prefix(namespace)?;
let limit = match delegation.admission {
true => MessageLimit::Delegated,
false => MessageLimit::Enforced,
};
let window = match delegation.replay {
true => ReplayWindow::Link,
false => ReplayWindow::Durable,
};
swarm.set_admission_delegation(prefix.clone(), limit);
swarm.set_replay_delegation(prefix, window);
}
Ok(())
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use super::Envelope;
use crate::error::Result;
fn envelope(namespace: &str) -> Vec<u8> {
Envelope::new(namespace, Bytes::from_static(b"payload"))
.encode()
.expect("envelope encodes")
}
#[test]
fn test_an_envelope_starts_with_exactly_its_own_namespace_prefix() -> Result<()> {
let prefix = Envelope::namespace_prefix("delegating")?;
assert!(envelope("delegating").starts_with(&prefix));
assert!(!envelope("delegating-not").starts_with(&prefix));
assert!(!envelope("delegate").starts_with(&prefix));
Ok(())
}
}