#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
use std::collections::VecDeque;
use iec61850_kit::common::{Instant, TimeQuality, UtcTime};
use iec61850_kit::proto::data::Value;
use iec61850_kit::proto::ethernet::{ETHERTYPE_GOOSE, FrameHeader, MacAddr};
use iec61850_kit::proto::goose::{Invalid, Publisher, PublisherConfig, Retransmission, Subscriber, SubscriberConfig, SubscriberEvent, SubscriptionKey};
struct Rng(u64);
impl Rng {
fn next_u64(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn chance(&mut self, percent: u32) -> bool {
self.next_u64() % 100 < u64::from(percent)
}
fn range(&mut self, n: u64) -> u64 {
if n == 0 { 0 } else { self.next_u64() % n }
}
}
fn publisher_config() -> PublisherConfig {
PublisherConfig {
header: FrameHeader {
dst: MacAddr::GOOSE_BASE,
src: MacAddr([2, 0, 0, 0, 0, 1]),
vlan: None,
ethertype: ETHERTYPE_GOOSE,
appid: 1,
reserved1: 0,
reserved2: 0,
},
gocb_ref: "IED1LD0/LLN0$GO$gcbTrip".into(),
dat_set: "IED1LD0/LLN0$dsTrip".into(),
go_id: Some("IED1".into()),
conf_rev: 1,
retransmission: Retransmission { min_time_ms: 4, max_time_ms: 100, tal_factor: 2 },
simulation: false,
nds_com: false,
}
}
fn subscriber() -> Subscriber {
Subscriber::new(SubscriberConfig::new(SubscriptionKey { dst: MacAddr::GOOSE_BASE, appid: 1, gocb_ref: "IED1LD0/LLN0$GO$gcbTrip".into() }).with_conf_rev(1))
}
fn run(seed: u64, steps: u32) -> u64 {
let mut rng = Rng(seed | 1);
let mut pubr = Publisher::new(publisher_config(), &[Value::Boolean(false)], UtcTime::default()).unwrap();
let mut sub = subscriber();
let mut wire: VecDeque<(Instant, Vec<u8>)> = VecDeque::new();
let mut seen: Vec<Vec<u8>> = Vec::new();
let mut now = Instant::ZERO;
let mut trip = false;
let mut published_states: u64 = 1;
let mut last_delivered_st: Option<u32> = None;
let mut live = false;
let mut expected_missed: u64 = 0;
let mut partitioned_until = Instant::ZERO;
for step in 0..steps {
now = now.plus_millis(1 + rng.range(3));
if rng.chance(6) {
trip = !trip;
let t = UtcTime::from_unix(1_700_000_000 + step, 0, TimeQuality::SYNCHRONIZED);
pubr.publish(now, &[Value::Boolean(trip)], t).unwrap();
published_states += 1;
} else if pubr.next_timeout().is_some_and(|d| now >= d) {
pubr.on_timeout(now).unwrap();
}
if let Some(frame) = pubr.poll_transmit() {
let frame = frame.to_vec();
seen.push(frame.clone());
if rng.chance(15) {
} else {
let delay = Instant(now.0 + rng.range(3_000_000));
wire.push_back((delay, frame.clone()));
if rng.chance(10) {
wire.push_back((Instant(now.0 + rng.range(6_000_000)), frame));
}
}
}
if rng.chance(8) && !seen.is_empty() {
let old = seen[rng.range(seen.len() as u64) as usize].clone();
wire.push_back((now, old));
}
if now >= partitioned_until && rng.chance(1) {
partitioned_until = now.plus_millis(250);
}
if rng.chance(50) {
wire.make_contiguous().sort_by_key(|(t, _)| *t);
}
let mut deliverable: Vec<(Instant, Vec<u8>)> = Vec::new();
wire.retain(|(t, f)| {
if *t <= now {
deliverable.push((*t, f.clone()));
false
} else {
true
}
});
for (_, frame) in deliverable {
if now < partitioned_until {
continue;
}
for event in sub.feed(now, &frame) {
match event {
SubscriberEvent::NewState { st_num, .. } => {
if let (Some(prev), true) = (last_delivered_st, live) {
assert!(st_num > prev, "seed {seed}: went back to stNum {st_num} from {prev} with no Expired in between");
expected_missed += u64::from(st_num - prev - 1);
}
last_delivered_st = Some(st_num);
live = true;
}
SubscriberEvent::Retransmission { .. } => live = true,
SubscriberEvent::Expired => live = false,
SubscriberEvent::Invalid(Invalid::Malformed(e)) => {
panic!("seed {seed}: the publisher emitted a frame its own decoder rejects: {e}")
}
SubscriberEvent::Invalid(Invalid::MemberCountMismatch | Invalid::SimulationMismatch) => {
panic!("seed {seed}: the publisher emitted an inconsistent frame")
}
SubscriberEvent::ConfRevMismatch { .. } => panic!("seed {seed}: confRev is constant in this run"),
_ => {}
}
}
}
sub.on_timeout(now);
while let Some(event) = sub.poll_event() {
if let SubscriberEvent::Expired = event {
assert!(sub.is_expired(), "seed {seed}: Expired was reported but the flag is not set");
live = false;
}
}
if let Some(st) = sub.st_num() {
assert!(u64::from(st) <= published_states, "seed {seed}: subscriber invented stNum {st} (published {published_states})");
}
assert_eq!(sub.next_timeout().is_none(), sub.st_num().is_none() || sub.is_expired(), "seed {seed}: timeout bookkeeping");
}
let stats = sub.stats();
assert!(stats.state_changes > 0, "seed {seed}: no state reached the subscriber; the run tested nothing");
assert_eq!(stats.accepted, stats.state_changes + stats.retransmissions, "seed {seed}: accepted frames must be states or retransmissions");
assert_eq!(stats.malformed, 0, "seed {seed}");
assert_eq!(stats.simulation_mismatches, 0, "seed {seed}");
assert_eq!(stats.states_missed, expected_missed, "seed {seed}: missed-state count disagrees with the event stream");
assert_eq!(stats.state_gaps > 0, expected_missed > 0, "seed {seed}: a gap and a missed state must go together");
stats.state_changes
}
#[test]
fn publisher_and_subscriber_hold_their_invariants_under_an_adversarial_network() {
let seeds: Vec<u64> = match std::env::var("SIM_SEED") {
Ok(s) => vec![s.parse().expect("SIM_SEED must be a number")],
Err(_) => (1..=64).collect(),
};
for seed in seeds {
run(seed, 400);
}
}
#[test]
fn a_replayed_frame_is_never_accepted_while_the_state_is_live() {
let mut pubr = Publisher::new(publisher_config(), &[Value::Boolean(false)], UtcTime::default()).unwrap();
let mut sub = subscriber();
let now = Instant::ZERO;
pubr.on_timeout(now).unwrap();
let first = pubr.poll_transmit().unwrap().to_vec();
assert!(matches!(sub.feed(now, &first).as_slice(), [SubscriberEvent::NewState { st_num: 1, .. }]));
pubr.publish(now, &[Value::Boolean(true)], UtcTime::from_unix(2, 0, TimeQuality::SYNCHRONIZED)).unwrap();
let second = pubr.poll_transmit().unwrap().to_vec();
assert!(matches!(sub.feed(now, &second).as_slice(), [SubscriberEvent::NewState { st_num: 2, .. }]));
assert!(matches!(sub.feed(now, &first).as_slice(), [SubscriberEvent::Invalid(Invalid::Replay { st_num: 1, .. })]));
assert_eq!(sub.st_num(), Some(2), "a replay must not move the subscriber back");
assert!(matches!(sub.feed(now, &second).as_slice(), [SubscriberEvent::Invalid(Invalid::Replay { st_num: 2, .. })]));
assert_eq!(sub.stats().replays, 2);
}
#[test]
fn the_publisher_keeps_the_subscription_alive_by_itself() {
let mut pubr = Publisher::new(publisher_config(), &[Value::Boolean(false)], UtcTime::default()).unwrap();
let mut sub = subscriber();
for _ in 0..200 {
let now = pubr.next_timeout().expect("a publisher always has a next frame due");
pubr.on_timeout(now).unwrap();
let frame = pubr.poll_transmit().expect("the timer came due, so there is a frame").to_vec();
sub.on_frame(now, &frame);
sub.on_timeout(now);
while sub.poll_event().is_some() {}
assert!(!sub.is_expired(), "the subscription expired while the publisher was transmitting on time");
}
let deadline = sub.next_timeout().unwrap();
sub.on_timeout(deadline);
assert!(sub.is_expired(), "the subscription must expire once TAL elapses with no frame");
}