gossip_server/
membership.rs

1use std::sync::OnceLock;
2
3use gossip_kv::membership::MemberId;
4use rand::distributions::Distribution;
5use rand::{Rng, thread_rng};
6
7/// This is a simple distribution that generates a random lower-case alphanumeric
8struct LowercaseAlphanumeric;
9
10impl Distribution<char> for LowercaseAlphanumeric {
11    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
12        let choices = b"abcdefghijklmnopqrstuvwxyz0123456789";
13        choices[rng.gen_range(0..choices.len())] as char
14    }
15}
16
17/// Gets a name for the current process.
18pub fn member_name(random_suffix_len: usize) -> &'static MemberId {
19    static MEMBER_NAME: OnceLock<MemberId> = OnceLock::new();
20    MEMBER_NAME.get_or_init(|| {
21        let hostname = hostname::get().unwrap().to_str().unwrap().to_string();
22
23        if random_suffix_len > 0 {
24            let suffix: String = thread_rng()
25                .sample_iter(&LowercaseAlphanumeric)
26                .take(4)
27                .collect();
28            format!("{}-{}", hostname, suffix)
29        } else {
30            hostname
31        }
32    })
33}