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, LaserScan, 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
30fn normalize_policy(value: PolicyValue, names: &[(i64, &'static str)]) -> String {
31    let unknown = || {
32        names
33            .iter()
34            .find(|(_, name)| *name == "unknown")
35            .map(|(_, name)| (*name).to_string())
36            .expect("every policy mapping lists unknown")
37    };
38
39    match value {
40        PolicyValue::Numeric(n) => names
41            .iter()
42            .find(|(code, _)| *code == n)
43            .map(|(_, name)| (*name).to_string())
44            .unwrap_or_else(unknown),
45        PolicyValue::String(s) => {
46            let s = s.trim().to_ascii_lowercase();
47            // Some writers quote the numeric enumerator, so a string that is
48            // really a number still has to resolve by code.
49            if let Ok(n) = s.parse::<i64>() {
50                return normalize_policy(PolicyValue::Numeric(n), names);
51            }
52            names
53                .iter()
54                .find(|(_, name)| *name == s)
55                .map(|(_, name)| (*name).to_string())
56                .unwrap_or_else(unknown)
57        }
58    }
59}
60
61const HISTORY_POLICIES: &[(i64, &str)] = &[
62    (0, "system_default"),
63    (1, "keep_last"),
64    (2, "keep_all"),
65    (3, "unknown"),
66];
67
68const RELIABILITY_POLICIES: &[(i64, &str)] = &[
69    (0, "system_default"),
70    (1, "reliable"),
71    (2, "best_effort"),
72    (3, "unknown"),
73    (4, "best_available"),
74];
75
76const DURABILITY_POLICIES: &[(i64, &str)] = &[
77    (0, "system_default"),
78    (1, "transient_local"),
79    (2, "volatile"),
80    (3, "unknown"),
81    (4, "best_available"),
82];
83
84const LIVELINESS_POLICIES: &[(i64, &str)] = &[
85    (0, "system_default"),
86    (1, "automatic"),
87    (2, "manual_by_node"),
88    (3, "manual_by_topic"),
89    (4, "unknown"),
90    (5, "best_available"),
91];
92
93fn deserialize_history<'de, D>(deserializer: D) -> Result<String, D::Error>
94where
95    D: serde::Deserializer<'de>,
96{
97    Ok(normalize_policy(
98        PolicyValue::deserialize(deserializer)?,
99        HISTORY_POLICIES,
100    ))
101}
102
103fn deserialize_reliability<'de, D>(deserializer: D) -> Result<String, D::Error>
104where
105    D: serde::Deserializer<'de>,
106{
107    Ok(normalize_policy(
108        PolicyValue::deserialize(deserializer)?,
109        RELIABILITY_POLICIES,
110    ))
111}
112
113fn deserialize_durability<'de, D>(deserializer: D) -> Result<String, D::Error>
114where
115    D: serde::Deserializer<'de>,
116{
117    Ok(normalize_policy(
118        PolicyValue::deserialize(deserializer)?,
119        DURABILITY_POLICIES,
120    ))
121}
122
123fn deserialize_liveliness<'de, D>(deserializer: D) -> Result<String, D::Error>
124where
125    D: serde::Deserializer<'de>,
126{
127    Ok(normalize_policy(
128        PolicyValue::deserialize(deserializer)?,
129        LIVELINESS_POLICIES,
130    ))
131}
132
133#[derive(
134    rkyv::Archive, Deserialize, Debug, Serialize, Clone, rkyv::Deserialize, rkyv::Serialize,
135)]
136pub struct QosProfile {
137    #[serde(deserialize_with = "deserialize_history")]
138    pub history: String,
139    pub depth: i32,
140    #[serde(deserialize_with = "deserialize_reliability")]
141    pub reliability: String,
142    #[serde(deserialize_with = "deserialize_durability")]
143    pub durability: String,
144    pub deadline: QosTime,
145    pub lifespan: QosTime,
146    #[serde(deserialize_with = "deserialize_liveliness")]
147    pub liveliness: String,
148    pub liveliness_lease_duration: QosTime,
149    pub avoid_ros_namespace_conventions: bool,
150}
151
152#[derive(
153    Deserialize, Serialize, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, Clone, Copy,
154)]
155pub struct QosTime {
156    pub sec: u64,
157    pub nsec: u64,
158}
159
160#[allow(clippy::large_enum_variant)]
161#[derive(Clone, Debug, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)]
162pub enum SensorTypeMapped {
163    Lidar(PointCloud2),
164    Imu(Imu),
165    Odometry(Odometry),
166    Clock(Clock),
167    Any(Vec<u8>),
168    // Append variants to preserve the discriminants of existing wire types.
169    Tf(TFMessage),
170    Image(Image),
171    CompressedImage(CompressedImage),
172    CameraInfo(CameraInfo),
173    LaserScan(LaserScan),
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_resolve_cache_basic_pair() {
1045        let mut rules = Rules::new();
1046        rules.register(
1047            "position".to_string(),
1048            "ShipA".to_string(),
1049            RatPubRegisterKind::Publish,
1050        );
1051        rules.register(
1052            "position".to_string(),
1053            "ShipB".to_string(),
1054            RatPubRegisterKind::Subscribe,
1055        );
1056
1057        rules.resolve_cache();
1058
1059        // Check the store
1060        let mut expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1061            let mut map = HashMap::new();
1062            let var_humans = vec![VariableHuman {
1063                ship: "ShipA".to_string(),
1064                strategy: Some(ActionPlan::Shoot {
1065                    target: vec!["ShipB".to_string()],
1066                    id: 1,
1067                }),
1068            }];
1069            map.insert("position".to_string(), var_humans);
1070            map
1071        };
1072
1073        let mut actual_store = rules.store.clone();
1074
1075        // Sort both actual and expected for comparison
1076        if let Some(humans) = actual_store.get_mut("position") {
1077            sort_variable_humans(humans);
1078        }
1079        if let Some(humans) = expected_store.get_mut("position") {
1080            sort_variable_humans(humans);
1081        }
1082
1083        assert_eq!(actual_store, expected_store);
1084
1085        // Check the cache
1086        assert!(rules.cache.is_empty());
1087    }
1088
1089    #[test]
1090    fn test_resolve_cache_multiple_pubs_subs() {
1091        let mut rules = Rules::new();
1092        rules.register(
1093            "velocity".to_string(),
1094            "ShipX".to_string(),
1095            RatPubRegisterKind::Publish,
1096        );
1097        rules.register(
1098            "velocity".to_string(),
1099            "ShipY".to_string(),
1100            RatPubRegisterKind::Publish,
1101        );
1102        rules.register(
1103            "velocity".to_string(),
1104            "ShipZ".to_string(),
1105            RatPubRegisterKind::Subscribe,
1106        );
1107        rules.register(
1108            "velocity".to_string(),
1109            "ShipW".to_string(),
1110            RatPubRegisterKind::Subscribe,
1111        );
1112
1113        rules.resolve_cache();
1114
1115        // Check the store
1116        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1117            let mut map = HashMap::new();
1118            // Define the expected rules (order doesn't matter initially, will sort later)
1119            let var_humans = vec![
1120                // Publishers shooting at all subscribers (targets should be sorted by resolve_cache)
1121                VariableHuman {
1122                    ship: "ShipX".to_string(),
1123                    strategy: Some(ActionPlan::Shoot {
1124                        target: vec!["ShipW".to_string(), "ShipZ".to_string()],
1125                        id: 1,
1126                    }),
1127                },
1128                VariableHuman {
1129                    ship: "ShipY".to_string(),
1130                    strategy: Some(ActionPlan::Shoot {
1131                        target: vec!["ShipW".to_string(), "ShipZ".to_string()],
1132                        id: 1,
1133                    }),
1134                },
1135            ];
1136            map.insert("velocity".to_string(), var_humans);
1137            map
1138        };
1139
1140        // Clone and sort the actual store for comparison
1141        let mut actual_store_sorted = rules.store.clone();
1142        if let Some(humans) = actual_store_sorted.get_mut("velocity") {
1143            sort_variable_humans(humans); // Sorts outer vec and inner targets
1144        }
1145
1146        // Clone and sort the expected store for comparison
1147        let mut expected_store_sorted = expected_store.clone();
1148        if let Some(humans) = expected_store_sorted.get_mut("velocity") {
1149            sort_variable_humans(humans); // Sorts outer vec and inner targets
1150        }
1151
1152        assert_eq!(actual_store_sorted, expected_store_sorted);
1153
1154        // Check the cache
1155        assert!(rules.cache.is_empty());
1156    }
1157
1158    #[test]
1159    fn test_resolve_cache_no_pair_pubs_only() {
1160        let mut rules = Rules::new();
1161        rules.register(
1162            "fuel".to_string(),
1163            "ShipA".to_string(),
1164            RatPubRegisterKind::Publish,
1165        );
1166        rules.register(
1167            "fuel".to_string(),
1168            "ShipC".to_string(),
1169            RatPubRegisterKind::Publish,
1170        );
1171
1172        rules.resolve_cache();
1173
1174        // Check the store - should be unchanged as 'fuel' was not in store and no pair formed
1175        assert!(rules.store.is_empty());
1176
1177        // Check the cache - entries should still be there
1178        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1179            let mut map = HashMap::new();
1180            let mut set = HashSet::new();
1181            set.insert(("ShipA".to_string(), RatPubRegisterKind::Publish));
1182            set.insert(("ShipC".to_string(), RatPubRegisterKind::Publish));
1183            map.insert("fuel".to_string(), set);
1184            map
1185        };
1186        assert_eq!(rules.cache, expected_cache);
1187    }
1188
1189    #[test]
1190    fn test_resolve_cache_mixed_variables() {
1191        let mut rules = Rules::new();
1192        // Variable with a pair (should be resolved and added to store)
1193        rules.register(
1194            "shields".to_string(),
1195            "ShipF".to_string(),
1196            RatPubRegisterKind::Publish,
1197        );
1198        rules.register(
1199            "shields".to_string(),
1200            "ShipG".to_string(),
1201            RatPubRegisterKind::Subscribe,
1202        );
1203
1204        // Variable without a pair (should remain in cache)
1205        rules.register(
1206            "waypoints".to_string(),
1207            "ShipH".to_string(),
1208            RatPubRegisterKind::Publish,
1209        );
1210
1211        rules.resolve_cache();
1212
1213        // Check the store - only 'shields' should be present, generated from the pair
1214        let mut expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1215            let mut map = HashMap::new();
1216            let var_humans = vec![VariableHuman {
1217                ship: "ShipF".to_string(),
1218                strategy: Some(ActionPlan::Shoot {
1219                    target: vec!["ShipG".to_string()],
1220                    id: 1,
1221                }),
1222            }];
1223            map.insert("shields".to_string(), var_humans);
1224            map
1225        };
1226
1227        let mut actual_store = rules.store.clone();
1228
1229        // Sort both actual and expected for comparison
1230        if let Some(humans) = actual_store.get_mut("shields") {
1231            sort_variable_humans(humans);
1232        }
1233        if let Some(humans) = expected_store.get_mut("shields") {
1234            sort_variable_humans(humans);
1235        }
1236
1237        assert_eq!(actual_store, expected_store);
1238
1239        // Check the cache - only 'waypoints' should remain
1240        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1241            let mut map = HashMap::new();
1242            let mut set = HashSet::new();
1243            set.insert(("ShipH".to_string(), RatPubRegisterKind::Publish));
1244            map.insert("waypoints".to_string(), set);
1245            map
1246        };
1247        assert_eq!(rules.cache, expected_cache);
1248    }
1249
1250    #[test]
1251    fn test_resolve_cache_state_after_mixed_plus_new_subs() {
1252        let mut rules = Rules::new();
1253
1254        // Set up the state expected after test_resolve_cache_mixed_variables
1255        // Store should have 'shields' rules
1256        let shields_rules = vec![VariableHuman {
1257            ship: "ShipF".to_string(),
1258            strategy: Some(ActionPlan::Shoot {
1259                target: vec!["ShipG".to_string()],
1260                id: 0,
1261            }),
1262        }];
1263        rules.insert("shields".to_string(), shields_rules.clone());
1264
1265        // Cache should have 'waypoints' pub-only registration
1266        rules.register(
1267            "waypoints".to_string(),
1268            "ShipH".to_string(),
1269            RatPubRegisterKind::Publish,
1270        );
1271
1272        // Add new cache entries: subs-only for a new topic 'status'
1273        rules.register(
1274            "status".to_string(),
1275            "ShipI".to_string(),
1276            RatPubRegisterKind::Subscribe,
1277        );
1278        rules.register(
1279            "status".to_string(),
1280            "ShipJ".to_string(),
1281            RatPubRegisterKind::Subscribe,
1282        );
1283
1284        // Clone initial states to compare against after resolution
1285        let initial_store = rules.store.clone();
1286        let initial_cache = rules.cache.clone();
1287
1288        rules.resolve_cache();
1289
1290        // Expected: Store remains unchanged ('status' cache didn't form pair, 'waypoints' still no sub)
1291        // We need to sort the initial store for comparison as insert order isn't guaranteed
1292        let mut initial_store_sorted = initial_store.clone();
1293        if let Some(humans) = initial_store_sorted.get_mut("shields") {
1294            sort_variable_humans(humans);
1295        }
1296        let mut actual_store_sorted = rules.store.clone();
1297        if let Some(humans) = actual_store_sorted.get_mut("shields") {
1298            sort_variable_humans(humans);
1299        }
1300
1301        assert_eq!(actual_store_sorted, initial_store_sorted);
1302
1303        // Expected: Cache remains unchanged ('status' and 'waypoints' entries persist)
1304        assert_eq!(rules.cache, initial_cache);
1305    }
1306
1307    #[test]
1308    fn test_resolve_cache_state_after_prev_plus_new_pub() {
1309        let mut rules = Rules::new();
1310
1311        // Set up the state expected after the previous test
1312        // Store should have 'shields' rules
1313        let shields_rules = vec![VariableHuman {
1314            ship: "ShipF".to_string(),
1315            strategy: Some(ActionPlan::Shoot {
1316                target: vec!["ShipG".to_string()],
1317                id: 0,
1318            }),
1319        }];
1320        rules.insert("shields".to_string(), shields_rules.clone());
1321
1322        // Cache should have 'waypoints' pub-only registration
1323        rules.register(
1324            "waypoints".to_string(),
1325            "ShipH".to_string(),
1326            RatPubRegisterKind::Publish,
1327        );
1328        // Cache should have 'status' subs-only registrations
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        // Add the new cache entry: publisher for 'status'
1341        rules.register(
1342            "status".to_string(),
1343            "ShipK".to_string(),
1344            RatPubRegisterKind::Publish,
1345        );
1346
1347        rules.resolve_cache();
1348
1349        // Check the store - Should contain original 'shields' rules + new 'status' rules from the pair
1350        let mut expected_store: HashMap<Variable, Vec<VariableHuman>> = HashMap::new();
1351        expected_store.insert("shields".to_string(), shields_rules); // Original shields rules
1352
1353        // Expected 'status' rules (ShipK publishes, ShipI and ShipJ subscribe)
1354        let status_rules = vec![VariableHuman {
1355            ship: "ShipK".to_string(),
1356            strategy: Some(ActionPlan::Shoot {
1357                target: vec!["ShipI".to_string(), "ShipJ".to_string()],
1358                id: 1,
1359            }),
1360        }];
1361        expected_store.insert("status".to_string(), status_rules);
1362
1363        let mut actual_store_sorted = rules.store.clone();
1364        if let Some(humans) = actual_store_sorted.get_mut("shields") {
1365            sort_variable_humans(humans);
1366        }
1367        if let Some(humans) = actual_store_sorted.get_mut("status") {
1368            sort_variable_humans(humans);
1369        }
1370
1371        let mut expected_store_sorted = expected_store.clone();
1372        if let Some(humans) = expected_store_sorted.get_mut("shields") {
1373            sort_variable_humans(humans);
1374        }
1375        if let Some(humans) = expected_store_sorted.get_mut("status") {
1376            sort_variable_humans(humans);
1377        }
1378
1379        assert_eq!(actual_store_sorted, expected_store_sorted);
1380
1381        // Check the cache - 'waypoints' should remain, 'status' should be gone
1382        let expected_cache: HashMap<Variable, HashSet<(Client, RatPubRegisterKind)>> = {
1383            let mut map = HashMap::new();
1384            let mut set = HashSet::new();
1385            set.insert(("ShipH".to_string(), RatPubRegisterKind::Publish));
1386            map.insert("waypoints".to_string(), set);
1387            map
1388        };
1389        assert_eq!(rules.cache, expected_cache);
1390    }
1391
1392    #[test]
1393    fn test_resolve_cache_store_with_rules_add_pub_sub() {
1394        let mut rules = Rules::new();
1395        let var_name = "telemetry".to_string();
1396
1397        // Initial Shoot/Catch rules in store
1398        rules.insert(
1399            var_name.clone(),
1400            vec![VariableHuman {
1401                ship: "BaseStation".to_string(),
1402                strategy: Some(ActionPlan::Shoot {
1403                    target: vec!["Rover1".to_string()],
1404                    id: 0,
1405                }),
1406            }],
1407        );
1408
1409        // Add registrations to cache: new publisher and new subscriber
1410        rules.register(
1411            var_name.clone(),
1412            "BaseStationBackup".to_string(),
1413            RatPubRegisterKind::Publish,
1414        );
1415        rules.register(
1416            var_name.clone(),
1417            "Rover2".to_string(),
1418            RatPubRegisterKind::Subscribe,
1419        );
1420
1421        rules.resolve_cache();
1422
1423        // Check the store - Should update all Shoot/Catch rules based on all 4 ships
1424        let expected_store: HashMap<Variable, Vec<VariableHuman>> = {
1425            let mut map = HashMap::new();
1426            // Combined unique pubs: BaseStation (store), BaseStationBackup (cache)
1427            // Combined unique subs: Rover1 (store), Rover2 (cache)
1428            let all_subs = vec!["Rover1".to_string(), "Rover2".to_string()]; // Already sorted
1429
1430            let var_humans = vec![
1431                // Shoot rules for all pubs targeting all subs
1432                VariableHuman {
1433                    ship: "BaseStation".to_string(),
1434                    strategy: Some(ActionPlan::Shoot {
1435                        target: all_subs.clone(),
1436                        id: 0,
1437                    }),
1438                },
1439                VariableHuman {
1440                    ship: "BaseStationBackup".to_string(),
1441                    strategy: Some(ActionPlan::Shoot {
1442                        target: all_subs.clone(),
1443                        id: 0,
1444                    }),
1445                },
1446            ];
1447            map.insert(var_name.clone(), var_humans);
1448            map
1449        };
1450
1451        let mut actual_store_sorted = rules.store.clone();
1452        if let Some(humans) = actual_store_sorted.get_mut(&var_name) {
1453            sort_variable_humans(humans);
1454        }
1455
1456        let mut expected_store_sorted = expected_store.clone();
1457        if let Some(humans) = expected_store_sorted.get_mut(&var_name) {
1458            sort_variable_humans(humans);
1459        }
1460
1461        assert_eq!(actual_store_sorted, expected_store_sorted);
1462
1463        // Check the cache - entry for 'telemetry' should be removed
1464        assert!(!rules.cache.contains_key(&var_name));
1465        assert!(rules.cache.is_empty()); // Assuming no other cache entries
1466    }
1467}
1468
1469#[cfg(test)]
1470mod unregister_tests {
1471    use super::{RatPubRegisterKind, Rules};
1472
1473    fn rules() -> Rules {
1474        Rules::default()
1475    }
1476
1477    #[test]
1478    fn unregistering_removes_only_that_client() {
1479        let mut rules = rules();
1480        rules.register(
1481            "clouds".into(),
1482            "viewer".into(),
1483            RatPubRegisterKind::Subscribe,
1484        );
1485        rules.register(
1486            "clouds".into(),
1487            "logger".into(),
1488            RatPubRegisterKind::Subscribe,
1489        );
1490
1491        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1492
1493        let remaining = rules.cache.get("clouds").expect("topic still in use");
1494        assert!(remaining.contains(&("logger".to_string(), RatPubRegisterKind::Subscribe)));
1495        assert!(!remaining.contains(&("viewer".to_string(), RatPubRegisterKind::Subscribe)));
1496    }
1497
1498    /// The point of unsubscribing is that you can subscribe again. Dropping the
1499    /// publisher along with its last subscriber would leave the next subscriber
1500    /// with nothing to be routed from.
1501    #[test]
1502    fn a_topic_still_routes_after_its_only_subscriber_leaves_and_another_joins() {
1503        let mut rules = rules();
1504        rules.register(
1505            "clouds".into(),
1506            "pelorus".into(),
1507            RatPubRegisterKind::Publish,
1508        );
1509        rules.register(
1510            "clouds".into(),
1511            "viewer".into(),
1512            RatPubRegisterKind::Subscribe,
1513        );
1514
1515        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1516        assert!(!targets_of(&rules, "clouds").contains(&"viewer".to_string()));
1517
1518        rules.register(
1519            "clouds".into(),
1520            "viewer2".into(),
1521            RatPubRegisterKind::Subscribe,
1522        );
1523        assert!(
1524            targets_of(&rules, "clouds").contains(&"viewer2".to_string()),
1525            "a new subscriber must still be routed from the existing publisher"
1526        );
1527    }
1528
1529    /// Every subscriber a publisher sends to, across all its rules.
1530    fn targets_of(rules: &Rules, var: &str) -> Vec<String> {
1531        rules
1532            .store
1533            .get(var)
1534            .map(|entries| {
1535                entries
1536                    .iter()
1537                    .filter_map(|vh| match &vh.strategy {
1538                        Some(super::ActionPlan::Shoot { target, .. }) => Some(target.clone()),
1539                        _ => None,
1540                    })
1541                    .flatten()
1542                    .collect()
1543            })
1544            .unwrap_or_default()
1545    }
1546
1547    #[test]
1548    fn the_last_client_leaving_drops_the_topic() {
1549        let mut rules = rules();
1550        rules.register(
1551            "clouds".into(),
1552            "viewer".into(),
1553            RatPubRegisterKind::Subscribe,
1554        );
1555        assert!(rules.unregister("clouds", "viewer", RatPubRegisterKind::Subscribe));
1556        assert!(!rules.cache.contains_key("clouds"));
1557        assert!(!rules.store.contains_key("clouds"));
1558    }
1559}