Skip to main content

vector_config_common/
human_friendly.rs

1use std::{
2    collections::{HashMap, HashSet},
3    sync::LazyLock,
4};
5
6use convert_case::{Boundary, Case, Converter};
7
8/// Well-known replacements.
9///
10/// Replacements are instances of strings with unique capitalization that cannot be achieved
11/// programmatically, as well as the potential insertion of additional characters, such as the
12/// replacement of "pubsub" with "Pub/Sub".
13static WELL_KNOWN_REPLACEMENTS: LazyLock<HashMap<String, &'static str>> = LazyLock::new(|| {
14    let pairs = vec![
15        ("eventstoredb", "EventStoreDB"),
16        ("mongodb", "MongoDB"),
17        ("opentelemetry", "OpenTelemetry"),
18        ("otel", "OTEL"),
19        ("postgresql", "PostgreSQL"),
20        ("pubsub", "Pub/Sub"),
21        ("statsd", "StatsD"),
22        ("journald", "JournalD"),
23        ("appsignal", "AppSignal"),
24        ("clickhouse", "ClickHouse"),
25        ("influxdb", "InfluxDB"),
26        ("webhdfs", "WebHDFS"),
27        ("cloudwatch", "CloudWatch"),
28        ("geoip", "GeoIP"),
29        ("ssekms", "SSE-KMS"),
30        ("aes256", "AES-256"),
31        ("apiserver", "API Server"),
32        ("dir", "Directory"),
33        ("ids", "IDs"),
34        ("ips", "IPs"),
35        ("grpc", "gRPC"),
36        ("oauth2", "OAuth2"),
37    ];
38
39    pairs.iter().map(|(k, v)| (k.to_lowercase(), *v)).collect()
40});
41
42/// Well-known acronyms.
43///
44/// Acronyms are distinct from replacements because they should be entirely capitalized (i.e. "aws"
45/// or "aWs" or "Aws" should always be replaced with "AWS") whereas replacements may insert
46/// additional characters or capitalize specific characters within the original string.
47static WELL_KNOWN_ACRONYMS: LazyLock<HashSet<String>> = LazyLock::new(|| {
48    let acronyms = &[
49        "api", "amqp", "aws", "ec2", "ecs", "gcp", "hec", "http", "https", "nats", "nginx", "s3",
50        "sqs", "tls", "ssl", "otel", "gelf", "csv", "json", "rfc3339", "lz4", "us", "eu", "bsd",
51        "vrl", "tcp", "udp", "id", "uuid", "kms", "uri", "url", "acp", "uid", "ip", "pid",
52        "ndjson", "ewma", "rtt", "cpu", "acl", "imds", "acl", "alpn", "sasl",
53    ];
54
55    acronyms.iter().map(|s| s.to_lowercase()).collect()
56});
57
58/// Generates a human-friendly version of the given string.
59///
60/// Many instances exist where type names, or string constants, represent a condensed form of an
61/// otherwise human-friendly/recognize string, such as "aws_s3" (for AWS S3) or "InfluxdbMetrics"
62/// (for InfluxDB Metrics) and so on.
63///
64/// This function takes a given input and restores it back to the human-friendly version by
65/// splitting it on the relevant word boundaries, adjusting the input to title case, and applying
66/// well-known replacements to ensure that brand-specific casing (such as "CloudWatch" instead of
67/// "Cloudwatch", or handling acronyms like AWS, GCP, and so on) makes it into the final version.
68pub fn generate_human_friendly_string(input: &str) -> String {
69    // Create our case converter, which specifically ignores letter/digit boundaries, which is
70    // important for not turning substrings like "Ec2" or "S3" into "Ec"/"2" and "S"/"3",
71    // respectively.
72    let converter = Converter::new()
73        .to_case(Case::Title)
74        .remove_boundaries(&[Boundary::LowerDigit, Boundary::UpperDigit]);
75    let normalized = converter.convert(input);
76
77    let replaced_segments = normalized
78        .split(' ')
79        .map(replace_well_known_segments)
80        .collect::<Vec<_>>();
81    replaced_segments.join(" ")
82}
83
84fn replace_well_known_segments(input: &str) -> String {
85    let as_lower = input.to_lowercase();
86    if let Some(replacement) = WELL_KNOWN_REPLACEMENTS.get(&as_lower) {
87        replacement.to_string()
88    } else if WELL_KNOWN_ACRONYMS.contains(&as_lower) {
89        input.to_uppercase()
90    } else {
91        input.to_string()
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::generate_human_friendly_string;
98
99    #[test]
100    fn autodetect_input_case() {
101        let pascal_input = "LogToMetric";
102        let snake_input = "log_to_metric";
103
104        let pascal_friendly = generate_human_friendly_string(pascal_input);
105        let snake_friendly = generate_human_friendly_string(snake_input);
106
107        let expected = "Log To Metric";
108        assert_eq!(expected, pascal_friendly);
109        assert_eq!(expected, snake_friendly);
110    }
111
112    #[test]
113    fn digit_letter_boundaries() {
114        let input1 = "Ec2Metadata";
115        let expected1 = "EC2 Metadata";
116        let actual1 = generate_human_friendly_string(input1);
117        assert_eq!(expected1, actual1);
118
119        let input2 = "AwsS3";
120        let expected2 = "AWS S3";
121        let actual2 = generate_human_friendly_string(input2);
122        assert_eq!(expected2, actual2);
123    }
124}