Skip to main content

hailstorm/controller/
message.rs

1use crate::communication::protobuf::grpc::AgentSimulationState;
2use crate::controller::model::simulation::SimulationDef;
3use std::time::SystemTime;
4
5/// Errors returned when a simulation control command cannot be applied.
6#[derive(Debug, thiserror::Error)]
7pub enum SimulationControlError {
8    /// The simulation definition is invalid and was not sent to the agents.
9    #[error("Invalid simulation - {0}")]
10    InvalidSimulation(String),
11    /// The command requires a loaded simulation.
12    #[error("No simulation is loaded")]
13    NotLoaded,
14}
15
16#[derive(actix::Message)]
17#[rtype(result = "Result<String, SimulationControlError>")]
18/// Load a new simulation, returning the identifier assigned to it
19pub struct LoadSimulation(pub(super) SimulationDef);
20
21impl LoadSimulation {
22    /// Create a new LoadSimulation message with given simulation definition
23    pub fn new(def: SimulationDef) -> Self {
24        Self(def)
25    }
26
27    /// Extract simulation definition
28    pub fn extract_definition(self) -> SimulationDef {
29        self.0
30    }
31}
32
33#[derive(actix::Message)]
34#[rtype(result = "Result<(), SimulationControlError>")]
35/// Start the loaded simulation at a specific time
36pub struct StartSimulation(pub(super) SystemTime);
37
38impl StartSimulation {
39    /// Create a new StartSimulation message with specific starting time
40    pub fn at(time: SystemTime) -> Self {
41        Self(time)
42    }
43
44    /// Extract start time ts
45    pub fn extract_ts(&self) -> SystemTime {
46        self.0
47    }
48}
49
50#[derive(actix::Message)]
51#[rtype(result = "()")]
52/// Stop the running simulation and unload it from every agent
53pub struct StopSimulation;
54
55#[derive(actix::Message)]
56#[rtype(result = "SimulationStatus")]
57/// Fetch the controller simulation state and the last state reported by each agent
58pub struct GetSimulationStatus;
59
60/// Lifecycle phase of the controller simulation.
61#[derive(Debug, Clone, PartialEq)]
62pub enum SimulationPhase {
63    /// No simulation is loaded.
64    Idle,
65    /// A simulation is loaded and waiting to be started.
66    Ready,
67    /// The simulation has been launched at the given time.
68    Launched {
69        /// Scheduled start time.
70        start_ts: SystemTime,
71    },
72}
73
74/// Last state reported by an agent.
75#[derive(Debug, Clone)]
76pub struct AgentStatus {
77    /// Agent identifier.
78    pub agent_id: u32,
79    /// Simulation state reported by the agent.
80    pub state: AgentSimulationState,
81    /// Identifier of the simulation loaded by the agent, empty when none is loaded.
82    pub simulation_id: String,
83    /// Why the agent could not load `simulation_id`.
84    pub simulation_error: Option<String>,
85    /// Timestamp of the last update received from the agent.
86    pub last_update: SystemTime,
87}
88
89/// Overall progress of the loaded simulation across the connected agents.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum SimulationOutcome {
92    /// No simulation is loaded.
93    Idle,
94    /// Some agents have not confirmed the current simulation yet.
95    Pending,
96    /// Every agent loaded the simulation, which has not been started.
97    Ready,
98    /// Every agent is running (or waiting to start) the simulation.
99    Running,
100    /// At least one agent could not load the simulation.
101    Failed,
102}
103
104/// Snapshot of the controller simulation and of the connected agents.
105#[derive(Debug, Clone, actix::MessageResponse)]
106pub struct SimulationStatus {
107    /// Controller lifecycle phase.
108    pub phase: SimulationPhase,
109    /// Identifier of the loaded simulation, if any.
110    pub simulation_id: Option<String>,
111    /// Connected agents, sorted by identifier.
112    pub agents: Vec<AgentStatus>,
113}
114
115impl SimulationStatus {
116    /// Summarize the agents' confirmations of the current simulation.
117    pub fn outcome(&self) -> SimulationOutcome {
118        let Some(simulation_id) = self.simulation_id.as_deref() else {
119            return SimulationOutcome::Idle;
120        };
121        let current = |agent: &&AgentStatus| agent.simulation_id == simulation_id;
122        if self
123            .agents
124            .iter()
125            .filter(current)
126            .any(|agent| agent.simulation_error.is_some())
127        {
128            return SimulationOutcome::Failed;
129        }
130        let (expected, outcome): (&[AgentSimulationState], _) = match self.phase {
131            SimulationPhase::Idle => return SimulationOutcome::Idle,
132            SimulationPhase::Ready => (&[AgentSimulationState::Ready], SimulationOutcome::Ready),
133            SimulationPhase::Launched { .. } => (
134                &[AgentSimulationState::Waiting, AgentSimulationState::Running],
135                SimulationOutcome::Running,
136            ),
137        };
138        let confirmed = !self.agents.is_empty()
139            && self.agents.iter().all(|agent| {
140                agent.simulation_id == simulation_id && expected.contains(&agent.state)
141            });
142        if confirmed {
143            outcome
144        } else {
145            SimulationOutcome::Pending
146        }
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn agent(
155        agent_id: u32,
156        state: AgentSimulationState,
157        simulation_id: &str,
158        error: Option<&str>,
159    ) -> AgentStatus {
160        AgentStatus {
161            agent_id,
162            state,
163            simulation_id: simulation_id.to_string(),
164            simulation_error: error.map(String::from),
165            last_update: SystemTime::now(),
166        }
167    }
168
169    fn status(phase: SimulationPhase, agents: Vec<AgentStatus>) -> SimulationStatus {
170        SimulationStatus {
171            simulation_id: (phase != SimulationPhase::Idle).then(|| String::from("run")),
172            phase,
173            agents,
174        }
175    }
176
177    #[test]
178    fn outcome_reflects_agent_confirmations() {
179        use AgentSimulationState::*;
180        let launched = || SimulationPhase::Launched {
181            start_ts: SystemTime::now(),
182        };
183        let cases = [
184            (
185                status(SimulationPhase::Idle, vec![agent(1, Idle, "", None)]),
186                SimulationOutcome::Idle,
187            ),
188            (
189                status(SimulationPhase::Ready, vec![]),
190                SimulationOutcome::Pending,
191            ),
192            (
193                status(
194                    SimulationPhase::Ready,
195                    vec![agent(1, Ready, "run", None), agent(2, Ready, "old", None)],
196                ),
197                SimulationOutcome::Pending,
198            ),
199            (
200                status(
201                    SimulationPhase::Ready,
202                    vec![agent(1, Ready, "run", None), agent(2, Ready, "run", None)],
203                ),
204                SimulationOutcome::Ready,
205            ),
206            (
207                status(
208                    SimulationPhase::Ready,
209                    vec![
210                        agent(1, Ready, "run", None),
211                        agent(2, Idle, "run", Some("bad")),
212                    ],
213                ),
214                SimulationOutcome::Failed,
215            ),
216            (
217                status(
218                    SimulationPhase::Ready,
219                    vec![
220                        agent(1, Idle, "old", Some("bad")),
221                        agent(2, Ready, "run", None),
222                    ],
223                ),
224                SimulationOutcome::Pending,
225            ),
226            (
227                status(
228                    launched(),
229                    vec![
230                        agent(1, Waiting, "run", None),
231                        agent(2, Running, "run", None),
232                    ],
233                ),
234                SimulationOutcome::Running,
235            ),
236            (
237                status(launched(), vec![agent(1, Ready, "run", None)]),
238                SimulationOutcome::Pending,
239            ),
240        ];
241        for (index, (status, expected)) in cases.into_iter().enumerate() {
242            assert_eq!(status.outcome(), expected, "case {index}");
243        }
244    }
245}