use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ClusterRole {
#[default]
Standalone,
Master,
Worker,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServerMode {
pub role: ClusterRole,
pub deprecated_alias_of: Option<&'static str>,
}
impl ClusterRole {
pub const ALL: [ClusterRole; 3] = [Self::Standalone, Self::Master, Self::Worker];
pub fn mode_word(self) -> &'static str {
match self {
ClusterRole::Standalone => "standalone",
ClusterRole::Master => "controller",
ClusterRole::Worker => "office",
}
}
pub fn deprecated_mode_word(self) -> Option<&'static str> {
match self {
ClusterRole::Standalone => None,
ClusterRole::Master => Some("master"),
ClusterRole::Worker => Some("worker"),
}
}
pub fn from_mode_arg(arg: &str) -> Option<ServerMode> {
for role in Self::ALL {
if arg == role.mode_word() {
return Some(ServerMode {
role,
deprecated_alias_of: None,
});
}
if role.deprecated_mode_word() == Some(arg) {
return Some(ServerMode {
role,
deprecated_alias_of: Some(role.mode_word()),
});
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_mode_words_select_their_role_without_deprecation() {
for (arg, role) in [
("standalone", ClusterRole::Standalone),
("controller", ClusterRole::Master),
("office", ClusterRole::Worker),
] {
let mode = ClusterRole::from_mode_arg(arg).expect("canonical mode word");
assert_eq!(mode.role, role);
assert_eq!(mode.deprecated_alias_of, None);
}
}
#[test]
fn legacy_mode_words_still_select_their_role_and_name_the_canonical_word() {
let controller = ClusterRole::from_mode_arg("master").expect("legacy mode word");
assert_eq!(controller.role, ClusterRole::Master);
assert_eq!(controller.deprecated_alias_of, Some("controller"));
let office = ClusterRole::from_mode_arg("worker").expect("legacy mode word");
assert_eq!(office.role, ClusterRole::Worker);
assert_eq!(office.deprecated_alias_of, Some("office"));
}
#[test]
fn unknown_mode_words_resolve_to_nothing() {
assert_eq!(ClusterRole::from_mode_arg("Controller"), None);
assert_eq!(ClusterRole::from_mode_arg("leader"), None);
assert_eq!(ClusterRole::from_mode_arg(""), None);
}
}