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