operations.rs 8.22 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// SPDX-License-Identifier: Apache-2.0

//! Operation execution with automatic retry and reconnection.
//!
//! Wraps etcd operations to handle transient connection failures transparently.

use crate::peer::{DiscoveryError, DiscoveryQueryError};
use crate::systems::etcd::client::Client;
use crate::systems::etcd::error::{EtcdErrorClass, classify_error};
use anyhow::Result;
use futures::future::BoxFuture;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Executes etcd operations with automatic reconnection on transient errors.
#[derive(Clone)]
pub struct OperationExecutor {
    client: Arc<Client>,
    default_timeout: Duration,
    max_retries: u32,
}

impl OperationExecutor {
    /// Create a new operation executor.
    pub fn new(client: Arc<Client>, default_timeout: Duration, max_retries: u32) -> Self {
        Self {
            client,
            default_timeout,
            max_retries,
        }
    }

    /// Execute a query operation with automatic retry on reconnectable errors.
    ///
    /// # Arguments
    ///
    /// * `op` - Function that performs the etcd operation given a client
    ///
    /// # Returns
    ///
    /// * `Ok(T)` - Operation succeeded
    /// * `Err(DiscoveryQueryError::NotFound)` - Key not found (expected)
    /// * `Err(DiscoveryQueryError::Backend)` - Fatal error or timeout
    ///
    /// # Behavior
    ///
    /// 1. Acquire client (brief RwLock read)
    /// 2. Execute operation
    /// 3. On reconnectable error:
    ///    - Trigger reconnection via `ensure_connected()`
    ///    - Retry operation
    /// 4. On NotFound: return DiscoveryQueryError::NotFound
    /// 5. On Fatal error: return DiscoveryQueryError::Backend
    pub async fn execute_query<F, T>(&self, op: F) -> Result<T, DiscoveryQueryError>
    where
        F: Fn(etcd_client::Client) -> BoxFuture<'static, Result<T, etcd_client::Error>>,
    {
        let deadline = Instant::now() + self.default_timeout;
        let mut retry_count = 0;

        loop {
            // Check deadline
            if Instant::now() >= deadline {
                return Err(DiscoveryQueryError::Backend(Arc::new(anyhow::anyhow!(
                    "Operation timed out after {:?}",
                    self.default_timeout
                ))));
            }

            // Await any in-progress reconnection (lightweight check)
            if let Err(e) = self.client.ensure_connected(deadline, false).await {
                return Err(DiscoveryQueryError::Backend(Arc::new(e)));
            }

            // Acquire client (brief lock)
            let client = self.client.get_client();

            // Execute operation
            match op(client).await {
                Ok(result) => {
                    return Ok(result);
                }
                Err(err) => {
                    // Classify the error to determine action
                    match classify_error(err) {
                        EtcdErrorClass::Reconnectable(kind) => {
                            retry_count += 1;
                            if retry_count >= self.max_retries {
                                tracing::error!(
                                    "Max retries ({}) exceeded for reconnectable error: {:?}",
                                    self.max_retries,
                                    kind
                                );
                                return Err(DiscoveryQueryError::Backend(Arc::new(
                                    anyhow::anyhow!("Max retries exceeded: {}", kind),
                                )));
                            }

                            tracing::debug!(
                                "Reconnectable error (attempt {}/{}): {:?}, retrying...",
                                retry_count,
                                self.max_retries,
                                kind
                            );

                            // Trigger reconnection (force=true)
                            if let Err(e) = self.client.ensure_connected(deadline, true).await {
                                tracing::error!("Failed to reconnect: {}", e);
                                return Err(DiscoveryQueryError::Backend(Arc::new(e)));
                            }

                            // Loop will retry operation
                            continue;
                        }
                        EtcdErrorClass::NotFound => {
                            return Err(DiscoveryQueryError::NotFound);
                        }
                        EtcdErrorClass::Fatal(e) => {
                            return Err(DiscoveryQueryError::Backend(Arc::new(e)));
                        }
                    }
                }
            }
        }
    }

    /// Execute a write operation (register/unregister) with automatic retry.
    ///
    /// Similar to `execute_query` but returns `DiscoveryError` instead.
    pub async fn execute_write<F>(&self, op: F) -> Result<(), DiscoveryError>
    where
        F: Fn(etcd_client::Client) -> BoxFuture<'static, Result<(), etcd_client::Error>>,
    {
        let deadline = Instant::now() + self.default_timeout;
        let mut retry_count = 0;

        loop {
            // Check deadline
            if Instant::now() >= deadline {
                return Err(DiscoveryError::Backend(anyhow::anyhow!(
                    "Operation timed out after {:?}",
                    self.default_timeout
                )));
            }

            // Await any in-progress reconnection (lightweight check)
            if let Err(e) = self.client.ensure_connected(deadline, false).await {
                return Err(DiscoveryError::Backend(e));
            }

            // Acquire client (brief lock)
            let client = self.client.get_client();

            // Execute operation
            match op(client).await {
                Ok(()) => {
                    return Ok(());
                }
                Err(err) => {
                    // Classify the error to determine action
                    match classify_error(err) {
                        EtcdErrorClass::Reconnectable(kind) => {
                            retry_count += 1;
                            if retry_count >= self.max_retries {
                                tracing::error!(
                                    "Max retries ({}) exceeded for reconnectable error: {:?}",
                                    self.max_retries,
                                    kind
                                );
                                return Err(DiscoveryError::Backend(anyhow::anyhow!(
                                    "Max retries exceeded: {}",
                                    kind
                                )));
                            }

                            tracing::debug!(
                                "Reconnectable error (attempt {}/{}): {:?}, retrying...",
                                retry_count,
                                self.max_retries,
                                kind
                            );

                            // Trigger reconnection (force=true)
                            if let Err(e) = self.client.ensure_connected(deadline, true).await {
                                tracing::error!("Failed to reconnect: {}", e);
                                return Err(DiscoveryError::Backend(e));
                            }

                            // Loop will retry operation
                            continue;
                        }
                        EtcdErrorClass::NotFound => {
                            // For writes, NotFound might be valid (e.g., deleting non-existent key)
                            // Treat as success
                            tracing::debug!("Write operation: key not found (treating as success)");
                            return Ok(());
                        }
                        EtcdErrorClass::Fatal(e) => {
                            return Err(DiscoveryError::Backend(e));
                        }
                    }
                }
            }
        }
    }

    /// Get the underlying client reference.
    #[allow(dead_code)]
    pub fn client(&self) -> &Arc<Client> {
        &self.client
    }
}