Initial import: ICE-NET research docs and Rust workspace (v0.4)
Some checks failed
rust-ci / checks (push) Has been cancelled
Some checks failed
rust-ci / checks (push) Has been cancelled
- Rust workspace: 7 library crates, icenetd CLI, icenet-city (Slint GUI) - Sim: fix false Delivered after a route cut, derive traffic class from payload size, per-link airtime slots (link capacity, queueing) - Docs: single docs/STATUS.md for all figures, remove v0.2/egui leftovers, drop unimplemented seed claims, uncheck store-and-forward - License: LGPL-3.0-or-later (LICENSE, LICENSES/GPL-3.0.txt)
This commit is contained in:
commit
2e61688eb3
141 changed files with 13993 additions and 0 deletions
7
workspace/crates/icenet-core/Cargo.toml
Normal file
7
workspace/crates/icenet-core/Cargo.toml
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "icenet-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
106
workspace/crates/icenet-core/src/lib.rs
Normal file
106
workspace/crates/icenet-core/src/lib.rs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
//! Shared, platform-independent types for ICE-NET prototypes.
|
||||
//!
|
||||
//! These numeric node IDs are simulation placeholders, not cryptographic IDs.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
/// An ICE-NET node identifier in the current prototype.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
||||
pub struct NodeId(pub u64);
|
||||
|
||||
/// An ICE-NET application service identifier; not a TCP/UDP port.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
||||
pub struct ServiceId(pub u64);
|
||||
|
||||
/// User-facing classes of traffic.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum TrafficClass {
|
||||
/// Tiny announcements and routing control messages.
|
||||
Control,
|
||||
/// Small user messages that may use a slow radio link.
|
||||
Text,
|
||||
/// Bulk transfers, including photos and files.
|
||||
Bulk,
|
||||
}
|
||||
|
||||
impl TrafficClass {
|
||||
/// Largest payload that may travel as [`TrafficClass::Control`].
|
||||
pub const CONTROL_MAX_BYTES: u64 = 256;
|
||||
/// Largest payload that may travel as [`TrafficClass::Text`].
|
||||
///
|
||||
/// Equals the wire frame payload limit, so one text is one frame.
|
||||
pub const TEXT_MAX_BYTES: u64 = 4_096;
|
||||
|
||||
/// Returns whether slow radio links are eligible for this traffic class.
|
||||
pub const fn allows_slow_radio(self) -> bool {
|
||||
!matches!(self, Self::Bulk)
|
||||
}
|
||||
|
||||
/// Returns the class a payload of `bytes` is actually treated as.
|
||||
///
|
||||
/// The label is chosen by the sender and cannot be trusted: an oversized
|
||||
/// `Control` becomes `Text` and an oversized `Text` becomes `Bulk`, so a
|
||||
/// large payload can never claim a slow radio. `Bulk` never shrinks.
|
||||
pub const fn effective_for(self, bytes: u64) -> Self {
|
||||
match self {
|
||||
Self::Control if bytes <= Self::CONTROL_MAX_BYTES => Self::Control,
|
||||
Self::Control | Self::Text if bytes <= Self::TEXT_MAX_BYTES => Self::Text,
|
||||
_ => Self::Bulk,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstract physical or tunnel link categories used by the simulator.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum LinkKind {
|
||||
/// Low-throughput, long-range radio.
|
||||
SlowRadio,
|
||||
/// Directional Wi-Fi or comparable fast wireless communication.
|
||||
FastWireless,
|
||||
/// Wired fiber or Ethernet-style backhaul.
|
||||
Wired,
|
||||
/// A best-effort internet tunnel.
|
||||
Internet,
|
||||
}
|
||||
|
||||
impl LinkKind {
|
||||
/// Returns an illustrative bitrate, not a measured hardware capability.
|
||||
pub const fn demo_bps(self) -> u64 {
|
||||
match self {
|
||||
Self::SlowRadio => 1_000,
|
||||
Self::FastWireless => 20_000_000,
|
||||
Self::Wired => 100_000_000,
|
||||
Self::Internet => 10_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns illustrative serialization time for `bytes`, rounded up.
|
||||
///
|
||||
/// A zero-byte payload costs one byte, so the result is always at least
|
||||
/// one millisecond for a nonzero bitrate.
|
||||
pub const fn transfer_ms(self, bytes: u64) -> u64 {
|
||||
let bitrate = self.demo_bps() as u128;
|
||||
if bitrate == 0 {
|
||||
return u64::MAX;
|
||||
}
|
||||
let transfer = ((if bytes == 0 { 1 } else { bytes }) as u128)
|
||||
.saturating_mul(8_000)
|
||||
.saturating_add(bitrate - 1)
|
||||
/ bitrate;
|
||||
if transfer > u64::MAX as u128 {
|
||||
u64::MAX
|
||||
} else {
|
||||
transfer as u64
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a short display name.
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::SlowRadio => "LoRa (slow)",
|
||||
Self::FastWireless => "Wi-Fi (fast)",
|
||||
Self::Wired => "Wired",
|
||||
Self::Internet => "Internet",
|
||||
}
|
||||
}
|
||||
}
|
||||
41
workspace/crates/icenet-core/tests/types.rs
Normal file
41
workspace/crates/icenet-core/tests/types.rs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
use icenet_core::{LinkKind, NodeId, ServiceId, TrafficClass};
|
||||
|
||||
#[test]
|
||||
fn slow_radio_is_not_allowed_for_bulk() {
|
||||
assert!(TrafficClass::Text.allows_slow_radio());
|
||||
assert!(TrafficClass::Control.allows_slow_radio());
|
||||
assert!(!TrafficClass::Bulk.allows_slow_radio());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_id_is_not_limited_to_tcp_ports() {
|
||||
assert!(ServiceId(77_777).0 > 65_535);
|
||||
assert_eq!(NodeId(42), NodeId(42));
|
||||
assert!(LinkKind::FastWireless.demo_bps() > LinkKind::SlowRadio.demo_bps());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfer_time_uses_ceiling_and_a_nonzero_minimum() {
|
||||
assert_eq!(LinkKind::SlowRadio.transfer_ms(1), 8);
|
||||
assert_eq!(LinkKind::Wired.transfer_ms(1), 1);
|
||||
assert_eq!(LinkKind::FastWireless.transfer_ms(0), 1);
|
||||
assert_eq!(LinkKind::SlowRadio.transfer_ms(1_000), 8_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_is_derived_from_size_not_only_from_the_label() {
|
||||
use TrafficClass::{Bulk, Control, Text};
|
||||
assert_eq!(
|
||||
Control.effective_for(TrafficClass::CONTROL_MAX_BYTES),
|
||||
Control
|
||||
);
|
||||
assert_eq!(
|
||||
Control.effective_for(TrafficClass::CONTROL_MAX_BYTES + 1),
|
||||
Text
|
||||
);
|
||||
assert_eq!(Text.effective_for(TrafficClass::TEXT_MAX_BYTES), Text);
|
||||
assert_eq!(Text.effective_for(TrafficClass::TEXT_MAX_BYTES + 1), Bulk);
|
||||
assert_eq!(Control.effective_for(5_000_000), Bulk);
|
||||
// A Bulk label never shrinks, however small the payload is.
|
||||
assert_eq!(Bulk.effective_for(1), Bulk);
|
||||
}
|
||||
8
workspace/crates/icenet-guard/Cargo.toml
Normal file
8
workspace/crates/icenet-guard/Cargo.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "icenet-guard"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../icenet-core" }
|
||||
131
workspace/crates/icenet-guard/src/lib.rs
Normal file
131
workspace/crates/icenet-guard/src/lib.rs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
//! Deterministic local admission policy: ACL, size, queue, replay and rate.
|
||||
//!
|
||||
//! This crate provides no cryptographic authentication. `authenticated` is a
|
||||
//! test-only input until a reviewed handshake exists.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use icenet_core::{NodeId, ServiceId};
|
||||
|
||||
mod rate;
|
||||
mod replay;
|
||||
|
||||
use rate::TokenBucket;
|
||||
use replay::ReplayWindow;
|
||||
|
||||
/// Configurable local limits for one guard instance.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
/// Largest accepted payload in bytes.
|
||||
pub max_payload_bytes: usize,
|
||||
/// Queue depth at which new work is denied.
|
||||
pub max_queue_depth: usize,
|
||||
/// Sustained accepted messages per second; `0` disables rate limiting.
|
||||
pub rate_per_second: u64,
|
||||
/// Messages that may be accepted back-to-back after an idle period.
|
||||
pub burst: u64,
|
||||
/// Number of recent sequence numbers remembered per peer.
|
||||
pub replay_window: u64,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_payload_bytes: 4_096,
|
||||
max_queue_depth: 64,
|
||||
rate_per_second: 20,
|
||||
burst: 10,
|
||||
replay_window: 64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Input metadata for a local access decision.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Context {
|
||||
/// A test-only authorization hint; NOT real signature verification.
|
||||
pub authenticated: bool,
|
||||
/// Sender identity used to scope replay and rate state.
|
||||
pub peer: NodeId,
|
||||
/// The requested application service.
|
||||
pub service: ServiceId,
|
||||
/// The declared payload size in bytes.
|
||||
pub payload_bytes: usize,
|
||||
/// Monotonic sender sequence number for replay protection.
|
||||
pub sequence: u64,
|
||||
/// Caller-supplied monotonic time in milliseconds.
|
||||
pub now_ms: u64,
|
||||
/// Current pending messages for this peer or service.
|
||||
pub queue_depth: usize,
|
||||
}
|
||||
|
||||
/// The local decision and a stable reason identifier.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Verdict {
|
||||
/// The request passes the configured local policy.
|
||||
Permit,
|
||||
/// The request is denied for a deterministic reason.
|
||||
Deny(&'static str),
|
||||
}
|
||||
|
||||
/// An allow-list plus bounded replay, rate and queue state.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Guard {
|
||||
allowed: BTreeSet<ServiceId>,
|
||||
limits: Limits,
|
||||
replay: BTreeMap<NodeId, ReplayWindow>,
|
||||
buckets: BTreeMap<NodeId, TokenBucket>,
|
||||
}
|
||||
|
||||
impl Guard {
|
||||
/// Creates a guard with an allowed-service list and explicit limits.
|
||||
pub fn new(allowed: impl IntoIterator<Item = ServiceId>, limits: Limits) -> Self {
|
||||
Self {
|
||||
allowed: allowed.into_iter().collect(),
|
||||
limits,
|
||||
replay: BTreeMap::new(),
|
||||
buckets: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks local policy and consumes replay/rate state only on `Permit`.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `context`: sender, service, size, sequence, time and queue pressure.
|
||||
///
|
||||
/// # Returns
|
||||
/// `Permit` or `Deny(reason)`; denied requests do not consume state.
|
||||
pub fn check(&mut self, context: Context) -> Verdict {
|
||||
let limits = self.limits;
|
||||
if !context.authenticated {
|
||||
return Verdict::Deny("unauthenticated");
|
||||
}
|
||||
if context.payload_bytes > limits.max_payload_bytes {
|
||||
return Verdict::Deny("oversized");
|
||||
}
|
||||
if !self.allowed.contains(&context.service) {
|
||||
return Verdict::Deny("service_denied");
|
||||
}
|
||||
if context.queue_depth >= limits.max_queue_depth {
|
||||
return Verdict::Deny("queue_full");
|
||||
}
|
||||
let replay = self
|
||||
.replay
|
||||
.entry(context.peer)
|
||||
.or_insert_with(|| ReplayWindow::new(limits.replay_window));
|
||||
if !replay.would_admit(context.sequence) {
|
||||
return Verdict::Deny("replay");
|
||||
}
|
||||
let bucket = self
|
||||
.buckets
|
||||
.entry(context.peer)
|
||||
.or_insert_with(|| TokenBucket::new(limits.burst));
|
||||
if !bucket.take(context.now_ms, limits.rate_per_second, limits.burst) {
|
||||
return Verdict::Deny("rate_limited");
|
||||
}
|
||||
replay.admit(context.sequence);
|
||||
Verdict::Permit
|
||||
}
|
||||
}
|
||||
38
workspace/crates/icenet-guard/src/rate.rs
Normal file
38
workspace/crates/icenet-guard/src/rate.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
//! Deterministic per-peer token bucket using caller-supplied monotonic time.
|
||||
|
||||
/// Allows bursts while enforcing a sustained per-second message rate.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct TokenBucket {
|
||||
tokens_milli: u64,
|
||||
last_ms: u64,
|
||||
}
|
||||
|
||||
impl TokenBucket {
|
||||
/// Creates a full bucket that can immediately spend `burst` messages.
|
||||
pub fn new(burst: u64) -> Self {
|
||||
Self {
|
||||
tokens_milli: burst.saturating_mul(1_000),
|
||||
last_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to spend one message; a zero rate disables limiting.
|
||||
pub fn take(&mut self, now_ms: u64, rate_per_second: u64, burst: u64) -> bool {
|
||||
if rate_per_second == 0 {
|
||||
return true;
|
||||
}
|
||||
let capacity = burst.saturating_mul(1_000);
|
||||
let elapsed = now_ms.saturating_sub(self.last_ms);
|
||||
self.tokens_milli = self
|
||||
.tokens_milli
|
||||
.saturating_add(elapsed.saturating_mul(rate_per_second))
|
||||
.min(capacity);
|
||||
self.last_ms = self.last_ms.max(now_ms);
|
||||
if self.tokens_milli >= 1_000 {
|
||||
self.tokens_milli -= 1_000;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
52
workspace/crates/icenet-guard/src/replay.rs
Normal file
52
workspace/crates/icenet-guard/src/replay.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
//! Per-peer anti-replay sliding window over monotonic sequence numbers.
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Remembers the newest sequence numbers accepted from one peer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ReplayWindow {
|
||||
window: u64,
|
||||
highest: Option<u64>,
|
||||
seen: BTreeSet<u64>,
|
||||
}
|
||||
|
||||
impl ReplayWindow {
|
||||
/// Creates a window of at least one sequence slot.
|
||||
pub fn new(window: u64) -> Self {
|
||||
Self {
|
||||
window: window.max(1),
|
||||
highest: None,
|
||||
seen: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether `sequence` would be accepted without changing state.
|
||||
pub fn would_admit(&self, sequence: u64) -> bool {
|
||||
let Some(highest) = self.highest else {
|
||||
return true;
|
||||
};
|
||||
if sequence > highest {
|
||||
return true;
|
||||
}
|
||||
let cutoff = highest.saturating_sub(self.window - 1);
|
||||
sequence >= cutoff && !self.seen.contains(&sequence)
|
||||
}
|
||||
|
||||
/// Records an accepted sequence and prunes entries outside the window.
|
||||
pub fn admit(&mut self, sequence: u64) {
|
||||
match self.highest {
|
||||
None => {
|
||||
self.highest = Some(sequence);
|
||||
self.seen.insert(sequence);
|
||||
}
|
||||
Some(highest) if sequence > highest => {
|
||||
self.highest = Some(sequence);
|
||||
self.seen.insert(sequence);
|
||||
let cutoff = sequence.saturating_sub(self.window - 1);
|
||||
self.seen.retain(|value| *value >= cutoff);
|
||||
}
|
||||
Some(_) => {
|
||||
self.seen.insert(sequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
46
workspace/crates/icenet-guard/tests/policy.rs
Normal file
46
workspace/crates/icenet-guard/tests/policy.rs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
use icenet_core::{NodeId, ServiceId};
|
||||
use icenet_guard::{Context, Guard, Limits, Verdict};
|
||||
|
||||
fn context() -> Context {
|
||||
Context {
|
||||
authenticated: true,
|
||||
peer: NodeId(1),
|
||||
service: ServiceId(77_777),
|
||||
payload_bytes: 5,
|
||||
sequence: 1,
|
||||
now_ms: 0,
|
||||
queue_depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits {
|
||||
max_payload_bytes: 128,
|
||||
..Limits::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denies_untrusted_and_unknown_service() {
|
||||
let mut guard = Guard::new([ServiceId(77_777)], limits());
|
||||
let mut request = context();
|
||||
request.authenticated = false;
|
||||
assert_eq!(guard.check(request), Verdict::Deny("unauthenticated"));
|
||||
request.authenticated = true;
|
||||
request.service = ServiceId(1);
|
||||
assert_eq!(guard.check(request), Verdict::Deny("service_denied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permits_bounded_known_service() {
|
||||
let mut guard = Guard::new([ServiceId(77_777)], limits());
|
||||
assert_eq!(guard.check(context()), Verdict::Permit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denies_oversized_payload() {
|
||||
let mut guard = Guard::new([ServiceId(77_777)], limits());
|
||||
let mut request = context();
|
||||
request.payload_bytes = 129;
|
||||
assert_eq!(guard.check(request), Verdict::Deny("oversized"));
|
||||
}
|
||||
37
workspace/crates/icenet-guard/tests/queue.rs
Normal file
37
workspace/crates/icenet-guard/tests/queue.rs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
use icenet_core::{NodeId, ServiceId};
|
||||
use icenet_guard::{Context, Guard, Limits, Verdict};
|
||||
|
||||
fn context(queue_depth: usize, sequence: u64) -> Context {
|
||||
Context {
|
||||
authenticated: true,
|
||||
peer: NodeId(1),
|
||||
service: ServiceId(7),
|
||||
payload_bytes: 1,
|
||||
sequence,
|
||||
now_ms: 0,
|
||||
queue_depth,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_queue_is_denied_before_accepting_more_work() {
|
||||
let limits = Limits {
|
||||
max_queue_depth: 2,
|
||||
rate_per_second: 0,
|
||||
..Limits::default()
|
||||
};
|
||||
let mut guard = Guard::new([ServiceId(7)], limits);
|
||||
assert_eq!(guard.check(context(1, 1)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(2, 2)), Verdict::Deny("queue_full"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_queue_below_the_cap_is_permitted() {
|
||||
let limits = Limits {
|
||||
max_queue_depth: 2,
|
||||
rate_per_second: 0,
|
||||
..Limits::default()
|
||||
};
|
||||
let mut guard = Guard::new([ServiceId(7)], limits);
|
||||
assert_eq!(guard.check(context(0, 1)), Verdict::Permit);
|
||||
}
|
||||
52
workspace/crates/icenet-guard/tests/rate.rs
Normal file
52
workspace/crates/icenet-guard/tests/rate.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
54
workspace/crates/icenet-guard/tests/replay.rs
Normal file
54
workspace/crates/icenet-guard/tests/replay.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
use icenet_core::{NodeId, ServiceId};
|
||||
use icenet_guard::{Context, Guard, Limits, Verdict};
|
||||
|
||||
fn limits(window: u64) -> Limits {
|
||||
Limits {
|
||||
replay_window: window,
|
||||
rate_per_second: 0,
|
||||
..Limits::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn context(peer: u64, sequence: u64) -> Context {
|
||||
Context {
|
||||
authenticated: true,
|
||||
peer: NodeId(peer),
|
||||
service: ServiceId(7),
|
||||
payload_bytes: 1,
|
||||
sequence,
|
||||
now_ms: 0,
|
||||
queue_depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_sequence_is_denied() {
|
||||
let mut guard = Guard::new([ServiceId(7)], limits(4));
|
||||
assert_eq!(guard.check(context(1, 1)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(1, 1)), Verdict::Deny("replay"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_below_the_window_is_denied() {
|
||||
let mut guard = Guard::new([ServiceId(7)], limits(4));
|
||||
assert_eq!(guard.check(context(1, 10)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(1, 6)), Verdict::Deny("replay"));
|
||||
assert_eq!(guard.check(context(1, 7)), Verdict::Permit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_sequence_advances_and_prunes_the_window() {
|
||||
let mut guard = Guard::new([ServiceId(7)], limits(4));
|
||||
assert_eq!(guard.check(context(1, 4)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(1, 5)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(1, 1)), Verdict::Deny("replay"));
|
||||
assert_eq!(guard.check(context(1, 2)), Verdict::Permit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_state_is_per_peer() {
|
||||
let mut guard = Guard::new([ServiceId(7)], limits(4));
|
||||
assert_eq!(guard.check(context(1, 5)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(2, 5)), Verdict::Permit);
|
||||
assert_eq!(guard.check(context(2, 5)), Verdict::Deny("replay"));
|
||||
}
|
||||
8
workspace/crates/icenet-routing/Cargo.toml
Normal file
8
workspace/crates/icenet-routing/Cargo.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "icenet-routing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../icenet-core" }
|
||||
138
workspace/crates/icenet-routing/src/lib.rs
Normal file
138
workspace/crates/icenet-routing/src/lib.rs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
//! Deterministic, constrained shortest-path selection for graph experiments.
|
||||
//!
|
||||
//! This crate does not claim to predict radio-wave propagation.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
|
||||
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
|
||||
/// Fixed per-hop framing and turnaround cost, in milliseconds of airtime.
|
||||
pub const HOP_OVERHEAD_MS: u64 = 10;
|
||||
|
||||
/// An undirected available/disabled link in the simulated topology.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Link {
|
||||
/// First endpoint.
|
||||
pub a: NodeId,
|
||||
/// Second endpoint.
|
||||
pub b: NodeId,
|
||||
/// Category used for eligibility and nominal throughput.
|
||||
pub kind: LinkKind,
|
||||
/// Whether the link is currently available.
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// Result of a constrained route lookup.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Path {
|
||||
/// Ordered endpoint IDs, including source and destination.
|
||||
pub nodes: Vec<NodeId>,
|
||||
/// Index into the `links` slice of every hop, in travel order.
|
||||
///
|
||||
/// Parallel links between the same two nodes stay distinguishable.
|
||||
pub links: Vec<usize>,
|
||||
/// Illustrative serialization latency, not a real RTT estimate.
|
||||
pub estimated_ms: u64,
|
||||
}
|
||||
|
||||
/// Returns a deterministic eligible path, or `None` when disconnected.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `nodes`: Active node IDs in the simulated graph.
|
||||
/// - `links`: Candidate undirected links.
|
||||
/// - `class`: Declared class; it is raised to the size-derived effective class
|
||||
/// (see [`TrafficClass::effective_for`]) before slow radio links are judged.
|
||||
/// - `size_bytes`: Data size for illustrative weighted costs.
|
||||
///
|
||||
/// # Returns
|
||||
/// A path optimized for approximate serialization cost.
|
||||
#[must_use]
|
||||
pub fn choose_path(
|
||||
nodes: &[NodeId],
|
||||
links: &[Link],
|
||||
source: NodeId,
|
||||
destination: NodeId,
|
||||
class: TrafficClass,
|
||||
size_bytes: u64,
|
||||
) -> Option<Path> {
|
||||
let class = class.effective_for(size_bytes);
|
||||
let active: BTreeSet<NodeId> = nodes.iter().copied().collect();
|
||||
if !active.contains(&source) || !active.contains(&destination) {
|
||||
return None;
|
||||
}
|
||||
let mut distances = BTreeMap::<NodeId, u128>::new();
|
||||
let mut previous = BTreeMap::<NodeId, (NodeId, usize)>::new();
|
||||
let mut seen = BTreeSet::<NodeId>::new();
|
||||
let mut frontier = BinaryHeap::<Reverse<(u128, NodeId)>>::new();
|
||||
let mut adjacency = BTreeMap::<NodeId, Vec<(NodeId, LinkKind, usize)>>::new();
|
||||
for (index, link) in links.iter().enumerate().filter(|(_, link)| link.enabled) {
|
||||
if !active.contains(&link.a) || !active.contains(&link.b) {
|
||||
continue;
|
||||
}
|
||||
adjacency
|
||||
.entry(link.a)
|
||||
.or_default()
|
||||
.push((link.b, link.kind, index));
|
||||
adjacency
|
||||
.entry(link.b)
|
||||
.or_default()
|
||||
.push((link.a, link.kind, index));
|
||||
}
|
||||
distances.insert(source, 0);
|
||||
frontier.push(Reverse((0, source)));
|
||||
while let Some(Reverse((cost, current))) = frontier.pop() {
|
||||
if !seen.insert(current) {
|
||||
continue;
|
||||
}
|
||||
if current == destination {
|
||||
break;
|
||||
}
|
||||
let Some(neighbours) = adjacency.get(¤t) else {
|
||||
continue;
|
||||
};
|
||||
for &(next, kind, index) in neighbours {
|
||||
if kind == LinkKind::SlowRadio && !class.allows_slow_radio() {
|
||||
continue;
|
||||
}
|
||||
if seen.contains(&next) {
|
||||
continue;
|
||||
}
|
||||
let transfer_ms = u128::from(kind.transfer_ms(size_bytes));
|
||||
let proposed = cost
|
||||
.saturating_add(transfer_ms)
|
||||
.saturating_add(u128::from(HOP_OVERHEAD_MS));
|
||||
let known = distances.get(&next).copied();
|
||||
if known.is_none_or(|value| proposed < value) {
|
||||
distances.insert(next, proposed);
|
||||
previous.insert(next, (current, index));
|
||||
frontier.push(Reverse((proposed, next)));
|
||||
} else if known == Some(proposed)
|
||||
&& previous
|
||||
.get(&next)
|
||||
.is_some_and(|&(parent, parent_link)| (current, index) < (parent, parent_link))
|
||||
{
|
||||
previous.insert(next, (current, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
let cost = *distances.get(&destination)?;
|
||||
let mut steps = vec![destination];
|
||||
let mut used = Vec::new();
|
||||
let mut node = destination;
|
||||
while node != source {
|
||||
let &(parent, link) = previous.get(&node)?;
|
||||
node = parent;
|
||||
steps.push(node);
|
||||
used.push(link);
|
||||
}
|
||||
steps.reverse();
|
||||
used.reverse();
|
||||
Some(Path {
|
||||
nodes: steps,
|
||||
links: used,
|
||||
estimated_ms: u64::try_from(cost).unwrap_or(u64::MAX),
|
||||
})
|
||||
}
|
||||
111
workspace/crates/icenet-routing/tests/routing.rs
Normal file
111
workspace/crates/icenet-routing/tests/routing.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_routing::{Link, choose_path};
|
||||
|
||||
#[test]
|
||||
fn bulk_never_uses_slow_radio() {
|
||||
let nodes = [NodeId(1), NodeId(2), NodeId(3)];
|
||||
let links = [
|
||||
Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::SlowRadio,
|
||||
enabled: true,
|
||||
},
|
||||
Link {
|
||||
a: nodes[1],
|
||||
b: nodes[2],
|
||||
kind: LinkKind::SlowRadio,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
assert!(
|
||||
choose_path(
|
||||
&nodes,
|
||||
&links,
|
||||
nodes[0],
|
||||
nodes[2],
|
||||
TrafficClass::Bulk,
|
||||
50_000
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(choose_path(&nodes, &links, nodes[0], nodes[2], TrafficClass::Text, 10).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooses_fast_route_when_bulk_is_allowed() {
|
||||
let nodes = [NodeId(1), NodeId(2), NodeId(3)];
|
||||
let links = [
|
||||
Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::FastWireless,
|
||||
enabled: true,
|
||||
},
|
||||
Link {
|
||||
a: nodes[1],
|
||||
b: nodes[2],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
let chosen = choose_path(
|
||||
&nodes,
|
||||
&links,
|
||||
nodes[0],
|
||||
nodes[2],
|
||||
TrafficClass::Bulk,
|
||||
5_000_000,
|
||||
);
|
||||
assert_eq!(chosen.expect("connected").nodes, nodes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_bridge_breaks_route() {
|
||||
let nodes = [NodeId(1), NodeId(2)];
|
||||
let links = [Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: false,
|
||||
}];
|
||||
assert!(choose_path(&nodes, &links, nodes[0], nodes[1], TrafficClass::Text, 5).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_cost_paths_use_a_stable_lexicographic_tie_break() {
|
||||
let nodes = [NodeId(1), NodeId(2), NodeId(3), NodeId(4)];
|
||||
let forward = [
|
||||
Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
Link {
|
||||
a: nodes[1],
|
||||
b: nodes[3],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
Link {
|
||||
a: nodes[0],
|
||||
b: nodes[2],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
Link {
|
||||
a: nodes[2],
|
||||
b: nodes[3],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
let mut reversed = forward;
|
||||
reversed.reverse();
|
||||
for links in [&forward, &reversed] {
|
||||
let path = choose_path(&nodes, links, nodes[0], nodes[3], TrafficClass::Text, 10)
|
||||
.expect("diamond is connected");
|
||||
assert_eq!(path.nodes, [NodeId(1), NodeId(2), NodeId(4)]);
|
||||
}
|
||||
}
|
||||
79
workspace/crates/icenet-routing/tests/size_limits.rs
Normal file
79
workspace/crates/icenet-routing/tests/size_limits.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
//! Size limits: a payload label cannot smuggle bulk data onto a slow radio.
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_routing::{Link, choose_path};
|
||||
|
||||
fn slow_pair() -> ([NodeId; 2], [Link; 1]) {
|
||||
let nodes = [NodeId(1), NodeId(2)];
|
||||
let links = [Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::SlowRadio,
|
||||
enabled: true,
|
||||
}];
|
||||
(nodes, links)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_text_is_treated_as_bulk_and_refused_on_slow_radio() {
|
||||
let (nodes, links) = slow_pair();
|
||||
let at_limit = TrafficClass::TEXT_MAX_BYTES;
|
||||
assert!(
|
||||
choose_path(
|
||||
&nodes,
|
||||
&links,
|
||||
nodes[0],
|
||||
nodes[1],
|
||||
TrafficClass::Text,
|
||||
at_limit
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
choose_path(
|
||||
&nodes,
|
||||
&links,
|
||||
nodes[0],
|
||||
nodes[1],
|
||||
TrafficClass::Text,
|
||||
at_limit + 1
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_control_is_treated_as_text_then_bulk() {
|
||||
let (nodes, links) = slow_pair();
|
||||
let control = TrafficClass::Control;
|
||||
let just_over = TrafficClass::CONTROL_MAX_BYTES + 1;
|
||||
assert!(choose_path(&nodes, &links, nodes[0], nodes[1], control, just_over).is_some());
|
||||
assert!(choose_path(&nodes, &links, nodes[0], nodes[1], control, 1_000_000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_reports_the_index_of_every_link_it_uses() {
|
||||
let nodes = [NodeId(1), NodeId(2), NodeId(3)];
|
||||
let links = [
|
||||
Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::SlowRadio,
|
||||
enabled: false,
|
||||
},
|
||||
Link {
|
||||
a: nodes[0],
|
||||
b: nodes[1],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
Link {
|
||||
a: nodes[1],
|
||||
b: nodes[2],
|
||||
kind: LinkKind::Wired,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
let path =
|
||||
choose_path(&nodes, &links, nodes[0], nodes[2], TrafficClass::Text, 10).expect("connected");
|
||||
assert_eq!(path.links, [1, 2]);
|
||||
}
|
||||
11
workspace/crates/icenet-sdk/Cargo.toml
Normal file
11
workspace/crates/icenet-sdk/Cargo.toml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
[package]
|
||||
name = "icenet-sdk"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../icenet-core" }
|
||||
icenet-wire = { path = "../icenet-wire" }
|
||||
icenet-guard = { path = "../icenet-guard" }
|
||||
icenet-transport = { path = "../icenet-transport" }
|
||||
28
workspace/crates/icenet-sdk/src/lib.rs
Normal file
28
workspace/crates/icenet-sdk/src/lib.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
//! An early public facade for application developers.
|
||||
//!
|
||||
//! There is no networking daemon or authenticated handshake in this scaffold.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub use icenet_core::{NodeId, ServiceId, TrafficClass};
|
||||
pub use icenet_guard::{Context, Guard, Limits, Verdict};
|
||||
pub use icenet_transport::{
|
||||
MAX_DATAGRAM_BYTES, MemoryTransport, Transport, TransportError, UdpTransport,
|
||||
};
|
||||
pub use icenet_wire::{Frame, FrameError, decode, encode};
|
||||
|
||||
/// Builds an encoded *local test* message without cryptographic protection.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a `FrameError` for oversized frames.
|
||||
pub fn encode_message(
|
||||
service: ServiceId,
|
||||
class: TrafficClass,
|
||||
text: &[u8],
|
||||
) -> Result<Vec<u8>, FrameError> {
|
||||
icenet_wire::encode(&Frame {
|
||||
service,
|
||||
class,
|
||||
payload: text.to_vec(),
|
||||
})
|
||||
}
|
||||
7
workspace/crates/icenet-sdk/tests/facade.rs
Normal file
7
workspace/crates/icenet-sdk/tests/facade.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
use icenet_sdk::{ServiceId, TrafficClass, encode_message};
|
||||
|
||||
#[test]
|
||||
fn sdk_constructs_bounded_frames() {
|
||||
let bytes = encode_message(ServiceId(77_777), TrafficClass::Text, b"hi").unwrap();
|
||||
assert!(!bytes.is_empty());
|
||||
}
|
||||
33
workspace/crates/icenet-sdk/tests/udp_roundtrip.rs
Normal file
33
workspace/crates/icenet-sdk/tests/udp_roundtrip.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
//! End-to-end frame exchange over a real UDP loopback pair.
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use icenet_sdk::{Frame, ServiceId, TrafficClass, Transport, UdpTransport, decode, encode};
|
||||
|
||||
#[test]
|
||||
fn encoded_frame_survives_a_udp_round_trip() {
|
||||
let first = UdpTransport::bind("127.0.0.1:0").expect("bind first");
|
||||
let second = UdpTransport::bind("127.0.0.1:0").expect("bind second");
|
||||
let first_addr = first.local_addr().expect("first address");
|
||||
let second_addr = second.local_addr().expect("second address");
|
||||
let mut sender = first.connect(second_addr).expect("connect sender");
|
||||
let mut receiver = second.connect(first_addr).expect("connect receiver");
|
||||
|
||||
let frame = Frame {
|
||||
class: TrafficClass::Text,
|
||||
service: ServiceId(77_777),
|
||||
payload: b"hello over udp".to_vec(),
|
||||
};
|
||||
sender.send(encode(&frame).expect("encode")).expect("send");
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
let mut received = None;
|
||||
while Instant::now() < deadline {
|
||||
if let Some(bytes) = receiver.recv().expect("recv") {
|
||||
received = Some(bytes);
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let bytes = received.expect("frame within deadline");
|
||||
assert_eq!(decode(&bytes), Ok(frame));
|
||||
}
|
||||
9
workspace/crates/icenet-sim/Cargo.toml
Normal file
9
workspace/crates/icenet-sim/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "icenet-sim"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../icenet-core" }
|
||||
icenet-routing = { path = "../icenet-routing" }
|
||||
101
workspace/crates/icenet-sim/src/engine/ledger.rs
Normal file
101
workspace/crates/icenet-sim/src/engine/ledger.rs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
//! Per-link airtime reservations: a link carries one transmission at a time.
|
||||
use icenet_routing::HOP_OVERHEAD_MS;
|
||||
|
||||
use crate::SimLink;
|
||||
|
||||
/// One reserved transmission interval on a link.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Slot {
|
||||
begin: u64,
|
||||
end: u64,
|
||||
owner: u64,
|
||||
}
|
||||
|
||||
/// Reservation calendar for every link, indexed like `City::links`.
|
||||
///
|
||||
/// Slots on one link never overlap and are kept sorted by start time, so
|
||||
/// later reservations queue behind earlier ones and may reuse freed gaps.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) struct LinkLedger {
|
||||
slots: Vec<Vec<Slot>>,
|
||||
spent_ms: Vec<u64>,
|
||||
}
|
||||
|
||||
impl LinkLedger {
|
||||
/// Reserves each hop in order and returns the arrival time at the end.
|
||||
///
|
||||
/// The result is always at least one millisecond after `start_ms`.
|
||||
pub fn reserve_path(
|
||||
&mut self,
|
||||
links: &[SimLink],
|
||||
hops: &[usize],
|
||||
bytes: u64,
|
||||
start_ms: u64,
|
||||
owner: u64,
|
||||
) -> u64 {
|
||||
let mut ready = start_ms;
|
||||
for &index in hops {
|
||||
let hop_ms = links[index]
|
||||
.kind
|
||||
.transfer_ms(bytes)
|
||||
.saturating_add(HOP_OVERHEAD_MS);
|
||||
ready = self.reserve(index, ready, hop_ms, owner);
|
||||
}
|
||||
ready.max(start_ms.saturating_add(1))
|
||||
}
|
||||
|
||||
/// Frees the not-yet-started slots of `owner`; started airtime stays spent.
|
||||
pub fn release(&mut self, owner: u64, now_ms: u64) {
|
||||
for (slots, spent) in self.slots.iter_mut().zip(self.spent_ms.iter_mut()) {
|
||||
slots.retain(|slot| {
|
||||
let free = slot.owner == owner && slot.begin >= now_ms;
|
||||
if free {
|
||||
*spent = spent.saturating_sub(slot.end - slot.begin);
|
||||
}
|
||||
!free
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets slots that finished at or before `now_ms`; totals are kept.
|
||||
pub fn prune(&mut self, now_ms: u64) {
|
||||
for slots in &mut self.slots {
|
||||
slots.retain(|slot| slot.end > now_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Total airtime reserved on one link, in milliseconds.
|
||||
pub fn airtime_ms(&self, link: usize) -> u64 {
|
||||
self.spent_ms.get(link).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Milliseconds from `now_ms` until the last reservation on `link` ends.
|
||||
pub fn backlog_ms(&self, link: usize, now_ms: u64) -> u64 {
|
||||
let last = self.slots.get(link).and_then(|slots| slots.last());
|
||||
last.map_or(0, |slot| slot.end.saturating_sub(now_ms))
|
||||
}
|
||||
|
||||
fn reserve(&mut self, link: usize, ready_ms: u64, duration_ms: u64, owner: u64) -> u64 {
|
||||
if self.slots.len() <= link {
|
||||
self.slots.resize_with(link + 1, Vec::new);
|
||||
self.spent_ms.resize(link + 1, 0);
|
||||
}
|
||||
let slots = &mut self.slots[link];
|
||||
let mut begin = ready_ms;
|
||||
let mut position = slots.len();
|
||||
for (index, slot) in slots.iter().enumerate() {
|
||||
if slot.end <= begin {
|
||||
continue;
|
||||
}
|
||||
if slot.begin >= begin.saturating_add(duration_ms) {
|
||||
position = index;
|
||||
break;
|
||||
}
|
||||
begin = slot.end;
|
||||
}
|
||||
let end = begin.saturating_add(duration_ms);
|
||||
slots.insert(position, Slot { begin, end, owner });
|
||||
self.spent_ms[link] = self.spent_ms[link].saturating_add(duration_ms);
|
||||
end
|
||||
}
|
||||
}
|
||||
169
workspace/crates/icenet-sim/src/engine/mod.rs
Normal file
169
workspace/crates/icenet-sim/src/engine/mod.rs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
//! Virtual time and deterministic state transitions for the city model.
|
||||
use crate::{DeliveryState, Device, DeviceRole, Message, SimLink};
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_routing::{Link, Path, choose_path};
|
||||
|
||||
mod ledger;
|
||||
mod tick;
|
||||
|
||||
use ledger::LinkLedger;
|
||||
|
||||
/// Mutable state of one in-memory city simulation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct City {
|
||||
/// Available virtual devices.
|
||||
pub devices: Vec<Device>,
|
||||
/// Simulated point-to-point links.
|
||||
pub links: Vec<SimLink>,
|
||||
/// Recorded synthetic application messages.
|
||||
pub messages: Vec<Message>,
|
||||
/// Current deterministic simulation time in milliseconds.
|
||||
pub now_ms: u64,
|
||||
next_message_id: u64,
|
||||
ledger: LinkLedger,
|
||||
}
|
||||
|
||||
impl City {
|
||||
/// Default message lifetime: 24 simulated hours.
|
||||
pub const DEFAULT_TTL_MS: u64 = 86_400_000;
|
||||
|
||||
/// Returns an empty simulation for custom scenario construction.
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
devices: Vec::new(),
|
||||
links: Vec::new(),
|
||||
messages: Vec::new(),
|
||||
now_ms: 0,
|
||||
next_message_id: 1,
|
||||
ledger: LinkLedger::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a six-device topology with redundant slow and fast paths.
|
||||
pub fn demo() -> Self {
|
||||
let spec = [
|
||||
(1, "Phone A", 70.0, 85.0, DeviceRole::Client),
|
||||
(2, "LoRa relay", 175.0, 70.0, DeviceRole::Relay),
|
||||
(3, "Friend B", 410.0, 95.0, DeviceRole::Client),
|
||||
(4, "Rooftop", 185.0, 205.0, DeviceRole::Relay),
|
||||
(5, "Backbone", 335.0, 200.0, DeviceRole::Backbone),
|
||||
(6, "Remote", 480.0, 230.0, DeviceRole::Client),
|
||||
];
|
||||
let devices = spec
|
||||
.into_iter()
|
||||
.map(|(id, name, x, y, role)| Device {
|
||||
id: NodeId(id),
|
||||
label: name.to_owned(),
|
||||
x,
|
||||
y,
|
||||
role,
|
||||
online: true,
|
||||
})
|
||||
.collect();
|
||||
let links = [
|
||||
(1, 2, LinkKind::SlowRadio),
|
||||
(2, 3, LinkKind::SlowRadio),
|
||||
(1, 4, LinkKind::FastWireless),
|
||||
(4, 5, LinkKind::Wired),
|
||||
(5, 3, LinkKind::FastWireless),
|
||||
(5, 6, LinkKind::FastWireless),
|
||||
(2, 4, LinkKind::SlowRadio),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(a, b, kind)| SimLink {
|
||||
a: NodeId(a),
|
||||
b: NodeId(b),
|
||||
kind,
|
||||
enabled: true,
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
devices,
|
||||
links,
|
||||
messages: Vec::new(),
|
||||
now_ms: 0,
|
||||
next_message_id: 1,
|
||||
ledger: LinkLedger::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a route for a class and size under the current topology.
|
||||
pub fn route(&self, from: NodeId, to: NodeId, class: TrafficClass, bytes: u64) -> Option<Path> {
|
||||
let active: Vec<NodeId> = self
|
||||
.devices
|
||||
.iter()
|
||||
.filter(|d| d.online)
|
||||
.map(|d| d.id)
|
||||
.collect();
|
||||
let links = self
|
||||
.links
|
||||
.iter()
|
||||
.map(|link| Link {
|
||||
a: link.a,
|
||||
b: link.b,
|
||||
kind: link.kind,
|
||||
enabled: link.enabled,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
choose_path(&active, &links, from, to, class, bytes)
|
||||
}
|
||||
|
||||
/// Creates a message with the default lifetime and queues it when necessary.
|
||||
pub fn send(&mut self, from: NodeId, to: NodeId, class: TrafficClass, bytes: u64) -> u64 {
|
||||
self.send_with_ttl(from, to, class, bytes, Self::DEFAULT_TTL_MS)
|
||||
}
|
||||
|
||||
/// Creates a message with an explicit lifetime in simulated milliseconds.
|
||||
///
|
||||
/// An undelivered message expires once `now_ms` reaches
|
||||
/// `created_ms + ttl_ms`; expired messages are never retried. The declared
|
||||
/// `class` is raised to the size-derived class before routing.
|
||||
pub fn send_with_ttl(
|
||||
&mut self,
|
||||
from: NodeId,
|
||||
to: NodeId,
|
||||
class: TrafficClass,
|
||||
bytes: u64,
|
||||
ttl_ms: u64,
|
||||
) -> u64 {
|
||||
let id = self.next_message_id;
|
||||
self.next_message_id = self.next_message_id.saturating_add(1);
|
||||
self.messages.push(Message {
|
||||
id,
|
||||
from,
|
||||
to,
|
||||
class,
|
||||
bytes,
|
||||
status: DeliveryState::Queued,
|
||||
created_ms: self.now_ms,
|
||||
expires_ms: self.now_ms.saturating_add(ttl_ms.max(1)),
|
||||
first_route_ms: None,
|
||||
estimated_ms: 0,
|
||||
due_ms: None,
|
||||
route: Vec::new(),
|
||||
route_links: Vec::new(),
|
||||
});
|
||||
if let Some(path) = self.route(from, to, class, bytes) {
|
||||
self.schedule(self.messages.len() - 1, path);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Returns the airtime ever reserved on links of `kind`, in milliseconds.
|
||||
///
|
||||
/// Reservations released before they started are not counted.
|
||||
pub fn link_airtime_ms(&self, kind: LinkKind) -> u64 {
|
||||
let mut total = 0_u64;
|
||||
for (index, link) in self.links.iter().enumerate() {
|
||||
if link.kind == kind {
|
||||
total = total.saturating_add(self.ledger.airtime_ms(index));
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Returns how long link `index` stays busy from now, in milliseconds.
|
||||
pub fn link_backlog_ms(&self, index: usize) -> u64 {
|
||||
self.ledger.backlog_ms(index, self.now_ms)
|
||||
}
|
||||
}
|
||||
114
workspace/crates/icenet-sim/src/engine/tick.rs
Normal file
114
workspace/crates/icenet-sim/src/engine/tick.rs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
//! Time advance: delivery, expiry, re-planning and queueing of messages.
|
||||
use icenet_core::{LinkKind, NodeId};
|
||||
use icenet_routing::Path;
|
||||
|
||||
use super::City;
|
||||
use crate::{DeliveryState, Message};
|
||||
|
||||
impl City {
|
||||
/// Advances virtual time and updates delivery state without sleeping.
|
||||
///
|
||||
/// Topology edits only happen between ticks, so the topology seen here has
|
||||
/// held for the whole elapsed interval. A message is therefore delivered
|
||||
/// only if its planned route is still usable now; a coarse step can never
|
||||
/// jump over a link cut into a false `Delivered`.
|
||||
pub fn tick(&mut self, elapsed_ms: u64) {
|
||||
self.now_ms = self.now_ms.saturating_add(elapsed_ms);
|
||||
self.ledger.prune(self.now_ms);
|
||||
for index in 0..self.messages.len() {
|
||||
let message = &self.messages[index];
|
||||
if matches!(
|
||||
message.status,
|
||||
DeliveryState::Delivered | DeliveryState::Expired
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let usable = message.status == DeliveryState::InFlight && self.route_is_usable(message);
|
||||
let (id, expires_ms, due_ms) = (message.id, message.expires_ms, message.due_ms);
|
||||
// Arrival at or before the deadline wins even when one coarse tick
|
||||
// jumps past both timestamps, provided the route survived.
|
||||
if usable && due_ms.is_some_and(|due| due <= self.now_ms && due <= expires_ms) {
|
||||
self.messages[index].status = DeliveryState::Delivered;
|
||||
continue;
|
||||
}
|
||||
if self.now_ms >= expires_ms {
|
||||
self.ledger.release(id, self.now_ms);
|
||||
let message = &mut self.messages[index];
|
||||
message.status = DeliveryState::Expired;
|
||||
message.clear_plan();
|
||||
continue;
|
||||
}
|
||||
let message = &self.messages[index];
|
||||
let fresh = self.route(message.from, message.to, message.class, message.bytes);
|
||||
match fresh {
|
||||
None => {
|
||||
self.ledger.release(id, self.now_ms);
|
||||
let message = &mut self.messages[index];
|
||||
message.status = DeliveryState::Queued;
|
||||
message.clear_plan();
|
||||
}
|
||||
Some(path) => {
|
||||
let message = &self.messages[index];
|
||||
let unchanged = message.status == DeliveryState::InFlight
|
||||
&& usable
|
||||
&& path.nodes == message.route
|
||||
&& path.links == message.route_links
|
||||
&& path.estimated_ms == message.estimated_ms;
|
||||
if !unchanged {
|
||||
self.schedule(index, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plans `path` for message `index`, replacing any earlier reservation.
|
||||
///
|
||||
/// A re-plan restarts the transfer from the source: airtime already spent
|
||||
/// is not refunded, and only slots that have not started are released.
|
||||
pub(super) fn schedule(&mut self, index: usize, path: Path) {
|
||||
let (id, bytes) = (self.messages[index].id, self.messages[index].bytes);
|
||||
self.ledger.release(id, self.now_ms);
|
||||
let due = self
|
||||
.ledger
|
||||
.reserve_path(&self.links, &path.links, bytes, self.now_ms, id);
|
||||
let message = &mut self.messages[index];
|
||||
message.status = DeliveryState::InFlight;
|
||||
if message.first_route_ms.is_none() {
|
||||
message.first_route_ms = Some(self.now_ms);
|
||||
}
|
||||
message.estimated_ms = path.estimated_ms;
|
||||
message.due_ms = Some(due);
|
||||
message.route = path.nodes;
|
||||
message.route_links = path.links;
|
||||
}
|
||||
|
||||
/// Returns whether every device and link of the planned route is usable now.
|
||||
fn route_is_usable(&self, message: &Message) -> bool {
|
||||
let route = &message.route;
|
||||
let hops = &message.route_links;
|
||||
if route.is_empty() || route.len() != hops.len() + 1 {
|
||||
return false;
|
||||
}
|
||||
let class = message.class.effective_for(message.bytes);
|
||||
let online = |id: &NodeId| self.devices.iter().any(|d| d.id == *id && d.online);
|
||||
route.iter().all(online)
|
||||
&& route.windows(2).zip(hops).all(|(pair, &index)| {
|
||||
self.links.get(index).is_some_and(|link| {
|
||||
let joins = (link.a == pair[0] && link.b == pair[1])
|
||||
|| (link.a == pair[1] && link.b == pair[0]);
|
||||
let eligible = class.allows_slow_radio() || link.kind != LinkKind::SlowRadio;
|
||||
link.enabled && joins && eligible
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Message {
|
||||
fn clear_plan(&mut self) {
|
||||
self.due_ms = None;
|
||||
self.estimated_ms = 0;
|
||||
self.route.clear();
|
||||
self.route_links.clear();
|
||||
}
|
||||
}
|
||||
14
workspace/crates/icenet-sim/src/lib.rs
Normal file
14
workspace/crates/icenet-sim/src/lib.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//! Deterministic graph simulator for ICE-NET traffic policies.
|
||||
//!
|
||||
//! Links carry one transmission at a time (see `City::link_airtime_ms`).
|
||||
//! RF physics, cryptography, NAT and real sockets are out of scope.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod engine;
|
||||
pub mod metrics;
|
||||
mod model;
|
||||
mod topology;
|
||||
|
||||
pub use engine::City;
|
||||
pub use model::{DeliveryState, Device, DeviceRole, Message, SimLink};
|
||||
171
workspace/crates/icenet-sim/src/metrics/export.rs
Normal file
171
workspace/crates/icenet-sim/src/metrics/export.rs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
//! Deterministic CSV and JSON serialization for city experiments.
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use icenet_core::{LinkKind, TrafficClass};
|
||||
|
||||
use crate::{City, DeliveryState, DeviceRole, Message};
|
||||
|
||||
/// Exports one CSV row per message in creation order.
|
||||
pub fn messages_csv(city: &City) -> String {
|
||||
let mut out = String::from(
|
||||
"id,from,to,class,bytes,status,created_ms,expires_ms,first_route_ms,due_ms,route\n",
|
||||
);
|
||||
for message in &city.messages {
|
||||
let route = message
|
||||
.route
|
||||
.iter()
|
||||
.map(|node| node.0.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-");
|
||||
writeln!(
|
||||
out,
|
||||
"{},{},{},{},{},{},{},{},{},{},{}",
|
||||
message.id,
|
||||
message.from.0,
|
||||
message.to.0,
|
||||
class_name(message.class),
|
||||
message.bytes,
|
||||
status_name(message.status),
|
||||
message.created_ms,
|
||||
message.expires_ms,
|
||||
optional(message.first_route_ms),
|
||||
optional(message.due_ms),
|
||||
route
|
||||
)
|
||||
.expect("writing into a String cannot fail");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Exports the whole scenario as deterministic, dependency-free JSON.
|
||||
pub fn scenario_json(city: &City) -> String {
|
||||
let mut out = String::from("{\n");
|
||||
writeln!(out, " \"now_ms\": {},", city.now_ms).expect("String write");
|
||||
out.push_str(" \"devices\": [");
|
||||
for (index, device) in city.devices.iter().enumerate() {
|
||||
out.push_str(if index == 0 { "\n" } else { ",\n" });
|
||||
write!(
|
||||
out,
|
||||
" {{\"id\":{},\"label\":\"{}\",\"x\":{},\"y\":{},\"role\":\"{}\",\"online\":{}}}",
|
||||
device.id.0,
|
||||
escape(&device.label),
|
||||
coordinate(device.x),
|
||||
coordinate(device.y),
|
||||
role_name(device.role),
|
||||
device.online
|
||||
)
|
||||
.expect("String write");
|
||||
}
|
||||
out.push_str("\n ],\n \"links\": [");
|
||||
for (index, link) in city.links.iter().enumerate() {
|
||||
out.push_str(if index == 0 { "\n" } else { ",\n" });
|
||||
write!(
|
||||
out,
|
||||
" {{\"a\":{},\"b\":{},\"kind\":\"{}\",\"enabled\":{}}}",
|
||||
link.a.0,
|
||||
link.b.0,
|
||||
link_kind_name(link.kind),
|
||||
link.enabled
|
||||
)
|
||||
.expect("String write");
|
||||
}
|
||||
out.push_str("\n ],\n \"messages\": [");
|
||||
for (index, message) in city.messages.iter().enumerate() {
|
||||
out.push_str(if index == 0 { "\n" } else { ",\n" });
|
||||
write!(out, " {}", message_json(message)).expect("String write");
|
||||
}
|
||||
out.push_str("\n ]\n}\n");
|
||||
out
|
||||
}
|
||||
|
||||
fn message_json(message: &Message) -> String {
|
||||
let route = message
|
||||
.route
|
||||
.iter()
|
||||
.map(|node| node.0.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
format!(
|
||||
"{{\"id\":{},\"from\":{},\"to\":{},\"class\":\"{}\",\"bytes\":{},\"status\":\"{}\",\
|
||||
\"created_ms\":{},\"expires_ms\":{},\"first_route_ms\":{},\"due_ms\":{},\"route\":[{}]}}",
|
||||
message.id,
|
||||
message.from.0,
|
||||
message.to.0,
|
||||
class_name(message.class),
|
||||
message.bytes,
|
||||
status_name(message.status),
|
||||
message.created_ms,
|
||||
message.expires_ms,
|
||||
json_option(message.first_route_ms),
|
||||
json_option(message.due_ms),
|
||||
route
|
||||
)
|
||||
}
|
||||
|
||||
fn json_option(value: Option<u64>) -> String {
|
||||
value.map_or_else(|| "null".to_owned(), |number| number.to_string())
|
||||
}
|
||||
|
||||
fn optional(value: Option<u64>) -> String {
|
||||
value.map_or_else(String::new, |number| number.to_string())
|
||||
}
|
||||
|
||||
fn coordinate(value: f32) -> String {
|
||||
if value.is_finite() {
|
||||
format!("{value:.1}")
|
||||
} else {
|
||||
"null".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn class_name(class: TrafficClass) -> &'static str {
|
||||
match class {
|
||||
TrafficClass::Control => "Control",
|
||||
TrafficClass::Text => "Text",
|
||||
TrafficClass::Bulk => "Bulk",
|
||||
}
|
||||
}
|
||||
|
||||
fn status_name(status: DeliveryState) -> &'static str {
|
||||
match status {
|
||||
DeliveryState::Queued => "Queued",
|
||||
DeliveryState::InFlight => "InFlight",
|
||||
DeliveryState::Delivered => "Delivered",
|
||||
DeliveryState::Expired => "Expired",
|
||||
}
|
||||
}
|
||||
|
||||
fn role_name(role: DeviceRole) -> &'static str {
|
||||
match role {
|
||||
DeviceRole::Client => "Client",
|
||||
DeviceRole::Relay => "Relay",
|
||||
DeviceRole::Backbone => "Backbone",
|
||||
}
|
||||
}
|
||||
|
||||
fn link_kind_name(kind: LinkKind) -> &'static str {
|
||||
match kind {
|
||||
LinkKind::SlowRadio => "SlowRadio",
|
||||
LinkKind::FastWireless => "FastWireless",
|
||||
LinkKind::Wired => "Wired",
|
||||
LinkKind::Internet => "Internet",
|
||||
}
|
||||
}
|
||||
|
||||
fn escape(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len());
|
||||
for character in value.chars() {
|
||||
match character {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
control if control.is_control() => {
|
||||
write!(out, "\\u{:04x}", u32::from(control)).expect("String write");
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
109
workspace/crates/icenet-sim/src/metrics/mod.rs
Normal file
109
workspace/crates/icenet-sim/src/metrics/mod.rs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
//! Deterministic aggregate metrics for the city simulator.
|
||||
//!
|
||||
//! These helpers never read wall-clock time, so identical simulations produce
|
||||
//! identical summaries.
|
||||
use icenet_core::{LinkKind, TrafficClass};
|
||||
use icenet_routing::HOP_OVERHEAD_MS;
|
||||
|
||||
use crate::{City, DeliveryState, Message};
|
||||
|
||||
mod export;
|
||||
pub use export::{messages_csv, scenario_json};
|
||||
|
||||
/// Aggregate counters for one simulation snapshot.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Summary {
|
||||
/// Messages submitted by the application.
|
||||
pub created: usize,
|
||||
/// Messages whose transmission completed.
|
||||
pub delivered: usize,
|
||||
/// Messages currently waiting for an eligible path.
|
||||
pub queued: usize,
|
||||
/// Messages with a scheduled transmission.
|
||||
pub in_flight: usize,
|
||||
/// Messages whose lifetime elapsed before delivery.
|
||||
pub expired: usize,
|
||||
/// Median simulated timestamp when a path first became available.
|
||||
pub first_route_p50_ms: Option<u64>,
|
||||
/// 95th percentile simulated timestamp when a path first became available.
|
||||
pub first_route_p95_ms: Option<u64>,
|
||||
/// Approximate control-message airtime across all route hops.
|
||||
pub control_airtime_ms: u64,
|
||||
/// Airtime reserved on slow radio links by all messages, in milliseconds.
|
||||
pub slow_radio_airtime_ms: u64,
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
/// Returns delivered messages divided by created messages.
|
||||
///
|
||||
/// The ratio is `0.0` for an empty simulation.
|
||||
pub fn delivery_ratio(&self) -> f64 {
|
||||
if self.created == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
self.delivered as f64 / self.created as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// Summarizes delivery states, first-route latency and control airtime.
|
||||
pub fn summarize(city: &City) -> Summary {
|
||||
let mut summary = Summary {
|
||||
created: city.messages.len(),
|
||||
delivered: 0,
|
||||
queued: 0,
|
||||
in_flight: 0,
|
||||
expired: 0,
|
||||
first_route_p50_ms: None,
|
||||
first_route_p95_ms: None,
|
||||
control_airtime_ms: 0,
|
||||
slow_radio_airtime_ms: city.link_airtime_ms(LinkKind::SlowRadio),
|
||||
};
|
||||
let mut first_route_samples = Vec::new();
|
||||
for message in &city.messages {
|
||||
match message.status {
|
||||
DeliveryState::Delivered => summary.delivered += 1,
|
||||
DeliveryState::Queued => summary.queued += 1,
|
||||
DeliveryState::InFlight => summary.in_flight += 1,
|
||||
DeliveryState::Expired => summary.expired += 1,
|
||||
}
|
||||
if let Some(sample) = message.first_route_ms {
|
||||
first_route_samples.push(sample);
|
||||
}
|
||||
if message.class == TrafficClass::Control {
|
||||
summary.control_airtime_ms = summary
|
||||
.control_airtime_ms
|
||||
.saturating_add(airtime_ms(city, message));
|
||||
}
|
||||
}
|
||||
summary.first_route_p50_ms = percentile(&mut first_route_samples, 50);
|
||||
summary.first_route_p95_ms = percentile(&mut first_route_samples, 95);
|
||||
summary
|
||||
}
|
||||
|
||||
/// Returns the nearest-rank percentile, sorting `samples` in place.
|
||||
///
|
||||
/// `percent` is clamped to `1..=100`. An empty slice returns `None`.
|
||||
pub fn percentile(samples: &mut [u64], percent: u8) -> Option<u64> {
|
||||
if samples.is_empty() {
|
||||
return None;
|
||||
}
|
||||
samples.sort_unstable();
|
||||
let rank = usize::from(percent.clamp(1, 100));
|
||||
let index = (rank.saturating_mul(samples.len()))
|
||||
.div_ceil(100)
|
||||
.saturating_sub(1);
|
||||
samples.get(index).copied()
|
||||
}
|
||||
|
||||
fn airtime_ms(city: &City, message: &Message) -> u64 {
|
||||
message
|
||||
.route_links
|
||||
.iter()
|
||||
.filter_map(|&index| city.links.get(index))
|
||||
.map(|link| {
|
||||
link.kind
|
||||
.transfer_ms(message.bytes)
|
||||
.saturating_add(HOP_OVERHEAD_MS)
|
||||
})
|
||||
.fold(0, u64::saturating_add)
|
||||
}
|
||||
87
workspace/crates/icenet-sim/src/model.rs
Normal file
87
workspace/crates/icenet-sim/src/model.rs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
//! Plain state structures for the city graph simulator.
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
|
||||
/// Logical role of one virtual city device.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DeviceRole {
|
||||
/// A battery-powered or user-facing endpoint.
|
||||
Client,
|
||||
/// A transit node forwarding messages.
|
||||
Relay,
|
||||
/// A normally available backbone node.
|
||||
Backbone,
|
||||
}
|
||||
|
||||
/// A visible node in the city diagram.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Device {
|
||||
/// Numeric simulator node ID.
|
||||
pub id: NodeId,
|
||||
/// Display label shown by the city GUI.
|
||||
pub label: String,
|
||||
/// Horizontal map coordinate (not longitude).
|
||||
pub x: f32,
|
||||
/// Vertical map coordinate (not latitude).
|
||||
pub y: f32,
|
||||
/// Whether this device is available.
|
||||
pub online: bool,
|
||||
/// Intended role in the city.
|
||||
pub role: DeviceRole,
|
||||
}
|
||||
|
||||
/// A simulated undirected point-to-point connection.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SimLink {
|
||||
/// First endpoint ID.
|
||||
pub a: NodeId,
|
||||
/// Second endpoint ID.
|
||||
pub b: NodeId,
|
||||
/// Link class used for rough capacity.
|
||||
pub kind: LinkKind,
|
||||
/// Whether this connection is currently available.
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// Current delivery state; queued is never equivalent to delivered.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DeliveryState {
|
||||
/// No eligible path exists, or a path failed.
|
||||
Queued,
|
||||
/// A simulated transmission has been scheduled.
|
||||
InFlight,
|
||||
/// The simulator has completed transmission.
|
||||
Delivered,
|
||||
/// The message lifetime elapsed before delivery.
|
||||
Expired,
|
||||
}
|
||||
|
||||
/// One synthetic application message.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Message {
|
||||
/// Monotonic message identifier for this simulation.
|
||||
pub id: u64,
|
||||
/// Message origin.
|
||||
pub from: NodeId,
|
||||
/// Destination.
|
||||
pub to: NodeId,
|
||||
/// Traffic class governing link eligibility.
|
||||
pub class: TrafficClass,
|
||||
/// Synthetic payload size, no byte payload is stored.
|
||||
pub bytes: u64,
|
||||
/// Current delivery state.
|
||||
pub status: DeliveryState,
|
||||
/// Simulated time when the application submitted this message.
|
||||
pub created_ms: u64,
|
||||
/// Simulated time after which an undelivered message expires.
|
||||
pub expires_ms: u64,
|
||||
/// Simulated time when a path first became available.
|
||||
pub first_route_ms: Option<u64>,
|
||||
/// Illustrative serialization time of the current route.
|
||||
pub estimated_ms: u64,
|
||||
/// The expected end of transmission in simulated time.
|
||||
pub due_ms: Option<u64>,
|
||||
/// Current ordered route through the graph.
|
||||
pub route: Vec<NodeId>,
|
||||
/// Index into [`City::links`](crate::City) of every hop of `route`.
|
||||
pub route_links: Vec<usize>,
|
||||
}
|
||||
87
workspace/crates/icenet-sim/src/topology.rs
Normal file
87
workspace/crates/icenet-sim/src/topology.rs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
//! Topology editing operations for the city simulator.
|
||||
use crate::{City, Device, DeviceRole, SimLink};
|
||||
use icenet_core::{LinkKind, NodeId};
|
||||
|
||||
impl City {
|
||||
/// Appends a virtual device and returns its new simulator ID.
|
||||
pub fn add_device(&mut self, label: String, role: DeviceRole) -> NodeId {
|
||||
let id = NodeId(self.devices.iter().map(|d| d.id.0).max().unwrap_or(0) + 1);
|
||||
let n = self.devices.len() as f32;
|
||||
self.devices.push(Device {
|
||||
id,
|
||||
label,
|
||||
x: 65.0 + (n * 57.0) % 420.0,
|
||||
y: 70.0 + (n * 41.0) % 200.0,
|
||||
online: true,
|
||||
role,
|
||||
});
|
||||
id
|
||||
}
|
||||
|
||||
/// Adds a simulated link if both endpoints exist and are distinct.
|
||||
pub fn add_link(&mut self, a: NodeId, b: NodeId, kind: LinkKind) -> bool {
|
||||
let exists = |id| self.devices.iter().any(|device| device.id == id);
|
||||
if a == b || !exists(a) || !exists(b) {
|
||||
return false;
|
||||
}
|
||||
if self
|
||||
.links
|
||||
.iter()
|
||||
.any(|link| (link.a == a && link.b == b) || (link.a == b && link.b == a))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.links.push(SimLink {
|
||||
a,
|
||||
b,
|
||||
kind,
|
||||
enabled: true,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Changes a link category while retaining its endpoints.
|
||||
pub fn set_link_kind(&mut self, index: usize, kind: LinkKind) -> bool {
|
||||
match self.links.get_mut(index) {
|
||||
Some(link) => {
|
||||
link.kind = kind;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates a link by list index. Returns false when the index is invalid.
|
||||
pub fn set_link_enabled(&mut self, index: usize, enabled: bool) -> bool {
|
||||
match self.links.get_mut(index) {
|
||||
Some(link) => {
|
||||
link.enabled = enabled;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the availability of one device.
|
||||
pub fn set_device_online(&mut self, id: NodeId, online: bool) -> bool {
|
||||
match self.devices.iter_mut().find(|device| device.id == id) {
|
||||
Some(device) => {
|
||||
device.online = online;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves a device on the map without changing routing eligibility.
|
||||
pub fn move_device(&mut self, id: NodeId, x: f32, y: f32) -> bool {
|
||||
match self.devices.iter_mut().find(|device| device.id == id) {
|
||||
Some(device) => {
|
||||
device.x = x;
|
||||
device.y = y;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
101
workspace/crates/icenet-sim/tests/capacity/main.rs
Normal file
101
workspace/crates/icenet-sim/tests/capacity/main.rs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
//! Link capacity: transmissions share a link in FIFO order instead of overlapping.
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeliveryState, DeviceRole, metrics};
|
||||
|
||||
fn pair(kind: LinkKind) -> (City, NodeId, NodeId) {
|
||||
let mut city = City::empty();
|
||||
let a = city.add_device("a".to_owned(), DeviceRole::Client);
|
||||
let b = city.add_device("b".to_owned(), DeviceRole::Client);
|
||||
assert!(city.add_link(a, b, kind));
|
||||
(city, a, b)
|
||||
}
|
||||
|
||||
fn delivered(city: &City) -> usize {
|
||||
city.messages
|
||||
.iter()
|
||||
.filter(|m| m.status == DeliveryState::Delivered)
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texts_queue_behind_each_other_on_one_slow_link() {
|
||||
let (mut city, a, b) = pair(LinkKind::SlowRadio);
|
||||
// 200 B at 1 kbit/s is 1600 ms of airtime plus 10 ms overhead each.
|
||||
for _ in 0..100 {
|
||||
city.send(a, b, TrafficClass::Text, 200);
|
||||
}
|
||||
city.tick(2_000);
|
||||
assert_eq!(delivered(&city), 1, "only one 1610 ms frame fits in 2 s");
|
||||
city.tick(161_000 - 2_000);
|
||||
assert_eq!(delivered(&city), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_times_are_strictly_ordered_by_link_reservation() {
|
||||
let (mut city, a, b) = pair(LinkKind::SlowRadio);
|
||||
let first = city.send(a, b, TrafficClass::Text, 200);
|
||||
let second = city.send(a, b, TrafficClass::Text, 200);
|
||||
let due = |id| {
|
||||
city.messages
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.and_then(|m| m.due_ms)
|
||||
};
|
||||
assert_eq!(due(first), Some(1_610));
|
||||
assert_eq!(due(second), Some(3_220));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_link_does_not_delay_the_next_message() {
|
||||
let (mut city, a, b) = pair(LinkKind::SlowRadio);
|
||||
city.send(a, b, TrafficClass::Text, 200);
|
||||
city.tick(10_000);
|
||||
let id = city.send(a, b, TrafficClass::Text, 200);
|
||||
let message = city.messages.iter().find(|m| m.id == id).expect("message");
|
||||
assert_eq!(message.due_ms, Some(10_000 + 1_610));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backlog_can_push_a_message_past_its_ttl() {
|
||||
let (mut city, a, b) = pair(LinkKind::SlowRadio);
|
||||
for _ in 0..3 {
|
||||
city.send(a, b, TrafficClass::Text, 200);
|
||||
}
|
||||
let late = city.send_with_ttl(a, b, TrafficClass::Text, 200, 5_000);
|
||||
city.tick(5_000);
|
||||
let status = city
|
||||
.messages
|
||||
.iter()
|
||||
.find(|m| m.id == late)
|
||||
.expect("late")
|
||||
.status;
|
||||
assert_eq!(
|
||||
status,
|
||||
DeliveryState::Expired,
|
||||
"airtime backlog ate the TTL"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_text_never_consumes_slow_radio_airtime() {
|
||||
let (mut city, a, b) = pair(LinkKind::SlowRadio);
|
||||
let id = city.send(a, b, TrafficClass::Text, 5_000_000);
|
||||
let status = city
|
||||
.messages
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.expect("message")
|
||||
.status;
|
||||
assert_eq!(status, DeliveryState::Queued);
|
||||
assert_eq!(city.link_airtime_ms(LinkKind::SlowRadio), 0);
|
||||
assert_eq!(metrics::summarize(&city).slow_radio_airtime_ms, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn airtime_is_reported_per_link_kind() {
|
||||
let (mut city, a, b) = pair(LinkKind::SlowRadio);
|
||||
city.send(a, b, TrafficClass::Text, 200);
|
||||
assert_eq!(city.link_airtime_ms(LinkKind::SlowRadio), 1_610);
|
||||
assert_eq!(city.link_airtime_ms(LinkKind::Wired), 0);
|
||||
assert_eq!(metrics::summarize(&city).slow_radio_airtime_ms, 1_610);
|
||||
}
|
||||
140
workspace/crates/icenet-sim/tests/city.rs
Normal file
140
workspace/crates/icenet-sim/tests/city.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeliveryState, DeviceRole, metrics};
|
||||
|
||||
#[test]
|
||||
fn bulk_is_queued_when_only_slow_links_remain() {
|
||||
let mut city = City::demo();
|
||||
assert!(city.set_link_enabled(2, false));
|
||||
let id = city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
assert_eq!(
|
||||
city.messages.iter().find(|m| m.id == id).unwrap().status,
|
||||
DeliveryState::Queued
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_delivers_after_virtual_time_advance() {
|
||||
let mut city = City::demo();
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 50_000);
|
||||
city.tick(200_000);
|
||||
assert_eq!(city.messages[0].status, DeliveryState::Delivered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_message_recovers_when_fast_link_returns() {
|
||||
let mut city = City::demo();
|
||||
city.set_link_enabled(2, false);
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 100);
|
||||
assert_eq!(city.messages[0].status, DeliveryState::Queued);
|
||||
city.set_link_enabled(2, true);
|
||||
city.tick(1);
|
||||
assert_eq!(city.messages[0].status, DeliveryState::InFlight);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slower_link_kind_reschedules_an_in_flight_message() {
|
||||
let mut city = City::demo();
|
||||
let id = city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
let before = city.messages[0].due_ms.expect("scheduled");
|
||||
assert!(city.set_link_kind(3, LinkKind::Internet));
|
||||
city.tick(1);
|
||||
let after = city.messages[0].due_ms.expect("still scheduled");
|
||||
assert!(after > before, "due {after} must move past {before}");
|
||||
assert_eq!(city.messages[0].id, id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_route_timestamp_is_not_restamped_after_requeue() {
|
||||
let mut city = City::demo();
|
||||
assert!(city.set_link_enabled(2, false));
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 100);
|
||||
city.tick(1_000);
|
||||
assert!(city.set_link_enabled(2, true));
|
||||
city.tick(1);
|
||||
let first = city.messages[0].first_route_ms;
|
||||
assert_eq!(first, Some(1_001));
|
||||
assert!(city.set_link_enabled(2, false));
|
||||
city.tick(1);
|
||||
assert_eq!(city.messages[0].status, DeliveryState::Queued);
|
||||
assert!(city.set_link_enabled(2, true));
|
||||
city.tick(1);
|
||||
assert_eq!(city.messages[0].first_route_ms, first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_city_has_no_devices_links_or_messages() {
|
||||
let city = City::empty();
|
||||
assert!(city.devices.is_empty());
|
||||
assert!(city.links.is_empty());
|
||||
assert!(city.messages.is_empty());
|
||||
assert_eq!(city.now_ms, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_action_scripts_produce_byte_identical_exports() {
|
||||
let first = run_script();
|
||||
let second = run_script();
|
||||
assert_eq!(
|
||||
metrics::messages_csv(&first),
|
||||
metrics::messages_csv(&second)
|
||||
);
|
||||
assert_eq!(
|
||||
metrics::scenario_json(&first),
|
||||
metrics::scenario_json(&second)
|
||||
);
|
||||
assert_eq!(metrics::summarize(&first), metrics::summarize(&second));
|
||||
}
|
||||
|
||||
fn run_script() -> City {
|
||||
let mut city = City::demo();
|
||||
assert!(city.set_link_enabled(2, false));
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128);
|
||||
city.tick(1_000);
|
||||
assert!(city.set_link_enabled(2, true));
|
||||
city.tick(120_000);
|
||||
let extra = city.add_device("Extra".to_owned(), DeviceRole::Client);
|
||||
assert!(city.add_link(extra, NodeId(5), LinkKind::Internet));
|
||||
city.send_with_ttl(extra, NodeId(6), TrafficClass::Bulk, 1_000, 1);
|
||||
city.tick(10);
|
||||
city
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cutting_the_route_before_a_coarse_tick_never_yields_delivered() {
|
||||
let mut city = City::demo();
|
||||
let id = city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
for index in 0..city.links.len() {
|
||||
assert!(city.set_link_enabled(index, false));
|
||||
}
|
||||
// One huge step jumps far past `due_ms`; the cut still happened first.
|
||||
city.tick(1_000_000);
|
||||
let status = city.messages.iter().find(|m| m.id == id).unwrap().status;
|
||||
assert_eq!(status, DeliveryState::Queued);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn taking_a_relay_offline_before_arrival_does_not_deliver() {
|
||||
let mut city = City::demo();
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
assert!(city.set_device_online(NodeId(5), false));
|
||||
city.tick(1_000_000);
|
||||
assert_ne!(city.messages[0].status, DeliveryState::Delivered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_still_valid_route_is_delivered_normally_after_a_coarse_tick() {
|
||||
let mut city = City::demo();
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
city.tick(1_000_000);
|
||||
assert_eq!(city.messages[0].status, DeliveryState::Delivered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_that_is_repaired_before_the_tick_reroutes_without_false_delivery() {
|
||||
let mut city = City::demo();
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000);
|
||||
assert!(city.set_link_enabled(3, false));
|
||||
city.tick(1);
|
||||
assert_ne!(city.messages[0].status, DeliveryState::Delivered);
|
||||
}
|
||||
114
workspace/crates/icenet-sim/tests/metrics.rs
Normal file
114
workspace/crates/icenet-sim/tests/metrics.rs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
//! Deterministic metrics and export formats for offline experiments.
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeliveryState, metrics};
|
||||
|
||||
#[test]
|
||||
fn summary_counts_states_and_excludes_expired_from_delivery_ratio() {
|
||||
let mut city = City::demo();
|
||||
for index in [2, 3, 4] {
|
||||
assert!(city.set_link_enabled(index, false));
|
||||
}
|
||||
city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 1_000);
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128);
|
||||
city.tick(5_000);
|
||||
let summary = metrics::summarize(&city);
|
||||
assert_eq!(summary.created, 2);
|
||||
assert_eq!(summary.delivered, 1);
|
||||
assert_eq!(summary.expired, 1);
|
||||
assert_eq!(summary.queued, 0);
|
||||
assert!((summary.delivery_ratio() - 0.5).abs() < f64::EPSILON);
|
||||
assert!(summary.first_route_p50_ms.is_some());
|
||||
assert!(summary.first_route_p95_ms.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_rank_percentiles_are_deterministic() {
|
||||
let mut samples = [40, 10, 30, 20];
|
||||
assert_eq!(metrics::percentile(&mut samples, 50), Some(20));
|
||||
assert_eq!(metrics::percentile(&mut samples, 95), Some(40));
|
||||
assert_eq!(metrics::percentile(&mut [], 50), None);
|
||||
assert_eq!(metrics::percentile(&mut [7], 99), Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_airtime_is_counted_from_the_last_route() {
|
||||
let mut city = City::demo();
|
||||
let id = city.send(NodeId(1), NodeId(3), TrafficClass::Control, 100);
|
||||
city.tick(60_000);
|
||||
assert_eq!(status_of(&city, id), DeliveryState::Delivered);
|
||||
assert!(metrics::summarize(&city).control_airtime_ms > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_export_has_stable_header_and_one_row_per_message() {
|
||||
let mut city = City::demo();
|
||||
city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128);
|
||||
let csv = metrics::messages_csv(&city);
|
||||
let mut lines = csv.lines();
|
||||
assert_eq!(
|
||||
lines.next(),
|
||||
Some("id,from,to,class,bytes,status,created_ms,expires_ms,first_route_ms,due_ms,route")
|
||||
);
|
||||
assert_eq!(lines.clone().count(), 1);
|
||||
assert!(lines.next().is_some_and(|row| row.contains(",Text,")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_scenario_is_deterministic_and_escapes_labels() {
|
||||
let mut first = City::demo();
|
||||
first.devices[0].label = "A \"quoted\" \\ path".to_owned();
|
||||
first.send(NodeId(1), NodeId(3), TrafficClass::Text, 128);
|
||||
let mut second = first.clone();
|
||||
second.tick(1_000);
|
||||
|
||||
let first_json = metrics::scenario_json(&first);
|
||||
let first_again = metrics::scenario_json(&first);
|
||||
assert_eq!(first_json, first_again);
|
||||
assert!(first_json.contains(r#""label":"A \"quoted\" \\ path""#));
|
||||
assert!(first_json.contains(r#""status":"InFlight""#));
|
||||
assert!(second_json_after_tick(&second).contains("Delivered"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_escapes_control_characters() {
|
||||
let mut city = City::demo();
|
||||
city.devices[0].label = "a\u{1}b".to_owned();
|
||||
let json = metrics::scenario_json(&city);
|
||||
assert!(json.contains(r#""label":"a\u0001b""#), "json: {json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_uses_null_for_non_finite_coordinates() {
|
||||
let mut city = City::demo();
|
||||
city.devices[0].x = f32::NAN;
|
||||
city.devices[0].y = f32::INFINITY;
|
||||
let json = metrics::scenario_json(&city);
|
||||
assert!(json.contains("\"x\":null,\"y\":null"), "json: {json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_encodes_every_supported_link_kind() {
|
||||
for kind in [
|
||||
LinkKind::SlowRadio,
|
||||
LinkKind::FastWireless,
|
||||
LinkKind::Wired,
|
||||
LinkKind::Internet,
|
||||
] {
|
||||
let mut city = City::demo();
|
||||
city.links[0].kind = kind;
|
||||
let json = metrics::scenario_json(&city);
|
||||
assert!(json.contains(&format!("\"kind\":\"{kind:?}\"")));
|
||||
}
|
||||
}
|
||||
|
||||
fn status_of(city: &City, id: u64) -> DeliveryState {
|
||||
city.messages
|
||||
.iter()
|
||||
.find(|message| message.id == id)
|
||||
.expect("recorded message")
|
||||
.status
|
||||
}
|
||||
|
||||
fn second_json_after_tick(city: &City) -> String {
|
||||
metrics::scenario_json(city)
|
||||
}
|
||||
68
workspace/crates/icenet-sim/tests/scale.rs
Normal file
68
workspace/crates/icenet-sim/tests/scale.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
//! Scale smoke tests: 100 and 1000 virtual nodes on a deterministic grid.
|
||||
use std::time::Instant;
|
||||
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeliveryState, DeviceRole, metrics};
|
||||
|
||||
#[test]
|
||||
fn hundred_node_grid_delivers_bulk_with_full_ratio() {
|
||||
let mut city = grid(10, 10);
|
||||
let source = city.devices.first().expect("grid nodes").id;
|
||||
let destination = city.devices.last().expect("grid nodes").id;
|
||||
let id = city.send(source, destination, TrafficClass::Bulk, 5_000_000);
|
||||
city.tick(200_000);
|
||||
assert_eq!(status_of(&city, id), DeliveryState::Delivered);
|
||||
let summary = metrics::summarize(&city);
|
||||
assert_eq!(summary.created, 1);
|
||||
assert!((summary.delivery_ratio() - 1.0).abs() < f64::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thousand_node_grid_reports_route_latency() {
|
||||
let city = grid(40, 25);
|
||||
let nodes: Vec<NodeId> = city.devices.iter().map(|device| device.id).collect();
|
||||
let mut samples = Vec::with_capacity(200);
|
||||
let mut state = 0x2545_f491_4f6c_dd1d_u64;
|
||||
for _ in 0..200 {
|
||||
state = state
|
||||
.wrapping_mul(6_364_136_223_846_793_005)
|
||||
.wrapping_add(1);
|
||||
let from = nodes[(state as usize) % nodes.len()];
|
||||
let to = nodes[((state >> 32) as usize) % nodes.len()];
|
||||
let started = Instant::now();
|
||||
let path = city.route(from, to, TrafficClass::Text, 128);
|
||||
samples.push(u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX));
|
||||
assert!(path.is_some(), "grid must stay connected");
|
||||
}
|
||||
let p50 = metrics::percentile(&mut samples.clone(), 50).expect("samples");
|
||||
let p95 = metrics::percentile(&mut samples, 95).expect("samples");
|
||||
println!("1000-node route search (release-independent debug build): p50={p50}us p95={p95}us");
|
||||
assert!(p50 <= p95);
|
||||
}
|
||||
|
||||
fn grid(columns: usize, rows: usize) -> City {
|
||||
let mut city = City::empty();
|
||||
let ids: Vec<NodeId> = (0..columns * rows)
|
||||
.map(|index| city.add_device(format!("n{index}"), DeviceRole::Relay))
|
||||
.collect();
|
||||
for row in 0..rows {
|
||||
for column in 0..columns {
|
||||
let index = row * columns + column;
|
||||
if column + 1 < columns {
|
||||
assert!(city.add_link(ids[index], ids[index + 1], LinkKind::FastWireless));
|
||||
}
|
||||
if row + 1 < rows {
|
||||
assert!(city.add_link(ids[index], ids[index + columns], LinkKind::FastWireless));
|
||||
}
|
||||
}
|
||||
}
|
||||
city
|
||||
}
|
||||
|
||||
fn status_of(city: &City, id: u64) -> DeliveryState {
|
||||
city.messages
|
||||
.iter()
|
||||
.find(|message| message.id == id)
|
||||
.expect("recorded message")
|
||||
.status
|
||||
}
|
||||
83
workspace/crates/icenet-sim/tests/ttl.rs
Normal file
83
workspace/crates/icenet-sim/tests/ttl.rs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
//! Store-and-forward lifetime behaviour: queued work must expire, never fake delivery.
|
||||
use icenet_core::{NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeliveryState};
|
||||
|
||||
fn city_without_bulk_path() -> City {
|
||||
let mut city = City::demo();
|
||||
for index in [2, 3, 4] {
|
||||
assert!(city.set_link_enabled(index, false));
|
||||
}
|
||||
city
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_message_expires_after_its_ttl() {
|
||||
let mut city = city_without_bulk_path();
|
||||
let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 5_000);
|
||||
city.tick(4_999);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::Queued);
|
||||
city.tick(1);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_flight_message_expires_when_ttl_is_shorter_than_transfer() {
|
||||
let mut city = City::demo();
|
||||
let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 10);
|
||||
city.tick(11);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrival_at_expiry_is_delivered_but_one_ms_earlier_expires() {
|
||||
let mut delivered = City::demo();
|
||||
let estimate = delivered
|
||||
.route(NodeId(1), NodeId(3), TrafficClass::Text, 128)
|
||||
.expect("route")
|
||||
.estimated_ms;
|
||||
let id = delivered.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Text, 128, estimate);
|
||||
delivered.tick(estimate);
|
||||
assert_eq!(message_status(&delivered, id), DeliveryState::Delivered);
|
||||
|
||||
let mut expired = City::demo();
|
||||
let id = expired.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Text, 128, estimate - 1);
|
||||
expired.tick(estimate - 1);
|
||||
assert_eq!(message_status(&expired, id), DeliveryState::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_message_never_revives_when_a_path_returns() {
|
||||
let mut city = city_without_bulk_path();
|
||||
let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 1_000);
|
||||
city.tick(2_000);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::Expired);
|
||||
assert!(city.set_link_enabled(2, true));
|
||||
city.tick(60_000);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_ttl_gets_the_shortest_positive_lifetime() {
|
||||
let mut city = City::demo();
|
||||
let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Text, 128, 0);
|
||||
city.tick(0);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::InFlight);
|
||||
city.tick(1);
|
||||
assert_eq!(message_status(&city, id), DeliveryState::Expired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_send_uses_the_documented_default_ttl() {
|
||||
let mut city = City::demo();
|
||||
let id = city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128);
|
||||
let message = city.messages.iter().find(|m| m.id == id).expect("message");
|
||||
assert_eq!(message.expires_ms, City::DEFAULT_TTL_MS);
|
||||
}
|
||||
|
||||
fn message_status(city: &City, id: u64) -> DeliveryState {
|
||||
city.messages
|
||||
.iter()
|
||||
.find(|message| message.id == id)
|
||||
.expect("recorded message")
|
||||
.status
|
||||
}
|
||||
8
workspace/crates/icenet-transport/Cargo.toml
Normal file
8
workspace/crates/icenet-transport/Cargo.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "icenet-transport"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../icenet-core" }
|
||||
56
workspace/crates/icenet-transport/src/lib.rs
Normal file
56
workspace/crates/icenet-transport/src/lib.rs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
//! Dependency-free transport boundary, in-memory and UDP adapters.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
mod udp;
|
||||
pub use udp::UdpTransport;
|
||||
|
||||
/// Largest draft frame accepted by these adapters (payload cap plus wire header).
|
||||
pub const MAX_DATAGRAM_BYTES: usize = 4_096 + 14;
|
||||
|
||||
/// Errors produced by a transport implementation.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum TransportError {
|
||||
/// This implementation will not accept a frame of this size.
|
||||
TooLarge,
|
||||
/// The socket is temporarily unable to send or receive.
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// A small synchronous transport interface for early experiments.
|
||||
pub trait Transport {
|
||||
/// Sends one bounded frame; ownership moves into the transport.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if local transport limits reject this frame.
|
||||
fn send(&mut self, frame: Vec<u8>) -> Result<(), TransportError>;
|
||||
|
||||
/// Receives the next available frame without blocking.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `Unavailable` when the socket fails; `Ok(None)` means no frame
|
||||
/// is ready yet.
|
||||
fn recv(&mut self) -> Result<Option<Vec<u8>>, TransportError>;
|
||||
}
|
||||
|
||||
/// A loopback transport used only for controlled tests.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MemoryTransport {
|
||||
queue: VecDeque<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Transport for MemoryTransport {
|
||||
fn send(&mut self, frame: Vec<u8>) -> Result<(), TransportError> {
|
||||
if frame.len() > MAX_DATAGRAM_BYTES {
|
||||
return Err(TransportError::TooLarge);
|
||||
}
|
||||
self.queue.push_back(frame);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn recv(&mut self) -> Result<Option<Vec<u8>>, TransportError> {
|
||||
Ok(self.queue.pop_front())
|
||||
}
|
||||
}
|
||||
68
workspace/crates/icenet-transport/src/udp.rs
Normal file
68
workspace/crates/icenet-transport/src/udp.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
//! Non-blocking UDP adapter for one connected peer.
|
||||
use std::io;
|
||||
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
|
||||
|
||||
use crate::{MAX_DATAGRAM_BYTES, Transport, TransportError};
|
||||
|
||||
/// A non-blocking UDP socket connected to one peer address.
|
||||
#[derive(Debug)]
|
||||
pub struct UdpTransport {
|
||||
socket: UdpSocket,
|
||||
}
|
||||
|
||||
impl UdpTransport {
|
||||
/// Binds a local address and makes the socket non-blocking.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the underlying socket error when binding or configuration fails.
|
||||
pub fn bind(address: impl ToSocketAddrs) -> io::Result<Self> {
|
||||
let socket = UdpSocket::bind(address)?;
|
||||
socket.set_nonblocking(true)?;
|
||||
Ok(Self { socket })
|
||||
}
|
||||
|
||||
/// Connects this socket to one peer.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the underlying socket error when connecting fails.
|
||||
pub fn connect(self, peer: impl ToSocketAddrs) -> io::Result<Self> {
|
||||
self.socket.connect(peer)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Returns the local socket address, including an OS-assigned port.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the underlying socket error when the address is unavailable.
|
||||
pub fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
self.socket.local_addr()
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for UdpTransport {
|
||||
fn send(&mut self, frame: Vec<u8>) -> Result<(), TransportError> {
|
||||
if frame.len() > MAX_DATAGRAM_BYTES {
|
||||
return Err(TransportError::TooLarge);
|
||||
}
|
||||
match self.socket.send(&frame) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(TransportError::Unavailable),
|
||||
}
|
||||
}
|
||||
|
||||
fn recv(&mut self) -> Result<Option<Vec<u8>>, TransportError> {
|
||||
let mut buffer = [0_u8; MAX_DATAGRAM_BYTES];
|
||||
match self.socket.recv(&mut buffer) {
|
||||
Ok(size) => Ok(Some(buffer[..size].to_vec())),
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
Err(_) => Err(TransportError::Unavailable),
|
||||
}
|
||||
}
|
||||
}
|
||||
11
workspace/crates/icenet-transport/tests/memory.rs
Normal file
11
workspace/crates/icenet-transport/tests/memory.rs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
use icenet_transport::{MemoryTransport, Transport};
|
||||
|
||||
#[test]
|
||||
fn memory_transport_preserves_frame_order() {
|
||||
let mut transport = MemoryTransport::default();
|
||||
transport.send(vec![1]).unwrap();
|
||||
transport.send(vec![2]).unwrap();
|
||||
assert_eq!(transport.recv(), Ok(Some(vec![1])));
|
||||
assert_eq!(transport.recv(), Ok(Some(vec![2])));
|
||||
assert_eq!(transport.recv(), Ok(None));
|
||||
}
|
||||
45
workspace/crates/icenet-transport/tests/udp.rs
Normal file
45
workspace/crates/icenet-transport/tests/udp.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
use std::time::{Duration, Instant};
|
||||
|
||||
use icenet_transport::{Transport, TransportError, UdpTransport};
|
||||
|
||||
fn connected_pair() -> (UdpTransport, UdpTransport) {
|
||||
let first = UdpTransport::bind("127.0.0.1:0").expect("bind first");
|
||||
let second = UdpTransport::bind("127.0.0.1:0").expect("bind second");
|
||||
let first_addr = first.local_addr().expect("first address");
|
||||
let second_addr = second.local_addr().expect("second address");
|
||||
(
|
||||
first.connect(second_addr).expect("connect first"),
|
||||
second.connect(first_addr).expect("connect second"),
|
||||
)
|
||||
}
|
||||
|
||||
fn receive(transport: &mut UdpTransport) -> Vec<u8> {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < deadline {
|
||||
if let Some(frame) = transport.recv().expect("recv") {
|
||||
return frame;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
panic!("no UDP frame within the deadline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_transport_round_trips_frames() {
|
||||
let (mut first, mut second) = connected_pair();
|
||||
first.send(b"hello over udp".to_vec()).expect("send");
|
||||
assert_eq!(receive(&mut second), b"hello over udp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_transport_rejects_oversized_frames() {
|
||||
let (mut first, _second) = connected_pair();
|
||||
let oversized = vec![0; 8_192];
|
||||
assert_eq!(first.send(oversized), Err(TransportError::TooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_udp_socket_returns_no_frame() {
|
||||
let (mut first, _second) = connected_pair();
|
||||
assert_eq!(first.recv().expect("recv"), None);
|
||||
}
|
||||
8
workspace/crates/icenet-wire/Cargo.toml
Normal file
8
workspace/crates/icenet-wire/Cargo.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "icenet-wire"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../icenet-core" }
|
||||
106
workspace/crates/icenet-wire/src/lib.rs
Normal file
106
workspace/crates/icenet-wire/src/lib.rs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
//! An intentionally minimal, unauthenticated wire-format experiment.
|
||||
//!
|
||||
//! Do not use this framing for live, untrusted network traffic before review.
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use icenet_core::{ServiceId, TrafficClass};
|
||||
|
||||
/// Magic bytes of the experimental frame layout.
|
||||
pub const MAGIC: [u8; 2] = *b"IN";
|
||||
/// The current (experimental) wire layout version.
|
||||
pub const VERSION: u8 = 1;
|
||||
/// Maximum application payload of one example frame.
|
||||
pub const MAX_PAYLOAD_BYTES: usize = 4_096;
|
||||
const HEADER_BYTES: usize = 14;
|
||||
|
||||
/// A bounded message frame.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Frame {
|
||||
/// The class assigned to this payload.
|
||||
pub class: TrafficClass,
|
||||
/// Destination service on a remote node.
|
||||
pub service: ServiceId,
|
||||
/// Application payload, not encrypted by this crate.
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Parse or serialization errors.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FrameError {
|
||||
/// Insufficient bytes for the header or declared payload.
|
||||
Truncated,
|
||||
/// The magic marker or protocol version is not recognized.
|
||||
InvalidHeader,
|
||||
/// Class byte is not recognized.
|
||||
InvalidClass,
|
||||
/// A frame exceeded the configured size budget.
|
||||
TooLarge,
|
||||
/// Additional bytes follow the declared payload.
|
||||
TrailingBytes,
|
||||
}
|
||||
|
||||
/// Serializes an experimental frame with a checked payload cap.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `TooLarge` when the payload exceeds the configured limit.
|
||||
pub fn encode(frame: &Frame) -> Result<Vec<u8>, FrameError> {
|
||||
if frame.payload.len() > MAX_PAYLOAD_BYTES {
|
||||
return Err(FrameError::TooLarge);
|
||||
}
|
||||
let class = match frame.class {
|
||||
TrafficClass::Control => 0,
|
||||
TrafficClass::Text => 1,
|
||||
TrafficClass::Bulk => 2,
|
||||
};
|
||||
let mut bytes = Vec::with_capacity(HEADER_BYTES + frame.payload.len());
|
||||
bytes.extend(MAGIC);
|
||||
bytes.push(VERSION);
|
||||
bytes.push(class);
|
||||
bytes.extend(frame.service.0.to_be_bytes());
|
||||
let length = u16::try_from(frame.payload.len()).map_err(|_| FrameError::TooLarge)?;
|
||||
bytes.extend(length.to_be_bytes());
|
||||
bytes.extend(&frame.payload);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Parses an experimental frame, rejecting malformed and oversized packets.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a typed error for malformed or unsupported input.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Frame, FrameError> {
|
||||
if bytes.len() < HEADER_BYTES {
|
||||
return Err(FrameError::Truncated);
|
||||
}
|
||||
if &bytes[0..2] != MAGIC.as_slice() || bytes[2] != VERSION {
|
||||
return Err(FrameError::InvalidHeader);
|
||||
}
|
||||
let class = match bytes[3] {
|
||||
0 => TrafficClass::Control,
|
||||
1 => TrafficClass::Text,
|
||||
2 => TrafficClass::Bulk,
|
||||
_ => return Err(FrameError::InvalidClass),
|
||||
};
|
||||
let service = ServiceId(u64::from_be_bytes(
|
||||
bytes[4..12].try_into().map_err(|_| FrameError::Truncated)?,
|
||||
));
|
||||
let count = usize::from(u16::from_be_bytes(
|
||||
bytes[12..14]
|
||||
.try_into()
|
||||
.map_err(|_| FrameError::Truncated)?,
|
||||
));
|
||||
if count > MAX_PAYLOAD_BYTES {
|
||||
return Err(FrameError::TooLarge);
|
||||
}
|
||||
if bytes.len() < HEADER_BYTES + count {
|
||||
return Err(FrameError::Truncated);
|
||||
}
|
||||
if bytes.len() > HEADER_BYTES + count {
|
||||
return Err(FrameError::TrailingBytes);
|
||||
}
|
||||
Ok(Frame {
|
||||
class,
|
||||
service,
|
||||
payload: bytes[HEADER_BYTES..].to_vec(),
|
||||
})
|
||||
}
|
||||
36
workspace/crates/icenet-wire/tests/frames.rs
Normal file
36
workspace/crates/icenet-wire/tests/frames.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
use icenet_core::{ServiceId, TrafficClass};
|
||||
use icenet_wire::{Frame, FrameError, MAX_PAYLOAD_BYTES, decode, encode};
|
||||
|
||||
#[test]
|
||||
fn frame_round_trip() {
|
||||
let frame = Frame {
|
||||
class: TrafficClass::Text,
|
||||
service: ServiceId(77_777),
|
||||
payload: b"hello".to_vec(),
|
||||
};
|
||||
let packed = encode(&frame).expect("valid frame");
|
||||
assert_eq!(decode(&packed), Ok(frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_lengths_and_invalid_classes() {
|
||||
assert_eq!(decode(b"hi"), Err(FrameError::Truncated));
|
||||
let mut frame = encode(&Frame {
|
||||
class: TrafficClass::Control,
|
||||
service: ServiceId(1),
|
||||
payload: vec![],
|
||||
})
|
||||
.unwrap();
|
||||
frame[3] = 255;
|
||||
assert_eq!(decode(&frame), Err(FrameError::InvalidClass));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_oversized_payload() {
|
||||
let frame = Frame {
|
||||
class: TrafficClass::Bulk,
|
||||
service: ServiceId(1),
|
||||
payload: vec![0; MAX_PAYLOAD_BYTES + 1],
|
||||
};
|
||||
assert_eq!(encode(&frame), Err(FrameError::TooLarge));
|
||||
}
|
||||
60
workspace/crates/icenet-wire/tests/fuzz.rs
Normal file
60
workspace/crates/icenet-wire/tests/fuzz.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
//! Deterministic parser smoke-fuzz: random bytes must never panic.
|
||||
use icenet_core::{ServiceId, TrafficClass};
|
||||
use icenet_wire::{Frame, FrameError, MAX_PAYLOAD_BYTES, decode, encode};
|
||||
|
||||
#[test]
|
||||
fn random_bytes_never_panic() {
|
||||
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
|
||||
for _ in 0..10_000 {
|
||||
state = next(state);
|
||||
let length = usize::try_from(state % 96).expect("small length");
|
||||
let mut bytes = Vec::with_capacity(length);
|
||||
for _ in 0..length {
|
||||
state = next(state);
|
||||
bytes.push((state >> 24) as u8);
|
||||
}
|
||||
if let Ok(frame) = decode(&bytes) {
|
||||
assert!(frame.payload.len() <= MAX_PAYLOAD_BYTES);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_frames_round_trip_at_payload_boundaries() {
|
||||
for size in [0, 1, 4_095, MAX_PAYLOAD_BYTES] {
|
||||
let frame = Frame {
|
||||
class: TrafficClass::Bulk,
|
||||
service: ServiceId(42),
|
||||
payload: vec![0xab; size],
|
||||
};
|
||||
let bytes = encode(&frame).expect("boundary frame encodes");
|
||||
assert_eq!(decode(&bytes), Ok(frame));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_headers_and_trailing_bytes_are_rejected() {
|
||||
let frame = Frame {
|
||||
class: TrafficClass::Text,
|
||||
service: ServiceId(7),
|
||||
payload: b"hello".to_vec(),
|
||||
};
|
||||
let valid = encode(&frame).expect("frame");
|
||||
let mut bad_magic = valid.clone();
|
||||
bad_magic[0] = b'X';
|
||||
assert_eq!(decode(&bad_magic), Err(FrameError::InvalidHeader));
|
||||
|
||||
let mut bad_version = valid.clone();
|
||||
bad_version[2] = 99;
|
||||
assert_eq!(decode(&bad_version), Err(FrameError::InvalidHeader));
|
||||
|
||||
let mut trailing = valid;
|
||||
trailing.push(0);
|
||||
assert_eq!(decode(&trailing), Err(FrameError::TrailingBytes));
|
||||
}
|
||||
|
||||
fn next(state: u64) -> u64 {
|
||||
state
|
||||
.wrapping_mul(6_364_136_223_846_793_005)
|
||||
.wrapping_add(1_442_695_040_888_963_407)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue