Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/skip-wot-thresholds-none.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

refactor(relay): skip WoT thresholds vec allocation when distance is None (#1264)
79 changes: 79 additions & 0 deletions crates/nostream-relay/src/handlers/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,10 @@ pub fn required_difficulty(
let computed =
adaptive_pow::compute_difficulty(&config, events_per_second).unwrap_or(adaptive.floor_bits);

if distance.is_none() {
return computed;
}

let thresholds: Option<Vec<WotPowThreshold>> =
adaptive.wot_thresholds.as_ref().map(|thresholds| {
thresholds
Expand Down Expand Up @@ -654,3 +658,78 @@ pub const ALL_RELAYS_TAG: &str = ALL_RELAYS;

/// `EventKinds.REACTION`, re-exported for the tests.
pub const REACTION: Kind = REACTION_KIND;

#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]

use nostream_config::settings::{AdaptivePowSettings, EventLimits, WotPowThreshold};

use super::*;

#[test]
fn required_difficulty_skips_thresholds_when_distance_is_none() {
let limits = EventLimits {
pow: Some(AdaptivePowSettings {
enabled: true,
floor_bits: 16,
ceiling_bits: 32,
target_events_per_second: 50.0,
period_ms: 60_000,
wot_thresholds: Some(vec![
WotPowThreshold {
max_distance: 1,
difficulty_factor: 0.0,
},
WotPowThreshold {
max_distance: 2,
difficulty_factor: 0.5,
},
]),
}),
..Default::default()
};

// When distance is None, the computed difficulty is returned without WoT discount.
assert_eq!(required_difficulty(Some(&limits), 0.0, None), 16);

// When distance is provided, eligible thresholds are applied.
assert_eq!(required_difficulty(Some(&limits), 0.0, Some(1)), 0);
assert_eq!(required_difficulty(Some(&limits), 0.0, Some(2)), 8);
assert_eq!(required_difficulty(Some(&limits), 0.0, Some(3)), 16);
}

#[test]
fn required_difficulty_handles_empty_or_absent_thresholds() {
let no_thresholds = EventLimits {
pow: Some(AdaptivePowSettings {
enabled: true,
floor_bits: 20,
ceiling_bits: 32,
target_events_per_second: 50.0,
period_ms: 60_000,
wot_thresholds: None,
}),
..Default::default()
};
assert_eq!(required_difficulty(Some(&no_thresholds), 0.0, None), 20);
assert_eq!(required_difficulty(Some(&no_thresholds), 0.0, Some(1)), 20);

let empty_thresholds = EventLimits {
pow: Some(AdaptivePowSettings {
enabled: true,
floor_bits: 20,
ceiling_bits: 32,
target_events_per_second: 50.0,
period_ms: 60_000,
wot_thresholds: Some(Vec::new()),
}),
..Default::default()
};
assert_eq!(required_difficulty(Some(&empty_thresholds), 0.0, None), 20);
assert_eq!(
required_difficulty(Some(&empty_thresholds), 0.0, Some(1)),
20
);
}
}
Loading