heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
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
//! QUIC Incremental Sync Test using builder pattern
//!
//! This test:
//! 1. Creates a new Heroforge repository from scratch
//! 2. Adds 1000 files and commits
//! 3. Syncs to a destination repo via QUIC
//! 4. Verifies all 1000 files are present
//! 5. Modifies 4 files in the source
//! 6. Syncs again and verifies only 4 artifacts are transferred
//!
//! Usage:
//!   cargo run --example quic_incremental_sync_test --features sync-quic --release

use heroforge_core::sync::quic::{QuicClient, QuicServer};
use heroforge_core::Repository;
use std::path::Path;
use std::time::Instant;
use tokio::runtime::Runtime;

const NUM_FILES: usize = 1000;
const NUM_MODIFIED: usize = 4;

fn main() {
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║       QUIC Incremental Sync Test - heroforge               ║");
    println!("╚════════════════════════════════════════════════════════════╝\n");

    let test_dir = Path::new("/tmp/quic_incremental_test");

    // Clean up
    if test_dir.exists() {
        std::fs::remove_dir_all(test_dir).expect("Failed to clean up");
    }
    std::fs::create_dir_all(test_dir).expect("Failed to create test dir");

    let source_path = test_dir.join("source.forge");
    let dest_path = test_dir.join("dest.forge");

    // ========================================
    // Step 1: Create source repository with 1000 files
    // ========================================
    println!(
        "=== Step 1: Creating source repository with {} files ===\n",
        NUM_FILES
    );

    let start = Instant::now();
    let source_repo = Repository::init(&source_path).expect("Failed to init source repo");

    // Create initial check-in using builder pattern
    let init_hash = source_repo
        .commit_builder()
        .message("initial empty check-in")
        .author("test-user")
        .initial()
        .execute()
        .expect("Failed to create initial checkin");
    println!("  Repository initialized: {}", source_path.display());
    println!("  Initial checkin: {}", &init_hash[..16]);

    // Create 1000 files
    let mut files_data: Vec<(String, Vec<u8>)> = Vec::with_capacity(NUM_FILES);
    for i in 0..NUM_FILES {
        let name = format!("src/file_{:04}.txt", i);
        let content = format!(
            "File number {}\nCreated for incremental sync test\nRandom data: {}\nMore content line 4\nLine 5\n",
            i,
            i * 17 + 42
        );
        files_data.push((name, content.into_bytes()));
    }

    // Add a README
    files_data.push((
        "README.md".to_string(),
        b"# Incremental Sync Test\n\nThis repo has 1000 test files.\n".to_vec(),
    ));

    let files: Vec<(&str, &[u8])> = files_data
        .iter()
        .map(|(n, c)| (n.as_str(), c.as_slice()))
        .collect();

    // Commit using builder pattern
    let commit_hash = source_repo
        .commit_builder()
        .message("Add 1000 test files")
        .author("test-user")
        .parent(&init_hash)
        .branch("trunk")
        .files(&files)
        .execute()
        .expect("Failed to commit files");

    let create_time = start.elapsed();
    println!(
        "  Created {} files in commit: {}",
        NUM_FILES,
        &commit_hash[..16]
    );
    println!("  Time: {:.2}s\n", create_time.as_secs_f64());

    // Verify source file count using files builder
    let source_files = source_repo
        .files()
        .at_commit(&commit_hash)
        .list()
        .expect("Failed to list files");
    println!("  Source file count: {}", source_files.len());
    assert_eq!(
        source_files.len(),
        NUM_FILES + 1,
        "Expected {} files",
        NUM_FILES + 1
    );

    // Get artifact count
    let source_artifacts: i64 = source_repo
        .database()
        .connection()
        .query_row("SELECT COUNT(*) FROM blob", [], |row| row.get(0))
        .unwrap();
    println!("  Source artifact count: {}\n", source_artifacts);

    // ========================================
    // Step 2: Create destination and sync via QUIC
    // ========================================
    println!("=== Step 2: Initial sync via QUIC ===\n");

    // Create empty destination with same project code
    let dest_repo = Repository::init(&dest_path).expect("Failed to init dest repo");
    let project_code = source_repo
        .project_code()
        .expect("Failed to get project code");
    dest_repo
        .database()
        .connection()
        .execute(
            "UPDATE config SET value = ?1 WHERE name = 'project-code'",
            [&project_code],
        )
        .expect("Failed to set project code");
    println!("  Destination initialized: {}", dest_path.display());
    println!("  Project code: {}\n", &project_code[..16]);

    // Drop repos before sync (they'll be reopened by sync)
    drop(source_repo);
    drop(dest_repo);

    // Run initial sync
    let (initial_sent, initial_received) = run_quic_sync(&source_path, &dest_path, "Initial sync");

    // Verify destination has all files using builder pattern
    let dest_repo = Repository::open(&dest_path).expect("Failed to open dest");
    let dest_files = dest_repo
        .files()
        .at_commit(&commit_hash)
        .list()
        .expect("Failed to list dest files");
    println!("  Destination file count: {}", dest_files.len());
    assert_eq!(
        dest_files.len(),
        NUM_FILES + 1,
        "Destination should have all files"
    );

    // Verify a few random files using files builder
    for i in [0, 100, 500, 999] {
        let name = format!("src/file_{:04}.txt", i);
        let content = dest_repo
            .files()
            .at_commit(&commit_hash)
            .read_string(&name)
            .expect("Failed to read file");
        let expected_start = format!("File number {}", i);
        assert!(
            content.starts_with(&expected_start),
            "Content mismatch for {}",
            name
        );
    }
    println!("  Content verification: PASSED\n");

    let dest_artifacts: i64 = dest_repo
        .database()
        .connection()
        .query_row("SELECT COUNT(*) FROM blob", [], |row| row.get(0))
        .unwrap();
    println!("  Destination artifact count: {}", dest_artifacts);
    println!("  Initial sync sent {} artifacts\n", initial_sent);

    drop(dest_repo);

    // ========================================
    // Step 3: Modify 4 files in source
    // ========================================
    println!(
        "=== Step 3: Modifying {} files in source ===\n",
        NUM_MODIFIED
    );

    let source_repo = Repository::open_rw(&source_path).expect("Failed to open source");

    // Rebuild files_data with 4 modified files
    let mut modified_files_data: Vec<(String, Vec<u8>)> = Vec::with_capacity(NUM_FILES + 1);
    let modified_indices = [0, 250, 500, 750]; // Modify these 4 files

    for i in 0..NUM_FILES {
        let name = format!("src/file_{:04}.txt", i);
        let content = if modified_indices.contains(&i) {
            format!(
                "MODIFIED - File number {}\nThis file was updated!\nNew content here.\nTimestamp: {}\n",
                i,
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
            )
        } else {
            format!(
                "File number {}\nCreated for incremental sync test\nRandom data: {}\nMore content line 4\nLine 5\n",
                i,
                i * 17 + 42
            )
        };
        modified_files_data.push((name, content.into_bytes()));
    }
    modified_files_data.push((
        "README.md".to_string(),
        b"# Incremental Sync Test\n\nThis repo has 1000 test files.\n".to_vec(),
    ));

    let files: Vec<(&str, &[u8])> = modified_files_data
        .iter()
        .map(|(n, c)| (n.as_str(), c.as_slice()))
        .collect();

    // Commit using builder pattern
    let modified_hash = source_repo
        .commit_builder()
        .message("Modify 4 files")
        .author("test-user")
        .parent(&commit_hash)
        .branch("trunk")
        .files(&files)
        .execute()
        .expect("Failed to commit modifications");

    println!(
        "  Modified files: {:?}",
        modified_indices
            .iter()
            .map(|i| format!("file_{:04}.txt", i))
            .collect::<Vec<_>>()
    );
    println!("  New commit: {}\n", &modified_hash[..16]);

    let source_artifacts_after: i64 = source_repo
        .database()
        .connection()
        .query_row("SELECT COUNT(*) FROM blob", [], |row| row.get(0))
        .unwrap();
    let new_artifacts = source_artifacts_after - source_artifacts;
    println!(
        "  New artifacts in source: {} (4 modified files + 1 manifest)\n",
        new_artifacts
    );

    drop(source_repo);

    // ========================================
    // Step 4: Incremental sync - only 4 files should transfer
    // ========================================
    println!("=== Step 4: Incremental sync (only modified files) ===\n");

    let (incr_sent, incr_received) = run_quic_sync(&source_path, &dest_path, "Incremental sync");

    // Verify only ~5 artifacts transferred (4 files + 1 manifest)
    println!("\n  Incremental sync sent {} artifacts", incr_sent);
    println!("  Expected: ~5 (4 modified files + 1 manifest)");

    if incr_sent <= 10 {
        println!("  Result: PASSED - Only modified files were transferred!\n");
    } else {
        println!("  Result: WARNING - More artifacts than expected were transferred\n");
    }

    // Verify destination has the modified content using files builder
    let dest_repo = Repository::open(&dest_path).expect("Failed to open dest");

    // Check modified files have new content
    for i in modified_indices {
        let name = format!("src/file_{:04}.txt", i);
        let content = dest_repo
            .files()
            .at_commit(&modified_hash)
            .read_string(&name)
            .expect("Failed to read file");
        assert!(
            content.starts_with("MODIFIED"),
            "File {} should be modified",
            name
        );
    }
    println!("  Modified content verification: PASSED");

    // Check unmodified files still have original content
    let unmodified_indices = [1, 100, 999];
    for i in unmodified_indices {
        let name = format!("src/file_{:04}.txt", i);
        let content = dest_repo
            .files()
            .at_commit(&modified_hash)
            .read_string(&name)
            .expect("Failed to read file");
        let expected_start = format!("File number {}", i);
        assert!(
            content.starts_with(&expected_start),
            "File {} should be unmodified",
            name
        );
    }
    println!("  Unmodified content verification: PASSED\n");

    // Final stats
    let dest_artifacts_final: i64 = dest_repo
        .database()
        .connection()
        .query_row("SELECT COUNT(*) FROM blob", [], |row| row.get(0))
        .unwrap();

    // ========================================
    // Summary
    // ========================================
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║                        SUMMARY                             ║");
    println!("╚════════════════════════════════════════════════════════════╝\n");
    println!("  Source repository: {}", source_path.display());
    println!("  Destination repository: {}", dest_path.display());
    println!("  Total files: {}", NUM_FILES + 1);
    println!("  Modified files: {}", NUM_MODIFIED);
    println!();
    println!("  Initial sync:");
    println!("    - Artifacts sent: {}", initial_sent);
    println!("    - Artifacts received: {}", initial_received);
    println!();
    println!("  Incremental sync:");
    println!("    - Artifacts sent: {}", incr_sent);
    println!("    - Artifacts received: {}", incr_received);
    println!();
    println!("  Final artifact counts:");
    println!("    - Source: {}", source_artifacts_after);
    println!("    - Destination: {}", dest_artifacts_final);
    println!();

    if incr_sent <= 10 && dest_artifacts_final == source_artifacts_after {
        println!("  TEST PASSED: Incremental sync correctly transferred only modified files!");
    } else {
        println!("  TEST FAILED: Unexpected sync behavior");
        std::process::exit(1);
    }

    println!("\n  To explore the repositories:");
    println!("    heroforge ui {}", source_path.display());
    println!("    heroforge ui {}", dest_path.display());
}

fn run_quic_sync(source_path: &Path, dest_path: &Path, description: &str) -> (usize, usize) {
    println!("  Starting {}...", description);

    let source_path = source_path.to_path_buf();
    let dest_path = dest_path.to_path_buf();

    let rt = Runtime::new().expect("Failed to create runtime");

    let result = rt.block_on(async {
        // Bind server
        let server = QuicServer::bind("127.0.0.1:0").expect("Failed to bind server");
        let addr = server.local_addr().expect("Failed to get addr").to_string();

        // Clone paths for server thread
        let source_path_clone = source_path.clone();

        // Run server in separate thread
        let server_handle = std::thread::spawn(move || {
            let rt = Runtime::new().expect("runtime");
            rt.block_on(async {
                let repo = Repository::open(&source_path_clone).expect("open source");
                server.handle_sync(&repo, &source_path_clone).await
            })
        });

        // Small delay for server startup
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Run client
        let dest_path_clone = dest_path.clone();
        let client_result = {
            let repo = Repository::open_rw(&dest_path_clone).expect("open dest");
            QuicClient::sync(&repo, &dest_path_clone, &addr).await
        };

        let client_stats = client_result.expect("Client sync failed");
        let server_stats = server_handle
            .join()
            .expect("Server panicked")
            .expect("Server sync failed");

        (server_stats.artifacts_sent, client_stats.artifacts_received)
    });

    println!("  {} complete.", description);
    result
}