lxmd: keep one processed store and bound the announce backlog

This commit is contained in:
DeFiDude committed 2026-11-11 09:25:42 -07:00
1 parent a5ad58e999
commit ba4202a18a
5 files changed
+863 -119

No files matched your search

+109 -4
View File
@@ -43,6 +43,8 @@ struct UserDeletedMessage {
struct Inner {
journal: PathBuf,
bodies: PathBuf,
/// The only directory journaled bodies may be moved in from.
legacy_bodies: Option<PathBuf>,
committed: HashMap<AdmissionScope, AdmissionCommit>,
deleted: HashMap<([u8; 16], [u8; 32]), UserDeletedMessage>,
}
@@ -85,6 +87,24 @@ impl FileAdmissionStore {
/// Parent is the daemon's already configured state directory. A strict
/// outside bootstrap receipt witnesses creation of journal/body directories.
pub fn open(state_dir: &Path, bodies: &Path) -> Result<Self, AdmissionError> {
Self::open_inner(state_dir, bodies, None)
}
/// [`Self::open`] for a store whose bodies used to live in `legacy_bodies`:
/// a journaled body still there is moved into `bodies`.
pub fn open_moving_bodies_from(
state_dir: &Path,
bodies: &Path,
legacy_bodies: &Path,
) -> Result<Self, AdmissionError> {
Self::open_inner(state_dir, bodies, Some(legacy_bodies))
}
fn open_inner(
state_dir: &Path,
bodies: &Path,
legacy_bodies: Option<&Path>,
) -> Result<Self, AdmissionError> {
let journal = state_dir.join("download-admission-v1");
let parent = state_dir
.ancestors()
@@ -103,6 +123,7 @@ impl FileAdmissionStore {
let mut inner = Inner {
journal,
bodies: bodies.to_owned(),
legacy_bodies: legacy_bodies.map(Path::to_owned),
committed: HashMap::new(),
deleted: HashMap::new(),
};
@@ -265,7 +286,13 @@ impl FileAdmissionStore {
.committed
.values()
.filter(|c| !c.hook_completed)
.filter_map(|c| Some((c.intent.hook_event?, c.intent.body_path.clone()?)))
.filter_map(|c| {
c.intent.body_path.as_ref()?;
Some((
c.intent.hook_event?,
inner.body_path(&c.intent.record.message_id),
))
})
.collect()
}
@@ -413,6 +440,9 @@ impl DurableAdmissionBackend for FileAdmissionCommit {
}
impl Inner {
fn body_path(&self, message_id: &[u8; 32]) -> PathBuf {
self.bodies.join(format!("{}.lxm", hex::encode(message_id)))
}
fn intent_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.intent", hex::encode(id)))
}
@@ -431,12 +461,21 @@ impl Inner {
return Err(other("message was explicitly deleted"));
}
if let Some(path) = &intent.body_path {
if path.parent() != Some(self.bodies.as_path())
|| path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
if path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
{
return Err(other("admission archive path escapes configured inbox"));
}
// A journal written before the bodies moved names the old directory.
let journaled = path;
let path = &self.body_path(&intent.record.message_id);
if !path.exists()
&& self.legacy_bodies.is_some()
&& journaled.parent() == self.legacy_bodies.as_deref()
&& journaled.exists()
{
std::fs::rename(journaled, path).map_err(other)?;
}
let body = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
if Some(rns_crypto::sha::full_hash(&body)) != intent.record.stored_message_wire_hash {
return Err(other("admission archive content mismatch"));
@@ -606,4 +645,70 @@ mod tests {
.unwrap();
assert!(recovered.pending_hooks().is_empty());
}
/// A store whose one committed body sits in `<temp>/messages`.
fn store_with_body_in_inbox() -> (tempfile::TempDir, PathBuf, String, AdmissionScope, Vec<u8>) {
let temp = tempfile::tempdir().unwrap();
let inbox = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &inbox).unwrap();
let message = crate::message::test_message(
[1; 16],
[2; 16],
"",
"body",
crate::constants::DeliveryMethod::Propagated,
);
let scope = AdmissionScope {
identity: [3; 16],
node: [4; 16],
transient_id: [5; 32],
};
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: [0; 32],
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
DurableAdmissionReceipt::commit(store.prepare(
record,
Bytes::copy_from_slice(message.wire_bytes()),
true,
))
.unwrap();
drop(store);
let name = format!("{}.lxm", hex::encode(message.message_id()));
assert!(inbox.join(&name).exists());
(temp, inbox, name, scope, message.wire_bytes().to_vec())
}
#[test]
fn bodies_journaled_in_the_inbox_move_to_a_new_bodies_directory_on_open() {
let (temp, inbox, name, scope, wire) = store_with_body_in_inbox();
let bodies = temp.path().join("bodies");
let reopened =
FileAdmissionStore::open_moving_bodies_from(temp.path(), &bodies, &inbox).unwrap();
assert!(!inbox.join(&name).exists());
assert_eq!(std::fs::read(bodies.join(&name)).unwrap(), wire);
assert_eq!(
reopened.haves(scope.identity, scope.node, 101),
vec![scope.transient_id.to_vec()]
);
assert_eq!(reopened.pending_hooks()[0].1, bodies.join(&name));
}
#[test]
fn bodies_are_moved_in_only_from_the_named_legacy_directory() {
let (temp, inbox, name, _, _) = store_with_body_in_inbox();
let bodies = temp.path().join("bodies");
let elsewhere = temp.path().join("elsewhere");
for _ in [
FileAdmissionStore::open(temp.path(), &bodies),
FileAdmissionStore::open_moving_bodies_from(temp.path(), &bodies, &elsewhere),
] {
assert!(inbox.join(&name).exists());
assert!(!bodies.join(&name).exists());
}
}
}
+66 -17
View File
@@ -49,6 +49,43 @@ pub enum CompressionSupport {
Supported,
}
/// A per-transfer or per-sync limit as Python holds it: lxmd's built-in defaults
/// are ints, configured values come from `as_float` (lxmd.py:165-184@1.3.0),
/// and the announce packs whichever it has (LXMRouter.py:394-395).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PnLimit {
Int(u64),
Float(f64),
}
impl PnLimit {
pub fn as_f64(self) -> f64 {
match self {
Self::Int(n) => n as f64,
Self::Float(f) => f,
}
}
fn to_value(self) -> rmpv::Value {
match self {
Self::Int(n) => rmpv::Value::from(n),
Self::Float(f) => rmpv::Value::F64(f),
}
}
}
impl From<u64> for PnLimit {
fn from(n: u64) -> Self {
Self::Int(n)
}
}
impl From<f64> for PnLimit {
fn from(f: f64) -> Self {
Self::Float(f)
}
}
/// Parsed propagation-node announce data.
///
/// Wire layout is an 8-element msgpack array:
@@ -69,9 +106,9 @@ pub struct PropagationNodeAnnounceData {
/// True when the node is actively serving propagation.
pub node_state: bool,
/// Per-transfer limit in decimal kilobytes (1 kB = 1000 bytes).
pub transfer_limit: u64,
pub transfer_limit: PnLimit,
/// Per-sync limit in decimal kilobytes (1 kB = 1000 bytes).
pub sync_limit: u64,
pub sync_limit: PnLimit,
/// Propagation stamp cost, flexibility and peering cost as announced.
pub stamp_cost: f64,
pub stamp_flex: f64,
@@ -87,8 +124,8 @@ pub struct PropagationNodeAnnounceData {
impl PropagationNodeAnnounceData {
pub fn new(
node_state: bool,
transfer_limit: u64,
sync_limit: u64,
transfer_limit: impl Into<PnLimit>,
sync_limit: impl Into<PnLimit>,
stamp_cost: f64,
stamp_flex: f64,
peering_cost: f64,
@@ -100,8 +137,8 @@ impl PropagationNodeAnnounceData {
.unwrap_or_default()
.as_secs() as i64,
node_state,
transfer_limit,
sync_limit,
transfer_limit: transfer_limit.into(),
sync_limit: sync_limit.into(),
stamp_cost,
stamp_flex,
peering_cost,
@@ -158,8 +195,8 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
Value::Boolean(false),
Value::from(data.timebase),
Value::Boolean(data.node_state),
Value::from(data.transfer_limit),
Value::from(data.sync_limit),
data.transfer_limit.to_value(),
data.sync_limit.to_value(),
ceil_costs,
metadata,
stamp_costs,
@@ -414,7 +451,7 @@ pub fn pn_announce_data_is_valid(data: &[u8]) -> bool {
/// Parse propagation-node announce data that [`pn_announce_data_is_valid`] accepts.
///
/// Limits are extracted with `int()` as the Python announce handler does.
/// Limits keep their wire form ([`PnLimit`]); the announce handler reads them with `int()`.
/// Costs come from the fractional slot 7 when present, else from `int()` of
/// slot 5, as the handler takes them. Limits below zero become zero; announces with a
/// non-finite cost are refused. String [`PN_META_IMPL_NAME`] and
@@ -425,9 +462,18 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
let int_at = |index: usize| python_int(&python_index(&value, index)?);
let timebase = int_at(1)?.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
let node_state = python_bool_state(&python_index(&value, 2)?)?;
let limit = |raw: i128| raw.clamp(0, i128::from(u64::MAX)) as u64;
let transfer_limit = limit(int_at(3)?);
let sync_limit = limit(int_at(4)?);
// A float is kept raw, as LXMRouter's sync autopeer reads it (LXMRouter.py:2700).
let limit_at = |index: usize| -> Option<PnLimit> {
let raw = python_index(&value, index)?;
let int = python_int(&raw)?;
Some(match raw {
rmpv::Value::F32(f) => PnLimit::Float(f64::from(f).max(0.0)),
rmpv::Value::F64(f) => PnLimit::Float(f.max(0.0)),
_ => PnLimit::Int(int.clamp(0, i128::from(u64::MAX)) as u64),
})
};
let transfer_limit = limit_at(3)?;
let sync_limit = limit_at(4)?;
let ceil_costs = python_index(&value, 5)?;
for index in 0..3 {
python_int(&python_index(&ceil_costs, index)?)?;
@@ -1015,8 +1061,11 @@ mod tests {
let parsed = parse_pn_announce_data(&packed).unwrap();
assert!(!parsed.legacy);
assert!(parsed.node_state);
assert_eq!(parsed.transfer_limit, PROPAGATION_LIMIT as u64);
assert_eq!(parsed.sync_limit, SYNC_LIMIT as u64);
assert_eq!(
parsed.transfer_limit,
PnLimit::Int(PROPAGATION_LIMIT as u64)
);
assert_eq!(parsed.sync_limit, PnLimit::Int(SYNC_LIMIT as u64));
assert_eq!(parsed.stamp_cost, PROPAGATION_COST);
assert_eq!(parsed.stamp_flex, PROPAGATION_COST_FLEX);
assert_eq!(parsed.peering_cost, PEERING_COST);
@@ -1044,8 +1093,8 @@ mod tests {
let parsed = parse_pn_announce_data(&packed).unwrap();
assert!(parsed.node_state);
assert_eq!(parsed.transfer_limit, 10240);
assert_eq!(parsed.sync_limit, 10240);
assert_eq!(parsed.transfer_limit, PnLimit::Float(10240.0));
assert_eq!(parsed.sync_limit, PnLimit::Float(10240.0));
assert_eq!(parsed.stamp_cost, 16.0);
}
@@ -1097,7 +1146,7 @@ mod tests {
// Python accepts these (int() succeeds); the typed values are clamped.
let negative = parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).unwrap();
assert_eq!(negative.transfer_limit, 0);
assert_eq!(negative.transfer_limit, PnLimit::Int(0));
let large = parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).unwrap();
assert_eq!(large.stamp_cost, 256.0);
let fractional =
+12 -2
View File
@@ -339,6 +339,16 @@ pub struct LxmRouter {
claims_dir: Option<std::path::PathBuf>,
}
/// `RouterConfig` holds limits as f64: a whole number announces as Python's int
/// default, anything else as the float LXMRouter was given.
fn router_limit(limit_kb: f64) -> crate::handlers::PnLimit {
if limit_kb.fract() == 0.0 && (0.0..=u64::MAX as f64).contains(&limit_kb) {
crate::handlers::PnLimit::Int(limit_kb as u64)
} else {
crate::handlers::PnLimit::Float(limit_kb)
}
}
/// Delivered destinations a router holds for the embedder to retain.
const MAX_PENDING_RETAINS: usize = 256;
@@ -1780,8 +1790,8 @@ impl LxmRouter {
let mut data = crate::handlers::PropagationNodeAnnounceData::new(
self.config.propagation_enabled && !self.config.ext.from_static_only,
self.config.propagation_limit_kb as u64,
self.config.sync_limit_kb as u64,
router_limit(self.config.propagation_limit_kb),
router_limit(self.config.sync_limit_kb),
self.config.propagation_stamp_cost,
self.config.propagation_stamp_flex,
self.config.ext.peering_cost,
File diff suppressed because it is too large. Load diff
+42 -31
View File
@@ -3,6 +3,7 @@
//! Python reference: LXMF/Utilities/lxmd.py.
use lxmf_core::constants::*;
pub use lxmf_core::handlers::PnLimit;
use lxmf_core::propagation_admission::{
PN_DEFAULT_MAX_INBOUND_SYNCS, PN_MIN_MAX_INBOUND_SYNCS, PnInboundAdmissionConfig,
};
@@ -32,8 +33,8 @@ pub struct PythonLxmdConfig {
pub max_inbound_syncs: i64,
pub node_announce_interval: Option<i64>,
pub message_storage_limit: f64,
pub propagation_transfer_max_accepted_size: f64,
pub propagation_sync_max_accepted_size: f64,
pub propagation_transfer_max_accepted_size: PnLimit,
pub propagation_sync_max_accepted_size: PnLimit,
pub propagation_stamp_cost_target: f64,
pub propagation_stamp_cost_flexibility: f64,
pub peering_cost: f64,
@@ -148,13 +149,8 @@ impl PythonLxmdConfig {
"propagation",
"propagation_transfer_max_accepted_size",
)?;
let propagation_transfer_max_accepted_size = get_float_or_floor(
propagation,
"propagation",
"propagation_message_max_accepted_size",
256.0,
0.38,
)?;
let propagation_transfer_max_accepted_size =
get_limit(propagation, "propagation_message_max_accepted_size", 256)?;
let peer_stamp_cost = generated_cost(
floored_cost(lxmf, "lxmf", "stamp_cost", 1.0, 12.0)?,
@@ -269,12 +265,10 @@ impl PythonLxmdConfig {
0.005,
)?,
propagation_transfer_max_accepted_size,
propagation_sync_max_accepted_size: get_float_or_floor(
propagation_sync_max_accepted_size: get_limit(
propagation,
"propagation",
"propagation_sync_max_accepted_size",
256.0 * 40.0,
0.38,
256 * 40,
)?,
propagation_stamp_cost_target,
propagation_stamp_cost_flexibility,
@@ -373,6 +367,19 @@ fn get_float_or_floor(
Ok(get_cost(section, section_name, key)?.map_or(default, |value| value.max(floor)))
}
/// lxmd's size limits: an int default, or the configured `as_float` value floored at 0.38.
fn get_limit(
section: Option<&ConfigSection>,
key: &'static str,
default: u64,
) -> Result<PnLimit, DaemonConfigError> {
Ok(
get_cost(section, "propagation", key)?.map_or(PnLimit::Int(default), |value| {
PnLimit::Float(value.max(0.38))
}),
)
}
fn get_list(section: Option<&ConfigSection>, key: &str) -> Vec<String> {
section
.and_then(|sec| sec.get_list(key))
@@ -421,8 +428,8 @@ pub struct DaemonConfig {
pub sequential_pn_stamp_validation: bool,
pub static_peers_bypass_sequential: bool,
pub max_inbound_syncs: usize,
pub propagation_limit_kb: f64,
pub sync_limit_kb: f64,
pub propagation_limit_kb: PnLimit,
pub sync_limit_kb: PnLimit,
pub on_inbound_command: Option<String>,
pub node_announce_at_start: bool,
pub node_announce_interval: Option<u64>,
@@ -460,8 +467,8 @@ impl Default for DaemonConfig {
sequential_pn_stamp_validation: true,
static_peers_bypass_sequential: true,
max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS,
propagation_limit_kb: PROPAGATION_LIMIT as f64,
sync_limit_kb: SYNC_LIMIT as f64,
propagation_limit_kb: PnLimit::Int(PROPAGATION_LIMIT as u64),
sync_limit_kb: PnLimit::Int(SYNC_LIMIT as u64),
on_inbound_command: None,
node_announce_at_start: false,
node_announce_interval: None,
@@ -487,9 +494,9 @@ impl DaemonConfig {
propagation_enabled: self.propagation_enabled,
autopeer: self.autopeer,
max_peers: self.max_peers,
propagation_limit_kb: self.propagation_limit_kb,
propagation_limit_kb: self.propagation_limit_kb.as_f64(),
delivery_limit_kb: self.delivery_transfer_max_accepted_size,
sync_limit_kb: self.sync_limit_kb,
sync_limit_kb: self.sync_limit_kb.as_f64(),
propagation_stamp_cost: self.propagation_stamp_cost,
propagation_stamp_flex: self.propagation_stamp_flex,
stamp_cost: self.stamp_cost,
@@ -587,13 +594,15 @@ impl DaemonConfig {
&& get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none()
&& let Some(limit) = sec.get_uint("propagation_limit")
{
dc.propagation_limit_kb = limit as f64;
dc.propagation_limit_kb = PnLimit::Int(limit);
}
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
// LXMRouter raises the per-sync limit to the per-transfer limit.
dc.sync_limit_kb = dc.sync_limit_kb.max(dc.propagation_limit_kb);
if dc.sync_limit_kb.as_f64() < dc.propagation_limit_kb.as_f64() {
dc.sync_limit_kb = dc.propagation_limit_kb;
}
if let Some(sec) = config.section("control") {
if !dc.auth_required {
@@ -852,8 +861,8 @@ mod tests {
dc.to_inbound_admission_config(),
PnInboundAdmissionConfig::default()
);
assert_eq!(dc.propagation_limit_kb, 256.0);
assert_eq!(dc.sync_limit_kb, 10_240.0);
assert_eq!(dc.propagation_limit_kb.as_f64(), 256.0);
assert_eq!(dc.sync_limit_kb.as_f64(), 10_240.0);
assert!(!dc.node_announce_at_start);
assert_eq!(dc.node_announce_interval, None);
assert_eq!(dc.message_storage_limit, Some(500_000_000));
@@ -883,8 +892,8 @@ mod tests {
assert_eq!(py.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS as i64);
assert_eq!(py.node_announce_interval, None);
assert_eq!(py.message_storage_limit, 500.0);
assert_eq!(py.propagation_transfer_max_accepted_size, 256.0);
assert_eq!(py.propagation_sync_max_accepted_size, 10240.0);
assert_eq!(py.propagation_transfer_max_accepted_size.as_f64(), 256.0);
assert_eq!(py.propagation_sync_max_accepted_size.as_f64(), 10240.0);
assert_eq!(py.propagation_stamp_cost_target, 16.0);
assert_eq!(py.propagation_stamp_cost_flexibility, 3.0);
assert_eq!(py.peering_cost, 18.0);
@@ -934,8 +943,8 @@ loglevel = 6
assert_eq!(py.peer_stamp_cost, 1.0);
assert_eq!(py.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(py.message_storage_limit, 0.005);
assert_eq!(py.propagation_transfer_max_accepted_size, 0.38);
assert_eq!(py.propagation_sync_max_accepted_size, 0.38);
assert_eq!(py.propagation_transfer_max_accepted_size.as_f64(), 0.38);
assert_eq!(py.propagation_sync_max_accepted_size.as_f64(), 0.38);
assert_eq!(py.propagation_stamp_cost_target, 13.0);
assert_eq!(py.propagation_stamp_cost_flexibility, 0.0);
assert_eq!(py.peering_cost, 0.0);
@@ -967,7 +976,8 @@ propagation_transfer_max_accepted_size = 12
let py = PythonLxmdConfig::from_config(&config).unwrap();
assert_eq!(
py.propagation_transfer_max_accepted_size, 256.0,
py.propagation_transfer_max_accepted_size.as_f64(),
256.0,
"Python 0.9.6 ignores legacy propagation_transfer_max_accepted_size unless the newer key is set"
);
}
@@ -982,7 +992,8 @@ propagation_transfer_max_accepted_size = 12
let dc = DaemonConfig::from_config(&config).unwrap();
assert_eq!(
dc.propagation_limit_kb, 256.0,
dc.propagation_limit_kb.as_f64(),
256.0,
"DaemonConfig should match Python 0.9.6 handling of legacy propagation_transfer_max_accepted_size"
);
}
@@ -1074,8 +1085,8 @@ from_static_only = yes
assert!(dc.node_announce_at_start);
assert_eq!(dc.node_announce_interval, Some(120));
assert_eq!(dc.message_storage_limit, Some(5_000));
assert_eq!(dc.propagation_limit_kb, 0.38);
assert_eq!(dc.sync_limit_kb, 0.38);
assert_eq!(dc.propagation_limit_kb.as_f64(), 0.38);
assert_eq!(dc.sync_limit_kb.as_f64(), 0.38);
assert_eq!(dc.propagation_stamp_cost, 13.0);
assert_eq!(dc.propagation_stamp_flex, 0.0);
assert_eq!(dc.peering_cost, 0.0);