Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
382 changes: 382 additions & 0 deletions backend/crates/station/examples/ws_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,382 @@
//! Throwaway test runner: serves station's HTTP catalogs and WebSocket from an
//! ADJ and publishes fake updates on every frontend topic.
//!
//! ```sh
//! cargo run -p station --example ws_test -- [--adj-dir PATH] [--bind 127.0.0.1:4000] [--heartbeat-ms N] [--interval-ms N]
//! ```
//!
//! Without `--adj-dir` it loads the test ADJ in `crates/core/src/adj/test/adj`.
//! Telemetry, connections and protections use that ADJ's ids, so a frontend
//! that loads the catalogs can show them.
//!
//! `--heartbeat-ms` defaults to a day so manual clients that send no heartbeats
//! stay connected; pass `100` to test the production timeout. Orders and logger
//! commands have no destination here: they are only traced.

use std::{
collections::HashMap,
error::Error,
net::SocketAddr,
path::PathBuf,
sync::Arc,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use software_core::{
adj::{Adj, load_from_dir},
model::{
AdjId, Measurement, MeasurementKind, MessageLevel, NumericKind, PacketType, ProtectionKind,
Value,
},
};
use station::{
payload::{
BackendMessage, Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate,
MeasurementUpdate, MessageTimestamp, MessageUpdate, ProtectionUpdate,
},
websocket::{
self, Commands,
broker::{self, Broker, BrokerClient},
},
};
use tokio::{net::TcpListener, sync::mpsc, time::interval};
use tracing_subscriber::EnvFilter;

const TEST_ADJ: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../core/src/adj/test/adj");
const EVENT_PERIOD: Duration = Duration::from_secs(3);
/// How long the flapping board stays connected, then disconnected.
const FLAP_SECONDS: u64 = 10;

#[derive(Debug)]
struct Options {
adj_dir: PathBuf,
bind: SocketAddr,
heartbeat: Duration,
interval: Duration,
}

impl Options {
fn parse() -> Result<Self, Box<dyn Error>> {
let mut options = Self {
adj_dir: PathBuf::from(TEST_ADJ),
bind: SocketAddr::from(([127, 0, 0, 1], 4000)),
heartbeat: Duration::from_secs(24 * 60 * 60),
interval: Duration::from_millis(500),
};
let mut args = std::env::args().skip(1);
while let Some(flag) = args.next() {
let value = args.next().ok_or_else(|| format!("{flag} needs a value"))?;
match flag.as_str() {
"--adj-dir" => options.adj_dir = PathBuf::from(value),
"--bind" => options.bind = value.parse()?,
"--heartbeat-ms" => options.heartbeat = Duration::from_millis(value.parse()?),
"--interval-ms" => options.interval = Duration::from_millis(value.parse()?),
_ => return Err(format!("unknown argument {flag}").into()),
}
}
if options.interval.is_zero() {
return Err("--interval-ms must be greater than 0".into());
}
Ok(options)
}
}

/// What the fake publisher needs from the ADJ, extracted once.
#[derive(Debug)]
struct FakePod {
/// Board names, sorted. The first one flaps.
boards: Vec<String>,
/// Data packets with the measurements each one carries.
packets: Vec<(AdjId, Vec<Measurement>)>,
/// One trigger per protection packet, sorted by id.
triggers: Vec<Trigger>,
orders: usize,
}

/// A protection packet and a reading that violates it.
#[derive(Debug)]
struct Trigger {
id: AdjId,
value: Value,
}

impl FakePod {
fn new(adj: &Adj) -> Self {
let mut pod = Self {
boards: Vec::new(),
packets: Vec::new(),
triggers: Vec::new(),
orders: 0,
};
for board in adj.pod_data.boards.values() {
pod.boards.push(board.name.clone());
for packet in board.packets.values() {
match &packet.packet_type {
PacketType::Data(measurements) => {
pod.packets.push((packet.id, measurements.clone()));
}
PacketType::Order(_) => pod.orders += 1,
PacketType::Protection(measurement) => {
let position = usize::from(packet.id.protection_position());
let Some(protection) = position
.checked_sub(1)
.and_then(|index| measurement.protections.get(index))
else {
continue;
};
pod.triggers.push(Trigger {
id: packet.id,
value: violation(measurement, protection.kind),
});
}
PacketType::Message(_) => {}
}
}
}
pod.boards.sort();
pod.packets.sort_by_key(|(id, _)| id.0);
pod.triggers.sort_by_key(|trigger| trigger.id.0);
pod
}
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
tracing_subscriber::fmt().with_env_filter(filter).init();
let options = Options::parse()?;

let adj =
Arc::new(load_from_dir(&options.adj_dir).map_err(|error| {
format!("loading the ADJ in {}: {error}", options.adj_dir.display())
})?);
let pod = FakePod::new(&adj);
tracing::info!(
adj = %options.adj_dir.display(),
boards = pod.boards.len(),
data_packets = pod.packets.len(),
orders = pod.orders,
protections = pod.triggers.len(),
"ADJ loaded"
);

let listener = TcpListener::bind(options.bind).await?;
let address = listener.local_addr()?;
let (sockets, connections) = mpsc::channel(16);
let mut http =
tokio::spawn(async move { station::http::serve(listener, &adj, Some(sockets)).await });

let (broker, client) = Broker::new();
let broker = tokio::spawn(broker.run());
let mut frontends = tokio::spawn(websocket::run(
connections,
client.subscriber(),
Commands::default(),
options.heartbeat,
));
// The publisher owns the only BrokerClient: stopping it stops the broker.
let publisher = tokio::spawn(publish_fake_updates(client, pod, options.interval));

println!("HTTP http://{address}/backend/adj/DataPackets");
println!(" http://{address}/backend/adj/OrderPackets");
println!(" http://{address}/backend/adj/ProtectionPackets");
println!("WS ws://{address}/backend/ws");
println!(r#" {{"topic":"podData/update","payload":{{"subscribe":true}}}}"#);
println!("Ctrl+C to stop");

tokio::select! {
signal = tokio::signal::ctrl_c() => signal?,
// Only with a short heartbeat: run has already traced FrontendDisconnected.
result = &mut frontends => return Ok(result??),
result = &mut http => {
result??;
return Err("HTTP server stopped".into());
}
}

tracing::info!("stopping");
publisher.abort();
let _ = publisher.await;
broker.await?;
frontends.await??;
http.abort();
Ok(())
}

async fn publish_fake_updates(
client: BrokerClient,
pod: FakePod,
period: Duration,
) -> Result<(), broker::Error> {
let start = Instant::now();
let cycle_time = u64::try_from(period.as_nanos()).unwrap_or(u64::MAX);
let mut data_ticker = interval(period);
let mut event_ticker = interval(EVENT_PERIOD);
let mut count = 0;
let mut event = 0_usize;
let mut flapping_connected = None;

loop {
tokio::select! {
_ = data_ticker.tick() => {
count += 1;
let elapsed = start.elapsed();
let connected = (elapsed.as_secs() / FLAP_SECONDS).is_multiple_of(2);
// Connections are state: publish them only when they change.
if flapping_connected != Some(connected) {
flapping_connected = Some(connected);
client.publish_connections(connections(&pod.boards, connected)).await?;
}
client
.publish_data(data(&pod.packets, elapsed.as_secs_f64(), count, cycle_time))
.await?;
}
_ = event_ticker.tick() => {
let round = event / 3;
let trigger = pod.triggers.get(round % pod.triggers.len().max(1));
let board = pod.boards.get(round % pod.boards.len().max(1)).cloned();
match (event % 3, trigger) {
(0, _) => client.publish_message(MessageUpdate {
kind: MessageLevel::Info,
payload: "Text message from ws_test".into(),
board: board.unwrap_or_default(),
origin: "ws_test.rs".into(),
name: "Fake info".into(),
timestamp: now(),
}).await?,
// The frontend completes it from the protections catalog.
(1, Some(trigger)) => client.publish_protection(ProtectionUpdate {
id: trigger.id,
value: trigger.value.clone(),
timestamp: now(),
}).await?,
_ => client.publish_backend_message(BackendMessage::new(
MessageLevel::Warning,
board,
"Backend message from ws_test",
now(),
)).await?,
}
event += 1;
}
}
}
}

/// Every board connected except the first, which follows `flapping_connected`.
fn connections(boards: &[String], flapping_connected: bool) -> ConnectionUpdate {
let connections = boards
.iter()
.enumerate()
.map(|(index, name)| {
let connection = Connection {
name: name.clone(),
is_connected: index != 0 || flapping_connected,
};
(name.clone(), connection)
})
.collect();
ConnectionUpdate(connections)
}

fn data(
packets: &[(AdjId, Vec<Measurement>)],
elapsed: f64,
count: u64,
cycle_time: u64,
) -> DataUpdate {
let packets = packets
.iter()
.map(|(id, measurements)| {
let measurement_updates = measurements
.iter()
.map(|measurement| (measurement.id, reading(measurement, elapsed)))
.collect();
let packet = DataPacketUpdate {
id: *id,
count,
cycle_time,
measurement_updates,
};
(*id, packet)
})
.collect::<HashMap<_, _>>();
DataUpdate(packets)
}

/// A slow wave between 10 and 90, offset by the measurement id so charts
/// don't move in lockstep. Booleans follow its sign; enums step through their
/// options.
fn reading(measurement: &Measurement, elapsed: f64) -> MeasurementUpdate {
let id = measurement.id.0;
let wave = (elapsed / 2.0 + f64::from(id)).sin();
match &measurement.kind {
MeasurementKind::Numeric { wire_type } => {
let last = 50.0 + 40.0 * wave;
let last = match wire_type {
NumericKind::F32 | NumericKind::F64 => last,
_ => last.round(),
};
MeasurementUpdate::Numeric {
last,
average: 50.0,
}
}
MeasurementKind::Boolean => MeasurementUpdate::Boolean(wave > 0.0),
MeasurementKind::Enum { options } => {
let step = (elapsed / 3.0) as usize + usize::from(id);
let option = options.get(step % options.len().max(1));
MeasurementUpdate::Enum(option.cloned().unwrap_or_default())
}
}
}

/// A reading that breaks `kind`, typed like `measurement`.
fn violation(measurement: &Measurement, kind: ProtectionKind) -> Value {
let margin = |reference: f64| reference.abs().max(1.0) * 0.1;
let reading = match kind {
ProtectionKind::Above { limit } => limit + margin(limit),
ProtectionKind::Below { limit } => limit - margin(limit),
ProtectionKind::Range { min, max } => max + margin(max - min),
ProtectionKind::Equal { target } => target,
ProtectionKind::NotEqual { target } => target + 1.0,
};
match &measurement.kind {
MeasurementKind::Numeric { .. } => Value::Number(reading),
MeasurementKind::Boolean => Value::Bool(reading != 0.0),
MeasurementKind::Enum { options } => {
Value::Enum(options.get(reading as usize).cloned().unwrap_or_default())
}
}
}

/// Current UTC time from the system clock.
fn now() -> MessageTimestamp {
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs());
let (year, month, day) = civil_from_days(seconds / 86_400);
let time = seconds % 86_400;
MessageTimestamp {
second: (time % 60) as u8,
minute: (time / 60 % 60) as u8,
hour: (time / 3600) as u8,
day,
month,
year,
}
}

/// Days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's algorithm).
fn civil_from_days(days: u64) -> (u16, u8, u8) {
let z = days + 719_468;
let era = z / 146_097;
let doe = z % 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + u64::from(month <= 2);
(year as u16, month as u8, day as u8)
}
Loading
Loading