Initial import: ICE-NET research docs and Rust workspace (v0.4)
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:
Loki 2026-11-13 12:28:48 +01:00
commit 2e61688eb3
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
141 changed files with 13993 additions and 0 deletions

View 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" }

View 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
}
}

View 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)
}
}

View 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();
}
}

View 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};

View 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
}

View 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)
}

View 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>,
}

View 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,
}
}
}

View 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);
}

View 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);
}

View 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)
}

View 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
}

View 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
}