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