This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

View File

@@ -0,0 +1,646 @@
//! Performance benchmarks and stress testing integration tests
//!
//! This module tests the performance characteristics of the P2P library under
//! various load conditions, including stress testing and throughput measurements.
const std = @import("std");
const testing = std.testing;
const fs = std.fs;
const mem = std.mem;
const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap;
const time = std.time;
// Import P2P library components
const P2P = @import("../../src/p2p.zig").P2P;
const P2PConfig = @import("../../src/p2p.zig").P2PConfig;
const P2PEvent = @import("../../src/p2p.zig").P2PEvent;
const P2PState = @import("../../src/p2p.zig").P2PState;
const Address = @import("../../src/core/address.zig").Address;
const PeerId = @import("../../src/network/peer.zig").PeerId;
const FileMetadata = @import("../../src/files/hash.zig").FileMetadata;
const FileUtils = @import("../../src/files/hash.zig").FileUtils;
const FileSharingManager = @import("../../src/files/manager.zig").FileSharingManager;
const FileSharingConfig = @import("../../src/files/manager.zig").FileSharingConfig;
const { DownloadManager } = @import("../../src/files/download.zig");
const Error = @import("../../src/core/error.zig").Error;
/// Performance testing scenarios and benchmarks
pub const PerformanceTests = struct {
allocator: mem.Allocator,
pub fn init(allocator: mem.Allocator) PerformanceTests {
return PerformanceTests{ .allocator = allocator };
}
pub fn deinit(self: *PerformanceTests) void {
_ = self;
}
/// Benchmark P2P library initialization and startup
pub fn testInitializationPerformance(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing Initialization Performance ===\n", .{});
const iterations = 50;
var total_time: i128 = 0;
var min_time: i128 = std.math.maxInt(i128);
var max_time: i128 = 0;
for (0..iterations) |i| {
const start_time = time.timestamp();
var p2p = try P2P.init(self.allocator, P2PConfig.default());
defer p2p.deinit();
const init_time = time.timestamp() - start_time;
total_time += init_time;
min_time = @min(min_time, init_time);
max_time = @max(max_time, init_time);
if (i % 10 == 0) {
std.debug.print(" Progress: {d}/{d} initializations\n", .{ i + 1, iterations });
}
}
const avg_time = @as(f32, @floatFromInt(total_time)) / @as(f32, @floatFromInt(iterations));
std.debug.print(" Average init time: {d:.3}s\n", .{avg_time});
std.debug.print(" Min init time: {d:.3}s\n", .{@as(f32, @floatFromInt(min_time))});
std.debug.print(" Max init time: {d:.3}s\n", .{@as(f32, @floatFromInt(max_time))});
// Performance requirements
try std.testing.expect(avg_time < 0.5); // Should initialize in under 500ms on average
std.debug.print("✓ Initialization performance test passed\n", .{});
}
/// Benchmark file sharing operations
pub fn testFileSharingPerformance(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing File Sharing Performance ===\n", .{});
const file_count = 10;
var file_paths = ArrayList([]const u8).init(self.allocator);
defer {
for (file_paths.items) |path| {
self.allocator.free(path);
}
file_paths.deinit();
}
// Create test files
for (0..file_count) |i| {
const file_path = try std.fmt.allocPrint(self.allocator, "perf_test_{d}.bin", .{i});
try file_paths.append(file_path);
const content = try std.fmt.allocPrint(self.allocator, "Performance test file {d} with some content", .{i});
defer self.allocator.free(content);
try self.createTestFile(file_path, content);
defer fs.cwd().deleteFile(file_path) catch {};
}
var p2p = try P2P.init(self.allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
// Benchmark file addition
const add_start = time.timestamp();
var session_ids = ArrayList(u64).init(self.allocator);
defer session_ids.deinit();
for (file_paths.items) |file_path| {
const session_id = try p2p.addFile(file_path);
try session_ids.append(session_id);
}
const add_time = time.timestamp() - add_start;
// Benchmark session startup
const start_start = time.timestamp();
for (session_ids.items) |session_id| {
try p2p.startSharing(session_id);
}
const start_time = time.timestamp() - start_start;
// Process events
_ = p2p.processAllEvents();
// Performance metrics
const files_per_second = @as(f32, @floatFromInt(file_count)) / @as(f32, @floatFromInt(add_time));
const sessions_per_second = @as(f32, @floatFromInt(file_count)) / @as(f32, @floatFromInt(start_time));
std.debug.print(" Added {d} files in {d}s ({d:.1f} files/sec)\n", .{
file_count, add_time, files_per_second
});
std.debug.print(" Started {d} sessions in {d}s ({d:.1f} sessions/sec)\n", .{
file_count, start_time, sessions_per_second
});
// Performance requirements
try std.testing.expect(files_per_second > 10.0); // Should handle at least 10 file additions per second
try std.testing.expect(sessions_per_second > 50.0); // Should handle at least 50 session starts per second
// Clean up
for (session_ids.items) |session_id| {
_ = p2p.stopSharing(session_id);
}
try p2p.stop();
std.debug.print("✓ File sharing performance test passed\n", .{});
}
/// Benchmark event processing performance
pub fn testEventProcessingPerformance(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing Event Processing Performance ===\n", .{});
const event_count = 1000;
var p2p = try P2P.init(self.allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
// Generate many events
const generate_start = time.timestamp();
for (0..event_count) |i| {
const event = P2PEvent.create(.message_sent, .{
.message_sent = .{
.message_type = @as(u8, @intCast(i % 256)),
.destination = null,
}
});
_ = p2p.emitEvent(event);
}
const generate_time = time.timestamp() - generate_start;
// Process events and measure throughput
const process_start = time.timestamp();
const processed = p2p.processAllEvents();
const process_time = time.timestamp() - process_start;
const events_per_second = @as(f32, @floatFromInt(event_count)) / @as(f32, @floatFromInt(process_time));
std.debug.print(" Generated {d} events in {d}s\n", .{ event_count, generate_time });
std.debug.print(" Processed {d} events in {d}s ({d:.1f} events/sec)\n", .{
processed, process_time, events_per_second
});
// Performance requirements
try std.testing.expect(events_per_second > 1000.0); // Should process at least 1000 events per second
try p2p.stop();
std.debug.print("✓ Event processing performance test passed\n", .{});
}
/// Stress test with many peers
pub fn testManyPeersStressTest(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing Many Peers Stress Test ===\n", .{});
const peer_count = 20;
var peers = ArrayList(P2P).init(self.allocator);
defer {
for (peers.items) |*p2p| {
p2p.deinit();
}
peers.deinit();
}
const start_time = time.timestamp();
// Initialize all peers
for (0..peer_count) |i| {
var config = P2PConfig.high_performance();
config.network.listen_port = @as(u16, 15000 + i);
var p2p = try P2P.init(self.allocator, config);
try peers.append(p2p);
}
const init_time = time.timestamp() - start_time;
const connect_start = time.timestamp();
// Establish connections between all peers
for (0..peer_count) |i| {
for (i + 1..peer_count) |j| {
var address = Address.init();
address.port = @as(u16, 15000 + j);
_ = try peers.items[i].connectToPeer(address);
}
}
const connect_time = time.timestamp() - connect_start;
// Start all peers
const start_start = time.timestamp();
for (peers.items) |*p2p| {
try p2p.start();
}
const start_peers_time = time.timestamp() - start_start;
// Process events for all peers
const process_start = time.timestamp();
for (peers.items) |*p2p| {
_ = p2p.processAllEvents();
}
const process_time = time.timestamp() - process_start;
const total_time = time.timestamp() - start_time;
// Performance metrics
const connections_per_second = @as(f32, @floatFromInt(peer_count * (peer_count - 1) / 2)) / @as(f32, @floatFromInt(connect_time));
const peer_init_per_second = @as(f32, @floatFromInt(peer_count)) / @as(f32, @floatFromInt(init_time));
std.debug.print(" Initialized {d} peers in {d}s ({d:.1f} peers/sec)\n", .{
peer_count, init_time, peer_init_per_second
});
std.debug.print(" Established {d} connections in {d}s ({d:.1f} conns/sec)\n", .{
peer_count * (peer_count - 1) / 2, connect_time, connections_per_second
});
std.debug.print(" Started {d} peers in {d}s\n", .{ peer_count, start_peers_time });
std.debug.print(" Processed events in {d}s\n", .{ process_time });
std.debug.print(" Total time: {d}s\n", .{ total_time });
// Verify all peers are operational
for (peers.items) |p2p| {
try std.testing.expect(p2p.isOperational());
}
// Clean shutdown
for (peers.items) |*p2p| {
try p2p.stop();
}
std.debug.print("✓ Many peers stress test passed\n", .{});
}
/// Benchmark memory usage under load
pub fn testMemoryUsageUnderLoad(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing Memory Usage Under Load ===\n", .{});
const operation_count = 100;
var p2p = try P2P.init(self.allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
// Track memory usage over operations
const memory_samples = ArrayList(usize).init(self.allocator);
defer memory_samples.deinit();
// Create test files for sharing
for (0..operation_count) |i| {
const file_path = try std.fmt.allocPrint(self.allocator, "memory_test_{d}.bin", .{i});
defer self.allocator.free(file_path);
const content = try std.fmt.allocPrint(self.allocator, "Memory test file {d}", .{i});
defer self.allocator.free(content);
try self.createTestFile(file_path, content);
defer fs.cwd().deleteFile(file_path) catch {};
// Add file and start sharing
const session_id = try p2p.addFile(file_path);
try p2p.startSharing(session_id);
// Sample memory usage
const stats = p2p.getStats();
try memory_samples.append(stats.memory_allocated);
// Clean up every 10 operations to test memory management
if (i % 10 == 0) {
_ = p2p.stopSharing(session_id);
_ = p2p.processAllEvents();
}
}
// Analyze memory usage
var min_memory: usize = std.math.maxInt(usize);
var max_memory: usize = 0;
var total_memory: usize = 0;
for (memory_samples.items) |memory| {
min_memory = @min(min_memory, memory);
max_memory = @max(max_memory, memory);
total_memory += memory;
}
const avg_memory = total_memory / memory_samples.items.len;
const memory_growth = if (memory_samples.items.len > 1)
@as(f32, @floatFromInt(memory_samples.items[memory_samples.items.len - 1] - memory_samples.items[0]))
else 0;
std.debug.print(" Memory samples: {d}\n", .{memory_samples.items.len});
std.debug.print(" Min memory: {d} bytes\n", .{min_memory});
std.debug.print(" Max memory: {d} bytes\n", .{max_memory});
std.debug.print(" Avg memory: {d} bytes\n", .{avg_memory});
std.debug.print(" Memory growth: {d} bytes\n", .{
@as(i32, @intCast(memory_growth))
});
// Memory growth should be reasonable (less than 10MB for 100 operations)
try std.testing.expect(memory_growth < 10 * 1024 * 1024);
try p2p.stop();
std.debug.print("✓ Memory usage under load test passed\n", .{});
}
/// Benchmark network throughput simulation
pub fn testNetworkThroughputSimulation(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing Network Throughput Simulation ===\n", .{});
const message_count = 1000;
const message_size = 1024; // 1KB messages
var p2p = try P2P.init(self.allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
// Create large message payload
const payload = try self.allocator.alloc(u8, message_size);
defer self.allocator.free(payload);
@memset(payload, 'A');
const throughput_start = time.timestamp();
// Send many messages
for (0..message_count) |i| {
const message_data = try std.fmt.allocPrint(self.allocator, "Message {d}: {s}", .{i, payload});
defer self.allocator.free(message_data);
const message_id = try p2p.sendMessage(null, @as(u8, @intCast(i % 256)), message_data);
_ = message_id; // Ignore result
}
const throughput_time = time.timestamp() - throughput_start;
// Calculate throughput
const total_bytes = message_count * message_size;
const throughput_bps = @as(f64, @floatFromInt(total_bytes)) / @as(f64, @floatFromInt(throughput_time));
const throughput_mbps = throughput_bps / (1024.0 * 1024.0);
const messages_per_second = @as(f64, @floatFromInt(message_count)) / @as(f64, @floatFromInt(throughput_time));
std.debug.print(" Sent {d} messages ({d} bytes) in {d}s\n", .{
message_count, total_bytes, throughput_time
});
std.debug.print(" Throughput: {d:.1f} MB/s ({d:.1f} messages/sec)\n", .{
throughput_mbps, messages_per_second
});
// Process events to complete the test
_ = p2p.processAllEvents();
// Performance requirements (these are simulation targets)
try std.testing.expect(messages_per_second > 100.0); // Should handle at least 100 messages per second
try std.testing.expect(throughput_bps > 1024.0); // Should handle at least 1KB/s
try p2p.stop();
std.debug.print("✓ Network throughput simulation test passed\n", .{});
}
/// Test performance with different configurations
pub fn testPerformanceWithDifferentConfigs(self: *PerformanceTests) !void {
std.debug.print("\n=== Testing Performance with Different Configs ===\n", .{});
const configs = .{
P2PConfig.low_resource(),
P2PConfig.default(),
P2PConfig.high_performance(),
};
const config_names = .{ "Low Resource", "Default", "High Performance" };
for (configs, config_names) |config, name| {
std.debug.print(" Testing {s} config...\n", .{name});
const start_time = time.timestamp();
var p2p = try P2P.init(self.allocator, config);
defer p2p.deinit();
try p2p.start();
// Perform standard operations
const file_path = try std.fmt.allocPrint(self.allocator, "config_test_{s}.bin", .{name});
defer self.allocator.free(file_path);
const content = try std.fmt.allocPrint(self.allocator, "Config test for {s}", .{name});
defer self.allocator.free(content);
try self.createTestFile(file_path, content);
defer fs.cwd().deleteFile(file_path) catch {};
const session_id = try p2p.addFile(file_path);
try p2p.startSharing(session_id);
_ = p2p.processAllEvents();
const config_time = time.timestamp() - start_time;
const stats = p2p.getStats();
try std.testing.expect(stats.state == P2PState.Running);
std.debug.print(" {s} config completed in {d}s\n", .{ name, config_time });
try p2p.stop();
}
std.debug.print("✓ Different configs performance test passed\n", .{});
}
/// Helper: Create test file
fn createTestFile(self: *PerformanceTests, file_path: []const u8, content: []const u8) !void {
const file = fs.cwd().createFile(file_path, .{}) catch return;
defer file.close();
_ = try file.write(content);
}
};
// Individual test functions for Zig test runner
test "P2P library initialization performance" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testInitializationPerformance();
}
test "file sharing performance benchmarks" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testFileSharingPerformance();
}
test "event processing performance" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testEventProcessingPerformance();
}
test "many peers stress test" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testManyPeersStressTest();
}
test "memory usage under load" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testMemoryUsageUnderLoad();
}
test "network throughput simulation" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testNetworkThroughputSimulation();
}
test "performance with different configurations" {
const allocator = testing.allocator;
var tests = PerformanceTests.init(allocator);
defer tests.deinit();
try tests.testPerformanceWithDifferentConfigs();
}
test "sustained operation performance" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
const start_time = time.timestamp();
const duration_seconds = 5; // Run for 5 seconds
var operations_count: usize = 0;
while (time.timestamp() - start_time < duration_seconds) {
// Perform various operations
const test_event = P2PEvent.create(.message_sent, .{
.message_sent = .{ .message_type = 0x80, .destination = null }
});
_ = p2p.emitEvent(test_event);
_ = p2p.processAllEvents();
operations_count += 1;
// Small delay to avoid overwhelming the system
time.sleep(100 * time.ns_per_ms);
}
const total_time = time.timestamp() - start_time;
const ops_per_second = @as(f64, @floatFromInt(operations_count)) / @as(f64, @floatFromInt(total_time));
std.debug.print("Sustained operation: {d} operations in {d}s ({d:.1f} ops/sec)\n", .{
operations_count, total_time, ops_per_second
});
// Should maintain reasonable performance over time
try testing.expect(ops_per_second > 10.0);
try p2p.stop();
}
test "concurrent operation performance" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
const concurrent_operations = 10;
var start_time = time.timestamp();
// Perform concurrent-like operations
var session_ids = ArrayList(u64).init(allocator);
defer session_ids.deinit();
for (0..concurrent_operations) |i| {
const file_path = try std.fmt.allocPrint(allocator, "concurrent_{d}.bin", .{i});
defer allocator.free(file_path);
const content = try std.fmt.allocPrint(allocator, "Concurrent operation {d}", .{i});
defer allocator.free(content);
try fs.cwd().createFile(file_path, .{}) catch continue;
defer fs.cwd().deleteFile(file_path) catch {};
_ = try p2p.addFile(file_path);
}
const concurrent_time = time.timestamp() - start_time;
// Process all events
_ = p2p.processAllEvents();
std.debug.print("Concurrent operations: {d} in {d}s\n", .{
concurrent_operations, concurrent_time
});
// Should handle concurrent operations efficiently
try testing.expect(concurrent_time < 5); // Should complete within 5 seconds
try p2p.stop();
}
test "scalability performance test" {
const allocator = testing.allocator;
const scale_factors = .{ 1, 5, 10 };
for (scale_factors) |scale| {
var p2p = try P2P.init(allocator, P2PConfig.high_performance());
defer p2p.deinit();
try p2p.start();
const start_time = time.timestamp();
// Scale operations with factor
const file_count = 10 * scale;
for (0..file_count) |i| {
const file_path = try std.fmt.allocPrint(allocator, "scale_{d}_{d}.bin", .{ scale, i });
defer allocator.free(file_path);
const content = try std.fmt.allocPrint(allocator, "Scale test {d} file {d}", .{ scale, i });
defer allocator.free(content);
try fs.cwd().createFile(file_path, .{}) catch continue;
defer fs.cwd().deleteFile(file_path) catch {};
_ = try p2p.addFile(file_path);
}
const scale_time = time.timestamp() - start_time;
const efficiency = @as(f64, @floatFromInt(file_count)) / @as(f64, @floatFromInt(scale_time));
std.debug.print("Scale factor {d}: {d} files in {d}s ({d:.1f} files/sec)\n", .{
scale, file_count, scale_time, efficiency
});
// Performance should scale reasonably
try testing.expect(efficiency > 1.0); // At least 1 file per second
try p2p.stop();
}
}