mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-22 23:10:35 +00:00
router: journal delivery claims and keep upstream's delivery metadata
This commit is contained in:
1 parent
186ffb48e3
commit
ed3ec7070c
8 files changed
+386
-39
No files matched your search
@@ -287,6 +287,8 @@ pub const JOB_LINKS_INTERVAL: u64 = 1;
|
||||
pub const JOB_TRANSIENT_INTERVAL: u64 = 60;
|
||||
/// Interval (in ticks) for cleaning the message store.
|
||||
pub const JOB_STORE_INTERVAL: u64 = 120;
|
||||
/// Interval (in ticks) for culling stamp costs and expired tickets.
|
||||
pub const JOB_STAMPCOST_INTERVAL: u64 = 120;
|
||||
/// Tick interval for cleaning throttled-peer entries, named for Python
|
||||
/// peer-sync cadence. Peer synchronization is driven by the embedding runtime.
|
||||
pub const JOB_PEERSYNC_INTERVAL: u64 = 6;
|
||||
|
||||
@@ -161,6 +161,21 @@ impl InboundResourceHandle {
|
||||
.is_ok()
|
||||
})
|
||||
}
|
||||
|
||||
/// Like [`Self::cancel`], but waits for room in the command channel instead
|
||||
/// of refusing when it is full.
|
||||
pub async fn cancel_wait(&self) -> bool {
|
||||
if self.snapshot().is_closed() {
|
||||
return false;
|
||||
}
|
||||
match &self.cancel_tx {
|
||||
Some(tx) => tx
|
||||
.send(InboundResourceCancelRequest::new(self.key))
|
||||
.await
|
||||
.is_ok(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveInboundResource {
|
||||
@@ -250,6 +265,22 @@ impl InboundResourceTracker {
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Request cancellation of every active Resource, waiting for channel room,
|
||||
/// so the count covers all of them as Python's `cancel_all_inbound` does.
|
||||
/// The future owns its handles and does not borrow the tracker.
|
||||
pub fn cancel_all_inbound_wait(
|
||||
&self,
|
||||
) -> impl std::future::Future<Output = usize> + Send + 'static {
|
||||
let handles = self.inbound_resources();
|
||||
async move {
|
||||
let mut cancelled = 0;
|
||||
for handle in handles {
|
||||
cancelled += usize::from(handle.cancel_wait().await);
|
||||
}
|
||||
cancelled
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply one lifecycle update from the embedding runtime.
|
||||
pub fn handle_event(&mut self, event: InboundResourceEvent) {
|
||||
match event {
|
||||
@@ -286,6 +317,15 @@ impl InboundResourceTracker {
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
"Began {} transfer for LXMF delivery resource {}",
|
||||
if data_size > 0 {
|
||||
pretty_size(data_size)
|
||||
} else {
|
||||
"unknown size".to_string()
|
||||
},
|
||||
hex::encode(key.resource_id)
|
||||
);
|
||||
let snapshot = InboundResourceSnapshot {
|
||||
key,
|
||||
data_size,
|
||||
@@ -333,6 +373,22 @@ impl InboundResourceTracker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `RNS.prettysize` for byte counts.
|
||||
fn pretty_size(size: usize) -> String {
|
||||
let mut num = size as f64;
|
||||
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] {
|
||||
if num.abs() < 1000.0 {
|
||||
return if unit.is_empty() {
|
||||
format!("{num:.0} B")
|
||||
} else {
|
||||
format!("{num:.2} {unit}B")
|
||||
};
|
||||
}
|
||||
num /= 1000.0;
|
||||
}
|
||||
format!("{num:.2}YB")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -71,12 +71,25 @@ impl std::fmt::Debug for MessageCallbacks {
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
pub const ENCRYPTION_DESCRIPTION_AES: &str = "AES-256";
|
||||
pub const ENCRYPTION_DESCRIPTION_EC: &str = "Curve25519";
|
||||
pub const ENCRYPTION_DESCRIPTION_UNENCRYPTED: &str = "Unencrypted";
|
||||
|
||||
/// Physical-layer readings of the packet or Link a message arrived on.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct PhyStats {
|
||||
pub rssi: Option<f64>,
|
||||
pub snr: Option<f64>,
|
||||
pub q: Option<f64>,
|
||||
}
|
||||
|
||||
/// Mutable delivery observations; none can change a message's authenticated bytes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MessageMetadata {
|
||||
pub state: MessageState,
|
||||
pub method: DeliveryMethod,
|
||||
pub ratchet_id: Option<[u8; 32]>,
|
||||
/// The ratchet ID (10 bytes) or Link ID (16 bytes) the message travelled under.
|
||||
pub ratchet_id: Option<Vec<u8>>,
|
||||
pub delivery_attempts: u32,
|
||||
pub last_delivery_attempt: f64,
|
||||
pub next_delivery_attempt: f64,
|
||||
@@ -96,6 +109,11 @@ pub struct MessageMetadata {
|
||||
pub path_request_retried: bool,
|
||||
pub max_delivery_attempts: Option<u32>,
|
||||
pub receipt_timeout: Option<f64>,
|
||||
pub rssi: Option<f64>,
|
||||
pub snr: Option<f64>,
|
||||
pub q: Option<f64>,
|
||||
pub stamp_valid: bool,
|
||||
pub stamp_checked: bool,
|
||||
}
|
||||
impl Default for MessageMetadata {
|
||||
fn default() -> Self {
|
||||
@@ -121,6 +139,11 @@ impl Default for MessageMetadata {
|
||||
path_request_retried: false,
|
||||
max_delivery_attempts: None,
|
||||
receipt_timeout: None,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
stamp_valid: false,
|
||||
stamp_checked: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -659,14 +682,83 @@ impl LxMessage {
|
||||
full_hash(lxmf_data)
|
||||
}
|
||||
|
||||
/// Python `LXMessage.determine_transport_encryption` for the current method
|
||||
/// and the recipient destination type.
|
||||
pub fn determine_transport_encryption(
|
||||
&mut self,
|
||||
destination_type: rns_wire::flags::DestinationType,
|
||||
) {
|
||||
use rns_wire::flags::DestinationType;
|
||||
let by_type = match destination_type {
|
||||
DestinationType::Single => (true, ENCRYPTION_DESCRIPTION_EC),
|
||||
DestinationType::Group => (true, ENCRYPTION_DESCRIPTION_AES),
|
||||
_ => (false, ENCRYPTION_DESCRIPTION_UNENCRYPTED),
|
||||
};
|
||||
let (encrypted, description) = match self.method {
|
||||
DeliveryMethod::Direct => (true, ENCRYPTION_DESCRIPTION_EC),
|
||||
DeliveryMethod::Opportunistic | DeliveryMethod::Propagated | DeliveryMethod::Paper => {
|
||||
by_type
|
||||
}
|
||||
};
|
||||
self.transport_encrypted = encrypted;
|
||||
self.transport_encryption = Some(description.to_string());
|
||||
}
|
||||
|
||||
/// Python `lxmf_delivery` receive metadata: a ratchet ID is kept if already
|
||||
/// set, and transport encryption follows the destination type the message
|
||||
/// arrived on (`None` when unknown).
|
||||
pub fn record_delivery(
|
||||
&mut self,
|
||||
destination_type: Option<rns_wire::flags::DestinationType>,
|
||||
ratchet_id: Option<&[u8]>,
|
||||
method: Option<DeliveryMethod>,
|
||||
phy: Option<PhyStats>,
|
||||
) {
|
||||
use rns_wire::flags::DestinationType;
|
||||
if let Some(id) = ratchet_id.filter(|id| !id.is_empty())
|
||||
&& self.ratchet_id.is_none()
|
||||
{
|
||||
self.ratchet_id = Some(id.to_vec());
|
||||
}
|
||||
if let Some(method) = method {
|
||||
self.method = method;
|
||||
}
|
||||
if let Some(phy) = phy {
|
||||
self.rssi = phy.rssi;
|
||||
self.snr = phy.snr;
|
||||
self.q = phy.q;
|
||||
}
|
||||
let (encrypted, description) = match destination_type {
|
||||
Some(DestinationType::Single | DestinationType::Link) => {
|
||||
(true, Some(ENCRYPTION_DESCRIPTION_EC))
|
||||
}
|
||||
Some(DestinationType::Group) => (true, Some(ENCRYPTION_DESCRIPTION_AES)),
|
||||
_ => (false, None),
|
||||
};
|
||||
self.transport_encrypted = encrypted;
|
||||
self.transport_encryption = description.map(str::to_string);
|
||||
}
|
||||
|
||||
/// Record the result of an inbound stamp check against `required_cost`
|
||||
/// (Python `lxmf_delivery`); whether to drop on failure is the caller's policy.
|
||||
pub fn check_stamp(&mut self, required_cost: f64, tickets: Option<&[Vec<u8>]>) -> bool {
|
||||
self.stamp_valid = self.validate_stamp_with_tickets(required_cost, tickets);
|
||||
self.stamp_checked = true;
|
||||
self.stamp_valid
|
||||
}
|
||||
|
||||
pub fn cancel(&mut self) {
|
||||
if self.state == MessageState::Outbound || self.state == MessageState::Sending {
|
||||
self.state = MessageState::Cancelled;
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `fail_message`: progress resets and a rejected message stays rejected.
|
||||
pub fn mark_failed(&mut self) {
|
||||
self.state = MessageState::Failed;
|
||||
self.progress = 0.0;
|
||||
if self.state != MessageState::Rejected {
|
||||
self.state = MessageState::Failed;
|
||||
}
|
||||
self.notify_failed();
|
||||
}
|
||||
|
||||
@@ -680,6 +772,7 @@ impl LxMessage {
|
||||
return;
|
||||
}
|
||||
self.state = MessageState::Delivered;
|
||||
self.progress = 1.0;
|
||||
self.notify_delivered();
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! * `local_deliveries` — delivered transient IDs and timestamps
|
||||
//! * `locally_processed` — processed transient IDs and timestamps
|
||||
//! * `node_stats` — propagation-node counters
|
||||
//! * `delivery_claims` — delivered/processed IDs appended since the last full save
|
||||
//! * `propagation_suppression_v1` — bounded download suppression records
|
||||
//! * `propagation_node_policies_v1` — recorded propagation-node policies
|
||||
//!
|
||||
@@ -28,6 +29,116 @@ 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";
|
||||
/// Append-only delivered/processed claims written before delivery callbacks run.
|
||||
pub const DELIVERY_CLAIMS_FILE: &str = "delivery_claims";
|
||||
|
||||
const CLAIM_DELIVERED: u8 = 0;
|
||||
const CLAIM_PROCESSED: u8 = 1;
|
||||
const CLAIM_RECORD_LEN: usize = 1 + 32 + 8;
|
||||
|
||||
/// Durably append a claim (`processed = false` for delivered IDs).
|
||||
pub fn append_delivery_claim(
|
||||
dir: &Path,
|
||||
id: &PropagationTransientId,
|
||||
processed: bool,
|
||||
at: f64,
|
||||
) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let mut record = [0u8; CLAIM_RECORD_LEN];
|
||||
record[0] = if processed {
|
||||
CLAIM_PROCESSED
|
||||
} else {
|
||||
CLAIM_DELIVERED
|
||||
};
|
||||
record[1..33].copy_from_slice(id);
|
||||
record[33..].copy_from_slice(&at.to_le_bytes());
|
||||
let mut file = open_claims_for_append(&dir.join(DELIVERY_CLAIMS_FILE), true)?;
|
||||
file.write_all(&record)?;
|
||||
file.sync_data()
|
||||
}
|
||||
|
||||
/// Open a claims file for appending, first dropping a torn trailing record so
|
||||
/// later records stay aligned.
|
||||
fn open_claims_for_append(path: &Path, create: bool) -> io::Result<fs::File> {
|
||||
let file = fs::OpenOptions::new()
|
||||
.create(create)
|
||||
.append(true)
|
||||
.open(path)?;
|
||||
let len = file.metadata()?.len();
|
||||
let torn = len % CLAIM_RECORD_LEN as u64;
|
||||
if torn != 0 {
|
||||
file.set_len(len - torn)?;
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Read appended claims as (delivered, processed). A torn trailing record is ignored.
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn load_delivery_claims(
|
||||
dir: &Path,
|
||||
) -> io::Result<(
|
||||
Vec<(PropagationTransientId, f64)>,
|
||||
Vec<(PropagationTransientId, f64)>,
|
||||
)> {
|
||||
let mut records = Vec::new();
|
||||
for path in [claims_saving(dir), dir.join(DELIVERY_CLAIMS_FILE)] {
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => {
|
||||
let whole = bytes.len() - bytes.len() % CLAIM_RECORD_LEN;
|
||||
records.extend_from_slice(&bytes[..whole]);
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
let (mut delivered, mut processed) = (Vec::new(), Vec::new());
|
||||
for record in records.chunks_exact(CLAIM_RECORD_LEN) {
|
||||
let id: PropagationTransientId = record[1..33].try_into().expect("32 bytes");
|
||||
let at = f64::from_le_bytes(record[33..].try_into().expect("8 bytes"));
|
||||
match record[0] {
|
||||
CLAIM_DELIVERED => delivered.push((id, at)),
|
||||
CLAIM_PROCESSED => processed.push((id, at)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok((delivered, processed))
|
||||
}
|
||||
|
||||
fn claims_saving(dir: &Path) -> std::path::PathBuf {
|
||||
dir.join(format!("{DELIVERY_CLAIMS_FILE}.saving"))
|
||||
}
|
||||
|
||||
/// Set the claims appended so far aside for the snapshot being saved; later
|
||||
/// claims start a new file. Claims set aside by an unfinished save are kept.
|
||||
pub fn rotate_delivery_claims(dir: &Path) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let current = dir.join(DELIVERY_CLAIMS_FILE);
|
||||
let saving = claims_saving(dir);
|
||||
if !saving.exists() {
|
||||
return match fs::rename(¤t, &saving) {
|
||||
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
|
||||
_ => Ok(()),
|
||||
};
|
||||
}
|
||||
let bytes = match fs::read(¤t) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let whole = bytes.len() - bytes.len() % CLAIM_RECORD_LEN;
|
||||
let mut file = open_claims_for_append(&saving, false)?;
|
||||
file.write_all(&bytes[..whole])?;
|
||||
file.sync_data()?;
|
||||
fs::remove_file(current)
|
||||
}
|
||||
|
||||
/// Drop the claims set aside once the caches holding them are saved.
|
||||
pub fn clear_rotated_delivery_claims(dir: &Path) -> io::Result<()> {
|
||||
match fs::remove_file(claims_saving(dir)) {
|
||||
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Counters persisted by Python's `LXMRouter.save_node_stats`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -288,6 +399,20 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn claims_after_a_torn_record_stay_readable() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
append_delivery_claim(tmp.path(), &[1; 32], false, 1.0).unwrap();
|
||||
let path = tmp.path().join(DELIVERY_CLAIMS_FILE);
|
||||
let mut bytes = fs::read(&path).unwrap();
|
||||
bytes.extend_from_slice(&[0xFF; 7]);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
append_delivery_claim(tmp.path(), &[2; 32], true, 2.0).unwrap();
|
||||
let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap();
|
||||
assert_eq!(delivered, vec![([1; 32], 1.0)]);
|
||||
assert_eq!(processed, vec![([2; 32], 2.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamp_costs_roundtrip() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -308,6 +308,18 @@ impl PropagationStore {
|
||||
&self.locally_processed_ids
|
||||
}
|
||||
|
||||
/// Merge a loaded delivered ID, keeping the later timestamp.
|
||||
pub fn restore_locally_delivered(&mut self, id: PropagationTransientId, at: f64) {
|
||||
let entry = self.locally_delivered_ids.entry(id).or_insert(at);
|
||||
*entry = entry.max(at);
|
||||
}
|
||||
|
||||
/// Merge a loaded processed ID, keeping the later timestamp.
|
||||
pub fn restore_locally_processed(&mut self, id: PropagationTransientId, at: f64) {
|
||||
let entry = self.locally_processed_ids.entry(id).or_insert(at);
|
||||
*entry = entry.max(at);
|
||||
}
|
||||
|
||||
pub fn replace_locally_delivered(&mut self, ids: HashMap<PropagationTransientId, f64>) {
|
||||
self.locally_delivered_ids = ids;
|
||||
}
|
||||
|
||||
@@ -330,6 +330,9 @@ pub struct LxmRouter {
|
||||
path_request_times: HashMap<[u8; 16], f64>,
|
||||
/// A slow-path message concluded; outbound processing should run again.
|
||||
outbound_kick: bool,
|
||||
/// Directory given to [`Self::load_state`]; delivered and processed IDs are
|
||||
/// claimed there durably before delivery callbacks run.
|
||||
claims_dir: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
/// Delivered destinations a router holds for the embedder to retain.
|
||||
@@ -373,6 +376,7 @@ pub struct RouterStateSnapshot {
|
||||
local_deliveries: HashMap<PropagationTransientId, f64>,
|
||||
locally_processed: HashMap<PropagationTransientId, f64>,
|
||||
node_stats: crate::persist::PersistedNodeStats,
|
||||
claims_dir: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl RouterStateSnapshot {
|
||||
@@ -389,6 +393,9 @@ impl RouterStateSnapshot {
|
||||
persist::save_local_deliveries(state_dir, &self.local_deliveries)?;
|
||||
persist::save_locally_processed(state_dir, &self.locally_processed)?;
|
||||
persist::save_node_stats(state_dir, &self.node_stats)?;
|
||||
if self.claims_dir.as_deref() == Some(state_dir) {
|
||||
persist::clear_rotated_delivery_claims(state_dir)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -433,6 +440,7 @@ impl LxmRouter {
|
||||
destination_retains: VecDeque::new(),
|
||||
path_request_times: HashMap::new(),
|
||||
outbound_kick: false,
|
||||
claims_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,6 +515,14 @@ impl LxmRouter {
|
||||
self.inbound_resource_tracker.cancel_all_inbound()
|
||||
}
|
||||
|
||||
/// Request cancellation of all active Resources, waiting for adapter queue
|
||||
/// room; the count covers every active Resource (Python `cancel_all_inbound`).
|
||||
pub fn cancel_all_inbound_wait(
|
||||
&self,
|
||||
) -> impl std::future::Future<Output = usize> + Send + 'static {
|
||||
self.inbound_resource_tracker.cancel_all_inbound_wait()
|
||||
}
|
||||
|
||||
/// Queue a message for outbound delivery.
|
||||
///
|
||||
/// Opportunistic messages that exceed the single-packet ceiling are
|
||||
@@ -558,13 +574,17 @@ impl LxmRouter {
|
||||
limit: PLAIN_PACKET_MAX_CONTENT,
|
||||
});
|
||||
}
|
||||
message.transport_encrypted = false;
|
||||
message.transport_encryption = Some("Unencrypted".to_string());
|
||||
} else if content_size > ENCRYPTED_PACKET_MAX_CONTENT {
|
||||
message.method = DeliveryMethod::Direct;
|
||||
}
|
||||
}
|
||||
|
||||
let destination_type = if self.is_plain_destination(&message.destination_hash()) {
|
||||
rns_wire::flags::DestinationType::Plain
|
||||
} else {
|
||||
rns_wire::flags::DestinationType::Single
|
||||
};
|
||||
message.determine_transport_encryption(destination_type);
|
||||
message.state = MessageState::Outbound;
|
||||
self.pending_outbound.push(message);
|
||||
Ok(())
|
||||
@@ -1021,26 +1041,28 @@ impl LxmRouter {
|
||||
self.ticket_store.inbound()
|
||||
}
|
||||
|
||||
/// Remove a matching message from the router's outbound or deferred-stamp queue.
|
||||
/// Returns `true` when found, regardless of its prior state. A matching active
|
||||
/// stamp worker receives a cooperative cancellation request. The embedding
|
||||
/// runtime must separately cancel any Link/Resource work it already owns.
|
||||
/// Cancel a message in the router's outbound or deferred-stamp queue
|
||||
/// (Python `cancel_outbound`): it becomes [`MessageState::Cancelled`] whatever
|
||||
/// its prior state, leaves the queue and its failure callback runs. Returns
|
||||
/// `true` when found. A matching active stamp worker receives a cooperative
|
||||
/// cancellation request. The embedding runtime must separately cancel any
|
||||
/// Link/Resource work it already owns.
|
||||
pub fn cancel_outbound(&mut self, message_hash: &[u8; 32]) -> bool {
|
||||
if let Some(pos) = self
|
||||
.pending_outbound
|
||||
.iter()
|
||||
.position(|m| &m.message_id() == message_hash)
|
||||
{
|
||||
let msg = &mut self.pending_outbound[pos];
|
||||
msg.cancel();
|
||||
self.pending_outbound.remove(pos);
|
||||
let mut msg = self.pending_outbound.remove(pos);
|
||||
msg.state = MessageState::Cancelled;
|
||||
msg.notify_failed();
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(msg) = self.pending_deferred_stamps.remove(message_hash) {
|
||||
if let Ok(mut message) = msg.finalize(None) {
|
||||
message.cancel();
|
||||
}
|
||||
let mut message = msg.into_unstamped();
|
||||
message.state = MessageState::Cancelled;
|
||||
message.notify_failed();
|
||||
let active_matches = self
|
||||
.active_deferred_stamp
|
||||
.as_ref()
|
||||
@@ -1223,13 +1245,34 @@ impl LxmRouter {
|
||||
if !allow_duplicate && self.propagation_store.is_locally_delivered(&message_id) {
|
||||
return false;
|
||||
}
|
||||
self.propagation_store.mark_locally_delivered(message_id);
|
||||
self.claim_locally_delivered(message_id);
|
||||
if let Some(ref callback) = self.delivery_callback {
|
||||
callback(message);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Record a delivered ID, durably first when state is loaded from a directory
|
||||
/// (Python `conditionally_claim_delivered`). A failed write is logged and the
|
||||
/// message still counts as new, as Python's store does.
|
||||
fn claim_locally_delivered(&mut self, id: PropagationTransientId) {
|
||||
self.propagation_store.mark_locally_delivered(id);
|
||||
self.append_claim(&id, false);
|
||||
}
|
||||
|
||||
fn claim_locally_processed(&mut self, id: PropagationTransientId) {
|
||||
self.propagation_store.mark_locally_processed(id);
|
||||
self.append_claim(&id, true);
|
||||
}
|
||||
|
||||
fn append_claim(&self, id: &PropagationTransientId, processed: bool) {
|
||||
if let Some(dir) = &self.claims_dir
|
||||
&& let Err(error) = crate::persist::append_delivery_claim(dir, id, processed, now_f64())
|
||||
{
|
||||
tracing::error!(%error, "could not claim transient id in the router state directory");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reserve a message ID before local disk/DB work. An existing reservation
|
||||
/// for that ID returns `None`; this does not check the delivered cache or
|
||||
/// authenticate the message. No ticket learning, dedupe publication or callback
|
||||
@@ -1280,15 +1323,12 @@ impl LxmRouter {
|
||||
{
|
||||
self.learn_ticket_from_inbound(verified);
|
||||
}
|
||||
self.propagation_store
|
||||
.mark_locally_delivered(receipt.record().scope.transient_id);
|
||||
self.propagation_store
|
||||
.mark_locally_processed(receipt.record().scope.transient_id);
|
||||
self.claim_locally_delivered(receipt.record().scope.transient_id);
|
||||
self.claim_locally_processed(receipt.record().scope.transient_id);
|
||||
let new_message = !self
|
||||
.propagation_store
|
||||
.is_locally_delivered(&message.message_id());
|
||||
self.propagation_store
|
||||
.mark_locally_delivered(message.message_id());
|
||||
self.claim_locally_delivered(message.message_id());
|
||||
if new_message
|
||||
&& receipt.record().disposition == crate::admission::DurableDisposition::Committed
|
||||
{
|
||||
@@ -1342,14 +1382,14 @@ impl LxmRouter {
|
||||
{
|
||||
return Ok(PaperIngest::Duplicate);
|
||||
}
|
||||
self.propagation_store.mark_locally_processed(transient_id);
|
||||
self.claim_locally_processed(transient_id);
|
||||
|
||||
let mut packed = destination_hash.to_vec();
|
||||
packed.extend_from_slice(&decrypt_fn(&encrypted)?);
|
||||
// Python records the transient id as delivered even when the decrypted
|
||||
// bytes do not unpack (LXMRouter.py:2858-2864).
|
||||
let unpacked = LxMessage::unpack(&packed);
|
||||
self.propagation_store.mark_locally_delivered(transient_id);
|
||||
self.claim_locally_delivered(transient_id);
|
||||
let mut message = unpacked?;
|
||||
message.method = DeliveryMethod::Propagated;
|
||||
message.representation = DeliveryRepresentation::Paper;
|
||||
@@ -1388,13 +1428,22 @@ impl LxmRouter {
|
||||
.replace_locally_delivered(persist::load_local_deliveries(state_dir)?);
|
||||
self.propagation_store
|
||||
.replace_locally_processed(persist::load_locally_processed(state_dir)?);
|
||||
let (delivered, processed) = persist::load_delivery_claims(state_dir)?;
|
||||
for (id, at) in delivered {
|
||||
self.propagation_store.restore_locally_delivered(id, at);
|
||||
}
|
||||
for (id, at) in processed {
|
||||
self.propagation_store.restore_locally_processed(id, at);
|
||||
}
|
||||
self.claims_dir = Some(state_dir.to_path_buf());
|
||||
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).
|
||||
// Python cleans transient IDs, tickets and stamp costs at load (LXMRouter.py:292-297).
|
||||
let now = now_f64();
|
||||
self.propagation_store.clean_transient_caches(now);
|
||||
self.ticket_store.cull(now);
|
||||
self.outbound_stamp_costs
|
||||
.retain(|_, e| now - e.recorded_at < STAMP_COST_EXPIRY as f64);
|
||||
@@ -1406,7 +1455,13 @@ impl LxmRouter {
|
||||
/// release the lock, and perform persistence through
|
||||
/// [`RouterStateSnapshot::save_state`].
|
||||
pub fn state_snapshot(&self) -> RouterStateSnapshot {
|
||||
let claims_dir = self.claims_dir.as_ref().filter(|dir| {
|
||||
crate::persist::rotate_delivery_claims(dir)
|
||||
.inspect_err(|error| tracing::warn!(%error, "could not rotate delivery claims"))
|
||||
.is_ok()
|
||||
});
|
||||
RouterStateSnapshot {
|
||||
claims_dir: claims_dir.cloned(),
|
||||
outbound_stamp_costs: self.outbound_stamp_costs.clone(),
|
||||
tickets: crate::persist::TicketPersistenceSnapshot::capture(
|
||||
self.ticket_store.snapshot(),
|
||||
@@ -2620,6 +2675,10 @@ impl LxmRouter {
|
||||
{
|
||||
self.rotate_peers();
|
||||
}
|
||||
if self.processing_count.is_multiple_of(JOB_STAMPCOST_INTERVAL) {
|
||||
self.cull_stamp_costs();
|
||||
self.ticket_store.cull(now_f64());
|
||||
}
|
||||
}
|
||||
|
||||
/// Get summary statistics.
|
||||
|
||||
@@ -162,10 +162,15 @@ impl TicketStore {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(ticket) = self.inbound.iter().find(|ticket| {
|
||||
ticket.destination_hash == destination_hash
|
||||
&& ticket.expires - now > TICKET_RENEW as f64
|
||||
}) {
|
||||
if let Some(ticket) = self
|
||||
.inbound
|
||||
.iter()
|
||||
.filter(|ticket| {
|
||||
ticket.destination_hash == destination_hash
|
||||
&& ticket.expires - now > TICKET_RENEW as f64
|
||||
})
|
||||
.max_by(|a, b| a.expires.total_cmp(&b.expires))
|
||||
{
|
||||
return Some(ticket.clone());
|
||||
}
|
||||
|
||||
|
||||
@@ -1089,9 +1089,11 @@ fn link_snapshot_state(
|
||||
/// Python `lxmf_delivery()` receive state: the delivery method, and Curve25519
|
||||
/// transport encryption for SINGLE and LINK destinations (LXMRouter.py:2174,2218-2226).
|
||||
fn mark_received(msg: &mut LxMessage, method: DeliveryMethod) {
|
||||
msg.method = method;
|
||||
msg.transport_encrypted = true;
|
||||
msg.transport_encryption = Some(rns_identity::identity::CURVE.to_string());
|
||||
let destination_type = match method {
|
||||
DeliveryMethod::Direct => rns_wire::flags::DestinationType::Link,
|
||||
_ => rns_wire::flags::DestinationType::Single,
|
||||
};
|
||||
msg.record_delivery(Some(destination_type), None, Some(method), None);
|
||||
}
|
||||
|
||||
/// Write the stored propagated message as Python's `write_to_directory()` file,
|
||||
@@ -6218,14 +6220,7 @@ pub(crate) async fn main() {
|
||||
}
|
||||
|
||||
let shutdown = rns_runtime::lifecycle::ShutdownSignal::new();
|
||||
let shutdown_clone = shutdown.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Ok(()) = tokio::signal::ctrl_c().await {
|
||||
tracing::info!("Received shutdown signal");
|
||||
shutdown_clone.trigger();
|
||||
}
|
||||
});
|
||||
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone());
|
||||
|
||||
let rns_config_dir_str = rns_config_dir.to_string_lossy().to_string();
|
||||
let is_foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
|
||||
Reference in new issue
Block a user