rabbitmq-backup-core 0.1.0

Core engine for RabbitMQ backup and restore operations
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
406
407
408
409
410
//! RabbitMQ Management HTTP API client.

use tracing::{debug, info};

use url::form_urlencoded;

use crate::config::{QueueSelection, QueueType, SourceConfig};
use crate::definitions::types::{ClusterOverview, QueueInfo, RabbitMqDefinitions};
use crate::error::{Error, Result};

/// Client for the RabbitMQ Management HTTP API.
pub struct ManagementClient {
    client: reqwest::Client,
    base_url: String,
    username: String,
    password: String,
}

impl ManagementClient {
    /// Create a new Management API client from source configuration.
    pub fn from_config(source: &SourceConfig) -> Result<Self> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| Error::ManagementApi(format!("Failed to create HTTP client: {}", e)))?;

        Ok(Self {
            client,
            base_url: source.management_url.trim_end_matches('/').to_string(),
            username: source.management_username.clone(),
            password: source.management_password.clone(),
        })
    }

    /// Create a new Management API client with explicit credentials.
    pub fn new(base_url: &str, username: &str, password: &str) -> Result<Self> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| Error::ManagementApi(format!("Failed to create HTTP client: {}", e)))?;

        Ok(Self {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            username: username.to_string(),
            password: password.to_string(),
        })
    }

    /// Get cluster overview information.
    pub async fn get_overview(&self) -> Result<ClusterOverview> {
        let url = format!("{}/api/overview", self.base_url);
        debug!("Fetching cluster overview from {}", url);

        let resp = self
            .client
            .get(&url)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to fetch overview: {}", e)))?;

        if !resp.status().is_success() {
            return Err(Error::ManagementApi(format!(
                "Overview request failed with status {}",
                resp.status()
            )));
        }

        resp.json()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to parse overview: {}", e)))
    }

    /// Export all definitions (or per-vhost).
    pub async fn export_definitions(&self, vhost: Option<&str>) -> Result<RabbitMqDefinitions> {
        let url = match vhost {
            Some(vh) => format!("{}/api/definitions/{}", self.base_url, url_encode(vh)),
            None => format!("{}/api/definitions", self.base_url),
        };
        info!("Exporting definitions from {}", url);

        let resp = self
            .client
            .get(&url)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to export definitions: {}", e)))?;

        if !resp.status().is_success() {
            return Err(Error::ManagementApi(format!(
                "Definitions export failed with status {}",
                resp.status()
            )));
        }

        resp.json()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to parse definitions: {}", e)))
    }

    /// Import definitions to the cluster.
    pub async fn import_definitions(&self, definitions: &RabbitMqDefinitions) -> Result<()> {
        let url = format!("{}/api/definitions", self.base_url);
        info!("Importing definitions to {}", url);

        let resp = self
            .client
            .post(&url)
            .basic_auth(&self.username, Some(&self.password))
            .json(definitions)
            .send()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to import definitions: {}", e)))?;

        if !resp.status().is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::ManagementApi(format!(
                "Definitions import failed: {}",
                body
            )));
        }

        info!("Definitions imported successfully");
        Ok(())
    }

    /// List all queues, optionally filtered by vhost.
    pub async fn list_queues(&self, vhost: Option<&str>) -> Result<Vec<QueueInfo>> {
        let url = match vhost {
            Some(vh) => format!("{}/api/queues/{}", self.base_url, url_encode(vh)),
            None => format!("{}/api/queues", self.base_url),
        };
        debug!("Listing queues from {}", url);

        let resp = self
            .client
            .get(&url)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to list queues: {}", e)))?;

        if !resp.status().is_success() {
            return Err(Error::ManagementApi(format!(
                "Queue list failed with status {}",
                resp.status()
            )));
        }

        resp.json()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to parse queue list: {}", e)))
    }

    /// Discover queues matching the selection criteria.
    pub async fn discover_queues(&self, selection: &QueueSelection) -> Result<Vec<QueueInfo>> {
        // Fetch all queues, filtering by vhost if specified
        let mut all_queues = if selection.vhosts.is_empty() {
            self.list_queues(None).await?
        } else {
            let mut queues = Vec::new();
            for vhost in &selection.vhosts {
                queues.extend(self.list_queues(Some(vhost)).await?);
            }
            queues
        };

        let initial_count = all_queues.len();

        // Apply include patterns (if any)
        if !selection.include.is_empty() {
            all_queues.retain(|q| {
                selection
                    .include
                    .iter()
                    .any(|pattern| glob_matches(pattern, &q.name))
            });
        }

        // Apply exclude patterns
        if !selection.exclude.is_empty() {
            all_queues.retain(|q| {
                !selection
                    .exclude
                    .iter()
                    .any(|pattern| glob_matches(pattern, &q.name))
            });
        }

        // Filter by queue type
        if !selection.types.is_empty() {
            all_queues.retain(|q| {
                selection.types.iter().any(|t| {
                    let type_str = match t {
                        QueueType::Classic => "classic",
                        QueueType::Quorum => "quorum",
                        QueueType::Stream => "stream",
                    };
                    q.queue_type == type_str
                })
            });
        }

        // Filter by minimum messages
        if selection.min_messages > 0 {
            all_queues.retain(|q| q.messages >= selection.min_messages);
        }

        info!(
            "Discovered {} queues (filtered from {} total)",
            all_queues.len(),
            initial_count
        );

        Ok(all_queues)
    }

    /// Get info for a single queue.
    pub async fn get_queue(&self, vhost: &str, name: &str) -> Result<QueueInfo> {
        let url = format!(
            "{}/api/queues/{}/{}",
            self.base_url,
            url_encode(vhost),
            url_encode(name)
        );

        let resp = self
            .client
            .get(&url)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to get queue {}: {}", name, e)))?;

        if !resp.status().is_success() {
            return Err(Error::ManagementApi(format!(
                "Queue {} not found (status {})",
                name,
                resp.status()
            )));
        }

        resp.json()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to parse queue info: {}", e)))
    }

    /// Check whether a queue exists.
    pub async fn queue_exists(&self, vhost: &str, name: &str) -> Result<bool> {
        let url = format!(
            "{}/api/queues/{}/{}",
            self.base_url,
            url_encode(vhost),
            url_encode(name)
        );

        let resp = self
            .client
            .get(&url)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await
            .map_err(|e| Error::ManagementApi(format!("Failed to get queue {}: {}", name, e)))?;

        if resp.status().is_success() {
            return Ok(true);
        }

        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(false);
        }

        Err(Error::ManagementApi(format!(
            "Queue {} existence check failed with status {}",
            name,
            resp.status()
        )))
    }

    /// Declare a durable queue with safe restore defaults.
    pub async fn declare_queue(
        &self,
        vhost: &str,
        name: &str,
        queue_type: QueueType,
    ) -> Result<()> {
        let url = format!(
            "{}/api/queues/{}/{}",
            self.base_url,
            url_encode(vhost),
            url_encode(name)
        );

        let arguments = match queue_type {
            QueueType::Classic => serde_json::json!({}),
            QueueType::Quorum => serde_json::json!({"x-queue-type": "quorum"}),
            QueueType::Stream => serde_json::json!({"x-queue-type": "stream"}),
        };

        let resp = self
            .client
            .put(&url)
            .basic_auth(&self.username, Some(&self.password))
            .json(&serde_json::json!({
                "durable": true,
                "auto_delete": false,
                "arguments": arguments,
            }))
            .send()
            .await
            .map_err(|e| {
                Error::ManagementApi(format!("Failed to declare queue {}: {}", name, e))
            })?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::ManagementApi(format!(
                "Queue {} declaration failed with status {}: {}",
                name, status, body
            )));
        }

        info!("Declared missing queue {}/{}", vhost, name);
        Ok(())
    }
}

/// URL-encode a string for use in API paths (e.g., vhost "/" → "%2F").
fn url_encode(s: &str) -> String {
    form_urlencoded::byte_serialize(s.as_bytes()).collect()
}

/// Simple glob pattern matching supporting `*` and `?` wildcards.
fn glob_matches(pattern: &str, text: &str) -> bool {
    let pattern_chars: Vec<char> = pattern.chars().collect();
    let text_chars: Vec<char> = text.chars().collect();
    glob_match_recursive(&pattern_chars, &text_chars, 0, 0)
}

fn glob_match_recursive(pattern: &[char], text: &[char], pi: usize, ti: usize) -> bool {
    if pi == pattern.len() && ti == text.len() {
        return true;
    }
    if pi == pattern.len() {
        return false;
    }

    match pattern[pi] {
        '*' => {
            // Match zero or more characters
            for i in ti..=text.len() {
                if glob_match_recursive(pattern, text, pi + 1, i) {
                    return true;
                }
            }
            false
        }
        '?' => {
            // Match exactly one character
            if ti < text.len() {
                glob_match_recursive(pattern, text, pi + 1, ti + 1)
            } else {
                false
            }
        }
        c => {
            if ti < text.len() && text[ti] == c {
                glob_match_recursive(pattern, text, pi + 1, ti + 1)
            } else {
                false
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_glob_matches_exact() {
        assert!(glob_matches("hello", "hello"));
        assert!(!glob_matches("hello", "world"));
    }

    #[test]
    fn test_glob_matches_star() {
        assert!(glob_matches("orders-*", "orders-queue"));
        assert!(glob_matches("orders-*", "orders-"));
        assert!(!glob_matches("orders-*", "payments-queue"));
        assert!(glob_matches("*-dead-letter", "orders-dead-letter"));
        assert!(glob_matches("*", "anything"));
    }

    #[test]
    fn test_glob_matches_question() {
        assert!(glob_matches("queue-?", "queue-1"));
        assert!(!glob_matches("queue-?", "queue-12"));
    }

    #[test]
    fn test_glob_matches_combined() {
        assert!(glob_matches("*-retry-*", "orders-retry-3"));
        assert!(glob_matches("*-retry-*", "payments-retry-queue"));
        assert!(!glob_matches("*-retry-*", "orders-queue"));
    }
}