Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement cascade deregistering #27

Merged
merged 1 commit into from
Nov 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions src/admin/registry.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::collections::hash_map::HashMap;
use std::sync::{Arc, Mutex};

use super::entry::RegistryEntry;
use super::entry::{Placement, RegistryEntry};
use crate::types::*;
use anyhow::{anyhow, bail};
use givc_common::query::{Event, QueryResult};
use tokio::sync::broadcast;
use tracing::{debug, info};
use tracing::{debug, error, info};

#[derive(Clone, Debug)]
pub struct Registry {
Expand Down Expand Up @@ -48,6 +48,22 @@ impl Registry {
let mut state = self.map.lock().unwrap();
match state.remove(name) {
Some(entry) => {
let cascade: Vec<String> = state
.values()
.filter_map(|re| match &re.placement {
Placement::Managed(within) if within == name => Some(re.name.clone()),
_ => None,
})
.collect();
for each in cascade {
match state.remove(&each) {
Some(entry1) => {
info!("Cascade deregistering {:#?}", entry1);
self.send_event(Event::UnitShutdown(entry1.into()))
}
None => error!("Problems due cascade deregistering {each} (via {name})"),
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Annoyingly there's a nightly feature providing .extract_if() that would provide exactly what we'd need here; I guess the closest would be to rebuild the hashmap:

                *state = state
                    .drain()
                    .filter_map(|(k, v)| {
                        if matches!(v.placement, Placement::Managed(ref within) if within == name) {
                            info!("Cascade deregistering {:#?}", v);
                            self.send_event(Event::UnitShutdown(v.into()));
                            None
                        } else {
                            Some((k, v))
                        }
                    })
                    .collect();

But I'm guessing the number of cascaded services should normally be rather small, so probably the current way is better. As a chaining over-user, I would write this as:

                for entry in state
                    .values()
                    .filter_map(|re| {
                        matches!(&re.placement, Placement::Managed(within) if within == name)
                            .then(|| re.name.clone())
                    })
                    .collect::<Vec<_>>()
                    .into_iter()
                    .filter_map(|re| state.remove(&re))
                {
                    info!("Cascade deregistering {entry:#?}");
                    self.send_event(Event::UnitShutdown(entry.into()))
                }

Third option; shortest, but involves cloning the whole entry:

                state.retain(|_, val| if matches!(&val.placement, Placement::Managed(within) if within == name) {
                    info!("Cascade deregistering {entry:#?}");
                    self.send_event(Event::UnitShutdown(val.clone().into()));
                    false
                } else {
                    true
                });

info!("Deregistering {:#?}", entry);
self.send_event(Event::UnitShutdown(entry.into()));
Ok(())
Expand Down Expand Up @@ -183,6 +199,38 @@ mod tests {
Ok(())
}

#[test]
fn test_cascade_deregister() -> anyhow::Result<()> {
let r = Registry::new();
let foo = RegistryEntry::dummy("foo".to_string());
let bar = RegistryEntry {
placement: Placement::Managed("foo".into()),
..RegistryEntry::dummy("bar".to_string())
};
let baz = RegistryEntry {
placement: Placement::Managed("foo".into()),
..RegistryEntry::dummy("baz".to_string())
};

r.register(foo);
r.register(bar);
r.register(baz);
assert!(r.contains("foo"));
assert!(r.contains("bar"));
assert!(r.contains("baz"));

r.deregister("baz");
assert!(r.contains("foo"));
assert!(r.contains("bar"));
assert!(!r.contains("baz"));

r.deregister("foo");
assert!(!r.contains("foo"));
assert!(!r.contains("bar"));

Ok(())
}

#[test]
fn test_unique_name() -> anyhow::Result<()> {
let r = Registry::new();
Expand Down