Files
leleka/crates/backend-api/src/recent_ids.rs
T

137 lines
4.4 KiB
Rust

//! A bounded ledger of generation identities.
//!
//! The runtime refuses an identity it has already accepted (`generation_not_replayed`): a request id may have had
//! visible effects, so a repeated one must never run twice. Remembering every identity for the life of a runtime epoch
//! caps the number of generations a process can serve; the first deployment limit was 256, which an agent session
//! exhausts in minutes. This ledger keeps the most recent [`RecentIds::capacity`] identities and forgets the oldest
//! first. Identities are random UUIDs minted per attempt, so a repeat is only possible within a short window; the
//! window is large enough that a client retry or a duplicated delivery is always caught.
use std::collections::{HashSet, VecDeque};
/// The default number of remembered identities: about two megabytes of memory, days of agent traffic.
pub const DEFAULT_RECENT_IDS: usize = 16 * 1024;
#[derive(Debug, Clone)]
pub struct RecentIds {
set: HashSet<String>,
order: VecDeque<String>,
capacity: usize,
}
impl RecentIds {
/// `capacity` must be at least 1.
pub fn new(capacity: usize) -> Self {
let capacity = capacity.max(1);
Self { set: HashSet::new(), order: VecDeque::new(), capacity }
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn len(&self) -> usize {
self.set.len()
}
pub fn is_empty(&self) -> bool {
self.set.is_empty()
}
pub fn contains(&self, id: &str) -> bool {
self.set.contains(id)
}
/// Remember `id`, forgetting the oldest identity when the ledger is full. Returns false (and changes nothing) when
/// `id` is already remembered.
pub fn insert(&mut self, id: &str) -> bool {
if self.set.contains(id) {
return false;
}
while self.set.len() >= self.capacity {
match self.order.pop_front() {
Some(oldest) => {
self.set.remove(&oldest);
}
None => break,
}
}
self.set.insert(id.to_owned());
self.order.push_back(id.to_owned());
true
}
/// Forget `id` (an identity proven to have produced no effects). Returns whether it was remembered.
pub fn remove(&mut self, id: &str) -> bool {
if !self.set.remove(id) {
return false;
}
// A just-rejected identity is the newest entry, so the search from the back is short.
if let Some(at) = self.order.iter().rposition(|x| x == id) {
self.order.remove(at);
}
true
}
}
impl Default for RecentIds {
fn default() -> Self {
Self::new(DEFAULT_RECENT_IDS)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_repeated_identity_is_refused_and_does_not_age_the_ledger() {
let mut ids = RecentIds::new(3);
assert!(ids.insert("a"));
assert!(!ids.insert("a"));
assert!(ids.insert("b"));
assert_eq!(ids.len(), 2);
assert!(ids.contains("a") && ids.contains("b"));
}
#[test]
fn the_oldest_identity_is_forgotten_first_and_the_size_stays_bounded() {
let mut ids = RecentIds::new(3);
for id in ["a", "b", "c", "d", "e"] {
ids.insert(id);
assert!(ids.len() <= 3);
}
assert!(!ids.contains("a") && !ids.contains("b"));
assert!(ids.contains("c") && ids.contains("d") && ids.contains("e"));
// A forgotten identity is new again; a remembered one is still fenced.
assert!(!ids.insert("e"));
assert!(ids.insert("a"));
assert!(!ids.contains("c"));
}
#[test]
fn a_removed_identity_can_be_retried_and_does_not_evict_a_live_one_early() {
let mut ids = RecentIds::new(2);
ids.insert("a");
ids.insert("b");
assert!(ids.remove("b"));
assert!(!ids.remove("b"));
assert!(ids.insert("b"));
// ledger is [a, b]; the next insert must evict a, not the re-inserted b
ids.insert("c");
assert!(!ids.contains("a"));
assert!(ids.contains("b") && ids.contains("c"));
assert_eq!(ids.len(), 2);
}
#[test]
fn a_ledger_serves_far_more_generations_than_the_old_fixed_limit() {
let mut ids = RecentIds::default();
for n in 0..(3 * 256 + 5000) {
assert!(ids.insert(&format!("req-{n}")));
}
assert_eq!(ids.len(), 3 * 256 + 5000);
assert!(ids.contains("req-0"));
}
}