git clone https://garage44.eu/jeroen/pinnacle.git.. /p2p/src/delivery.rs
//! Texts a contact's device has not said arrived. Its p2p service answers
//! each one at once, as it answers a ring; a text with no answer within
//! [`FALLBACK_MS`], or to a contact the DHT does not find, goes another way
//! (the p2p service texts the contact's phone number), as Calls calls it.
//! An app payload on a session is lost when it is lost: a session whose
//! other end switched off still takes it.
use crate::identity::Key;
use alloc::vec::Vec;
/// How long a text waits for its answer.
pub const FALLBACK_MS: u64 = 8000;
#[derive(Default)]
pub struct Delivery {
/// To whom, since when (none: due at once, its contact was not
/// found), and the text.
waiting: Vec<(Key, Option<u64>, Vec<u8>)>,
}
impl Delivery {
/// A text went to `contact`.
pub fn sent(&mut self, contact: Key, text: Vec<u8>, now: u64) {
self.waiting.push((contact, Some(now), text));
}
/// `contact`'s device said a text arrived: it is reachable, so none
/// waiting for it goes another way.
pub fn arrived(&mut self, contact: &Key) {
self.waiting.retain(|w| w.0 != *contact);
}
/// `contact` could not be found: what waits for it is due now.
pub fn unreachable(&mut self, contact: &Key) {
for w in self.waiting.iter_mut().filter(|w| w.0 == *contact) {
w.1 = None;
}
}
/// The texts that had no answer in time, oldest first, no longer
/// waited for.
pub fn due(&mut self, now: u64) -> Vec<(Key, Vec<u8>)> {
let mut due = Vec::new();
self.waiting.retain(|(contact, since, text)| {
if since.is_some_and(|t| now.saturating_sub(t) < FALLBACK_MS) {
return true;
}
due.push((*contact, text.clone()));
false
});
due
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn an_answered_text_is_never_due() {
let mut d = Delivery::default();
d.sent([1; 32], b"hoi".to_vec(), 1000);
d.arrived(&[1; 32]);
assert!(d.due(1000 + FALLBACK_MS * 2).is_empty());
}
#[test]
fn an_unanswered_text_is_due_after_the_wait_once() {
let mut d = Delivery::default();
d.sent([1; 32], b"one".to_vec(), 1000);
d.sent([2; 32], b"other".to_vec(), 2000);
d.sent([1; 32], b"two".to_vec(), 3000);
assert!(d.due(1000 + FALLBACK_MS - 1).is_empty());
assert_eq!(d.due(1000 + FALLBACK_MS), vec![([1; 32], b"one".to_vec())]);
// The other contact answers; the second text to the first is due
// in its turn, and nothing is due twice.
d.arrived(&[2; 32]);
assert_eq!(d.due(3000 + FALLBACK_MS), vec![([1; 32], b"two".to_vec())]);
assert!(d.due(u64::MAX).is_empty());
}
#[test]
fn a_contact_not_found_is_due_at_once() {
let mut d = Delivery::default();
d.sent([1; 32], b"a".to_vec(), 5000);
d.sent([1; 32], b"b".to_vec(), 5100);
d.sent([2; 32], b"c".to_vec(), 5200);
d.unreachable(&[1; 32]);
assert_eq!(
d.due(5300),
vec![([1; 32], b"a".to_vec()), ([1; 32], b"b".to_vec())]
);
assert!(d.due(5300).is_empty());
}
}