memtui 0.1.2

An interactive TUI (Terminal User Interface) for browsing and inspecting key-value stores (Redis, Memcached, etc.)
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use super::{
    Backend, BackendCapabilities, BackendError, ConnectionInfo, RawCommandResult, ServerInfo,
};
use crate::types::{BackendType, ConnectionConfig, KeyMetadata, KeyScanResult, Value, ValueType};
use memcache::Client as MemcacheClient;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;

/// Memcached backend implementation
pub struct MemcachedBackend {
    config: ConnectionConfig,
    client: Option<Arc<Mutex<MemcacheClient>>>,
    /// Cache of known keys (memcached doesn't have SCAN)
    key_cache: Arc<Mutex<HashSet<String>>>,
}

impl MemcachedBackend {
    pub fn new(config: ConnectionConfig) -> Self {
        Self {
            config,
            client: None,
            key_cache: Arc::new(Mutex::new(HashSet::new())),
        }
    }

    /// Build Memcached connection URL from config
    fn build_connection_url(&self) -> String {
        // memcache crate uses format: "memcache://host:port"
        format!("memcache://{}:{}", self.config.host, self.config.port)
    }

    /// Get a reference to the client
    fn get_client(&self) -> Result<Arc<Mutex<MemcacheClient>>, BackendError> {
        self.client
            .clone()
            .ok_or_else(|| BackendError::ConnectionError("Not connected".to_string()))
    }

    /// Get list of slab IDs using stats slabs command
    async fn get_slab_ids(&self, host: &str, port: u16) -> Result<Vec<u32>, BackendError> {
        let addr = format!("{}:{}", host, port);
        let mut stream = TcpStream::connect(&addr)
            .await
            .map_err(|e| BackendError::ConnectionError(e.to_string()))?;

        stream
            .write_all(b"stats slabs\r\n")
            .await
            .map_err(|e| BackendError::Internal(e.to_string()))?;

        let mut reader = BufReader::new(stream);
        let mut slab_ids = HashSet::new();
        let mut line = String::new();

        loop {
            line.clear();
            reader
                .read_line(&mut line)
                .await
                .map_err(|e| BackendError::Internal(e.to_string()))?;

            if line.trim() == "END" {
                break;
            }

            // Parse lines like: STAT 1:chunk_size 96
            if line.starts_with("STAT ") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2
                    && let Some(slab_part) = parts[1].split(':').next()
                    && let Ok(slab_id) = slab_part.parse::<u32>()
                {
                    slab_ids.insert(slab_id);
                }
            }
        }

        let mut sorted_slabs: Vec<u32> = slab_ids.into_iter().collect();
        sorted_slabs.sort_unstable();
        Ok(sorted_slabs)
    }

    /// Get keys from a specific slab using stats cachedump
    async fn get_keys_from_slab(
        &self,
        host: &str,
        port: u16,
        slab_id: u32,
        limit: usize,
    ) -> Result<Vec<String>, BackendError> {
        let addr = format!("{}:{}", host, port);
        let mut stream = TcpStream::connect(&addr)
            .await
            .map_err(|e| BackendError::ConnectionError(e.to_string()))?;

        let command = format!("stats cachedump {} {}\r\n", slab_id, limit);
        stream
            .write_all(command.as_bytes())
            .await
            .map_err(|e| BackendError::Internal(e.to_string()))?;

        let mut reader = BufReader::new(stream);
        let mut keys = Vec::new();
        let mut line = String::new();

        loop {
            line.clear();
            reader
                .read_line(&mut line)
                .await
                .map_err(|e| BackendError::Internal(e.to_string()))?;

            if line.trim() == "END" {
                break;
            }

            // Parse lines like: ITEM test [5 b; 0 s]
            if line.starts_with("ITEM ") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    keys.push(parts[1].to_string());
                }
            }
        }

        Ok(keys)
    }
}

#[async_trait::async_trait]
impl Backend for MemcachedBackend {
    fn backend_type(&self) -> BackendType {
        BackendType::Memcached
    }

    fn capabilities(&self) -> BackendCapabilities {
        BackendCapabilities {
            supports_ttl: true,
            supports_scan: true,          // Using stats cachedump
            supports_raw_commands: false, // Limited command support
            supports_batch_get: true,
        }
    }

    async fn connect(&mut self) -> Result<ConnectionInfo, BackendError> {
        let url = self.build_connection_url();

        // Check if auth is provided (not commonly supported by basic memcache clients)
        if self.config.auth.is_some() {
            return Err(BackendError::AuthenticationError(
                "This memcache client does not support SASL authentication".to_string(),
            ));
        }

        let host = self.config.host.clone();
        let port = self.config.port;

        // Connect in a blocking task
        let client = tokio::task::spawn_blocking(move || {
            MemcacheClient::connect(url).map_err(|e| BackendError::ConnectionError(e.to_string()))
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        // Test the connection with version command
        let client_arc = Arc::new(Mutex::new(client));
        let client_clone = client_arc.clone();

        let version = tokio::task::spawn_blocking(move || {
            let client = client_clone
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            client
                .version()
                .map_err(|e| BackendError::ConnectionError(e.to_string()))
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        let version_str = version
            .into_iter()
            .next()
            .map(|(_, v)| v)
            .unwrap_or_else(|| "unknown".to_string());

        self.client = Some(client_arc);

        Ok(ConnectionInfo {
            connected: true,
            server_version: version_str,
            address: format!("{}:{}", host, port),
        })
    }

    async fn disconnect(&mut self) -> Result<(), BackendError> {
        self.client = None;
        if let Ok(mut cache) = self.key_cache.lock() {
            cache.clear();
        }
        Ok(())
    }

    async fn ping(&self) -> Result<Duration, BackendError> {
        let client = self.get_client()?;
        let start = std::time::Instant::now();

        tokio::task::spawn_blocking(move || {
            let client = client
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            client
                .version()
                .map_err(|e| BackendError::ConnectionError(e.to_string()))?;
            Ok::<_, BackendError>(())
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        Ok(start.elapsed())
    }

    async fn info(&self) -> Result<ServerInfo, BackendError> {
        let client = self.get_client()?;

        let stats = tokio::task::spawn_blocking(move || {
            let client = client
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            client
                .stats()
                .map_err(|e| BackendError::Internal(e.to_string()))
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        // Parse stats from memcache
        let first_server_stats =
            stats.into_iter().next().map(|(_, s)| s).ok_or_else(|| {
                BackendError::Internal("No stats returned from server".to_string())
            })?;

        let mut version = String::from("unknown");
        let mut uptime = 0u64;
        let mut memory_used = 0u64;
        let mut memory_max = None;
        let mut clients_connected = 0usize;
        let mut keys_total = 0u64;

        for (key, value) in first_server_stats {
            match key.as_str() {
                "version" => version = value,
                "uptime" => uptime = value.parse().unwrap_or(0),
                "bytes" => memory_used = value.parse().unwrap_or(0),
                "limit_maxbytes" => {
                    let max: u64 = value.parse().unwrap_or(0);
                    if max > 0 {
                        memory_max = Some(max);
                    }
                }
                "curr_connections" => clients_connected = value.parse().unwrap_or(0),
                "curr_items" => keys_total = value.parse().unwrap_or(0),
                _ => {}
            }
        }

        Ok(ServerInfo {
            version,
            uptime: Duration::from_secs(uptime),
            memory_used,
            memory_max,
            clients_connected,
            keys_total,
        })
    }

    async fn scan_keys(
        &self,
        pattern: Option<&str>,
        cursor: Option<String>,
        limit: usize,
    ) -> Result<KeyScanResult, BackendError> {
        // Use Memcached's stats cachedump to list keys
        let host = self.config.host.clone();
        let port = self.config.port;

        // Parse cursor to get current slab_id
        let current_slab: u32 = cursor.as_ref().and_then(|c| c.parse().ok()).unwrap_or(1);

        // Get all slab IDs first
        let slab_ids = self.get_slab_ids(&host, port).await?;

        if slab_ids.is_empty() {
            return Ok(KeyScanResult {
                keys: vec![],
                cursor: None,
                has_more: false,
            });
        }

        // Collect keys from current slab
        let mut all_keys = Vec::new();
        let mut next_slab = None;

        for &slab_id in slab_ids.iter() {
            if slab_id < current_slab {
                continue;
            }

            let keys = self
                .get_keys_from_slab(&host, port, slab_id, limit * 10)
                .await?;

            for key in keys {
                // Apply pattern filter
                let matches = if let Some(p) = pattern {
                    if p == "*" {
                        true
                    } else {
                        // Simple pattern matching
                        key.contains(p.trim_matches('*'))
                    }
                } else {
                    true
                };

                if matches {
                    all_keys.push(key);
                }

                if all_keys.len() >= limit {
                    break;
                }
            }

            if all_keys.len() >= limit {
                // Check if there are more slabs
                if let Some(&next_id) = slab_ids.iter().find(|&&id| id > slab_id) {
                    next_slab = Some(next_id);
                }
                break;
            }
        }

        // Get metadata for keys
        let mut key_metadata = Vec::new();
        for key in all_keys.into_iter().take(limit) {
            match self.key_info(&key).await {
                Ok(metadata) => key_metadata.push(metadata),
                Err(_) => {
                    // Key might have been evicted, but we still want to show it
                    // Create basic metadata without fetching the value
                    key_metadata.push(KeyMetadata {
                        name: key.clone(),
                        value_type: ValueType::String, // Default assumption
                        size_bytes: 0,
                        ttl: None,
                        last_accessed: None,
                        encoding: None,
                    });
                }
            }
        }

        Ok(KeyScanResult {
            keys: key_metadata,
            cursor: next_slab.map(|id| id.to_string()),
            has_more: next_slab.is_some(),
        })
    }

    async fn key_count(&self, _pattern: Option<&str>) -> Result<u64, BackendError> {
        // Get from stats
        let info = self.info().await?;
        Ok(info.keys_total)
    }

    async fn key_info(&self, key: &str) -> Result<KeyMetadata, BackendError> {
        let client = self.get_client()?;
        let key_str = key.to_string();
        let key_cache = self.key_cache.clone();

        let data: Option<Vec<u8>> = tokio::task::spawn_blocking(move || {
            let client = client
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            client
                .get(&key_str)
                .map_err(|e| BackendError::Internal(e.to_string()))
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        if let Some(data) = data {
            let size_bytes = data.len() as u64;

            // Add to key cache
            if let Ok(mut cache) = key_cache.lock() {
                cache.insert(key.to_string());
            }

            // Determine value type
            let value_type = if super::utils::is_json(&data) {
                ValueType::Json
            } else if data.iter().all(|&b| b.is_ascii()) {
                ValueType::String
            } else {
                ValueType::Binary
            };

            Ok(KeyMetadata {
                name: key.to_string(),
                value_type,
                size_bytes,
                ttl: None, // Memcached doesn't expose TTL information
                last_accessed: Some(SystemTime::now()),
                encoding: Some("utf8".to_string()),
            })
        } else {
            Err(BackendError::KeyNotFound(key.to_string()))
        }
    }

    async fn get(&self, key: &str) -> Result<Value, BackendError> {
        let client = self.get_client()?;
        let key_str = key.to_string();
        let key_cache = self.key_cache.clone();

        let data: Option<Vec<u8>> = tokio::task::spawn_blocking(move || {
            let client = client
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            client
                .get(&key_str)
                .map_err(|e| BackendError::Internal(e.to_string()))
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        if let Some(data) = data {
            // Add to key cache
            if let Ok(mut cache) = key_cache.lock() {
                cache.insert(key.to_string());
            }

            // Detect value type
            let value_type = if super::utils::is_json(&data) {
                ValueType::Json
            } else if data.iter().all(|&b| b.is_ascii()) {
                ValueType::String
            } else {
                ValueType::Binary
            };

            Ok(Value {
                data,
                value_type,
                encoding: Some("utf8".to_string()),
            })
        } else {
            Err(BackendError::KeyNotFound(key.to_string()))
        }
    }

    async fn get_many(&self, keys: &[String]) -> Result<Vec<(String, Value)>, BackendError> {
        let client = self.get_client()?;
        let keys = keys.to_vec();
        let key_cache = self.key_cache.clone();

        let results: std::collections::HashMap<String, Vec<u8>> =
            tokio::task::spawn_blocking(move || {
                let client = client
                    .lock()
                    .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;

                let key_refs: Vec<&str> = keys.iter().map(|s| s.as_str()).collect();
                client
                    .gets(&key_refs)
                    .map_err(|e| BackendError::Internal(e.to_string()))
            })
            .await
            .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        // Add all keys to cache
        if let Ok(mut cache) = key_cache.lock() {
            for key in results.keys() {
                cache.insert(key.clone());
            }
        }

        let mut values = Vec::new();
        for (key, data) in results {
            let value_type = if super::utils::is_json(&data) {
                ValueType::Json
            } else if data.iter().all(|&b| b.is_ascii()) {
                ValueType::String
            } else {
                ValueType::Binary
            };

            values.push((
                key,
                Value {
                    data,
                    value_type,
                    encoding: Some("utf8".to_string()),
                },
            ));
        }

        Ok(values)
    }

    async fn set(
        &self,
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
    ) -> Result<(), BackendError> {
        if self.config.read_only {
            return Err(BackendError::ReadOnly);
        }

        let client = self.get_client()?;
        let key = key.to_string();
        let value = value.to_vec();
        let key_cache = self.key_cache.clone();

        let ttl_secs = ttl.map(|d| d.as_secs() as u32).unwrap_or(0);

        tokio::task::spawn_blocking(move || {
            let client = client
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            client
                .set(&key, &value[..], ttl_secs)
                .map_err(|e| BackendError::Internal(e.to_string()))?;

            // Add to key cache
            if let Ok(mut cache) = key_cache.lock() {
                cache.insert(key);
            }

            Ok::<_, BackendError>(())
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        Ok(())
    }

    async fn delete(&self, key: &str) -> Result<bool, BackendError> {
        if self.config.read_only {
            return Err(BackendError::ReadOnly);
        }

        let client = self.get_client()?;
        let key = key.to_string();
        let key_cache = self.key_cache.clone();

        let deleted = tokio::task::spawn_blocking(move || {
            let client = client
                .lock()
                .map_err(|e| BackendError::Internal(format!("Mutex error: {}", e)))?;
            let result = client
                .delete(&key)
                .map_err(|e| BackendError::Internal(e.to_string()))?;

            // Remove from key cache
            if let Ok(mut cache) = key_cache.lock() {
                cache.remove(&key);
            }

            Ok::<bool, BackendError>(result)
        })
        .await
        .map_err(|e| BackendError::Internal(format!("Join error: {}", e)))??;

        Ok(deleted)
    }

    async fn execute_raw(&self, _command: &str) -> Result<RawCommandResult, BackendError> {
        // Memcached doesn't support arbitrary raw commands through this client
        Err(BackendError::NotSupported)
    }
}

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

    fn create_test_config() -> ConnectionConfig {
        ConnectionConfig {
            id: "test".to_string(),
            name: "Test Memcached".to_string(),
            backend_type: BackendType::Memcached,
            host: "localhost".to_string(),
            port: 11211,
            auth: None,
            database: None,
            tls: None,
            timeout: Duration::from_secs(5),
            read_only: false,
        }
    }

    #[test]
    fn test_build_connection_url_basic() {
        let backend = MemcachedBackend::new(create_test_config());
        let url = backend.build_connection_url();
        assert_eq!(url, "memcache://localhost:11211");
    }

    #[test]
    fn test_build_connection_url_custom_port() {
        let mut config = create_test_config();
        config.port = 11212;
        let backend = MemcachedBackend::new(config);
        let url = backend.build_connection_url();
        assert_eq!(url, "memcache://localhost:11212");
    }

    #[test]
    fn test_backend_type() {
        let backend = MemcachedBackend::new(create_test_config());
        assert_eq!(backend.backend_type(), BackendType::Memcached);
    }

    #[test]
    fn test_capabilities() {
        let backend = MemcachedBackend::new(create_test_config());
        let caps = backend.capabilities();
        assert!(caps.supports_ttl);
        assert!(caps.supports_scan); // Using stats cachedump
        assert!(!caps.supports_raw_commands);
        assert!(caps.supports_batch_get);
    }

    #[test]
    fn test_get_client_not_connected() {
        let backend = MemcachedBackend::new(create_test_config());
        let result = backend.get_client();
        assert!(matches!(result, Err(BackendError::ConnectionError(_))));
    }
}