#![forbid(unsafe_code)]
use alloc::collections::VecDeque;
use alloc::vec::Vec;
use hashbrown::HashMap;
use crate::message::{CausedBy, Message};
use crate::protocol::{verify_causal, CausalProtocol, CausalViolation, VerificationResult};
use crate::store::{ContentHash, MessageStore, ThreadId};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum UnknownPredecessorPolicy {
#[default]
Reject,
Buffer {
max_pending: usize,
ttl: u64,
},
}
impl UnknownPredecessorPolicy {
pub fn buffer(ttl: u64) -> Self {
UnknownPredecessorPolicy::Buffer {
max_pending: 64,
ttl,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PendingReason {
CausalPending,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DropReason {
CausalTimeout,
Evicted,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyOutcome {
Accept,
Reject(CausalViolation),
Pending(PendingReason),
Buffered,
}
pub fn apply_policy(
result: &VerificationResult,
policy: &UnknownPredecessorPolicy,
) -> PolicyOutcome {
match result {
VerificationResult::Valid => PolicyOutcome::Accept,
VerificationResult::Violation(v) => PolicyOutcome::Reject(v.clone()),
VerificationResult::Unknown => match policy {
UnknownPredecessorPolicy::Reject => {
PolicyOutcome::Pending(PendingReason::CausalPending)
}
UnknownPredecessorPolicy::Buffer { .. } => PolicyOutcome::Buffered,
},
}
}
#[derive(Debug, Clone)]
pub struct PendingEntry {
pub hash: ContentHash,
pub message: Message,
pub thread: ThreadId,
pub performative: alloc::string::String,
pub caused_by: Option<CausedBy>,
pub inserted_at: u64,
}
#[derive(Debug, Clone)]
pub struct PendingQueue {
max_pending: usize,
ttl: u64,
queues: HashMap<ThreadId, VecDeque<PendingEntry>>,
}
impl PendingQueue {
pub fn new(max_pending: usize, ttl: u64) -> Self {
PendingQueue {
max_pending,
ttl,
queues: HashMap::new(),
}
}
pub fn from_policy(policy: &UnknownPredecessorPolicy) -> Self {
match policy {
UnknownPredecessorPolicy::Buffer { max_pending, ttl } => {
PendingQueue::new(*max_pending, *ttl)
}
UnknownPredecessorPolicy::Reject => {
panic!("PendingQueue::from_policy called with Reject policy")
}
}
}
pub fn enqueue(&mut self, entry: PendingEntry) -> Option<(PendingEntry, DropReason)> {
let queue = self.queues.entry(entry.thread.clone()).or_default();
let evicted = if queue.len() >= self.max_pending {
queue.pop_front().map(|e| (e, DropReason::Evicted))
} else {
None
};
queue.push_back(entry);
evicted
}
pub fn expire(&mut self, now: u64) -> Vec<(PendingEntry, DropReason)> {
let mut expired = Vec::new();
for queue in self.queues.values_mut() {
while let Some(front) = queue.front() {
if now.saturating_sub(front.inserted_at) >= self.ttl {
let entry = queue.pop_front().unwrap();
expired.push((entry, DropReason::CausalTimeout));
} else {
break;
}
}
}
expired
}
pub fn re_evaluate<S: MessageStore>(
&mut self,
store: &S,
protocol: &CausalProtocol,
) -> Vec<(PendingEntry, PolicyOutcome)> {
self.re_evaluate_with(|entry, thread_id| {
Some(verify_causal(
&entry.performative,
entry.caused_by.as_ref(),
store,
protocol,
thread_id,
))
})
}
pub fn re_evaluate_with<F>(&mut self, mut decide: F) -> Vec<(PendingEntry, PolicyOutcome)>
where
F: FnMut(&PendingEntry, &ThreadId) -> Option<VerificationResult>,
{
let mut resolved = Vec::new();
for (thread_id, queue) in self.queues.iter_mut() {
let mut i = 0;
while i < queue.len() {
let entry = &queue[i];
match decide(entry, thread_id) {
None | Some(VerificationResult::Unknown) => {
i += 1; }
Some(VerificationResult::Valid) => {
let entry = queue.remove(i).unwrap();
resolved.push((entry, PolicyOutcome::Accept));
}
Some(VerificationResult::Violation(v)) => {
let entry = queue.remove(i).unwrap();
resolved.push((entry, PolicyOutcome::Reject(v)));
}
}
}
}
resolved
}
pub fn len(&self) -> usize {
self.queues.values().map(|q| q.len()).sum()
}
pub fn is_empty(&self) -> bool {
self.queues.values().all(|q| q.is_empty())
}
pub fn thread_len(&self, thread: &ThreadId) -> usize {
self.queues.get(thread).map_or(0, |q| q.len())
}
pub fn max_pending(&self) -> usize {
self.max_pending
}
pub fn ttl(&self) -> u64 {
self.ttl
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::{CausedBy, Message, Performative};
use crate::protocol::{CausalProtocol, CausalViolation, NodeRef, StepDecl, VerificationResult};
use crate::sexpr::{Atom, SExpr};
use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
use alloc::collections::BTreeMap;
use alloc::string::ToString;
use alloc::vec;
fn make_message(performative: &str) -> Message {
Message::Simple {
performative: Performative::Custom(performative.to_string()),
recipient: None,
content: SExpr::Atom(Atom::Str("x".into())),
params: vec![],
thread: None,
sender: None,
caused_by: None,
}
}
fn make_thread() -> ThreadId {
ThreadId("t1".to_string())
}
fn make_hash(s: &str) -> ContentHash {
ContentHash(s.to_string())
}
#[test]
fn test_apply_policy_valid_accept() {
let result = VerificationResult::Valid;
let outcome = apply_policy(&result, &UnknownPredecessorPolicy::Reject);
assert_eq!(outcome, PolicyOutcome::Accept);
let outcome = apply_policy(&result, &UnknownPredecessorPolicy::buffer(60));
assert_eq!(outcome, PolicyOutcome::Accept);
}
#[test]
fn test_apply_policy_violation_reject() {
let v = CausalViolation::MissingCausedBy;
let result = VerificationResult::Violation(v.clone());
let outcome = apply_policy(&result, &UnknownPredecessorPolicy::Reject);
assert_eq!(outcome, PolicyOutcome::Reject(v.clone()));
let outcome = apply_policy(&result, &UnknownPredecessorPolicy::buffer(60));
assert_eq!(outcome, PolicyOutcome::Reject(v));
}
#[test]
fn test_apply_policy_unknown_reject_pending() {
let result = VerificationResult::Unknown;
let outcome = apply_policy(&result, &UnknownPredecessorPolicy::Reject);
assert_eq!(
outcome,
PolicyOutcome::Pending(PendingReason::CausalPending)
);
}
#[test]
fn test_apply_policy_unknown_buffer_buffered() {
let result = VerificationResult::Unknown;
let outcome = apply_policy(&result, &UnknownPredecessorPolicy::buffer(60));
assert_eq!(outcome, PolicyOutcome::Buffered);
}
#[test]
fn test_reject_policy_no_mutable_state() {
let policy = UnknownPredecessorPolicy::Reject;
let results = [
VerificationResult::Valid,
VerificationResult::Unknown,
VerificationResult::Violation(CausalViolation::MissingCausedBy),
];
for r in &results {
let _ = apply_policy(r, &policy);
}
assert_eq!(policy, UnknownPredecessorPolicy::Reject);
}
fn make_entry(hash: &str, perf: &str, thread: &ThreadId, ts: u64) -> PendingEntry {
PendingEntry {
hash: make_hash(hash),
message: make_message(perf),
thread: thread.clone(),
performative: perf.to_string(),
caused_by: Some(CausedBy::Single(hash.to_string())),
inserted_at: ts,
}
}
#[test]
fn test_pending_queue_enqueue_within_capacity() {
let mut pq = PendingQueue::new(64, 300);
let tid = make_thread();
let evicted = pq.enqueue(make_entry("h1", "ask", &tid, 100));
assert!(evicted.is_none());
assert_eq!(pq.len(), 1);
assert_eq!(pq.thread_len(&tid), 1);
}
#[test]
fn test_pending_queue_evicts_oldest_at_capacity() {
let mut pq = PendingQueue::new(2, 300);
let tid = make_thread();
pq.enqueue(make_entry("h1", "ask", &tid, 100));
pq.enqueue(make_entry("h2", "ask", &tid, 101));
let evicted = pq.enqueue(make_entry("h3", "ask", &tid, 102));
assert!(evicted.is_some());
let (entry, reason) = evicted.unwrap();
assert_eq!(entry.hash, make_hash("h1"));
assert_eq!(reason, DropReason::Evicted);
assert_eq!(pq.thread_len(&tid), 2);
}
#[test]
fn test_pending_queue_per_thread_isolation() {
let mut pq = PendingQueue::new(2, 300);
let t1 = ThreadId("t1".to_string());
let t2 = ThreadId("t2".to_string());
pq.enqueue(make_entry("h1", "ask", &t1, 100));
pq.enqueue(make_entry("h2", "ask", &t1, 101));
pq.enqueue(make_entry("h3", "ask", &t2, 100));
assert_eq!(pq.thread_len(&t1), 2);
assert_eq!(pq.thread_len(&t2), 1);
assert_eq!(pq.len(), 3);
}
#[test]
fn test_pending_queue_ttl_expiry() {
let mut pq = PendingQueue::new(64, 10); let tid = make_thread();
pq.enqueue(make_entry("h1", "ask", &tid, 100));
pq.enqueue(make_entry("h2", "ask", &tid, 105));
let expired = pq.expire(109);
assert!(expired.is_empty());
let expired = pq.expire(110);
assert_eq!(expired.len(), 1);
assert_eq!(expired[0].0.hash, make_hash("h1"));
assert_eq!(expired[0].1, DropReason::CausalTimeout);
assert_eq!(pq.len(), 1);
let expired = pq.expire(115);
assert_eq!(expired.len(), 1);
assert_eq!(expired[0].0.hash, make_hash("h2"));
}
#[test]
fn test_pending_queue_re_evaluate_on_store_growth() {
let mut steps = BTreeMap::new();
steps.insert(
"ask".to_string(),
StepDecl {
performative: "ask".to_string(),
predecessors: vec![],
successors: vec![NodeRef::Single("reply".to_string())],
},
);
steps.insert(
"reply".to_string(),
StepDecl {
performative: "reply".to_string(),
predecessors: vec![NodeRef::Single("ask".to_string())],
successors: vec![],
},
);
let protocol = CausalProtocol { steps };
let tid = make_thread();
let mut store = ThreadedMessageStore::new();
let mut pq = PendingQueue::new(64, 300);
let entry = PendingEntry {
hash: make_hash("reply1"),
message: make_message("reply"),
thread: tid.clone(),
performative: "reply".to_string(),
caused_by: Some(CausedBy::Single("ask1".to_string())),
inserted_at: 100,
};
pq.enqueue(entry);
let resolved = pq.re_evaluate(&store, &protocol);
assert!(resolved.is_empty());
assert_eq!(pq.len(), 1);
let ask_msg = make_message("ask");
store.append(make_hash("ask1"), tid.clone(), ask_msg);
let resolved = pq.re_evaluate(&store, &protocol);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].1, PolicyOutcome::Accept);
assert_eq!(pq.len(), 0);
}
#[test]
fn test_pending_queue_violation_on_re_evaluate() {
let mut steps = BTreeMap::new();
steps.insert(
"ask".to_string(),
StepDecl {
performative: "ask".to_string(),
predecessors: vec![],
successors: vec![NodeRef::Single("reply".to_string())],
},
);
steps.insert(
"reply".to_string(),
StepDecl {
performative: "reply".to_string(),
predecessors: vec![NodeRef::Single("ask".to_string())],
successors: vec![],
},
);
let protocol = CausalProtocol { steps };
let tid = make_thread();
let mut store = ThreadedMessageStore::new();
let mut pq = PendingQueue::new(64, 300);
let entry = PendingEntry {
hash: make_hash("reply1"),
message: make_message("reply"),
thread: tid.clone(),
performative: "reply".to_string(),
caused_by: Some(CausedBy::Single("wrong_hash".to_string())),
inserted_at: 100,
};
pq.enqueue(entry);
let wrong_msg = make_message("notify"); store.append(make_hash("wrong_hash"), tid.clone(), wrong_msg);
let resolved = pq.re_evaluate(&store, &protocol);
assert_eq!(resolved.len(), 1);
match &resolved[0].1 {
PolicyOutcome::Reject(_) => {} other => panic!("expected Reject, got {:?}", other),
}
assert_eq!(pq.len(), 0);
}
#[test]
fn test_default_policy_is_reject() {
assert_eq!(
UnknownPredecessorPolicy::default(),
UnknownPredecessorPolicy::Reject
);
}
#[test]
fn test_buffer_convenience_constructor() {
let policy = UnknownPredecessorPolicy::buffer(120);
assert_eq!(
policy,
UnknownPredecessorPolicy::Buffer {
max_pending: 64,
ttl: 120,
}
);
}
#[test]
fn test_from_policy_buffer() {
let policy = UnknownPredecessorPolicy::buffer(60);
let pq = PendingQueue::from_policy(&policy);
assert_eq!(pq.max_pending(), 64);
assert_eq!(pq.ttl(), 60);
}
#[test]
#[should_panic(expected = "Reject policy")]
fn test_from_policy_reject_panics() {
PendingQueue::from_policy(&UnknownPredecessorPolicy::Reject);
}
}