"examples/offline_inference/openai_batch/README.md" did not exist on "fc0d9dfc3afcea2e23649ef8eb8bbe0446682813"
etcd.rs 25.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Ryan Olson's avatar
Ryan Olson committed
15

16
use crate::{CancellationToken, ErrorContext, Result, Runtime, error};
Ryan Olson's avatar
Ryan Olson committed
17
18
19
20
21

use async_nats::jetstream::kv;
use derive_builder::Builder;
use derive_getters::Dissolve;
use futures::StreamExt;
22
23
use std::collections::HashMap;
use std::sync::Arc;
24
use tokio::sync::{RwLock, mpsc};
Ryan Olson's avatar
Ryan Olson committed
25
26
use validator::Validate;

27
use etcd_client::{
28
29
30
    Certificate, Compare, CompareOp, DeleteOptions, GetOptions, Identity, LockClient, LockOptions,
    LockResponse, PutOptions, PutResponse, TlsOptions, Txn, TxnOp, TxnOpResponse, WatchOptions,
    Watcher,
31
};
Ryan Olson's avatar
Ryan Olson committed
32
pub use etcd_client::{ConnectOptions, KeyValue, LeaseClient};
33
use tokio::time::{Duration, interval};
Ryan Olson's avatar
Ryan Olson committed
34
35

mod lease;
36
37
mod path;

Ryan Olson's avatar
Ryan Olson committed
38
use lease::*;
39
pub use path::*;
Ryan Olson's avatar
Ryan Olson committed
40

41
42
use super::utils::build_in_runtime;

Ryan Olson's avatar
Ryan Olson committed
43
44
45
46
47
48
49
50
//pub use etcd::ConnectOptions as EtcdConnectOptions;

/// ETCD Client
#[derive(Clone)]
pub struct Client {
    client: etcd_client::Client,
    primary_lease: i64,
    runtime: Runtime,
51
    rt: Arc<tokio::runtime::Runtime>,
Ryan Olson's avatar
Ryan Olson committed
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
}

#[derive(Debug, Clone)]
pub struct Lease {
    /// ETCD lease ID
    id: i64,

    /// [`CancellationToken`] associated with the lease
    cancel_token: CancellationToken,
}

impl Lease {
    /// Get the lease ID
    pub fn id(&self) -> i64 {
        self.id
    }

    /// Get the primary [`CancellationToken`] associated with the lease.
    /// This token will revoke the lease if canceled.
    pub fn primary_token(&self) -> CancellationToken {
        self.cancel_token.clone()
    }

    /// Get a child [`CancellationToken`] from the lease's [`CancellationToken`].
    /// This child token will be triggered if the lease is revoked, but will not revoke the lease if canceled.
    pub fn child_token(&self) -> CancellationToken {
        self.cancel_token.child_token()
    }

    /// Revoke the lease triggering the [`CancellationToken`].
    pub fn revoke(&self) {
        self.cancel_token.cancel();
    }
85
86
87
88
89
90
91

    /// Check if the lease is still valid (not revoked)
    pub async fn is_valid(&self) -> Result<bool> {
        // A lease is valid if its cancellation token has not been triggered
        // We can use try_cancelled which returns immediately with a boolean
        Ok(!self.cancel_token.is_cancelled())
    }
Ryan Olson's avatar
Ryan Olson committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
}

impl Client {
    pub fn builder() -> ClientOptionsBuilder {
        ClientOptionsBuilder::default()
    }

    /// Create a new discovery client
    ///
    /// This will establish a connection to the etcd server, create a primary lease,
    /// and spawn a task to keep the lease alive and tie the lifetime of the [`Runtime`]
    /// to the lease.
    ///
    /// If the lease expires, the [`Runtime`] will be shutdown.
    /// If the [`Runtime`] is shutdown, the lease will be revoked.
    pub async fn new(config: ClientOptions, runtime: Runtime) -> Result<Self> {
        let token = runtime.primary_token();

110
111
112
113
114
        let ((client, lease_id), rt) = build_in_runtime(
            async move {
                let client =
                    etcd_client::Client::connect(config.etcd_url, config.etcd_connect_options)
                        .await?;
115

116
117
                let lease_id = if config.attach_lease {
                    let lease_client = client.lease_client();
118

119
120
121
122
123
124
125
126
127
128
129
130
131
132
                    let lease = create_lease(lease_client, 10, token)
                        .await
                        .context("creating primary lease")?;

                    lease.id
                } else {
                    0
                };

                Ok((client, lease_id))
            },
            1,
        )
        .await?;
Ryan Olson's avatar
Ryan Olson committed
133
134
135

        Ok(Client {
            client,
136
            primary_lease: lease_id,
137
            rt,
Ryan Olson's avatar
Ryan Olson committed
138
139
140
141
142
            runtime,
        })
    }

    /// Get a reference to the underlying [`etcd_client::Client`] instance.
143
    pub(crate) fn etcd_client(&self) -> &etcd_client::Client {
Ryan Olson's avatar
Ryan Olson committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        &self.client
    }

    /// Get the primary lease ID.
    pub fn lease_id(&self) -> i64 {
        self.primary_lease
    }

    /// Primary [`Lease`]
    pub fn primary_lease(&self) -> Lease {
        Lease {
            id: self.primary_lease,
            cancel_token: self.runtime.primary_token(),
        }
    }

    /// Create a [`Lease`] with a given time-to-live (TTL).
    /// This [`Lease`] will be tied to the [`Runtime`], specifically a child [`CancellationToken`].
    pub async fn create_lease(&self, ttl: i64) -> Result<Lease> {
        let token = self.runtime.child_token();
        let lease_client = self.client.lease_client();
165
        self.rt
Ryan Olson's avatar
Ryan Olson committed
166
167
168
169
            .spawn(create_lease(lease_client, ttl, token))
            .await?
    }

170
171
172
    // Revoke an etcd lease given its lease id. A wrapper over etcd_client::LeaseClient::revoke
    pub async fn revoke_lease(&self, lease_id: i64) -> Result<()> {
        let lease_client = self.client.lease_client();
173
        self.rt.spawn(revoke_lease(lease_client, lease_id)).await?
174
175
    }

176
    pub async fn kv_create(&self, key: &str, value: Vec<u8>, lease_id: Option<i64>) -> Result<()> {
177
178
        let id = lease_id.unwrap_or(self.lease_id());
        let put_options = PutOptions::new().with_lease(id);
Ryan Olson's avatar
Ryan Olson committed
179
180
181

        // Build the transaction
        let txn = Txn::new()
182
            .when(vec![Compare::version(key, CompareOp::Equal, 0)]) // Ensure the lock does not exist
Ryan Olson's avatar
Ryan Olson committed
183
            .and_then(vec![
184
                TxnOp::put(key, value, Some(put_options)), // Create the object
Ryan Olson's avatar
Ryan Olson committed
185
186
187
            ]);

        // Execute the transaction
188
189
        let result = self.client.kv_client().txn(txn).await?;

190
191
192
193
194
195
196
        if result.succeeded() {
            Ok(())
        } else {
            for resp in result.op_responses() {
                tracing::warn!("kv_create etcd op response: {resp:?}");
            }
            Err(error!("failed to create key"))
197
198
199
200
201
202
203
204
205
206
        }
    }

    /// Atomically create a key if it does not exist, or validate the values are identical if the key exists.
    pub async fn kv_create_or_validate(
        &self,
        key: String,
        value: Vec<u8>,
        lease_id: Option<i64>,
    ) -> Result<()> {
207
208
        let id = lease_id.unwrap_or(self.lease_id());
        let put_options = PutOptions::new().with_lease(id);
209
210
211
212
213
214

        // Build the transaction that either creates the key if it doesn't exist,
        // or validates the existing value matches what we expect
        let txn = Txn::new()
            .when(vec![Compare::version(key.as_str(), CompareOp::Equal, 0)]) // Key doesn't exist
            .and_then(vec![
215
                TxnOp::put(key.as_str(), value.clone(), Some(put_options)), // Create it
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
            ])
            .or_else(vec![
                // If key exists but values don't match, this will fail the transaction
                TxnOp::txn(Txn::new().when(vec![Compare::value(
                    key.as_str(),
                    CompareOp::Equal,
                    value.clone(),
                )])),
            ]);

        // Execute the transaction
        let result = self.client.kv_client().txn(txn).await?;

        // We have to enumerate the response paths to determine if the transaction succeeded
        if result.succeeded() {
            Ok(())
        } else {
            match result.op_responses().first() {
                Some(response) => match response {
                    TxnOpResponse::Txn(response) => match response.succeeded() {
                        true => Ok(()),
                        false => Err(error!("failed to create or validate key")),
                    },
                    _ => Err(error!("unexpected response type")),
                },
                None => Err(error!("failed to create or validate key")),
            }
        }
    }

    pub async fn kv_put(
        &self,
        key: impl AsRef<str>,
        value: impl AsRef<[u8]>,
        lease_id: Option<i64>,
    ) -> Result<()> {
252
253
        let id = lease_id.unwrap_or(self.lease_id());
        let put_options = PutOptions::new().with_lease(id);
254
255
256
        let _ = self
            .client
            .kv_client()
257
            .put(key.as_ref(), value.as_ref(), Some(put_options))
258
            .await?;
Ryan Olson's avatar
Ryan Olson committed
259
260
261
        Ok(())
    }

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
    pub async fn kv_put_with_options(
        &self,
        key: impl AsRef<str>,
        value: impl AsRef<[u8]>,
        options: Option<PutOptions>,
    ) -> Result<PutResponse> {
        let options = options
            .unwrap_or_default()
            .with_lease(self.primary_lease().id());
        self.client
            .kv_client()
            .put(key.as_ref(), value.as_ref(), Some(options))
            .await
            .map_err(|err| err.into())
    }

    pub async fn kv_get(
        &self,
        key: impl Into<Vec<u8>>,
        options: Option<GetOptions>,
    ) -> Result<Vec<KeyValue>> {
        let mut get_response = self.client.kv_client().get(key, options).await?;
        Ok(get_response.take_kvs())
    }

    pub async fn kv_delete(
        &self,
        key: impl Into<Vec<u8>>,
        options: Option<DeleteOptions>,
    ) -> Result<i64> {
        self.client
            .kv_client()
            .delete(key, options)
            .await
            .map(|del_response| del_response.deleted())
            .map_err(|err| err.into())
    }

Ryan Olson's avatar
Ryan Olson committed
300
301
302
303
304
305
306
307
308
309
    pub async fn kv_get_prefix(&self, prefix: impl AsRef<str>) -> Result<Vec<KeyValue>> {
        let mut get_response = self
            .client
            .kv_client()
            .get(prefix.as_ref(), Some(GetOptions::new().with_prefix()))
            .await?;

        Ok(get_response.take_kvs())
    }

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
    /// Acquire a distributed lock using etcd's native lock mechanism
    /// Returns a LockResponse that can be used to unlock later
    pub async fn lock(
        &self,
        key: impl Into<Vec<u8>>,
        lease_id: Option<i64>,
    ) -> Result<LockResponse> {
        let mut lock_client = self.client.lock_client();
        let id = lease_id.unwrap_or(self.lease_id());
        let options = LockOptions::new().with_lease(id);
        lock_client
            .lock(key, Some(options))
            .await
            .map_err(|err| err.into())
    }

    /// Release a distributed lock using the key from the LockResponse
    pub async fn unlock(&self, lock_key: impl Into<Vec<u8>>) -> Result<()> {
        let mut lock_client = self.client.lock_client();
        lock_client
            .unlock(lock_key)
            .await
            .map_err(|err: etcd_client::Error| anyhow::anyhow!(err))?;
        Ok(())
    }

336
337
338
339
    pub async fn kv_get_and_watch_prefix(
        &self,
        prefix: impl AsRef<str> + std::fmt::Display,
    ) -> Result<PrefixWatcher> {
Ryan Olson's avatar
Ryan Olson committed
340
341
342
343
344
345
346
347
348
349
350
351
        let mut kv_client = self.client.kv_client();
        let mut watch_client = self.client.watch_client();

        let mut get_response = kv_client
            .get(prefix.as_ref(), Some(GetOptions::new().with_prefix()))
            .await?;

        let start_revision = get_response
            .header()
            .ok_or(error!("missing header; unable to get revision"))?
            .revision();

352
        tracing::trace!("{prefix}: start_revision: {start_revision}");
Ryan Olson's avatar
Ryan Olson committed
353
354
        let start_revision = start_revision + 1;

Ryan Olson's avatar
Ryan Olson committed
355
356
357
358
359
360
        let (watcher, mut watch_stream) = watch_client
            .watch(
                prefix.as_ref(),
                Some(
                    WatchOptions::new()
                        .with_prefix()
361
362
                        .with_start_revision(start_revision)
                        .with_prev_key(),
Ryan Olson's avatar
Ryan Olson committed
363
364
365
366
367
                ),
            )
            .await?;

        let kvs = get_response.take_kvs();
368
        tracing::trace!("initial kv count: {:?}", kvs.len());
Ryan Olson's avatar
Ryan Olson committed
369
370
371

        let (tx, rx) = mpsc::channel(32);

372
        self.rt.spawn(async move {
Ryan Olson's avatar
Ryan Olson committed
373
374
            for kv in kvs {
                if tx.send(WatchEvent::Put(kv)).await.is_err() {
375
376
                    // receiver is already closed
                    return;
Ryan Olson's avatar
Ryan Olson committed
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
            loop {
                tokio::select! {
                    maybe_resp = watch_stream.next() => {
                        // Early return for None or Err cases
                        let Some(Ok(response)) = maybe_resp else {
                            tracing::info!("kv watch stream closed");
                            return;
                        };

                        // Process events
                        for event in response.events() {
                            // Extract the KeyValue if it exists
                            let Some(kv) = event.kv() else {
                                continue; // Skip events with no KV
                            };

                            // Handle based on event type
                            match event.event_type() {
                                etcd_client::EventType::Put => {
                                    if let Err(err) = tx.send(WatchEvent::Put(kv.clone())).await {
                                        tracing::error!("kv watcher error forwarding WatchEvent::Put: {err}");
                                        return;
                                    }
403
                                }
404
405
406
407
                                etcd_client::EventType::Delete => {
                                    if tx.send(WatchEvent::Delete(kv.clone())).await.is_err() {
                                        return;
                                    }
Ryan Olson's avatar
Ryan Olson committed
408
409
410
411
                                }
                            }
                        }
                    }
412
413
414
415
                    _ = tx.closed() => {
                        tracing::debug!("no more receivers, stopping watcher");
                        return;
                    }
Ryan Olson's avatar
Ryan Olson committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
                }
            }
        });
        Ok(PrefixWatcher {
            prefix: prefix.as_ref().to_string(),
            watcher,
            rx,
        })
    }
}

#[derive(Dissolve)]
pub struct PrefixWatcher {
    prefix: String,
    watcher: Watcher,
    rx: mpsc::Receiver<WatchEvent>,
}

434
#[derive(Debug)]
Ryan Olson's avatar
Ryan Olson committed
435
436
437
438
439
440
441
442
443
pub enum WatchEvent {
    Put(KeyValue),
    Delete(KeyValue),
}

/// ETCD client configuration options
#[derive(Debug, Clone, Builder, Validate)]
pub struct ClientOptions {
    #[validate(length(min = 1))]
Ryan Olson's avatar
Ryan Olson committed
444
    pub etcd_url: Vec<String>,
Ryan Olson's avatar
Ryan Olson committed
445
446

    #[builder(default)]
Ryan Olson's avatar
Ryan Olson committed
447
    pub etcd_connect_options: Option<ConnectOptions>,
448
449
450

    /// If true, the client will attach a lease to the primary [`CancellationToken`].
    #[builder(default = "true")]
Ryan Olson's avatar
Ryan Olson committed
451
    pub attach_lease: bool,
Ryan Olson's avatar
Ryan Olson committed
452
453
454
455
}

impl Default for ClientOptions {
    fn default() -> Self {
wxsm's avatar
wxsm committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
        let mut connect_options = None;

        if let (Ok(username), Ok(password)) = (
            std::env::var("ETCD_AUTH_USERNAME"),
            std::env::var("ETCD_AUTH_PASSWORD"),
        ) {
            // username and password are set
            connect_options = Some(ConnectOptions::new().with_user(username, password));
        } else if let (Ok(ca), Ok(cert), Ok(key)) = (
            std::env::var("ETCD_AUTH_CA"),
            std::env::var("ETCD_AUTH_CLIENT_CERT"),
            std::env::var("ETCD_AUTH_CLIENT_KEY"),
        ) {
            // TLS is set
            connect_options = Some(
                ConnectOptions::new().with_tls(
                    TlsOptions::new()
                        .ca_certificate(Certificate::from_pem(ca))
                        .identity(Identity::from_pem(cert, key)),
                ),
            );
        }

Ryan Olson's avatar
Ryan Olson committed
479
480
        ClientOptions {
            etcd_url: default_servers(),
wxsm's avatar
wxsm committed
481
            etcd_connect_options: connect_options,
482
            attach_lease: true,
Ryan Olson's avatar
Ryan Olson committed
483
484
485
486
487
488
489
490
491
492
493
494
495
        }
    }
}

fn default_servers() -> Vec<String> {
    match std::env::var("ETCD_ENDPOINTS") {
        Ok(possible_list_of_urls) => possible_list_of_urls
            .split(',')
            .map(|s| s.to_string())
            .collect(),
        Err(_) => vec!["http://localhost:2379".to_string()],
    }
}
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
/// A cache for etcd key-value pairs that watches for changes
pub struct KvCache {
    client: Client,
    pub prefix: String,
    cache: Arc<RwLock<HashMap<String, Vec<u8>>>>,
    watcher: Option<PrefixWatcher>,
}

impl KvCache {
    /// Create a new KV cache for the given prefix
    pub async fn new(
        client: Client,
        prefix: String,
        initial_values: HashMap<String, Vec<u8>>,
    ) -> Result<Self> {
        let mut cache = HashMap::new();

        // First get all existing keys with this prefix
        let existing_kvs = client.kv_get_prefix(&prefix).await?;
        for kv in existing_kvs {
            let key = String::from_utf8_lossy(kv.key()).to_string();
            cache.insert(key, kv.value().to_vec());
        }

        // For any keys in initial_values that don't exist in etcd, write them
        // TODO: proper lease handling, this requires the first process that write to a prefix atomically
        // create a lease and write the lease to etcd. Later processes will attach to the lease and
        // help refresh the lease.
        for (key, value) in initial_values.iter() {
            let full_key = format!("{}{}", prefix, key);
            if let std::collections::hash_map::Entry::Vacant(e) = cache.entry(full_key.clone()) {
                client.kv_put(&full_key, value.clone(), None).await?;
                e.insert(value.clone());
            }
        }

        // Start watching for changes
        // we won't miss events bewteen the initial push and the watcher starting because
        // client.kv_get_and_watch_prefix() will get all kv pairs and put them back again
        let watcher = client.kv_get_and_watch_prefix(&prefix).await?;

        let cache = Arc::new(RwLock::new(cache));
        let mut result = Self {
            client,
            prefix,
            cache,
            watcher: Some(watcher),
        };

        // Start the background watcher task
        result.start_watcher().await?;

        Ok(result)
    }

    /// Start the background watcher task
    async fn start_watcher(&mut self) -> Result<()> {
        if let Some(watcher) = self.watcher.take() {
            let cache = self.cache.clone();
            let prefix = self.prefix.clone();

            tokio::spawn(async move {
                let mut rx = watcher.rx;

                while let Some(event) = rx.recv().await {
                    match event {
                        WatchEvent::Put(kv) => {
                            let key = String::from_utf8_lossy(kv.key()).to_string();
                            let value = kv.value().to_vec();

                            tracing::debug!("KvCache update: {} = {:?}", key, value);
                            let mut cache_write = cache.write().await;
                            cache_write.insert(key, value);
                        }
                        WatchEvent::Delete(kv) => {
                            let key = String::from_utf8_lossy(kv.key()).to_string();

                            tracing::debug!("KvCache delete: {}", key);
                            let mut cache_write = cache.write().await;
                            cache_write.remove(&key);
                        }
                    }
                }

                tracing::info!("KvCache watcher for prefix '{}' stopped", prefix);
            });
        }

        Ok(())
    }

    /// Get a value from the cache
    pub async fn get(&self, key: &str) -> Option<Vec<u8>> {
        let full_key = format!("{}{}", self.prefix, key);
        let cache_read = self.cache.read().await;
        cache_read.get(&full_key).cloned()
    }

    /// Get all key-value pairs in the cache
    pub async fn get_all(&self) -> HashMap<String, Vec<u8>> {
        let cache_read = self.cache.read().await;
        cache_read.clone()
    }

    /// Update a value in both the cache and etcd
    pub async fn put(&self, key: &str, value: Vec<u8>, lease_id: Option<i64>) -> Result<()> {
        let full_key = format!("{}{}", self.prefix, key);

        // Update etcd first
        self.client
            .kv_put(&full_key, value.clone(), lease_id)
            .await?;

        // Then update local cache
        let mut cache_write = self.cache.write().await;
        cache_write.insert(full_key, value);

        Ok(())
    }

617
618
619
620
621
622
623
624
625
626
627
628
629
    /// Delete a key from both the cache and etcd
    pub async fn delete(&self, key: &str) -> Result<()> {
        let full_key = format!("{}{}", self.prefix, key);

        // Delete from etcd first
        self.client.kv_delete(full_key.clone(), None).await?;

        // Then remove from local cache
        let mut cache_write = self.cache.write().await;
        cache_write.remove(&full_key);

        Ok(())
    }
630
631
}

632
633
634
#[cfg(feature = "integration")]
#[cfg(test)]
mod tests {
635
    use crate::{DistributedRuntime, distributed::DistributedConfig};
636
637
638
639
640
641
642

    use super::*;

    #[test]
    fn test_ectd_client() {
        let rt = Runtime::from_settings().unwrap();
        let rt_clone = rt.clone();
643
        let config = DistributedConfig::from_settings(false);
644
645
646
647
648
649
650
651
652
653
654

        rt_clone.primary().block_on(async move {
            let drt = DistributedRuntime::new(rt, config).await.unwrap();
            test_kv_create_or_validate(drt).await.unwrap();
        });
    }

    async fn test_kv_create_or_validate(drt: DistributedRuntime) -> Result<()> {
        let key = "__integration_test_key";
        let value = b"test_value";

655
656
657
658
659
        let client = drt.etcd_client().expect("etcd client should be available");
        let lease_id = drt
            .primary_lease()
            .expect("primary lease should be available")
            .id();
660
661

        // Create the key
662
        let result = client.kv_create(key, value.to_vec(), Some(lease_id)).await;
663
664
665
        assert!(result.is_ok(), "");

        // Try to create the key again - this should fail
666
        let result = client.kv_create(key, value.to_vec(), Some(lease_id)).await;
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        assert!(result.is_err());

        // Create or validate should succeed as the values match
        let result = client
            .kv_create_or_validate(key.to_string(), value.to_vec(), Some(lease_id))
            .await;
        assert!(result.is_ok());

        // Try to create the key with a different value
        let different_value = b"different_value";
        let result = client
            .kv_create_or_validate(key.to_string(), different_value.to_vec(), Some(lease_id))
            .await;
        assert!(result.is_err(), "");

        Ok(())
    }
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781

    #[test]
    fn test_kv_cache() {
        let rt = Runtime::from_settings().unwrap();
        let rt_clone = rt.clone();
        let config = DistributedConfig::from_settings(false);

        rt_clone.primary().block_on(async move {
            let drt = DistributedRuntime::new(rt, config).await.unwrap();
            test_kv_cache_operations(drt).await.unwrap();
        });
    }

    async fn test_kv_cache_operations(drt: DistributedRuntime) -> Result<()> {
        // Get the client and unwrap it
        let client = drt.etcd_client().expect("etcd client should be available");

        // Create a unique test prefix to avoid conflicts with other tests
        let test_id = uuid::Uuid::new_v4().to_string();
        let prefix = format!("test_kv_cache_{}/", test_id);

        // Initial values
        let mut initial_values = HashMap::new();
        initial_values.insert("key1".to_string(), b"value1".to_vec());
        initial_values.insert("key2".to_string(), b"value2".to_vec());

        // Create the KV cache
        let kv_cache = KvCache::new(client.clone(), prefix.clone(), initial_values).await?;

        // Test get
        let value1 = kv_cache.get("key1").await;
        assert_eq!(value1, Some(b"value1".to_vec()));

        let value2 = kv_cache.get("key2").await;
        assert_eq!(value2, Some(b"value2".to_vec()));

        // Test get_all
        let all_values = kv_cache.get_all().await;
        assert_eq!(all_values.len(), 2);
        assert_eq!(
            all_values.get(&format!("{}key1", prefix)),
            Some(&b"value1".to_vec())
        );
        assert_eq!(
            all_values.get(&format!("{}key2", prefix)),
            Some(&b"value2".to_vec())
        );

        // Test put - using None for lease_id
        kv_cache.put("key3", b"value3".to_vec(), None).await?;

        // Allow some time for the update to propagate
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Verify the new value
        let value3 = kv_cache.get("key3").await;
        assert_eq!(value3, Some(b"value3".to_vec()));

        // Test update
        kv_cache
            .put("key1", b"updated_value1".to_vec(), None)
            .await?;

        // Allow some time for the update to propagate
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Verify the updated value
        let updated_value1 = kv_cache.get("key1").await;
        assert_eq!(updated_value1, Some(b"updated_value1".to_vec()));

        // Test external update (simulating another client updating a value)
        client
            .kv_put(
                &format!("{}key2", prefix),
                b"external_update".to_vec(),
                None,
            )
            .await?;

        // Allow some time for the update to propagate
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Verify the cache was updated
        let external_update = kv_cache.get("key2").await;
        assert_eq!(external_update, Some(b"external_update".to_vec()));

        // Clean up - delete the test keys
        let etcd_client = client.etcd_client();
        let _ = etcd_client
            .kv_client()
            .delete(
                prefix,
                Some(etcd_client::DeleteOptions::new().with_prefix()),
            )
            .await?;

        Ok(())
    }
782
}