etcd.rs 31.7 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3

4
5
use crate::runtime::Runtime;
use anyhow::{Context, Result};
Ryan Olson's avatar
Ryan Olson committed
6
7
8
9
10

use async_nats::jetstream::kv;
use derive_builder::Builder;
use derive_getters::Dissolve;
use futures::StreamExt;
11
12
use std::collections::HashMap;
use std::sync::Arc;
13
use tokio::sync::{RwLock, mpsc};
Ryan Olson's avatar
Ryan Olson committed
14
15
use validator::Validate;

16
use etcd_client::{
17
18
    Certificate, Compare, CompareOp, DeleteOptions, GetOptions, Identity, LockClient, LockOptions,
    LockResponse, PutOptions, PutResponse, TlsOptions, Txn, TxnOp, TxnOpResponse, WatchOptions,
19
    WatchStream, Watcher,
20
};
Ryan Olson's avatar
Ryan Olson committed
21
pub use etcd_client::{ConnectOptions, KeyValue, LeaseClient};
22
use tokio::time::{Duration, interval};
23
use tokio_util::sync::CancellationToken;
Ryan Olson's avatar
Ryan Olson committed
24

25
mod connector;
Ryan Olson's avatar
Ryan Olson committed
26
mod lease;
27
mod lock;
28

29
use connector::Connector;
Ryan Olson's avatar
Ryan Olson committed
30
use lease::*;
31
pub use lock::*;
Ryan Olson's avatar
Ryan Olson committed
32

33
use super::utils::build_in_runtime;
34
use crate::config::environment_names::etcd as env_etcd;
35

36
37
38
39
40
41
/// ETCD Client
#[derive(Clone)]
pub struct Client {
    connector: Arc<Connector>,
    primary_lease: u64,
    runtime: Runtime,
42
43
44
    // Exclusive runtime for etcd lease keep-alive and watch tasks
    // Avoid those tasks from being starved when the main runtime is busy
    // WARNING: Do not await on main runtime from this runtime or deadlocks may occur
45
46
47
48
49
50
51
52
53
    rt: Arc<tokio::runtime::Runtime>,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "etcd::Client primary_lease={}", self.primary_lease)
    }
}

Ryan Olson's avatar
Ryan Olson committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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();

70
        let ((connector, lease_id), rt) = build_in_runtime(
71
            async move {
72
73
74
75
76
77
78
79
80
81
82
83
                let etcd_urls = config.etcd_url.clone();
                let connect_options = config.etcd_connect_options.clone();

                // Create the connector
                let connector = Connector::new(etcd_urls, connect_options)
                    .await
                    .with_context(|| {
                        format!(
                            "Unable to connect to etcd server at {}. Check etcd server status",
                            config.etcd_url.join(", ")
                        )
                    })?;
84

85
                let lease_id = if config.attach_lease {
86
                    create_lease(connector.clone(), 10, token)
87
                        .await
88
89
90
91
92
                        .with_context(|| {
                            format!(
                                "Unable to create lease. Check etcd server status at {}",
                                config.etcd_url.join(", ")
                            )
93
                        })?
94
95
96
97
                } else {
                    0
                };

98
                Ok((connector, lease_id))
99
100
101
102
            },
            1,
        )
        .await?;
Ryan Olson's avatar
Ryan Olson committed
103
104

        Ok(Client {
105
            connector,
106
            primary_lease: lease_id,
107
            rt,
Ryan Olson's avatar
Ryan Olson committed
108
109
110
111
            runtime,
        })
    }

112
113
    /// Get a clone of the underlying [`etcd_client::Client`] instance.
    /// This returns a clone since the client is behind an RwLock.
114
    fn etcd_client(&self) -> etcd_client::Client {
115
        self.connector.get_client()
Ryan Olson's avatar
Ryan Olson committed
116
117
118
    }

    /// Get the primary lease ID.
119
    pub fn lease_id(&self) -> u64 {
Ryan Olson's avatar
Ryan Olson committed
120
121
122
        self.primary_lease
    }

123
124
125
126
127
128
129
130
131
132
133
    /// Atomically create a key-value pair if it doesn't already exist.
    ///
    /// Returns:
    /// - `Ok(None)` if the key was successfully created
    /// - `Ok(Some(version))` if the key already exists (returns the existing version)
    /// - `Err(...)` only on actual errors (connection failure, timeout, etc.)
    ///
    /// This idempotent behavior was introduced in PR #4212 (Nov 10, 2025) to align with
    /// the StoreOutcome pattern used in KeyValueStore implementations, where both
    /// Created and Exists are successful outcomes rather than errors. This design supports
    /// distributed systems where multiple processes might attempt to create the same key.
134
135
136
137
138
139
    pub async fn kv_create(
        &self,
        key: &str,
        value: Vec<u8>,
        lease_id: Option<u64>,
    ) -> Result<Option<u64>> {
140
        let id = lease_id.unwrap_or(self.lease_id());
141
        let put_options = PutOptions::new().with_lease(id as i64);
Ryan Olson's avatar
Ryan Olson committed
142

143
        // Build transaction that creates key only if it doesn't exist
Ryan Olson's avatar
Ryan Olson committed
144
        let txn = Txn::new()
145
            .when(vec![Compare::version(key, CompareOp::Equal, 0)]) // Ensure the lock does not exist
Ryan Olson's avatar
Ryan Olson committed
146
            .and_then(vec![
147
                TxnOp::put(key, value, Some(put_options)), // Create the object
148
149
150
            ])
            .or_else(vec![
                TxnOp::get(key, None), // Key exists, get its info
Ryan Olson's avatar
Ryan Olson committed
151
152
153
            ]);

        // Execute the transaction
154
        let result = self.connector.get_client().kv_client().txn(txn).await?;
155

156
        // Created
157
        if result.succeeded() {
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
            return Ok(None);
        }

        // Already exists
        if let Some(etcd_client::TxnOpResponse::Get(get_resp)) =
            result.op_responses().into_iter().next()
            && let Some(kv) = get_resp.kvs().first()
        {
            let version = kv.version() as u64;
            return Ok(Some(version));
        }

        // Error
        for resp in result.op_responses() {
            tracing::warn!(response = ?resp, "kv_create etcd op response");
173
        }
174
        anyhow::bail!("Unable to create key. Check etcd server status")
175
176
177
178
179
180
181
    }

    /// 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>,
182
        lease_id: Option<u64>,
183
    ) -> Result<()> {
184
        let id = lease_id.unwrap_or(self.lease_id());
185
        let put_options = PutOptions::new().with_lease(id as i64);
186
187
188
189
190
191

        // 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![
192
                TxnOp::put(key.as_str(), value.clone(), Some(put_options)), // Create it
193
194
195
196
197
198
199
200
201
202
203
            ])
            .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
204
        let result = self.connector.get_client().kv_client().txn(txn).await?;
205
206
207
208
209
210
211
212
213

        // 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(()),
214
                        false => anyhow::bail!(
215
                            "Unable to create or validate key. Check etcd server status"
216
                        ),
217
                    },
218
219
220
                    _ => {
                        anyhow::bail!("Unable to validate key operation. Check etcd server status")
                    }
221
                },
222
                None => anyhow::bail!("Unable to create or validate key. Check etcd server status"),
223
224
225
226
227
228
229
230
            }
        }
    }

    pub async fn kv_put(
        &self,
        key: impl AsRef<str>,
        value: impl AsRef<[u8]>,
231
        lease_id: Option<u64>,
232
    ) -> Result<()> {
233
        let id = lease_id.unwrap_or(self.lease_id());
234
        let put_options = PutOptions::new().with_lease(id as i64);
235
        let _ = self
236
237
            .connector
            .get_client()
238
            .kv_client()
239
            .put(key.as_ref(), value.as_ref(), Some(put_options))
240
            .await?;
Ryan Olson's avatar
Ryan Olson committed
241
242
243
        Ok(())
    }

244
245
246
247
248
249
250
251
    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()
252
            .with_lease(self.lease_id() as i64);
253
254
        self.connector
            .get_client()
255
256
257
258
259
260
261
262
263
264
265
            .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>> {
266
267
268
269
270
271
        let mut get_response = self
            .connector
            .get_client()
            .kv_client()
            .get(key, options)
            .await?;
272
273
274
275
276
277
278
        Ok(get_response.take_kvs())
    }

    pub async fn kv_delete(
        &self,
        key: impl Into<Vec<u8>>,
        options: Option<DeleteOptions>,
279
    ) -> Result<u64> {
280
281
        self.connector
            .get_client()
282
283
284
            .kv_client()
            .delete(key, options)
            .await
285
            .map(|del_response| del_response.deleted() as u64)
286
287
288
            .map_err(|err| err.into())
    }

Ryan Olson's avatar
Ryan Olson committed
289
290
    pub async fn kv_get_prefix(&self, prefix: impl AsRef<str>) -> Result<Vec<KeyValue>> {
        let mut get_response = self
291
292
            .connector
            .get_client()
Ryan Olson's avatar
Ryan Olson committed
293
294
295
296
297
298
299
            .kv_client()
            .get(prefix.as_ref(), Some(GetOptions::new().with_prefix()))
            .await?;

        Ok(get_response.take_kvs())
    }

300
301
302
303
304
    /// 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>>,
305
        lease_id: Option<u64>,
306
    ) -> Result<LockResponse> {
307
        let mut lock_client = self.connector.get_client().lock_client();
308
        let id = lease_id.unwrap_or(self.lease_id());
309
        let options = LockOptions::new().with_lease(id as i64);
310
311
312
313
314
315
316
317
        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<()> {
318
        let mut lock_client = self.connector.get_client().lock_client();
319
320
321
322
323
324
325
        lock_client
            .unlock(lock_key)
            .await
            .map_err(|err: etcd_client::Error| anyhow::anyhow!(err))?;
        Ok(())
    }

326
327
328
329
330
331
332
333
    /// Like kv_get_and_watch_prefix but only for new changes, does not include existing values.
    pub async fn kv_watch_prefix(
        &self,
        prefix: impl AsRef<str> + std::fmt::Display,
    ) -> Result<PrefixWatcher> {
        self.watch_internal(prefix, false).await
    }

334
335
336
    pub async fn kv_get_and_watch_prefix(
        &self,
        prefix: impl AsRef<str> + std::fmt::Display,
337
338
339
340
    ) -> Result<PrefixWatcher> {
        self.watch_internal(prefix, true).await
    }

341
342
343
344
345
    /// Core watch implementation that sets up a resilient watcher for a key prefix.
    ///
    /// Creates a background task that maintains a watch stream with automatic reconnection
    /// on recoverable errors. If `include_existing` is true, existing keys are included
    /// in the initial watch events.
346
347
348
349
    async fn watch_internal(
        &self,
        prefix: impl AsRef<str> + std::fmt::Display,
        include_existing: bool,
350
    ) -> Result<PrefixWatcher> {
351
352
        let (mut start_revision, existing_kvs) = self
            .get_start_revision(prefix.as_ref(), include_existing)
353
354
            .await?;

355
356
357
358
359
360
361
362
363
364
365
366
367
        // Size channel to fit all existing KVs (avoids deadlock when sending before return)
        let existing_count = existing_kvs.as_ref().map_or(0, |kvs| kvs.len());
        let (tx, rx) = mpsc::channel(existing_count + 32);

        // Send existing KVs before returning so they're immediately available to consumers
        if let Some(kvs) = existing_kvs {
            tracing::trace!("sending {} existing kvs", kvs.len());
            for kv in kvs {
                tx.send(WatchEvent::Put(kv)).await?;
            }
        }

        // Watch for new events in background
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        let connector = self.connector.clone();
        let prefix_str = prefix.as_ref().to_string();
        self.rt.spawn(async move {
            let mut reconnect = true;
            while reconnect {
                // Start a new watch stream
                let watch_stream =
                    match Self::new_watch_stream(&connector, &prefix_str, start_revision).await {
                        Ok(stream) => stream,
                        Err(_) => return,
                    };

                // Watch the stream
                reconnect =
                    Self::monitor_watch_stream(watch_stream, &prefix_str, &mut start_revision, &tx)
                        .await;
            }
        });
Ryan Olson's avatar
Ryan Olson committed
386

387
388
389
390
391
392
        Ok(PrefixWatcher {
            prefix: prefix.as_ref().to_string(),
            rx,
        })
    }

393
    /// Fetch the start revision and optionally return existing key-values.
394
395
396
    async fn get_start_revision(
        &self,
        prefix: impl AsRef<str> + std::fmt::Display,
397
398
        include_existing: bool,
    ) -> Result<(i64, Option<Vec<KeyValue>>)> {
399
        let mut kv_client = self.connector.get_client().kv_client();
Ryan Olson's avatar
Ryan Olson committed
400
401
402
403
        let mut get_response = kv_client
            .get(prefix.as_ref(), Some(GetOptions::new().with_prefix()))
            .await?;

404
405
        // Get the start revision
        let mut start_revision = get_response
Ryan Olson's avatar
Ryan Olson committed
406
            .header()
407
            .ok_or(anyhow::anyhow!("missing header; unable to get revision"))?
Ryan Olson's avatar
Ryan Olson committed
408
            .revision();
409
        tracing::trace!("{prefix}: start_revision: {start_revision}");
410
        start_revision += 1;
Ryan Olson's avatar
Ryan Olson committed
411

412
413
        // Return existing KVs if requested
        let existing_kvs = include_existing.then(|| {
414
415
            let kvs = get_response.take_kvs();
            tracing::trace!("initial kv count: {:?}", kvs.len());
416
417
            kvs
        });
Ryan Olson's avatar
Ryan Olson committed
418

419
        Ok((start_revision, existing_kvs))
420
    }
Ryan Olson's avatar
Ryan Olson committed
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
    /// Establish a new watch stream with automatic retry and reconnection.
    ///
    /// Attempts to create a watch stream, reconnecting to ETCD if necessary.
    /// Uses a 10-second timeout for reconnection attempts before giving up.
    async fn new_watch_stream(
        connector: &Arc<Connector>,
        prefix: &String,
        start_revision: i64,
    ) -> Result<WatchStream> {
        loop {
            match connector
                .get_client()
                .watch_client()
                .watch(
                    prefix.as_str(),
                    Some(
                        WatchOptions::new()
                            .with_prefix()
                            .with_start_revision(start_revision)
                            .with_prev_key(),
                    ),
                )
                .await
            {
                Ok((_, watch_stream)) => {
447
                    tracing::debug!("Watch stream established for prefix '{prefix}'");
448
449
450
451
452
453
454
455
456
457
458
459
                    return Ok(watch_stream);
                }
                Err(err) => {
                    tracing::debug!(error = %err, "Failed to establish watch stream for prefix '{}'", prefix);
                    let deadline = std::time::Instant::now() + Duration::from_secs(10);
                    if let Err(err) = connector.reconnect(deadline).await {
                        tracing::error!(
                            "Failed to reconnect to ETCD within 10 secs for watching prefix '{}': {}",
                            prefix,
                            err
                        );
                        return Err(err);
460
                    }
461
                    // continue - retry establishing the watch stream
Ryan Olson's avatar
Ryan Olson committed
462
463
                }
            }
464
465
        }
    }
Ryan Olson's avatar
Ryan Olson committed
466

467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    /// Monitor a watch stream and forward events to receivers.
    ///
    /// Returns `true` for recoverable errors (network issues, stream closure) that warrant
    /// reconnection attempts. Returns `false` for permanent failures (protocol violations,
    /// channel errors, no receivers) where watching should stop.
    async fn monitor_watch_stream(
        mut watch_stream: WatchStream,
        prefix: &String,
        start_revision: &mut i64,
        tx: &mpsc::Sender<WatchEvent>,
    ) -> bool {
        loop {
            tokio::select! {
                maybe_resp = watch_stream.next() => {
                    // Handle the watch response
                    let response = match maybe_resp {
                        Some(Ok(res)) => res,
                        Some(Err(err)) => {
                            tracing::warn!(error = %err, "Error watching stream for prefix '{}'", prefix);
                            return true; // Exit to reconnect
                        }
                        None => {
489
                            tracing::warn!("Watch stream unexpectedly closed for prefix '{prefix}'");
490
                            return true; // Exit to reconnect
Ryan Olson's avatar
Ryan Olson committed
491
                        }
492
493
494
495
496
497
                    };

                    // Update revision for reconnect
                    *start_revision = match response.header() {
                        Some(header) => header.revision() + 1,
                        None => {
498
                            tracing::error!("Missing header in watch response for prefix '{prefix}'");
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
                            return false;
                        }
                    };

                    // Process events
                    if Self::process_watch_events(response.events(), tx).await.is_err() {
                        return false;
                    };
                }
                _ = tx.closed() => {
                    tracing::debug!("no more receivers, stopping watcher");
                    return false;
                }
            }
        }
    }

    /// Process etcd events and forward them as Put/Delete watch events.
    ///
    /// Filters out events without key-values and transforms etcd events into
    /// appropriate WatchEvent types for channel transmission.
    async fn process_watch_events(
        events: &[etcd_client::Event],
        tx: &mpsc::Sender<WatchEvent>,
    ) -> Result<()> {
        for event in 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 Err(err.into());
Ryan Olson's avatar
Ryan Olson committed
536
                    }
537
538
539
540
                }
                etcd_client::EventType::Delete => {
                    if tx.send(WatchEvent::Delete(kv.clone())).await.is_err() {
                        return Err(anyhow::anyhow!("failed to send WatchEvent::Delete"));
541
                    }
Ryan Olson's avatar
Ryan Olson committed
542
543
                }
            }
544
545
        }
        Ok(())
Ryan Olson's avatar
Ryan Olson committed
546
547
548
549
550
551
552
553
554
    }
}

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

555
#[derive(Debug)]
Ryan Olson's avatar
Ryan Olson committed
556
557
558
559
560
561
562
563
564
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
565
    pub etcd_url: Vec<String>,
Ryan Olson's avatar
Ryan Olson committed
566
567

    #[builder(default)]
Ryan Olson's avatar
Ryan Olson committed
568
    pub etcd_connect_options: Option<ConnectOptions>,
569
570
571

    /// If true, the client will attach a lease to the primary [`CancellationToken`].
    #[builder(default = "true")]
Ryan Olson's avatar
Ryan Olson committed
572
    pub attach_lease: bool,
Ryan Olson's avatar
Ryan Olson committed
573
574
575
576
}

impl Default for ClientOptions {
    fn default() -> Self {
wxsm's avatar
wxsm committed
577
578
579
        let mut connect_options = None;

        if let (Ok(username), Ok(password)) = (
580
581
            std::env::var(env_etcd::auth::ETCD_AUTH_USERNAME),
            std::env::var(env_etcd::auth::ETCD_AUTH_PASSWORD),
wxsm's avatar
wxsm committed
582
583
584
585
        ) {
            // username and password are set
            connect_options = Some(ConnectOptions::new().with_user(username, password));
        } else if let (Ok(ca), Ok(cert), Ok(key)) = (
586
587
588
            std::env::var(env_etcd::auth::ETCD_AUTH_CA),
            std::env::var(env_etcd::auth::ETCD_AUTH_CLIENT_CERT),
            std::env::var(env_etcd::auth::ETCD_AUTH_CLIENT_KEY),
wxsm's avatar
wxsm committed
589
590
591
592
593
594
595
596
597
598
599
        ) {
            // 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
600
601
        ClientOptions {
            etcd_url: default_servers(),
wxsm's avatar
wxsm committed
602
            etcd_connect_options: connect_options,
603
            attach_lease: true,
Ryan Olson's avatar
Ryan Olson committed
604
605
606
607
608
        }
    }
}

fn default_servers() -> Vec<String> {
609
    match std::env::var(env_etcd::ETCD_ENDPOINTS) {
Ryan Olson's avatar
Ryan Olson committed
610
611
612
613
614
615
616
        Ok(possible_list_of_urls) => possible_list_of_urls
            .split(',')
            .map(|s| s.to_string())
            .collect(),
        Err(_) => vec!["http://localhost:2379".to_string()],
    }
}
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
651
652
653
654
/// 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
655
        // we won't miss events between the initial push and the watcher starting because
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
        // 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();

688
                            tracing::trace!("KvCache update: {} = {:?}", key, value);
689
690
691
692
693
694
                            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();

695
                            tracing::trace!("KvCache delete: {key}");
696
697
698
699
700
701
                            let mut cache_write = cache.write().await;
                            cache_write.remove(&key);
                        }
                    }
                }

702
                tracing::debug!("KvCache watcher for prefix '{prefix}' stopped");
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
            });
        }

        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
723
    pub async fn put(&self, key: &str, value: Vec<u8>, lease_id: Option<u64>) -> Result<()> {
724
725
726
727
728
729
730
731
732
733
734
735
736
737
        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(())
    }

738
739
740
741
742
743
744
745
746
747
748
749
750
    /// 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(())
    }
751
752
}

753
754
755
#[cfg(feature = "integration")]
#[cfg(test)]
mod tests {
756
    use crate::{DistributedRuntime, distributed::DistributedConfig};
757
758
759
760
761
762
763

    use super::*;

    #[test]
    fn test_ectd_client() {
        let rt = Runtime::from_settings().unwrap();
        let rt_clone = rt.clone();
764
        let config = DistributedConfig::from_settings();
765
766
767
768
769
770
771
772
773
774
775

        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";

776
777
778
        let client = Client::new(ClientOptions::default(), drt.runtime().clone())
            .await
            .expect("etcd client should be available");
779
        let lease_id = drt.connection_id();
780
781

        // Create the key
782
        let result = client.kv_create(key, value.to_vec(), Some(lease_id)).await;
783
784
        assert!(result.is_ok(), "");

785
786
787
788
789
790
        // Try to create the key again - this should return Ok(Some(version)) indicating key already exists
        // Note: Prior to PR #4212 (Nov 10, 2025), kv_create returned Err when key existed.
        // PR #4212 changed the behavior to return Ok(Some(version)) for idempotency, matching
        // the StoreOutcome::Exists pattern used in the KeyValueStore abstraction.
        // The transaction now includes .or_else(TxnOp::get) to retrieve existing key info
        // instead of failing, making the operation idempotent for distributed systems.
791
        let result = client.kv_create(key, value.to_vec(), Some(lease_id)).await;
792
793
794
795
        assert!(
            result.is_ok() && result.unwrap().is_some(),
            "Expected Ok(Some(version)) when key already exists"
        );
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811

        // 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(())
    }
812
813
814
815
816

    #[test]
    fn test_kv_cache() {
        let rt = Runtime::from_settings().unwrap();
        let rt_clone = rt.clone();
817
        let config = DistributedConfig::from_settings();
818
819
820
821
822
823
824
825

        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<()> {
826
827
828
829
        // Make the client and unwrap it
        let client = Client::new(ClientOptions::default(), drt.runtime().clone())
            .await
            .expect("etcd client should be available");
830
831
832

        // Create a unique test prefix to avoid conflicts with other tests
        let test_id = uuid::Uuid::new_v4().to_string();
833
        let prefix = format!("v1/test_kv_cache_{}/", test_id);
834
835
836
837
838
839
840

        // 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
841
        let kv_cache = KvCache::new(client.clone(), prefix.clone(), initial_values).await?;
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911

        // 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(())
    }
912
}