mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-27 13:52:18 +00:00
router: make inbound state durable
This commit is contained in:
1 parent
5c37690bd6
commit
42e3907835
4 files changed
+331
-12
No files matched your search
@@ -23,6 +23,16 @@ pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
|
||||
pub const TICKETS_FILE: &str = "available_tickets";
|
||||
pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries";
|
||||
pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed";
|
||||
pub const NODE_STATS_FILE: &str = "node_stats";
|
||||
|
||||
/// Counters persisted by Python's `LXMRouter.save_node_stats`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedNodeStats {
|
||||
pub client_propagation_messages_received: u64,
|
||||
pub client_propagation_messages_served: u64,
|
||||
pub unpeered_propagation_incoming: u64,
|
||||
pub unpeered_propagation_rx_bytes: u64,
|
||||
}
|
||||
|
||||
/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename.
|
||||
///
|
||||
@@ -78,10 +88,7 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let tmp = path.with_extension("tmp");
|
||||
fs::write(&tmp, &bytes)?;
|
||||
fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
write_file_atomic(path, &bytes)
|
||||
}
|
||||
|
||||
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
|
||||
@@ -134,6 +141,17 @@ pub fn load_locally_processed(dir: &Path) -> io::Result<HashMap<PropagationTrans
|
||||
Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
|
||||
let bytes = rmp_serde::to_vec_named(stats)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
fs::create_dir_all(dir)?;
|
||||
write_file_atomic(&dir.join(NODE_STATS_FILE), &bytes)
|
||||
}
|
||||
|
||||
pub fn load_node_stats(dir: &Path) -> io::Result<PersistedNodeStats> {
|
||||
Ok(read_mpk(&dir.join(NODE_STATS_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -184,6 +202,37 @@ mod tests {
|
||||
assert!(load_tickets(tmp.path()).unwrap().is_empty());
|
||||
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
|
||||
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
load_node_stats(tmp.path()).unwrap(),
|
||||
PersistedNodeStats::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_stats_roundtrip_uses_named_python_fields() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let expected = PersistedNodeStats {
|
||||
client_propagation_messages_received: 11,
|
||||
client_propagation_messages_served: 12,
|
||||
unpeered_propagation_incoming: 13,
|
||||
unpeered_propagation_rx_bytes: 14,
|
||||
};
|
||||
|
||||
save_node_stats(tmp.path(), &expected).unwrap();
|
||||
assert_eq!(load_node_stats(tmp.path()).unwrap(), expected);
|
||||
|
||||
let encoded = fs::read(tmp.path().join(NODE_STATS_FILE)).unwrap();
|
||||
let value = rmpv::decode::read_value(&mut std::io::Cursor::new(encoded)).unwrap();
|
||||
let keys = value
|
||||
.as_map()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|(key, _)| key.as_str())
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
assert!(keys.contains("client_propagation_messages_received"));
|
||||
assert!(keys.contains("client_propagation_messages_served"));
|
||||
assert!(keys.contains("unpeered_propagation_incoming"));
|
||||
assert!(keys.contains("unpeered_propagation_rx_bytes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -223,4 +272,63 @@ mod tests {
|
||||
.collect();
|
||||
assert!(leftovers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialization_failure_preserves_existing_file_without_temp_residue() {
|
||||
struct FailsToSerialize;
|
||||
|
||||
impl serde::Serialize for FailsToSerialize {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
Err(serde::ser::Error::custom("intentional failure"))
|
||||
}
|
||||
}
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("state");
|
||||
fs::write(&path, b"previous-good-state").unwrap();
|
||||
|
||||
assert!(write_mpk(&path, &FailsToSerialize).is_err());
|
||||
assert_eq!(fs::read(&path).unwrap(), b"previous-good-state");
|
||||
assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_atomic_writers_never_publish_torn_data_or_collide_on_temp_names() {
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = Arc::new(tmp.path().join("shared"));
|
||||
let barrier = Arc::new(Barrier::new(8));
|
||||
let payloads = (0u8..8)
|
||||
.map(|value| vec![value; 16 * 1024])
|
||||
.collect::<Vec<_>>();
|
||||
let threads = payloads
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|payload| {
|
||||
let path = Arc::clone(&path);
|
||||
let barrier = Arc::clone(&barrier);
|
||||
std::thread::spawn(move || {
|
||||
barrier.wait();
|
||||
write_file_atomic(path.as_ref(), &payload).unwrap();
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for thread in threads {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
|
||||
let published = fs::read(path.as_ref()).unwrap();
|
||||
assert!(payloads.contains(&published));
|
||||
let leftovers = fs::read_dir(tmp.path())
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_name().to_string_lossy().contains(".tmp."))
|
||||
.count();
|
||||
assert_eq!(leftovers, 0);
|
||||
}
|
||||
}
|
||||
@@ -727,7 +727,7 @@ impl PropagationNode {
|
||||
let filename = format!("{}.peer", hex_encode(&peer.destination_hash));
|
||||
let path = dir.join(filename);
|
||||
let data = peer.to_bytes_with_handled();
|
||||
std::fs::write(path, data)?;
|
||||
crate::persist::write_file_atomic(&path, &data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1856,6 +1856,14 @@ mod tests {
|
||||
peer.add_handled_message(&tid(0xCC));
|
||||
node.save_peer(&peer).unwrap();
|
||||
|
||||
drop(node);
|
||||
let node = PropagationNode::with_storage(
|
||||
PropagationNodeConfig::default(),
|
||||
[0xAA; 16],
|
||||
dir.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let loaded_peers = node.load_peers();
|
||||
assert_eq!(loaded_peers.len(), 1);
|
||||
assert!(loaded_peers[0].has_handled(&live_id));
|
||||
|
||||
@@ -20,6 +20,7 @@ use crate::peer::{LxmPeer, OutboundOfferPolicy};
|
||||
use crate::propagation::PropagationStore;
|
||||
use crate::stamper;
|
||||
use crate::ticket::{Ticket, TicketStore};
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
/// Router configuration.
|
||||
///
|
||||
@@ -926,12 +927,55 @@ impl LxmRouter {
|
||||
.and_then(|m| m.stamp_cost)
|
||||
}
|
||||
|
||||
/// Return whether a message or propagation transient ID has already been
|
||||
/// delivered locally.
|
||||
///
|
||||
/// Python reference: `LXMRouter.has_message` — LXMRouter.py:1667-1669.
|
||||
pub fn has_message(&self, transient_id: &PropagationTransientId) -> bool {
|
||||
self.propagation_store.is_locally_delivered(transient_id)
|
||||
}
|
||||
|
||||
/// Atomically admit one already-decoded inbound message and invoke the
|
||||
/// router callback at most once.
|
||||
///
|
||||
/// Both ordinary packet/Resource delivery and propagation download must
|
||||
/// use this actor-owned gate before any application-visible side effect.
|
||||
/// A propagation message may carry a ciphertext-derived `transient_id`
|
||||
/// distinct from its signed message hash; both identifiers are retained
|
||||
/// so a later delivery through another representation is still deduped.
|
||||
pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool {
|
||||
let Some(message_id) = message.message_id.or(message.hash) else {
|
||||
return false;
|
||||
};
|
||||
let transient_id = message.transient_id.unwrap_or(message_id);
|
||||
let propagated = transient_id != message_id;
|
||||
|
||||
if !allow_duplicate
|
||||
&& (self.propagation_store.is_locally_delivered(&message_id)
|
||||
|| self.propagation_store.is_locally_delivered(&transient_id)
|
||||
|| (propagated && self.propagation_store.is_locally_processed(&transient_id)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
self.propagation_store.mark_locally_delivered(message_id);
|
||||
if propagated {
|
||||
self.propagation_store.mark_locally_processed(transient_id);
|
||||
self.propagation_store.mark_locally_delivered(transient_id);
|
||||
}
|
||||
|
||||
if let Some(ref callback) = self.delivery_callback {
|
||||
callback(message);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Ingest an encrypted paper (`lxm://...`) URI and invoke the delivery callback as if the
|
||||
/// message had arrived via the network.
|
||||
///
|
||||
/// Python reference: `LXMRouter.ingest_lxm_uri` — LXMRouter.py:2370-2385.
|
||||
pub fn ingest_lxm_uri<F>(
|
||||
&self,
|
||||
&mut self,
|
||||
uri: &str,
|
||||
decrypt_fn: F,
|
||||
) -> Result<LxMessage, crate::message::MessageError>
|
||||
@@ -939,9 +983,7 @@ impl LxmRouter {
|
||||
F: FnOnce(&[u8]) -> Result<Vec<u8>, crate::message::MessageError>,
|
||||
{
|
||||
let message = LxMessage::from_paper_uri(uri, decrypt_fn)?;
|
||||
if let Some(ref cb) = self.delivery_callback {
|
||||
cb(&message);
|
||||
}
|
||||
self.deliver_inbound(&message, false);
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
@@ -968,6 +1010,11 @@ impl LxmRouter {
|
||||
.replace_locally_delivered(persist::load_local_deliveries(state_dir)?);
|
||||
self.propagation_store
|
||||
.replace_locally_processed(persist::load_locally_processed(state_dir)?);
|
||||
let stats = persist::load_node_stats(state_dir)?;
|
||||
self.client_propagation_messages_received = stats.client_propagation_messages_received;
|
||||
self.client_propagation_messages_served = stats.client_propagation_messages_served;
|
||||
self.unpeered_propagation_incoming = stats.unpeered_propagation_incoming;
|
||||
self.unpeered_propagation_rx_bytes = stats.unpeered_propagation_rx_bytes;
|
||||
// Python cleans tickets and stamp costs at load (LXMRouter.py:258-284).
|
||||
let now = now_f64();
|
||||
self.ticket_store.cull(now);
|
||||
@@ -985,6 +1032,15 @@ impl LxmRouter {
|
||||
persist::save_tickets(state_dir, self.ticket_store.all())?;
|
||||
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
|
||||
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
|
||||
persist::save_node_stats(
|
||||
state_dir,
|
||||
&persist::PersistedNodeStats {
|
||||
client_propagation_messages_received: self.client_propagation_messages_received,
|
||||
client_propagation_messages_served: self.client_propagation_messages_served,
|
||||
unpeered_propagation_incoming: self.unpeered_propagation_incoming,
|
||||
unpeered_propagation_rx_bytes: self.unpeered_propagation_rx_bytes,
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2626,11 +2682,70 @@ mod tests {
|
||||
fired_clone.store(true, Ordering::Relaxed);
|
||||
});
|
||||
|
||||
let msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct);
|
||||
(router.delivery_callback.as_ref().unwrap())(&msg);
|
||||
let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct);
|
||||
msg.hash = Some([0x11; 32]);
|
||||
msg.message_id = msg.hash;
|
||||
msg.transient_id = msg.hash;
|
||||
assert!(router.deliver_inbound(&msg, false));
|
||||
assert!(fired.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_delivery_is_deduped_across_packet_and_resource_representations() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let deliveries = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::clone(&deliveries);
|
||||
router.register_delivery_callback(move |_| {
|
||||
observed.fetch_add(1, Ordering::Relaxed);
|
||||
});
|
||||
|
||||
let mut packet = LxMessage::new(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"same",
|
||||
"message",
|
||||
DeliveryMethod::Opportunistic,
|
||||
);
|
||||
packet.hash = Some([0x22; 32]);
|
||||
packet.message_id = packet.hash;
|
||||
packet.transient_id = packet.hash;
|
||||
let mut resource = packet.clone();
|
||||
resource.method = DeliveryMethod::Direct;
|
||||
|
||||
assert!(router.deliver_inbound(&packet, false));
|
||||
assert!(!router.deliver_inbound(&resource, false));
|
||||
assert_eq!(deliveries.load(Ordering::Relaxed), 1);
|
||||
assert!(router.has_message(&[0x22; 32]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn propagated_delivery_records_ciphertext_and_signed_message_ids() {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let mut propagated = LxMessage::new(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"propagated",
|
||||
"message",
|
||||
DeliveryMethod::Propagated,
|
||||
);
|
||||
propagated.hash = Some([0x33; 32]);
|
||||
propagated.message_id = propagated.hash;
|
||||
propagated.transient_id = Some([0x44; 32]);
|
||||
|
||||
assert!(router.deliver_inbound(&propagated, false));
|
||||
assert!(router.has_message(&[0x33; 32]));
|
||||
assert!(router.has_message(&[0x44; 32]));
|
||||
assert!(router.propagation_store.is_locally_processed(&[0x44; 32]));
|
||||
|
||||
let mut direct = propagated.clone();
|
||||
direct.method = DeliveryMethod::Direct;
|
||||
direct.transient_id = direct.hash;
|
||||
assert!(!router.deliver_inbound(&direct, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ingest_lxm_uri() {
|
||||
use rns_crypto::ed25519::Ed25519PrivateKey;
|
||||
@@ -2676,6 +2791,10 @@ mod tests {
|
||||
r1.remember_ticket(dest_a, [0x01; 16], 4_102_444_800.0);
|
||||
r1.propagation_store.mark_locally_delivered(transient_a);
|
||||
r1.propagation_store.mark_locally_processed(transient_a);
|
||||
r1.client_propagation_messages_received = 10;
|
||||
r1.client_propagation_messages_served = 11;
|
||||
r1.unpeered_propagation_incoming = 12;
|
||||
r1.unpeered_propagation_rx_bytes = 13;
|
||||
r1.save_state(tmp.path()).unwrap();
|
||||
|
||||
let mut r2 = LxmRouter::new(RouterConfig::default());
|
||||
@@ -2687,6 +2806,10 @@ mod tests {
|
||||
assert_eq!(r2.get_outbound_ticket(&dest_a), Some([0x01; 16]));
|
||||
assert!(r2.propagation_store.is_locally_delivered(&transient_a));
|
||||
assert!(r2.propagation_store.is_locally_processed(&transient_a));
|
||||
assert_eq!(r2.client_propagation_messages_received, 10);
|
||||
assert_eq!(r2.client_propagation_messages_served, 11);
|
||||
assert_eq!(r2.unpeered_propagation_incoming, 12);
|
||||
assert_eq!(r2.unpeered_propagation_rx_bytes, 13);
|
||||
}
|
||||
|
||||
/// T1-10: persisted dedup timestamps are the REAL first-seen times —
|
||||
|
||||
@@ -2710,6 +2710,12 @@ impl LxmdRunner {
|
||||
return;
|
||||
}
|
||||
|
||||
// The propagation transient ID is over the representation received
|
||||
// from the node, before destination decryption. Retain it alongside
|
||||
// the signed message hash so redelivery through a different LXMF path
|
||||
// is still suppressed by the router-owned gate.
|
||||
let propagation_transient_id = LxMessage::compute_propagation_transient_id(data);
|
||||
|
||||
let unpack_data = if data[..16] == self.lxmf_dest_hash {
|
||||
match self.decrypt_inbound(&data[16..]) {
|
||||
Some(plaintext) => {
|
||||
@@ -2726,6 +2732,7 @@ impl LxmdRunner {
|
||||
match LxMessage::unpack(&unpack_data) {
|
||||
Ok(mut msg) => {
|
||||
msg.method = lxmf_core::constants::DeliveryMethod::Propagated;
|
||||
msg.transient_id = Some(propagation_transient_id);
|
||||
tracing::info!(
|
||||
from = %hex::encode(msg.source_hash),
|
||||
title = %msg.title,
|
||||
@@ -2876,7 +2883,15 @@ impl LxmdRunner {
|
||||
}
|
||||
|
||||
/// Write a received LXMF message to disk and invoke `on_inbound`.
|
||||
fn handle_inbound_message(&self, msg: LxMessage) {
|
||||
fn handle_inbound_message(&mut self, msg: LxMessage) {
|
||||
if !self.router.deliver_inbound(&msg, false) {
|
||||
tracing::debug!(
|
||||
message = ?msg.message_id.or(msg.hash).map(hex::encode),
|
||||
"ignoring already delivered inbound LXMF message"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Also deposit into the propagation store (if enabled) so peers can
|
||||
// download it via offer/get sync.
|
||||
if let Some(ref pn) = self.propagation_node
|
||||
@@ -4462,6 +4477,71 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&temp);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_then_link_resource_delivers_one_application_message() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
let unique = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let temp = std::env::temp_dir().join(format!(
|
||||
"lxmd-cross-path-dedup-{}-{unique}",
|
||||
std::process::id()
|
||||
));
|
||||
let (tx, _rx) = mpsc::channel::<TransportMessage>(64);
|
||||
let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx).expect("runner");
|
||||
|
||||
let deliveries = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::clone(&deliveries);
|
||||
runner.router.register_delivery_callback(move |_| {
|
||||
observed.fetch_add(1, Ordering::Relaxed);
|
||||
});
|
||||
|
||||
let mut message = LxMessage::new(
|
||||
runner.lxmf_dest_hash,
|
||||
[0xCD; 16],
|
||||
"one",
|
||||
"delivery",
|
||||
DeliveryMethod::Direct,
|
||||
);
|
||||
message.signature = Some([0u8; 64]);
|
||||
let packed = message.pack().expect("pack");
|
||||
let message_id = LxMessage::unpack(&packed)
|
||||
.expect("unpack")
|
||||
.message_id
|
||||
.expect("message id");
|
||||
|
||||
let ciphertext = runner
|
||||
.identity
|
||||
.encrypt(&packed[16..], None)
|
||||
.expect("encrypt opportunistic payload");
|
||||
let header = rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
context_flag: false,
|
||||
transport_type: rns_wire::flags::TransportType::Broadcast,
|
||||
destination_type: rns_wire::flags::DestinationType::Single,
|
||||
packet_type: rns_wire::flags::PacketType::Data,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash: runner.lxmf_dest_hash,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
};
|
||||
let mut packet = header.pack();
|
||||
packet.extend_from_slice(&ciphertext);
|
||||
|
||||
runner.handle_inbound_packet(&packet);
|
||||
runner.handle_link_delivered_data(&packed);
|
||||
|
||||
assert_eq!(deliveries.load(Ordering::Relaxed), 1);
|
||||
assert!(runner.router.has_message(&message_id));
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
let _ = std::fs::remove_dir_all(&temp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_reusable_link_state_uses_registered_backchannel() {
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
|
||||
Reference in new issue
Block a user