use icenet_core::{NodeId, ServiceId}; use icenet_guard::{Context, Guard, Limits, Verdict}; fn limits(rate: u64, burst: u64) -> Limits { Limits { rate_per_second: rate, burst, replay_window: 64, ..Limits::default() } } fn context(peer: u64, sequence: u64, now_ms: u64) -> Context { Context { authenticated: true, peer: NodeId(peer), service: ServiceId(7), payload_bytes: 1, sequence, now_ms, queue_depth: 0, } } #[test] fn burst_is_allowed_then_requests_are_limited_until_refill() { let mut guard = Guard::new([ServiceId(7)], limits(2, 2)); assert_eq!(guard.check(context(1, 1, 0)), Verdict::Permit); assert_eq!(guard.check(context(1, 2, 0)), Verdict::Permit); assert_eq!(guard.check(context(1, 3, 0)), Verdict::Deny("rate_limited")); assert_eq!(guard.check(context(1, 4, 500)), Verdict::Permit); assert_eq!( guard.check(context(1, 5, 500)), Verdict::Deny("rate_limited") ); } #[test] fn rate_buckets_are_per_peer() { let mut guard = Guard::new([ServiceId(7)], limits(1, 1)); assert_eq!(guard.check(context(1, 1, 0)), Verdict::Permit); assert_eq!(guard.check(context(1, 2, 0)), Verdict::Deny("rate_limited")); assert_eq!(guard.check(context(2, 1, 0)), Verdict::Permit); } #[test] fn zero_rate_disables_limiting() { let mut guard = Guard::new([ServiceId(7)], limits(0, 0)); for sequence in 0..50 { assert_eq!(guard.check(context(1, sequence, 0)), Verdict::Permit); } }