use std::collections::BTreeMap;
pub const KEYS: &[&str] = &[
"app", "env", "cluster", "role", "shard", "tier", "region", "zone",
];
pub const ENVS: &[&str] = &["prod", "staging", "dev", "test"];
pub const ROLES: &[&str] = &[
"arbiter",
"broker",
"config",
"control-plane",
"controller",
"coordinator",
"data",
"ingest",
"keeper",
"learner",
"mongos",
"observer",
"pd",
"primary",
"proxy",
"replica",
"sentinel",
"tidb",
"tikv",
"worker",
];
pub const TIERS: &[&str] = &["hot", "warm", "cold"];
pub const MAX_LABELS: usize = 6;
pub const MAX_VALUE_LEN: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LabelError {
TooMany { got: usize },
UnknownKey(String),
BadValue { key: String, value: String },
BadEnv(String),
BadVocabulary { key: String, value: String },
OrphanKey(String),
}
impl LabelError {
pub fn code(&self) -> &'static str {
match self {
LabelError::TooMany { .. } => "too_many_metric_labels",
LabelError::UnknownKey(_) => "unknown_metric_label",
LabelError::BadValue { .. } => "invalid_metric_label_value",
LabelError::BadEnv(_) => "invalid_metric_env",
LabelError::BadVocabulary { .. } => "invalid_metric_label_value",
LabelError::OrphanKey(_) => "metric_label_requires_app",
}
}
}
impl std::fmt::Display for LabelError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LabelError::TooMany { got } => {
write!(f, "选择类 label 最多 {MAX_LABELS} 对(给了 {got} 对)")
}
LabelError::UnknownKey(key) => {
write!(f, "`{key}` 不在键闭集({})", KEYS.join(" / "))
}
LabelError::BadValue { key, value } => write!(
f,
"`{key}` 的值 {value:?} 不合法:只允许小写字母 / 数字 / `-` / `_` / `.`,且不超过 {MAX_VALUE_LEN} 字符"
),
LabelError::BadEnv(value) => {
write!(f, "`env` 的值 {value:?} 不在闭集({})", ENVS.join(" / "))
}
LabelError::BadVocabulary { key, value } => {
write!(f, "`{key}` 的值 {value:?} 不在该键的词表里")
}
LabelError::OrphanKey(key) => {
write!(f, "`{key}` 需要先有 `app`(没有登记表时无法校验键组合)")
}
}
}
}
pub fn is_valid_value(value: &str) -> bool {
!value.is_empty()
&& value.len() <= MAX_VALUE_LEN
&& value
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | '.'))
}
pub fn validate_labels(labels: &BTreeMap<String, String>) -> Result<(), LabelError> {
if labels.len() > MAX_LABELS {
return Err(LabelError::TooMany { got: labels.len() });
}
for (key, value) in labels {
if !KEYS.contains(&key.as_str()) {
return Err(LabelError::UnknownKey(key.clone()));
}
if !is_valid_value(value) {
return Err(LabelError::BadValue {
key: key.clone(),
value: value.clone(),
});
}
match key.as_str() {
"env" if !ENVS.contains(&value.as_str()) => {
return Err(LabelError::BadEnv(value.clone()));
}
"role" if !ROLES.contains(&value.as_str()) => {
return Err(LabelError::BadVocabulary {
key: key.clone(),
value: value.clone(),
});
}
"tier" if !TIERS.contains(&value.as_str()) => {
return Err(LabelError::BadVocabulary {
key: key.clone(),
value: value.clone(),
});
}
_ => {}
}
}
if !labels.contains_key("app") {
for key in ["role", "shard", "tier"] {
if labels.contains_key(key) {
return Err(LabelError::OrphanKey(key.to_string()));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn labels(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
pairs
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect()
}
#[test]
fn a_minimal_pair_is_valid() {
assert_eq!(
validate_labels(&labels(&[("env", "prod"), ("cluster", "kafka-prod")])),
Ok(())
);
}
#[test]
fn an_empty_set_is_valid() {
assert_eq!(validate_labels(&BTreeMap::new()), Ok(()));
}
#[test]
fn unknown_keys_are_rejected() {
assert_eq!(
validate_labels(&labels(&[("service", "kafka")])),
Err(LabelError::UnknownKey("service".to_string()))
);
}
#[test]
fn env_must_come_from_the_closed_set() {
assert_eq!(
validate_labels(&labels(&[("env", "production")])),
Err(LabelError::BadEnv("production".to_string()))
);
}
#[test]
fn values_are_lowercase_and_length_limited() {
assert!(validate_labels(&labels(&[("cluster", "Kafka-Prod")])).is_err());
assert!(validate_labels(&labels(&[("cluster", "kafka prod")])).is_err());
assert!(validate_labels(&labels(&[("cluster", "")])).is_err());
assert!(validate_labels(&labels(&[("cluster", &"a".repeat(33))])).is_err());
assert!(validate_labels(&labels(&[("cluster", &"a".repeat(32))])).is_ok());
assert!(validate_labels(&labels(&[("cluster", "kafka-prod_1.a")])).is_ok());
}
#[test]
fn role_and_tier_are_vocabulary_bounded() {
assert!(validate_labels(&labels(&[("app", "kafka"), ("role", "broker")])).is_ok());
assert_eq!(
validate_labels(&labels(&[("app", "kafka"), ("role", "leader")])),
Err(LabelError::BadVocabulary {
key: "role".to_string(),
value: "leader".to_string()
})
);
assert!(validate_labels(&labels(&[("app", "es"), ("tier", "hot")])).is_ok());
assert!(validate_labels(&labels(&[("app", "es"), ("tier", "frozen")])).is_err());
}
#[test]
fn role_without_app_is_rejected() {
assert_eq!(
validate_labels(&labels(&[("role", "broker")])),
Err(LabelError::OrphanKey("role".to_string()))
);
assert!(validate_labels(&labels(&[("env", "dev"), ("region", "cn-north")])).is_ok());
}
#[test]
fn at_most_six_pairs() {
let six = labels(&[
("app", "kafka"),
("env", "prod"),
("cluster", "c"),
("role", "broker"),
("region", "cn-north"),
("zone", "az1"),
]);
assert!(validate_labels(&six).is_ok());
let mut seven = six;
seven.insert("shard".to_string(), "0".to_string());
assert_eq!(validate_labels(&seven), Err(LabelError::TooMany { got: 7 }));
}
}