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/.gitignore
vendored
Normal file
7
workspace/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
/target/
|
||||
**/*.rs.bk
|
||||
*.log
|
||||
.env
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
5424
workspace/Cargo.lock
generated
Normal file
5424
workspace/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
16
workspace/Cargo.toml
Normal file
16
workspace/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*", "apps/*"]
|
||||
default-members = ["crates/icenet-sim", "apps/icenetd"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
license = "LGPL-3.0-or-later"
|
||||
|
||||
[profile.dev]
|
||||
debug = 1
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
32
workspace/README.md
Normal file
32
workspace/README.md
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
# ICE-NET Rust workspace
|
||||
|
||||
Исследовательский каркас, а не работающий сетевой протокол. Два приложения:
|
||||
`icenet-city` (GUI графового эмулятора на Slint) и `icenetd` (CLI: route/send/sim/policy/wire
|
||||
и UDP `serve`/`send-udp`). Что проверено и какие цифры — в [../docs/STATUS.md](../docs/STATUS.md).
|
||||
|
||||
## Запуск на Arch
|
||||
|
||||
```bash
|
||||
rustup default stable # toolchain закреплён в rust-toolchain.toml
|
||||
cd workspace
|
||||
python3 tools/check_layout.py
|
||||
cargo test -p icenet-sim -p icenet-routing
|
||||
cargo run -p icenet-city # нужна графическая сессия
|
||||
```
|
||||
|
||||
## Карта зависимостей
|
||||
|
||||
`core` → `wire`, `guard`, `routing`, `transport` → `sdk` → `icenetd`
|
||||
|
||||
`core + routing` → `sim` → `icenet-city`, `icenetd`
|
||||
|
||||
`icenet-transport` содержит `MemoryTransport` (тесты) и неблокирующий `UdpTransport` на
|
||||
`std::net`; loopback-тесты в `tests/udp.rs`.
|
||||
|
||||
Тесты **не** внутри `src`, а в `tests/` каждого крейта. Лицензия: LGPL-3.0-or-later (`../LICENSE`).
|
||||
|
||||
## Зависимости
|
||||
|
||||
Прямые внешние: `slint` (runtime) и `slint-build` (build-time) только в `icenet-city`;
|
||||
остальные крейты без внешних библиотек. `cargo test --workspace` собирает и Slint; для быстрой
|
||||
проверки алгоритмов выбирай конкретные пакеты. `Cargo.lock` коммитится.
|
||||
16
workspace/apps/icenet-city/Cargo.toml
Normal file
16
workspace/apps/icenet-city/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "icenet-city"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
build = "build.rs"
|
||||
|
||||
[dependencies]
|
||||
icenet-core = { path = "../../crates/icenet-core" }
|
||||
icenet-sim = { path = "../../crates/icenet-sim" }
|
||||
slint = { version = "=1.18.1", default-features = false, features = [
|
||||
"std", "backend-winit", "renderer-software", "compat-1-18",
|
||||
] }
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "=1.18.1"
|
||||
6
workspace/apps/icenet-city/build.rs
Normal file
6
workspace/apps/icenet-city/build.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
//! Compile the declarative interface without including GUI code in domain crates.
|
||||
|
||||
/// Compiles the Slint UI into generated Rust bindings.
|
||||
fn main() {
|
||||
slint_build::compile("ui/main.slint").expect("Slint UI compilation failed");
|
||||
}
|
||||
5
workspace/apps/icenet-city/src/lib.rs
Normal file
5
workspace/apps/icenet-city/src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Slint application adapter for the deterministic ICE-NET city simulator.
|
||||
pub mod state;
|
||||
pub mod view;
|
||||
|
||||
slint::include_modules!();
|
||||
119
workspace/apps/icenet-city/src/main.rs
Normal file
119
workspace/apps/icenet-city/src/main.rs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
//! Standalone Slint GUI for offline ICE-NET city routing experiments.
|
||||
use icenet_city::{CityWindow, state::UiState, view};
|
||||
use slint::{ComponentHandle, Weak};
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
/// Performs a state command and refreshes the window, if it still exists.
|
||||
fn apply(weak: &Weak<CityWindow>, state: &Rc<RefCell<UiState>>, change: impl FnOnce(&mut UiState)) {
|
||||
let mut state = state.borrow_mut();
|
||||
change(&mut state);
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
view::refresh(&ui, &state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers UI callbacks without allowing the simulator to depend on Slint.
|
||||
fn register_callbacks(ui: &CityWindow, state: Rc<RefCell<UiState>>) {
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_send_text(move || apply(&weak, &state, |s| s.send(false)));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_send_photo(move || apply(&weak, &state, |s| s.send(true)));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_export_csv(move || apply(&weak, &state, UiState::export_default_csv));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_export_json(move || apply(&weak, &state, UiState::export_default_json));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_next_from(move || apply(&weak, &state, |s| s.cycle_endpoint(true)));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_next_to(move || apply(&weak, &state, |s| s.cycle_endpoint(false)));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_next_role(move || apply(&weak, &state, UiState::cycle_role));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_next_link_kind(move || apply(&weak, &state, UiState::cycle_link_kind));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_add_node(move || apply(&weak, &state, UiState::add_node));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_connect_nodes(move || apply(&weak, &state, UiState::connect));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_toggle_node(move |id| apply(&weak, &state, |s| s.toggle_node(id)));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_toggle_link(move |index| apply(&weak, &state, |s| s.toggle_link(index)));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
ui.on_drag_start(move |id, x, y| state.borrow_mut().start_drag(id, x, y));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_drag_move(move |x, y| {
|
||||
let mut state = state.borrow_mut();
|
||||
state.drag_to(x, y);
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
view::drag(&ui, &state);
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_drag_end(move || apply(&weak, &state, UiState::end_drag));
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let weak = ui.as_weak();
|
||||
ui.on_advance(move |elapsed| {
|
||||
apply(&weak, &state, |s| {
|
||||
s.city.tick(u64::try_from(elapsed).unwrap_or(0));
|
||||
})
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = ui.as_weak();
|
||||
ui.on_reset_city(move || apply(&weak, &state, |s| *s = UiState::default()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the desktop simulator. The event loop is owned by Slint.
|
||||
fn main() -> Result<(), slint::PlatformError> {
|
||||
let ui = CityWindow::new()?;
|
||||
let state = Rc::new(RefCell::new(UiState::default()));
|
||||
view::refresh(&ui, &state.borrow());
|
||||
register_callbacks(&ui, state);
|
||||
ui.run()
|
||||
}
|
||||
194
workspace/apps/icenet-city/src/state.rs
Normal file
194
workspace/apps/icenet-city/src/state.rs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
//! GUI-independent commands applied to the city simulator.
|
||||
use std::{io, path::Path};
|
||||
|
||||
use icenet_core::{LinkKind, NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeviceRole, metrics};
|
||||
|
||||
const CSV_FILE: &str = "icenet-metrics.csv";
|
||||
const JSON_FILE: &str = "icenet-scenario.json";
|
||||
|
||||
/// Grab state for stable pointer dragging of one node.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Drag {
|
||||
id: NodeId,
|
||||
node_x: f32,
|
||||
node_y: f32,
|
||||
pointer_x: f32,
|
||||
pointer_y: f32,
|
||||
}
|
||||
|
||||
/// Mutable state of the standalone city editor.
|
||||
#[derive(Debug)]
|
||||
pub struct UiState {
|
||||
/// Deterministic offline city graph.
|
||||
pub city: City,
|
||||
/// Current sender in the sample graph.
|
||||
pub from: NodeId,
|
||||
/// Current recipient in the sample graph.
|
||||
pub to: NodeId,
|
||||
/// New node role selected in the editor.
|
||||
pub role: DeviceRole,
|
||||
/// New link technology selected in the editor.
|
||||
pub link_kind: LinkKind,
|
||||
/// Human-readable result of the last export action.
|
||||
pub last_export: String,
|
||||
drag: Option<Drag>,
|
||||
}
|
||||
|
||||
impl Default for UiState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
city: City::demo(),
|
||||
from: NodeId(1),
|
||||
to: NodeId(3),
|
||||
role: DeviceRole::Client,
|
||||
link_kind: LinkKind::FastWireless,
|
||||
last_export: String::new(),
|
||||
drag: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
/// Cycles through available sender or recipient IDs.
|
||||
pub fn cycle_endpoint(&mut self, sender: bool) {
|
||||
let current = if sender { self.from } else { self.to };
|
||||
let ids: Vec<NodeId> = self.city.devices.iter().map(|d| d.id).collect();
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let index = ids.iter().position(|id| *id == current).unwrap_or(0);
|
||||
let next = ids[(index + 1) % ids.len()];
|
||||
if sender {
|
||||
self.from = next;
|
||||
} else {
|
||||
self.to = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Cycles among client, relay and backbone device roles.
|
||||
pub fn cycle_role(&mut self) {
|
||||
self.role = match self.role {
|
||||
DeviceRole::Client => DeviceRole::Relay,
|
||||
DeviceRole::Relay => DeviceRole::Backbone,
|
||||
DeviceRole::Backbone => DeviceRole::Client,
|
||||
};
|
||||
}
|
||||
|
||||
/// Cycles among simulated radio, Wi-Fi, cable and internet links.
|
||||
pub fn cycle_link_kind(&mut self) {
|
||||
self.link_kind = match self.link_kind {
|
||||
LinkKind::SlowRadio => LinkKind::FastWireless,
|
||||
LinkKind::FastWireless => LinkKind::Wired,
|
||||
LinkKind::Wired => LinkKind::Internet,
|
||||
LinkKind::Internet => LinkKind::SlowRadio,
|
||||
};
|
||||
}
|
||||
|
||||
/// Adds a new device and selects it as recipient.
|
||||
pub fn add_node(&mut self) {
|
||||
let label = format!("New {:?} {}", self.role, self.city.devices.len() + 1);
|
||||
self.to = self.city.add_device(label, self.role);
|
||||
}
|
||||
|
||||
/// Adds a link between the selected endpoints, if valid.
|
||||
pub fn connect(&mut self) {
|
||||
self.city.add_link(self.from, self.to, self.link_kind);
|
||||
}
|
||||
|
||||
/// Toggles a device's online state.
|
||||
pub fn toggle_node(&mut self, id: i32) {
|
||||
let update = self
|
||||
.city
|
||||
.devices
|
||||
.iter()
|
||||
.find(|d| d.id.0 == id as u64)
|
||||
.map(|device| (device.id, !device.online));
|
||||
if let Some((id, online)) = update {
|
||||
self.city.set_device_online(id, online);
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles a link by its visible index.
|
||||
pub fn toggle_link(&mut self, index: i32) {
|
||||
if let Ok(index) = usize::try_from(index)
|
||||
&& let Some(enabled) = self.city.links.get(index).map(|link| !link.enabled)
|
||||
{
|
||||
self.city.set_link_enabled(index, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remembers the node and pointer position when a drag begins.
|
||||
pub fn start_drag(&mut self, id: i32, pointer_x: f32, pointer_y: f32) {
|
||||
let id = NodeId(id as u64);
|
||||
if let Some(device) = self.city.devices.iter().find(|device| device.id == id) {
|
||||
self.drag = Some(Drag {
|
||||
id,
|
||||
node_x: device.x,
|
||||
node_y: device.y,
|
||||
pointer_x,
|
||||
pointer_y,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the grabbed node by the pointer delta from the drag start.
|
||||
pub fn drag_to(&mut self, pointer_x: f32, pointer_y: f32) {
|
||||
if let Some(drag) = self.drag {
|
||||
self.city.move_device(
|
||||
drag.id,
|
||||
(drag.node_x + pointer_x - drag.pointer_x).clamp(20.0, 520.0),
|
||||
(drag.node_y + pointer_y - drag.pointer_y).clamp(20.0, 310.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases the current drag, if any.
|
||||
pub fn end_drag(&mut self) {
|
||||
self.drag = None;
|
||||
}
|
||||
|
||||
/// Sends synthetic text or bulk data; no real bytes leave this process.
|
||||
pub fn send(&mut self, bulk: bool) {
|
||||
let (kind, size) = if bulk {
|
||||
(TrafficClass::Bulk, 5 * 1024 * 1024)
|
||||
} else {
|
||||
(TrafficClass::Text, 128)
|
||||
};
|
||||
self.city.send(self.from, self.to, kind, size);
|
||||
}
|
||||
|
||||
/// Writes deterministic message metrics to `path`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the underlying I/O error when the file cannot be written.
|
||||
pub fn export_csv(&mut self, path: &Path) -> io::Result<()> {
|
||||
std::fs::write(path, metrics::messages_csv(&self.city))?;
|
||||
self.last_export = format!("Exported {}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the full scenario to `path` as deterministic JSON.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the underlying I/O error when the file cannot be written.
|
||||
pub fn export_json(&mut self, path: &Path) -> io::Result<()> {
|
||||
std::fs::write(path, metrics::scenario_json(&self.city))?;
|
||||
self.last_export = format!("Exported {}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes `icenet-metrics.csv` in the process working directory.
|
||||
pub fn export_default_csv(&mut self) {
|
||||
if let Err(error) = self.export_csv(Path::new(CSV_FILE)) {
|
||||
self.last_export = format!("Export failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `icenet-scenario.json` in the process working directory.
|
||||
pub fn export_default_json(&mut self) {
|
||||
if let Err(error) = self.export_json(Path::new(JSON_FILE)) {
|
||||
self.last_export = format!("Export failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
140
workspace/apps/icenet-city/src/view.rs
Normal file
140
workspace/apps/icenet-city/src/view.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
//! Translate simulation state into Slint models without introducing UI into core crates.
|
||||
use crate::{CityWindow, UiLink, UiNode, state::UiState};
|
||||
use icenet_core::NodeId;
|
||||
use icenet_sim::{City, DeliveryState};
|
||||
use slint::{Color, Model, VecModel};
|
||||
|
||||
/// Updates node and link rows in place so an active drag is not interrupted.
|
||||
pub fn drag(ui: &CityWindow, state: &UiState) {
|
||||
if let Some(nodes) = ui.get_nodes().as_any().downcast_ref::<VecModel<UiNode>>() {
|
||||
for (index, device) in state.city.devices.iter().enumerate() {
|
||||
let Some(mut node) = nodes.row_data(index) else {
|
||||
continue;
|
||||
};
|
||||
node.px = device.x;
|
||||
node.py = device.y;
|
||||
nodes.set_row_data(index, node);
|
||||
}
|
||||
}
|
||||
if let Some(links) = ui.get_links().as_any().downcast_ref::<VecModel<UiLink>>() {
|
||||
for (index, link) in state.city.links.iter().enumerate() {
|
||||
let Some(mut row) = links.row_data(index) else {
|
||||
continue;
|
||||
};
|
||||
let (Some(a), Some(b)) = (device(&state.city, link.a), device(&state.city, link.b))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
row.ax = a.x;
|
||||
row.ay = a.y;
|
||||
row.bx = b.x;
|
||||
row.by = b.y;
|
||||
links.set_row_data(index, row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn device(city: &City, id: NodeId) -> Option<&icenet_sim::Device> {
|
||||
city.devices.iter().find(|device| device.id == id)
|
||||
}
|
||||
|
||||
/// Applies one immutable simulator snapshot to the Slint window.
|
||||
pub fn refresh(ui: &CityWindow, state: &UiState) {
|
||||
let route = state
|
||||
.city
|
||||
.messages
|
||||
.last()
|
||||
.map(|m| m.route.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
let nodes: Vec<UiNode> = state
|
||||
.city
|
||||
.devices
|
||||
.iter()
|
||||
.map(|device| UiNode {
|
||||
id: device.id.0 as i32,
|
||||
label: device.label.as_str().into(),
|
||||
px: device.x,
|
||||
py: device.y,
|
||||
online: device.online,
|
||||
})
|
||||
.collect();
|
||||
ui.set_nodes(VecModel::from_slice(&nodes));
|
||||
|
||||
let links: Vec<UiLink> = state
|
||||
.city
|
||||
.links
|
||||
.iter()
|
||||
.map(|link| {
|
||||
let a = state.city.devices.iter().find(|d| d.id == link.a);
|
||||
let b = state.city.devices.iter().find(|d| d.id == link.b);
|
||||
let (ax, ay, bx, by) = match (a, b) {
|
||||
(Some(a), Some(b)) => (a.x, a.y, b.x, b.y),
|
||||
_ => (0.0, 0.0, 0.0, 0.0),
|
||||
};
|
||||
let enabled =
|
||||
link.enabled && a.is_some_and(|n| n.online) && b.is_some_and(|n| n.online);
|
||||
let highlighted = route
|
||||
.windows(2)
|
||||
.any(|hop| hop == [link.a, link.b] || hop == [link.b, link.a]);
|
||||
UiLink {
|
||||
ax,
|
||||
ay,
|
||||
bx,
|
||||
by,
|
||||
title: format!("{} — {} / {}", link.a.0, link.b.0, link.kind.label()).into(),
|
||||
enabled,
|
||||
highlighted,
|
||||
color: if !enabled {
|
||||
Color::from_rgb_u8(78, 88, 99)
|
||||
} else {
|
||||
link_color(link.kind.label())
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
ui.set_links(VecModel::from_slice(&links));
|
||||
|
||||
let messages: Vec<slint::SharedString> = state
|
||||
.city
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.take(12)
|
||||
.map(|message| {
|
||||
let status = match message.status {
|
||||
DeliveryState::Queued => "QUEUED",
|
||||
DeliveryState::InFlight => "IN_FLIGHT",
|
||||
DeliveryState::Delivered => "DELIVERED",
|
||||
DeliveryState::Expired => "EXPIRED",
|
||||
};
|
||||
format!(
|
||||
"#{} {} → {} | {:?} | {}",
|
||||
message.id, message.from.0, message.to.0, message.class, status
|
||||
)
|
||||
.into()
|
||||
})
|
||||
.collect();
|
||||
ui.set_messages(VecModel::from_slice(&messages));
|
||||
ui.set_clock(format!("Virtual clock: {} ms", state.city.now_ms).into());
|
||||
ui.set_from_label(endpoint_name(&state.city, state.from).into());
|
||||
ui.set_to_label(endpoint_name(&state.city, state.to).into());
|
||||
ui.set_role_label(format!("Role: {:?}", state.role).into());
|
||||
ui.set_link_label(format!("New link: {}", state.link_kind.label()).into());
|
||||
ui.set_export_status(state.last_export.as_str().into());
|
||||
}
|
||||
|
||||
fn endpoint_name(city: &City, id: NodeId) -> String {
|
||||
city.devices.iter().find(|n| n.id == id).map_or_else(
|
||||
|| format!("#{:?}", id.0),
|
||||
|n| format!("{} (#{})", n.label, id.0),
|
||||
)
|
||||
}
|
||||
|
||||
fn link_color(kind: &str) -> Color {
|
||||
match kind {
|
||||
"LoRa (slow)" => Color::from_rgb_u8(230, 177, 94),
|
||||
"Wi-Fi (fast)" => Color::from_rgb_u8(89, 174, 250),
|
||||
"Wired" => Color::from_rgb_u8(73, 222, 164),
|
||||
_ => Color::from_rgb_u8(195, 145, 255),
|
||||
}
|
||||
}
|
||||
11
workspace/apps/icenet-city/tests/smoke.rs
Normal file
11
workspace/apps/icenet-city/tests/smoke.rs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
use icenet_core::{NodeId, TrafficClass};
|
||||
use icenet_sim::City;
|
||||
|
||||
#[test]
|
||||
fn city_example_contains_bulk_eligible_route() {
|
||||
let city = City::demo();
|
||||
assert!(
|
||||
city.route(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000)
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
100
workspace/apps/icenet-city/tests/state.rs
Normal file
100
workspace/apps/icenet-city/tests/state.rs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
//! Regression tests for UI commands with no graphical backend.
|
||||
use icenet_city::state::UiState;
|
||||
use icenet_core::{NodeId, TrafficClass};
|
||||
use icenet_sim::DeliveryState;
|
||||
|
||||
#[test]
|
||||
fn photo_avoids_slow_radio_after_fast_links_are_disabled() {
|
||||
let mut app = UiState::default();
|
||||
for index in [2, 3, 4, 5] {
|
||||
app.city.set_link_enabled(index, false);
|
||||
}
|
||||
app.send(true);
|
||||
assert_eq!(
|
||||
app.city.messages.last().unwrap().status,
|
||||
DeliveryState::Queued
|
||||
);
|
||||
assert!(
|
||||
app.city
|
||||
.route(NodeId(1), NodeId(3), TrafficClass::Text, 128)
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_a_device_and_restarting_are_deterministic() {
|
||||
let mut app = UiState::default();
|
||||
app.toggle_node(2);
|
||||
assert!(
|
||||
!app.city
|
||||
.devices
|
||||
.iter()
|
||||
.find(|d| d.id == NodeId(2))
|
||||
.unwrap()
|
||||
.online
|
||||
);
|
||||
app = UiState::default();
|
||||
assert!(app.city.devices.iter().all(|d| d.online));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_adds_a_link_and_cycles_endpoints() {
|
||||
let mut app = UiState::default();
|
||||
app.add_node();
|
||||
assert_eq!(app.to, NodeId(7));
|
||||
app.connect();
|
||||
assert!(
|
||||
app.city
|
||||
.links
|
||||
.iter()
|
||||
.any(|link| link.a == NodeId(1) && link.b == NodeId(7))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_uses_a_fixed_start_pointer_offset() {
|
||||
let mut app = UiState::default();
|
||||
app.start_drag(1, 409.0, 186.0);
|
||||
app.drag_to(470.0, 240.0);
|
||||
app.drag_to(530.0, 290.0);
|
||||
let node = app
|
||||
.city
|
||||
.devices
|
||||
.iter()
|
||||
.find(|device| device.id == NodeId(1))
|
||||
.expect("demo node");
|
||||
assert!((node.x - 191.0).abs() < f32::EPSILON);
|
||||
assert!((node.y - 189.0).abs() < f32::EPSILON);
|
||||
app.end_drag();
|
||||
app.drag_to(0.0, 0.0);
|
||||
let node = app
|
||||
.city
|
||||
.devices
|
||||
.iter()
|
||||
.find(|device| device.id == NodeId(1))
|
||||
.expect("demo node");
|
||||
assert!((node.x - 191.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_csv_and_json_to_requested_paths() {
|
||||
let mut app = UiState::default();
|
||||
app.send(false);
|
||||
let stamp = format!("icenet-test-{}", std::process::id());
|
||||
let csv_path = std::env::temp_dir().join(format!("{stamp}.csv"));
|
||||
let json_path = std::env::temp_dir().join(format!("{stamp}.json"));
|
||||
|
||||
app.export_csv(&csv_path).expect("csv export");
|
||||
let csv = std::fs::read_to_string(&csv_path).expect("read csv");
|
||||
assert!(csv.starts_with("id,from,to,class,bytes,status,"));
|
||||
assert_eq!(csv.lines().count(), 2);
|
||||
assert!(app.last_export.contains(&stamp));
|
||||
|
||||
app.export_json(&json_path).expect("json export");
|
||||
let json = std::fs::read_to_string(&json_path).expect("read json");
|
||||
assert!(json.contains("\"messages\""));
|
||||
assert!(json.contains("\"devices\""));
|
||||
|
||||
std::fs::remove_file(csv_path).expect("cleanup csv");
|
||||
std::fs::remove_file(json_path).expect("cleanup json");
|
||||
}
|
||||
206
workspace/apps/icenet-city/ui/main.slint
Normal file
206
workspace/apps/icenet-city/ui/main.slint
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
// A desktop-only city topology editor; all networking logic stays in Rust crates.
|
||||
import { Button, ScrollView } from "std-widgets.slint";
|
||||
|
||||
export struct UiNode {
|
||||
id: int,
|
||||
label: string,
|
||||
px: float,
|
||||
py: float,
|
||||
online: bool,
|
||||
}
|
||||
|
||||
export struct UiLink {
|
||||
ax: float,
|
||||
ay: float,
|
||||
bx: float,
|
||||
by: float,
|
||||
title: string,
|
||||
enabled: bool,
|
||||
highlighted: bool,
|
||||
color: color,
|
||||
}
|
||||
|
||||
export component CityWindow inherits Window {
|
||||
title: "ICE-NET City Lab | Slint";
|
||||
preferred-width: 1140px;
|
||||
preferred-height: 760px;
|
||||
background: #0c131b;
|
||||
|
||||
in property <[UiNode]> nodes;
|
||||
in property <[UiLink]> links;
|
||||
in property <[string]> messages;
|
||||
in property <string> clock;
|
||||
in property <string> from-label;
|
||||
in property <string> to-label;
|
||||
in property <string> role-label;
|
||||
in property <string> link-label;
|
||||
in property <string> export-status;
|
||||
|
||||
callback send-text();
|
||||
callback send-photo();
|
||||
callback export-csv();
|
||||
callback export-json();
|
||||
callback next-from();
|
||||
callback next-to();
|
||||
callback next-role();
|
||||
callback next-link-kind();
|
||||
callback add-node();
|
||||
callback connect-nodes();
|
||||
callback toggle-node(int);
|
||||
callback toggle-link(int);
|
||||
callback drag-start(int, float, float);
|
||||
callback drag-move(float, float);
|
||||
callback drag-end();
|
||||
callback advance(int);
|
||||
callback reset-city();
|
||||
|
||||
HorizontalLayout {
|
||||
padding: 16px;
|
||||
spacing: 14px;
|
||||
side := Rectangle {
|
||||
width: 295px;
|
||||
background: #172533;
|
||||
border-radius: 12px;
|
||||
VerticalLayout {
|
||||
padding: 14px;
|
||||
spacing: 9px;
|
||||
Text { text: "ICE-NET / CITY LAB"; color: #6de0cb; font-size: 20px; font-weight: 700; }
|
||||
Text { text: "Offline graph simulation • no real radio"; color: #adc0ce; font-size: 12px; }
|
||||
Rectangle { height: 1px; background: #344557; }
|
||||
Text { text: "ROUTE"; color: #6de0cb; font-size: 13px; font-weight: 700; }
|
||||
Button { text: "From: " + root.from-label; clicked => { root.next-from(); } }
|
||||
Button { text: "To: " + root.to-label; clicked => { root.next-to(); } }
|
||||
HorizontalLayout {
|
||||
spacing: 5px;
|
||||
Button { text: "Text (128 B)"; clicked => { root.send-text(); } }
|
||||
Button { text: "Photo (5 MiB)"; clicked => { root.send-photo(); } }
|
||||
}
|
||||
Rectangle { height: 1px; background: #344557; }
|
||||
Text { text: "TOPOLOGY EDITOR"; color: #6de0cb; font-size: 13px; font-weight: 700; }
|
||||
Button { text: root.role-label; clicked => { root.next-role(); } }
|
||||
Button { text: "Add device"; clicked => { root.add-node(); } }
|
||||
Button { text: root.link-label; clicked => { root.next-link-kind(); } }
|
||||
Button { text: "Connect selected devices"; clicked => { root.connect-nodes(); } }
|
||||
Text { text: "DEVICES (CLICK TO TOGGLE)"; color: #b5c9d5; font-size: 12px; }
|
||||
ScrollView {
|
||||
height: 92px;
|
||||
VerticalLayout {
|
||||
spacing: 3px;
|
||||
for node in root.nodes: Button {
|
||||
text: node.label + (node.online ? " [ON]" : " [OFF]");
|
||||
clicked => { root.toggle-node(node.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Text { text: "LINKS (CLICK TO TOGGLE)"; color: #b5c9d5; font-size: 12px; }
|
||||
ScrollView {
|
||||
height: 82px;
|
||||
VerticalLayout {
|
||||
spacing: 3px;
|
||||
for edge[index] in root.links: Button {
|
||||
text: edge.title + (edge.enabled ? " ON" : " OFF");
|
||||
clicked => { root.toggle-link(index); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Text { text: root.clock; color: #adc0ce; font-size: 12px; }
|
||||
HorizontalLayout {
|
||||
spacing: 5px;
|
||||
Button { text: "+1 sec"; clicked => { root.advance(1000); } }
|
||||
Button { text: "+1 min"; clicked => { root.advance(60000); } }
|
||||
Button { text: "Reset"; clicked => { root.reset-city(); } }
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: 5px;
|
||||
Button { text: "Export CSV"; clicked => { root.export-csv(); } }
|
||||
Button { text: "Export JSON"; clicked => { root.export-json(); } }
|
||||
}
|
||||
Text { text: root.export-status; color: #6de0cb; font-size: 11px; }
|
||||
}
|
||||
}
|
||||
content := Rectangle {
|
||||
background: #17212e;
|
||||
border-radius: 12px;
|
||||
VerticalLayout {
|
||||
padding: 16px;
|
||||
spacing: 12px;
|
||||
Text { text: "Network topology"; color: #e7f3f8; font-size: 21px; font-weight: 600; }
|
||||
Text { text: "Drag nodes. Thick links show the last selected route."; color: #9cb2c6; }
|
||||
graph := Rectangle {
|
||||
height: 355px;
|
||||
background: #101c29;
|
||||
border-radius: 8px;
|
||||
for edge in root.links: Path {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
viewbox-x: 0;
|
||||
viewbox-y: 0;
|
||||
viewbox-width: parent.width / 1px;
|
||||
viewbox-height: parent.height / 1px;
|
||||
stroke: edge.highlighted ? #ffffff : edge.color;
|
||||
stroke-width: edge.highlighted ? 4px : 2px;
|
||||
MoveTo { x: edge.ax; y: edge.ay; }
|
||||
LineTo { x: edge.bx; y: edge.by; }
|
||||
}
|
||||
for node in root.nodes: Rectangle {
|
||||
x: (node.px - 17.0) * 1px;
|
||||
y: (node.py - 17.0) * 1px;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 17px;
|
||||
background: node.online ? #235b66 : #35404c;
|
||||
border-color: node.online ? #72d0e2 : #78808a;
|
||||
border-width: 2px;
|
||||
Text {
|
||||
text: node.id;
|
||||
color: #ffffff;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
pointer-event(event) => {
|
||||
if (event.kind == PointerEventKind.down) {
|
||||
root.drag-start(node.id,
|
||||
(self.absolute-position.x + self.mouse-x) / 1px,
|
||||
(self.absolute-position.y + self.mouse-y) / 1px);
|
||||
} else if (event.kind == PointerEventKind.up) {
|
||||
root.drag-end();
|
||||
}
|
||||
}
|
||||
moved => {
|
||||
if (self.pressed) {
|
||||
root.drag-move(
|
||||
(self.absolute-position.x + self.mouse-x) / 1px,
|
||||
(self.absolute-position.y + self.mouse-y) / 1px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text { text: "Message log"; color: #e7f3f8; font-size: 17px; font-weight: 600; }
|
||||
ScrollView {
|
||||
VerticalLayout {
|
||||
spacing: 6px;
|
||||
for line in root.messages: Rectangle {
|
||||
height: 28px;
|
||||
background: #233242;
|
||||
border-radius: 5px;
|
||||
Text {
|
||||
x: 9px;
|
||||
text: line;
|
||||
color: #d8e4ed;
|
||||
vertical-alignment: center;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text { text: "Synthetic transmission estimates; not an RF model or a live network.";
|
||||
color: #91aabd; font-size: 11px; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
9
workspace/apps/icenetd/Cargo.toml
Normal file
9
workspace/apps/icenetd/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "icenetd"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
icenet-sdk = { path = "../../crates/icenet-sdk" }
|
||||
icenet-sim = { path = "../../crates/icenet-sim" }
|
||||
148
workspace/apps/icenetd/src/args.rs
Normal file
148
workspace/apps/icenetd/src/args.rs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
//! Minimal dependency-free option parser for the offline CLI.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
const VALUE_OPTIONS: [&str; 25] = [
|
||||
"from",
|
||||
"to",
|
||||
"class",
|
||||
"size",
|
||||
"ttl",
|
||||
"ticks",
|
||||
"disable",
|
||||
"service",
|
||||
"allow",
|
||||
"max-size",
|
||||
"text",
|
||||
"hex",
|
||||
"csv",
|
||||
"json",
|
||||
"peer",
|
||||
"seq",
|
||||
"now",
|
||||
"queue",
|
||||
"max-queue",
|
||||
"rate",
|
||||
"burst",
|
||||
"window",
|
||||
"bind",
|
||||
"count",
|
||||
"timeout",
|
||||
];
|
||||
const FLAGS: [&str; 3] = ["unauthenticated", "help", "version"];
|
||||
|
||||
/// Parsed command line: one command name plus value options and boolean flags.
|
||||
#[derive(Debug)]
|
||||
pub struct Args {
|
||||
command: String,
|
||||
options: BTreeMap<String, String>,
|
||||
flags: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
/// Parses arguments after the executable name.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a message for a missing command, an unknown option, or a
|
||||
/// value option without a value.
|
||||
pub fn parse(argv: impl IntoIterator<Item = String>) -> Result<Self, String> {
|
||||
let mut iter = argv.into_iter();
|
||||
let Some(command) = iter.next() else {
|
||||
return Err("missing command; try `help`".to_owned());
|
||||
};
|
||||
let mut options = BTreeMap::new();
|
||||
let mut flags = BTreeSet::new();
|
||||
while let Some(token) = iter.next() {
|
||||
let Some(name) = token.strip_prefix("--") else {
|
||||
return Err(format!("unexpected argument `{token}`"));
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Err("empty option name".to_owned());
|
||||
}
|
||||
if FLAGS.contains(&name) {
|
||||
flags.insert(name.to_owned());
|
||||
continue;
|
||||
}
|
||||
let Some(value) = iter.next() else {
|
||||
return Err(format!("option `--{name}` needs a value"));
|
||||
};
|
||||
if options.insert(name.to_owned(), value).is_some() {
|
||||
return Err(format!("option `--{name}` was supplied more than once"));
|
||||
}
|
||||
}
|
||||
for name in options.keys().chain(flags.iter()) {
|
||||
if !VALUE_OPTIONS.contains(&name.as_str()) && !FLAGS.contains(&name.as_str()) {
|
||||
return Err(format!("unknown option `--{name}`"));
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
command,
|
||||
options,
|
||||
flags,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the command name.
|
||||
pub fn command(&self) -> &str {
|
||||
&self.command
|
||||
}
|
||||
|
||||
/// Returns an option value, if present.
|
||||
pub fn value(&self, name: &str) -> Option<&str> {
|
||||
self.options.get(name).map(String::as_str)
|
||||
}
|
||||
|
||||
/// Returns whether a boolean flag was supplied.
|
||||
pub fn flag(&self, name: &str) -> bool {
|
||||
self.flags.contains(name)
|
||||
}
|
||||
|
||||
/// Rejects options and flags that the current command does not implement.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a message naming the first unsupported option.
|
||||
pub fn only(&self, allowed: &[&str]) -> Result<(), String> {
|
||||
for name in self.options.keys() {
|
||||
if !allowed.contains(&name.as_str()) {
|
||||
return Err(format!(
|
||||
"option `--{name}` is not supported by `{}`",
|
||||
self.command
|
||||
));
|
||||
}
|
||||
}
|
||||
for name in &self.flags {
|
||||
if name != "help" && name != "version" && !allowed.contains(&name.as_str()) {
|
||||
return Err(format!(
|
||||
"option `--{name}` is not supported by `{}`",
|
||||
self.command
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads a required unsigned integer option.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a message when the option is absent or not an integer.
|
||||
pub fn u64(&self, name: &str) -> Result<u64, String> {
|
||||
let value = self
|
||||
.value(name)
|
||||
.ok_or_else(|| format!("option `--{name}` is required"))?;
|
||||
value
|
||||
.parse()
|
||||
.map_err(|_| format!("`--{name}` must be an unsigned integer, got `{value}`"))
|
||||
}
|
||||
|
||||
/// Reads an optional unsigned integer option or returns `default`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a message when the supplied value is not an integer.
|
||||
pub fn u64_or(&self, name: &str, default: u64) -> Result<u64, String> {
|
||||
match self.value(name) {
|
||||
Some(value) => value
|
||||
.parse()
|
||||
.map_err(|_| format!("`--{name}` must be an unsigned integer, got `{value}`")),
|
||||
None => Ok(default),
|
||||
}
|
||||
}
|
||||
}
|
||||
178
workspace/apps/icenetd/src/commands/mod.rs
Normal file
178
workspace/apps/icenetd/src/commands/mod.rs
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
//! Offline command implementations; no sockets, GUI or cryptography are used.
|
||||
use icenet_sdk::{NodeId, TrafficClass};
|
||||
use icenet_sim::{City, DeliveryState, metrics};
|
||||
|
||||
use crate::args::Args;
|
||||
|
||||
mod policy;
|
||||
mod udp;
|
||||
mod wire;
|
||||
|
||||
/// A CLI failure with a usage/runtime distinction for exit codes.
|
||||
#[derive(Debug)]
|
||||
pub enum CommandError {
|
||||
/// The caller supplied invalid arguments.
|
||||
Usage(String),
|
||||
/// A valid request failed at runtime.
|
||||
Runtime(String),
|
||||
}
|
||||
|
||||
impl From<String> for CommandError {
|
||||
fn from(message: String) -> Self {
|
||||
Self::Usage(message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one subcommand.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a usage or runtime failure with a human-readable message.
|
||||
pub fn run(args: &Args) -> Result<(), CommandError> {
|
||||
match args.command() {
|
||||
"route" => route(args),
|
||||
"send" => send(args),
|
||||
"sim" => sim(args),
|
||||
"policy" => policy::run(args),
|
||||
"send-udp" => udp::send(args),
|
||||
"serve" => udp::serve(args),
|
||||
"wire-encode" => wire::encode(args),
|
||||
"wire-decode" => wire::decode(args),
|
||||
other => Err(CommandError::Usage(format!(
|
||||
"unknown command `{other}`; try `help`"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn route(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["from", "to", "class", "size", "disable"])?;
|
||||
let city = demo_city(args)?;
|
||||
let class = class(args)?;
|
||||
let size = args.u64_or("size", 128)?;
|
||||
let from = NodeId(args.u64("from")?);
|
||||
let to = NodeId(args.u64("to")?);
|
||||
match city.route(from, to, class, size) {
|
||||
Some(path) => {
|
||||
println!("route: {}", join_nodes(&path.nodes));
|
||||
println!("estimated_ms: {}", path.estimated_ms);
|
||||
}
|
||||
None => println!("route: NO_ROUTE"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["from", "to", "class", "size", "disable", "ttl", "ticks"])?;
|
||||
let mut city = demo_city(args)?;
|
||||
let class = class(args)?;
|
||||
let size = args.u64_or("size", 128)?;
|
||||
let ttl = args.u64_or("ttl", City::DEFAULT_TTL_MS)?;
|
||||
if ttl == 0 {
|
||||
return Err(CommandError::Usage(
|
||||
"`--ttl` must be at least 1 millisecond".to_owned(),
|
||||
));
|
||||
}
|
||||
let ticks = args.u64_or("ticks", 0)?;
|
||||
let from = NodeId(args.u64("from")?);
|
||||
let to = NodeId(args.u64("to")?);
|
||||
let id = city.send_with_ttl(from, to, class, size, ttl);
|
||||
city.tick(ticks);
|
||||
let message = city
|
||||
.messages
|
||||
.iter()
|
||||
.find(|message| message.id == id)
|
||||
.ok_or_else(|| CommandError::Runtime("message was not recorded".to_owned()))?;
|
||||
println!(
|
||||
"message: id={} status={:?} class={:?} bytes={} created_ms={} expires_ms={} \
|
||||
first_route_ms={:?} due_ms={:?} route={}",
|
||||
message.id,
|
||||
message.status,
|
||||
message.class,
|
||||
message.bytes,
|
||||
message.created_ms,
|
||||
message.expires_ms,
|
||||
message.first_route_ms,
|
||||
message.due_ms,
|
||||
join_nodes(&message.route)
|
||||
);
|
||||
if message.status == DeliveryState::Queued {
|
||||
println!("hint: QUEUED means no eligible path, not delivered");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sim(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["csv", "json"])?;
|
||||
let mut city = City::demo();
|
||||
set_link(&mut city, 2, 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(1_000);
|
||||
set_link(&mut city, 2, true)?;
|
||||
city.tick(120_000);
|
||||
|
||||
let summary = metrics::summarize(&city);
|
||||
println!(
|
||||
"created={} delivered={} in_flight={} queued={} expired={} \
|
||||
delivery_ratio={:.2} first_route_p50_ms={:?} first_route_p95_ms={:?} control_airtime_ms={}",
|
||||
summary.created,
|
||||
summary.delivered,
|
||||
summary.in_flight,
|
||||
summary.queued,
|
||||
summary.expired,
|
||||
summary.delivery_ratio(),
|
||||
summary.first_route_p50_ms,
|
||||
summary.first_route_p95_ms,
|
||||
summary.control_airtime_ms
|
||||
);
|
||||
if let Some(path) = args.value("csv") {
|
||||
std::fs::write(path, metrics::messages_csv(&city))
|
||||
.map_err(|error| CommandError::Runtime(format!("cannot write `{path}`: {error}")))?;
|
||||
println!("csv: {path}");
|
||||
}
|
||||
if let Some(path) = args.value("json") {
|
||||
std::fs::write(path, metrics::scenario_json(&city))
|
||||
.map_err(|error| CommandError::Runtime(format!("cannot write `{path}`: {error}")))?;
|
||||
println!("json: {path}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn class(args: &Args) -> Result<TrafficClass, String> {
|
||||
match args.value("class").unwrap_or("text") {
|
||||
"control" => Ok(TrafficClass::Control),
|
||||
"text" => Ok(TrafficClass::Text),
|
||||
"bulk" => Ok(TrafficClass::Bulk),
|
||||
other => Err(format!("unknown class `{other}`; use control|text|bulk")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn join_nodes(nodes: &[NodeId]) -> String {
|
||||
if nodes.is_empty() {
|
||||
return "NO_ROUTE".to_owned();
|
||||
}
|
||||
nodes
|
||||
.iter()
|
||||
.map(|node| node.0.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-")
|
||||
}
|
||||
|
||||
fn demo_city(args: &Args) -> Result<City, String> {
|
||||
let mut city = City::demo();
|
||||
if let Some(list) = args.value("disable") {
|
||||
for part in list.split(',') {
|
||||
let index = part
|
||||
.trim()
|
||||
.parse::<usize>()
|
||||
.map_err(|_| format!("invalid link index `{part}`"))?;
|
||||
set_link(&mut city, index, false)?;
|
||||
}
|
||||
}
|
||||
Ok(city)
|
||||
}
|
||||
|
||||
fn set_link(city: &mut City, index: usize, enabled: bool) -> Result<(), String> {
|
||||
city.set_link_enabled(index, enabled)
|
||||
.then_some(())
|
||||
.ok_or_else(|| format!("no link with index {index}"))
|
||||
}
|
||||
67
workspace/apps/icenetd/src/commands/policy.rs
Normal file
67
workspace/apps/icenetd/src/commands/policy.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! Local Guard policy command.
|
||||
use icenet_sdk::{Context, Guard, Limits, NodeId, ServiceId, Verdict};
|
||||
|
||||
use super::CommandError;
|
||||
use crate::args::Args;
|
||||
|
||||
/// Evaluates one local admission request and prints the verdict.
|
||||
pub fn run(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&[
|
||||
"service",
|
||||
"size",
|
||||
"allow",
|
||||
"max-size",
|
||||
"unauthenticated",
|
||||
"peer",
|
||||
"seq",
|
||||
"now",
|
||||
"queue",
|
||||
"max-queue",
|
||||
"rate",
|
||||
"burst",
|
||||
"window",
|
||||
])?;
|
||||
let service = ServiceId(args.u64("service")?);
|
||||
let payload_bytes = to_usize(args.u64_or("size", 0)?, "--size")?;
|
||||
let limits = Limits {
|
||||
max_payload_bytes: to_usize(args.u64_or("max-size", 4_096)?, "--max-size")?,
|
||||
max_queue_depth: to_usize(args.u64_or("max-queue", 64)?, "--max-queue")?,
|
||||
rate_per_second: args.u64_or("rate", 20)?,
|
||||
burst: args.u64_or("burst", 10)?,
|
||||
replay_window: args.u64_or("window", 64)?,
|
||||
};
|
||||
let allowed = match args.value("allow") {
|
||||
Some(list) => parse_services(list)?,
|
||||
None => vec![service],
|
||||
};
|
||||
let mut guard = Guard::new(allowed, limits);
|
||||
let context = Context {
|
||||
authenticated: !args.flag("unauthenticated"),
|
||||
peer: NodeId(args.u64_or("peer", 1)?),
|
||||
service,
|
||||
payload_bytes,
|
||||
sequence: args.u64_or("seq", 1)?,
|
||||
now_ms: args.u64_or("now", 0)?,
|
||||
queue_depth: to_usize(args.u64_or("queue", 0)?, "--queue")?,
|
||||
};
|
||||
match guard.check(context) {
|
||||
Verdict::Permit => println!("Permit"),
|
||||
Verdict::Deny(reason) => println!("Deny({reason})"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_usize(value: u64, name: &str) -> Result<usize, String> {
|
||||
usize::try_from(value).map_err(|_| format!("`{name}` is too large for this machine"))
|
||||
}
|
||||
|
||||
fn parse_services(list: &str) -> Result<Vec<ServiceId>, String> {
|
||||
list.split(',')
|
||||
.map(|part| {
|
||||
part.trim()
|
||||
.parse::<u64>()
|
||||
.map(ServiceId)
|
||||
.map_err(|_| format!("invalid service id `{part}`"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
135
workspace/apps/icenetd/src/commands/udp.rs
Normal file
135
workspace/apps/icenetd/src/commands/udp.rs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
//! Real UDP frame exchange for local process-to-process experiments.
|
||||
use std::io::{self, Write as _};
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use icenet_sdk::{Frame, ServiceId, Transport, UdpTransport, decode, encode};
|
||||
|
||||
use super::wire::hex_encode;
|
||||
use super::{CommandError, class};
|
||||
use crate::args::Args;
|
||||
|
||||
/// Encodes one frame and sends it to `--to`.
|
||||
pub fn send(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["to", "service", "class", "text"])?;
|
||||
let peer = address(required(args, "to")?)?;
|
||||
let service = ServiceId(args.u64("service")?);
|
||||
let class = class(args)?;
|
||||
let text = args.value("text").unwrap_or("");
|
||||
let frame = Frame {
|
||||
class,
|
||||
service,
|
||||
payload: text.as_bytes().to_vec(),
|
||||
};
|
||||
let bytes = encode(&frame)
|
||||
.map_err(|error| CommandError::Runtime(format!("encode failed: {error:?}")))?;
|
||||
let transport = UdpTransport::bind("0.0.0.0:0")
|
||||
.map_err(|error| CommandError::Runtime(format!("bind failed: {error}")))?;
|
||||
let mut transport = transport
|
||||
.connect(peer)
|
||||
.map_err(|error| CommandError::Runtime(format!("connect failed: {error}")))?;
|
||||
transport
|
||||
.send(bytes)
|
||||
.map_err(|error| CommandError::Runtime(format!("send failed: {error:?}")))?;
|
||||
println!("sent: {} bytes to {peer}", frame.payload.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Receives frames until `--count` is reached or `--timeout` elapses.
|
||||
pub fn serve(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["bind", "count", "timeout"])?;
|
||||
let bind = address(required(args, "bind")?)?;
|
||||
let count = optional_count(args)?;
|
||||
let timeout = optional_timeout(args)?;
|
||||
let transport = UdpTransport::bind(bind)
|
||||
.map_err(|error| CommandError::Runtime(format!("bind failed: {error}")))?;
|
||||
let mut transport = transport;
|
||||
let local = transport
|
||||
.local_addr()
|
||||
.map_err(|error| CommandError::Runtime(format!("local address failed: {error}")))?;
|
||||
println!("listening: {local}");
|
||||
flush()?;
|
||||
|
||||
let deadline = timeout.map(|duration| Instant::now() + duration);
|
||||
let mut received = 0_usize;
|
||||
loop {
|
||||
if let Some(bytes) = transport
|
||||
.recv()
|
||||
.map_err(|error| CommandError::Runtime(format!("recv failed: {error:?}")))?
|
||||
{
|
||||
match decode(&bytes) {
|
||||
Ok(frame) => {
|
||||
received = received.saturating_add(1);
|
||||
println!(
|
||||
"frame: service={} class={:?} bytes={} payload={}",
|
||||
frame.service.0,
|
||||
frame.class,
|
||||
frame.payload.len(),
|
||||
printable(&frame.payload)
|
||||
);
|
||||
flush()?;
|
||||
if count.is_some_and(|limit| received >= limit) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
println!("malformed: {error:?}");
|
||||
flush()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if deadline.is_some_and(|limit| Instant::now() >= limit) {
|
||||
let millis = timeout.unwrap_or_default().as_millis();
|
||||
return Err(CommandError::Runtime(format!(
|
||||
"timeout after {millis} ms waiting for frames"
|
||||
)));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
fn required<'a>(args: &'a Args, name: &str) -> Result<&'a str, CommandError> {
|
||||
args.value(name)
|
||||
.ok_or_else(|| CommandError::Usage(format!("option `--{name}` is required")))
|
||||
}
|
||||
|
||||
fn address(value: &str) -> Result<SocketAddr, String> {
|
||||
value
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid socket address `{value}`; expected IP:PORT"))
|
||||
}
|
||||
|
||||
fn optional_count(args: &Args) -> Result<Option<usize>, String> {
|
||||
if args.value("count").is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let count = usize::try_from(args.u64("count")?).map_err(|_| "`--count` is too large")?;
|
||||
if count == 0 {
|
||||
return Err("`--count` must be at least 1".to_owned());
|
||||
}
|
||||
Ok(Some(count))
|
||||
}
|
||||
|
||||
fn optional_timeout(args: &Args) -> Result<Option<Duration>, String> {
|
||||
if args.value("timeout").is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let millis = args.u64("timeout")?;
|
||||
if millis == 0 {
|
||||
return Err("`--timeout` must be at least 1 millisecond".to_owned());
|
||||
}
|
||||
Ok(Some(Duration::from_millis(millis)))
|
||||
}
|
||||
|
||||
fn printable(payload: &[u8]) -> String {
|
||||
match std::str::from_utf8(payload) {
|
||||
Ok(text) if !text.chars().any(char::is_control) => text.to_owned(),
|
||||
_ => format!("0x{}", hex_encode(payload)),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush() -> Result<(), CommandError> {
|
||||
io::stdout()
|
||||
.flush()
|
||||
.map_err(|error| CommandError::Runtime(format!("stdout flush failed: {error}")))
|
||||
}
|
||||
64
workspace/apps/icenetd/src/commands/wire.rs
Normal file
64
workspace/apps/icenetd/src/commands/wire.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
//! Draft frame encoding and decoding commands.
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use icenet_sdk::{Frame, ServiceId, decode as decode_frame, encode as encode_frame};
|
||||
|
||||
use super::{CommandError, class};
|
||||
use crate::args::Args;
|
||||
|
||||
/// Encodes a draft frame and prints its hex bytes.
|
||||
pub fn encode(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["service", "class", "text"])?;
|
||||
let service = ServiceId(args.u64("service")?);
|
||||
let class = class(args)?;
|
||||
let text = args.value("text").unwrap_or("");
|
||||
let frame = Frame {
|
||||
class,
|
||||
service,
|
||||
payload: text.as_bytes().to_vec(),
|
||||
};
|
||||
let bytes = encode_frame(&frame).map_err(|error| format!("encode failed: {error:?}"))?;
|
||||
println!("frame: {}", hex_encode(&bytes));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decodes a draft frame from hex and prints its fields.
|
||||
pub fn decode(args: &Args) -> Result<(), CommandError> {
|
||||
args.only(&["hex"])?;
|
||||
let hex = args
|
||||
.value("hex")
|
||||
.ok_or_else(|| CommandError::Usage("option `--hex` is required".to_owned()))?;
|
||||
let bytes = hex_decode(hex)?;
|
||||
let frame = decode_frame(&bytes).map_err(|error| format!("decode failed: {error:?}"))?;
|
||||
println!("service: {}", frame.service.0);
|
||||
println!("class: {:?}", frame.class);
|
||||
println!("payload_bytes: {}", frame.payload.len());
|
||||
match std::str::from_utf8(&frame.payload) {
|
||||
Ok(text) if !text.chars().any(char::is_control) => println!("payload: {text}"),
|
||||
_ => println!("payload_hex: {}", hex_encode(&frame.payload)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn hex_encode(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
write!(out, "{byte:02x}").expect("writing into a String cannot fail");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hex_decode(text: &str) -> Result<Vec<u8>, String> {
|
||||
let clean = text.trim();
|
||||
if !clean.len().is_multiple_of(2) {
|
||||
return Err("hex input must have an even number of digits".to_owned());
|
||||
}
|
||||
let mut out = Vec::with_capacity(clean.len() / 2);
|
||||
for index in (0..clean.len()).step_by(2) {
|
||||
let pair = clean
|
||||
.get(index..index + 2)
|
||||
.ok_or_else(|| format!("invalid hex at byte {index}"))?;
|
||||
out.push(u8::from_str_radix(pair, 16).map_err(|_| format!("invalid hex pair `{pair}`"))?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
63
workspace/apps/icenetd/src/help.rs
Normal file
63
workspace/apps/icenetd/src/help.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
//! Usage text for the offline CLI.
|
||||
|
||||
/// Prints the command reference.
|
||||
pub fn print() {
|
||||
println!("{USAGE}");
|
||||
}
|
||||
|
||||
const USAGE: &str = "\
|
||||
icenetd — offline ICE-NET lab (no sockets, no GUI, no cryptography)
|
||||
|
||||
USAGE:
|
||||
icenetd <command> [options]
|
||||
|
||||
COMMANDS:
|
||||
route Find a policy-eligible path in the demo topology
|
||||
send Create one message, advance time, print its state
|
||||
sim Run the deterministic demo scenario and export metrics
|
||||
policy Evaluate the local Guard policy (ACL/size/queue/replay/rate)
|
||||
send-udp Encode one frame and send it over UDP
|
||||
serve Receive draft frames over UDP and print them
|
||||
wire-encode Encode a draft frame and print its hex bytes
|
||||
wire-decode Parse a draft frame from hex bytes
|
||||
version Print the binary version
|
||||
help Print this text
|
||||
|
||||
OPTIONS:
|
||||
--from N --to N node IDs for route/send (default none)
|
||||
--class C control | text | bulk (default text)
|
||||
--size N payload bytes (default 128; policy default 0)
|
||||
--ttl MS message lifetime, at least 1 (default 86400000)
|
||||
--ticks MS simulated time to advance after send
|
||||
--disable I,J disable demo link indexes before routing
|
||||
--service N service ID for policy/wire commands
|
||||
--allow I,J allowed service IDs (default: requested service)
|
||||
--max-size N guard payload cap (default 4096)
|
||||
--unauthenticated simulate an unauthenticated caller
|
||||
--peer N --seq N guard sender identity and replay sequence
|
||||
--now MS guard monotonic time for rate limiting
|
||||
--queue N --max-queue N current and maximum guard queue depth
|
||||
--rate N --burst N guard sustained rate and burst (rate 0 disables;
|
||||
burst 0 with rate > 0 blocks all traffic)
|
||||
--window N guard replay window size (default 64)
|
||||
--text TEXT frame payload for wire-encode
|
||||
--hex HEX frame bytes for wire-decode
|
||||
--to IP:PORT UDP peer for send-udp
|
||||
--bind IP:PORT local UDP address for serve (port 0 = auto)
|
||||
--count N serve: exit after N valid frames
|
||||
--timeout MS serve: exit with code 1 after this idle time
|
||||
--csv PATH --json PATH exports for the sim command
|
||||
--help print this text
|
||||
|
||||
EXAMPLES:
|
||||
icenetd route --from 1 --to 3 --class bulk --size 5000000
|
||||
icenetd route --from 1 --to 3 --class bulk --size 5000000 --disable 2,3,4
|
||||
icenetd send --from 1 --to 3 --class text --size 128 --ticks 1000
|
||||
icenetd sim --csv metrics.csv --json scenario.json
|
||||
icenetd policy --service 77777 --size 5 --allow 1
|
||||
icenetd wire-encode --service 7 --class text --text hello
|
||||
icenetd serve --bind 127.0.0.1:9000 --count 1 --timeout 5000
|
||||
icenetd send-udp --to 127.0.0.1:9000 --service 7 --class text --text hello
|
||||
|
||||
Reminder: the simulator is not an RF model and this CLI has no authentication.
|
||||
";
|
||||
88
workspace/apps/icenetd/src/main.rs
Normal file
88
workspace/apps/icenetd/src/main.rs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
//! Offline command-line lab for the ICE-NET core crates.
|
||||
//!
|
||||
//! Besides offline route/send/sim/policy/wire commands it offers plain UDP
|
||||
//! `serve`/`send-udp`; there is no GUI, cryptography or daemon loop yet.
|
||||
use std::ffi::OsString;
|
||||
use std::process::ExitCode;
|
||||
|
||||
mod args;
|
||||
mod commands;
|
||||
mod help;
|
||||
|
||||
use args::Args;
|
||||
use commands::CommandError;
|
||||
|
||||
/// Classifies CLI failures so usage mistakes exit with code 2.
|
||||
enum Failure {
|
||||
Usage(String),
|
||||
Runtime(String),
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv = match utf8_arguments(std::env::args_os().skip(1)) {
|
||||
Ok(argv) => argv,
|
||||
Err(message) => return exit(Failure::Usage(message)),
|
||||
};
|
||||
match dispatch(argv) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(failure) => exit(failure),
|
||||
}
|
||||
}
|
||||
|
||||
fn exit(failure: Failure) -> ExitCode {
|
||||
match failure {
|
||||
Failure::Usage(message) => {
|
||||
eprintln!("error: {message}");
|
||||
eprintln!();
|
||||
help::print();
|
||||
ExitCode::from(2)
|
||||
}
|
||||
Failure::Runtime(message) => {
|
||||
eprintln!("error: {message}");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn utf8_arguments(args: impl Iterator<Item = OsString>) -> Result<Vec<String>, String> {
|
||||
args.map(|arg| {
|
||||
arg.into_string()
|
||||
.map_err(|_| "command-line arguments must be valid UTF-8".to_owned())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn dispatch(argv: Vec<String>) -> Result<(), Failure> {
|
||||
if argv.is_empty() {
|
||||
help::print();
|
||||
return Ok(());
|
||||
}
|
||||
match argv[0].as_str() {
|
||||
"--help" | "-h" => {
|
||||
help::print();
|
||||
return Ok(());
|
||||
}
|
||||
"--version" => {
|
||||
print_version();
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let args = Args::parse(argv).map_err(Failure::Usage)?;
|
||||
if args.flag("help") || args.command() == "help" {
|
||||
help::print();
|
||||
return Ok(());
|
||||
}
|
||||
if args.flag("version") || args.command() == "version" {
|
||||
print_version();
|
||||
return Ok(());
|
||||
}
|
||||
commands::run(&args).map_err(|error| match error {
|
||||
CommandError::Usage(message) => Failure::Usage(message),
|
||||
CommandError::Runtime(message) => Failure::Runtime(message),
|
||||
})
|
||||
}
|
||||
|
||||
fn print_version() {
|
||||
println!("icenetd {}", env!("CARGO_PKG_VERSION"));
|
||||
}
|
||||
156
workspace/apps/icenetd/tests/cli.rs
Normal file
156
workspace/apps/icenetd/tests/cli.rs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
//! End-to-end route/send/sim/wire tests against the real `icenetd` binary.
|
||||
mod common;
|
||||
|
||||
use common::{run, stderr, stdout, temp};
|
||||
|
||||
#[test]
|
||||
fn help_lists_all_commands() {
|
||||
let output = run(&["help"]);
|
||||
assert!(output.status.success());
|
||||
let text = stdout(&output);
|
||||
for command in [
|
||||
"route",
|
||||
"send",
|
||||
"sim",
|
||||
"policy",
|
||||
"wire-encode",
|
||||
"wire-decode",
|
||||
] {
|
||||
assert!(text.contains(command), "missing {command} in help");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_route_avoids_slow_radio() {
|
||||
let output = run(&[
|
||||
"route", "--from", "1", "--to", "3", "--class", "bulk", "--size", "5000000",
|
||||
]);
|
||||
assert!(output.status.success(), "stderr: {}", stderr(&output));
|
||||
assert!(stdout(&output).contains("1-4-5-3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_route_reports_no_route_without_fast_links() {
|
||||
let output = run(&[
|
||||
"route",
|
||||
"--from",
|
||||
"1",
|
||||
"--to",
|
||||
"3",
|
||||
"--class",
|
||||
"bulk",
|
||||
"--size",
|
||||
"5000000",
|
||||
"--disable",
|
||||
"2,3,4",
|
||||
]);
|
||||
assert!(output.status.success());
|
||||
assert!(stdout(&output).contains("NO_ROUTE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_route_may_use_slow_radio() {
|
||||
let output = run(&[
|
||||
"route",
|
||||
"--from",
|
||||
"1",
|
||||
"--to",
|
||||
"3",
|
||||
"--class",
|
||||
"text",
|
||||
"--size",
|
||||
"128",
|
||||
"--disable",
|
||||
"2,3,4",
|
||||
]);
|
||||
assert!(output.status.success());
|
||||
assert!(stdout(&output).contains("1-2-3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_reports_delivered_message() {
|
||||
let output = run(&[
|
||||
"send", "--from", "1", "--to", "3", "--class", "text", "--size", "128", "--ticks", "1000",
|
||||
]);
|
||||
assert!(output.status.success());
|
||||
assert!(stdout(&output).contains("status=Delivered"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_reports_expired_message() {
|
||||
let output = run(&[
|
||||
"send",
|
||||
"--from",
|
||||
"1",
|
||||
"--to",
|
||||
"3",
|
||||
"--class",
|
||||
"bulk",
|
||||
"--size",
|
||||
"5000000",
|
||||
"--disable",
|
||||
"2,3,4",
|
||||
"--ttl",
|
||||
"1000",
|
||||
"--ticks",
|
||||
"2000",
|
||||
]);
|
||||
assert!(output.status.success(), "stderr: {}", stderr(&output));
|
||||
assert!(stdout(&output).contains("status=Expired"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sim_writes_csv_and_json_exports() {
|
||||
let csv = temp("metrics.csv");
|
||||
let json = temp("scenario.json");
|
||||
let output = run(&[
|
||||
"sim",
|
||||
"--csv",
|
||||
csv.to_str().expect("utf8 path"),
|
||||
"--json",
|
||||
json.to_str().expect("utf8 path"),
|
||||
]);
|
||||
assert!(output.status.success(), "stderr: {}", stderr(&output));
|
||||
assert!(stdout(&output).contains("expired=1"));
|
||||
let csv_body = std::fs::read_to_string(&csv).expect("csv export");
|
||||
assert!(csv_body.starts_with("id,from,to,class,bytes,status,"));
|
||||
let json_body = std::fs::read_to_string(&json).expect("json export");
|
||||
assert!(json_body.contains("\"messages\""));
|
||||
let _ = std::fs::remove_file(csv);
|
||||
let _ = std::fs::remove_file(json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_encoder_and_decoder_round_trip() {
|
||||
let encoded = run(&[
|
||||
"wire-encode",
|
||||
"--service",
|
||||
"7",
|
||||
"--class",
|
||||
"text",
|
||||
"--text",
|
||||
"hello",
|
||||
]);
|
||||
assert!(encoded.status.success(), "stderr: {}", stderr(&encoded));
|
||||
let text = stdout(&encoded);
|
||||
let hex = text
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("frame: "))
|
||||
.expect("frame hex line")
|
||||
.to_owned();
|
||||
let decoded = run(&["wire-decode", "--hex", &hex]);
|
||||
assert!(decoded.status.success(), "stderr: {}", stderr(&decoded));
|
||||
let text = stdout(&decoded);
|
||||
assert!(text.contains("class: Text"));
|
||||
assert!(text.contains("service: 7"));
|
||||
assert!(text.contains("payload: hello"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_decode_escapes_control_bytes() {
|
||||
let output = run(&["wire-decode", "--hex", "494e0101000000000000000700020102"]);
|
||||
assert!(output.status.success(), "stderr: {}", stderr(&output));
|
||||
let text = stdout(&output);
|
||||
assert!(text.contains("payload_hex: 0102"));
|
||||
assert!(!text.contains('\u{1}'));
|
||||
}
|
||||
23
workspace/apps/icenetd/tests/common/mod.rs
Normal file
23
workspace/apps/icenetd/tests/common/mod.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
//! Shared helpers for CLI integration tests.
|
||||
#![allow(dead_code)]
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
pub fn run(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_icenetd"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("icenetd must start")
|
||||
}
|
||||
|
||||
pub fn stdout(output: &Output) -> String {
|
||||
String::from_utf8_lossy(&output.stdout).into_owned()
|
||||
}
|
||||
|
||||
pub fn stderr(output: &Output) -> String {
|
||||
String::from_utf8_lossy(&output.stderr).into_owned()
|
||||
}
|
||||
|
||||
pub fn temp(name: &str) -> PathBuf {
|
||||
std::env::temp_dir().join(format!("icenetd-{}-{name}", std::process::id()))
|
||||
}
|
||||
104
workspace/apps/icenetd/tests/policy.rs
Normal file
104
workspace/apps/icenetd/tests/policy.rs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
//! Policy, usage and exit-code tests against the real `icenetd` binary.
|
||||
mod common;
|
||||
|
||||
use common::{run, stderr, stdout};
|
||||
|
||||
#[test]
|
||||
fn policy_reports_acl_and_authentication_reasons() {
|
||||
let permit = run(&["policy", "--service", "77777", "--size", "5"]);
|
||||
assert!(permit.status.success());
|
||||
assert!(stdout(&permit).contains("Permit"));
|
||||
|
||||
let denied = run(&[
|
||||
"policy",
|
||||
"--service",
|
||||
"77777",
|
||||
"--size",
|
||||
"5",
|
||||
"--allow",
|
||||
"1",
|
||||
]);
|
||||
assert!(denied.status.success());
|
||||
assert!(stdout(&denied).contains("service_denied"));
|
||||
|
||||
let anonymous = run(&[
|
||||
"policy",
|
||||
"--service",
|
||||
"77777",
|
||||
"--size",
|
||||
"5",
|
||||
"--unauthenticated",
|
||||
]);
|
||||
assert!(anonymous.status.success());
|
||||
assert!(stdout(&anonymous).contains("unauthenticated"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_reports_rate_and_queue_reasons() {
|
||||
let queue = run(&[
|
||||
"policy",
|
||||
"--service",
|
||||
"77777",
|
||||
"--size",
|
||||
"5",
|
||||
"--queue",
|
||||
"2",
|
||||
"--max-queue",
|
||||
"2",
|
||||
]);
|
||||
assert!(queue.status.success());
|
||||
assert!(stdout(&queue).contains("queue_full"));
|
||||
|
||||
let rate = run(&[
|
||||
"policy",
|
||||
"--service",
|
||||
"77777",
|
||||
"--size",
|
||||
"5",
|
||||
"--rate",
|
||||
"1",
|
||||
"--burst",
|
||||
"0",
|
||||
]);
|
||||
assert!(rate.status.success());
|
||||
assert!(stdout(&rate).contains("rate_limited"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_flags_work_without_a_command() {
|
||||
let help = run(&["--help"]);
|
||||
assert!(help.status.success());
|
||||
assert!(stdout(&help).contains("USAGE"));
|
||||
let version = run(&["--version"]);
|
||||
assert!(version.status.success());
|
||||
assert!(stdout(&version).contains("icenetd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_values_are_usage_errors_with_exit_two() {
|
||||
let cases: Vec<Vec<&str>> = vec![
|
||||
vec!["route", "--from", "1"],
|
||||
vec!["route", "--from", "1", "--to", "3", "--class", "Bulk"],
|
||||
vec!["route", "--from", "1", "--to", "3", "--disable", "99"],
|
||||
vec!["route", "--from", "1", "--to", "3", "--csv", "x.csv"],
|
||||
vec!["send", "--from", "1", "--to", "3", "--ttl", "0"],
|
||||
vec!["sim", "--disable", "0"],
|
||||
vec!["route", "--from", "1", "--from", "3", "--to", "2"],
|
||||
];
|
||||
for case in cases {
|
||||
let output = run(&case);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(2),
|
||||
"case {case:?} stderr: {}",
|
||||
stderr(&output)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_option_is_a_usage_error() {
|
||||
let output = run(&["route", "--bogus", "1"]);
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
assert!(stderr(&output).contains("unknown option"));
|
||||
}
|
||||
75
workspace/apps/icenetd/tests/udp_cli.rs
Normal file
75
workspace/apps/icenetd/tests/udp_cli.rs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
//! Process-to-process UDP tests for `icenetd send-udp` and `icenetd serve`.
|
||||
mod common;
|
||||
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use common::{run, stderr, stdout};
|
||||
|
||||
#[test]
|
||||
fn serve_and_send_udp_exchange_a_frame() {
|
||||
let mut server = Command::new(env!("CARGO_BIN_EXE_icenetd"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--count",
|
||||
"1",
|
||||
"--timeout",
|
||||
"5000",
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("serve starts");
|
||||
|
||||
let stdout_pipe = server.stdout.take().expect("server stdout");
|
||||
let mut reader = BufReader::new(stdout_pipe);
|
||||
let mut first_line = String::new();
|
||||
reader.read_line(&mut first_line).expect("listening line");
|
||||
let address = first_line
|
||||
.trim()
|
||||
.strip_prefix("listening: ")
|
||||
.expect("listening address")
|
||||
.to_owned();
|
||||
|
||||
let sent = run(&[
|
||||
"send-udp",
|
||||
"--to",
|
||||
&address,
|
||||
"--service",
|
||||
"77777",
|
||||
"--class",
|
||||
"text",
|
||||
"--text",
|
||||
"hello-udp",
|
||||
]);
|
||||
assert!(sent.status.success(), "stderr: {}", stderr(&sent));
|
||||
assert!(stdout(&sent).contains("sent:"));
|
||||
|
||||
let mut received = String::new();
|
||||
reader.read_to_string(&mut received).expect("server output");
|
||||
let status = server.wait().expect("server exits");
|
||||
assert!(status.success(), "server stderr: {received}");
|
||||
assert!(
|
||||
received.contains("service=77777 class=Text bytes=9 payload=hello-udp"),
|
||||
"received: {received}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_times_out_when_no_frames_arrive() {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_icenetd"))
|
||||
.args(["serve", "--bind", "127.0.0.1:0", "--timeout", "200"])
|
||||
.output()
|
||||
.expect("serve starts");
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(stderr(&output).contains("timeout after"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_udp_rejects_invalid_addresses() {
|
||||
let output = run(&["send-udp", "--to", "not-an-address", "--text", "hello"]);
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
assert!(stderr(&output).contains("invalid socket address"));
|
||||
}
|
||||
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)
|
||||
}
|
||||
4
workspace/rust-toolchain.toml
Normal file
4
workspace/rust-toolchain.toml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
[toolchain]
|
||||
channel = "1.95.0"
|
||||
components = ["rustfmt", "clippy"]
|
||||
profile = "minimal"
|
||||
13
workspace/tools/check_all.sh
Executable file
13
workspace/tools/check_all.sh
Executable file
|
|
@ -0,0 +1,13 @@
|
|||
#!/bin/sh
|
||||
# Validate authored files and Rust code. Use --full to include Slint GUI.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 tools/check_layout.py
|
||||
cargo fmt --all -- --check
|
||||
if [ "${1:-}" = "--full" ]; then
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
else
|
||||
cargo clippy -p icenet-routing -p icenet-sim --all-targets -- -D warnings
|
||||
cargo test -p icenet-routing -p icenet-sim
|
||||
fi
|
||||
50
workspace/tools/check_layout.py
Normal file
50
workspace/tools/check_layout.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Validate ICE-NET repository layout constraints without third-party modules."""
|
||||
from __future__ import annotations
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
TEXT_EXT = {'.md', '.rs', '.slint', '.toml', '.py', '.yml', '.yaml', '.sh', '.json', '.txt'}
|
||||
|
||||
|
||||
def check() -> list[str]:
|
||||
"""Return all layout violations, including forbidden tests inside source files."""
|
||||
errors: list[str] = []
|
||||
for folder in sorted(p for p in ROOT.rglob('*') if p.is_dir()):
|
||||
if any(part in {'target', '.git', '__pycache__'} for part in folder.parts):
|
||||
continue
|
||||
direct_files = [p for p in folder.iterdir() if p.is_file()]
|
||||
# Cargo.lock and OS/editor metadata are generated or ecosystem files.
|
||||
counted = [p for p in direct_files if p.name not in {'Cargo.lock', '.gitignore', '.DS_Store'}]
|
||||
if len(counted) > 4:
|
||||
errors.append(f'{folder.relative_to(ROOT)}: {len(counted)} source files, max 4')
|
||||
for path in sorted(p for p in ROOT.rglob('*') if p.is_file()):
|
||||
if any(part in {'target', '.git', '__pycache__'} for part in path.parts):
|
||||
continue
|
||||
if path.suffix not in TEXT_EXT and path.name != '.gitignore':
|
||||
continue
|
||||
# Verbatim license texts are not authored files; keep them unmodified.
|
||||
if 'LICENSES' in path.relative_to(ROOT).parts:
|
||||
continue
|
||||
try:
|
||||
body = path.read_text(encoding='utf8')
|
||||
except UnicodeError:
|
||||
errors.append(f'{path.relative_to(ROOT)}: not UTF-8')
|
||||
continue
|
||||
lines = len(body.splitlines())
|
||||
if lines > 250:
|
||||
errors.append(f'{path.relative_to(ROOT)}: {lines} lines, max 250')
|
||||
if path.suffix == '.rs' and '/src/' in path.as_posix():
|
||||
if re.search(r'#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]', body):
|
||||
errors.append(f'{path.relative_to(ROOT)}: inline tests are forbidden')
|
||||
return errors
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
errors = check()
|
||||
if errors:
|
||||
print('\n'.join('ERROR: ' + error for error in errors), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print('PASS: text <=250 lines, <=4 owned files/directory (lock excluded), external tests')
|
||||
Loading…
Add table
Add a link
Reference in a new issue