Skip to main content

dynamo_runtime/transports/
etcd.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::runtime::Runtime;
5use anyhow::{Context, Result};
6
7use async_nats::jetstream::kv;
8use derive_builder::Builder;
9use derive_getters::Dissolve;
10use futures::StreamExt;
11use std::collections::HashMap;
12use std::sync::Arc;
13use tokio::sync::{RwLock, mpsc};
14use validator::Validate;
15
16use etcd_client::{
17    Certificate, Compare, CompareOp, DeleteOptions, GetOptions, Identity, LockClient, LockOptions,
18    LockResponse, PutOptions, PutResponse, TlsOptions, Txn, TxnOp, TxnOpResponse, WatchOptions,
19    WatchStream, Watcher,
20};
21pub use etcd_client::{ConnectOptions, KeyValue, LeaseClient};
22use tokio::time::{Duration, Instant, interval};
23use tokio_util::sync::CancellationToken;
24
25mod connector;
26mod lease;
27mod lock;
28
29use connector::Connector;
30use lease::*;
31pub use lock::*;
32
33use super::utils::build_in_runtime;
34use crate::config::environment_names::etcd as env_etcd;
35
36const DEFAULT_STARTUP_CONNECT_TIMEOUT: Duration = Duration::from_secs(120);
37const STARTUP_CONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
38const STARTUP_CONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
39const WATCH_RETRY_INITIAL_BACKOFF: Duration = Duration::from_millis(250);
40const WATCH_RETRY_MAX_BACKOFF: Duration = Duration::from_secs(5);
41const WATCH_RESYNC_GET_TIMEOUT: Duration = Duration::from_secs(10);
42const DEFAULT_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
43const DEFAULT_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(10);
44const DEFAULT_LEASE_TTL_SECS: u64 = 30;
45/// etcd's default `--grpc-keepalive-min-time`; pinging faster gets GOAWAY `too_many_pings`.
46const ETCD_SERVER_KEEPALIVE_MIN_TIME: Duration = Duration::from_secs(5);
47const WATCH_CHANNEL_CAPACITY: usize = 32;
48
49/// ETCD Client
50#[derive(Clone)]
51pub struct Client {
52    connector: Arc<Connector>,
53    primary_lease: u64,
54    runtime: Runtime,
55    // Exclusive runtime for etcd lease keep-alive and watch tasks
56    // Avoid those tasks from being starved when the main runtime is busy
57    // WARNING: Do not await on main runtime from this runtime or deadlocks may occur
58    rt: Arc<tokio::runtime::Runtime>,
59}
60
61#[derive(Debug, Copy, Clone, Eq, PartialEq)]
62pub enum CompareAndPutOutcome {
63    Updated,
64    Missing,
65    Conflict,
66}
67
68impl std::fmt::Debug for Client {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        write!(f, "etcd::Client primary_lease={}", self.primary_lease)
71    }
72}
73
74impl Client {
75    pub fn builder() -> ClientOptionsBuilder {
76        ClientOptionsBuilder::default()
77    }
78
79    /// Create a new discovery client
80    ///
81    /// This will establish a connection to the etcd server, create a primary lease,
82    /// and spawn a task to keep the lease alive and tie the lifetime of the [`Runtime`]
83    /// to the lease.
84    ///
85    /// If the lease expires, the [`Runtime`] will be shutdown.
86    /// If the [`Runtime`] is shutdown, the lease will be revoked.
87    pub async fn new(config: ClientOptions, runtime: Runtime) -> Result<Self> {
88        let runtime_for_lease = runtime.clone();
89
90        let ((connector, lease_id), rt) = build_in_runtime(
91            async move { Self::connect_with_startup_retry(&config, runtime_for_lease).await },
92            1,
93        )
94        .await?;
95
96        Ok(Client {
97            connector,
98            primary_lease: lease_id,
99            rt,
100            runtime,
101        })
102    }
103
104    /// Connect to etcd during startup, retrying with exponential backoff until the configured
105    /// startup deadline.
106    async fn connect_with_startup_retry(
107        config: &ClientOptions,
108        runtime: Runtime,
109    ) -> Result<(Arc<Connector>, u64)> {
110        let token = runtime.primary_token();
111        let timeout = config.startup_connect_timeout;
112        let deadline = Instant::now().checked_add(timeout).ok_or_else(|| {
113            anyhow::anyhow!(
114                "etcd startup connection timeout {timeout:?} exceeds the supported duration"
115            )
116        })?;
117        let mut backoff = STARTUP_CONNECT_INITIAL_BACKOFF;
118
119        loop {
120            if token.is_cancelled() {
121                anyhow::bail!("etcd startup connection cancelled");
122            }
123
124            let remaining = deadline.saturating_duration_since(Instant::now());
125            if remaining.is_zero() {
126                anyhow::bail!(
127                    "etcd startup connection timed out after {} seconds",
128                    timeout.as_secs_f64()
129                );
130            }
131
132            let attempt = tokio::select! {
133                biased;
134
135                _ = token.cancelled() => {
136                    anyhow::bail!("etcd startup connection cancelled");
137                }
138
139                result = tokio::time::timeout(
140                    remaining,
141                    Self::connect_startup_attempt(config, &runtime),
142                ) => {
143                    match result {
144                        Ok(result) => result,
145                        Err(_) => anyhow::bail!(
146                            "etcd startup connection timed out after {} seconds",
147                            timeout.as_secs_f64()
148                        ),
149                    }
150                }
151            };
152
153            match attempt {
154                Ok(connection) => return Ok(connection),
155                Err(err) => {
156                    let now = Instant::now();
157                    if now >= deadline {
158                        return Err(err);
159                    }
160
161                    let sleep_duration = backoff.min(deadline.saturating_duration_since(now));
162
163                    tracing::warn!(
164                        error = %err,
165                        retry_in = ?sleep_duration,
166                        remaining = ?deadline.saturating_duration_since(now),
167                        "etcd not reachable yet; retrying startup connection"
168                    );
169
170                    tokio::select! {
171                        biased;
172
173                        _ = token.cancelled() => {
174                            anyhow::bail!("etcd startup connection cancelled");
175                        }
176
177                        _ = tokio::time::sleep(sleep_duration) => {}
178                    }
179                    backoff = backoff.saturating_mul(2).min(STARTUP_CONNECT_MAX_BACKOFF);
180                }
181            }
182        }
183    }
184
185    async fn connect_startup_attempt(
186        config: &ClientOptions,
187        runtime: &Runtime,
188    ) -> Result<(Arc<Connector>, u64)> {
189        let token = runtime.primary_token();
190        let connect_options = config
191            .etcd_connect_options
192            .clone()
193            .or_else(|| with_default_keep_alive(None, config.lease_ttl));
194        let connector = Connector::new(config.etcd_url.clone(), connect_options).await?;
195
196        let lease_id = if config.attach_lease {
197            create_lease(connector.clone(), config.lease_ttl, runtime.clone())
198                .await
199                .with_context(|| {
200                    format!(
201                        "Unable to create lease. Check etcd server status at {}",
202                        config.etcd_url.join(", ")
203                    )
204                })?
205        } else {
206            0
207        };
208
209        if token.is_cancelled() {
210            anyhow::bail!("etcd startup connection cancelled");
211        }
212
213        Ok((connector, lease_id))
214    }
215
216    /// Get a clone of the underlying [`etcd_client::Client`] instance.
217    /// This returns a clone since the client is behind an RwLock.
218    fn etcd_client(&self) -> etcd_client::Client {
219        self.connector.get_client()
220    }
221
222    /// Get the primary lease ID.
223    pub fn lease_id(&self) -> u64 {
224        self.primary_lease
225    }
226
227    /// Probe etcd connectivity via the maintenance status RPC.
228    /// Returns immediately with no side effects; a missing key is not an error.
229    /// A follower can answer this RPC even without quorum, so we also reject
230    /// leader == 0, which indicates no elected leader and means linearizable
231    /// reads will time out.
232    pub(crate) async fn check_connection(&self) -> anyhow::Result<()> {
233        let resp = self.etcd_client().maintenance_client().status().await?;
234        anyhow::ensure!(
235            resp.leader() != 0,
236            "etcd has no elected leader (quorum lost)"
237        );
238        Ok(())
239    }
240
241    /// Atomically create a key-value pair if it doesn't already exist.
242    ///
243    /// Returns:
244    /// - `Ok(None)` if the key was successfully created
245    /// - `Ok(Some(version))` if the key already exists (returns the existing version)
246    /// - `Err(...)` only on actual errors (connection failure, timeout, etc.)
247    ///
248    /// This idempotent behavior was introduced in PR #4212 (Nov 10, 2025) to align with
249    /// the StoreOutcome pattern used in KeyValueStore implementations, where both
250    /// Created and Exists are successful outcomes rather than errors. This design supports
251    /// distributed systems where multiple processes might attempt to create the same key.
252    pub async fn kv_create(
253        &self,
254        key: &str,
255        value: Vec<u8>,
256        lease_id: Option<u64>,
257    ) -> Result<Option<u64>> {
258        let id = lease_id.unwrap_or(self.lease_id());
259        let put_options = PutOptions::new().with_lease(id as i64);
260
261        // Build transaction that creates key only if it doesn't exist
262        let txn = Txn::new()
263            .when(vec![Compare::version(key, CompareOp::Equal, 0)]) // Ensure the lock does not exist
264            .and_then(vec![
265                TxnOp::put(key, value, Some(put_options)), // Create the object
266            ])
267            .or_else(vec![
268                TxnOp::get(key, None), // Key exists, get its info
269            ]);
270
271        // Execute the transaction
272        let result = self.connector.get_client().kv_client().txn(txn).await?;
273
274        // Created
275        if result.succeeded() {
276            return Ok(None);
277        }
278
279        // Already exists
280        if let Some(etcd_client::TxnOpResponse::Get(get_resp)) =
281            result.op_responses().into_iter().next()
282            && let Some(kv) = get_resp.kvs().first()
283        {
284            let version = kv.version() as u64;
285            return Ok(Some(version));
286        }
287
288        // Error
289        for resp in result.op_responses() {
290            tracing::warn!(response = ?resp, "kv_create etcd op response");
291        }
292        anyhow::bail!("Unable to create key. Check etcd server status")
293    }
294
295    /// Atomically create a key if it does not exist, or validate the values are identical if the key exists.
296    pub async fn kv_create_or_validate(
297        &self,
298        key: String,
299        value: Vec<u8>,
300        lease_id: Option<u64>,
301    ) -> Result<()> {
302        let id = lease_id.unwrap_or(self.lease_id());
303        let put_options = PutOptions::new().with_lease(id as i64);
304
305        // Build the transaction that either creates the key if it doesn't exist,
306        // or validates the existing value matches what we expect
307        let txn = Txn::new()
308            .when(vec![Compare::version(key.as_str(), CompareOp::Equal, 0)]) // Key doesn't exist
309            .and_then(vec![
310                TxnOp::put(key.as_str(), value.clone(), Some(put_options)), // Create it
311            ])
312            .or_else(vec![
313                // If key exists but values don't match, this will fail the transaction
314                TxnOp::txn(Txn::new().when(vec![Compare::value(
315                    key.as_str(),
316                    CompareOp::Equal,
317                    value.clone(),
318                )])),
319            ]);
320
321        // Execute the transaction
322        let result = self.connector.get_client().kv_client().txn(txn).await?;
323
324        // We have to enumerate the response paths to determine if the transaction succeeded
325        if result.succeeded() {
326            Ok(())
327        } else {
328            match result.op_responses().first() {
329                Some(response) => match response {
330                    TxnOpResponse::Txn(response) => match response.succeeded() {
331                        true => Ok(()),
332                        false => anyhow::bail!(
333                            "Unable to create or validate key. Check etcd server status"
334                        ),
335                    },
336                    _ => {
337                        anyhow::bail!("Unable to validate key operation. Check etcd server status")
338                    }
339                },
340                None => anyhow::bail!("Unable to create or validate key. Check etcd server status"),
341            }
342        }
343    }
344
345    pub async fn kv_put(
346        &self,
347        key: impl AsRef<str>,
348        value: impl AsRef<[u8]>,
349        lease_id: Option<u64>,
350    ) -> Result<()> {
351        let id = lease_id.unwrap_or(self.lease_id());
352        let put_options = PutOptions::new().with_lease(id as i64);
353        let _ = self
354            .connector
355            .get_client()
356            .kv_client()
357            .put(key.as_ref(), value.as_ref(), Some(put_options))
358            .await?;
359        Ok(())
360    }
361
362    /// Put all entries atomically, using the primary lease when none is supplied.
363    pub async fn kv_put_many(
364        &self,
365        entries: Vec<(String, Vec<u8>)>,
366        lease_id: Option<u64>,
367    ) -> Result<()> {
368        let options = PutOptions::new().with_lease(lease_id.unwrap_or(self.lease_id()) as i64);
369        let operations: Vec<_> = entries
370            .into_iter()
371            .map(|(key, value)| TxnOp::put(key, value, Some(options.clone())))
372            .collect();
373        self.connector
374            .get_client()
375            .kv_client()
376            .txn(Txn::new().and_then(operations))
377            .await?;
378        Ok(())
379    }
380
381    pub async fn kv_put_with_options(
382        &self,
383        key: impl AsRef<str>,
384        value: impl AsRef<[u8]>,
385        options: Option<PutOptions>,
386    ) -> Result<PutResponse> {
387        let options = options
388            .unwrap_or_default()
389            .with_lease(self.lease_id() as i64);
390        self.connector
391            .get_client()
392            .kv_client()
393            .put(key.as_ref(), value.as_ref(), Some(options))
394            .await
395            .map_err(|err| err.into())
396    }
397
398    /// Replace an existing value with a compare-on-mod-revision transaction.
399    pub async fn kv_compare_and_put(
400        &self,
401        key: impl AsRef<str>,
402        expected: impl AsRef<[u8]>,
403        value: impl AsRef<[u8]>,
404        lease_id: Option<u64>,
405    ) -> Result<CompareAndPutOutcome> {
406        let key = key.as_ref();
407        let current = self
408            .connector
409            .get_client()
410            .kv_client()
411            .get(key, None)
412            .await?;
413        let Some(current) = current.kvs().first() else {
414            return Ok(CompareAndPutOutcome::Missing);
415        };
416        if current.value() != expected.as_ref() {
417            return Ok(CompareAndPutOutcome::Conflict);
418        }
419        let expected_mod_revision = current.mod_revision();
420
421        let put_options = PutOptions::new().with_lease(lease_id.unwrap_or(self.lease_id()) as i64);
422        let txn = Txn::new()
423            .when(vec![Compare::mod_revision(
424                key,
425                CompareOp::Equal,
426                expected_mod_revision,
427            )])
428            .and_then(vec![TxnOp::put(
429                key,
430                value.as_ref().to_vec(),
431                Some(put_options),
432            )])
433            .or_else(vec![TxnOp::get(key, None)]);
434
435        let result = self.connector.get_client().kv_client().txn(txn).await?;
436        if result.succeeded() {
437            return Ok(CompareAndPutOutcome::Updated);
438        }
439
440        match result.op_responses().into_iter().next() {
441            Some(TxnOpResponse::Get(response)) if response.kvs().is_empty() => {
442                Ok(CompareAndPutOutcome::Missing)
443            }
444            Some(TxnOpResponse::Get(_)) => Ok(CompareAndPutOutcome::Conflict),
445            response => {
446                tracing::warn!(?response, "unexpected compare-and-put response");
447                anyhow::bail!("Unable to compare and replace key. Check etcd server status")
448            }
449        }
450    }
451
452    pub async fn kv_get(
453        &self,
454        key: impl Into<Vec<u8>>,
455        options: Option<GetOptions>,
456    ) -> Result<Vec<KeyValue>> {
457        let mut get_response = self.connector.kv_client().get(key, options).await?;
458        Ok(get_response.take_kvs())
459    }
460
461    pub async fn kv_delete(
462        &self,
463        key: impl Into<Vec<u8>>,
464        options: Option<DeleteOptions>,
465    ) -> Result<u64> {
466        self.connector
467            .get_client()
468            .kv_client()
469            .delete(key, options)
470            .await
471            .map(|del_response| del_response.deleted() as u64)
472            .map_err(|err| err.into())
473    }
474
475    pub async fn kv_get_prefix(&self, prefix: impl AsRef<str>) -> Result<Vec<KeyValue>> {
476        let mut get_response = self
477            .connector
478            .kv_client()
479            .get(prefix.as_ref(), Some(GetOptions::new().with_prefix()))
480            .await?;
481
482        Ok(get_response.take_kvs())
483    }
484
485    /// Acquire a distributed lock using etcd's native lock mechanism
486    /// Returns a LockResponse that can be used to unlock later
487    pub async fn lock(
488        &self,
489        key: impl Into<Vec<u8>>,
490        lease_id: Option<u64>,
491    ) -> Result<LockResponse> {
492        let mut lock_client = self.connector.get_client().lock_client();
493        let id = lease_id.unwrap_or(self.lease_id());
494        let options = LockOptions::new().with_lease(id as i64);
495        lock_client
496            .lock(key, Some(options))
497            .await
498            .map_err(|err| err.into())
499    }
500
501    /// Release a distributed lock using the key from the LockResponse
502    pub async fn unlock(&self, lock_key: impl Into<Vec<u8>>) -> Result<()> {
503        let mut lock_client = self.connector.get_client().lock_client();
504        lock_client
505            .unlock(lock_key)
506            .await
507            .map_err(|err: etcd_client::Error| anyhow::anyhow!(err))?;
508        Ok(())
509    }
510
511    /// Like kv_get_and_watch_prefix but only for new changes, does not include existing values.
512    pub async fn kv_watch_prefix(
513        &self,
514        prefix: impl AsRef<str> + std::fmt::Display,
515    ) -> Result<PrefixWatcher> {
516        self.watch_internal(prefix, false).await
517    }
518
519    pub async fn kv_get_and_watch_prefix(
520        &self,
521        prefix: impl AsRef<str> + std::fmt::Display,
522    ) -> Result<PrefixWatcher> {
523        self.watch_internal(prefix, true).await
524    }
525
526    /// Core watch implementation that sets up a resilient watcher for a key prefix.
527    ///
528    /// Creates a background task that maintains a watch stream with automatic reconnection
529    /// on recoverable errors. If `include_existing` is true, the first event is one
530    /// [`WatchEvent::Resync`] that holds every existing key, possibly none.
531    async fn watch_internal(
532        &self,
533        prefix: impl AsRef<str> + std::fmt::Display,
534        include_existing: bool,
535    ) -> Result<PrefixWatcher> {
536        let (mut start_revision, existing_kvs) = self
537            .get_start_revision(prefix.as_ref(), include_existing)
538            .await?;
539
540        let (tx, rx) = mpsc::channel(WATCH_CHANNEL_CAPACITY);
541
542        if let Some(kvs) = existing_kvs {
543            tracing::trace!(
544                count = kvs.len(),
545                "sending the existing kvs as the initial snapshot"
546            );
547            tx.send(WatchEvent::Resync(kvs)).await?;
548        }
549
550        // Watch for new events in background
551        let connector = self.connector.clone();
552        let prefix_str = prefix.as_ref().to_string();
553        let cancel_token = self.runtime.primary_token();
554        self.rt.spawn(async move {
555            let mut first_connect = true;
556            let mut reconnect = true;
557            while reconnect {
558                if !first_connect {
559                    let mut retry_attempt = 0u64;
560                    let mut retry_backoff = WATCH_RETRY_INITIAL_BACKOFF;
561                    while let Err(err) = Self::resync_watch_prefix(
562                        &connector,
563                        &prefix_str,
564                        &mut start_revision,
565                        &tx,
566                        &cancel_token,
567                    )
568                    .await
569                    {
570                        if tx.is_closed() || cancel_token.is_cancelled() {
571                            return;
572                        }
573
574                        retry_attempt = retry_attempt.saturating_add(1);
575                        if retry_attempt == 1 {
576                            tracing::warn!(
577                                error = %err,
578                                prefix = %prefix_str,
579                                "failed to resync etcd watch prefix after reconnect; retrying"
580                            );
581                        } else {
582                            tracing::info!(
583                                error = %err,
584                                prefix = %prefix_str,
585                                retry_attempt,
586                                backoff_ms = retry_backoff.as_millis(),
587                                "still failing to resync etcd watch prefix after reconnect; retrying"
588                            );
589                        }
590
591                        if Self::is_etcd_connection_error(&err) {
592                            let deadline = std::time::Instant::now() + Duration::from_secs(10);
593                            if let Err(err) = connector.reconnect(deadline).await {
594                                tracing::warn!(
595                                    error = %err,
596                                    prefix = %prefix_str,
597                                    "failed to reconnect to ETCD before watch resync; retrying"
598                                );
599                            }
600                        }
601
602                        tokio::select! {
603                            _ = cancel_token.cancelled() => return,
604                            _ = tokio::time::sleep(Self::watch_retry_backoff(retry_backoff)) => {}
605                        }
606                        retry_backoff =
607                            retry_backoff.saturating_mul(2).min(WATCH_RETRY_MAX_BACKOFF);
608                    }
609                }
610
611                // Start a new watch stream. Never give up while there are receivers: exiting
612                // here freezes discovery for the lifetime of the process.
613                let mut stream_backoff = WATCH_RETRY_INITIAL_BACKOFF;
614                let watch_stream = loop {
615                    let result = tokio::select! {
616                        biased;
617                        _ = cancel_token.cancelled() => return,
618                        _ = tx.closed() => return,
619                        result = Self::new_watch_stream(&connector, &prefix_str, start_revision) => result,
620                    };
621                    match result {
622                        Ok(stream) => break stream,
623                        Err(err) => {
624                            if tx.is_closed() || cancel_token.is_cancelled() {
625                                return;
626                            }
627                            tracing::warn!(
628                                error = %err,
629                                prefix = %prefix_str,
630                                backoff_ms = stream_backoff.as_millis(),
631                                "failed to establish etcd watch stream; retrying"
632                            );
633                            tokio::select! {
634                                biased;
635                                _ = cancel_token.cancelled() => return,
636                                _ = tx.closed() => return,
637                                _ = tokio::time::sleep(Self::watch_retry_backoff(stream_backoff)) => {}
638                            }
639                            stream_backoff =
640                                stream_backoff.saturating_mul(2).min(WATCH_RETRY_MAX_BACKOFF);
641                        }
642                    }
643                };
644
645                first_connect = false;
646
647                // Watch the stream
648                reconnect =
649                    Self::monitor_watch_stream(watch_stream, &prefix_str, &mut start_revision, &tx)
650                        .await;
651            }
652        });
653
654        Ok(PrefixWatcher {
655            prefix: prefix.as_ref().to_string(),
656            rx,
657        })
658    }
659
660    /// Fetch the start revision and optionally return existing key-values.
661    async fn get_start_revision(
662        &self,
663        prefix: impl AsRef<str> + std::fmt::Display,
664        include_existing: bool,
665    ) -> Result<(i64, Option<Vec<KeyValue>>)> {
666        let mut kv_client = self.connector.kv_client();
667        let mut get_response = kv_client
668            .get(prefix.as_ref(), Some(GetOptions::new().with_prefix()))
669            .await?;
670
671        // Get the start revision
672        let mut start_revision = get_response
673            .header()
674            .ok_or(anyhow::anyhow!("missing header; unable to get revision"))?
675            .revision();
676        tracing::trace!("{prefix}: start_revision: {start_revision}");
677        start_revision += 1;
678
679        // Return existing KVs if requested
680        let existing_kvs = include_existing.then(|| {
681            let kvs = get_response.take_kvs();
682            tracing::trace!("initial kv count: {:?}", kvs.len());
683            kvs
684        });
685
686        Ok((start_revision, existing_kvs))
687    }
688
689    /// Fetch current prefix state after reconnect and publish it as an authoritative snapshot.
690    async fn resync_watch_prefix(
691        connector: &Arc<Connector>,
692        prefix: &str,
693        start_revision: &mut i64,
694        tx: &mpsc::Sender<WatchEvent>,
695        cancel_token: &CancellationToken,
696    ) -> Result<()> {
697        let mut kv_client = connector.kv_client();
698        let get_result = tokio::select! {
699            _ = cancel_token.cancelled() => anyhow::bail!("watch resync cancelled"),
700            result = tokio::time::timeout(
701                WATCH_RESYNC_GET_TIMEOUT,
702                kv_client.get(prefix, Some(GetOptions::new().with_prefix())),
703            ) => result,
704        };
705        let mut response = get_result
706            .with_context(|| format!("timed out fetching etcd prefix snapshot for '{prefix}'"))?
707            .with_context(|| format!("failed to fetch etcd prefix snapshot for '{prefix}'"))?;
708
709        let header = response
710            .header()
711            .ok_or_else(|| anyhow::anyhow!("missing header during watch resync for '{prefix}'"))?;
712        *start_revision = header.revision() + 1;
713
714        let kvs = response.take_kvs();
715        tracing::warn!(
716            prefix,
717            kv_count = kvs.len(),
718            start_revision = *start_revision,
719            "resyncing etcd watch prefix after reconnect"
720        );
721
722        tokio::select! {
723            _ = cancel_token.cancelled() => anyhow::bail!("watch resync cancelled"),
724            result = tx.send(WatchEvent::Resync(kvs)) => {
725                result.context("failed to send WatchEvent::Resync")
726            }
727        }
728    }
729
730    fn is_etcd_connection_error(err: &anyhow::Error) -> bool {
731        if err.chain().any(|cause| {
732            cause
733                .downcast_ref::<tokio::time::error::Elapsed>()
734                .is_some()
735        }) {
736            return true;
737        }
738
739        err.chain().any(|cause| {
740            let Some(err) = cause.downcast_ref::<etcd_client::Error>() else {
741                return false;
742            };
743
744            match err {
745                etcd_client::Error::IoError(_)
746                | etcd_client::Error::TransportError(_)
747                | etcd_client::Error::EndpointError(_) => true,
748                etcd_client::Error::GRpcStatus(status) => matches!(
749                    status.code() as i32,
750                    // tonic::Code::Cancelled
751                    1
752                    // tonic::Code::Unknown
753                    | 2
754                    // tonic::Code::DeadlineExceeded
755                    | 4
756                    // tonic::Code::Unavailable
757                    | 14
758                ),
759                _ => false,
760            }
761        })
762    }
763
764    fn watch_retry_backoff(current: Duration) -> Duration {
765        let max_ms = u64::try_from(current.as_millis()).unwrap_or(u64::MAX);
766        let min_ms = (max_ms / 2).max(1);
767        let jitter_range = max_ms.saturating_sub(min_ms).saturating_add(1);
768        Duration::from_millis(min_ms + rand::random::<u64>() % jitter_range)
769    }
770
771    /// Establish a new watch stream with automatic retry and reconnection.
772    ///
773    /// Attempts to create a watch stream, reconnecting to ETCD if necessary.
774    /// Uses a 10-second timeout for reconnection attempts before giving up.
775    async fn new_watch_stream(
776        connector: &Arc<Connector>,
777        prefix: &String,
778        start_revision: i64,
779    ) -> Result<WatchStream> {
780        loop {
781            match connector
782                .watch_client()
783                .watch(
784                    prefix.as_str(),
785                    Some(
786                        WatchOptions::new()
787                            .with_prefix()
788                            .with_start_revision(start_revision)
789                            .with_prev_key(),
790                    ),
791                )
792                .await
793            {
794                Ok((_, watch_stream)) => {
795                    tracing::debug!("Watch stream established for prefix '{prefix}'");
796                    return Ok(watch_stream);
797                }
798                Err(err) => {
799                    tracing::debug!(error = %err, "Failed to establish watch stream for prefix '{}'", prefix);
800                    let deadline = std::time::Instant::now() + Duration::from_secs(10);
801                    if let Err(err) = connector.reconnect(deadline).await {
802                        tracing::error!(
803                            "Failed to reconnect to ETCD within 10 secs for watching prefix '{}': {}",
804                            prefix,
805                            err
806                        );
807                        return Err(err);
808                    }
809                    // continue - retry establishing the watch stream
810                }
811            }
812        }
813    }
814
815    /// Monitor a watch stream and forward events to receivers.
816    ///
817    /// Returns `true` for recoverable errors (network issues, stream closure) that warrant
818    /// reconnection attempts. Returns `false` for permanent failures (protocol violations,
819    /// channel errors, no receivers) where watching should stop.
820    async fn monitor_watch_stream(
821        mut watch_stream: WatchStream,
822        prefix: &String,
823        start_revision: &mut i64,
824        tx: &mpsc::Sender<WatchEvent>,
825    ) -> bool {
826        loop {
827            tokio::select! {
828                maybe_resp = watch_stream.next() => {
829                    // Handle the watch response
830                    let response = match maybe_resp {
831                        Some(Ok(res)) => res,
832                        Some(Err(err)) => {
833                            tracing::warn!(error = %err, "Error watching stream for prefix '{}'", prefix);
834                            return true; // Exit to reconnect
835                        }
836                        None => {
837                            tracing::warn!("Watch stream unexpectedly closed for prefix '{prefix}'");
838                            return true; // Exit to reconnect
839                        }
840                    };
841
842                    // Update revision for reconnect
843                    *start_revision = match response.header() {
844                        Some(header) => header.revision() + 1,
845                        None => {
846                            tracing::error!("Missing header in watch response for prefix '{prefix}'");
847                            return false;
848                        }
849                    };
850
851                    // Process events
852                    if Self::process_watch_events(response.events(), tx).await.is_err() {
853                        return false;
854                    };
855                }
856                _ = tx.closed() => {
857                    tracing::debug!("no more receivers, stopping watcher");
858                    return false;
859                }
860            }
861        }
862    }
863
864    /// Process etcd events and forward them as Put/Delete watch events.
865    ///
866    /// Filters out events without key-values and transforms etcd events into
867    /// appropriate WatchEvent types for channel transmission.
868    async fn process_watch_events(
869        events: &[etcd_client::Event],
870        tx: &mpsc::Sender<WatchEvent>,
871    ) -> Result<()> {
872        for event in events {
873            // Extract the KeyValue if it exists
874            let Some(kv) = event.kv() else {
875                continue; // Skip events with no KV
876            };
877
878            // Handle based on event type
879            match event.event_type() {
880                etcd_client::EventType::Put => {
881                    if let Err(err) = tx.send(WatchEvent::Put(kv.clone())).await {
882                        tracing::error!("kv watcher error forwarding WatchEvent::Put: {err}");
883                        return Err(err.into());
884                    }
885                }
886                etcd_client::EventType::Delete => {
887                    if tx.send(WatchEvent::Delete(kv.clone())).await.is_err() {
888                        return Err(anyhow::anyhow!("failed to send WatchEvent::Delete"));
889                    }
890                }
891            }
892        }
893        Ok(())
894    }
895}
896
897#[derive(Dissolve)]
898pub struct PrefixWatcher {
899    prefix: String,
900    rx: mpsc::Receiver<WatchEvent>,
901}
902
903#[derive(Debug)]
904pub enum WatchEvent {
905    Put(KeyValue),
906    Delete(KeyValue),
907    /// Full prefix state after watch reconnection.
908    ///
909    /// Consumers that maintain local state should replace that state with this
910    /// authoritative snapshot before applying subsequent incremental events.
911    Resync(Vec<KeyValue>),
912}
913
914/// ETCD client configuration options
915#[derive(Debug, Clone, Builder, Validate)]
916pub struct ClientOptions {
917    #[validate(length(min = 1))]
918    pub etcd_url: Vec<String>,
919
920    #[builder(default)]
921    pub etcd_connect_options: Option<ConnectOptions>,
922
923    /// If true, the client will attach a lease to the primary [`CancellationToken`].
924    #[builder(default = "true")]
925    pub attach_lease: bool,
926
927    /// Lease TTL in seconds
928    #[builder(default = "default_lease_ttl()")]
929    pub lease_ttl: u64,
930
931    /// Maximum duration for the initial connection and lease creation retry loop.
932    #[builder(default = "default_startup_connect_timeout()")]
933    pub startup_connect_timeout: Duration,
934}
935
936impl Default for ClientOptions {
937    fn default() -> Self {
938        let mut connect_options = None;
939        let lease_ttl = default_lease_ttl();
940
941        if let (Ok(username), Ok(password)) = (
942            std::env::var(env_etcd::auth::ETCD_AUTH_USERNAME),
943            std::env::var(env_etcd::auth::ETCD_AUTH_PASSWORD),
944        ) {
945            // username and password are set
946            connect_options = Some(ConnectOptions::new().with_user(username, password));
947        } else if let (Ok(ca), Ok(cert), Ok(key)) = (
948            std::env::var(env_etcd::auth::ETCD_AUTH_CA),
949            std::env::var(env_etcd::auth::ETCD_AUTH_CLIENT_CERT),
950            std::env::var(env_etcd::auth::ETCD_AUTH_CLIENT_KEY),
951        ) {
952            // TLS is set
953            connect_options = Some(
954                ConnectOptions::new().with_tls(
955                    TlsOptions::new()
956                        .ca_certificate(Certificate::from_pem(ca))
957                        .identity(Identity::from_pem(cert, key)),
958                ),
959            );
960        }
961
962        // Without HTTP/2 keepalive, an etcd member that hangs without closing its TCP
963        // connections leaves watch streams open but silent forever, so deletes are never
964        // seen and the reconnect/resync path never runs.
965        connect_options = with_default_keep_alive(connect_options, lease_ttl);
966
967        ClientOptions {
968            etcd_url: default_servers(),
969            etcd_connect_options: connect_options,
970            attach_lease: true,
971            lease_ttl,
972            startup_connect_timeout: default_startup_connect_timeout(),
973        }
974    }
975}
976
977fn default_servers() -> Vec<String> {
978    match std::env::var(env_etcd::ETCD_ENDPOINTS) {
979        Ok(possible_list_of_urls) => possible_list_of_urls
980            .split(',')
981            .map(|s| s.to_string())
982            .collect(),
983        Err(_) => vec!["http://localhost:2379".to_string()],
984    }
985}
986
987fn default_lease_ttl() -> u64 {
988    match std::env::var(env_etcd::ETCD_LEASE_TTL) {
989        Ok(raw) => match raw.parse::<u64>() {
990            Ok(ttl) if ttl > 0 => ttl,
991            Ok(_) => {
992                tracing::warn!(
993                    "{} must be >= 1; got 0. Falling back to {}.",
994                    env_etcd::ETCD_LEASE_TTL,
995                    DEFAULT_LEASE_TTL_SECS
996                );
997                DEFAULT_LEASE_TTL_SECS
998            }
999            Err(err) => {
1000                tracing::warn!(
1001                    "Invalid {}='{}' ({err}). Falling back to {}.",
1002                    env_etcd::ETCD_LEASE_TTL,
1003                    raw,
1004                    DEFAULT_LEASE_TTL_SECS
1005                );
1006                DEFAULT_LEASE_TTL_SECS
1007            }
1008        },
1009        Err(_) => DEFAULT_LEASE_TTL_SECS,
1010    }
1011}
1012
1013fn startup_connect_timeout_from_value(value: Option<&str>) -> Duration {
1014    match value {
1015        Some(raw) => match raw.parse::<u64>() {
1016            Ok(seconds) if seconds > 0 => Duration::from_secs(seconds),
1017            Ok(_) => {
1018                tracing::warn!(
1019                    "{} must be >= 1; got 0. Falling back to {}.",
1020                    env_etcd::ETCD_STARTUP_CONNECT_TIMEOUT_SECONDS,
1021                    DEFAULT_STARTUP_CONNECT_TIMEOUT.as_secs()
1022                );
1023                DEFAULT_STARTUP_CONNECT_TIMEOUT
1024            }
1025            Err(error) => {
1026                tracing::warn!(
1027                    "Invalid {}='{}' ({error}). Falling back to {}.",
1028                    env_etcd::ETCD_STARTUP_CONNECT_TIMEOUT_SECONDS,
1029                    raw,
1030                    DEFAULT_STARTUP_CONNECT_TIMEOUT.as_secs()
1031                );
1032                DEFAULT_STARTUP_CONNECT_TIMEOUT
1033            }
1034        },
1035        None => DEFAULT_STARTUP_CONNECT_TIMEOUT,
1036    }
1037}
1038
1039/// Resolve the etcd channel keepalive `(interval, timeout)`, or `None` when disabled
1040/// (`ETCD_KEEPALIVE_INTERVAL_SECONDS=0`).
1041fn keep_alive_from_values(
1042    interval: Option<&str>,
1043    timeout: Option<&str>,
1044) -> Option<(Duration, Duration)> {
1045    let interval = match interval {
1046        Some(raw) => match raw.parse::<u64>() {
1047            Ok(0) => return None,
1048            Ok(seconds) => Duration::from_secs(seconds),
1049            Err(error) => {
1050                tracing::warn!(
1051                    "Invalid {}='{}' ({error}). Falling back to {}.",
1052                    env_etcd::ETCD_KEEPALIVE_INTERVAL_SECONDS,
1053                    raw,
1054                    DEFAULT_KEEPALIVE_INTERVAL.as_secs()
1055                );
1056                DEFAULT_KEEPALIVE_INTERVAL
1057            }
1058        },
1059        None => DEFAULT_KEEPALIVE_INTERVAL,
1060    };
1061    if interval < ETCD_SERVER_KEEPALIVE_MIN_TIME {
1062        tracing::warn!(
1063            "{}={} is below etcd's default --grpc-keepalive-min-time ({}s); the server may \
1064             close the connection with GOAWAY too_many_pings.",
1065            env_etcd::ETCD_KEEPALIVE_INTERVAL_SECONDS,
1066            interval.as_secs(),
1067            ETCD_SERVER_KEEPALIVE_MIN_TIME.as_secs()
1068        );
1069    }
1070    let timeout = match timeout {
1071        Some(raw) => match raw.parse::<u64>() {
1072            Ok(seconds) if seconds > 0 => Duration::from_secs(seconds),
1073            Ok(_) => {
1074                tracing::warn!(
1075                    "{} must be >= 1; got 0. Falling back to {}.",
1076                    env_etcd::ETCD_KEEPALIVE_TIMEOUT_SECONDS,
1077                    DEFAULT_KEEPALIVE_TIMEOUT.as_secs()
1078                );
1079                DEFAULT_KEEPALIVE_TIMEOUT
1080            }
1081            Err(error) => {
1082                tracing::warn!(
1083                    "Invalid {}='{}' ({error}). Falling back to {}.",
1084                    env_etcd::ETCD_KEEPALIVE_TIMEOUT_SECONDS,
1085                    raw,
1086                    DEFAULT_KEEPALIVE_TIMEOUT.as_secs()
1087                );
1088                DEFAULT_KEEPALIVE_TIMEOUT
1089            }
1090        },
1091        None => DEFAULT_KEEPALIVE_TIMEOUT,
1092    };
1093    Some((interval, timeout))
1094}
1095
1096fn default_keep_alive() -> Option<(Duration, Duration)> {
1097    keep_alive_from_values(
1098        std::env::var(env_etcd::ETCD_KEEPALIVE_INTERVAL_SECONDS)
1099            .ok()
1100            .as_deref(),
1101        std::env::var(env_etcd::ETCD_KEEPALIVE_TIMEOUT_SECONDS)
1102            .ok()
1103            .as_deref(),
1104    )
1105}
1106
1107fn with_default_keep_alive(
1108    connect_options: Option<ConnectOptions>,
1109    lease_ttl: u64,
1110) -> Option<ConnectOptions> {
1111    let Some((interval, timeout)) = default_keep_alive() else {
1112        return connect_options;
1113    };
1114    if interval.saturating_add(timeout) >= Duration::from_secs(lease_ttl) {
1115        tracing::warn!(
1116            interval_secs = interval.as_secs(),
1117            timeout_secs = timeout.as_secs(),
1118            lease_ttl_secs = lease_ttl,
1119            "etcd keepalive detection can take as long as the primary lease TTL"
1120        );
1121    }
1122    Some(
1123        connect_options
1124            .unwrap_or_default()
1125            .with_keep_alive(interval, timeout)
1126            .with_keep_alive_while_idle(false),
1127    )
1128}
1129
1130fn default_startup_connect_timeout() -> Duration {
1131    startup_connect_timeout_from_value(
1132        std::env::var(env_etcd::ETCD_STARTUP_CONNECT_TIMEOUT_SECONDS)
1133            .ok()
1134            .as_deref(),
1135    )
1136}
1137
1138/// A cache for etcd key-value pairs that watches for changes
1139pub struct KvCache {
1140    client: Client,
1141    pub prefix: String,
1142    cache: Arc<RwLock<HashMap<String, Vec<u8>>>>,
1143    watcher: Option<PrefixWatcher>,
1144}
1145
1146impl KvCache {
1147    /// Create a new KV cache for the given prefix
1148    pub async fn new(
1149        client: Client,
1150        prefix: String,
1151        initial_values: HashMap<String, Vec<u8>>,
1152    ) -> Result<Self> {
1153        let mut cache = HashMap::new();
1154
1155        // First get all existing keys with this prefix
1156        let existing_kvs = client.kv_get_prefix(&prefix).await?;
1157        for kv in existing_kvs {
1158            let key = String::from_utf8_lossy(kv.key()).to_string();
1159            cache.insert(key, kv.value().to_vec());
1160        }
1161
1162        // For any keys in initial_values that don't exist in etcd, write them
1163        // TODO: proper lease handling, this requires the first process that write to a prefix atomically
1164        // create a lease and write the lease to etcd. Later processes will attach to the lease and
1165        // help refresh the lease.
1166        for (key, value) in initial_values.iter() {
1167            let full_key = format!("{}{}", prefix, key);
1168            if let std::collections::hash_map::Entry::Vacant(e) = cache.entry(full_key.clone()) {
1169                client.kv_put(&full_key, value.clone(), None).await?;
1170                e.insert(value.clone());
1171            }
1172        }
1173
1174        // Start watching for changes
1175        // we won't miss events between the initial push and the watcher starting because
1176        // client.kv_get_and_watch_prefix() will get all kv pairs and put them back again
1177        let watcher = client.kv_get_and_watch_prefix(&prefix).await?;
1178
1179        let cache = Arc::new(RwLock::new(cache));
1180        let mut result = Self {
1181            client,
1182            prefix,
1183            cache,
1184            watcher: Some(watcher),
1185        };
1186
1187        // Start the background watcher task
1188        result.start_watcher().await?;
1189
1190        Ok(result)
1191    }
1192
1193    /// Start the background watcher task
1194    async fn start_watcher(&mut self) -> Result<()> {
1195        if let Some(watcher) = self.watcher.take() {
1196            let cache = self.cache.clone();
1197            let prefix = self.prefix.clone();
1198
1199            tokio::spawn(async move {
1200                let mut rx = watcher.rx;
1201                // The first resync is the initial snapshot; a later one means the watch reconnected.
1202                let mut is_established = false;
1203
1204                while let Some(event) = rx.recv().await {
1205                    match event {
1206                        WatchEvent::Put(kv) => {
1207                            let key = String::from_utf8_lossy(kv.key()).to_string();
1208                            let value = kv.value().to_vec();
1209
1210                            tracing::trace!("KvCache update: {} = {:?}", key, value);
1211                            let mut cache_write = cache.write().await;
1212                            cache_write.insert(key, value);
1213                        }
1214                        WatchEvent::Delete(kv) => {
1215                            let key = String::from_utf8_lossy(kv.key()).to_string();
1216
1217                            tracing::trace!("KvCache delete: {key}");
1218                            let mut cache_write = cache.write().await;
1219                            cache_write.remove(&key);
1220                        }
1221                        WatchEvent::Resync(kvs) => {
1222                            let mut replacement = HashMap::with_capacity(kvs.len());
1223                            for kv in kvs {
1224                                let key = String::from_utf8_lossy(kv.key()).to_string();
1225                                let value = kv.value().to_vec();
1226                                replacement.insert(key, value);
1227                            }
1228
1229                            if is_established {
1230                                tracing::warn!(
1231                                    prefix,
1232                                    new_count = replacement.len(),
1233                                    "KvCache replacing state from etcd watch resync"
1234                                );
1235                            } else {
1236                                tracing::debug!(
1237                                    prefix,
1238                                    count = replacement.len(),
1239                                    "KvCache loaded the initial snapshot"
1240                                );
1241                            }
1242                            is_established = true;
1243                            let mut cache_write = cache.write().await;
1244                            *cache_write = replacement;
1245                        }
1246                    }
1247                }
1248
1249                tracing::debug!("KvCache watcher for prefix '{prefix}' stopped");
1250            });
1251        }
1252
1253        Ok(())
1254    }
1255
1256    /// Get a value from the cache
1257    pub async fn get(&self, key: &str) -> Option<Vec<u8>> {
1258        let full_key = format!("{}{}", self.prefix, key);
1259        let cache_read = self.cache.read().await;
1260        cache_read.get(&full_key).cloned()
1261    }
1262
1263    /// Get all key-value pairs in the cache
1264    pub async fn get_all(&self) -> HashMap<String, Vec<u8>> {
1265        let cache_read = self.cache.read().await;
1266        cache_read.clone()
1267    }
1268
1269    /// Update a value in both the cache and etcd
1270    pub async fn put(&self, key: &str, value: Vec<u8>, lease_id: Option<u64>) -> Result<()> {
1271        let full_key = format!("{}{}", self.prefix, key);
1272
1273        // Update etcd first
1274        self.client
1275            .kv_put(&full_key, value.clone(), lease_id)
1276            .await?;
1277
1278        // Then update local cache
1279        let mut cache_write = self.cache.write().await;
1280        cache_write.insert(full_key, value);
1281
1282        Ok(())
1283    }
1284
1285    /// Delete a key from both the cache and etcd
1286    pub async fn delete(&self, key: &str) -> Result<()> {
1287        let full_key = format!("{}{}", self.prefix, key);
1288
1289        // Delete from etcd first
1290        self.client.kv_delete(full_key.clone(), None).await?;
1291
1292        // Then remove from local cache
1293        let mut cache_write = self.cache.write().await;
1294        cache_write.remove(&full_key);
1295
1296        Ok(())
1297    }
1298}
1299
1300#[cfg(test)]
1301mod unit_tests {
1302    use super::*;
1303
1304    #[test]
1305    fn parses_startup_connect_timeout() {
1306        assert_eq!(
1307            startup_connect_timeout_from_value(None),
1308            DEFAULT_STARTUP_CONNECT_TIMEOUT
1309        );
1310        assert_eq!(
1311            startup_connect_timeout_from_value(Some("45")),
1312            Duration::from_secs(45)
1313        );
1314        assert_eq!(
1315            startup_connect_timeout_from_value(Some("0")),
1316            DEFAULT_STARTUP_CONNECT_TIMEOUT
1317        );
1318        assert_eq!(
1319            startup_connect_timeout_from_value(Some("invalid")),
1320            DEFAULT_STARTUP_CONNECT_TIMEOUT
1321        );
1322    }
1323
1324    #[test]
1325    fn parses_keep_alive() {
1326        let defaults = Some((DEFAULT_KEEPALIVE_INTERVAL, DEFAULT_KEEPALIVE_TIMEOUT));
1327        assert_eq!(keep_alive_from_values(None, None), defaults);
1328        assert_eq!(keep_alive_from_values(Some("0"), None), None);
1329        assert_eq!(keep_alive_from_values(Some("0"), Some("3")), None);
1330        assert_eq!(
1331            keep_alive_from_values(Some("30"), Some("10")),
1332            Some((Duration::from_secs(30), Duration::from_secs(10)))
1333        );
1334        assert_eq!(
1335            keep_alive_from_values(Some("invalid"), Some("junk")),
1336            defaults
1337        );
1338        assert_eq!(
1339            keep_alive_from_values(Some("20"), Some("0")),
1340            Some((Duration::from_secs(20), DEFAULT_KEEPALIVE_TIMEOUT))
1341        );
1342    }
1343
1344    #[test]
1345    fn rejects_unrepresentable_startup_connect_timeout() {
1346        let runtime = Runtime::single_threaded().unwrap();
1347        let runtime_for_connect = runtime.clone();
1348        let options = Client::builder()
1349            .etcd_url(vec!["http://127.0.0.1:1".to_string()])
1350            .startup_connect_timeout(Duration::from_secs(u64::MAX))
1351            .build()
1352            .unwrap();
1353
1354        let result = runtime
1355            .primary()
1356            .block_on(Client::connect_with_startup_retry(
1357                &options,
1358                runtime_for_connect,
1359            ));
1360        let error = match result {
1361            Ok(_) => panic!("unrepresentable startup timeout unexpectedly succeeded"),
1362            Err(error) => error,
1363        };
1364
1365        assert!(
1366            error.to_string().contains("exceeds the supported duration"),
1367            "unexpected error: {error:#}"
1368        );
1369    }
1370
1371    #[test]
1372    fn startup_connection_respects_configured_timeout() {
1373        let runtime = Runtime::single_threaded().unwrap();
1374        let runtime_for_connect = runtime.clone();
1375        let options = Client::builder()
1376            .etcd_url(vec!["http://127.0.0.1:1".to_string()])
1377            .startup_connect_timeout(Duration::from_millis(50))
1378            .build()
1379            .unwrap();
1380
1381        let started = Instant::now();
1382        let result = runtime
1383            .primary()
1384            .block_on(Client::connect_with_startup_retry(
1385                &options,
1386                runtime_for_connect,
1387            ));
1388        let error = match result {
1389            Ok(_) => panic!("etcd startup connection unexpectedly succeeded"),
1390            Err(error) => error,
1391        };
1392
1393        assert!(
1394            error
1395                .to_string()
1396                .contains("etcd startup connection timed out after 0.05 seconds"),
1397            "unexpected error: {error:#}"
1398        );
1399        assert!(
1400            started.elapsed() < Duration::from_secs(1),
1401            "configured startup timeout was not respected"
1402        );
1403    }
1404
1405    #[test]
1406    fn classifies_etcd_connection_errors() {
1407        let err = anyhow::Error::new(etcd_client::Error::EndpointError(
1408            "endpoint unavailable".to_string(),
1409        ));
1410        assert!(Client::is_etcd_connection_error(&err));
1411
1412        let err = anyhow::Error::new(etcd_client::Error::IoError(std::io::Error::new(
1413            std::io::ErrorKind::ConnectionRefused,
1414            "connection refused",
1415        )));
1416        assert!(Client::is_etcd_connection_error(&err));
1417
1418        let runtime = tokio::runtime::Builder::new_current_thread()
1419            .enable_time()
1420            .build()
1421            .unwrap();
1422        let elapsed = runtime.block_on(async {
1423            tokio::time::timeout(Duration::from_millis(0), std::future::pending::<()>())
1424                .await
1425                .unwrap_err()
1426        });
1427        let err = anyhow::Error::new(elapsed).context("timed out fetching etcd prefix snapshot");
1428        assert!(Client::is_etcd_connection_error(&err));
1429
1430        let err = anyhow::Error::new(etcd_client::Error::InvalidArgs("bad request".to_string()));
1431        assert!(!Client::is_etcd_connection_error(&err));
1432
1433        let err = anyhow::anyhow!("missing header during watch resync");
1434        assert!(!Client::is_etcd_connection_error(&err));
1435    }
1436}
1437
1438#[cfg(feature = "integration")]
1439#[cfg(test)]
1440mod tests {
1441    use crate::{DistributedRuntime, distributed::DistributedConfig};
1442
1443    use super::*;
1444
1445    #[test]
1446    fn test_ectd_client() {
1447        let rt = Runtime::single_threaded().unwrap();
1448        let rt_clone = rt.clone();
1449        let config = DistributedConfig::from_settings();
1450
1451        rt_clone.primary().block_on(async move {
1452            let drt = DistributedRuntime::new(rt, config).await.unwrap();
1453            test_kv_create_or_validate(drt).await.unwrap();
1454        });
1455    }
1456
1457    async fn test_kv_create_or_validate(drt: DistributedRuntime) -> Result<()> {
1458        let key = "__integration_test_key";
1459        let value = b"test_value";
1460
1461        let client = Client::new(ClientOptions::default(), drt.runtime().clone())
1462            .await
1463            .expect("etcd client should be available");
1464        let lease_id = drt.connection_id();
1465
1466        // Create the key
1467        let result = client.kv_create(key, value.to_vec(), Some(lease_id)).await;
1468        assert!(result.is_ok(), "");
1469
1470        // Try to create the key again - this should return Ok(Some(version)) indicating key already exists
1471        // Note: Prior to PR #4212 (Nov 10, 2025), kv_create returned Err when key existed.
1472        // PR #4212 changed the behavior to return Ok(Some(version)) for idempotency, matching
1473        // the StoreOutcome::Exists pattern used in the KeyValueStore abstraction.
1474        // The transaction now includes .or_else(TxnOp::get) to retrieve existing key info
1475        // instead of failing, making the operation idempotent for distributed systems.
1476        let result = client.kv_create(key, value.to_vec(), Some(lease_id)).await;
1477        assert!(
1478            result.is_ok() && result.unwrap().is_some(),
1479            "Expected Ok(Some(version)) when key already exists"
1480        );
1481
1482        // Create or validate should succeed as the values match
1483        let result = client
1484            .kv_create_or_validate(key.to_string(), value.to_vec(), Some(lease_id))
1485            .await;
1486        assert!(result.is_ok());
1487
1488        // Try to create the key with a different value
1489        let different_value = b"different_value";
1490        let result = client
1491            .kv_create_or_validate(key.to_string(), different_value.to_vec(), Some(lease_id))
1492            .await;
1493        assert!(result.is_err(), "");
1494
1495        Ok(())
1496    }
1497
1498    #[test]
1499    fn test_prefix_reads_beyond_default_grpc_limit() {
1500        let rt = Runtime::single_threaded().unwrap();
1501        let rt_clone = rt.clone();
1502        let config = DistributedConfig::from_settings();
1503
1504        rt_clone.primary().block_on(async move {
1505            let drt = DistributedRuntime::new(rt, config).await.unwrap();
1506            test_large_prefix_reads(drt).await.unwrap();
1507        });
1508    }
1509
1510    async fn test_large_prefix_reads(drt: DistributedRuntime) -> Result<()> {
1511        let client = Client::new(ClientOptions::default(), drt.runtime().clone())
1512            .await
1513            .expect("etcd client should be available");
1514        let prefix = format!("v1/test_large_prefix_{}/", uuid::Uuid::new_v4());
1515
1516        // Each 1 MiB put fits etcd's default 1.5 MiB request limit; together the six exceed
1517        // tonic's 4 MiB default response limit.
1518        let value = vec![b'x'; 1 << 20];
1519        let keys = 6;
1520        for i in 0..keys {
1521            client.kv_put(format!("{prefix}{i}"), &value, None).await?;
1522        }
1523
1524        let listed = client.kv_get_prefix(&prefix).await.map(|kvs| kvs.len());
1525        let watched = initial_snapshot_len(&client, &prefix).await;
1526
1527        client
1528            .etcd_client()
1529            .kv_client()
1530            .delete(prefix, Some(DeleteOptions::new().with_prefix()))
1531            .await?;
1532
1533        assert_eq!(listed?, keys);
1534        assert_eq!(watched?, keys);
1535        Ok(())
1536    }
1537
1538    async fn initial_snapshot_len(client: &Client, prefix: &str) -> Result<usize> {
1539        let (_, mut rx) = client.kv_get_and_watch_prefix(prefix).await?.dissolve();
1540        match tokio::time::timeout(Duration::from_secs(10), rx.recv()).await? {
1541            Some(WatchEvent::Resync(kvs)) => Ok(kvs.len()),
1542            other => anyhow::bail!("expected the initial snapshot, got {other:?}"),
1543        }
1544    }
1545
1546    #[test]
1547    fn test_kv_cache() {
1548        let rt = Runtime::single_threaded().unwrap();
1549        let rt_clone = rt.clone();
1550        let config = DistributedConfig::from_settings();
1551
1552        rt_clone.primary().block_on(async move {
1553            let drt = DistributedRuntime::new(rt, config).await.unwrap();
1554            test_kv_cache_operations(drt).await.unwrap();
1555        });
1556    }
1557
1558    async fn test_kv_cache_operations(drt: DistributedRuntime) -> Result<()> {
1559        // Make the client and unwrap it
1560        let client = Client::new(ClientOptions::default(), drt.runtime().clone())
1561            .await
1562            .expect("etcd client should be available");
1563
1564        // Create a unique test prefix to avoid conflicts with other tests
1565        let test_id = uuid::Uuid::new_v4().to_string();
1566        let prefix = format!("v1/test_kv_cache_{}/", test_id);
1567
1568        // Initial values
1569        let mut initial_values = HashMap::new();
1570        initial_values.insert("key1".to_string(), b"value1".to_vec());
1571        initial_values.insert("key2".to_string(), b"value2".to_vec());
1572
1573        // Create the KV cache
1574        let kv_cache = KvCache::new(client.clone(), prefix.clone(), initial_values).await?;
1575
1576        // Test get
1577        let value1 = kv_cache.get("key1").await;
1578        assert_eq!(value1, Some(b"value1".to_vec()));
1579
1580        let value2 = kv_cache.get("key2").await;
1581        assert_eq!(value2, Some(b"value2".to_vec()));
1582
1583        // Test get_all
1584        let all_values = kv_cache.get_all().await;
1585        assert_eq!(all_values.len(), 2);
1586        assert_eq!(
1587            all_values.get(&format!("{}key1", prefix)),
1588            Some(&b"value1".to_vec())
1589        );
1590        assert_eq!(
1591            all_values.get(&format!("{}key2", prefix)),
1592            Some(&b"value2".to_vec())
1593        );
1594
1595        // Test put - using None for lease_id
1596        kv_cache.put("key3", b"value3".to_vec(), None).await?;
1597
1598        // Allow some time for the update to propagate
1599        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1600
1601        // Verify the new value
1602        let value3 = kv_cache.get("key3").await;
1603        assert_eq!(value3, Some(b"value3".to_vec()));
1604
1605        // Test update
1606        kv_cache
1607            .put("key1", b"updated_value1".to_vec(), None)
1608            .await?;
1609
1610        // Allow some time for the update to propagate
1611        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1612
1613        // Verify the updated value
1614        let updated_value1 = kv_cache.get("key1").await;
1615        assert_eq!(updated_value1, Some(b"updated_value1".to_vec()));
1616
1617        // Test external update (simulating another client updating a value)
1618        client
1619            .kv_put(
1620                &format!("{}key2", prefix),
1621                b"external_update".to_vec(),
1622                None,
1623            )
1624            .await?;
1625
1626        // Allow some time for the update to propagate
1627        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1628
1629        // Verify the cache was updated
1630        let external_update = kv_cache.get("key2").await;
1631        assert_eq!(external_update, Some(b"external_update".to_vec()));
1632
1633        // Clean up - delete the test keys
1634        let etcd_client = client.etcd_client();
1635        let _ = etcd_client
1636            .kv_client()
1637            .delete(
1638                prefix,
1639                Some(etcd_client::DeleteOptions::new().with_prefix()),
1640            )
1641            .await?;
1642
1643        Ok(())
1644    }
1645}