redisctl-core 0.11.0

Core library for Redis CLI tools - config, workflows, and shared logic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Progress tracking and action polling for async Enterprise operations
//!
//! Enterprise API operations that are asynchronous return an `Action` which must be polled
//! until completion. This module provides utilities for that polling
//! with optional progress callbacks for UI updates.

use crate::error::{CoreError, Result};
use redis_enterprise::EnterpriseClient;
use redis_enterprise::actions::Action;
use std::time::{Duration, Instant};

/// Progress events emitted during async Enterprise operations
#[derive(Debug, Clone)]
pub enum EnterpriseProgressEvent {
    /// Action has been created/started
    Started { action_uid: String },
    /// Polling iteration with current status
    Polling {
        /// Action UID being polled.
        action_uid: String,
        /// Current status string (e.g. `"running"`, `"completed"`).
        status: String,
        /// Percent complete as reported by the API.
        ///
        /// Typed as `Option<String>` because the Redis Enterprise REST
        /// API emits this as a string (e.g. `"100"`), not a float.
        /// Callers that need a numeric value can `.parse::<f32>().ok()`.
        progress: Option<String>,
        /// Time since polling started.
        elapsed: Duration,
    },
    /// Action completed successfully
    Completed { action_uid: String },
    /// Action failed
    Failed { action_uid: String, error: String },
}

/// Callback type for Enterprise progress updates
///
/// CLI can use this to update spinners/progress bars.
/// MCP typically doesn't need this.
pub type EnterpriseProgressCallback = Box<dyn Fn(EnterpriseProgressEvent) + Send + Sync>;

/// Poll an Enterprise action until completion
///
/// # Arguments
///
/// * `client` - The Enterprise API client
/// * `action_uid` - The action UID to poll
/// * `timeout` - Maximum time to wait for completion
/// * `interval` - Time between polling attempts
/// * `on_progress` - Optional callback for progress updates
///
/// # Returns
///
/// The completed action, or an error if the action failed or timed out.
///
/// # Example
///
/// ```rust,ignore
/// use redisctl_core::enterprise::{poll_action, EnterpriseProgressEvent};
/// use std::time::Duration;
///
/// // Start an async operation (returns an action_uid)
/// let action_uid = "some-action-uid";
///
/// // Poll with progress callback
/// let completed = poll_action(
///     &client,
///     action_uid,
///     Duration::from_secs(600),
///     Duration::from_secs(5),
///     Some(Box::new(|event| {
///         match event {
///             EnterpriseProgressEvent::Polling { status, progress, elapsed, .. } => {
///                 println!("Status: {} ({:?}%) ({:.0}s)", status, progress, elapsed.as_secs());
///             }
///             EnterpriseProgressEvent::Completed { .. } => {
///                 println!("Done!");
///             }
///             _ => {}
///         }
///     })),
/// ).await?;
/// ```
pub async fn poll_action(
    client: &EnterpriseClient,
    action_uid: &str,
    timeout: Duration,
    interval: Duration,
    on_progress: Option<EnterpriseProgressCallback>,
) -> Result<Action> {
    let start = Instant::now();
    let handler = client.actions();

    emit(
        &on_progress,
        EnterpriseProgressEvent::Started {
            action_uid: action_uid.to_string(),
        },
    );

    loop {
        let elapsed = start.elapsed();
        if elapsed > timeout {
            return Err(CoreError::TaskTimeout(timeout));
        }

        let action = handler.get(action_uid).await?;
        let status = action.status.clone();

        emit(
            &on_progress,
            EnterpriseProgressEvent::Polling {
                action_uid: action_uid.to_string(),
                status: status.clone(),
                progress: action.progress.clone(),
                elapsed,
            },
        );

        match status.as_str() {
            "completed" => {
                emit(
                    &on_progress,
                    EnterpriseProgressEvent::Completed {
                        action_uid: action_uid.to_string(),
                    },
                );
                return Ok(action);
            }
            "failed" | "cancelled" => {
                let error = action
                    .error
                    .clone()
                    .unwrap_or_else(|| format!("Action {}", status));

                emit(
                    &on_progress,
                    EnterpriseProgressEvent::Failed {
                        action_uid: action_uid.to_string(),
                        error: error.clone(),
                    },
                );
                return Err(CoreError::TaskFailed(error));
            }
            // 'queued', 'starting', 'running', 'cancelling' - still in progress
            _ => {
                tokio::time::sleep(interval).await;
            }
        }
    }
}

/// Helper to emit progress events
fn emit(callback: &Option<EnterpriseProgressCallback>, event: EnterpriseProgressEvent) {
    if let Some(cb) = callback {
        cb(event);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::{Arc, Mutex};
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn test_client(uri: String) -> EnterpriseClient {
        EnterpriseClient::builder()
            .base_url(uri)
            .username("test-user".to_string())
            .password("test-pass".to_string())
            .insecure(true)
            .build()
            .unwrap()
    }

    // An action that is already in a terminal "completed" state on the first
    // poll should return Ok immediately.
    #[tokio::test]
    async fn poll_action_immediate_success() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "flush",
                "status": "completed",
                "progress": "100"
            })))
            .mount(&mock_server)
            .await;

        let client = test_client(mock_server.uri());
        let result = poll_action(
            &client,
            "action-1",
            Duration::from_secs(5),
            Duration::from_millis(10),
            None,
        )
        .await;

        match result {
            Ok(action) => assert_eq!(action.status, "completed"),
            other => panic!("expected Ok(completed action), got {other:?}"),
        }
    }

    // An action that reports "running" twice before completing should keep
    // polling and ultimately return Ok.
    #[tokio::test]
    async fn poll_action_polls_then_succeeds() {
        let mock_server = MockServer::start().await;

        // Higher priority (lower number) + a call limit means the "running"
        // response is served for the first two polls, then exhausted.
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "flush",
                "status": "running",
                "progress": "50"
            })))
            .up_to_n_times(2)
            .with_priority(1)
            .mount(&mock_server)
            .await;

        // Default-priority fallback that takes over once the "running" mock is
        // exhausted.
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "flush",
                "status": "completed",
                "progress": "100"
            })))
            .mount(&mock_server)
            .await;

        let client = test_client(mock_server.uri());
        let result = poll_action(
            &client,
            "action-1",
            Duration::from_secs(5),
            Duration::from_millis(10),
            None,
        )
        .await;

        match result {
            Ok(action) => assert_eq!(action.status, "completed"),
            other => panic!("expected Ok(completed action), got {other:?}"),
        }
    }

    // A "failed" status surfaces the action's error message as TaskFailed.
    #[tokio::test]
    async fn poll_action_failure_surfaces_error() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "upgrade",
                "status": "failed",
                "error": "upgrade failed: version conflict"
            })))
            .mount(&mock_server)
            .await;

        let client = test_client(mock_server.uri());
        let result = poll_action(
            &client,
            "action-1",
            Duration::from_secs(5),
            Duration::from_millis(10),
            None,
        )
        .await;

        match result {
            Err(CoreError::TaskFailed(msg)) => {
                assert_eq!(msg, "upgrade failed: version conflict");
            }
            other => panic!("expected TaskFailed, got {other:?}"),
        }
    }

    // A "cancelled" status is also terminal and surfaces as TaskFailed. When no
    // error is provided, the message falls back to the status.
    #[tokio::test]
    async fn poll_action_cancelled_surfaces_as_failed() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "flush",
                "status": "cancelled"
            })))
            .mount(&mock_server)
            .await;

        let client = test_client(mock_server.uri());
        let result = poll_action(
            &client,
            "action-1",
            Duration::from_secs(5),
            Duration::from_millis(10),
            None,
        )
        .await;

        match result {
            Err(CoreError::TaskFailed(msg)) => {
                assert!(msg.contains("cancelled"), "unexpected message: {msg}");
            }
            other => panic!("expected TaskFailed, got {other:?}"),
        }
    }

    // With a 1ms timeout and a never-completing action, the first poll runs,
    // the function sleeps, and the next loop iteration trips the timeout.
    #[tokio::test]
    async fn poll_action_times_out() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "flush",
                "status": "running",
                "progress": "10"
            })))
            .mount(&mock_server)
            .await;

        let client = test_client(mock_server.uri());
        let result = poll_action(
            &client,
            "action-1",
            Duration::from_millis(1),
            Duration::from_millis(5),
            None,
        )
        .await;

        match result {
            Err(CoreError::TaskTimeout(_)) => {}
            other => panic!("expected TaskTimeout, got {other:?}"),
        }
    }

    // The progress callback must observe the lifecycle: Started, at least one
    // Polling event, and Completed.
    #[tokio::test]
    async fn poll_action_emits_progress_events() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/actions/action-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "action_uid": "action-1",
                "name": "flush",
                "status": "completed",
                "progress": "100"
            })))
            .mount(&mock_server)
            .await;

        let events: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&events);
        let callback: EnterpriseProgressCallback = Box::new(move |event| {
            let label = match event {
                EnterpriseProgressEvent::Started { .. } => "started",
                EnterpriseProgressEvent::Polling { .. } => "polling",
                EnterpriseProgressEvent::Completed { .. } => "completed",
                EnterpriseProgressEvent::Failed { .. } => "failed",
            };
            sink.lock().unwrap().push(label.to_string());
        });

        let client = test_client(mock_server.uri());
        let result = poll_action(
            &client,
            "action-1",
            Duration::from_secs(5),
            Duration::from_millis(10),
            Some(callback),
        )
        .await;

        assert!(result.is_ok(), "expected Ok, got {result:?}");

        let observed = events.lock().unwrap();
        assert!(observed.contains(&"started".to_string()), "{observed:?}");
        assert!(observed.contains(&"polling".to_string()), "{observed:?}");
        assert!(observed.contains(&"completed".to_string()), "{observed:?}");
    }
}