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
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue