//! Stress Testing Suite //! //! High-load stress tests that push the system to its limits: //! - High message volume //! - Many concurrent connections //! - Rapid connect/disconnect cycles //! - Memory pressure scenarios //! - Resource exhaustion handling const std = @import("std"); const testing = std.testing; const p2p_lib = @import("p2p"); const core = @import("core"); const network = @import("network"); const P2P = p2p_lib.P2P; const P2PConfig = p2p_lib.P2PConfig; const Address = core.Address; const PeerId = network.peer.PeerId; test "stress: high message volume" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19601; config.protocol.max_message_size = 1024; var peer = try P2P.init(allocator, config); defer peer.deinit(); try peer.start(); _ = peer.processAllEvents(); const num_messages = 1000; const message = "Stress test message payload for high volume testing"; const start_time = std.time.milliTimestamp(); // Send many messages rapidly var send_count: usize = 0; var error_count: usize = 0; for (0..num_messages) |_| { _ = peer.sendMessage(null, 0x01, message) catch { error_count += 1; continue; }; send_count += 1; // Periodic update to prevent queue overflow if (send_count % 100 == 0) { try peer.update(); } } // Final update to process remaining for (0..10) |_| { try peer.update(); std.time.sleep(10 * std.time.ns_per_ms); } const elapsed = std.time.milliTimestamp() - start_time; const stats = peer.getStats(); std.debug.print("High volume test: {} messages in {}ms\n", .{ send_count, elapsed }); std.debug.print("Messages sent: {}, errors: {}\n", .{ stats.messages_sent, error_count }); std.debug.print("Throughput: {d:.2} msg/sec\n", .{@as(f64, @floatFromInt(send_count)) / (@as(f64, @floatFromInt(elapsed)) / 1000.0)}); // Verify system survived and is operational try testing.expect(peer.isOperational()); } test "stress: many concurrent connections attempt" { const allocator = testing.allocator; var config_server = P2PConfig.default(); config_server.network.listen_port = 19611; config_server.network.max_connections = 100; var server = try P2P.init(allocator, config_server); defer server.deinit(); try server.start(); _ = server.processAllEvents(); var listen_addr = Address.init(); listen_addr.port = 19611; listen_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } }; try server.startListening(listen_addr); std.time.sleep(100 * std.time.ns_per_ms); // Create many client instances const num_clients = 10; // Reasonable for unit test var clients: [num_clients]P2P = undefined; var client_ids: [num_clients]?PeerId = [_]?PeerId{null} ** num_clients; // Initialize clients for (&clients, 0..) |*client, i| { var config = P2PConfig.default(); config.network.listen_port = @intCast(19612 + i); client.* = P2P.init(allocator, config) catch |err| { std.debug.print("Client {} init failed: {}\n", .{ i, err }); continue; }; client.start() catch |err| { std.debug.print("Client {} start failed: {}\n", .{ i, err }); continue; }; _ = client.processAllEvents(); } defer { for (&clients) |*client| { client.deinit(); } } const start_time = std.time.milliTimestamp(); // Connect all clients to server for (&clients, 0..) |*client, i| { var connect_addr = Address.init(); connect_addr.port = 19611; connect_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } }; client_ids[i] = client.connectToPeer(connect_addr) catch |err| { std.debug.print("Client {} connect failed: {}\n", .{ i, err }); continue; }; } // Update all to process connections for (0..100) |_| { try server.update(); for (&clients) |*client| { try client.update(); } std.time.sleep(5 * std.time.ns_per_ms); } const elapsed = std.time.milliTimestamp() - start_time; const server_stats = server.getStats(); std.debug.print("Connection stress: {} clients attempted, {} connected in {}ms\n", .{ num_clients, server_stats.active_connections, elapsed, }); // Verify server is still operational try testing.expect(server.isOperational()); } test "stress: rapid connect disconnect cycles" { const allocator = testing.allocator; var config_server = P2PConfig.default(); config_server.network.listen_port = 19621; var server = try P2P.init(allocator, config_server); defer server.deinit(); try server.start(); _ = server.processAllEvents(); var listen_addr = Address.init(); listen_addr.port = 19621; listen_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } }; try server.startListening(listen_addr); std.time.sleep(50 * std.time.ns_per_ms); var config_client = P2PConfig.default(); config_client.network.listen_port = 19622; var client = try P2P.init(allocator, config_client); defer client.deinit(); try client.start(); _ = client.processAllEvents(); const num_cycles = 50; var success_count: usize = 0; var connect_errors: usize = 0; var disconnect_errors: usize = 0; const start_time = std.time.milliTimestamp(); for (0..num_cycles) |i| { var connect_addr = Address.init(); connect_addr.port = 19621; connect_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } }; const peer_id = client.connectToPeer(connect_addr) catch |err| { std.debug.print("Cycle {} connect failed: {}\n", .{ i, err }); connect_errors += 1; continue; }; // Brief connection time for (0..5) |_| { try server.update(); try client.update(); std.time.sleep(2 * std.time.ns_per_ms); } // Disconnect client.disconnectPeer(peer_id) catch |err| { std.debug.print("Cycle {} disconnect failed: {}\n", .{ i, err }); disconnect_errors += 1; continue; }; success_count += 1; // Brief pause between cycles for (0..5) |_| { try server.update(); try client.update(); std.time.sleep(2 * std.time.ns_per_ms); } } const elapsed = std.time.milliTimestamp() - start_time; std.debug.print("Rapid cycles: {} successful, {} connect errors, {} disconnect errors in {}ms\n", .{ success_count, connect_errors, disconnect_errors, elapsed, }); // Verify both peers still operational try testing.expect(server.isOperational()); try testing.expect(client.isOperational()); } test "stress: event queue saturation" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19631; config.events.max_event_queue = 100; var peer = try P2P.init(allocator, config); defer peer.deinit(); try peer.start(); _ = peer.processAllEvents(); // Generate massive number of events const num_state_changes = 200; const start_time = std.time.milliTimestamp(); for (0..num_state_changes) |_| { try peer.enterMaintenanceMode(); try peer.exitMaintenanceMode(); } const elapsed = std.time.milliTimestamp() - start_time; const stats = peer.getStats(); std.debug.print("Event saturation: {} events generated in {}ms\n", .{ num_state_changes * 2, elapsed }); std.debug.print("Queue size: {}, events dropped: {}\n", .{ stats.event_queue_size, stats.events_dropped.load(.monotonic), }); // Process all remaining events const processed = peer.processAllEvents(); std.debug.print("Processed {} remaining events\n", .{processed}); // Verify system survived try testing.expect(peer.isOperational()); } test "stress: memory allocation pressure" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19641; var peer = try P2P.init(allocator, config); defer peer.deinit(); try peer.start(); // Create and delete many files to stress memory const num_files = 20; for (0..num_files) |i| { const path = try std.fmt.allocPrint(allocator, "stress_file_{}.bin", .{i}); defer allocator.free(path); // Create file var file = try std.fs.cwd().createFile(path, .{}); try file.writeAll("Stress test content " ** 10); file.close(); defer std.fs.cwd().deleteFile(path) catch {}; // Add to peer const session_id = peer.addFile(path) catch |err| { std.debug.print("Add file {} failed: {}\n", .{ i, err }); continue; }; // Update try peer.update(); // Stop sharing to free memory peer.stopSharing(session_id) catch |err| { std.debug.print("Stop sharing {} failed: {}\n", .{ i, err }); }; if (i % 5 == 0) { // Process events to allow cleanup _ = peer.processAllEvents(); } } const stats = peer.getStats(); std.debug.print("Memory pressure test: {} MB allocated\n", .{stats.memory_allocated / (1024 * 1024)}); try testing.expect(peer.isOperational()); } test "stress: prolonged operation" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19651; config.network.health_check_interval_ms = 100; var peer = try P2P.init(allocator, config); defer peer.deinit(); try peer.start(); _ = peer.processAllEvents(); const start_time = std.time.milliTimestamp(); const duration_ms = 1000; // 1 second of continuous operation var iterations: usize = 0; while (std.time.milliTimestamp() - start_time < duration_ms) { try peer.update(); // Simulate various activities if (iterations % 10 == 0) { _ = peer.sendMessage(null, 0x01, "periodic message") catch {}; } if (iterations % 20 == 0) { _ = peer.processAllEvents(); } iterations += 1; std.time.sleep(1 * std.time.ns_per_ms); } const elapsed = std.time.milliTimestamp() - start_time; const stats = peer.getStats(); std.debug.print("Prolonged operation: {} iterations in {}ms\n", .{ iterations, elapsed }); std.debug.print("Final stats: {} connections, {} msgs sent, {} errors\n", .{ stats.active_connections, stats.messages_sent, stats.errors_total.load(.monotonic), }); try testing.expect(peer.isOperational()); try testing.expect(iterations > 0); } test "stress: callback overhead" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19661; var peer = try P2P.init(allocator, config); defer peer.deinit(); // Register many callbacks const num_callbacks = 10; const TestCallbacks = struct { fn cb1(_: p2p_lib.P2PEvent) void {} fn cb2(_: p2p_lib.P2PEvent) void {} fn cb3(_: p2p_lib.P2PEvent) void {} fn cb4(_: p2p_lib.P2PEvent) void {} fn cb5(_: p2p_lib.P2PEvent) void {} fn cb6(_: p2p_lib.P2PEvent) void {} fn cb7(_: p2p_lib.P2PEvent) void {} fn cb8(_: p2p_lib.P2PEvent) void {} fn cb9(_: p2p_lib.P2PEvent) void {} fn cb10(_: p2p_lib.P2PEvent) void {} }; try peer.registerCallback(TestCallbacks.cb1, null); try peer.registerCallback(TestCallbacks.cb2, null); try peer.registerCallback(TestCallbacks.cb3, null); try peer.registerCallback(TestCallbacks.cb4, null); try peer.registerCallback(TestCallbacks.cb5, null); try peer.registerCallback(TestCallbacks.cb6, null); try peer.registerCallback(TestCallbacks.cb7, null); try peer.registerCallback(TestCallbacks.cb8, null); try peer.registerCallback(TestCallbacks.cb9, null); try peer.registerCallback(TestCallbacks.cb10, null); try peer.start(); // Generate many events const num_events = 100; for (0..num_events) |_| { try peer.enterMaintenanceMode(); try peer.exitMaintenanceMode(); } const start_time = std.time.milliTimestamp(); // Process all events (each callback called for each event) const processed = peer.processAllEvents(); const elapsed = std.time.milliTimestamp() - start_time; const total_callback_invocations = processed * num_callbacks; std.debug.print("Callback overhead: {} events * {} callbacks = {} invocations in {}ms\n", .{ processed, num_callbacks, total_callback_invocations, elapsed, }); try testing.expect(peer.isOperational()); } test "stress: stats collection overhead" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19671; config.library.enable_statistics = true; var peer = try P2P.init(allocator, config); defer peer.deinit(); try peer.start(); const num_iterations = 1000; const start_time = std.time.milliTimestamp(); // Continuously read stats for (0..num_iterations) |_| { const stats = peer.getStats(); _ = stats; if (_ % 10 == 0) { try peer.update(); } } const elapsed = std.time.milliTimestamp() - start_time; std.debug.print("Stats overhead: {} getStats() calls in {}ms\n", .{ num_iterations, elapsed }); std.debug.print("Average time per call: {d:.3}ms\n", .{@as(f64, @floatFromInt(elapsed)) / @as(f64, @floatFromInt(num_iterations))}); try testing.expect(peer.isOperational()); } test "stress: resource cleanup under load" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.listen_port = 19681; var peer = try P2P.init(allocator, config); defer peer.deinit(); try peer.start(); // Repeatedly start and stop file sharing sessions for (0..10) |i| { const path = try std.fmt.allocPrint(allocator, "cleanup_test_{}.bin", .{i}); defer allocator.free(path); var file = try std.fs.cwd().createFile(path, .{}); try file.writeAll("Test content for cleanup"); file.close(); defer std.fs.cwd().deleteFile(path) catch {}; const session_id = peer.addFile(path) catch continue; try peer.startSharing(session_id); // Let it run briefly for (0..10) |_| { try peer.update(); std.time.sleep(5 * std.time.ns_per_ms); } // Stop and cleanup try peer.stopSharing(session_id); _ = peer.processAllEvents(); } std.debug.print("Resource cleanup test completed\n", .{}); try testing.expect(peer.isOperational()); }