//! Performance and scalability testing for file sharing workflows 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, DownloadQueue } = @import("../../src/files/download.zig"); const { UploadManager, UploadQueue } = @import("../../src/files/upload.zig"); const { FileChunker, FileWriter } = @import("../../src/files/file.zig"); const { PieceSelector } = @import("../../src/files/piece.zig"); test "large file download performance" { const allocator = testing.allocator; // Create a larger test file (1MB) const source_path = "perf_large_source.bin"; const file_size: u64 = 1024 * 1024; // 1MB const piece_size: u64 = 64 * 1024; // 64KB pieces const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Write file in chunks var bytes_written: u64 = 0; while (bytes_written < file_size) { const chunk_size = @min(1024, file_size - bytes_written); const chunk = [_]u8{ @as(u8, @intCast(bytes_written % 256)) } ** chunk_size; _ = source_file.write(&chunk) catch break; bytes_written += chunk_size; } source_file.close(); // Step 1: Measure metadata creation time const chunker = FileChunker.init(piece_size, allocator); const start_time = std.time.timestamp(); const metadata = try chunker.createMetadata(source_path); const metadata_time = std.time.timestamp() - start_time; defer allocator.free(metadata.piece_hashes); try testing.expectEqual(@as(u32, 16), metadata.piece_count); // 1MB / 64KB = 16 pieces // Step 2: Measure download manager initialization const init_start = std.time.timestamp(); var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, .sequential, piece_size, allocator, ); const init_time = std.time.timestamp() - init_start; defer download_manager.deinit(); // Step 3: Measure piece selection performance const output_path = "perf_large_download.bin"; try download_manager.setOutputFile(output_path); try download_manager.addPeer("perf_peer", &.{0}); const selection_start = std.time.timestamp(); const needed_pieces = try download_manager.getNeededPieces(16); const selection_time = std.time.timestamp() - selection_start; defer allocator.free(needed_pieces); try testing.expectEqual(@as(usize, 16), needed_pieces.len); // Step 4: Simulate downloading all pieces and measure time const download_start = std.time.timestamp(); for (needed_pieces) |piece_index| { try download_manager.requestPiece(piece_index, .normal, "perf_peer"); } try download_manager.processRequests(16); // Complete all downloads for (needed_pieces) |piece_index| { 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); } const download_time = std.time.timestamp() - download_start; // Step 5: Verify performance metrics try testing.expect(download_manager.isComplete()); const final_stats = download_manager.getStats(); // Performance assertions (should complete within reasonable time) try testing.expect(init_time < 5); // Init should be fast try testing.expect(metadata_time < 10); // Metadata creation should be reasonable try testing.expect(selection_time < 2); // Selection should be very fast try testing.expect(download_time < 30); // Download processing should be reasonable // Verify download speed const download_speed = @as(f32, @floatFromInt(file_size)) / @as(f32, @floatFromInt(@max(1, download_time))); try testing.expect(download_speed > 1000); // Should be at least 1KB/s in test environment // Clean up fs.cwd().deleteFile(source_path) catch return; fs.cwd().deleteFile(output_path) catch return; } test "concurrent download queue performance" { const allocator = testing.allocator; // Create multiple source files const file_count = 10; const file_size: u64 = 50 * 1024; // 50KB 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, "queue_perf_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 download queue var queue = DownloadQueue.init(allocator); defer queue.deinit(); // Step 2: Add multiple downloads to queue const add_start = std.time.timestamp(); var download_managers = std.ArrayList(*DownloadManager).init(allocator); defer download_managers.deinit(); for (file_paths.items) |file_path| { const chunker = FileChunker.init(1024, allocator); const metadata = try chunker.createMetadata(file_path); defer allocator.free(metadata.piece_hashes); const download_manager = try queue.addDownload( metadata.size, metadata.piece_count, .sequential, 1024, ); try download_managers.append(download_manager); } const add_time = std.time.timestamp() - add_start; // Step 3: Measure queue processing performance const process_start = std.time.timestamp(); const config = DownloadConfig{ .max_concurrent_downloads = 5, .piece_size = 1024, }; try queue.processAll(config); const process_time = std.time.timestamp() - process_start; // Step 4: Verify queue performance try testing.expectEqual(@as(usize, file_count), queue.downloads.items.len); // Processing should be reasonably fast try testing.expect(add_time < 10); // Adding downloads should be fast try testing.expect(process_time < 5); // Queue processing should be fast // Step 5: Get combined statistics const combined_stats = queue.getCombinedStats(); try testing.expectEqual(@as(u64, file_size * file_count), combined_stats.total_size); // Clean up files for (file_paths.items) |file_path| { fs.cwd().deleteFile(file_path) catch continue; } } test "upload bandwidth scaling test" { const allocator = testing.allocator; // Step 1: Initialize upload queue with multiple managers var queue = UploadQueue.init(allocator); defer queue.deinit(); // Step 2: Add upload managers with different bandwidth limits const upload_configs = .{ .{ 1024 * 1024, 1024 }, // 1MB/s, 1KB pieces .{ 512 * 1024, 2048 }, // 512KB/s, 2KB pieces .{ 256 * 1024, 512 }, // 256KB/s, 512B pieces .{ 128 * 1024, 256 }, // 128KB/s, 256B pieces }; var upload_managers = std.ArrayList(*UploadManager).init(allocator); defer upload_managers.deinit(); for (upload_configs) |config| { const upload_manager = try queue.addUpload(config[0], config[1]); try upload_managers.append(upload_manager); } // Step 3: Measure upload processing performance const process_start = std.time.timestamp(); try queue.processAll(2); // Max 2 concurrent per manager const process_time = std.time.timestamp() - process_start; // Step 4: Verify scaling performance const combined_stats = queue.getCombinedStats(); try testing.expectEqual(@as(u64, 1920 * 1024), combined_stats.max_bandwidth); // Sum of all limits // Processing should be fast even with multiple managers try testing.expect(process_time < 3); // Step 5: Simulate bandwidth usage and measure reset performance const reset_start = std.time.timestamp(); for (upload_managers.items) |upload_manager| { upload_manager.resetBandwidth(); } const reset_time = std.time.timestamp() - reset_start; // Bandwidth reset should be very fast try testing.expect(reset_time < 1); } test "memory usage with large number of pieces" { const allocator = testing.allocator; // Create a file with many small pieces const source_path = "memory_pieces_source.bin"; const piece_count = 1000; const piece_size: u64 = 1024; // 1KB pieces const total_size = piece_count * piece_size; const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Write file in chunks var bytes_written: u64 = 0; while (bytes_written < total_size) { const chunk_size = @min(4096, total_size - bytes_written); const chunk = [_]u8{ @as(u8, @intCast(bytes_written % 256)) } ** chunk_size; _ = source_file.write(&chunk) catch break; bytes_written += chunk_size; } source_file.close(); // Step 1: Create metadata for many pieces 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); // Step 2: Test piece selector with many pieces const selector_start = std.time.timestamp(); var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add all pieces to selector for (0..piece_count) |i| { const availability = @as(u32, @intCast(i % 10) + 1); // Varying availability try selector.addPiece(@as(u32, @intCast(i)), availability); } const selector_init_time = std.time.timestamp() - selector_start; // Step 3: Test piece selection with many pieces const selection_start = std.time.timestamp(); const selected_pieces = try selector.selectNext(100); // Select 100 pieces defer allocator.free(selected_pieces); const selection_time = std.time.timestamp() - selection_start; try testing.expectEqual(@as(usize, 100), selected_pieces.len); // Step 4: Test download manager with many pieces const download_start = std.time.timestamp(); var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, .rarest_first, piece_size, allocator, ); defer download_manager.deinit(); // Add pieces to download manager for (0..piece_count) |i| { try download_manager.addPiece(@as(u32, @intCast(i)), 1); } const download_init_time = std.time.timestamp() - download_start; // Step 5: Performance assertions try testing.expect(selector_init_time < 10); // Should handle 1000 pieces quickly try testing.expect(selection_time < 5); // Selection should be fast try testing.expect(download_init_time < 10); // Download manager should handle many pieces // Step 6: Test statistics calculation with many pieces const stats = selector.getStats(); try testing.expectEqual(@as(usize, piece_count), stats.total_pieces); const avg_availability = stats.getAverageAvailability(); try testing.expect(avg_availability > 0.0); try testing.expect(avg_availability < 11.0); // Should be around 5.5 // Clean up fs.cwd().deleteFile(source_path) catch return; } test "file sharing manager scalability" { const allocator = testing.allocator; // Test with many files const max_files = 50; const file_size: u64 = 10 * 1024; // 10KB each // Step 1: Create many test files var file_paths = std.ArrayList([]const u8).init(allocator); defer { for (file_paths.items) |path| { allocator.free(path); } file_paths.deinit(); } const create_start = std.time.timestamp(); for (0..max_files) |i| { const file_path = try fmt.allocPrint(allocator, "scalability_file_{d}.bin", .{i}); try file_paths.append(file_path); const content = [_]u8{ @as(u8, @intCast(i % 256)) } ** file_size; const file = fs.cwd().createFile(file_path, .{}) catch continue; _ = file.write(&content) catch continue; file.close(); } const create_time = std.time.timestamp() - create_start; // Step 2: Initialize file sharing manager const config = FileSharingConfig.high_performance(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); const manager_init_start = std.time.timestamp(); // Step 3: Add all files to manager 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); } const add_time = std.time.timestamp() - manager_init_start; // Step 4: Test manager operations with many files const operations_start = std.time.timestamp(); // Get statistics const stats = manager.getStats(); try testing.expectEqual(@as(usize, max_files), stats.total_sessions); try testing.expectEqual(@as(usize, max_files), stats.registered_files); // Get active sessions const active_sessions = manager.getActiveSessions(); try testing.expect(active_sessions.len == max_files); // Get individual sessions for (session_ids.items) |session_id| { const session = manager.getSession(session_id); try testing.expect(session != null); } const operations_time = std.time.timestamp() - operations_start; // Step 5: Start and stop all sessions const session_management_start = std.time.timestamp(); for (session_ids.items) |session_id| { try manager.startSharing(session_id); } try manager.processSessions(); for (session_ids.items) |session_id| { try manager.stopSharing(session_id); } const session_management_time = std.time.timestamp() - session_management_start; // Step 6: Performance assertions try testing.expect(create_time < 30); // File creation should be reasonable try testing.expect(add_time < 20); // Adding files should be reasonable try testing.expect(operations_time < 10); // Operations should be fast try testing.expect(session_management_time < 30); // Session management should be reasonable // Final state check try testing.expect(manager.isIdle()); // Clean up all files for (file_paths.items) |file_path| { fs.cwd().deleteFile(file_path) catch continue; } } test "piece selection algorithm performance comparison" { const allocator = testing.allocator; // Create a file with pieces for selection testing const source_path = "selection_perf_source.bin"; const piece_count = 500; const piece_size: u64 = 2048; // 2KB pieces const total_size = piece_count * piece_size; const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Write file var bytes_written: u64 = 0; while (bytes_written < total_size) { const chunk_size = @min(4096, total_size - bytes_written); const chunk = [_]u8{ @as(u8, @intCast(bytes_written % 256)) } ** chunk_size; _ = source_file.write(&chunk) catch break; bytes_written += chunk_size; } source_file.close(); const chunker = FileChunker.init(piece_size, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); // Test different selection strategies const strategies = .{ .sequential, .rarest_first, .random, .priority_first, .balanced }; var strategy_times = std.ArrayList(f32).init(allocator); defer strategy_times.deinit(); for (strategies) |strategy| { const start_time = std.time.timestamp(); var selector = PieceSelector.init(strategy, 12345, allocator); defer selector.deinit(); // Add pieces with varying availability for (0..piece_count) |i| { const availability = @as(u32, @intCast(i % 20) + 1); // 1 to 20 availability try selector.addPiece(@as(u32, @intCast(i)), availability); // Set some pieces as downloaded to test filtering if (i % 10 == 0) { try selector.markDownloaded(@as(u32, @intCast(i))); if (i % 20 == 0) { try selector.markVerified(@as(u32, @intCast(i))); } } } // Perform selection const selected_pieces = try selector.selectNext(50); defer allocator.free(selected_pieces); const end_time = std.time.timestamp(); const elapsed = @as(f32, @floatFromInt(end_time - start_time)); try testing.expect(selected_pieces.len <= 50); try testing.expect(elapsed < 5.0); // Should complete within 5 seconds try strategy_times.append(elapsed); } // Verify all strategies completed try testing.expectEqual(@as(usize, strategies.len), strategy_times.len); // Sequential should typically be fastest, random might vary const sequential_time = strategy_times[0]; const random_time = strategy_times[2]; // Random might be slower due to randomization overhead try testing.expect(random_time >= 0.0); // Clean up fs.cwd().deleteFile(source_path) catch return; } test "concurrent operations stress test" { const allocator = testing.allocator; // Create a moderate-sized file const source_path = "concurrent_stress_source.bin"; const file_size: u64 = 100 * 1024; // 100KB const piece_size: u64 = 4096; // 4KB pieces const source_file = fs.cwd().createFile(source_path, .{}) catch return; // Write file var bytes_written: u64 = 0; while (bytes_written < file_size) { const chunk_size = @min(4096, file_size - bytes_written); const chunk = [_]u8{ @as(u8, @intCast(bytes_written % 256)) } ** chunk_size; _ = source_file.write(&chunk) catch break; bytes_written += chunk_size; } source_file.close(); // Step 1: Initialize multiple managers for concurrent operations var download_managers = std.ArrayList(DownloadManager).init(allocator); defer { for (download_managers.items) |*dm| { dm.deinit(); } download_managers.deinit(); } var upload_managers = std.ArrayList(UploadManager).init(allocator); defer { for (upload_managers.items) |*um| { um.deinit(); } upload_managers.deinit(); } const chunker = FileChunker.init(piece_size, allocator); const metadata = try chunker.createMetadata(source_path); defer allocator.free(metadata.piece_hashes); // Step 2: Create multiple managers (simulating concurrent operations) const manager_count = 10; const concurrent_start = std.time.timestamp(); for (0..manager_count) |i| { // Create download manager var download_manager = try DownloadManager.init( metadata.size, metadata.piece_count, .sequential, piece_size, allocator, ); try download_managers.append(download_manager); // Create upload manager var upload_manager = try UploadManager.init( 1024 * 1024, // 1MB/s piece_size, allocator, ); try upload_managers.append(upload_manager); } const concurrent_init_time = std.time.timestamp() - concurrent_start; // Step 3: Perform concurrent operations const operations_start = std.time.timestamp(); // Add pieces to all managers for (download_managers.items, 0..) |*download_manager, i| { const peer_id = try fmt.allocPrint(allocator, "peer_{d}", .{i}); defer allocator.free(peer_id); for (0..metadata.piece_count) |piece_idx| { try download_manager.addPiece(@as(u32, @intCast(piece_idx)), 1); } try download_manager.addPeer(peer_id, &.{0}); try download_manager.requestPiece(0, .normal, peer_id); } for (upload_managers.items, metadata.piece_hashes) |*upload_manager, hash| { try upload_manager.addAvailablePiece(0, hash); _ = try upload_manager.handleUploadRequest(0, 0, piece_size, "request_peer", .normal); } // Process all managers for (download_managers.items) |*download_manager| { try download_manager.processRequests(1); } for (upload_managers.items) |*upload_manager| { try upload_manager.processRequests(1); } const operations_time = std.time.timestamp() - operations_start; // Step 4: Performance assertions try testing.expect(concurrent_init_time < 20); // Should handle 10 managers reasonably try testing.expect(operations_time < 10); // Concurrent operations should be fast // Verify some operations completed var completed_downloads: usize = 0; for (download_managers.items) |download_manager| { if (download_manager.active_downloads.count() > 0) { completed_downloads += 1; } } var active_uploads: usize = 0; for (upload_managers.items) |upload_manager| { if (upload_manager.active_uploads.count() > 0) { active_uploads += 1; } } try testing.expect(completed_downloads > 0 or upload_managers.items.len == 0); try testing.expect(active_uploads > 0); // Clean up fs.cwd().deleteFile(source_path) catch return; } test "memory cleanup and resource management" { const allocator = testing.allocator; // Test proper cleanup of resources var managers = std.ArrayList(std.meta.FieldType(FileSharingManager, "sessions")).init(allocator); defer managers.deinit(); // Create and destroy multiple managers to test memory cleanup for (0..5) |i| { const config = FileSharingConfig.default(); var manager = try FileSharingManager.init(config, allocator); // Create some test files for (0..3) |j| { const file_path = try fmt.allocPrint(allocator, "cleanup_test_{d}_{d}.bin", .{ i, j }); defer allocator.free(file_path); const content = try fmt.allocPrint(allocator, "Content {d}-{d}", .{ i, j }); defer allocator.free(content); const file = fs.cwd().createFile(file_path, .{}) catch continue; _ = file.write(content) catch continue; file.close(); // Add file to manager _ = manager.addFile(file_path) catch continue; } // Get stats (some operations) const stats = manager.getStats(); _ = stats.total_sessions; // Use the value to prevent optimization // Manager will be cleaned up when it goes out of scope } // If we get here without memory issues, cleanup is working try testing.expect(true); // Clean up any remaining test files for (0..5) |i| { for (0..3) |j| { const file_path = try fmt.allocPrint(allocator, "cleanup_test_{d}_{d}.bin", .{ i, j }); defer allocator.free(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); }