nacos_rust_client/client/naming_client/
request_client.rs

1use crate::client;
2use crate::client::auth::{AuthActor, AuthCmd, AuthHandleResult};
3use crate::client::naming_client::Instance;
4use crate::client::naming_client::QueryInstanceListParams;
5use crate::client::naming_client::QueryListResult;
6use crate::client::utils::Utils;
7use crate::client::ServerEndpointInfo;
8use actix::Addr;
9use std::{collections::HashMap, sync::Arc};
10
11#[derive(Clone)]
12pub struct InnerNamingRequestClient {
13    pub(crate) client: reqwest::Client,
14    pub(crate) headers: HashMap<String, String>,
15    pub(crate) endpoints: Arc<ServerEndpointInfo>,
16    pub(crate) auth_addr: Option<Addr<AuthActor>>,
17}
18
19impl InnerNamingRequestClient {
20    /*
21    pub(crate) fn new(host:HostInfo) -> Self{
22        let client = reqwest::Client::builder()
23            .build().unwrap();
24        let mut headers = HashMap::new();
25        headers.insert("Content-Type".to_owned(), "application/x-www-form-urlencoded".to_owned());
26        let endpoints = Arc::new(ServerEndpointInfo{
27            hosts: vec![host],
28        });
29        Self{
30            client,
31            headers,
32            endpoints,
33            auth_addr:None,
34        }
35    }
36    */
37
38    pub(crate) fn new_with_endpoint(
39        endpoints: Arc<ServerEndpointInfo>,
40        auth_addr: Option<Addr<AuthActor>>,
41    ) -> Self {
42        let client = reqwest::Client::builder().build().unwrap();
43        Self {
44            endpoints,
45            client,
46            headers: client::Client::build_http_headers(),
47            auth_addr,
48        }
49    }
50
51    pub(crate) fn set_auth_addr(&mut self, addr: Addr<AuthActor>) {
52        self.auth_addr = Some(addr);
53    }
54
55    pub(crate) async fn get_token_result(&self) -> anyhow::Result<String> {
56        if let Some(auth_addr) = &self.auth_addr {
57            match auth_addr.send(AuthCmd::QueryToken).await?? {
58                AuthHandleResult::None => {}
59                AuthHandleResult::Token(v) => {
60                    if v.len() > 0 {
61                        return Ok(format!("accessToken={}", &v));
62                    }
63                }
64            };
65        }
66        Ok(String::new())
67    }
68
69    pub(crate) async fn get_token(&self) -> String {
70        self.get_token_result().await.unwrap_or_default()
71    }
72
73    pub(crate) async fn register(&self, instance: &Instance) -> anyhow::Result<bool> {
74        let params = instance.to_web_params();
75        let body = serde_urlencoded::to_string(&params)?;
76        let host = self.endpoints.select_host();
77        let token_param = self.get_token().await;
78        let url = format!(
79            "http://{}:{}/nacos/v1/ns/instance?{}",
80            &host.ip, &host.port, token_param
81        );
82        let resp = Utils::request(
83            &self.client,
84            "POST",
85            &url,
86            body.as_bytes().to_vec(),
87            Some(&self.headers),
88            Some(3000),
89        )
90        .await?;
91        //log::info!("register:{}",resp.get_lossy_string_body());
92        Ok("ok" == resp.get_string_body())
93    }
94
95    pub(crate) async fn remove(&self, instance: &Instance) -> anyhow::Result<bool> {
96        let params = instance.to_web_params();
97        let body = serde_urlencoded::to_string(&params)?;
98        let host = self.endpoints.select_host();
99        let token_param = self.get_token().await;
100        let url = format!(
101            "http://{}:{}/nacos/v1/ns/instance?{}",
102            &host.ip, &host.port, token_param
103        );
104        let resp = Utils::request(
105            &self.client,
106            "DELETE",
107            &url,
108            body.as_bytes().to_vec(),
109            Some(&self.headers),
110            Some(3000),
111        )
112        .await?;
113        //log::info!("remove:{}",resp.get_lossy_string_body());
114        Ok("ok" == resp.get_string_body())
115    }
116
117    pub(crate) async fn heartbeat(&self, beat_string: Arc<String>) -> anyhow::Result<bool> {
118        let host = self.endpoints.select_host();
119        let token_param = self.get_token().await;
120        let url = format!(
121            "http://{}:{}/nacos/v1/ns/instance/beat?{}",
122            &host.ip, &host.port, token_param
123        );
124        let resp = Utils::request(
125            &self.client,
126            "PUT",
127            &url,
128            beat_string.as_bytes().to_vec(),
129            Some(&self.headers),
130            Some(3000),
131        )
132        .await?;
133        //log::debug!("heartbeat:{}",resp.get_lossy_string_body());
134        Ok("ok" == resp.get_string_body())
135    }
136
137    pub(crate) async fn get_instance_list(
138        &self,
139        query_param: &QueryInstanceListParams,
140    ) -> anyhow::Result<QueryListResult> {
141        let params = query_param.to_web_params();
142        let token_param = self.get_token().await;
143        let host = self.endpoints.select_host();
144        let url = format!(
145            "http://{}:{}/nacos/v1/ns/instance/list?{}&{}",
146            &host.ip,
147            &host.port,
148            token_param,
149            &serde_urlencoded::to_string(&params)?
150        );
151        let resp = Utils::request(
152            &self.client,
153            "GET",
154            &url,
155            vec![],
156            Some(&self.headers),
157            Some(3000),
158        )
159        .await?;
160
161        let result: Result<QueryListResult, _> = serde_json::from_slice(&resp.body);
162        match result {
163            Ok(r) => {
164                //log::debug!("get_instance_list instance:{}",&r.hosts.is_some());
165                Ok(r)
166            }
167            Err(e) => {
168                log::error!(
169                    "get_instance_list error:\n\turl:{}\n\t{}",
170                    &url,
171                    resp.get_string_body()
172                );
173                Err(anyhow::format_err!(e))
174            }
175        }
176    }
177}