s3tui 0.5.0

Simple TUI application for multiple s3 account 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
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
//! Integration tests for S3-compatible storage using MinIO
//!
//! These tests require Docker to be running. They spin up a MinIO container
//! and test the S3DataFetcher against it.
//!
//! Run with: cargo test --test s3_compat_tests -- --ignored

use futures::future::join_all;
use s3tui::model::local_selected_item::LocalSelectedItem;
use s3tui::model::s3_selected_item::S3SelectedItem;
use s3tui::model::transfer_state::TransferState;
use s3tui::services::s3_data_fetcher::S3DataFetcher;
use s3tui::settings::file_credentials::FileCredential;
use std::io::Write;
use tempfile::NamedTempFile;
use testcontainers::runners::AsyncRunner;
use testcontainers::ContainerAsync;
use testcontainers_modules::minio::MinIO;
use tokio::sync::mpsc;

/// Default MinIO minio
const MINIO_ACCESS_KEY: &str = "minioadmin";
const MINIO_SECRET_KEY: &str = "minioadmin";

/// Create a FileCredential configured for a MinIO container
fn create_minio_credential(port: u16) -> FileCredential {
    FileCredential {
        name: "minio-test".to_string(),
        access_key: MINIO_ACCESS_KEY.to_string(),
        secret_key: MINIO_SECRET_KEY.to_string(),
        default_region: "us-east-1".to_string(),
        selected: true,
        endpoint_url: Some(format!("http://127.0.0.1:{}", port)),
        force_path_style: true,
    }
}

/// Start a MinIO container and return it along with configured minio
async fn setup_minio() -> (ContainerAsync<MinIO>, FileCredential) {
    let container = MinIO::default()
        .start()
        .await
        .expect("Failed to start MinIO container");

    let port = container
        .get_host_port_ipv4(9000)
        .await
        .expect("Failed to get MinIO port");

    let creds = create_minio_credential(port);
    (container, creds)
}

/// Create a test file with specified content
fn create_test_file(content: &[u8]) -> NamedTempFile {
    let mut file = NamedTempFile::new().expect("Failed to create temp file");
    file.write_all(content).expect("Failed to write to temp file");
    file.flush().expect("Failed to flush temp file");
    file
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_minio_list_buckets() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds);

    // List buckets - should be empty initially
    let buckets = fetcher
        .list_current_location(None, None)
        .await
        .expect("Failed to list buckets");
    assert!(buckets.is_empty(), "Expected no buckets initially");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_minio_create_and_list_bucket() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds);

    // Create a bucket
    let bucket_name = "test-bucket";
    let result = fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");
    assert!(result.is_none(), "Expected no error creating bucket");

    // List buckets - should have one bucket now
    let buckets = fetcher
        .list_current_location(None, None)
        .await
        .expect("Failed to list buckets");
    assert_eq!(buckets.len(), 1, "Expected one bucket");
    assert_eq!(buckets[0].name, bucket_name);
    assert!(buckets[0].is_bucket, "Expected item to be a bucket");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_minio_upload_and_list_objects() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a bucket
    let bucket_name = "upload-test-bucket";
    fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");

    // Create a test file
    let test_content = b"Hello, MinIO!";
    let test_file = create_test_file(test_content);
    let file_path = test_file.path().to_str().unwrap().to_string();

    // Create upload progress channel
    let (tx, mut rx) = mpsc::channel(100);

    // Create LocalSelectedItem for upload
    let upload_item = LocalSelectedItem {
        name: "test-file.txt".to_string(),
        path: file_path,
        is_directory: false,
        destination_bucket: bucket_name.to_string(),
        destination_path: "test-file.txt".to_string(),
        s3_creds: creds.clone(),
        children: None,
        transfer_state: TransferState::Pending,
        job_id: None,
    };

    // Upload the file
    let result = fetcher.upload_item(upload_item, tx, None).await;
    assert!(result.is_ok(), "Upload should succeed");

    // Drain the progress channel
    rx.close();
    while rx.recv().await.is_some() {}

    // List objects in bucket
    let objects = fetcher
        .list_current_location(Some(bucket_name.to_string()), None)
        .await
        .expect("Failed to list objects");

    assert_eq!(objects.len(), 1, "Expected one object");
    assert_eq!(objects[0].name, "test-file.txt");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_minio_upload_and_download() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a bucket
    let bucket_name = "download-test-bucket";
    fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");

    // Create a test file with known content
    let test_content = b"Test content for download verification";
    let test_file = create_test_file(test_content);
    let file_path = test_file.path().to_str().unwrap().to_string();

    // Upload progress channel
    let (upload_tx, mut upload_rx) = mpsc::channel(100);

    // Create LocalSelectedItem for upload
    let upload_item = LocalSelectedItem {
        name: "download-test.txt".to_string(),
        path: file_path,
        is_directory: false,
        destination_bucket: bucket_name.to_string(),
        destination_path: "download-test.txt".to_string(),
        s3_creds: creds.clone(),
        children: None,
        transfer_state: TransferState::Pending,
        job_id: None,
    };

    // Upload
    fetcher
        .upload_item(upload_item, upload_tx, None)
        .await
        .expect("Upload failed");

    // Drain upload progress channel
    upload_rx.close();
    while upload_rx.recv().await.is_some() {}

    // Create temp directory for download
    let download_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let download_path = download_dir.path().to_str().unwrap().to_string();

    // Download progress channel
    let (download_tx, mut download_rx) = mpsc::channel(100);

    // Create S3SelectedItem for download
    let download_item = S3SelectedItem {
        bucket: Some(bucket_name.to_string()),
        name: "download-test.txt".to_string(),
        path: Some("download-test.txt".to_string()),
        is_directory: false,
        is_bucket: false,
        destination_dir: download_path.clone(),
        s3_creds: creds,
        children: None,
        transfer_state: TransferState::Pending,
        job_id: None,
    };

    // Download
    fetcher
        .download_item(download_item, download_tx, None)
        .await
        .expect("Download failed");

    // Drain download progress channel
    download_rx.close();
    while download_rx.recv().await.is_some() {}

    // Verify downloaded content
    let downloaded_content =
        std::fs::read(format!("{}/download-test.txt", download_path)).expect("Failed to read downloaded file");
    assert_eq!(
        downloaded_content, test_content,
        "Downloaded content should match original"
    );
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_minio_delete_object() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a bucket
    let bucket_name = "delete-test-bucket";
    fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");

    // Create and upload a test file
    let test_file = create_test_file(b"Delete me");
    let file_path = test_file.path().to_str().unwrap().to_string();

    let (tx, mut rx) = mpsc::channel(100);

    let upload_item = LocalSelectedItem {
        name: "to-delete.txt".to_string(),
        path: file_path,
        is_directory: false,
        destination_bucket: bucket_name.to_string(),
        destination_path: "to-delete.txt".to_string(),
        s3_creds: creds.clone(),
        children: None,
        transfer_state: TransferState::Pending,
        job_id: None,
    };

    fetcher.upload_item(upload_item, tx, None).await.expect("Upload failed");
    rx.close();
    while rx.recv().await.is_some() {}

    // Verify object exists
    let objects_before = fetcher
        .list_current_location(Some(bucket_name.to_string()), None)
        .await
        .expect("Failed to list objects");
    assert_eq!(objects_before.len(), 1);

    // Delete the object
    let delete_result = fetcher
        .delete_data(false, Some(bucket_name.to_string()), "to-delete.txt".to_string(), false)
        .await
        .expect("Delete failed");
    assert!(delete_result.is_none(), "Expected no error on delete");

    // Verify object is gone
    let objects_after = fetcher
        .list_current_location(Some(bucket_name.to_string()), None)
        .await
        .expect("Failed to list objects");
    assert!(objects_after.is_empty(), "Object should be deleted");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_minio_list_objects_with_prefix() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a bucket
    let bucket_name = "prefix-test-bucket";
    fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");

    // Upload files with different prefixes
    let files = vec![
        ("folder1/file1.txt", b"content1" as &[u8]),
        ("folder1/file2.txt", b"content2"),
        ("folder2/file3.txt", b"content3"),
        ("root-file.txt", b"root content"),
    ];

    for (key, content) in files {
        let test_file = create_test_file(content);
        let file_path = test_file.path().to_str().unwrap().to_string();
        let (tx, mut rx) = mpsc::channel(100);

        let upload_item = LocalSelectedItem {
            name: key.split('/').last().unwrap().to_string(),
            path: file_path,
            is_directory: false,
            destination_bucket: bucket_name.to_string(),
            destination_path: key.to_string(),
            s3_creds: creds.clone(),
            children: None,
            transfer_state: TransferState::Pending,
            job_id: None,
        };

        fetcher.upload_item(upload_item, tx, None).await.expect("Upload failed");
        rx.close();
        while rx.recv().await.is_some() {}
    }

    // List all objects at root level
    let all_objects = fetcher
        .list_current_location(Some(bucket_name.to_string()), None)
        .await
        .expect("Failed to list objects");

    // Should have 2 "folders" (prefixes) and 1 root file at root level
    // MinIO returns common prefixes as directories
    assert!(
        all_objects.len() >= 2,
        "Expected at least 2 items at root level, got {}",
        all_objects.len()
    );

    // List objects in folder1/
    let folder1_objects = fetcher
        .list_current_location(Some(bucket_name.to_string()), Some("folder1/".to_string()))
        .await
        .expect("Failed to list folder1 objects");
    assert_eq!(folder1_objects.len(), 2, "Expected 2 files in folder1/");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_concurrent_transfers() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a bucket
    let bucket_name = "concurrent-test-bucket";
    fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");

    // Create multiple test files - keep them alive until uploads complete
    let file_count = 5;
    let mut temp_files = Vec::new();
    let mut handles = Vec::new();

    for i in 0..file_count {
        let content = format!("Content for file {}", i);
        let test_file = create_test_file(content.as_bytes());
        let file_path = test_file.path().to_str().unwrap().to_string();
        temp_files.push(test_file); // Keep temp file alive

        let creds_clone = creds.clone();
        let bucket = bucket_name.to_string();
        let fetcher_clone = S3DataFetcher::new(creds_clone.clone());

        // Spawn concurrent upload tasks
        let handle = tokio::spawn(async move {
            let (tx, mut rx) = mpsc::channel(100);

            let upload_item = LocalSelectedItem {
                name: format!("concurrent-file-{}.txt", i),
                path: file_path,
                is_directory: false,
                destination_bucket: bucket,
                destination_path: format!("concurrent-file-{}.txt", i),
                s3_creds: creds_clone,
                children: None,
                transfer_state: TransferState::Pending,
                job_id: None,
            };

            let result = fetcher_clone.upload_item(upload_item, tx, None).await;
            rx.close();
            while rx.recv().await.is_some() {}
            result
        });

        handles.push(handle);
    }

    // Wait for all uploads to complete
    let results: Vec<_> = join_all(handles).await;

    // Verify all uploads succeeded
    for (i, result) in results.into_iter().enumerate() {
        assert!(
            result.is_ok(),
            "Task {} should not panic",
            i
        );
        assert!(
            result.unwrap().is_ok(),
            "Upload {} should succeed",
            i
        );
    }

    // Verify all files are in the bucket
    let objects = fetcher
        .list_current_location(Some(bucket_name.to_string()), None)
        .await
        .expect("Failed to list objects");

    assert_eq!(
        objects.len(),
        file_count,
        "Expected {} objects, got {}",
        file_count,
        objects.len()
    );
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_error_recovery_nonexistent_bucket() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Try to list objects in a non-existent bucket
    let result = fetcher
        .list_current_location(Some("nonexistent-bucket".to_string()), None)
        .await;

    // Should return an error, not panic
    assert!(result.is_err(), "Listing non-existent bucket should fail gracefully");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_error_recovery_upload_to_nonexistent_bucket() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a test file
    let test_file = create_test_file(b"Test content");
    let file_path = test_file.path().to_str().unwrap().to_string();

    let (tx, mut rx) = mpsc::channel(100);

    let upload_item = LocalSelectedItem {
        name: "test-file.txt".to_string(),
        path: file_path,
        is_directory: false,
        destination_bucket: "nonexistent-bucket".to_string(),
        destination_path: "test-file.txt".to_string(),
        s3_creds: creds,
        children: None,
        transfer_state: TransferState::Pending,
        job_id: None,
    };

    // Upload should fail gracefully
    let result = fetcher.upload_item(upload_item, tx, None).await;
    rx.close();
    while rx.recv().await.is_some() {}

    assert!(result.is_err(), "Upload to non-existent bucket should fail gracefully");
}

#[tokio::test]
#[ignore] // Requires Docker
async fn test_error_recovery_download_nonexistent_object() {
    let (_container, creds) = setup_minio().await;
    let fetcher = S3DataFetcher::new(creds.clone());

    // Create a bucket
    let bucket_name = "error-recovery-bucket";
    fetcher
        .create_bucket(bucket_name.to_string(), "us-east-1".to_string())
        .await
        .expect("Failed to create bucket");

    // Create temp directory for download
    let download_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let download_path = download_dir.path().to_str().unwrap().to_string();

    let (tx, mut rx) = mpsc::channel(100);

    // Try to download a non-existent object
    let download_item = S3SelectedItem {
        bucket: Some(bucket_name.to_string()),
        name: "nonexistent-file.txt".to_string(),
        path: Some("nonexistent-file.txt".to_string()),
        is_directory: false,
        is_bucket: false,
        destination_dir: download_path,
        s3_creds: creds,
        children: None,
        transfer_state: TransferState::Pending,
        job_id: None,
    };

    let result = fetcher.download_item(download_item, tx, None).await;
    rx.close();
    while rx.recv().await.is_some() {}

    assert!(result.is_err(), "Download of non-existent object should fail gracefully");
}