//! Integration tests for complete download and upload workflows const std = @import("std"); const testing = std.testing; const fs = std.fs; const DownloadModule = @import("../../src/files/download.zig"); const UploadModule = @import("../../src/files/upload.zig"); const ManagerModule = @import("../../src/files/manager.zig"); const { DownloadManager, DownloadQueue } = DownloadModule; const { UploadManager, UploadQueue } = UploadModule; const { FileSharingManager, FileSharingConfig, FileSharingSession } = ManagerModule; const { FileChunker, FileWriter } = @import("../../src/files/file.zig"); const { HashUtils } = @import("../../src/files/hash.zig"); test "complete file download workflow" { const allocator = testing.allocator; // Create source file const source_path = "integration_source.bin"; const source_content = "Complete download workflow test content with multiple pieces"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(source_content) catch return; source_file.close(); // Create output file path const output_path = "integration_download.bin"; // Step 1: Create file metadata const chunker = FileChunker.init(16, allocator); // Small pieces for testing const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); try testing.expectEqual(@as(u32, 1), metadata.piece_count); // Content fits in one piece // Step 2: Initialize download manager var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, .sequential, 16, allocator, ); defer download_manager.deinit(); try download_manager.setOutputFile(output_path); // Step 3: Simulate peer with available pieces const peer_id = "test_peer_1"; try download_manager.addPeer(peer_id, &.{0}); // Step 4: Request piece download try download_manager.requestPiece(0, .normal, peer_id); try testing.expectEqual(@as(usize, 1), download_manager.pending_requests.items.len); // Step 5: Process download requests try download_manager.processRequests(1); try testing.expectEqual(@as(usize, 0), download_manager.pending_requests.items.len); try testing.expectEqual(@as(usize, 1), download_manager.active_downloads.count()); // Step 6: Simulate receiving piece data const piece_data = try chunker.readPiece(source_path, 0, metadata.pieceSize(0)); defer allocator.free(piece_data); const expected_hash = metadata.piece_hashes[0]; try download_manager.handlePieceData(0, piece_data, expected_hash); // Step 7: Verify download completion try testing.expect(download_manager.isComplete()); const stats = download_manager.getStats(); try testing.expectEqual(@as(f32, 1.0), stats.progress); try testing.expectEqual(@as(u32, 1), stats.state.completed_pieces); // Verify output file const output_file = fs.cwd().openFile(output_path, .{}) catch return; defer output_file.close(); const output_size = try output_file.getEndPos(); try testing.expectEqual(source_content.len, output_size); // Clean up fs.cwd().deleteFile(source_path) catch return; fs.cwd().deleteFile(output_path) catch return; } test "complete file upload workflow" { const allocator = testing.allocator; // Create source file const source_path = "upload_source.bin"; const source_content = "Complete upload workflow test content"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(source_content) catch return; source_file.close(); // Step 1: Create file metadata const chunker = FileChunker.init(16, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); // Step 2: Initialize upload manager var upload_manager = try UploadManager.init( 1024 * 1024, // 1MB/s bandwidth 16, allocator, ); defer upload_manager.deinit(); // Step 3: Add available pieces for (metadata.piece_hashes, 0..) |hash, i| { try upload_manager.addAvailablePiece(@as(u32, @intCast(i)), hash); } try testing.expectEqual(@as(usize, 1), upload_manager.available_pieces.count()); // Step 4: Handle upload request const request_accepted = try upload_manager.handleUploadRequest( 0, 0, source_content.len, "requesting_peer", .normal, ); try testing.expect(request_accepted); try testing.expectEqual(@as(usize, 1), upload_manager.pending_requests.items.len); // Step 5: Process upload requests try upload_manager.processRequests(1); try testing.expectEqual(@as(usize, 0), upload_manager.pending_requests.items.len); try testing.expectEqual(@as(usize, 1), upload_manager.active_uploads.count()); // Step 6: Send piece data try upload_manager.sendPieceData(0, source_content); // Step 7: Verify upload completion const stats = upload_manager.getStats(); try testing.expectEqual(@as(u64, source_content.len), stats.state.total_uploaded); try testing.expectEqual(@as(usize, 0), upload_manager.active_uploads.count()); // Should be completed // Clean up fs.cwd().deleteFile(source_path) catch return; } test "multi-piece download workflow" { const allocator = testing.allocator; // Create larger file with multiple pieces const source_path = "multi_piece_source.bin"; const piece_size: u64 = 10; const num_pieces = 5; const total_size = piece_size * num_pieces; const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Write pieces with different content for (0..num_pieces) |i| { const piece_content = try fmt.allocPrint(allocator, "Piece {d} data content", .{i}); defer allocator.free(piece_content); _ = source_file.write(piece_content) catch break; } source_file.close(); // Create output file const output_path = "multi_piece_download.bin"; // Step 1: Create metadata with specific piece size const chunker = FileChunker.init(piece_size, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); try testing.expectEqual(@as(u32, num_pieces), metadata.piece_count); // Step 2: Initialize download manager var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, .sequential, piece_size, allocator, ); defer download_manager.deinit(); try download_manager.setOutputFile(output_path); // Step 3: Add multiple peers with different pieces try download_manager.addPeer("peer1", &.{0, 2, 4}); // Odd pieces try download_manager.addPeer("peer2", &.{1, 3}); // Even pieces // Step 4: Request all pieces for (0..num_pieces) |i| { const peer_id = if (i % 2 == 0) "peer1" else "peer2"; try download_manager.requestPiece(@as(u32, @intCast(i)), .normal, peer_id); } try testing.expectEqual(@as(usize, num_pieces), download_manager.pending_requests.items.len); // Step 5: Process all downloads try download_manager.processRequests(num_pieces); try testing.expectEqual(@as(usize, 0), download_manager.pending_requests.items.len); try testing.expectEqual(@as(usize, num_pieces), download_manager.active_downloads.count()); // Step 6: Complete each piece download for (0..num_pieces) |i| { const piece_index = @as(u32, @intCast(i)); const piece_content = try chunker.readPiece(source_path, piece_index, metadata.pieceSize(piece_index)); defer allocator.free(piece_content); const expected_hash = metadata.piece_hashes[piece_index]; try download_manager.handlePieceData(piece_index, piece_content, expected_hash); } // Step 7: Verify complete download try testing.expect(download_manager.isComplete()); const final_stats = download_manager.getStats(); try testing.expectEqual(@as(f32, 1.0), final_stats.progress); try testing.expectEqual(@as(u32, num_pieces), final_stats.state.completed_pieces); // Verify output file size const output_file = fs.cwd().openFile(output_path, .{}) catch return; defer output_file.close(); const output_size = try output_file.getEndPos(); try testing.expectEqual(total_size, output_size); // Clean up fs.cwd().deleteFile(source_path) catch return; fs.cwd().deleteFile(output_path) catch return; } test "bandwidth-limited upload workflow" { const allocator = testing.allocator; // Create source file const source_path = "bandwidth_source.bin"; const large_content = [_]u8{1} ** 1024; // 1KB of data const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(&large_content) catch return; source_file.close(); // Step 1: Initialize upload manager with low bandwidth limit const max_bandwidth: u64 = 256; // Very low bandwidth limit var upload_manager = try UploadManager.init(max_bandwidth, 512, allocator); defer upload_manager.deinit(); // Step 2: Add available piece const chunker = FileChunker.init(512, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); try upload_manager.addAvailablePiece(0, metadata.piece_hashes[0]); // Step 3: Request upload that exceeds bandwidth const request_accepted = try upload_manager.handleUploadRequest(0, 0, 512, "peer1", .normal); try testing.expect(request_accepted); // Request accepted but will be throttled try upload_manager.processRequests(1); // Step 4: Try to send data exceeding bandwidth limit const large_data = [_]u8{2} ** 512; try upload_manager.sendPieceData(0, &large_data); // Bandwidth should be exceeded const stats = upload_manager.getStats(); try testing.expect(stats.bandwidth_utilization > 1.0); // Exceeded limit // Step 5: Reset bandwidth and try again upload_manager.resetBandwidth(); // Now should be able to send smaller amount const small_data = [_]u8{3} ** 128; try upload_manager.sendPieceData(0, &small_data); const final_stats = upload_manager.getStats(); try testing.expect(final_stats.state.total_uploaded > 0); // Clean up fs.cwd().deleteFile(source_path) catch return; } test "concurrent download and upload workflow" { const allocator = testing.allocator; // Create source file for upload const upload_source = "concurrent_upload_source.bin"; const upload_content = "Source content for concurrent upload test"; const upload_file = fs.cwd().createFile(upload_source, .{}) catch return; _ = upload_file.write(upload_content) catch return; upload_file.close(); // Create metadata for download const chunker = FileChunker.init(16, allocator); const download_metadata = try chunker.createMetadata(upload_source); defer allocator.free(download_metadata.piece_hashes); // Step 1: Initialize file sharing manager const config = FileSharingConfig{ .max_concurrent_downloads = 2, .max_concurrent_uploads = 2, .piece_size = 16, }; var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Step 2: Add file for sharing (creates upload capability) const session = try manager.addFile(upload_source); const session_id = session.session_id; // Step 3: Start sharing (both download and upload) try manager.startSharing(session_id); // Step 4: Process sessions try manager.processSessions(); // Step 5: Verify session is active try testing.expect(!manager.isIdle()); const active_sessions = manager.getActiveSessions(); try testing.expect(active_sessions.len > 0); // Step 6: Get session statistics const session_stats = session.getStats(); try testing.expect(session_stats.status == .uploading or session_stats.status == .ready); // Step 7: Get overall statistics const manager_stats = manager.getStats(); try testing.expectEqual(@as(usize, 1), manager_stats.total_sessions); try testing.expectEqual(@as(usize, 1), manager_stats.active_sessions); // Step 8: Stop sharing try manager.stopSharing(session_id); try testing.expect(manager.isIdle()); // Clean up fs.cwd().deleteFile(upload_source) catch return; } test "error recovery in download workflow" { const allocator = testing.allocator; // Create source file const source_path = "error_recovery_source.bin"; const source_content = "Error recovery test content"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(source_content) catch return; source_file.close(); // Create output file const output_path = "error_recovery_download.bin"; // Step 1: Initialize download const chunker = FileChunker.init(16, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, .sequential, 16, allocator, ); defer download_manager.deinit(); try download_manager.setOutputFile(output_path); try download_manager.addPeer("faulty_peer", &.{0}); // Step 2: Request piece try download_manager.requestPiece(0, .normal, "faulty_peer"); try download_manager.processRequests(1); // Step 3: Simulate receiving corrupted data const corrupted_data = "Corrupted data content"; const wrong_hash = [_]u8{9} ** 32; // This should fail verification try testing.expectError(Error.InvalidData, download_manager.handlePieceData(0, corrupted_data, wrong_hash)); // Step 4: Verify download failed and can be retried try testing.expect(!download_manager.isComplete()); try testing.expectEqual(@as(u32, 1), download_manager.state.failed_pieces); // Step 5: Retry with correct data const correct_data = try chunker.readPiece(source_path, 0, metadata.pieceSize(0)); defer allocator.free(correct_data); const correct_hash = metadata.piece_hashes[0]; try download_manager.handlePieceData(0, correct_data, correct_hash); // Step 6: Verify successful completion after retry try testing.expect(download_manager.isComplete()); const final_stats = download_manager.getStats(); try testing.expectEqual(@as(u32, 1), final_stats.state.completed_pieces); try testing.expectEqual(@as(u32, 0), final_stats.state.failed_pieces); // Reset after success // Clean up fs.cwd().deleteFile(source_path) catch return; fs.cwd().deleteFile(output_path) catch return; } test "peer coordination and fairness" { const allocator = testing.allocator; // Create source file with multiple pieces const source_path = "peer_coordination_source.bin"; const num_pieces = 4; const piece_size: u64 = 16; const source_file = fs.cwd().createFile(source_path, .{}) catch return; for (0..num_pieces) |i| { const piece_content = try fmt.allocPrint(allocator, "Piece {d} content for peer testing", .{i}); defer allocator.free(piece_content); _ = source_file.write(piece_content) catch break; } source_file.close(); // Step 1: Initialize upload manager var upload_manager = try UploadManager.init(1024, piece_size, allocator); defer upload_manager.deinit(); // Step 2: Add all pieces as available const chunker = FileChunker.init(piece_size, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); for (metadata.piece_hashes, 0..) |hash, i| { try upload_manager.addAvailablePiece(@as(u32, @intCast(i)), hash); } // Step 3: Set peer limits for fairness try upload_manager.setPeerLimit("peer1", 2, 512); // Max 2 concurrent uploads try upload_manager.setPeerLimit("peer2", 1, 256); // Max 1 concurrent upload // Step 4: Request uploads from both peers // Peer1 requests pieces 0 and 1 try testing.expect(try upload_manager.handleUploadRequest(0, 0, 16, "peer1", .normal)); try testing.expect(try upload_manager.handleUploadRequest(1, 0, 16, "peer1", .normal)); // Peer2 requests piece 2 try testing.expect(try upload_manager.handleUploadRequest(2, 0, 16, "peer2", .normal)); // Peer1 tries to request more than limit (should be rejected) try testing.expect(try upload_manager.handleUploadRequest(3, 0, 16, "peer1", .high)); // Step 5: Process uploads try upload_manager.processRequests(3); // Should only process 3 due to limits const stats = upload_manager.getStats(); try testing.expectEqual(@as(usize, 3), stats.active_uploads); // Step 6: Complete some uploads and verify fairness const piece_data = try chunker.readPiece(source_path, 0, 16); defer allocator.free(piece_data); try upload_manager.sendPieceData(0, piece_data); try upload_manager.sendPieceData(1, piece_data); try upload_manager.sendPieceData(2, piece_data); // All uploads should be completed try testing.expectEqual(@as(u64, 48), stats.state.total_uploaded); // Clean up fs.cwd().deleteFile(source_path) catch return; } test "complete file sharing workflow with multiple files" { const allocator = testing.allocator; // Create multiple source files const file_count = 3; var file_paths = std.ArrayList([]const u8).init(allocator); defer { for (file_paths.items) |path| { allocator.free(path); } file_paths.deinit(); } for (0..file_count) |i| { const file_path = try fmt.allocPrint(allocator, "multi_file_{d}.bin", .{i}); try file_paths.append(file_path); const content = try fmt.allocPrint(allocator, "Content of file {d} for testing", .{i}); defer allocator.free(content); const file = fs.cwd().createFile(file_path, .{}) catch continue; _ = file.write(content) catch continue; file.close(); } // Step 1: Initialize file sharing manager with high performance config const config = FileSharingConfig.high_performance(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Step 2: Add all files for sharing var session_ids = std.ArrayList(u64).init(allocator); defer session_ids.deinit(); for (file_paths.items) |file_path| { const session = try manager.addFile(file_path); try session_ids.append(session.session_id); } try testing.expectEqual(@as(usize, file_count), manager.getStats().registered_files); // Step 3: Start all sharing sessions for (session_ids.items) |session_id| { try manager.startSharing(session_id); } // Step 4: Process all sessions try manager.processSessions(); // Step 5: Verify multiple active sessions const stats = manager.getStats(); try testing.expectEqual(@as(usize, file_count), stats.total_sessions); try testing.expectEqual(@as(usize, file_count), stats.active_sessions); // Step 6: Check individual session progress var it = manager.sessions.valueIterator(); var active_count: usize = 0; while (it.next()) |session| { if (session.isActive()) { active_count += 1; const session_stats = session.getStats(); try testing.expect(session_stats.progress >= 0.0); } } try testing.expectEqual(@as(usize, file_count), active_count); // Step 7: Stop all sessions for (session_ids.items) |session_id| { try manager.stopSharing(session_id); } try testing.expect(manager.isIdle()); // Clean up all files for (file_paths.items) |file_path| { fs.cwd().deleteFile(file_path) catch continue; } } test "download queue workflow" { const allocator = testing.allocator; // Create source file const source_path = "queue_source.bin"; const source_content = "Download queue workflow test content"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(source_content) catch return; source_file.close(); // Step 1: Initialize download queue var queue = DownloadQueue.init(allocator); defer queue.deinit(); // Step 2: Add multiple downloads to queue const download1 = try queue.addDownload(1024, 1, .sequential, 512); const download2 = try queue.addDownload(2048, 2, .rarest_first, 1024); const download3 = try queue.addDownload(512, 1, .random, 256); try testing.expectEqual(@as(usize, 3), queue.downloads.items.len); // Step 3: Process all downloads const config = DownloadConfig{ .max_concurrent_downloads = 2, .piece_size = 512, }; try queue.processAll(config); // Step 4: Verify queue statistics const combined_stats = queue.getCombinedStats(); try testing.expectEqual(@as(u64, 3584), combined_stats.total_size); // 1024 + 2048 + 512 try testing.expectEqual(@as(u32, 4), combined_stats.total_pieces); // 1 + 2 + 1 try testing.expect(!queue.areAllComplete()); // Should not be complete yet // Step 5: Complete one download manually (simulate) download1.state.completed_pieces = 1; // Mark as complete try testing.expect(!queue.areAllComplete()); // Still 2 more to go download2.state.completed_pieces = 2; download3.state.completed_pieces = 1; try testing.expect(queue.areAllComplete()); // All complete now // Clean up fs.cwd().deleteFile(source_path) catch return; } test "upload queue workflow with bandwidth management" { const allocator = testing.allocator; // Step 1: Initialize upload queue var queue = UploadQueue.init(allocator); defer queue.deinit(); // Step 2: Add multiple upload managers with different bandwidth limits const upload1 = try queue.addUpload(1024 * 1024, 1024); // 1MB/s, 1KB pieces const upload2 = try queue.addUpload(512 * 1024, 2048); // 512KB/s, 2KB pieces const upload3 = try queue.addUpload(256 * 1024, 512); // 256KB/s, 512B pieces try testing.expectEqual(@as(usize, 3), queue.uploads.items.len); // Step 3: Process all uploads try queue.processAll(2); // Max 2 concurrent uploads per manager // Step 4: Verify combined statistics const combined_stats = queue.getCombinedStats(); try testing.expectEqual(@as(u64, 1792 * 1024), combined_stats.max_bandwidth); // Sum of all limits try testing.expectEqual(@as(u32, 0), combined_stats.active_uploads); // No uploads started yet try testing.expectEqual(@as(u64, 0), combined_stats.total_uploaded); // Step 5: Simulate uploads by updating state upload1.state.addUploadedBytes(1024 * 100); // 100KB uploaded upload2.state.addUploadedBytes(512 * 50); // 50KB uploaded upload3.state.addUploadedBytes(256 * 25); // 25KB uploaded const updated_stats = queue.getCombinedStats(); try testing.expectEqual(@as(u64, 175 * 1024), updated_stats.total_uploaded); // 100KB + 50KB + 25KB } test "file sharing configuration scenarios" { const allocator = testing.allocator; // Test different configuration scenarios var scenarios = std.ArrayList(FileSharingConfig).init(allocator); defer scenarios.deinit(); // Default configuration try scenarios.append(FileSharingConfig.default()); // High performance configuration try scenarios.append(FileSharingConfig.high_performance()); // Low bandwidth configuration try scenarios.append(FileSharingConfig.low_bandwidth()); // Custom configuration try scenarios.append(FileSharingConfig{ .piece_size = 8 * 1024 * 1024, // 8MB .max_concurrent_downloads = 6, .max_concurrent_uploads = 6, .max_bandwidth_download = 5 * 1024 * 1024, // 5MB/s .max_bandwidth_upload = 3 * 1024 * 1024, // 3MB/s .selection_strategy = .priority_first, .enable_upload = false, // Upload disabled .enable_download = true, .auto_verify = false, .temp_dir = "custom_temp", }); // Test each configuration for (scenarios.items, 0..) |config, i| { var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Verify configuration is applied try testing.expectEqual(config.piece_size, manager.config.piece_size); try testing.expectEqual(config.max_concurrent_downloads, manager.config.max_concurrent_downloads); try testing.expectEqual(config.max_concurrent_uploads, manager.config.max_concurrent_uploads); try testing.expectEqual(config.max_bandwidth_download, manager.config.max_bandwidth_download); try testing.expectEqual(config.max_bandwidth_upload, manager.config.max_bandwidth_upload); try testing.expectEqual(config.selection_strategy, manager.config.selection_strategy); try testing.expectEqual(config.enable_upload, manager.config.enable_upload); try testing.expectEqual(config.enable_download, manager.config.enable_download); // Test configuration changes manager.updateBandwidthLimits(2048 * 1024, 1024 * 1024); try testing.expectEqual(@as(u64, 2048 * 1024), manager.config.max_bandwidth_download); try testing.expectEqual(@as(u64, 1024 * 1024), manager.config.max_bandwidth_upload); manager.setSelectionStrategy(.random); try testing.expectEqual(.random, manager.config.selection_strategy); manager.setFeatures(true, false); try testing.expect(manager.config.enable_upload); try testing.expect(!manager.config.enable_download); } } // Helper function for formatted printing fn fmt(comptime format: []const u8, args: anytype) @TypeOf(std.fmt.comptimePrint(format, args)) { return std.fmt.comptimePrint(format, args); }