zus-discovery 1.1.4

Service discovery client for ZUS RPC framework with ZooServer integration
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
use {
  bytes::Bytes,
  dashmap::DashMap,
  prost::Message,
  std::{
    sync::{
      Arc,
      atomic::{AtomicBool, Ordering},
    },
    time::Duration,
  },
  tokio::time::interval,
  tracing::{error, info, warn},
};

use {
  zus_common::{Result, RpcEndpoint, ZusError},
  zus_proto::*,
};

/// ZooServer Path Node (cached path information)
#[derive(Debug, Clone)]
pub struct ZooPathNode {
  pub path: String,
  pub value: Bytes,
  pub version: i64,
  pub create_flags: i32,
}

/// ZooServer Client (replacing Java's ZusZooClient)
pub struct ZusZooClient {
  #[allow(dead_code)]
  addresses: Vec<String>, // Kept for potential reconnection logic
  sessionid: Arc<parking_lot::RwLock<String>>,
  endpoint: Arc<RpcEndpoint>,
  path_cache: Arc<DashMap<String, ZooPathNode>>,
  running: Arc<AtomicBool>,
}

impl ZusZooClient {
  /// Create new ZooServer client
  pub async fn new(addresses: Vec<String>) -> Result<Arc<Self>> {
    if addresses.is_empty() {
      return Err(ZusError::Connection("No ZooServer addresses provided".to_string()));
    }

    // Connect to first available server
    let endpoint = Self::connect_to_server(&addresses).await?;

    let client = Arc::new(Self {
      addresses,
      sessionid: Arc::new(parking_lot::RwLock::new(String::new())),
      endpoint: Arc::new(endpoint),
      path_cache: Arc::new(DashMap::new()),
      running: Arc::new(AtomicBool::new(true)),
    });

    // Register client
    client.register_client().await?;

    // Start background sync thread
    let client_clone = client.clone();
    tokio::spawn(async move {
      client_clone.sync_loop().await;
    });

    Ok(client)
  }

  /// Connect to ZooServer
  async fn connect_to_server(addresses: &[String]) -> Result<RpcEndpoint> {
    for addr in addresses {
      let parts: Vec<&str> = addr.split(':').collect();
      if parts.len() != 2 {
        continue;
      }

      let host = parts[0].to_string();
      let port = parts[1].parse::<u16>().ok().unwrap_or(2181);

      match RpcEndpoint::connect(host, port).await {
        | Ok(endpoint) => {
          info!("Connected to ZooServer at {}", addr);
          return Ok(endpoint);
        }
        | Err(_) => continue,
      }
    }

    Err(ZusError::Connection("Failed to connect to any ZooServer".to_string()))
  }

  /// Register client with ZooServer
  async fn register_client(&self) -> Result<()> {
    let req = ZooRegisterClientRequest::default();

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("RegisterClient"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooRegisterClientResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      return Err(ZusError::Rpc(format!("Registration failed: {}", resp.ret)));
    }

    let sessionid = resp.sessionid.clone().unwrap_or_default();
    *self.sessionid.write() = sessionid.clone();
    info!("Registered with sessionid: {}", sessionid);

    Ok(())
  }

  /// Create path in ZooServer
  pub async fn create_path(&self, path: String, value: Bytes, create_flags: i32) -> Result<u64> {
    let req = ZooCreatePathRequest {
      sessionid: self.sessionid.read().clone(),
      path: path.clone(),
      flags: Some(create_flags),
      val: Some(value.to_vec()),
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("CreatePath"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooCreatePathResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      return Err(ZusError::Rpc(format!("CreatePath failed: {}", resp.ret)));
    }

    let version = resp.version.unwrap_or(0);

    // Cache the path
    self.path_cache.insert(
      path.clone(),
      ZooPathNode {
        path,
        value,
        version: version as i64,
        create_flags,
      },
    );

    Ok(version)
  }

  /// Get path children
  pub async fn get_path_child(&self, path: &str) -> Result<Vec<ZooPathFileNode>> {
    let req = ZooGetPathChildRequest {
      sessionid: self.sessionid.read().clone(),
      path: path.to_string(),
      watch: None,
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("GetPathChild"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooGetPathChildResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      if resp.ret == constants::ZOO_RET_PATH_NOT_EXIST {
        return Ok(Vec::new());
      }
      return Err(ZusError::Rpc(format!("GetPathChild failed: {}", resp.ret)));
    }

    Ok(resp.childs)
  }

  /// Get path children with extended info (including ephemeral/persistent flags)
  pub async fn get_path_child_ex(&self, path: &str) -> Result<Vec<ZooPathFileNodeEx>> {
    let req = ZooGetPathChildExRequest {
      sessionid: self.sessionid.read().clone(),
      path: path.to_string(),
      watch: None,
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("GetPathChildEx"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooGetPathChildExResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      if resp.ret == constants::ZOO_RET_PATH_NOT_EXIST {
        return Ok(Vec::new());
      }
      return Err(ZusError::Rpc(format!("GetPathChildEx failed: {}", resp.ret)));
    }

    Ok(resp.childs)
  }

  /// Get path value
  pub async fn get_path_value(&self, path: &str) -> Result<(Bytes, u64)> {
    let req = ZooGetPathRequest {
      sessionid: self.sessionid.read().clone(),
      path: path.to_string(),
      watch: None,
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("GetPath"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooGetPathResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      return Err(ZusError::Rpc(format!("GetPath failed: {}", resp.ret)));
    }

    let value = resp.val.clone().unwrap_or_default();
    let version = resp.version.unwrap_or(0);

    Ok((Bytes::from(value), version))
  }

  /// Delete path
  pub async fn delete_path(&self, path: &str) -> Result<()> {
    let req = ZooDeletePathRequest {
      sessionid: self.sessionid.read().clone(),
      path: path.to_string(),
      version: None,
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("DeletePath"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooDeletePathResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      return Err(ZusError::Rpc(format!("DeletePath failed: {}", resp.ret)));
    }

    self.path_cache.remove(path);
    Ok(())
  }

  /// Set path value (update existing path)
  pub async fn set_path(&self, path: &str, value: Bytes, version: u64) -> Result<u64> {
    let req = ZooSetPathRequest {
      sessionid: self.sessionid.read().clone(),
      path: path.to_string(),
      watch: None,
      val: value.to_vec(),
      version: Some(version),
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("SetPath"), Bytes::from(buf), 5000)
      .await?;

    let resp = ZooSetPathResponse::decode(response)?;
    if resp.ret != constants::ZOO_RET_SUCCESS {
      return Err(ZusError::Rpc(format!("SetPath failed: {}", resp.ret)));
    }

    let new_version = resp.version.unwrap_or(version);

    // Update cache
    if let Some(mut entry) = self.path_cache.get_mut(path) {
      entry.value = value;
      entry.version = new_version as i64;
    }

    Ok(new_version)
  }

  /// Synchronize path versions (background task)
  async fn sync_path_versions(&self) -> Result<()> {
    if self.path_cache.is_empty() {
      return Ok(());
    }

    let path_nodes: Vec<ZooPathFileNode> = self
      .path_cache
      .iter()
      .map(|entry| ZooPathFileNode {
        file: entry.key().clone(),
        version: entry.value().version as u64,
        val: None,
      })
      .collect();

    let req = ZooSyncPathRequest {
      sessionid: self.sessionid.read().clone(),
      pathnode: path_nodes,
    };

    let mut buf = Vec::new();
    req.encode(&mut buf)?;

    let response = self
      .endpoint
      .sync_call(Bytes::from("SyncPath"), Bytes::from(buf), 5000)
      .await;

    match response {
      | Ok(data) => {
        let resp = ZooSyncPathResponse::decode(data)?;
        if resp.ret == constants::ZOO_RET_SERVER_NOT_REG {
          warn!("Server not registered, re-registering...");
          self.register_client().await?;
          self.rebuild_paths().await?;
        }
      }
      | Err(e) => {
        warn!("Sync failed: {:?}", e);
      }
    }

    Ok(())
  }

  /// Rebuild all paths after reconnection
  async fn rebuild_paths(&self) -> Result<()> {
    let paths: Vec<(String, Bytes, i32)> = self
      .path_cache
      .iter()
      .map(|entry| {
        (
          entry.key().clone(),
          entry.value().value.clone(),
          entry.value().create_flags,
        )
      })
      .collect();

    for (path, value, flags) in paths {
      if let Err(e) = self.create_path(path.clone(), value, flags).await {
        error!("Failed to rebuild path {}: {:?}", path, e);
      }
    }

    Ok(())
  }

  /// Background sync loop (every 3 seconds, matching Java version)
  async fn sync_loop(self: Arc<Self>) {
    let mut tick = interval(Duration::from_secs(3));

    while self.running.load(Ordering::SeqCst) {
      tick.tick().await;

      if let Err(e) = self.sync_path_versions().await {
        error!("Sync error: {:?}", e);
      }
    }
  }

  /// Shutdown the client
  pub async fn shutdown(&self) {
    self.running.store(false, Ordering::SeqCst);
  }

  pub fn sessionid(&self) -> String {
    self.sessionid.read().clone()
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_path_node() {
    let node = ZooPathNode {
      path: "/test".to_string(),
      value: Bytes::from("hello"),
      version: 1,
      create_flags: 0,
    };

    assert_eq!(node.path, "/test");
    assert_eq!(node.version, 1);
  }
}