msy 0.4.2

Modern musl rsync alternative - Fast, parallel file synchronization
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
/// SSH sparse file and hard link tests (requires fedora)
///
/// Tests detection of sparse files and hard links via scan() operation.
/// Direct sparse file transfer testing requires access to private methods.
///
/// Run with: cargo test --test ssh_sparse_hardlink_test -- --ignored
///
/// Prerequisites:
/// - fedora accessible via SSH
/// - sy-remote installed on fedora
/// - Filesystem on fedora that supports sparse files (ext4, xfs, btrfs)
///
use std::time::SystemTime;
use tempfile::TempDir;

const FEDORA_HOST: &str = "fedora";
const FEDORA_USER: &str = "nick";

fn create_fedora_config() -> msy::ssh::config::SshConfig {
    use msy::ssh::config::SshConfig;
    let mut config = SshConfig::new(FEDORA_HOST);
    config.user = FEDORA_USER.to_string();
    config.port = 22;
    config
}

fn create_remote_test_path(test_name: &str) -> String {
    format!(
        "/tmp/sy_ssh_sparse_test_{}_{}",
        test_name,
        std::process::id()
    )
}

fn cleanup_remote_path(path: &str) {
    let cleanup_cmd = format!("ssh {} 'rm -rf {}'", FEDORA_HOST, path);
    let _ = std::process::Command::new("sh")
        .arg("-c")
        .arg(&cleanup_cmd)
        .output();
}

// =============================================================================
// SECTION 1: Sparse File Detection via Scan
// =============================================================================

#[tokio::test]
#[ignore]
async fn test_ssh_detect_sparse_file_via_scan() {
    use msy::transport::ssh::SshTransport;
    use msy::transport::Transport;

    let remote_base = create_remote_test_path("sparse_scan");

    // Create sparse file on remote (10MB file with holes)
    // First MB has data, middle 8MB are holes, last MB has data
    let create_cmd = format!(
        "ssh {} 'mkdir -p {} && dd if=/dev/zero of={}/sparse.dat bs=1M count=1 seek=0 2>/dev/null && dd if=/dev/zero of={}/sparse.dat bs=1M count=1 seek=9 conv=notrunc 2>/dev/null'",
        FEDORA_HOST, remote_base, remote_base, remote_base
    );
    std::process::Command::new("sh")
        .arg("-c")
        .arg(&create_cmd)
        .output()
        .expect("Failed to create sparse file");

    let config = create_fedora_config();
    let transport = SshTransport::new(&config).await.expect("Failed to connect");

    // Scan directory to get file entries
    let entries = transport
        .scan(std::path::Path::new(&remote_base))
        .await
        .expect("scan failed");

    // Find sparse file entry
    let sparse_entry = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("sparse.dat"))
        .expect("Sparse file not found");

    println!("Sparse file detected:");
    println!("  Size: {} bytes", sparse_entry.size);
    println!("  Allocated: {} bytes", sparse_entry.allocated_size);
    println!("  Is sparse: {}", sparse_entry.is_sparse);

    // File should be 10MB
    assert_eq!(
        sparse_entry.size,
        10 * 1024 * 1024,
        "File size should be 10MB"
    );

    // Note: sparse detection depends on filesystem support
    if sparse_entry.is_sparse {
        assert!(
            sparse_entry.allocated_size < sparse_entry.size,
            "Sparse file should have allocated_size < size"
        );
        println!("✅ Sparse file detected correctly");
    } else {
        println!("⚠️  Filesystem may not support sparse detection");
    }

    cleanup_remote_path(&remote_base);
    println!("✅ SSH detect_sparse_file_via_scan: PASS");
}

#[tokio::test]
#[ignore]
async fn test_ssh_regular_file_not_sparse() {
    use msy::transport::ssh::SshTransport;
    use msy::transport::Transport;

    let remote_base = create_remote_test_path("regular_file");

    // Create regular (non-sparse) file
    let create_cmd = format!(
        "ssh {} 'mkdir -p {} && dd if=/dev/zero of={}/regular.dat bs=1M count=5 2>/dev/null'",
        FEDORA_HOST, remote_base, remote_base
    );
    std::process::Command::new("sh")
        .arg("-c")
        .arg(&create_cmd)
        .output()
        .expect("Failed to create regular file");

    let config = create_fedora_config();
    let transport = SshTransport::new(&config).await.expect("Failed to connect");

    let entries = transport
        .scan(std::path::Path::new(&remote_base))
        .await
        .expect("scan failed");

    let file_entry = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("regular.dat"))
        .expect("Regular file not found");

    assert_eq!(file_entry.size, 5 * 1024 * 1024);
    assert!(!file_entry.is_sparse, "Regular file should not be sparse");

    cleanup_remote_path(&remote_base);
    println!("✅ SSH regular_file_not_sparse: PASS");
}

// =============================================================================
// SECTION 2: Hard Link Detection via Scan
// =============================================================================

#[tokio::test]
#[ignore]
async fn test_ssh_detect_hardlink_via_scan() {
    use msy::transport::ssh::SshTransport;
    use msy::transport::Transport;

    let remote_base = create_remote_test_path("hardlink_scan");

    // Create file with hard links
    let create_cmd = format!(
        "ssh {} 'mkdir -p {} && echo \"content\" > {}/original.txt && ln {}/original.txt {}/link1.txt && ln {}/original.txt {}/link2.txt'",
        FEDORA_HOST, remote_base, remote_base, remote_base, remote_base, remote_base, remote_base
    );
    std::process::Command::new("sh")
        .arg("-c")
        .arg(&create_cmd)
        .output()
        .expect("Failed to create hard links");

    let config = create_fedora_config();
    let transport = SshTransport::new(&config).await.expect("Failed to connect");

    let entries = transport
        .scan(std::path::Path::new(&remote_base))
        .await
        .expect("scan failed");

    // Find the original file
    let original = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("original.txt"))
        .expect("Original file not found");

    println!("Hard link count (nlink): {}", original.nlink);

    // All three names should point to same file (nlink = 3)
    assert_eq!(original.nlink, 3, "File should have 3 hard links");

    // Verify all three have same inode
    let link1 = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("link1.txt"))
        .expect("Link1 not found");

    let link2 = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("link2.txt"))
        .expect("Link2 not found");

    assert_eq!(
        original.inode, link1.inode,
        "Original and link1 should have same inode"
    );
    assert_eq!(
        original.inode, link2.inode,
        "Original and link2 should have same inode"
    );

    cleanup_remote_path(&remote_base);
    println!("✅ SSH detect_hardlink_via_scan: PASS");
}

#[tokio::test]
#[ignore]
async fn test_ssh_single_file_nlink() {
    use msy::transport::ssh::SshTransport;
    use msy::transport::Transport;

    let remote_base = create_remote_test_path("single_nlink");

    // Create single file (no hard links)
    let create_cmd = format!(
        "ssh {} 'mkdir -p {} && echo \"single\" > {}/single.txt'",
        FEDORA_HOST, remote_base, remote_base
    );
    std::process::Command::new("sh")
        .arg("-c")
        .arg(&create_cmd)
        .output()
        .expect("Failed to create file");

    let config = create_fedora_config();
    let transport = SshTransport::new(&config).await.expect("Failed to connect");

    let entries = transport
        .scan(std::path::Path::new(&remote_base))
        .await
        .expect("scan failed");

    let file = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("single.txt"))
        .expect("File not found");

    assert_eq!(file.nlink, 1, "Single file should have nlink = 1");

    cleanup_remote_path(&remote_base);
    println!("✅ SSH single_file_nlink: PASS");
}

// =============================================================================
// SECTION 3: File Transfer Integrity
// =============================================================================

#[tokio::test]
#[ignore]
async fn test_ssh_transfer_large_file() {
    use msy::transport::ssh::SshTransport;
    use msy::transport::Transport;

    let remote_source = create_remote_test_path("large_transfer");

    // Create 50MB file on remote
    let create_cmd = format!(
        "ssh {} 'dd if=/dev/zero of={} bs=1M count=50 2>/dev/null'",
        FEDORA_HOST, remote_source
    );

    println!("Creating 50MB test file on fedora...");
    std::process::Command::new("sh")
        .arg("-c")
        .arg(&create_cmd)
        .output()
        .expect("Failed to create file");

    let config = create_fedora_config();
    let transport = SshTransport::new(&config).await.expect("Failed to connect");

    let dest_dir = TempDir::new().unwrap();
    let dest_file = dest_dir.path().join("large.dat");

    println!("Downloading 50MB file...");
    let start = std::time::Instant::now();

    let result = transport
        .copy_file_streaming(std::path::Path::new(&remote_source), &dest_file, None)
        .await
        .expect("Transfer failed");

    let duration = start.elapsed();
    let speed_mbps = (50.0 / duration.as_secs_f64()).round();

    assert_eq!(result.bytes_written, 50 * 1024 * 1024);
    assert!(dest_file.exists());

    cleanup_remote_path(&remote_source);
    println!(
        "✅ SSH transfer_large_file: PASS ({:.2}s @ {} MB/s)",
        duration.as_secs_f64(),
        speed_mbps
    );
}

#[tokio::test]
#[ignore]
async fn test_ssh_create_and_verify_hardlink() {
    use msy::transport::ssh::SshTransport;
    use msy::transport::Transport;

    let remote_base = create_remote_test_path("create_hardlink");
    let remote_original = format!("{}/original.txt", remote_base);
    let remote_link = format!("{}/link.txt", remote_base);

    let config = create_fedora_config();
    let transport = SshTransport::new(&config).await.expect("Failed to connect");

    // Create directory
    transport
        .create_dir_all(std::path::Path::new(&remote_base))
        .await
        .expect("create_dir_all failed");

    // Create original file
    transport
        .write_file(
            std::path::Path::new(&remote_original),
            b"hardlink test",
            SystemTime::now(),
        )
        .await
        .expect("write_file failed");

    // Create hard link
    transport
        .create_hardlink(
            std::path::Path::new(&remote_original),
            std::path::Path::new(&remote_link),
        )
        .await
        .expect("create_hardlink failed");

    // Verify both files exist
    let original_exists = transport
        .exists(std::path::Path::new(&remote_original))
        .await
        .expect("exists check failed");
    let link_exists = transport
        .exists(std::path::Path::new(&remote_link))
        .await
        .expect("exists check failed");

    assert!(original_exists, "Original file should exist");
    assert!(link_exists, "Hard link should exist");

    // Verify content is the same
    let original_content = transport
        .read_file(std::path::Path::new(&remote_original))
        .await
        .expect("read_file failed");
    let link_content = transport
        .read_file(std::path::Path::new(&remote_link))
        .await
        .expect("read_file failed");

    assert_eq!(
        original_content, link_content,
        "Hard link content should match"
    );

    // Verify nlink count via scan
    let entries = transport
        .scan(std::path::Path::new(&remote_base))
        .await
        .expect("scan failed");

    let original_entry = entries
        .iter()
        .find(|e| e.path.to_str().unwrap().contains("original.txt"))
        .expect("Original not found");

    assert_eq!(original_entry.nlink, 2, "Should have 2 hard links");

    cleanup_remote_path(&remote_base);
    println!("✅ SSH create_and_verify_hardlink: PASS");
}

// =============================================================================
// Test Summary
// =============================================================================

#[test]
#[ignore]
fn print_sparse_hardlink_test_summary() {
    println!("\n========================================");
    println!("SSH Sparse File & Hard Link Test Suite");
    println!("========================================\n");
    println!("SECTION 1: Sparse File Detection");
    println!("  - detect_sparse_file_via_scan");
    println!("  - regular_file_not_sparse");
    println!("\nSECTION 2: Hard Link Detection");
    println!("  - detect_hardlink_via_scan");
    println!("  - single_file_nlink");
    println!("\nSECTION 3: File Transfer Integrity");
    println!("  - transfer_large_file (50MB)");
    println!("  - create_and_verify_hardlink");
    println!("\nTotal: 6 tests");
    println!("\nRun with:");
    println!("  cargo test --test ssh_sparse_hardlink_test -- --ignored");
    println!("========================================\n");
}