Skip to main content

mt_net/
lib.rs

1pub use ros2_interfaces_jazzy_rkyv::nav_msgs::msg::Odometry;
2pub use ros2_interfaces_jazzy_rkyv::rosgraph_msgs::msg::Clock;
3pub use ros2_interfaces_jazzy_rkyv::sensor_msgs::msg::{
4    CameraInfo, CompressedImage, Image, Imu, PointCloud2,
5};
6pub use ros2_interfaces_jazzy_rkyv::tf2_msgs::msg::TFMessage;
7use serde::{Deserialize, Serialize};
8use std::collections::{HashMap, HashSet};
9
10#[cfg(feature = "image")]
11pub mod image;
12
13pub const COMPARE_NODE_NAME: &str = "#minot";
14
15#[derive(Clone, Debug, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
16pub enum Qos {
17    Sensor,
18    #[default]
19    SystemDefault,
20    Custom(QosProfile),
21}
22
23#[derive(Deserialize, Debug, Clone)]
24#[serde(untagged)]
25enum PolicyValue {
26    Numeric(i64),
27    String(String),
28}
29
30
31fn normalize_policy(value: PolicyValue, names: &[(i64, &'static str)]) -> String {
32    let unknown = || {
33        names
34            .iter()
35            .find(|(_, name)| *name == "unknown")
36            .map(|(_, name)| (*name).to_string())
37            .expect("every policy mapping lists unknown")
38    };
39
40    match value {
41        PolicyValue::Numeric(n) => names
42            .iter()
43            .find(|(code, _)| *code == n)
44            .map(|(_, name)| (*name).to_string())
45            .unwrap_or_else(unknown),
46        PolicyValue::String(s) => {
47            let s = s.trim().to_ascii_lowercase();
48            // Some writers quote the numeric enumerator, so a string that is
49            // really a number still has to resolve by code.
50            if let Ok(n) = s.parse::<i64>() {
51                return normalize_policy(PolicyValue::Numeric(n), names);
52            }
53            names
54                .iter()
55                .find(|(_, name)| *name == s)
56                .map(|(_, name)| (*name).to_string())
57                .unwrap_or_else(unknown)
58        }
59    }
60}
61
62const HISTORY_POLICIES: &[(i64, &str)] = &[
63    (0, "system_default"),
64    (1, "keep_last"),
65    (2, "keep_all"),
66    (3, "unknown"),
67];
68
69const RELIABILITY_POLICIES: &[(i64, &str)] = &[
70    (0, "system_default"),
71    (1, "reliable"),
72    (2, "best_effort"),
73    (3, "unknown"),
74    (4, "best_available"),
75];
76
77const DURABILITY_POLICIES: &[(i64, &str)] = &[
78    (0, "system_default"),
79    (1, "transient_local"),
80    (2, "volatile"),
81    (3, "unknown"),
82    (4, "best_available"),
83];
84
85const LIVELINESS_POLICIES: &[(i64, &str)] = &[
86    (0, "system_default"),
87    (1, "automatic"),
88    (2, "manual_by_node"),
89    (3, "manual_by_topic"),
90    (4, "unknown"),
91    (5, "best_available"),
92];
93
94fn deserialize_history<'de, D>(deserializer: D) -> Result<String, D::Error>
95where
96    D: serde::Deserializer<'de>,
97{
98    Ok(normalize_policy(
99        PolicyValue::deserialize(deserializer)?,
100        HISTORY_POLICIES,
101    ))
102}
103
104fn deserialize_reliability<'de, D>(deserializer: D) -> Result<String, D::Error>
105where
106    D: serde::Deserializer<'de>,
107{
108    Ok(normalize_policy(
109        PolicyValue::deserialize(deserializer)?,
110        RELIABILITY_POLICIES,
111    ))
112}
113
114fn deserialize_durability<'de, D>(deserializer: D) -> Result<String, D::Error>
115where
116    D: serde::Deserializer<'de>,
117{
118    Ok(normalize_policy(
119        PolicyValue::deserialize(deserializer)?,
120        DURABILITY_POLICIES,
121    ))
122}
123
124fn deserialize_liveliness<'de, D>(deserializer: D) -> Result<String, D::Error>
125where
126    D: serde::Deserializer<'de>,
127{
128    Ok(normalize_policy(
129        PolicyValue::deserialize(deserializer)?,
130        LIVELINESS_POLICIES,
131    ))
132}
133
134#[derive(
135    rkyv::Archive, Deserialize, Debug, Serialize, Clone, rkyv::Deserialize, rkyv::Serialize,
136)]
137pub struct QosProfile {
138    #[serde(deserialize_with = "deserialize_history")]
139    pub history: String,
140    pub depth: i32,
141    #[serde(deserialize_with = "deserialize_reliability")]
142    pub reliability: String,
143    #[serde(deserialize_with = "deserialize_durability")]
144    pub durability: String,
145    pub deadline: QosTime,
146    pub lifespan: QosTime,
147    #[serde(deserialize_with = "deserialize_liveliness")]
148    pub liveliness: String,
149    pub liveliness_lease_duration: QosTime,
150    pub avoid_ros_namespace_conventions: bool,
151}
152
153#[derive(
154    Deserialize, Serialize, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, Clone, Copy,
155)]
156pub struct QosTime {
157    pub sec: u64,
158    pub nsec: u64,
159}
160
161#[allow(clippy::large_enum_variant)]
162#[derive(Clone, Debug, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)]
163pub enum SensorTypeMapped {
164    Lidar(PointCloud2),
165    Imu(Imu),
166    Odometry(Odometry),
167    Clock(Clock),
168    Any(Vec<u8>),
169    // Append variants to preserve the discriminants of existing wire types.
170    Tf(TFMessage),
171    Image(Image),
172    CompressedImage(CompressedImage),
173    CameraInfo(CameraInfo),
174}
175
176#[derive(Clone, Debug, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)]
177pub struct BagMsg {
178    pub topic: String,
179    pub msg_type: String,
180    pub type_description_hash: Option<String>,
181    pub data: SensorTypeMapped,
182    pub qos: Option<Qos>,
183}
184
185#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
186pub enum RatPubRegisterKind {
187    Publish,
188    Subscribe,
189}
190
191#[derive(PartialEq, Eq, Debug, Clone)]
192pub struct Rules {
193    store: HashMap<Variable, Vec<VariableHuman>>,
194    pub cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>>,
195    id_counter: u32,
196}
197
198pub type Client = String;
199pub type Variable = String;
200
201impl Default for Rules {
202    fn default() -> Self {
203        Self::new()
204    }
205}
206
207impl Rules {
208    pub fn new() -> Self {
209        Self {
210            store: HashMap::new(),
211            cache: HashMap::new(),
212            id_counter: 0,
213        }
214    }
215
216    pub fn insert(&mut self, variable: String, strategies: Vec<VariableHuman>) {
217        match self.store.get_mut(&variable) {
218            Some(el) => {
219                el.extend(strategies);
220            }
221            None => {
222                self.store.insert(variable, strategies);
223            }
224        }
225    }
226
227    pub fn new_id(&mut self) -> u32 {
228        self.id_counter += 1;
229        self.id_counter
230    }
231
232    /// Removes a client (ship) from the rules and cache.
233    /// - If the client is the ship performing a Shoot, Catch, Sail, or None action, the entire rule is removed but if there is another partner like in catch or shoot, the partner will be put into the cache with a subscriber/publisher state based on if was receiving it (subscriber) or sending it and the removing client wanted to catch it (publisher)
234    /// - If the client is a target in a Shoot action, it is removed from the target list. If the list becomes empty, the Shoot rule is removed, AND the shooter ship is registered as a publisher in the cache.
235    /// - Any cache registrations for the client are removed.
236    pub fn remove_client(&mut self, client: &str) {
237        let mut variables_to_remove_from_store = Vec::new();
238        let mut cache_registrations_from_store: HashMap<
239            Variable,
240            HashSet<(Client, RatPubRegisterKind)>,
241        > = HashMap::new();
242        let mut store_updates: HashMap<Variable, Vec<VariableHuman>> = HashMap::new();
243
244        for (variable, rules) in self.store.iter_mut() {
245            let mut rules_to_keep_in_variable = Vec::new();
246            let mut variable_has_remaining_rules = false;
247
248            for rule in rules.drain(..) {
249                if rule.ship == client {
250                    // The client performs the action, so the rule goes and any
251                    // partner is put back into the cache in its opposite role.
252                    match &rule.strategy {
253                        Some(ActionPlan::Shoot { target, id: _ }) if !target.is_empty() => {
254                            cache_registrations_from_store
255                                .entry(variable.clone())
256                                .or_default()
257                                .extend(
258                                    target
259                                        .iter()
260                                        .cloned()
261                                        .map(|t| (t, RatPubRegisterKind::Subscribe)),
262                                );
263                        }
264                        Some(ActionPlan::Catch { source, id: _ }) => {
265                            cache_registrations_from_store
266                                .entry(variable.clone())
267                                .or_default()
268                                .insert((source.clone(), RatPubRegisterKind::Publish));
269                        }
270                        // Sail, None and no strategy have no partner.
271                        _ => {}
272                    }
273                } else if let Some(ActionPlan::Shoot { target, id }) = &rule.strategy {
274                    let initial_target_count = target.len();
275                    let new_target = target
276                        .iter()
277                        .filter(|t| t != &client)
278                        .cloned()
279                        .collect::<Vec<_>>();
280
281                    if new_target.len() < initial_target_count {
282                        if new_target.is_empty() {
283                            // Nothing left to shoot at, so the rule goes and the
284                            // shooter returns to the cache as a publisher.
285                            cache_registrations_from_store
286                                .entry(variable.clone())
287                                .or_default()
288                                .insert((rule.ship.clone(), RatPubRegisterKind::Publish));
289                        } else {
290                            rules_to_keep_in_variable.push(VariableHuman {
291                                ship: rule.ship.clone(),
292                                strategy: Some(ActionPlan::Shoot {
293                                    target: new_target,
294                                    id: *id,
295                                }),
296                            });
297                            variable_has_remaining_rules = true;
298                        }
299                    } else {
300                        rules_to_keep_in_variable.push(rule);
301                        variable_has_remaining_rules = true;
302                    }
303                } else if let Some(ActionPlan::Catch { source, id: _ }) = &rule.strategy {
304                    if source == client {
305                        // The source is going, so the catcher returns to the
306                        // cache as a subscriber.
307                        cache_registrations_from_store
308                            .entry(variable.clone())
309                            .or_default()
310                            .insert((rule.ship.clone(), RatPubRegisterKind::Subscribe));
311                    } else {
312                        rules_to_keep_in_variable.push(rule);
313                        variable_has_remaining_rules = true;
314                    }
315                } else {
316                    rules_to_keep_in_variable.push(rule);
317                    variable_has_remaining_rules = true;
318                }
319            }
320
321            if variable_has_remaining_rules {
322                store_updates.insert(variable.clone(), rules_to_keep_in_variable);
323            } else {
324                variables_to_remove_from_store.push(variable.clone());
325            }
326        }
327
328        for (variable, updated_rules) in store_updates {
329            self.store.insert(variable, updated_rules);
330        }
331        for var in variables_to_remove_from_store {
332            self.store.remove(&var);
333        }
334
335        for (variable, registrations) in cache_registrations_from_store {
336            self.cache
337                .entry(variable)
338                .or_default()
339                .extend(registrations);
340        }
341
342        let mut variables_to_remove_from_cache = Vec::new();
343        for (variable, registrations) in self.cache.iter_mut() {
344            let initial_count = registrations.len();
345            registrations.retain(|(c, _)| c != client);
346            if registrations.is_empty() && initial_count > 0 {
347                variables_to_remove_from_cache.push(variable.clone());
348            }
349        }
350
351        for var in variables_to_remove_from_cache {
352            self.cache.remove(&var);
353        }
354
355        // Remaining cache entries may now form new rules.
356        self.resolve_cache();
357    }
358
359    pub fn clear(&mut self) {
360        self.store.clear();
361    }
362
363    pub fn raw(&self) -> &std::collections::HashMap<String, Vec<VariableHuman>> {
364        &self.store
365    }
366
367    /// Resolves cache entries into rules in the store based on existing rules and new registrations.
368    /// Generates only Shoot actions, never Catch actions.
369    /// - If a variable exists in the store AND has existing Shoot rules,
370    ///   cache registrations for that variable are used to update/regenerate
371    ///   the Shoot rules based on the combined set of publishers and subscribers
372    ///   from the store and cache. The cache entry is removed.
373    /// - Variables without Shoot rules need a publisher/subscriber pair *within
374    ///   the cache* to generate new Shoot rules. These are added to a new entry
375    ///   or by extending a non-Shoot entry in the store. If no pair exists in
376    ///   the cache, the cache entry remains.
377    pub fn resolve_cache(&mut self) {
378        // Collected up front so the cache can be modified in the loop.
379        let vars_to_process: Vec<Variable> = self.cache.keys().cloned().collect();
380
381        for var_name in vars_to_process {
382            if let Some(registrations) = self.cache.remove(&var_name) {
383                let mut new_pubs: HashSet<String> = HashSet::new();
384                let mut new_subs: HashSet<String> = HashSet::new();
385
386                for (client, kind) in registrations.iter() {
387                    match kind {
388                        RatPubRegisterKind::Publish => {
389                            new_pubs.insert(client.clone());
390                        }
391                        RatPubRegisterKind::Subscribe => {
392                            new_subs.insert(client.clone());
393                        }
394                    }
395                }
396
397                // Taken out of the store and put back below, once it is known
398                // which of the three cases applies.
399                let existing_rules_option = self.store.remove(&var_name);
400
401                let had_existing_shoot = &existing_rules_option.as_ref().and_then(|rules| {
402                    rules
403                        .iter()
404                        .find(|vh| matches!(vh.strategy, Some(ActionPlan::Shoot { .. })))
405                        .map(|v| match v.strategy.as_ref() {
406                            // TODO cleanup
407                            Some(ap) => match ap {
408                                ActionPlan::Sail => unreachable!(),
409                                ActionPlan::Shoot { target: _, id } => id,
410                                ActionPlan::Catch { .. } => unreachable!(),
411                            },
412                            None => unreachable!(),
413                        })
414                });
415
416                let mut generated_rules: Vec<VariableHuman> = Vec::new();
417
418                match had_existing_shoot {
419                    Some(id) => {
420                        // Existing Shoot rules: regenerate them from the union
421                        // of the store's clients and the cache registrations.
422                        let mut all_pubs: HashSet<String> = HashSet::new();
423                        let mut all_subs: HashSet<String> = HashSet::new();
424                        let mut other_vh: Vec<VariableHuman> = Vec::new();
425                        let id = **id;
426                        if let Some(existing_rules) = existing_rules_option {
427                            for vh in existing_rules {
428                                match vh.strategy {
429                                    Some(ActionPlan::Shoot { target, id: _ }) => {
430                                        all_pubs.insert(vh.ship);
431                                        all_subs.extend(target);
432                                    }
433                                    // A catcher counts as a subscriber here.
434                                    Some(ActionPlan::Catch { source: _, id: _ }) => {
435                                        all_subs.insert(vh.ship);
436                                    }
437                                    _ => {
438                                        other_vh.push(vh);
439                                    }
440                                }
441                            }
442                        }
443                        all_pubs.extend(new_pubs);
444                        all_subs.extend(new_subs);
445
446                        let mut sorted_all_pubs: Vec<String> = all_pubs.into_iter().collect();
447                        sorted_all_pubs.sort();
448                        let mut sorted_all_subs: Vec<String> = all_subs.into_iter().collect();
449                        sorted_all_subs.sort();
450                        generated_rules.extend(other_vh);
451
452                        if !sorted_all_pubs.is_empty() && !sorted_all_subs.is_empty() {
453                            for pub_client in &sorted_all_pubs {
454                                generated_rules.push(VariableHuman {
455                                    ship: pub_client.clone(),
456                                    strategy: Some(ActionPlan::Shoot {
457                                        target: sorted_all_subs.clone(),
458                                        id,
459                                    }),
460                                });
461                            }
462                        }
463
464                        self.store.insert(var_name.clone(), generated_rules);
465                    }
466                    None => {
467                        // No Shoot rules yet, so the cache must supply a whole
468                        // publisher/subscriber pair before any can be generated.
469                        if !new_pubs.is_empty() && !new_subs.is_empty() {
470                            let mut sorted_new_pubs: Vec<String> = new_pubs.into_iter().collect();
471                            sorted_new_pubs.sort();
472                            let mut sorted_new_subs: Vec<String> = new_subs.into_iter().collect();
473                            sorted_new_subs.sort();
474
475                            let mut pair_generated_rules: Vec<VariableHuman> = Vec::new();
476                            let pair_id = self.new_id();
477                            for pub_client in &sorted_new_pubs {
478                                pair_generated_rules.push(VariableHuman {
479                                    ship: pub_client.clone(),
480                                    strategy: Some(ActionPlan::Shoot {
481                                        target: sorted_new_subs.clone(),
482                                        id: pair_id,
483                                    }),
484                                });
485                            }
486
487                            if let Some(mut existing_rules) = existing_rules_option {
488                                existing_rules.extend(pair_generated_rules);
489                                self.store.insert(var_name.clone(), existing_rules);
490                            } else {
491                                self.store.insert(var_name.clone(), pair_generated_rules);
492                            }
493                        } else {
494                            // Nothing to resolve, so store and cache go back
495                            // untouched.
496                            if let Some(existing_rules) = existing_rules_option {
497                                self.store.insert(var_name.clone(), existing_rules);
498                            }
499                            self.cache.insert(var_name.clone(), registrations);
500                        }
501                    }
502                }
503            }
504        }
505    }
506
507    /// Returns all ship names that are subscribers for `var`, from both cache and store.
508    pub fn subscriber_ships(&self, var: &str) -> Vec<String> {
509        let mut ships = Vec::new();
510
511        // Registrations not yet matched into rules.
512        if let Some(entries) = self.cache.get(var) {
513            for (ship, kind) in entries {
514                if *kind == RatPubRegisterKind::Subscribe {
515                    ships.push(ship.clone());
516                }
517            }
518        }
519
520        // Matched rules, where a subscriber holds a Catch action.
521        if let Some(rules) = self.store.get(var) {
522            for vh in rules {
523                if matches!(vh.strategy, Some(ActionPlan::Catch { .. })) {
524                    ships.push(vh.ship.clone());
525                }
526            }
527        }
528
529        ships
530    }
531
532    /// All ship names registered for a variable (store + cache, deduped).
533    pub fn all_ships_for_var(&self, var: &str) -> Vec<String> {
534        let mut ships = HashSet::new();
535
536        if let Some(rules) = self.store.get(var) {
537            for vh in rules {
538                ships.insert(vh.ship.clone());
539                match &vh.strategy {
540                    Some(ActionPlan::Shoot { target, .. }) => {
541                        for t in target {
542                            ships.insert(t.clone());
543                        }
544                    }
545                    Some(ActionPlan::Catch { source, .. }) => {
546                        ships.insert(source.clone());
547                    }
548                    _ => {}
549                }
550            }
551        }
552
553        if let Some(entries) = self.cache.get(var) {
554            for (ship, _) in entries {
555                ships.insert(ship.clone());
556            }
557        }
558
559        ships.into_iter().collect()
560    }
561
562    /// All variable names a given ship appears in (store + cache, deduped).
563    pub fn all_vars_for_ship(&self, ship: &str) -> Vec<String> {
564        let mut vars = HashSet::new();
565
566        for (var, rules) in &self.store {
567            let found = rules.iter().any(|vh| {
568                vh.ship == ship
569                    || matches!(&vh.strategy, Some(ActionPlan::Shoot { target, .. }) if target.iter().any(|t| t == ship))
570                    || matches!(&vh.strategy, Some(ActionPlan::Catch { source, .. }) if source == ship)
571            });
572            if found {
573                vars.insert(var.clone());
574            }
575        }
576
577        for (var, entries) in &self.cache {
578            if entries.iter().any(|(s, _)| s == ship) {
579                vars.insert(var.clone());
580            }
581        }
582
583        vars.into_iter().collect()
584    }
585
586    /// Remove a registration. Leaves the variable in place when other clients
587    /// still use it, so one viewer leaving does not disturb the rest.
588    ///
589    /// Touches both halves of the state, since a client can be in either:
590    /// `cache` holds unresolved registrations, and `resolve_cache` turns them
591    /// into `store` rules where a subscriber exists only as a name inside each
592    /// publisher's `Shoot` target list.
593    pub fn unregister(&mut self, var: &str, client: &str, kind: RatPubRegisterKind) -> bool {
594        let mut removed = false;
595
596        if let Some(clients) = self.cache.get_mut(var) {
597            removed |= clients.remove(&(client.to_owned(), kind.clone()));
598            if clients.is_empty() {
599                self.cache.remove(var);
600            }
601        }
602
603        if let Some(rules) = self.store.get_mut(var) {
604            let present = rules.iter().any(|vh| match (&kind, &vh.strategy) {
605                (RatPubRegisterKind::Publish, Some(ActionPlan::Shoot { .. })) => vh.ship == client,
606                (RatPubRegisterKind::Subscribe, Some(ActionPlan::Catch { .. })) => {
607                    vh.ship == client
608                }
609                (RatPubRegisterKind::Subscribe, Some(ActionPlan::Shoot { target, .. })) => {
610                    target.iter().any(|t| t == client)
611                }
612                _ => false,
613            });
614
615            match kind {
616                RatPubRegisterKind::Publish => rules.retain(|vh| {
617                    !(vh.ship == client && matches!(vh.strategy, Some(ActionPlan::Shoot { .. })))
618                }),
619                RatPubRegisterKind::Subscribe => {
620                    rules.retain(|vh| {
621                        !(vh.ship == client
622                            && matches!(vh.strategy, Some(ActionPlan::Catch { .. })))
623                    });
624                    for vh in rules.iter_mut() {
625                        if let Some(ActionPlan::Shoot { target, .. }) = vh.strategy.as_mut() {
626                            target.retain(|t| t != client);
627                        }
628                    }
629                }
630            }
631
632            // A publisher whose last subscriber left keeps its rule with an
633            // empty target list, so the next subscriber still has something to
634            // be routed from.
635            if rules.is_empty() {
636                self.store.remove(var);
637            }
638            removed |= present;
639        }
640
641        removed
642    }
643
644    pub fn register(&mut self, var: String, client: String, kind: RatPubRegisterKind) {
645        match self.cache.get_mut(&var) {
646            Some(el) => {
647                el.insert((client, kind));
648            }
649            None => {
650                let mut set = HashSet::new();
651                set.insert((client, kind));
652                self.cache.insert(var, set);
653            }
654        }
655
656        self.resolve_cache();
657    }
658}
659
660#[derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, Clone, Debug, PartialEq, Eq)]
661pub struct VariableHuman {
662    pub ship: String,
663    pub strategy: Option<ActionPlan>,
664}
665
666#[derive(
667    rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug, Clone, Default, PartialEq, Eq,
668)]
669pub enum ActionPlan {
670    #[default]
671    Sail,
672    Shoot {
673        target: Vec<String>,
674        id: u32,
675    },
676    Catch {
677        source: String,
678        id: u32,
679    },
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685
686    use std::collections::{HashMap, HashSet};
687
688    // Sorts the outer vector and the targets inside Shoot strategies, so
689    // comparisons do not depend on ordering.
690    fn sort_variable_humans(humans: &mut [VariableHuman]) {
691        humans.sort_by(|a, b| {
692            a.ship
693                .cmp(&b.ship)
694                .then(format!("{:?}", a.strategy).cmp(&format!("{:?}", b.strategy)))
695        });
696        for human in humans.iter_mut() {
697            if let Some(ActionPlan::Shoot { target, id: _ }) = &mut human.strategy {
698                target.sort();
699            }
700        }
701    }
702    fn create_rules() -> Rules {
703        Rules::new()
704    }
705
706    #[test]
707    fn test_remove_client_main_ship_no_partner() {
708        let mut rules = create_rules();
709        rules.insert(
710            "var1".to_string(),
711            vec![VariableHuman {
712                ship: "client1".to_string(),
713                strategy: Some(ActionPlan::Sail),
714            }],
715        );
716
717        rules.remove_client("client1");
718
719        // client1's rule should be removed
720        assert_eq!(rules.store.len(), 0);
721    }
722
723    #[test]
724    fn test_remove_client_main_ship_catch() {
725        let mut rules = create_rules();
726        rules.insert(
727            "var1".to_string(),
728            vec![VariableHuman {
729                ship: "client1".to_string(),
730                strategy: Some(ActionPlan::Catch {
731                    source: "client2".to_string(),
732                    id: 0,
733                }),
734            }],
735        );
736
737        rules.remove_client("client1");
738
739        // client1's rule should be removed from store
740        assert_eq!(rules.store.len(), 0);
741        // client2 should be registered as a publisher in cache and resolved into a shoot rule
742        assert_eq!(rules.cache.len(), 1); // Cache should be resolved
743        let generated_rules = rules.cache.get("var1").unwrap();
744        assert_eq!(generated_rules.len(), 1); // resolve_cache requires a pub/sub pair in cache if no existing shoot rule
745
746        // Re-run with an existing subscriber in the cache so resolution works.
747        let mut rules = create_rules();
748        rules.insert(
749            "var1".to_string(),
750            vec![VariableHuman {
751                ship: "client1".to_string(),
752                strategy: Some(ActionPlan::Catch {
753                    source: "client2".to_string(),
754                    id: 0,
755                }),
756            }],
757        );
758        rules
759            .cache
760            .entry("var1".to_string())
761            .or_default()
762            .insert(("client3".to_string(), RatPubRegisterKind::Subscribe));
763
764        rules.remove_client("client1");
765        assert_eq!(rules.store.len(), 1);
766        assert!(rules.store.contains_key("var1"));
767        let generated_rules = rules.store.get("var1").unwrap();
768        assert_eq!(generated_rules.len(), 1);
769        assert_eq!(generated_rules[0].ship, "client2");
770        assert_eq!(
771            generated_rules[0].strategy,
772            Some(ActionPlan::Shoot {
773                target: vec!["client3".to_string()],
774                id: 1
775            })
776        );
777        assert_eq!(rules.cache.len(), 0); // Cache should be resolved
778    }
779
780    #[test]
781    fn test_remove_client_main_ship_shoot() {
782        let mut rules = create_rules();
783        rules.insert(
784            "var1".to_string(),
785            vec![VariableHuman {
786                ship: "client1".to_string(),
787                strategy: Some(ActionPlan::Shoot {
788                    target: vec!["client2".to_string(), "client3".to_string()],
789                    id: 0,
790                }),
791            }],
792        );
793
794        rules.remove_client("client1");
795
796        // client1's rule should be removed from store
797        assert_eq!(rules.store.len(), 0);
798        // client2 and client3 should be registered as subscribers in cache and resolved
799        let generated_rules = rules.cache.get("var1").unwrap();
800        assert_eq!(generated_rules.len(), 2); // Cache should be resolved
801    }
802
803    #[test]
804    fn test_remove_client_target_in_shoot_partial_removal() {
805        let mut rules = create_rules();
806        rules.insert(
807            "var1".to_string(),
808            vec![
809                VariableHuman {
810                    ship: "shooter1".to_string(),
811                    strategy: Some(ActionPlan::Shoot {
812                        target: vec!["client_to_remove".to_string(), "client2".to_string()],
813                        id: 0,
814                    }),
815                },
816                VariableHuman {
817                    ship: "shooter2".to_string(),
818                    strategy: Some(ActionPlan::Shoot {
819                        target: vec!["client2".to_string(), "client_to_remove".to_string()],
820                        id: 0,
821                    }),
822                },
823            ],
824        );
825
826        rules.remove_client("client_to_remove");
827
828        // client_to_remove should be removed from target lists
829        assert_eq!(rules.store.len(), 1);
830        assert!(rules.store.contains_key("var1"));
831        let remaining_rules = rules.store.get("var1").unwrap();
832        assert_eq!(remaining_rules.len(), 2);
833
834        let rule1 = &remaining_rules[0];
835        let rule2 = &remaining_rules[1];
836
837        // Order might not be guaranteed, check both possibilities
838        if rule1.ship == "shooter1" {
839            assert_eq!(
840                rule1.strategy,
841                Some(ActionPlan::Shoot {
842                    target: vec!["client2".to_string()],
843                    id: 0
844                })
845            );
846            assert_eq!(rule2.ship, "shooter2");
847            assert_eq!(
848                rule2.strategy,
849                Some(ActionPlan::Shoot {
850                    target: vec!["client2".to_string()],
851                    id: 0
852                })
853            );
854        } else {
855            assert_eq!(rule1.ship, "shooter2");
856            assert_eq!(
857                rule1.strategy,
858                Some(ActionPlan::Shoot {
859                    target: vec!["client2".to_string()],
860                    id: 0
861                })
862            );
863            assert_eq!(rule2.ship, "shooter1");
864            assert_eq!(
865                rule2.strategy,
866                Some(ActionPlan::Shoot {
867                    target: vec!["client2".to_string()],
868                    id: 0
869                })
870            );
871        }
872
873        assert_eq!(rules.cache.len(), 0); // No rules were fully removed, no new cache registrations from store
874    }
875
876    #[test]
877    fn test_remove_client_target_in_shoot_full_removal() {
878        let mut rules = create_rules();
879        rules.insert(
880            "var1".to_string(),
881            vec![VariableHuman {
882                ship: "shooter1".to_string(),
883                strategy: Some(ActionPlan::Shoot {
884                    target: vec!["client_to_remove".to_string()],
885                    id: 0,
886                }),
887            }],
888        );
889
890        rules.remove_client("client_to_remove");
891
892        assert_eq!(rules.cache.len(), 1);
893        assert_eq!(rules.store.len(), 0);
894
895        // Re-run with an existing subscriber in the cache so resolution works.
896        let mut rules = create_rules();
897        rules.insert(
898            "var1".to_string(),
899            vec![VariableHuman {
900                ship: "shooter1".to_string(),
901                strategy: Some(ActionPlan::Shoot {
902                    target: vec!["client_to_remove".to_string()],
903                    id: 0,
904                }),
905            }],
906        );
907        rules
908            .cache
909            .entry("var1".to_string())
910            .or_default()
911            .insert(("client2".to_string(), RatPubRegisterKind::Subscribe));
912
913        rules.remove_client("client_to_remove");
914
915        assert_eq!(rules.store.len(), 1);
916        assert!(rules.store.contains_key("var1"));
917        let generated_rules = rules.store.get("var1").unwrap();
918        assert_eq!(generated_rules.len(), 1);
919        assert_eq!(generated_rules[0].ship, "shooter1");
920        assert_eq!(
921            generated_rules[0].strategy,
922            Some(ActionPlan::Shoot {
923                target: vec!["client2".to_string()],
924                id: 1
925            })
926        );
927        assert_eq!(rules.cache.len(), 0); // Cache should be resolved
928    }
929
930    #[test]
931    fn test_remove_client_from_cache_partial_removal() {
932        let mut rules = create_rules();
933        rules
934            .cache
935            .entry("var1".to_string())
936            .or_default()
937            .insert(("client_to_remove".to_string(), RatPubRegisterKind::Publish));
938        rules
939            .cache
940            .entry("var1".to_string())
941            .or_default()
942            .insert(("client2".to_string(), RatPubRegisterKind::Subscribe));
943        rules.cache.entry("var2".to_string()).or_default().insert((
944            "client_to_remove".to_string(),
945            RatPubRegisterKind::Subscribe,
946        ));
947        rules
948            .cache
949            .entry("var2".to_string())
950            .or_default()
951            .insert(("client3".to_string(), RatPubRegisterKind::Publish));
952
953        rules.remove_client("client_to_remove");
954
955        // client_to_remove's cache entries should be removed
956        // var1 cache: should only have client2 (Subscribe)
957        // var2 cache: should only have client3 (Publish)
958        // The cache should then be resolved.
959
960        assert_eq!(rules.cache.len(), 2); // Cache should be resolved
961        assert_eq!(rules.store.len(), 0);
962    }
963
964    #[test]
965    fn test_remove_client_from_cache_full_removal() {
966        let mut rules = create_rules();
967        rules
968            .cache
969            .entry("var1".to_string())
970            .or_default()
971            .insert(("client_to_remove".to_string(), RatPubRegisterKind::Publish));
972
973        rules.remove_client("client_to_remove");
974
975        // var1 cache should be empty and removed
976        assert_eq!(rules.cache.len(), 0);
977        assert_eq!(rules.store.len(), 0); // No cache entries to resolve into store rules
978    }
979
980    #[test]
981    fn test_remove_client_involved_in_multiple_rules_and_variables() {
982        let mut rules = create_rules();
983        rules.insert(
984            "var1".to_string(),
985            vec![
986                VariableHuman {
987                    ship: "client_to_remove".to_string(),
988                    strategy: Some(ActionPlan::Sail),
989                },
990                VariableHuman {
991                    ship: "shooter1".to_string(),
992                    strategy: Some(ActionPlan::Shoot {
993                        target: vec!["client_to_remove".to_string(), "client2".to_string()],
994                        id: 0,
995                    }),
996                },
997            ],
998        );
999        rules.insert(
1000            "var2".to_string(),
1001            vec![VariableHuman {
1002                ship: "client3".to_string(),
1003                strategy: Some(ActionPlan::Catch {
1004                    source: "client_to_remove".to_string(),
1005                    id: 0,
1006                }),
1007            }],
1008        );
1009        rules.cache.entry("var1".to_string()).or_default().insert((
1010            "client_to_remove".to_string(),
1011            RatPubRegisterKind::Subscribe,
1012        ));
1013        rules
1014            .cache
1015            .entry("var3".to_string())
1016            .or_default()
1017            .insert(("client_to_remove".to_string(), RatPubRegisterKind::Publish));
1018        rules
1019            .cache
1020            .entry("var3".to_string())
1021            .or_default()
1022            .insert(("client4".to_string(), RatPubRegisterKind::Subscribe));
1023
1024        rules.remove_client("client_to_remove");
1025
1026        assert_eq!(rules.cache.len(), 2); // Cache should be resolved
1027
1028        assert_eq!(rules.store.len(), 1);
1029        assert!(rules.store.contains_key("var1"));
1030
1031        let var1_rules = rules.store.get("var1").unwrap();
1032        assert_eq!(var1_rules.len(), 1);
1033        assert_eq!(var1_rules[0].ship, "shooter1");
1034        assert_eq!(
1035            var1_rules[0].strategy,
1036            Some(ActionPlan::Shoot {
1037                target: vec!["client2".to_string()],
1038                id: 0
1039            })
1040        );
1041    }
1042
1043    #[test]
1044    fn test_remove_client_not_present() {
1045        let mut rules = create_rules();
1046        rules.insert(
1047            "var1".to_string(),
1048            vec![VariableHuman {
1049                ship: "client1".to_string(),
1050                strategy: Some(ActionPlan::Sail),
1051            }],
1052        );
1053        rules
1054            .cache
1055            .entry("var2".to_string())
1056            .or_default()
1057            .insert(("client2".to_string(), RatPubRegisterKind::Publish));
1058
1059        let initial_store = rules.store.clone();
1060        let initial_cache = rules.cache.clone();
1061
1062        rules.remove_client("client_not_present");
1063
1064        // No changes should occur
1065        assert_eq!(rules.store, initial_store);
1066        assert_eq!(rules.cache, initial_cache);
1067    }
1068    #[test]
1069    fn test_resolve_cache_basic_pair() {
1070        let mut rules = Rules::new();
1071        rules.register(
1072            "position".to_string(),
1073            "ShipA".to_string(),
1074            RatPubRegisterKind::Publish,
1075        );
1076        rules.register(
1077            "position".to_string(),
1078            "ShipB".to_string(),
1079            RatPubRegisterKind::Subscribe,
1080        );
1081
1082        rules.resolve_cache();
1083
1084        // Check the store
1085        let mut expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1086            let mut map = HashMap::new();
1087            let var_humans = vec![VariableHuman {
1088                ship: "ShipA".to_string(),
1089                strategy: Some(ActionPlan::Shoot {
1090                    target: vec!["ShipB".to_string()],
1091                    id: 1,
1092                }),
1093            }];
1094            map.insert("position".to_string(), var_humans);
1095            map
1096        };
1097
1098        let mut actual_store = rules.store.clone();
1099
1100        // Sort both actual and expected for comparison
1101        if let Some(humans) = actual_store.get_mut("position") {
1102            sort_variable_humans(humans);
1103        }
1104        if let Some(humans) = expected_store.get_mut("position") {
1105            sort_variable_humans(humans);
1106        }
1107
1108        assert_eq!(actual_store, expected_store);
1109
1110        // Check the cache
1111        assert!(rules.cache.is_empty());
1112    }
1113
1114    #[test]
1115    fn test_resolve_cache_multiple_pubs_subs() {
1116        let mut rules = Rules::new();
1117        rules.register(
1118            "velocity".to_string(),
1119            "ShipX".to_string(),
1120            RatPubRegisterKind::Publish,
1121        );
1122        rules.register(
1123            "velocity".to_string(),
1124            "ShipY".to_string(),
1125            RatPubRegisterKind::Publish,
1126        );
1127        rules.register(
1128            "velocity".to_string(),
1129            "ShipZ".to_string(),
1130            RatPubRegisterKind::Subscribe,
1131        );
1132        rules.register(
1133            "velocity".to_string(),
1134            "ShipW".to_string(),
1135            RatPubRegisterKind::Subscribe,
1136        );
1137
1138        rules.resolve_cache();
1139
1140        // Check the store
1141        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1142            let mut map = HashMap::new();
1143            // Define the expected rules (order doesn't matter initially, will sort later)
1144            let var_humans = vec![
1145                // Publishers shooting at all subscribers (targets should be sorted by resolve_cache)
1146                VariableHuman {
1147                    ship: "ShipX".to_string(),
1148                    strategy: Some(ActionPlan::Shoot {
1149                        target: vec!["ShipW".to_string(), "ShipZ".to_string()],
1150                        id: 1,
1151                    }),
1152                },
1153                VariableHuman {
1154                    ship: "ShipY".to_string(),
1155                    strategy: Some(ActionPlan::Shoot {
1156                        target: vec!["ShipW".to_string(), "ShipZ".to_string()],
1157                        id: 1,
1158                    }),
1159                },
1160            ];
1161            map.insert("velocity".to_string(), var_humans);
1162            map
1163        };
1164
1165        // Clone and sort the actual store for comparison
1166        let mut actual_store_sorted = rules.store.clone();
1167        if let Some(humans) = actual_store_sorted.get_mut("velocity") {
1168            sort_variable_humans(humans); // Sorts outer vec and inner targets
1169        }
1170
1171        // Clone and sort the expected store for comparison
1172        let mut expected_store_sorted = expected_store.clone();
1173        if let Some(humans) = expected_store_sorted.get_mut("velocity") {
1174            sort_variable_humans(humans); // Sorts outer vec and inner targets
1175        }
1176
1177        assert_eq!(actual_store_sorted, expected_store_sorted);
1178
1179        // Check the cache
1180        assert!(rules.cache.is_empty());
1181    }
1182
1183    #[test]
1184    fn test_resolve_cache_no_pair_pubs_only() {
1185        let mut rules = Rules::new();
1186        rules.register(
1187            "fuel".to_string(),
1188            "ShipA".to_string(),
1189            RatPubRegisterKind::Publish,
1190        );
1191        rules.register(
1192            "fuel".to_string(),
1193            "ShipC".to_string(),
1194            RatPubRegisterKind::Publish,
1195        );
1196
1197        rules.resolve_cache();
1198
1199        // Check the store - should be unchanged as 'fuel' was not in store and no pair formed
1200        assert!(rules.store.is_empty());
1201
1202        // Check the cache - entries should still be there
1203        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1204            let mut map = HashMap::new();
1205            let mut set = HashSet::new();
1206            set.insert(("ShipA".to_string(), RatPubRegisterKind::Publish));
1207            set.insert(("ShipC".to_string(), RatPubRegisterKind::Publish));
1208            map.insert("fuel".to_string(), set);
1209            map
1210        };
1211        assert_eq!(rules.cache, expected_cache);
1212    }
1213
1214    #[test]
1215    fn test_resolve_cache_no_pair_subs_only() {
1216        let mut rules = Rules::new();
1217        rules.register(
1218            "cargo".to_string(),
1219            "ShipB".to_string(),
1220            RatPubRegisterKind::Subscribe,
1221        );
1222        rules.register(
1223            "cargo".to_string(),
1224            "ShipD".to_string(),
1225            RatPubRegisterKind::Subscribe,
1226        );
1227
1228        rules.resolve_cache();
1229
1230        // Check the store - should be unchanged as 'cargo' was not in store and no pair formed
1231        assert!(rules.store.is_empty());
1232
1233        // Check the cache - entries should still be there
1234        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1235            let mut map = HashMap::new();
1236            let mut set = HashSet::new();
1237            set.insert(("ShipB".to_string(), RatPubRegisterKind::Subscribe));
1238            set.insert(("ShipD".to_string(), RatPubRegisterKind::Subscribe));
1239            map.insert("cargo".to_string(), set);
1240            map
1241        };
1242        assert_eq!(rules.cache, expected_cache);
1243    }
1244
1245    #[test]
1246    fn test_resolve_cache_mixed_variables() {
1247        let mut rules = Rules::new();
1248        // Variable with a pair (should be resolved and added to store)
1249        rules.register(
1250            "shields".to_string(),
1251            "ShipF".to_string(),
1252            RatPubRegisterKind::Publish,
1253        );
1254        rules.register(
1255            "shields".to_string(),
1256            "ShipG".to_string(),
1257            RatPubRegisterKind::Subscribe,
1258        );
1259
1260        // Variable without a pair (should remain in cache)
1261        rules.register(
1262            "waypoints".to_string(),
1263            "ShipH".to_string(),
1264            RatPubRegisterKind::Publish,
1265        );
1266
1267        rules.resolve_cache();
1268
1269        // Check the store - only 'shields' should be present, generated from the pair
1270        let mut expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1271            let mut map = HashMap::new();
1272            let var_humans = vec![VariableHuman {
1273                ship: "ShipF".to_string(),
1274                strategy: Some(ActionPlan::Shoot {
1275                    target: vec!["ShipG".to_string()],
1276                    id: 1,
1277                }),
1278            }];
1279            map.insert("shields".to_string(), var_humans);
1280            map
1281        };
1282
1283        let mut actual_store = rules.store.clone();
1284
1285        // Sort both actual and expected for comparison
1286        if let Some(humans) = actual_store.get_mut("shields") {
1287            sort_variable_humans(humans);
1288        }
1289        if let Some(humans) = expected_store.get_mut("shields") {
1290            sort_variable_humans(humans);
1291        }
1292
1293        assert_eq!(actual_store, expected_store);
1294
1295        // Check the cache - only 'waypoints' should remain
1296        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1297            let mut map = HashMap::new();
1298            let mut set = HashSet::new();
1299            set.insert(("ShipH".to_string(), RatPubRegisterKind::Publish));
1300            map.insert("waypoints".to_string(), set);
1301            map
1302        };
1303        assert_eq!(rules.cache, expected_cache);
1304    }
1305
1306    #[test]
1307    fn test_resolve_cache_state_after_mixed_plus_new_subs() {
1308        let mut rules = Rules::new();
1309
1310        // Set up the state expected after test_resolve_cache_mixed_variables
1311        // Store should have 'shields' rules
1312        let shields_rules = vec![VariableHuman {
1313            ship: "ShipF".to_string(),
1314            strategy: Some(ActionPlan::Shoot {
1315                target: vec!["ShipG".to_string()],
1316                id: 0,
1317            }),
1318        }];
1319        rules.insert("shields".to_string(), shields_rules.clone());
1320
1321        // Cache should have 'waypoints' pub-only registration
1322        rules.register(
1323            "waypoints".to_string(),
1324            "ShipH".to_string(),
1325            RatPubRegisterKind::Publish,
1326        );
1327
1328        // Add new cache entries: subs-only for a new topic 'status'
1329        rules.register(
1330            "status".to_string(),
1331            "ShipI".to_string(),
1332            RatPubRegisterKind::Subscribe,
1333        );
1334        rules.register(
1335            "status".to_string(),
1336            "ShipJ".to_string(),
1337            RatPubRegisterKind::Subscribe,
1338        );
1339
1340        // Clone initial states to compare against after resolution
1341        let initial_store = rules.store.clone();
1342        let initial_cache = rules.cache.clone();
1343
1344        rules.resolve_cache();
1345
1346        // Expected: Store remains unchanged ('status' cache didn't form pair, 'waypoints' still no sub)
1347        // We need to sort the initial store for comparison as insert order isn't guaranteed
1348        let mut initial_store_sorted = initial_store.clone();
1349        if let Some(humans) = initial_store_sorted.get_mut("shields") {
1350            sort_variable_humans(humans);
1351        }
1352        let mut actual_store_sorted = rules.store.clone();
1353        if let Some(humans) = actual_store_sorted.get_mut("shields") {
1354            sort_variable_humans(humans);
1355        }
1356
1357        assert_eq!(actual_store_sorted, initial_store_sorted);
1358
1359        // Expected: Cache remains unchanged ('status' and 'waypoints' entries persist)
1360        assert_eq!(rules.cache, initial_cache);
1361    }
1362
1363    #[test]
1364    fn test_resolve_cache_state_after_prev_plus_new_pub() {
1365        let mut rules = Rules::new();
1366
1367        // Set up the state expected after the previous test
1368        // Store should have 'shields' rules
1369        let shields_rules = vec![VariableHuman {
1370            ship: "ShipF".to_string(),
1371            strategy: Some(ActionPlan::Shoot {
1372                target: vec!["ShipG".to_string()],
1373                id: 0,
1374            }),
1375        }];
1376        rules.insert("shields".to_string(), shields_rules.clone());
1377
1378        // Cache should have 'waypoints' pub-only registration
1379        rules.register(
1380            "waypoints".to_string(),
1381            "ShipH".to_string(),
1382            RatPubRegisterKind::Publish,
1383        );
1384        // Cache should have 'status' subs-only registrations
1385        rules.register(
1386            "status".to_string(),
1387            "ShipI".to_string(),
1388            RatPubRegisterKind::Subscribe,
1389        );
1390        rules.register(
1391            "status".to_string(),
1392            "ShipJ".to_string(),
1393            RatPubRegisterKind::Subscribe,
1394        );
1395
1396        // Add the new cache entry: publisher for 'status'
1397        rules.register(
1398            "status".to_string(),
1399            "ShipK".to_string(),
1400            RatPubRegisterKind::Publish,
1401        );
1402
1403        rules.resolve_cache();
1404
1405        // Check the store - Should contain original 'shields' rules + new 'status' rules from the pair
1406        let mut expected_store: HashMap<Variable, Vec<VariableHuman>> = HashMap::new();
1407        expected_store.insert("shields".to_string(), shields_rules); // Original shields rules
1408
1409        // Expected 'status' rules (ShipK publishes, ShipI and ShipJ subscribe)
1410        let status_rules = vec![VariableHuman {
1411            ship: "ShipK".to_string(),
1412            strategy: Some(ActionPlan::Shoot {
1413                target: vec!["ShipI".to_string(), "ShipJ".to_string()],
1414                id: 1,
1415            }),
1416        }];
1417        expected_store.insert("status".to_string(), status_rules);
1418
1419        let mut actual_store_sorted = rules.store.clone();
1420        if let Some(humans) = actual_store_sorted.get_mut("shields") {
1421            sort_variable_humans(humans);
1422        }
1423        if let Some(humans) = actual_store_sorted.get_mut("status") {
1424            sort_variable_humans(humans);
1425        }
1426
1427        let mut expected_store_sorted = expected_store.clone();
1428        if let Some(humans) = expected_store_sorted.get_mut("shields") {
1429            sort_variable_humans(humans);
1430        }
1431        if let Some(humans) = expected_store_sorted.get_mut("status") {
1432            sort_variable_humans(humans);
1433        }
1434
1435        assert_eq!(actual_store_sorted, expected_store_sorted);
1436
1437        // Check the cache - 'waypoints' should remain, 'status' should be gone
1438        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1439            let mut map = HashMap::new();
1440            let mut set = HashSet::new();
1441            set.insert(("ShipH".to_string(), RatPubRegisterKind::Publish));
1442            map.insert("waypoints".to_string(), set);
1443            map
1444        };
1445        assert_eq!(rules.cache, expected_cache);
1446    }
1447
1448    #[test]
1449    fn test_resolve_cache_empty_cache() {
1450        let mut rules = Rules::new();
1451        // Add some initial data to store to ensure it's not affected
1452        rules.insert(
1453            "initial".to_string(),
1454            vec![VariableHuman {
1455                ship: "ShipI".to_string(),
1456                strategy: Some(ActionPlan::Sail),
1457            }],
1458        );
1459
1460        rules.resolve_cache();
1461
1462        // Store should be unchanged
1463        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1464            let mut map = HashMap::new();
1465            map.insert(
1466                "initial".to_string(),
1467                vec![VariableHuman {
1468                    ship: "ShipI".to_string(),
1469                    strategy: Some(ActionPlan::Sail),
1470                }],
1471            );
1472            map
1473        };
1474        assert_eq!(rules.store, expected_store);
1475
1476        // Cache should remain empty
1477        assert!(rules.cache.is_empty());
1478    }
1479
1480    #[test]
1481    fn test_resolve_cache_store_with_rules_add_sub() {
1482        let mut rules = Rules::new();
1483        let var_name = "data_stream".to_string();
1484
1485        // Initial Shoot/Catch rules in store
1486        rules.insert(
1487            var_name.clone(),
1488            vec![
1489                VariableHuman {
1490                    ship: "ShipA".to_string(),
1491                    strategy: Some(ActionPlan::Shoot {
1492                        target: vec!["ShipB".to_string()],
1493                        id: 0,
1494                    }),
1495                },
1496                VariableHuman {
1497                    ship: "MonitorShip".to_string(),
1498                    strategy: Some(ActionPlan::Sail),
1499                }, // Existing Sail rule
1500            ],
1501        );
1502
1503        // Add registration to cache: new subscriber
1504        rules.register(
1505            var_name.clone(),
1506            "ShipC".to_string(),
1507            RatPubRegisterKind::Subscribe,
1508        );
1509
1510        rules.resolve_cache();
1511
1512        // Check the store - Should have updated Shoot for ShipA and new Catch for ShipC
1513        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1514            let mut map = HashMap::new();
1515            // Combined unique pubs: ShipA (from store)
1516            // Combined unique subs: ShipB (from store), ShipC (from cache)
1517            let var_humans = vec![
1518                VariableHuman {
1519                    ship: "MonitorShip".to_string(),
1520                    strategy: Some(ActionPlan::Sail),
1521                }, // Keep existing Sail rule
1522                VariableHuman {
1523                    ship: "ShipA".to_string(),
1524                    strategy: Some(ActionPlan::Shoot {
1525                        target: vec!["ShipB".to_string(), "ShipC".to_string()],
1526                        id: 0,
1527                    }),
1528                }, // Updated target list
1529            ];
1530            map.insert(var_name.clone(), var_humans);
1531            map
1532        };
1533
1534        let mut actual_store_sorted = rules.store.clone();
1535        if let Some(humans) = actual_store_sorted.get_mut(&var_name) {
1536            sort_variable_humans(humans);
1537        }
1538
1539        let mut expected_store_sorted = expected_store.clone();
1540        if let Some(humans) = expected_store_sorted.get_mut(&var_name) {
1541            sort_variable_humans(humans);
1542        }
1543
1544        assert_eq!(actual_store_sorted, expected_store_sorted);
1545
1546        // Check the cache - entry for 'data_stream' should be removed
1547        assert!(!rules.cache.contains_key(&var_name));
1548        assert!(rules.cache.is_empty()); // Assuming no other cache entries
1549    }
1550
1551    #[test]
1552    fn test_resolve_cache_store_with_rules_add_pub() {
1553        let mut rules = Rules::new();
1554        let var_name = "data_stream".to_string();
1555
1556        // Initial Shoot/Catch rules in store
1557        rules.insert(
1558            var_name.clone(),
1559            vec![
1560                VariableHuman {
1561                    ship: "ShipA".to_string(),
1562                    strategy: Some(ActionPlan::Shoot {
1563                        target: vec!["ShipB".to_string()],
1564                        id: 0,
1565                    }),
1566                },
1567                VariableHuman {
1568                    ship: "MonitorShip".to_string(),
1569                    strategy: Some(ActionPlan::Sail),
1570                }, // Existing Sail rule
1571            ],
1572        );
1573
1574        // Add registration to cache: new subscriber
1575        rules.register(
1576            var_name.clone(),
1577            "ShipC".to_string(),
1578            RatPubRegisterKind::Publish,
1579        );
1580
1581        rules.resolve_cache();
1582
1583        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1584            let mut map = HashMap::new();
1585            let var_humans = vec![
1586                VariableHuman {
1587                    ship: "MonitorShip".to_string(),
1588                    strategy: Some(ActionPlan::Sail),
1589                }, // Keep existing Sail rule
1590                VariableHuman {
1591                    ship: "ShipA".to_string(),
1592                    strategy: Some(ActionPlan::Shoot {
1593                        target: vec!["ShipB".to_string()],
1594                        id: 0,
1595                    }),
1596                }, // Existing Catch rule remains
1597                VariableHuman {
1598                    ship: "ShipC".to_string(),
1599                    strategy: Some(ActionPlan::Shoot {
1600                        target: vec!["ShipB".to_string()],
1601                        id: 0,
1602                    }),
1603                },
1604            ];
1605            map.insert(var_name.clone(), var_humans);
1606            map
1607        };
1608
1609        let mut actual_store_sorted = rules.store.clone();
1610        if let Some(humans) = actual_store_sorted.get_mut(&var_name) {
1611            sort_variable_humans(humans);
1612        }
1613
1614        let mut expected_store_sorted = expected_store.clone();
1615        if let Some(humans) = expected_store_sorted.get_mut(&var_name) {
1616            sort_variable_humans(humans);
1617        }
1618
1619        assert_eq!(actual_store_sorted, expected_store_sorted);
1620
1621        // Check the cache - entry for 'data_stream' should be removed
1622        assert!(!rules.cache.contains_key(&var_name));
1623        assert!(rules.cache.is_empty()); // Assuming no other cache entries
1624    }
1625
1626    #[test]
1627    fn test_resolve_cache_store_with_rules_add_pub_sub() {
1628        let mut rules = Rules::new();
1629        let var_name = "telemetry".to_string();
1630
1631        // Initial Shoot/Catch rules in store
1632        rules.insert(
1633            var_name.clone(),
1634            vec![VariableHuman {
1635                ship: "BaseStation".to_string(),
1636                strategy: Some(ActionPlan::Shoot {
1637                    target: vec!["Rover1".to_string()],
1638                    id: 0,
1639                }),
1640            }],
1641        );
1642
1643        // Add registrations to cache: new publisher and new subscriber
1644        rules.register(
1645            var_name.clone(),
1646            "BaseStationBackup".to_string(),
1647            RatPubRegisterKind::Publish,
1648        );
1649        rules.register(
1650            var_name.clone(),
1651            "Rover2".to_string(),
1652            RatPubRegisterKind::Subscribe,
1653        );
1654
1655        rules.resolve_cache();
1656
1657        // Check the store - Should update all Shoot/Catch rules based on all 4 ships
1658        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1659            let mut map = HashMap::new();
1660            // Combined unique pubs: BaseStation (store), BaseStationBackup (cache)
1661            // Combined unique subs: Rover1 (store), Rover2 (cache)
1662            let all_subs = vec!["Rover1".to_string(), "Rover2".to_string()]; // Already sorted
1663
1664            let var_humans = vec![
1665                // Shoot rules for all pubs targeting all subs
1666                VariableHuman {
1667                    ship: "BaseStation".to_string(),
1668                    strategy: Some(ActionPlan::Shoot {
1669                        target: all_subs.clone(),
1670                        id: 0,
1671                    }),
1672                },
1673                VariableHuman {
1674                    ship: "BaseStationBackup".to_string(),
1675                    strategy: Some(ActionPlan::Shoot {
1676                        target: all_subs.clone(),
1677                        id: 0,
1678                    }),
1679                },
1680            ];
1681            map.insert(var_name.clone(), var_humans);
1682            map
1683        };
1684
1685        let mut actual_store_sorted = rules.store.clone();
1686        if let Some(humans) = actual_store_sorted.get_mut(&var_name) {
1687            sort_variable_humans(humans);
1688        }
1689
1690        let mut expected_store_sorted = expected_store.clone();
1691        if let Some(humans) = expected_store_sorted.get_mut(&var_name) {
1692            sort_variable_humans(humans);
1693        }
1694
1695        assert_eq!(actual_store_sorted, expected_store_sorted);
1696
1697        // Check the cache - entry for 'telemetry' should be removed
1698        assert!(!rules.cache.contains_key(&var_name));
1699        assert!(rules.cache.is_empty()); // Assuming no other cache entries
1700    }
1701}
1702
1703#[cfg(test)]
1704mod unregister_tests {
1705    use super::{RatPubRegisterKind, Rules};
1706
1707    fn rules() -> Rules {
1708        Rules::default()
1709    }
1710
1711    #[test]
1712    fn unregistering_removes_only_that_client() {
1713        let mut rules = rules();
1714        rules.register(
1715            "clouds".into(),
1716            "viewer".into(),
1717            RatPubRegisterKind::Subscribe,
1718        );
1719        rules.register(
1720            "clouds".into(),
1721            "logger".into(),
1722            RatPubRegisterKind::Subscribe,
1723        );
1724
1725        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1726
1727        let remaining = rules.cache.get("clouds").expect("topic still in use");
1728        assert!(remaining.contains(&("logger".to_string(), RatPubRegisterKind::Subscribe)));
1729        assert!(!remaining.contains(&("viewer".to_string(), RatPubRegisterKind::Subscribe)));
1730    }
1731
1732    /// The point of unsubscribing is that you can subscribe again. Dropping the
1733    /// publisher along with its last subscriber would leave the next subscriber
1734    /// with nothing to be routed from.
1735    #[test]
1736    fn a_topic_still_routes_after_its_only_subscriber_leaves_and_another_joins() {
1737        let mut rules = rules();
1738        rules.register(
1739            "clouds".into(),
1740            "pelorus".into(),
1741            RatPubRegisterKind::Publish,
1742        );
1743        rules.register(
1744            "clouds".into(),
1745            "viewer".into(),
1746            RatPubRegisterKind::Subscribe,
1747        );
1748
1749        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1750        assert!(!targets_of(&rules, "clouds").contains(&"viewer".to_string()));
1751
1752        rules.register(
1753            "clouds".into(),
1754            "viewer2".into(),
1755            RatPubRegisterKind::Subscribe,
1756        );
1757        assert!(
1758            targets_of(&rules, "clouds").contains(&"viewer2".to_string()),
1759            "a new subscriber must still be routed from the existing publisher"
1760        );
1761    }
1762
1763    /// Every subscriber a publisher sends to, across all its rules.
1764    fn targets_of(rules: &Rules, var: &str) -> Vec<String> {
1765        rules
1766            .store
1767            .get(var)
1768            .map(|entries| {
1769                entries
1770                    .iter()
1771                    .filter_map(|vh| match &vh.strategy {
1772                        Some(super::ActionPlan::Shoot { target, .. }) => Some(target.clone()),
1773                        _ => None,
1774                    })
1775                    .flatten()
1776                    .collect()
1777            })
1778            .unwrap_or_default()
1779    }
1780
1781    #[test]
1782    fn the_last_client_leaving_drops_the_topic() {
1783        let mut rules = rules();
1784        rules.register(
1785            "clouds".into(),
1786            "viewer".into(),
1787            RatPubRegisterKind::Subscribe,
1788        );
1789        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1790        assert!(!rules.cache.contains_key("clouds"));
1791        assert!(!rules.store.contains_key("clouds"));
1792    }
1793
1794    /// Duplicate and unknown unsubscribe requests report an unchanged state so
1795    /// the coordinator can skip work.
1796    #[test]
1797    fn unregistering_what_was_never_registered_reports_no_change() {
1798        let mut rules = rules();
1799        rules.register(
1800            "clouds".into(),
1801            "viewer".into(),
1802            RatPubRegisterKind::Subscribe,
1803        );
1804
1805        assert!(!rules.unregister("other", "viewer", RatPubRegisterKind::Subscribe));
1806        assert!(!rules.unregister("clouds", "someone", RatPubRegisterKind::Subscribe));
1807        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1808        assert!(!rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1809    }
1810}