Files
zigp2p/examples/multi_peer_download_test.zig

690 lines
25 KiB
Zig

//! Multi-Peer Download Test
//!
//! Tests downloading a 5GB file from 10 peers simultaneously.
//! This verifies the P2P swarm functionality where a client can
//! retrieve pieces from multiple sources in parallel.
//!
//! OPTIMIZATIONS:
//! - Parallel peer creation using threads (file hashing runs concurrently)
//! - Parallel peer connections using threads
//!
//! Usage: zig build run-multi-peer-test
const std = @import("std");
pub const std_options: std.Options = .{
.log_level = .warn,
};
const p2p_lib = @import("p2p");
const core = @import("core");
const files = @import("files");
const P2P = p2p_lib.P2P;
const P2PEvent = p2p_lib.P2PEvent;
const Address = core.address.Address;
// Configuration
const TEST_FILE_SIZE_MB: usize = 5120; // 5GB file
// THROUGHPUT NOTE: With all seeders in the same process, CPU contention limits throughput.
// Test results: 2 peers = 361 MB/s, 4 peers = 146 MB/s, 8 peers = 30 MB/s
// For production, seeders should run in separate processes.
const NUM_PEERS: usize = 4; // Balanced between multi-peer testing and throughput
const TEST_FILE_SIZE: usize = TEST_FILE_SIZE_MB * 1024 * 1024;
const PIECE_SIZE: usize = 1024 * 1024; // 1MB pieces (fits within 2MB max message)
const TIMEOUT_MS: i64 = 1200000; // 20 minute timeout for 5GB
const PeerContext = struct {
p2p: ?*P2P = null,
session_id: u64 = 0,
listen_port: u16 = 0,
allocator: std.mem.Allocator,
initialized: bool = false,
init_error: ?anyerror = null,
pub fn deinit(self: *PeerContext) void {
if (self.p2p) |p2p_ptr| {
p2p_ptr.stopSharing(self.session_id) catch {};
p2p_ptr.stop() catch {};
p2p_ptr.deinit();
self.allocator.destroy(p2p_ptr);
self.p2p = null;
}
self.initialized = false;
}
};
/// Thread context for parallel peer creation (with pre-computed metadata)
const PeerInitContext = struct {
peer_index: usize,
base_port: u16,
test_file_path: []const u8,
allowed_dirs: []const []const u8,
allocator: std.mem.Allocator,
result: *PeerContext,
/// Pre-computed metadata (null for first peer which computes it)
metadata: ?*const files.hash.FileMetadata = null,
};
/// Thread context for parallel connections
const ConnectContext = struct {
client: *P2P,
listen_port: u16,
peer_index: usize,
success: bool = false,
peer_id_bytes: [32]u8 = undefined,
has_peer_id: bool = false,
err: ?anyerror = null,
};
/// Initialize a single peer (called from thread)
fn initPeerThread(ctx: *PeerInitContext) void {
const i = ctx.peer_index;
const peer_port = ctx.base_port + @as(u16, @intCast(i));
const listen_port = ctx.base_port + @as(u16, @intCast(NUM_PEERS)) + @as(u16, @intCast(i));
var config = p2p_lib.P2PConfig.default();
config.network.listen_port = peer_port;
config.network.enable_noise_encryption = false;
config.events.enable_logging = false;
config.file_sharing.max_concurrent_uploads = 64;
config.file_sharing.piece_size = PIECE_SIZE;
config.file_sharing.allowed_share_directories = ctx.allowed_dirs;
config.file_sharing.max_bandwidth_upload = 1024 * 1024 * 1024;
config.network.idle_timeout_ms = 600000;
const p2p_ptr = ctx.allocator.create(P2P) catch {
ctx.result.init_error = error.OutOfMemory;
return;
};
p2p_ptr.* = P2P.init(ctx.allocator, config) catch |err| {
ctx.allocator.destroy(p2p_ptr);
ctx.result.init_error = err;
return;
};
p2p_ptr.start() catch |err| {
p2p_ptr.deinit();
ctx.allocator.destroy(p2p_ptr);
ctx.result.init_error = err;
return;
};
const listen_addr = Address.ipv4(.{ 127, 0, 0, 1 }, listen_port);
p2p_ptr.startListening(listen_addr) catch |err| {
p2p_ptr.stop() catch {};
p2p_ptr.deinit();
ctx.allocator.destroy(p2p_ptr);
ctx.result.init_error = err;
return;
};
// Use pre-computed metadata if available (skips expensive file hashing)
const session_id = if (ctx.metadata) |meta|
p2p_ptr.addFileWithMetadata(ctx.test_file_path, meta.*) catch |err| {
p2p_ptr.stop() catch {};
p2p_ptr.deinit();
ctx.allocator.destroy(p2p_ptr);
ctx.result.init_error = err;
return;
}
else
p2p_ptr.addFile(ctx.test_file_path) catch |err| {
p2p_ptr.stop() catch {};
p2p_ptr.deinit();
ctx.allocator.destroy(p2p_ptr);
ctx.result.init_error = err;
return;
};
p2p_ptr.startSharing(session_id) catch |err| {
p2p_ptr.stop() catch {};
p2p_ptr.deinit();
ctx.allocator.destroy(p2p_ptr);
ctx.result.init_error = err;
return;
};
ctx.result.p2p = p2p_ptr;
ctx.result.session_id = session_id;
ctx.result.listen_port = listen_port;
ctx.result.allocator = ctx.allocator;
ctx.result.initialized = true;
}
/// Connect to a single peer (called from thread)
fn connectPeerThread(ctx: *ConnectContext) void {
const listen_addr = Address.ipv4(.{ 127, 0, 0, 1 }, ctx.listen_port);
const peer_id = ctx.client.connectToPeer(listen_addr) catch |err| {
ctx.err = err;
ctx.success = false;
return;
};
ctx.peer_id_bytes = peer_id.bytes;
ctx.has_peer_id = true;
ctx.success = true;
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
std.debug.print("=== Multi-Peer Download Test ===\n", .{});
std.debug.print(" File size: {} MB\n", .{TEST_FILE_SIZE_MB});
std.debug.print(" Peers: {}\n", .{NUM_PEERS});
std.debug.print(" Piece size: {} KB\n\n", .{PIECE_SIZE / 1024});
// Use random base port to avoid conflicts
const random_base = @mod(@as(u16, @truncate(@as(u64, @bitCast(std.time.milliTimestamp())))), 1000);
const base_port: u16 = 41000 + random_base;
std.debug.print("Using base port: {}\n\n", .{base_port});
// Create test file
std.debug.print("1. Creating/verifying test file...\n", .{});
const test_file_path = "./tests/test_data/multi_peer_test_source.bin";
const download_path = "./tests/test_data/multi_peer_test_download.bin";
// Check if source file already exists with correct size
const need_create = blk: {
const existing = std.fs.cwd().openFile(test_file_path, .{}) catch break :blk true;
defer existing.close();
const stat = existing.stat() catch break :blk true;
break :blk stat.size != TEST_FILE_SIZE;
};
if (need_create) {
std.debug.print(" Creating {} MB test file...\n", .{TEST_FILE_SIZE_MB});
const file = try std.fs.cwd().createFile(test_file_path, .{});
defer file.close();
// PERF: Write in 1MB chunks instead of 16 bytes at a time
const CHUNK_SIZE: usize = 1024 * 1024; // 1MB
var chunk: [CHUNK_SIZE]u8 = undefined;
// Fill chunk with repeating pattern
const pattern = "0123456789ABCDEF";
for (0..CHUNK_SIZE) |i| {
chunk[i] = pattern[i % pattern.len];
}
var written: usize = 0;
var last_progress: usize = 0;
while (written < TEST_FILE_SIZE) {
const to_write = @min(CHUNK_SIZE, TEST_FILE_SIZE - written);
try file.writeAll(chunk[0..to_write]);
written += to_write;
// Progress every 512MB
if (written - last_progress >= 512 * 1024 * 1024) {
std.debug.print(" ... {} MB written\n", .{written / (1024 * 1024)});
last_progress = written;
}
}
std.debug.print(" Created {s} ({} bytes)\n", .{ test_file_path, TEST_FILE_SIZE });
} else {
std.debug.print(" Reusing existing {s} ({} MB)\n", .{ test_file_path, TEST_FILE_SIZE_MB });
}
// Cleanup download file if exists
std.fs.cwd().deleteFile(download_path) catch {};
// Get current working directory for allowed paths
var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;
const cwd = std.fs.cwd().realpath(".", &cwd_buf) catch ".";
const allowed_dirs = [_][]const u8{cwd};
// Create seeding peers: first peer hashes file, others reuse metadata
std.debug.print("\n2. Creating {} seeding peers...\n", .{NUM_PEERS});
const peer_spawn_start = std.time.milliTimestamp();
var peers: [NUM_PEERS]PeerContext = undefined;
for (&peers) |*p| {
p.* = PeerContext{ .allocator = allocator };
}
var peers_initialized: usize = 0;
defer {
// Cleanup peers in reverse order
var i: usize = peers_initialized;
while (i > 0) {
i -= 1;
peers[i].deinit();
}
}
// STEP 1: Create first peer (hashes the file - this is the slow part)
std.debug.print(" Creating peer 1 (computing file hash)...\n", .{});
const hash_start = std.time.milliTimestamp();
{
var ctx = PeerInitContext{
.peer_index = 0,
.base_port = base_port,
.test_file_path = test_file_path,
.allowed_dirs = &allowed_dirs,
.allocator = allocator,
.result = &peers[0],
.metadata = null, // First peer computes metadata
};
initPeerThread(&ctx);
}
if (!peers[0].initialized) {
std.debug.print(" FATAL: First peer failed to initialize\n", .{});
if (peers[0].init_error) |err| {
std.debug.print(" Error: {}\n", .{err});
}
return error.PeerInitFailed;
}
peers_initialized = 1;
const hash_elapsed = std.time.milliTimestamp() - hash_start;
std.debug.print(" Peer 1 listening on port {} (hashed in {}ms)\n", .{ peers[0].listen_port, hash_elapsed });
// Get metadata from first peer
var metadata: ?files.hash.FileMetadata = null;
if (peers[0].p2p) |p2p_ptr| {
metadata = p2p_ptr.getFileMetadata(peers[0].session_id) catch null;
}
if (metadata == null) {
std.debug.print(" FATAL: Could not get metadata from first peer\n", .{});
return error.NoMetadata;
}
// STEP 2: Create remaining peers in parallel (using pre-computed metadata - FAST!)
if (NUM_PEERS > 1) {
std.debug.print(" Creating peers 2-{} (using cached metadata)...\n", .{NUM_PEERS});
const parallel_start = std.time.milliTimestamp();
var init_contexts: [NUM_PEERS - 1]PeerInitContext = undefined;
var init_threads: [NUM_PEERS - 1]?std.Thread = undefined;
// Spawn remaining peer initialization threads with pre-computed metadata
for (1..NUM_PEERS) |i| {
init_contexts[i - 1] = PeerInitContext{
.peer_index = i,
.base_port = base_port,
.test_file_path = test_file_path,
.allowed_dirs = &allowed_dirs,
.allocator = allocator,
.result = &peers[i],
.metadata = if (metadata) |*m| m else null,
};
init_threads[i - 1] = std.Thread.spawn(.{}, initPeerThread, .{&init_contexts[i - 1]}) catch null;
}
// Wait for all threads to complete
for (0..NUM_PEERS - 1) |i| {
if (init_threads[i]) |thread| {
thread.join();
}
}
// Count successful peers
for (1..NUM_PEERS) |i| {
if (peers[i].initialized) {
peers_initialized += 1;
std.debug.print(" Peer {} listening on port {}\n", .{ i + 1, peers[i].listen_port });
} else if (peers[i].init_error) |err| {
std.debug.print(" Peer {} FAILED: {}\n", .{ i + 1, err });
}
}
const parallel_elapsed = std.time.milliTimestamp() - parallel_start;
std.debug.print(" Peers 2-{} started in {}ms (no hashing)\n", .{ NUM_PEERS, parallel_elapsed });
}
const peer_spawn_elapsed = std.time.milliTimestamp() - peer_spawn_start;
std.debug.print(" {} peers total in {}ms\n", .{ peers_initialized, peer_spawn_elapsed });
// Give peers time to fully initialize
std.Thread.sleep(200 * std.time.ns_per_ms);
// Create downloading client
std.debug.print("\n3. Creating downloading client...\n", .{});
const client_port = base_port + @as(u16, @intCast(NUM_PEERS * 2));
var client_config = p2p_lib.P2PConfig.default();
client_config.network.listen_port = client_port;
client_config.network.enable_noise_encryption = false;
client_config.events.enable_logging = false;
client_config.file_sharing.max_concurrent_downloads = 512;
client_config.file_sharing.piece_size = PIECE_SIZE;
client_config.file_sharing.allowed_share_directories = &allowed_dirs;
client_config.file_sharing.max_bandwidth_download = 1024 * 1024 * 1024; // 1 GB/s
client_config.file_sharing.buffer_pool_size = 1024; // Larger pool for 5GB file
client_config.file_sharing.pipeline_workers = 32;
client_config.file_sharing.verification_workers = 32;
client_config.network.idle_timeout_ms = 600000;
var client = try P2P.init(allocator, client_config);
defer client.deinit();
try client.start();
std.debug.print(" Client started on port {}\n", .{client_port});
// Create download session
std.debug.print("\n4. Creating download session...\n", .{});
const file_metadata = metadata orelse return error.NoMetadata;
std.debug.print(" File: {s}, Size: {} bytes, Pieces: {}\n", .{
file_metadata.name,
file_metadata.size,
file_metadata.piece_count,
});
const download_session_id = try client.downloadFile(file_metadata, download_path);
std.debug.print(" Download session: {}\n", .{download_session_id});
// Connect to all peers IN PARALLEL with background peer updater
std.debug.print("\n5. Connecting to {} peers (parallel)...\n", .{NUM_PEERS});
const connect_start = std.time.milliTimestamp();
// Start background thread to continuously update peers (so they can accept connections)
var stop_updater = std.atomic.Value(bool).init(false);
const UpdaterCtx = struct {
peers_ptr: *[NUM_PEERS]PeerContext,
stop: *std.atomic.Value(bool),
};
var updater_ctx = UpdaterCtx{ .peers_ptr = &peers, .stop = &stop_updater };
const updater_thread = std.Thread.spawn(.{}, struct {
fn run(ctx: *UpdaterCtx) void {
while (!ctx.stop.load(.acquire)) {
for (ctx.peers_ptr) |*peer| {
if (peer.p2p) |p| {
p.update() catch {};
}
}
std.Thread.sleep(100 * std.time.ns_per_us); // 100 microseconds
}
}
}.run, .{&updater_ctx}) catch null;
// Connect to peers in parallel using threads
var connect_results: [NUM_PEERS]ConnectContext = undefined;
var connect_threads: [NUM_PEERS]?std.Thread = undefined;
var num_connect_threads: usize = 0;
for (0..NUM_PEERS) |i| {
if (!peers[i].initialized) {
connect_threads[i] = null;
continue;
}
connect_results[i] = ConnectContext{
.client = &client,
.listen_port = peers[i].listen_port,
.peer_index = i,
};
connect_threads[i] = std.Thread.spawn(.{}, connectPeerThread, .{&connect_results[i]}) catch null;
if (connect_threads[i] != null) num_connect_threads += 1;
}
// Wait for all connection threads to complete
for (0..NUM_PEERS) |i| {
if (connect_threads[i]) |t| {
t.join();
}
}
// Count successful connections and report
var connected_peers: usize = 0;
for (0..NUM_PEERS) |i| {
if (!peers[i].initialized) continue;
if (connect_results[i].success) {
connected_peers += 1;
if (connect_results[i].has_peer_id) {
std.debug.print(" Connected to peer {} (ID: {x})\n", .{ i + 1, connect_results[i].peer_id_bytes[0..4].* });
}
} else if (connect_results[i].err) |err| {
std.debug.print(" Failed to connect to peer {}: {}\n", .{ i + 1, err });
}
}
const connect_elapsed = std.time.milliTimestamp() - connect_start;
if (connected_peers == 0) {
stop_updater.store(true, .release);
if (updater_thread) |t| t.join();
std.debug.print(" ERROR: No peers connected!\n", .{});
return error.NoPeersConnected;
}
std.debug.print(" Connected to {}/{} peers in {}ms\n", .{ connected_peers, NUM_PEERS, connect_elapsed });
// Keep updater running for bitfield exchange
// Run multiple update cycles to ensure protocol messages are exchanged
for (0..50) |_| {
for (&peers) |*peer| {
if (peer.p2p) |p| {
p.update() catch {};
}
}
client.update() catch {};
std.Thread.sleep(10 * std.time.ns_per_ms);
}
// Stop background updater
stop_updater.store(true, .release);
if (updater_thread) |t| t.join();
// Start downloading
std.debug.print("\n6. Starting download...\n", .{});
try client.startSharing(download_session_id);
// Run transfer loop
std.debug.print("\n7. Running file transfer...\n", .{});
const start_time = std.time.milliTimestamp();
var last_progress_print: i64 = 0;
var transfer_complete = false;
while (!transfer_complete) {
const now = std.time.milliTimestamp();
// Check timeout
if (now - start_time > TIMEOUT_MS) {
std.debug.print("\n TIMEOUT: Transfer exceeded {}ms\n", .{TIMEOUT_MS});
break;
}
// THROUGHPUT FIX: Update all peers in PARALLEL using threads
// Previously sequential updates caused 200ms+ blocking when one seeder was slow,
// starving other seeders and causing 22% request timeouts.
var peer_update_threads: [NUM_PEERS]?std.Thread = [_]?std.Thread{null} ** NUM_PEERS;
for (&peers, 0..) |*peer, i| {
if (peer.p2p) |p| {
peer_update_threads[i] = std.Thread.spawn(.{}, struct {
fn run(p2p_ptr: *P2P) void {
p2p_ptr.update() catch {};
}
}.run, .{p}) catch null;
}
}
// Update client on main thread while seeders update in parallel
client.update() catch {};
// Wait for all seeder updates to complete
for (&peer_update_threads) |*maybe_thread| {
if (maybe_thread.*) |thread| {
thread.join();
maybe_thread.* = null;
}
}
// Drain events
for (&peers) |*peer| {
if (peer.p2p) |p| {
while (p.getNextEvent()) |_| {}
}
}
while (client.getNextEvent()) |event| {
switch (event.event_type) {
.file_download_completed => {
std.debug.print(" Download complete event received!\n", .{});
transfer_complete = true;
},
else => {},
}
}
// Check download progress
if (client.file_manager) |fm| {
if (fm.getSessionInfo(download_session_id)) |info| {
if (info.pieces_completed >= info.piece_count) {
transfer_complete = true;
}
// Print progress every second
if (now - last_progress_print >= 1000) {
const elapsed_sec = @as(f64, @floatFromInt(now - start_time)) / 1000.0;
const bytes_done = info.pieces_completed * PIECE_SIZE;
const speed_mbps = if (elapsed_sec > 0)
@as(f64, @floatFromInt(bytes_done)) / elapsed_sec / (1024 * 1024)
else
0;
const progress = @as(f64, @floatFromInt(info.pieces_completed)) /
@as(f64, @floatFromInt(info.piece_count)) * 100.0;
std.debug.print("[{d:.1}s] Progress: {d:.1}% ({}/{} pieces) - {d:.1} MB/s\n", .{
elapsed_sec,
progress,
info.pieces_completed,
info.piece_count,
speed_mbps,
});
last_progress_print = now;
}
}
}
// Small sleep to prevent CPU spin (50us for higher throughput)
if (!transfer_complete) {
std.Thread.sleep(50 * std.time.ns_per_us);
}
}
const end_time = std.time.milliTimestamp();
const total_time_sec = @as(f64, @floatFromInt(end_time - start_time)) / 1000.0;
if (transfer_complete) {
std.debug.print("\n Transfer completed in {d:.1}s\n", .{total_time_sec});
const avg_speed = @as(f64, @floatFromInt(TEST_FILE_SIZE)) / total_time_sec / (1024 * 1024);
std.debug.print(" Average speed: {d:.1} MB/s\n", .{avg_speed});
} else {
std.debug.print("\n WARNING: Transfer did NOT complete (timeout after {d:.1}s)\n", .{total_time_sec});
if (client.file_manager) |fm| {
if (fm.getSessionInfo(download_session_id)) |info| {
std.debug.print(" Only {}/{} pieces downloaded ({d:.1}%)\n", .{
info.pieces_completed,
info.piece_count,
@as(f64, @floatFromInt(info.pieces_completed)) / @as(f64, @floatFromInt(info.piece_count)) * 100.0,
});
}
}
}
// FIX: Stop the piece pipeline BEFORE verification to ensure all pwrite operations complete.
// Pipeline workers process pieces in parallel; when piece 5120 completes, the download is
// marked "done" but other workers may still be writing pieces 5000-5119 to disk.
// stopPiecePipeline() joins all worker threads, ensuring all pwrite ops finish.
if (client.file_manager) |fm| {
std.debug.print("\n Stopping piece pipeline to flush all writes...\n", .{});
fm.stopPiecePipeline();
}
// FIX: Fsync the download file to ensure OS buffers are flushed to disk.
// pwrite() writes to kernel buffers; fsync() ensures data reaches physical media.
{
const sync_file = std.fs.cwd().openFile(download_path, .{ .mode = .write_only }) catch |err| {
std.debug.print(" WARNING: Could not open file for fsync: {}\n", .{err});
return err;
};
sync_file.sync() catch |err| {
std.debug.print(" WARNING: fsync failed: {}\n", .{err});
};
sync_file.close();
std.debug.print(" File synced to disk.\n", .{});
}
// Verify the downloaded file
std.debug.print("\n8. Verifying download...\n", .{});
const download_file = std.fs.cwd().openFile(download_path, .{}) catch |err| {
std.debug.print(" ERROR: Could not open downloaded file: {}\n", .{err});
return err;
};
defer download_file.close();
const stat = try download_file.stat();
if (stat.size != TEST_FILE_SIZE) {
std.debug.print(" ERROR: Size mismatch! Expected {} bytes, got {} bytes\n", .{
TEST_FILE_SIZE,
stat.size,
});
return error.SizeMismatch;
}
// Verify content by sampling
var buf: [16]u8 = undefined;
const pattern = "0123456789ABCDEF";
var verified_samples: usize = 0;
const sample_positions = [_]u64{ 0, TEST_FILE_SIZE / 4, TEST_FILE_SIZE / 2, TEST_FILE_SIZE * 3 / 4, TEST_FILE_SIZE - 16 };
for (sample_positions) |pos| {
try download_file.seekTo(pos);
const bytes_read = try download_file.read(&buf);
if (bytes_read == 16) {
const expected_offset = pos % 16;
var matches = true;
for (0..16) |i| {
const expected_char = pattern[(expected_offset + i) % 16];
if (buf[i] != expected_char) {
matches = false;
break;
}
}
if (matches) {
verified_samples += 1;
}
}
}
if (verified_samples == sample_positions.len) {
std.debug.print(" SUCCESS: Content verified ({} samples checked)\n", .{verified_samples});
} else {
std.debug.print(" WARNING: Only {}/{} samples matched\n", .{ verified_samples, sample_positions.len });
}
// Print final statistics
std.debug.print("\n9. Final Statistics:\n", .{});
std.debug.print(" File size: {} MB\n", .{TEST_FILE_SIZE_MB});
std.debug.print(" Peers used: {}\n", .{connected_peers});
std.debug.print(" Total time: {d:.1}s\n", .{total_time_sec});
if (total_time_sec > 0) {
// Use actual verified bytes for throughput, not total file size
const actual_bytes: usize = if (client.file_manager) |fm| blk: {
if (fm.getSessionInfo(download_session_id)) |info| {
break :blk @as(usize, info.pieces_completed) * PIECE_SIZE;
}
break :blk TEST_FILE_SIZE;
} else TEST_FILE_SIZE;
std.debug.print(" Throughput: {d:.1} MB/s\n", .{@as(f64, @floatFromInt(actual_bytes)) / total_time_sec / (1024 * 1024)});
}
// Print detailed profiling stats
if (client.file_manager) |fm| {
const prof_stats = fm.getProfilingStats();
prof_stats.print();
}
// Cleanup
std.debug.print("\n10. Cleaning up...\n", .{});
client.stopSharing(download_session_id) catch {};
try client.stop();
// DEBUG: Keep download file for analysis
// std.fs.cwd().deleteFile(download_path) catch {};
std.debug.print(" DEBUG: Keeping download file for analysis: {s}\n", .{download_path});
std.debug.print("\n=== Multi-Peer Download Test Complete ===\n", .{});
}