batata-client 0.0.2

Rust client for Batata/Nacos service discovery and configuration management
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use std::sync::Arc;
use std::time::Duration;

use parking_lot::RwLock;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};

use crate::api::naming::{
    Instance, InstanceRequest, InstanceResponse, QueryServiceResponse, ServiceListRequest,
    ServiceListResponse, ServiceQueryRequest, SubscribeServiceRequest, SubscribeServiceResponse,
};
use crate::cache::FileCache;
use crate::common::{build_service_key, DEFAULT_GROUP};
use crate::error::{BatataError, Result};
use crate::naming::{
    CallbackServiceListener, LoadBalancer, ServiceChangeEvent, ServiceInfoCache, ServiceListener,
    SubscriberRegistry, WeightedRoundRobinBalancer,
};
use crate::remote::RpcClient;
use crate::CacheConfig;

/// Naming service for service discovery and registration
pub struct NamingService {
    /// RPC client for server communication
    rpc_client: Arc<RpcClient>,

    /// Service information cache
    cache: Arc<ServiceInfoCache>,

    /// File cache for failover
    file_cache: Option<Arc<FileCache>>,

    /// Cache configuration
    cache_config: CacheConfig,

    /// Load balancer for instance selection
    balancer: Arc<dyn LoadBalancer>,

    /// Subscriber registry
    subscribers: Arc<SubscriberRegistry>,

    /// Namespace
    namespace: String,

    /// Group name
    group_name: String,

    /// Whether the service is started
    started: Arc<RwLock<bool>>,

    /// Heartbeat task handle
    heartbeat_task: Arc<RwLock<Option<JoinHandle<()>>>>,

    /// Shutdown notify
    shutdown: Arc<Notify>,

    /// Registered instances
    registered_instances: Arc<RwLock<Vec<(String, String, Instance)>>>,
}

impl NamingService {
    /// Create a new NamingService with default WRR load balancer
    pub fn new(rpc_client: Arc<RpcClient>, namespace: &str, cache_config: CacheConfig) -> Self {
        Self::with_balancer(
            rpc_client,
            namespace,
            cache_config,
            Arc::new(WeightedRoundRobinBalancer::new()),
        )
    }

    /// Create a new NamingService with custom load balancer
    pub fn with_balancer(
        rpc_client: Arc<RpcClient>,
        namespace: &str,
        cache_config: CacheConfig,
        balancer: Arc<dyn LoadBalancer>,
    ) -> Self {
        // Create file cache if cache directory is configured
        let file_cache = cache_config
            .cache_dir
            .as_ref()
            .and_then(|dir| FileCache::new(dir).ok())
            .map(Arc::new);

        Self {
            rpc_client,
            cache: Arc::new(ServiceInfoCache::new()),
            file_cache,
            cache_config,
            balancer,
            subscribers: Arc::new(SubscriberRegistry::new()),
            namespace: namespace.to_string(),
            group_name: DEFAULT_GROUP.to_string(),
            started: Arc::new(RwLock::new(false)),
            heartbeat_task: Arc::new(RwLock::new(None)),
            shutdown: Arc::new(Notify::new()),
            registered_instances: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Set default group name
    pub fn with_group(mut self, group_name: &str) -> Self {
        self.group_name = group_name.to_string();
        self
    }

    /// Start the naming service
    pub async fn start(&self) -> Result<()> {
        if *self.started.read() {
            return Err(BatataError::ClientAlreadyStarted);
        }

        *self.started.write() = true;

        // Start heartbeat task for ephemeral instances
        let instances = self.registered_instances.clone();
        let rpc_client = self.rpc_client.clone();
        let namespace = self.namespace.clone();
        let shutdown = self.shutdown.clone();

        let handle = tokio::spawn(async move {
            Self::heartbeat_loop(instances, rpc_client, namespace, shutdown).await;
        });

        *self.heartbeat_task.write() = Some(handle);

        info!("NamingService started");
        Ok(())
    }

    /// Stop the naming service
    pub async fn stop(&self) {
        *self.started.write() = false;
        self.shutdown.notify_one();

        if let Some(handle) = self.heartbeat_task.write().take() {
            handle.abort();
        }

        // Deregister all instances
        let instances = self.registered_instances.read().clone();
        for (service_name, group_name, instance) in instances {
            if let Err(e) = self.deregister_instance(&service_name, &group_name, instance).await {
                warn!("Failed to deregister instance on shutdown: {}", e);
            }
        }

        info!("NamingService stopped");
    }

    /// Register a service instance
    pub async fn register_instance(
        &self,
        service_name: &str,
        group_name: &str,
        instance: Instance,
    ) -> Result<()> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        let mut instance = instance;
        instance.generate_instance_id();

        let request =
            InstanceRequest::register(&self.namespace, service_name, group_name, instance.clone());

        let response: InstanceResponse = self.rpc_client.request(&request).await?;

        if !response.response.success {
            return Err(BatataError::server_error(
                response.response.error_code,
                response.response.message,
            ));
        }

        // Track registered instance for heartbeat
        if instance.ephemeral {
            self.registered_instances.write().push((
                service_name.to_string(),
                group_name.to_string(),
                instance,
            ));
        }

        info!(
            "Registered instance: service={}, group={}",
            service_name, group_name
        );

        Ok(())
    }

    /// Register a service instance with simplified parameters
    pub async fn register_instance_simple(
        &self,
        service_name: &str,
        ip: &str,
        port: i32,
    ) -> Result<()> {
        let instance = Instance::new(ip, port);
        self.register_instance(service_name, &self.group_name, instance)
            .await
    }

    /// Deregister a service instance
    pub async fn deregister_instance(
        &self,
        service_name: &str,
        group_name: &str,
        instance: Instance,
    ) -> Result<()> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        let request =
            InstanceRequest::deregister(&self.namespace, service_name, group_name, instance.clone());

        let response: InstanceResponse = self.rpc_client.request(&request).await?;

        if !response.response.success {
            return Err(BatataError::server_error(
                response.response.error_code,
                response.response.message,
            ));
        }

        // Remove from registered instances
        self.registered_instances
            .write()
            .retain(|(s, g, i)| !(s == service_name && g == group_name && i.key() == instance.key()));

        info!(
            "Deregistered instance: service={}, group={}",
            service_name, group_name
        );

        Ok(())
    }

    /// Deregister a service instance with simplified parameters
    pub async fn deregister_instance_simple(
        &self,
        service_name: &str,
        ip: &str,
        port: i32,
    ) -> Result<()> {
        let instance = Instance::new(ip, port);
        self.deregister_instance(service_name, &self.group_name, instance)
            .await
    }

    /// Update a service instance
    pub async fn update_instance(
        &self,
        service_name: &str,
        group_name: &str,
        instance: Instance,
    ) -> Result<()> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        let request =
            InstanceRequest::update(&self.namespace, service_name, group_name, instance.clone());

        let response: InstanceResponse = self.rpc_client.request(&request).await?;

        if !response.response.success {
            return Err(BatataError::server_error(
                response.response.error_code,
                response.response.message,
            ));
        }

        // Update in registered instances list
        {
            let mut registered = self.registered_instances.write();
            for (s, g, i) in registered.iter_mut() {
                if s == service_name && g == group_name && i.key() == instance.key() {
                    *i = instance.clone();
                    break;
                }
            }
        }

        info!(
            "Updated instance: service={}, group={}",
            service_name, group_name
        );

        Ok(())
    }

    /// Update a service instance with simplified parameters
    pub async fn update_instance_simple(
        &self,
        service_name: &str,
        ip: &str,
        port: i32,
        weight: f64,
        enabled: bool,
    ) -> Result<()> {
        let instance = Instance::new(ip, port)
            .with_weight(weight)
            .with_enabled(enabled);
        self.update_instance(service_name, &self.group_name, instance)
            .await
    }

    /// Get service information with cluster filtering
    pub async fn get_service(
        &self,
        service_name: &str,
        group_name: &str,
        clusters: &[String],
    ) -> Result<crate::api::naming::Service> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        let cluster_str = clusters.join(",");
        let request = ServiceQueryRequest::new(&self.namespace, service_name, group_name)
            .with_cluster(&cluster_str);

        let response: QueryServiceResponse = self.rpc_client.request(&request).await?;

        // Update cache
        self.cache.put(&self.namespace, response.service_info.clone());

        Ok(response.service_info)
    }

    /// Get all instances of a service
    pub async fn get_all_instances(
        &self,
        service_name: &str,
        group_name: &str,
    ) -> Result<Vec<Instance>> {
        self.select_instances(service_name, group_name, false).await
    }

    /// Select healthy instances of a service
    pub async fn select_instances(
        &self,
        service_name: &str,
        group_name: &str,
        healthy_only: bool,
    ) -> Result<Vec<Instance>> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        // Try memory cache first
        if let Some(service) = self.cache.get(&self.namespace, group_name, service_name) {
            let instances = if healthy_only {
                service
                    .hosts
                    .into_iter()
                    .filter(|i| i.healthy && i.enabled)
                    .collect()
            } else {
                service.hosts
            };
            return Ok(instances);
        }

        // Fetch from server
        let request = ServiceQueryRequest::new(&self.namespace, service_name, group_name)
            .with_healthy_only(healthy_only);

        match self
            .rpc_client
            .request::<_, QueryServiceResponse>(&request)
            .await
        {
            Ok(response) => {
                // Update memory cache
                self.cache
                    .put(&self.namespace, response.service_info.clone());

                // Save to file cache for failover
                if let Some(file_cache) = &self.file_cache {
                    if let Err(e) = file_cache.save_service(&self.namespace, &response.service_info)
                    {
                        warn!("Failed to save service to file cache: {}", e);
                    }
                }

                let instances = if healthy_only {
                    response
                        .service_info
                        .hosts
                        .into_iter()
                        .filter(|i| i.healthy && i.enabled)
                        .collect()
                } else {
                    response.service_info.hosts
                };

                Ok(instances)
            }
            Err(e) => {
                // Failover: try file cache
                if self.cache_config.failover_enabled {
                    if let Some(file_cache) = &self.file_cache {
                        if let Some(service) =
                            file_cache.load_service(&self.namespace, group_name, service_name)
                        {
                            warn!(
                                "Using cached service due to server error: {} (service={}, group={})",
                                e, service_name, group_name
                            );

                            // Optionally update memory cache
                            if self.cache_config.update_cache_when_empty {
                                self.cache.put(&self.namespace, service.clone());
                            }

                            let instances = if healthy_only {
                                service
                                    .hosts
                                    .into_iter()
                                    .filter(|i| i.healthy && i.enabled)
                                    .collect()
                            } else {
                                service.hosts
                            };

                            return Ok(instances);
                        }
                    }
                }
                Err(e)
            }
        }
    }

    /// Select one healthy instance using the configured load balancer
    ///
    /// By default, uses Weighted Round Robin (WRR) algorithm which distributes
    /// traffic proportionally to instance weights.
    pub async fn select_one_healthy_instance(
        &self,
        service_name: &str,
        group_name: &str,
    ) -> Result<Instance> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        let instances = self.select_instances(service_name, group_name, false).await?;

        if instances.is_empty() {
            return Err(BatataError::ServiceNotFound {
                service_name: service_name.to_string(),
                group_name: group_name.to_string(),
                namespace: self.namespace.clone(),
            });
        }

        // Use load balancer for instance selection
        let service_key = build_service_key(service_name, group_name, &self.namespace);

        self.balancer
            .select(&service_key, &instances)
            .ok_or_else(|| BatataError::ServiceNotFound {
                service_name: service_name.to_string(),
                group_name: group_name.to_string(),
                namespace: self.namespace.clone(),
            })
    }

    /// Get list of services
    pub async fn get_services_of_server(
        &self,
        group_name: &str,
        page_no: i32,
        page_size: i32,
    ) -> Result<(i32, Vec<String>)> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        let request = ServiceListRequest::new(&self.namespace, group_name)
            .with_page(page_no, page_size);

        let response: ServiceListResponse = self.rpc_client.request(&request).await?;

        Ok((response.count, response.service_names))
    }

    /// Subscribe to service changes
    pub async fn subscribe<L>(
        &self,
        service_name: &str,
        group_name: &str,
        listener: L,
    ) -> Result<()>
    where
        L: ServiceListener + 'static,
    {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        // Add listener
        self.subscribers.subscribe(
            &self.namespace,
            group_name,
            service_name,
            Arc::new(listener),
        );

        // Send subscribe request
        let request = SubscribeServiceRequest::subscribe(&self.namespace, service_name, group_name);

        let response: SubscribeServiceResponse = self.rpc_client.request(&request).await?;

        // Update cache with initial data
        self.cache.put(&self.namespace, response.service_info.clone());

        info!(
            "Subscribed to service: service={}, group={}",
            service_name, group_name
        );

        Ok(())
    }

    /// Subscribe with callback
    pub async fn subscribe_callback<F>(
        &self,
        service_name: &str,
        group_name: &str,
        callback: F,
    ) -> Result<()>
    where
        F: Fn(ServiceChangeEvent) + Send + Sync + 'static,
    {
        self.subscribe(service_name, group_name, CallbackServiceListener::new(callback))
            .await
    }

    /// Unsubscribe from service changes
    pub async fn unsubscribe(&self, service_name: &str, group_name: &str) -> Result<()> {
        let group_name = if group_name.is_empty() {
            &self.group_name
        } else {
            group_name
        };

        self.subscribers
            .unsubscribe(&self.namespace, group_name, service_name);

        // Send unsubscribe request
        let request = SubscribeServiceRequest::unsubscribe(&self.namespace, service_name, group_name);

        let _response: SubscribeServiceResponse = self.rpc_client.request(&request).await?;

        info!(
            "Unsubscribed from service: service={}, group={}",
            service_name, group_name
        );

        Ok(())
    }

    /// Get server status
    pub async fn get_server_status(&self) -> Result<String> {
        if self.rpc_client.is_connected() {
            Ok("UP".to_string())
        } else {
            Ok("DOWN".to_string())
        }
    }

    /// Background heartbeat loop for ephemeral instances
    async fn heartbeat_loop(
        instances: Arc<RwLock<Vec<(String, String, Instance)>>>,
        rpc_client: Arc<RpcClient>,
        namespace: String,
        shutdown: Arc<Notify>,
    ) {
        let heartbeat_interval = Duration::from_secs(5);

        loop {
            tokio::select! {
                _ = shutdown.notified() => {
                    info!("Heartbeat loop shutdown");
                    break;
                }
                _ = tokio::time::sleep(heartbeat_interval) => {
                    let registered = instances.read().clone();

                    for (service_name, group_name, instance) in registered {
                        if !instance.ephemeral {
                            continue;
                        }

                        // Re-register to maintain heartbeat
                        let request = InstanceRequest::register(
                            &namespace,
                            &service_name,
                            &group_name,
                            instance,
                        );

                        if let Err(e) = rpc_client.request::<_, InstanceResponse>(&request).await {
                            warn!(
                                "Heartbeat failed for service={}, group={}: {}",
                                service_name, group_name, e
                            );
                        } else {
                            debug!(
                                "Heartbeat sent for service={}, group={}",
                                service_name, group_name
                            );
                        }
                    }
                }
            }
        }
    }
}

impl Drop for NamingService {
    fn drop(&mut self) {
        self.shutdown.notify_one();
    }
}