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