rocketmq_common/utils/
name_server_address_utils.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17use std::env;
18
19use lazy_static::lazy_static;
20use regex::Regex;
21
22use crate::common::mix_all;
23
24const INSTANCE_PREFIX: &str = "MQ_INST_";
25const INSTANCE_REGEX: &str = "MQ_INST_\\w+_\\w+";
26const ENDPOINT_PREFIX: &str = "(\\w+://|)";
27
28lazy_static! {
29    pub static ref NAMESRV_ENDPOINT_PATTERN: Regex = Regex::new("^http://.*").unwrap();
30    pub static ref INST_ENDPOINT_PATTERN: Regex =
31        Regex::new(&format!("^{ENDPOINT_PREFIX}{INSTANCE_REGEX}")).unwrap();
32}
33pub struct NameServerAddressUtils;
34
35impl NameServerAddressUtils {
36    pub fn get_name_server_addresses() -> Option<String> {
37        env::var(mix_all::NAMESRV_ADDR_PROPERTY)
38            .or_else(|_| env::var(mix_all::NAMESRV_ADDR_ENV))
39            .ok()
40    }
41
42    pub fn validate_instance_endpoint(endpoint: &str) -> bool {
43        INST_ENDPOINT_PATTERN.is_match(endpoint)
44    }
45
46    pub fn parse_instance_id_from_endpoint(endpoint: &str) -> Option<String> {
47        if endpoint.is_empty() {
48            None
49        } else {
50            let last_slash = endpoint.rfind('/').unwrap_or(0);
51            let dot_pos = endpoint.find('.').unwrap_or(endpoint.len());
52            Some(endpoint[last_slash + 1..dot_pos].to_string())
53        }
54    }
55
56    pub fn get_name_srv_addr_from_namesrv_endpoint(name_srv_endpoint: &str) -> Option<String> {
57        if name_srv_endpoint.is_empty() {
58            None
59        } else {
60            let last_slash = name_srv_endpoint.rfind('/').unwrap_or(0);
61            Some(name_srv_endpoint[last_slash + 1..].to_string())
62        }
63    }
64}