//! Advanced workflow scenarios and edge case testing const std = @import("std"); const testing = std.testing; const fs = std.fs; const ManagerModule = @import("../../src/files/manager.zig"); const { FileSharingManager, FileSharingConfig } = ManagerModule; const { DownloadManager } = @import("../../src/files/download.zig"); const { UploadManager } = @import("../../src/files/upload.zig"); const { FileChunker, FileWriter } = @import("../../src/files/file.zig"); const { PieceSelector } = @import("../../src/files/piece.zig"); test "concurrent peer file sharing simulation" { const allocator = testing.allocator; // Create source file const source_path = "concurrent_peers_source.bin"; const content = "Content for concurrent peer sharing simulation"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(content) catch return; source_file.close(); // Step 1: Initialize file sharing manager const config = FileSharingConfig.high_performance(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Step 2: Add file for sharing const session = try manager.addFile(source_path); const session_id = session.session_id; // Step 3: Simulate multiple peers connecting and downloading const peer_count = 5; var peer_ids = std.ArrayList([]const u8).init(allocator); defer { for (peer_ids.items) |peer_id| { allocator.free(peer_id); } peer_ids.deinit(); } // Create multiple "download managers" to simulate peers var download_managers = std.ArrayList(DownloadManager).init(allocator); defer { for (download_managers.items) |*dm| { dm.deinit(); } download_managers.deinit(); } const chunker = FileChunker.init(config.piece_size, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); // Step 4: Each peer creates a download manager for (0..peer_count) |i| { const peer_id = try fmt.allocPrint(allocator, "peer_{d}", .{i}); try peer_ids.append(peer_id); var peer_downloader = try DownloadManager.init( metadata.size, metadata.piece_count, .rarest_first, config.piece_size, allocator, ); // Simulate peer having the file available (for upload simulation) try download_managers.append(peer_downloader); } // Step 5: Start sharing try manager.startSharing(session_id); // Step 6: Simulate processing by multiple peers for (peer_ids.items, download_managers.items) |peer_id, *peer_downloader| { // Each peer "discovers" the file try peer_downloader.addPeer("source_peer", &.{0}); // Each peer requests the file try peer_downloader.requestPiece(0, .normal, "source_peer"); try peer_downloader.processRequests(1); // Simulate receiving the file const piece_data = try chunker.readPiece(source_path, 0, metadata.pieceSize(0)); defer allocator.free(piece_data); const expected_hash = metadata.piece_hashes[0]; peer_downloader.handlePieceData(0, piece_data, expected_hash) catch {}; } // Step 7: Verify all peers completed download var completed_peers: usize = 0; for (download_managers.items) |peer_downloader| { if (peer_downloader.isComplete()) { completed_peers += 1; } } try testing.expectEqual(peer_count, completed_peers); // Step 8: Check manager statistics const stats = manager.getStats(); try testing.expectEqual(@as(u64, content.len * peer_count), stats.total_downloaded); // Each peer downloaded // Clean up fs.cwd().deleteFile(source_path) catch return; } test "network partition and recovery simulation" { const allocator = testing.allocator; // Create source file const source_path = "partition_recovery_source.bin"; const content = "Content for network partition recovery testing"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(content) catch return; source_file.close(); // Step 1: Initialize download manager 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(); const output_path = "partition_recovery_download.bin"; try download_manager.setOutputFile(output_path); // Step 2: Simulate network partition - peer becomes unavailable try download_manager.addPeer("unreliable_peer", &.{0}); // Step 3: Start download try download_manager.requestPiece(0, .normal, "unreliable_peer"); try download_manager.processRequests(1); // Simulate network partition - peer goes offline download_manager.updatePeerAvailability("unreliable_peer", 0, false) catch {}; // Step 4: Handle download failure due to network issues try download_manager.handleDownloadFailure(0, "Network partition - peer unavailable"); try testing.expect(!download_manager.isComplete()); // Step 5: Simulate network recovery - new peer appears try download_manager.addPeer("recovery_peer", &.{0}); download_manager.updatePeerAvailability("recovery_peer", 0, true) catch {}; // Step 6: Retry download with new peer try download_manager.requestPiece(0, .high, "recovery_peer"); // Higher priority for retry try download_manager.processRequests(1); // Step 7: Complete download successfully 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 8: Verify successful recovery 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.expect(final_stats.state.failed_pieces >= 0); // May have had failures // Clean up fs.cwd().deleteFile(source_path) catch return; fs.cwd().deleteFile(output_path) catch return; } test "piece selection strategy comparison" { const allocator = testing.allocator; // Create metadata with many pieces const source_path = "strategy_comparison_source.bin"; const piece_count = 20; const piece_size: u64 = 32; const total_size = piece_count * piece_size; const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Create content for each piece for (0..piece_count) |i| { const piece_content = try fmt.allocPrint(allocator, "Piece {d:0>2} content for strategy testing", .{i}); defer allocator.free(piece_content); _ = source_file.write(piece_content) catch break; } source_file.close(); 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, piece_count), metadata.piece_count); // Test different selection strategies const strategies = .{ .sequential, .rarest_first, .random, .priority_first, .balanced }; for (strategies) |strategy| { var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, strategy, piece_size, allocator, ); defer download_manager.deinit(); // Add pieces with varying availability to simulate real network for (0..piece_count) |i| { // Create varied availability: some pieces rare, some common const availability = if (i < 5) 1 else if (i < 10) 2 else if (i < 15) 3 else 5; try download_manager.addPiece(@as(u32, @intCast(i)), availability); } // Select pieces using this strategy const selected_pieces = try download_manager.getNeededPieces(5); defer allocator.free(selected_pieces); try testing.expectEqual(@as(usize, 5), selected_pieces.len); // Verify pieces are valid for (selected_pieces) |piece_index| { try testing.expect(piece_index < piece_count); const piece_info = download_manager.selector.availability_map.get(piece_index); try testing.expect(piece_info != null); } } // Clean up fs.cwd().deleteFile(source_path) catch return; } test "large file streaming simulation" { const allocator = testing.allocator; // Create a larger file for streaming simulation const source_path = "streaming_source.bin"; const piece_size: u64 = 1024; // 1KB pieces const piece_count = 100; // 100KB total const total_size = piece_size * piece_count; const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Write file in chunks to avoid memory issues var bytes_written: usize = 0; while (bytes_written < total_size) { const chunk = [_]u8{ @as(u8, @intCast(bytes_written % 256)) } ** @min(piece_size, total_size - bytes_written); _ = source_file.write(&chunk) catch break; bytes_written += chunk.len; } source_file.close(); // Step 1: Initialize streaming download const chunker = FileChunker.init(piece_size, 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, piece_size, allocator, ); defer download_manager.deinit(); const output_path = "streaming_download.bin"; try download_manager.setOutputFile(output_path); // Step 2: Simulate streaming download piece by piece try download_manager.addPeer("streaming_peer", &.{0}); var pieces_completed: u32 = 0; // Stream download in batches const batch_size = 10; while (pieces_completed < piece_count) { const batch_end = @min(pieces_completed + batch_size, piece_count); // Request batch of pieces for (pieces_completed..batch_end) |i| { try download_manager.requestPiece(@as(u32, @intCast(i)), .normal, "streaming_peer"); } // Process requests try download_manager.processRequests(batch_size); // Complete batch for (pieces_completed..batch_end) |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); } pieces_completed = batch_end; // Check progress after each batch const stats = download_manager.getStats(); const expected_progress = @as(f32, @floatFromInt(pieces_completed)) / @as(f32, @floatFromInt(piece_count)); try testing.expectEqual(expected_progress, stats.progress); } // Step 3: 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, piece_count), 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 "upload bandwidth fairness and throttling" { const allocator = testing.allocator; // Create source file const source_path = "bandwidth_fairness_source.bin"; const content = "Content for bandwidth fairness testing"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(content) catch return; source_file.close(); // Step 1: Initialize upload manager with bandwidth limit const max_bandwidth: u64 = 512; // Very low limit for testing var upload_manager = try UploadManager.init(max_bandwidth, 64, allocator); defer upload_manager.deinit(); // Step 2: Add available pieces const chunker = FileChunker.init(64, 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 different bandwidth limits for peers try upload_manager.setPeerLimit("fast_peer", 3, 256); // Can use up to 256 bytes/s try upload_manager.setPeerLimit("slow_peer", 1, 128); // Can use up to 128 bytes/s // Step 4: Submit multiple upload requests // Fast peer submits multiple requests try testing.expect(try upload_manager.handleUploadRequest(0, 0, 100, "fast_peer", .normal)); try testing.expect(try upload_manager.handleUploadRequest(1, 0, 100, "fast_peer", .normal)); try testing.expect(try upload_manager.handleUploadRequest(2, 0, 100, "fast_peer", .normal)); // Slow peer submits one request try testing.expect(try upload_manager.handleUploadRequest(3, 0, 50, "slow_peer", .normal)); // Step 5: Process uploads try upload_manager.processRequests(2); // Process max 2 concurrent const stats = upload_manager.getStats(); try testing.expectEqual(@as(usize, 2), stats.active_uploads); // Step 6: Simulate sending data and check bandwidth usage const test_data = [_]u8{1} ** 50; // Send some data try upload_manager.sendPieceData(0, &test_data); try upload_manager.sendPieceData(1, &test_data); // Bandwidth should be partially used const partial_stats = upload_manager.getStats(); try testing.expect(partial_stats.bandwidth_utilization > 0.0); try testing.expect(partial_stats.bandwidth_utilization <= 1.0); // Step 7: Try to exceed bandwidth limit const large_data = [_]u8{2} ** 400; // Try to send 400 bytes // This should trigger throttling upload_manager.sendPieceData(2, &large_data) catch {}; // Bandwidth should be exceeded const exceeded_stats = upload_manager.getStats(); try testing.expect(exceeded_stats.bandwidth_utilization > 1.0); // Step 8: Reset bandwidth and verify fair sharing upload_manager.resetBandwidth(); const reset_stats = upload_manager.getStats(); try testing.expect(reset_stats.bandwidth_utilization < 1.0); // Clean up fs.cwd().deleteFile(source_path) catch return; } test "piece verification and corruption recovery" { const allocator = testing.allocator; // Create source file const source_path = "verification_source.bin"; const content = "Content for verification and corruption testing"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(content) catch return; source_file.close(); // Step 1: Initialize download with verification enabled 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(); const output_path = "verification_download.bin"; try download_manager.setOutputFile(output_path); try download_manager.addPeer("verification_peer", &.{0}); // Step 2: Download correct piece first try download_manager.requestPiece(0, .normal, "verification_peer"); try download_manager.processRequests(1); 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); try testing.expect(download_manager.isComplete()); // Step 3: Reset and test corruption detection 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("corruption_test_peer", &.{0}); // Step 4: Simulate downloading corrupted piece try download_manager.requestPiece(0, .normal, "corruption_test_peer"); try download_manager.processRequests(1); const corrupted_data = "Corrupted piece data that will fail verification"; const wrong_hash = [_]u8{9} ** 32; // This should fail verification try testing.expectError(Error.InvalidData, download_manager.handlePieceData(0, corrupted_data, wrong_hash)); try testing.expect(!download_manager.isComplete()); // Step 5: Retry with correct data try download_manager.requestPiece(0, .high, "corruption_test_peer"); // Higher priority for retry try download_manager.processRequests(1); try download_manager.handlePieceData(0, correct_data, correct_hash); // Step 6: Verify successful recovery try testing.expect(download_manager.isComplete()); // Verify output file integrity const is_valid = try chunker.verifyFile(output_path, metadata); try testing.expect(is_valid); // Clean up fs.cwd().deleteFile(source_path) catch return; fs.cwd().deleteFile(output_path) catch return; } test "session lifecycle management" { const allocator = testing.allocator; // Create test file const source_path = "session_lifecycle_source.bin"; const content = "Content for session lifecycle testing"; const source_file = fs.cwd().createFile(source_path, .{}) catch return; _ = source_file.write(content) catch return; source_file.close(); // Step 1: Initialize manager const config = FileSharingConfig.default(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Step 2: Create session const session = try manager.addFile(source_path); const session_id = session.session_id; try testing.expectEqual(FileSharingSession.SessionStatus.initializing, session.status); // Step 3: Start sharing try manager.startSharing(session_id); // Verify session status changed const updated_session = manager.getSession(session_id).?; try testing.expect(updated_session.status == .uploading or updated_session.status == .ready); // Step 4: Process sessions try manager.processSessions(); // Step 5: Verify active sessions try testing.expect(!manager.isIdle()); const active_sessions = manager.getActiveSessions(); try testing.expect(active_sessions.len > 0); // Step 6: Check session statistics const session_stats = updated_session.getStats(); try testing.expect(session_stats.session_id == session_id); try testing.expect(session_stats.progress >= 0.0); try testing.expect(session_stats.file_size > 0); // Step 7: Get formatted status const status_string = try session_stats.getStatusString(allocator); defer allocator.free(status_string); try testing.expect(status_string.len > 0); // Step 8: Stop sharing try manager.stopSharing(session_id); // Verify session is no longer active try testing.expect(manager.isIdle()); // Clean up fs.cwd().deleteFile(source_path) catch return; } test "stress test with many small files" { const allocator = testing.allocator; // Create many small files const file_count = 20; const file_size: u64 = 100; // 100 bytes each var file_paths = std.ArrayList([]const u8).init(allocator); defer { for (file_paths.items) |path| { allocator.free(path); } file_paths.deinit(); } // Create all files for (0..file_count) |i| { const file_path = try fmt.allocPrint(allocator, "stress_file_{d}.bin", .{i}); try file_paths.append(file_path); const content = [_]u8{ @as(u8, @intCast(i)) } ** file_size; const file = fs.cwd().createFile(file_path, .{}) catch continue; _ = file.write(&content) catch continue; file.close(); } // Step 1: Initialize 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 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 sessions for (session_ids.items) |session_id| { try manager.startSharing(session_id); } // Step 4: Process all sessions multiple times for (0..5) |_| { try manager.processSessions(); } // Step 5: Verify manager handles many sessions const stats = manager.getStats(); try testing.expectEqual(@as(usize, file_count), stats.total_sessions); try testing.expect(stats.total_downloaded > 0 or stats.total_uploaded > 0); // Step 6: Get all active sessions const active_sessions = manager.getActiveSessions(); try testing.expect(active_sessions.len <= file_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; } } // Helper function fn fmt(comptime format: []const u8, args: anytype) @TypeOf(std.fmt.comptimePrint(format, args)) { return std.fmt.comptimePrint(format, args); }