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
use std::sync::Arc;
use std::time::Duration;

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

use crate::api::config::{
    ConfigBatchListenRequest, ConfigChangeBatchListenResponse, ConfigInfo, ConfigListenContext,
    ConfigPublishRequest, ConfigPublishResponse, ConfigQueryRequest, ConfigQueryResponse,
    ConfigRemoveRequest, ConfigRemoveResponse, ConfigSearchRequest, ConfigSearchResponse,
    ConfigSearchItem,
};
use crate::cache::FileCache;
use crate::common::{md5_hash, DEFAULT_GROUP};
use crate::config::{
    CallbackListener, ConfigCache, ConfigChangeEvent, ConfigChangeType, ConfigListener,
    ListenerRegistry,
};
use crate::error::{BatataError, Result};
use crate::remote::RpcClient;
use crate::CacheConfig;

/// Configuration service for managing configurations
pub struct ConfigService {
    /// RPC client for server communication
    rpc_client: Arc<RpcClient>,

    /// Local configuration cache
    cache: Arc<ConfigCache>,

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

    /// Cache configuration
    cache_config: CacheConfig,

    /// Listener registry
    listeners: Arc<ListenerRegistry>,

    /// Namespace
    namespace: String,

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

    /// Background task handle
    listen_task: Arc<RwLock<Option<JoinHandle<()>>>>,

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

impl ConfigService {
    /// Create a new ConfigService
    pub fn new(rpc_client: Arc<RpcClient>, namespace: &str, cache_config: CacheConfig) -> 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(ConfigCache::new()),
            file_cache,
            cache_config,
            listeners: Arc::new(ListenerRegistry::new()),
            namespace: namespace.to_string(),
            started: Arc::new(RwLock::new(false)),
            listen_task: Arc::new(RwLock::new(None)),
            shutdown: Arc::new(Notify::new()),
        }
    }

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

        *self.started.write() = true;

        // Start background listener task
        let listeners = self.listeners.clone();
        let cache = self.cache.clone();
        let rpc_client = self.rpc_client.clone();
        let shutdown = self.shutdown.clone();

        let handle = tokio::spawn(async move {
            Self::listen_loop(listeners, cache, rpc_client, shutdown).await;
        });

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

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

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

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

        info!("ConfigService stopped");
    }

    /// Get configuration
    pub async fn get_config(&self, data_id: &str, group: &str) -> Result<String> {
        self.get_config_with_timeout(data_id, group, 3000).await
    }

    /// Get configuration with timeout
    pub async fn get_config_with_timeout(
        &self,
        data_id: &str,
        group: &str,
        _timeout_ms: u64,
    ) -> Result<String> {
        let group = if group.is_empty() { DEFAULT_GROUP } else { group };

        // Try memory cache first
        if let Some(config) = self.cache.get(data_id, group, &self.namespace) {
            return Ok(config.content);
        }

        // Fetch from server
        let request = ConfigQueryRequest::new(data_id, group, &self.namespace);

        match self.rpc_client.request::<_, ConfigQueryResponse>(&request).await {
            Ok(response) => {
                if response.response.error_code == ConfigQueryResponse::CONFIG_NOT_FOUND {
                    return Err(BatataError::ConfigNotFound {
                        data_id: data_id.to_string(),
                        group: group.to_string(),
                        namespace: self.namespace.clone(),
                    });
                }

                // Update memory cache
                let mut config = ConfigInfo::new(data_id, group, &self.namespace);
                config.content = response.content.clone();
                config.md5 = response.md5.clone();
                config.last_modified = response.last_modified;
                config.content_type = response.content_type.clone();
                self.cache.put(config.clone());

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

                Ok(response.content)
            }
            Err(e) => {
                // Failover: try file cache
                if self.cache_config.failover_enabled {
                    if let Some(file_cache) = &self.file_cache {
                        if let Some(config) = file_cache.load_config(data_id, group, &self.namespace)
                        {
                            warn!(
                                "Using cached config due to server error: {} (dataId={}, group={})",
                                e, data_id, group
                            );

                            // Optionally update memory cache
                            if self.cache_config.update_cache_when_empty {
                                self.cache.put(config.clone());
                            }

                            return Ok(config.content);
                        }
                    }
                }
                Err(e)
            }
        }
    }

    /// Get configuration and sign listener
    pub async fn get_config_and_sign_listener<L>(
        &self,
        data_id: &str,
        group: &str,
        listener: L,
    ) -> Result<String>
    where
        L: ConfigListener + 'static,
    {
        let content = self.get_config(data_id, group).await?;

        // Add listener
        self.add_listener(data_id, group, listener);

        // Update MD5 in listener registry
        let md5 = md5_hash(&content);
        self.listeners
            .set_md5(data_id, group, &self.namespace, &md5);

        Ok(content)
    }

    /// Publish configuration
    pub async fn publish_config(&self, data_id: &str, group: &str, content: &str) -> Result<bool> {
        self.publish_config_with_type(data_id, group, content, None)
            .await
    }

    /// Publish configuration with type
    pub async fn publish_config_with_type(
        &self,
        data_id: &str,
        group: &str,
        content: &str,
        config_type: Option<&str>,
    ) -> Result<bool> {
        let group = if group.is_empty() { DEFAULT_GROUP } else { group };

        let mut request = ConfigPublishRequest::new(data_id, group, &self.namespace, content);

        if let Some(t) = config_type {
            request = request.with_type(t);
        }

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

        if response.response.success {
            // Update cache
            let mut config = ConfigInfo::new(data_id, group, &self.namespace);
            config.update_content(content);
            self.cache.put(config);
        }

        Ok(response.response.success)
    }

    /// Remove configuration
    pub async fn remove_config(&self, data_id: &str, group: &str) -> Result<bool> {
        let group = if group.is_empty() { DEFAULT_GROUP } else { group };

        let request = ConfigRemoveRequest::new(data_id, group, &self.namespace);

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

        if response.response.success {
            self.cache.remove(data_id, group, &self.namespace);
        }

        Ok(response.response.success)
    }

    /// Add listener for configuration changes
    pub fn add_listener<L>(&self, data_id: &str, group: &str, listener: L)
    where
        L: ConfigListener + 'static,
    {
        let group = if group.is_empty() { DEFAULT_GROUP } else { group };

        self.listeners
            .add_listener(data_id, group, &self.namespace, Arc::new(listener));

        // Set initial MD5 from cache
        if let Some(config) = self.cache.get(data_id, group, &self.namespace) {
            self.listeners
                .set_md5(data_id, group, &self.namespace, &config.md5);
        }
    }

    /// Add callback listener
    pub fn add_callback_listener<F>(&self, data_id: &str, group: &str, callback: F)
    where
        F: Fn(ConfigChangeEvent) + Send + Sync + 'static,
    {
        self.add_listener(data_id, group, CallbackListener::new(callback));
    }

    /// Remove listener
    pub fn remove_listener(&self, data_id: &str, group: &str) {
        let group = if group.is_empty() { DEFAULT_GROUP } else { group };
        self.listeners.remove_listener(data_id, group, &self.namespace);
    }

    /// Search configurations with pagination
    pub async fn search_config(
        &self,
        data_id_pattern: &str,
        group_pattern: &str,
        page_no: i32,
        page_size: i32,
    ) -> Result<(i32, Vec<ConfigSearchItem>)> {
        let request = ConfigSearchRequest::new(&self.namespace)
            .with_data_id(data_id_pattern)
            .with_group(group_pattern)
            .with_page(page_no, page_size);

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

        Ok((response.total_count, response.page_items))
    }

    /// Search configurations with blur matching
    pub async fn search_config_blur(
        &self,
        data_id_pattern: &str,
        group_pattern: &str,
    ) -> Result<Vec<ConfigSearchItem>> {
        let (_, items) = self.search_config(data_id_pattern, group_pattern, 1, 1000).await?;
        Ok(items)
    }

    /// 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 listen loop for configuration changes
    async fn listen_loop(
        listeners: Arc<ListenerRegistry>,
        cache: Arc<ConfigCache>,
        rpc_client: Arc<RpcClient>,
        shutdown: Arc<Notify>,
    ) {
        let listen_interval = Duration::from_secs(30);

        loop {
            tokio::select! {
                _ = shutdown.notified() => {
                    info!("Listen loop shutdown");
                    break;
                }
                _ = tokio::time::sleep(listen_interval) => {
                    if listeners.listener_count() == 0 {
                        continue;
                    }

                    // Build batch listen request
                    let contexts = listeners.get_listen_contexts();
                    if contexts.is_empty() {
                        continue;
                    }

                    let mut request = ConfigBatchListenRequest::new(true);
                    for (data_id, group, tenant, md5) in contexts {
                        request = request.add_context(ConfigListenContext::new(
                            &data_id, &group, &tenant, &md5,
                        ));
                    }

                    // Send listen request
                    match rpc_client.request::<_, ConfigChangeBatchListenResponse>(&request).await {
                        Ok(response) => {
                            for changed in response.changed_configs {
                                debug!(
                                    "Config changed: dataId={}, group={}, tenant={}",
                                    changed.data_id, changed.group, changed.tenant
                                );

                                // Fetch new content
                                let query_request = ConfigQueryRequest::new(
                                    &changed.data_id,
                                    &changed.group,
                                    &changed.tenant,
                                );

                                match rpc_client.request::<_, ConfigQueryResponse>(&query_request).await {
                                    Ok(query_response) => {
                                        let old_content = cache
                                            .get(&changed.data_id, &changed.group, &changed.tenant)
                                            .map(|c| c.content);

                                        let event = ConfigChangeEvent::new(
                                            &changed.data_id,
                                            &changed.group,
                                            &changed.tenant,
                                            old_content,
                                            query_response.content.clone(),
                                            ConfigChangeType::Modify,
                                        );

                                        // Update cache
                                        let mut config = ConfigInfo::new(
                                            &changed.data_id,
                                            &changed.group,
                                            &changed.tenant,
                                        );
                                        config.content = query_response.content;
                                        config.md5 = query_response.md5.clone();
                                        config.last_modified = query_response.last_modified;
                                        cache.put(config);

                                        // Update MD5 in listeners
                                        listeners.set_md5(
                                            &changed.data_id,
                                            &changed.group,
                                            &changed.tenant,
                                            &query_response.md5,
                                        );

                                        // Notify listeners
                                        listeners.notify_change(event).await;
                                    }
                                    Err(e) => {
                                        error!("Failed to fetch changed config: {}", e);
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            warn!("Config listen request failed: {}", e);
                        }
                    }
                }
            }
        }
    }
}

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