nacos-sdk 0.7.0

Nacos client in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::{collections::HashMap, sync::Arc, time::Duration};
use tower::layer::util::Stack;
use tracing::{Instrument, instrument};

use crate::api::error::Error;
use crate::api::plugin::{AuthPlugin, NoopAuthPlugin, init_auth_plugin};
use crate::common::remote::grpc::message::{
    GrpcMessage, GrpcMessageBuilder, GrpcRequestMessage, GrpcResponseMessage,
};
use crate::common::remote::grpc::message::{GrpcMessageData, request::NacosClientAbilities};
use crate::common::remote::grpc::nacos_grpc_service::DynamicUnaryCallLayerWrapper;

use super::handlers::client_detection_request_handler::ClientDetectionRequestHandler;
use super::message::request::{ClientDetectionRequest, HealthCheckRequest};
use super::nacos_grpc_connection::{NacosGrpcConnection, SendRequest};
use super::nacos_grpc_service::{
    DynamicBiStreamingCallLayer, DynamicBiStreamingCallLayerWrapper, DynamicUnaryCallLayer,
};
use super::server_list_service::PollingServerListService;
use super::tonic::TonicBuilder;
use super::{config::GrpcConfiguration, nacos_grpc_service::ServerRequestHandler};

const APP_FIELD: &str = "app";

pub(crate) struct NacosGrpcClient {
    app_name: String,
    send_request: Arc<dyn SendRequest + Send + Sync + 'static>,
    auth_plugin: Arc<dyn AuthPlugin>,
}

impl NacosGrpcClient {
    #[instrument(skip_all)]
    pub(crate) async fn send_request<Request, Response>(
        &self,
        mut request: Request,
    ) -> Result<Response, Error>
    where
        Request: GrpcRequestMessage + 'static,
        Response: GrpcResponseMessage + 'static,
    {
        let mut request_headers = request.take_headers();
        if let Some(resource) = request.request_resource() {
            let auth_context = self.auth_plugin.get_login_identity(resource);
            request_headers.extend(auth_context.contexts);
        }

        let grpc_request = GrpcMessageBuilder::new(request)
            .header(APP_FIELD.to_owned(), self.app_name.clone())
            .headers(request_headers)
            .build();
        let grpc_request = grpc_request.into_payload()?;

        let grpc_response = self
            .send_request
            .send_request(grpc_request)
            .in_current_span()
            .await?;

        let grpc_response = GrpcMessage::<Response>::from_payload(grpc_response)?;
        Ok(grpc_response.into_body())
    }
}

type HandlerMap = HashMap<String, Arc<dyn ServerRequestHandler>>;
type ConnectedListener = Arc<dyn Fn(String) + Send + Sync + 'static>;
type DisconnectedListener = Arc<dyn Fn(String) + Send + Sync + 'static>;

pub(crate) struct NacosGrpcClientBuilder {
    app_name: String,
    client_version: String,
    namespace: String,
    labels: HashMap<String, String>,
    client_abilities: NacosClientAbilities,
    grpc_config: GrpcConfiguration,
    server_request_handler_map: HandlerMap,
    server_list: Vec<String>,
    connected_listener: Option<ConnectedListener>,
    disconnected_listener: Option<DisconnectedListener>,
    unary_call_layer: Option<DynamicUnaryCallLayer>,
    bi_call_layer: Option<DynamicBiStreamingCallLayer>,
    auth_plugin: Arc<dyn AuthPlugin>,
    auth_context: HashMap<String, String>,
    max_retries: Option<u32>,
    emergency_start: bool,
}

#[allow(dead_code)]
impl NacosGrpcClientBuilder {
    pub(crate) fn new(server_list: Vec<String>) -> Self {
        Self {
            app_name: "unknown".to_owned(),
            client_version: Default::default(),
            namespace: Default::default(),
            labels: Default::default(),
            client_abilities: Default::default(),
            grpc_config: Default::default(),
            server_request_handler_map: Default::default(),
            server_list,
            connected_listener: None,
            disconnected_listener: None,
            unary_call_layer: None,
            bi_call_layer: None,
            auth_context: Default::default(),
            auth_plugin: Arc::new(NoopAuthPlugin::default()),
            max_retries: None,
            emergency_start: false,
        }
    }

    pub(crate) fn app_name(self, app_name: String) -> Self {
        Self { app_name, ..self }
    }

    pub(crate) fn client_version(self, client_version: String) -> Self {
        Self {
            client_version,
            ..self
        }
    }

    pub(crate) fn namespace(self, namespace: String) -> Self {
        Self { namespace, ..self }
    }

    pub(crate) fn add_label(mut self, key: String, value: String) -> Self {
        self.labels.insert(key, value);
        Self { ..self }
    }

    pub(crate) fn add_labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels.extend(labels);
        Self { ..self }
    }

    pub(crate) fn max_retries(mut self, max_retries: Option<u32>) -> Self {
        self.max_retries = max_retries;
        Self { ..self }
    }

    pub(crate) fn emergency_start(mut self, emergency_start: bool) -> Self {
        self.emergency_start = emergency_start;
        Self { ..self }
    }

    pub(crate) fn support_remote_connection(mut self, enable: bool) -> Self {
        self.client_abilities.support_remote_connection(enable);
        Self { ..self }
    }

    pub(crate) fn support_config_remote_metrics(mut self, enable: bool) -> Self {
        self.client_abilities.support_config_remote_metrics(enable);
        Self { ..self }
    }

    pub(crate) fn support_naming_delta_push(mut self, enable: bool) -> Self {
        self.client_abilities.support_naming_delta_push(enable);
        Self { ..self }
    }

    pub(crate) fn support_naming_remote_metric(mut self, enable: bool) -> Self {
        self.client_abilities.support_naming_remote_metric(enable);
        Self { ..self }
    }

    pub(crate) fn host(mut self, host: String) -> Self {
        self.grpc_config.host = host;
        self
    }

    pub(crate) fn port(mut self, port: Option<u32>) -> Self {
        self.grpc_config.port = port;
        self
    }

    pub(crate) fn origin(mut self, uri: &str) -> Self {
        self.grpc_config = self.grpc_config.with_origin(uri);
        self
    }

    pub(crate) fn user_agent(mut self, ua: String) -> Self {
        self.grpc_config = self.grpc_config.with_user_agent(ua);
        self
    }

    pub(crate) fn timeout(mut self, timeout: Duration) -> Self {
        self.grpc_config.timeout = Some(timeout);
        self
    }

    pub(crate) fn concurrency_limit(mut self, concurrency_limit: usize) -> Self {
        self.grpc_config.concurrency_limit = Some(concurrency_limit);
        self
    }

    pub(crate) fn rate_limit(mut self, rate_limit: (u64, Duration)) -> Self {
        self.grpc_config.rate_limit = Some(rate_limit);
        self
    }

    pub(crate) fn init_stream_window_size(mut self, init_stream_window_size: u32) -> Self {
        self.grpc_config.init_stream_window_size = Some(init_stream_window_size);
        self
    }

    pub(crate) fn init_connection_window_size(mut self, init_connection_window_size: u32) -> Self {
        self.grpc_config.init_connection_window_size = Some(init_connection_window_size);
        self
    }

    pub(crate) fn tcp_keepalive(mut self, tcp_keepalive: Duration) -> Self {
        self.grpc_config.tcp_keepalive = Some(tcp_keepalive);
        self
    }

    pub(crate) fn tcp_nodelay(mut self, tcp_nodelay: bool) -> Self {
        self.grpc_config.tcp_nodelay = tcp_nodelay;
        self
    }

    pub(crate) fn http2_keep_alive_interval(mut self, http2_keep_alive_interval: Duration) -> Self {
        self.grpc_config.http2_keep_alive_interval = Some(http2_keep_alive_interval);
        self
    }

    pub(crate) fn http2_keep_alive_timeout(mut self, http2_keep_alive_timeout: Duration) -> Self {
        self.grpc_config.http2_keep_alive_timeout = Some(http2_keep_alive_timeout);
        self
    }

    pub(crate) fn http2_keep_alive_while_idle(mut self, http2_keep_alive_while_idle: bool) -> Self {
        self.grpc_config.http2_keep_alive_while_idle = Some(http2_keep_alive_while_idle);
        self
    }

    pub(crate) fn connect_timeout(mut self, connect_timeout: Duration) -> Self {
        self.grpc_config.connect_timeout = Some(connect_timeout);
        self
    }

    pub(crate) fn http2_adaptive_window(mut self, http2_adaptive_window: bool) -> Self {
        self.grpc_config.http2_adaptive_window = Some(http2_adaptive_window);
        self
    }

    pub(crate) fn auth_plugin(self, auth_plugin: Arc<dyn AuthPlugin>) -> Self {
        Self {
            auth_plugin,
            ..self
        }
    }

    pub(crate) fn auth_context(self, auth_context: HashMap<String, String>) -> Self {
        Self {
            auth_context,
            ..self
        }
    }

    pub(crate) fn register_server_request_handler<T: GrpcMessageData>(
        mut self,
        handler: Arc<dyn ServerRequestHandler>,
    ) -> Self {
        self.server_request_handler_map
            .insert(T::identity().to_string(), handler);
        Self { ..self }
    }

    pub(crate) fn connected_listener(
        mut self,
        listener: impl Fn(String) + Send + Sync + 'static,
    ) -> Self {
        self.connected_listener = Some(Arc::new(listener));
        Self { ..self }
    }

    pub(crate) fn disconnected_listener(
        mut self,
        listener: impl Fn(String) + Send + Sync + 'static,
    ) -> Self {
        self.disconnected_listener = Some(Arc::new(listener));
        Self { ..self }
    }

    pub(crate) fn unary_call_layer(self, layer: DynamicUnaryCallLayer) -> Self {
        let stack = if let Some(unary_call_layer) = self.unary_call_layer {
            Arc::new(Stack::new(
                DynamicUnaryCallLayerWrapper(layer),
                DynamicUnaryCallLayerWrapper(unary_call_layer),
            ))
        } else {
            layer
        };

        Self {
            unary_call_layer: Some(stack),
            ..self
        }
    }

    pub(crate) fn bi_call_layer(self, layer: DynamicBiStreamingCallLayer) -> Self {
        let stack = if let Some(bi_call_layer) = self.bi_call_layer {
            Arc::new(Stack::new(
                DynamicBiStreamingCallLayerWrapper(layer),
                DynamicBiStreamingCallLayerWrapper(bi_call_layer),
            ))
        } else {
            layer
        };

        Self {
            bi_call_layer: Some(stack),
            ..self
        }
    }

    pub(crate) async fn build(mut self, id: String) -> Result<NacosGrpcClient, Error> {
        self.server_request_handler_map.insert(
            ClientDetectionRequest::identity().to_string(),
            Arc::new(ClientDetectionRequestHandler),
        );

        let send_request = {
            let server_list = PollingServerListService::new(self.server_list.clone());
            let mut tonic_builder = TonicBuilder::new(self.grpc_config, server_list);
            if let Some(layer) = self.unary_call_layer {
                tonic_builder = tonic_builder.unary_call_layer(layer);
            }

            if let Some(layer) = self.bi_call_layer {
                tonic_builder = tonic_builder.bi_call_layer(layer);
            }

            let mut connection = NacosGrpcConnection::new(
                id.clone(),
                tonic_builder,
                self.server_request_handler_map,
                self.client_version,
                self.namespace,
                self.labels,
                self.client_abilities,
                self.max_retries,
            );

            if let Some(connected_listener) = self.connected_listener {
                connection = connection.connected_listener(connected_listener);
            }

            if let Some(disconnected_listener) = self.disconnected_listener {
                connection = connection.disconnected_listener(disconnected_listener);
            }

            let failover_connection = connection.into_failover_connection(id.clone());
            Arc::new(failover_connection) as Arc<dyn SendRequest + Send + Sync + 'static>
        };

        // Verify connection by sending a health check request
        let health_check_request = GrpcMessageBuilder::new(HealthCheckRequest::default())
            .build()
            .into_payload()?;
        match send_request.send_request(health_check_request).await {
            Ok(_) => {
                tracing::info!("health check passed, connected to Nacos server");
            }
            Err(e) => {
                if self.emergency_start {
                    tracing::warn!(
                        "health check failed, cannot connect to Nacos server, but continuing startup in emergency mode: {}",
                        e
                    );
                } else {
                    return Err(e);
                }
            }
        }

        init_auth_plugin(
            self.auth_plugin.clone(),
            self.server_list.clone(),
            self.auth_context.clone(),
            id,
        )
        .await;

        let app_name = self.app_name;
        let auth_plugin = self.auth_plugin;

        Ok(NacosGrpcClient {
            app_name,
            send_request,
            auth_plugin,
        })
    }
}

#[cfg(test)]
pub mod tests {

    use crate::common::remote::grpc::{
        message::{request::HealthCheckRequest, response::HealthCheckResponse},
        nacos_grpc_connection::MockSendRequest,
    };

    use mockall::predicate::*;

    use super::*;

    #[tokio::test]
    pub async fn test_send_request() {
        let health_check_request = HealthCheckRequest {
            request_id: Some("test_health_check_id".to_string()),
            ..Default::default()
        };

        let mut mock_send_request = MockSendRequest::new();
        mock_send_request
            .expect_send_request()
            .with(function(|req: &crate::nacos_proto::v2::Payload| {
                let app_name = &req
                    .metadata
                    .as_ref()
                    .map(|data| {
                        data.headers
                            .get(APP_FIELD)
                            .expect("APP field should exist in headers")
                            .clone()
                    })
                    .expect("APP field extraction should not fail");

                app_name.eq("test_app")
            }))
            .returning(|req| {
                let request = GrpcMessage::<HealthCheckRequest>::from_payload(req)
                    .expect("Payload should deserialize to HealthCheckRequest");
                let request = request.into_body();
                let req_id = request
                    .request_id
                    .expect("Request ID should exist in the deserialized request");

                let response = HealthCheckResponse {
                    request_id: Some(req_id),
                    ..Default::default()
                };

                let payload = GrpcMessageBuilder::new(response)
                    .build()
                    .into_payload()
                    .expect("GRPC message should build into payload");
                Ok(payload)
            });

        let nacos_grpc_client = NacosGrpcClient {
            app_name: "test_app".to_string(),
            send_request: Arc::new(mock_send_request),
            auth_plugin: Arc::new(NoopAuthPlugin::default()),
        };

        let response = nacos_grpc_client
            .send_request::<HealthCheckRequest, HealthCheckResponse>(health_check_request)
            .await;
        let response = response.expect("Health check response should succeed");

        assert_eq!(
            "test_health_check_id".to_string(),
            response
                .request_id
                .expect("Response request ID should exist")
        );
    }
}