servers/
addrs.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use common_telemetry::warn;
16
17/// Resolves server address for meta registration.
18/// If `server_addr` is present, prefer to use it, `bind_addr` otherwise.
19pub fn resolve_addr(bind_addr: &str, server_addr: Option<&str>) -> String {
20    match server_addr {
21        Some(server_addr) => {
22            // it has port configured
23            if server_addr.contains(':') {
24                server_addr.to_string()
25            } else {
26                // otherwise, resolve port from bind_addr
27                // should be safe to unwrap here because bind_addr is already validated
28                let port = bind_addr.split(':').nth(1).unwrap();
29                format!("{server_addr}:{port}")
30            }
31        }
32        None => {
33            warn!("hostname not set, using bind_addr: {bind_addr} instead.");
34            bind_addr.to_string()
35        }
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    #[test]
42    fn test_resolve_addr() {
43        assert_eq!(
44            "tomcat:3001",
45            super::resolve_addr("127.0.0.1:3001", Some("tomcat"))
46        );
47
48        assert_eq!(
49            "tomcat:3002",
50            super::resolve_addr("127.0.0.1:3001", Some("tomcat:3002"))
51        );
52
53        assert_eq!(
54            "127.0.0.1:3001",
55            super::resolve_addr("127.0.0.1:3001", None)
56        );
57    }
58}