Files
zigp2p/examples/file_transfer_test.zig
2026-02-06 21:03:59 -03:00

447 lines
19 KiB
Zig

//! File Transfer Integration Test
//!
//! Tests actual file transfer between two P2P instances.
//! Creates a file on server side, transfers it to client, and verifies contents.
//!
//! Usage: Set TEST_FILE_SIZE_MB to control test file size (default: 0 = small test)
const std = @import("std");
// Disable debug logging for performance - only show warnings and above
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;
const FileMetadata = files.FileMetadata;
// Configuration: Set to 0 for small test, or size in MB for large test
const TEST_FILE_SIZE_MB: usize = 5120; // Set to 10, 100, 500, 1024, 2048, 5120 etc for larger tests
const SMALL_TEST_CONTENT = "Hello from P2P file transfer!\nThis is line 2.\nThis is line 3 with more content.\nEnd of test file.\n";
// Calculate actual test size and piece size
const TEST_FILE_SIZE: usize = if (TEST_FILE_SIZE_MB > 0) TEST_FILE_SIZE_MB * 1024 * 1024 else SMALL_TEST_CONTENT.len;
const USE_LARGE_FILE = TEST_FILE_SIZE_MB > 0;
// Use larger pieces for large files to reduce overhead
// PERF: 512KB leaves room for protocol headers within 1MB max message size
const PIECE_SIZE: usize = if (TEST_FILE_SIZE_MB >= 10) 512 * 1024 else 1024;
// Timeout scales with file size
const TIMEOUT_MS: i64 = if (TEST_FILE_SIZE_MB >= 5000) 7200000 else if (TEST_FILE_SIZE_MB >= 2000) 3600000 else if (TEST_FILE_SIZE_MB >= 1000) 1200000 else if (TEST_FILE_SIZE_MB >= 500) 600000 else if (TEST_FILE_SIZE_MB >= 100) 300000 else if (TEST_FILE_SIZE_MB >= 10) 60000 else 30000;
pub fn main() !void {
const allocator = std.heap.page_allocator;
std.debug.print("=== P2P File Transfer Integration Test ===\n\n", .{});
// Use random ports to avoid conflicts
const random_base = @mod(@as(u16, @truncate(@as(u64, @bitCast(std.time.milliTimestamp())))), 1000);
const server_port = 40000 + random_base;
const client_port = 40001 + random_base;
const listen_port = 40002 + random_base;
std.debug.print("Using ports: Server={}, Client={}, Listen={}\n\n", .{ server_port, client_port, listen_port });
// Create test file under tests/test_data (avoid polluting root directory)
std.debug.print("1. Creating test file to share...\n", .{});
const test_file_path = "./tests/test_data/p2p_test_source.txt";
const download_path = "./tests/test_data/p2p_test_download.txt";
// Check if source file already exists with correct size (reuse to save time)
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) {
const file = try std.fs.cwd().createFile(test_file_path, .{});
defer file.close();
if (USE_LARGE_FILE) {
// Generate large file with repeating pattern
var written: usize = 0;
const pattern = "0123456789ABCDEF"; // 16-byte pattern for easy verification
while (written < TEST_FILE_SIZE) {
const to_write = @min(pattern.len, TEST_FILE_SIZE - written);
try file.writeAll(pattern[0..to_write]);
written += to_write;
}
std.debug.print(" Created {s} ({d} MB, {d} bytes)\n", .{ test_file_path, TEST_FILE_SIZE_MB, TEST_FILE_SIZE });
} else {
try file.writeAll(SMALL_TEST_CONTENT);
std.debug.print(" Created {s} ({d} bytes)\n", .{ test_file_path, TEST_FILE_SIZE });
}
} else {
std.debug.print(" Reusing existing {s} ({d} MB, {d} bytes)\n", .{ test_file_path, TEST_FILE_SIZE_MB, TEST_FILE_SIZE });
}
// 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};
// Configure server
var server_config = p2p_lib.P2PConfig.default();
server_config.network.listen_port = server_port;
server_config.events.enable_logging = false;
server_config.file_sharing.max_concurrent_uploads = 128;
server_config.file_sharing.piece_size = PIECE_SIZE;
server_config.file_sharing.allowed_share_directories = &allowed_dirs;
server_config.file_sharing.max_bandwidth_upload = 100 * 1024 * 1024; // 100 MB/s for testing
// Increase idle timeout for large file transfers (5GB hashing can take 100+ seconds)
server_config.network.idle_timeout_ms = 600000; // 10 minutes
// Configure client
var client_config = p2p_lib.P2PConfig.default();
client_config.network.listen_port = client_port;
client_config.events.enable_logging = false;
client_config.file_sharing.max_concurrent_downloads = 128;
client_config.file_sharing.piece_size = PIECE_SIZE;
client_config.file_sharing.allowed_share_directories = &allowed_dirs;
client_config.file_sharing.max_bandwidth_download = 100 * 1024 * 1024; // 100 MB/s for testing
// Increase idle timeout for large file transfers
client_config.network.idle_timeout_ms = 600000; // 10 minutes
// Create P2P instances
std.debug.print("\n2. Creating P2P instances...\n", .{});
var server = try P2P.init(allocator, server_config);
defer server.deinit();
var client = try P2P.init(allocator, client_config);
defer client.deinit();
std.debug.print(" Done.\n", .{});
// Start instances
std.debug.print("\n3. Starting P2P instances...\n", .{});
try server.start();
try client.start();
std.debug.print(" Done.\n", .{});
// Server listens for connections
std.debug.print("\n4. Server listening on port {d}...\n", .{listen_port});
const listen_addr = Address.ipv4(.{ 127, 0, 0, 1 }, listen_port);
try server.startListening(listen_addr);
std.debug.print(" Done.\n", .{});
// Give server time to start listening
std.Thread.sleep(100 * std.time.ns_per_ms);
// Server adds file for sharing
std.debug.print("\n5. Server adding file for sharing...\n", .{});
const session_id = server.addFile(test_file_path) catch |err| {
std.debug.print(" ERROR: Could not add file: {}\n", .{err});
return err;
};
std.debug.print(" File added with session ID: {d}\n", .{session_id});
// Start sharing
std.debug.print("\n6. Server starting file sharing session...\n", .{});
server.startSharing(session_id) catch |err| {
std.debug.print(" ERROR: Could not start sharing: {}\n", .{err});
return err;
};
std.debug.print(" Sharing started.\n", .{});
// Get file metadata from server for client to use
std.debug.print("\n7. Getting file metadata for download...\n", .{});
const file_manager = server.file_manager orelse {
std.debug.print(" ERROR: File manager not available\n", .{});
return error.InvalidState;
};
const session_info = file_manager.getSessionInfo(session_id) orelse {
std.debug.print(" ERROR: Session not found\n", .{});
return error.ConnectionNotFound;
};
std.debug.print(" File size: {d} bytes, Pieces: {d}\n", .{ session_info.file_size, session_info.piece_count });
// Get the full metadata to share with client (simulates discovery)
const metadata = try server.getFileMetadata(session_id) orelse {
std.debug.print(" ERROR: Could not get file metadata\n", .{});
return error.ConnectionNotFound;
};
std.debug.print(" Got metadata for file: {s}\n", .{metadata.name});
// Client creates download session BEFORE connecting so it can receive bitfield updates
std.debug.print("\n8. Client creating download session...\n", .{});
const download_session_id = client.downloadFile(metadata, download_path) catch |err| {
std.debug.print(" ERROR: Could not start download: {}\n", .{err});
return err;
};
std.debug.print(" Download session created: {d}\n", .{download_session_id});
const client_file_manager = client.file_manager orelse {
std.debug.print(" ERROR: Client file manager not available\n", .{});
return error.InvalidState;
};
if (client_file_manager.getSessionInfo(download_session_id)) |info| {
std.debug.print(" Client session status: {}, piece_count: {d}\n", .{ info.status, info.piece_count });
}
// Client connects to server - this triggers bitfield exchange
std.debug.print("\n9. Client connecting to server...\n", .{});
const peer_id = try client.connectToPeer(listen_addr);
std.debug.print(" Connected! Peer ID: {x}\n", .{peer_id.bytes[0..8].*});
// Let server accept the connection and process bitfield
std.Thread.sleep(200 * std.time.ns_per_ms);
try server.update();
try client.update();
// The bitfield from server should have been processed by now
// The download manager should know which pieces the server has
// Start the download
std.debug.print("\n10. Starting download...\n", .{});
client.startSharing(download_session_id) catch |err| {
std.debug.print(" ERROR: Could not start download sharing: {}\n", .{err});
};
std.debug.print(" Download started.\n", .{});
// Run transfer loop
std.debug.print("\n11. Running file transfer loop...\n", .{});
if (USE_LARGE_FILE) {
std.debug.print(" Piece size: {d} KB, Timeout: {d}s\n", .{ PIECE_SIZE / 1024, @divFloor(TIMEOUT_MS, 1000) });
}
const start_time = std.time.milliTimestamp();
var iteration: u32 = 0;
const max_iterations: u32 = if (USE_LARGE_FILE) 100000 else 1000;
var last_progress_print: i64 = 0;
var transfer_complete = false;
while (!transfer_complete and iteration < max_iterations) : (iteration += 1) {
const now = std.time.milliTimestamp();
// Check timeout
if (now - start_time > TIMEOUT_MS) {
std.debug.print("\n TIMEOUT: Transfer exceeded {d}ms\n", .{TIMEOUT_MS});
break;
}
// Update both instances multiple times for higher throughput
// Each update processes a batch of messages, so multiple calls per iteration
// helps drain queues faster
var update_round: u32 = 0;
while (update_round < 10) : (update_round += 1) {
server.update() catch |err| {
std.debug.print(" Server update error: {}\n", .{err});
};
client.update() catch |err| {
std.debug.print(" Client update error: {}\n", .{err});
};
}
// Check server events
while (server.getNextEvent()) |event| {
switch (event.event_type) {
.peer_connected => std.debug.print(" Server: Peer connected\n", .{}),
.message_sent => {},
.message_received => {},
.upload_started => std.debug.print(" Server: Upload started\n", .{}),
.upload_completed => {
std.debug.print(" Server: Upload complete!\n", .{});
},
else => {},
}
}
// Check client events
while (client.getNextEvent()) |event| {
switch (event.event_type) {
.connection_established => std.debug.print(" Client: Connection established\n", .{}),
.file_download_started => std.debug.print(" Client: Download started\n", .{}),
.file_download_completed => {
std.debug.print(" Client: Download complete!\n", .{});
transfer_complete = true;
},
.file_download_failed => {
std.debug.print(" Client: Download failed!\n", .{});
},
else => {},
}
}
// Check client download session status
if (client_file_manager.getSessionInfo(download_session_id)) |info| {
// Print progress for large files periodically
if (USE_LARGE_FILE and 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 mb_per_sec = if (elapsed_sec > 0) @as(f64, @floatFromInt(bytes_done)) / elapsed_sec / 1024.0 / 1024.0 else 0;
last_progress_print = now;
std.debug.print("[{d:.1}s] Progress: {d:.1}% ({d}/{d} pieces) - {d:.1} MB/s\n", .{
elapsed_sec,
info.progress * 100,
info.pieces_completed,
info.piece_count,
mb_per_sec,
});
}
if (info.status == .completed) {
std.debug.print(" Client download completed!\n", .{});
transfer_complete = true;
}
}
// Check server upload session status (secondary check)
if (file_manager.getSessionInfo(session_id)) |info| {
if (info.status == .completed) {
std.debug.print(" Server upload completed!\n", .{});
// Only set complete if client also done or if file exists
if (std.fs.cwd().access(download_path, .{})) |_| {
transfer_complete = true;
} else |_| {}
}
}
std.Thread.sleep(1 * std.time.ns_per_ms); // Minimal sleep for max throughput
}
// Drain any remaining pending sends before verifying
std.debug.print("\n11b. Draining remaining data...\n", .{});
const drain_start = std.time.milliTimestamp();
const drain_timeout: i64 = 30000; // 30 seconds max drain time
while (std.time.milliTimestamp() - drain_start < drain_timeout) {
server.update() catch {};
client.update() catch {};
std.Thread.sleep(10 * std.time.ns_per_ms);
}
std.debug.print(" Drain complete.\n", .{});
// Show statistics
std.debug.print("\n12. Transfer Statistics:\n", .{});
std.debug.print(" Server - Messages Sent: {d}, Received: {d}\n", .{
server.stats.messages_sent.load(.monotonic),
server.stats.messages_received.load(.monotonic),
});
std.debug.print(" Client - Messages Sent: {d}, Received: {d}\n", .{
client.stats.messages_sent.load(.monotonic),
client.stats.messages_received.load(.monotonic),
});
std.debug.print(" Client - Downloaded: {d} bytes\n", .{
client.stats.total_downloaded.load(.monotonic),
});
// Verify file was transferred (if download path exists)
std.debug.print("\n13. Verifying transfer...\n", .{});
if (std.fs.cwd().openFile(download_path, .{})) |file| {
defer file.close();
const stat = try file.stat();
if (stat.size != TEST_FILE_SIZE) {
std.debug.print(" MISMATCH: File size differs (expected {d}, got {d})\n", .{ TEST_FILE_SIZE, stat.size });
} else if (USE_LARGE_FILE) {
// For large files, verify pattern at start, middle, and end
var buf: [64]u8 = undefined;
const pattern = "0123456789ABCDEF";
var verified = true;
// Check start
_ = try file.read(&buf);
for (0..4) |i| {
if (!std.mem.eql(u8, buf[i * 16 .. (i + 1) * 16], pattern)) {
verified = false;
break;
}
}
// Check middle
try file.seekTo(TEST_FILE_SIZE / 2);
_ = try file.read(&buf);
for (0..4) |i| {
if (!std.mem.eql(u8, buf[i * 16 .. (i + 1) * 16], pattern)) {
verified = false;
break;
}
}
// Check end
try file.seekTo(TEST_FILE_SIZE - 64);
const end_read = try file.read(&buf);
const end_expected = TEST_FILE_SIZE % 16;
if (end_expected == 0) {
for (0..@min(4, end_read / 16)) |i| {
if (!std.mem.eql(u8, buf[i * 16 .. (i + 1) * 16], pattern)) {
verified = false;
break;
}
}
}
if (verified) {
std.debug.print(" SUCCESS: Large file content verified! ({d} MB)\n", .{TEST_FILE_SIZE_MB});
} else {
std.debug.print(" MISMATCH: Large file content pattern mismatch\n", .{});
}
} else {
var buf: [256]u8 = undefined;
const bytes_read = try file.readAll(&buf);
if (std.mem.eql(u8, buf[0..bytes_read], SMALL_TEST_CONTENT)) {
std.debug.print(" SUCCESS: File content matches!\n", .{});
} else {
std.debug.print(" MISMATCH: File content differs\n", .{});
std.debug.print(" Expected: {s}\n", .{SMALL_TEST_CONTENT});
std.debug.print(" Got: {s}\n", .{buf[0..bytes_read]});
}
}
} else |_| {
std.debug.print(" NOTE: Download file not created (transfer may not have completed)\n", .{});
std.debug.print(" This is expected - file transfer requires:\n", .{});
std.debug.print(" 1. Client to discover file metadata from server\n", .{});
std.debug.print(" 2. Client to initiate download with that metadata\n", .{});
std.debug.print(" 3. Piece request/response exchange over the network\n", .{});
}
// Report final status
std.debug.print("\n14. Final Session Status:\n", .{});
std.debug.print(" Looking up client session {d}...\n", .{download_session_id});
if (client_file_manager.getSessionInfo(download_session_id)) |info| {
std.debug.print(" Client Download - Status: {}, Progress: {d:.1}%, Pieces: {d}/{d}\n", .{
info.status,
info.progress * 100,
info.pieces_completed,
info.piece_count,
});
} else {
std.debug.print(" Client session not found!\n", .{});
}
std.debug.print(" Looking up server session {d}...\n", .{session_id});
if (file_manager.getSessionInfo(session_id)) |info| {
std.debug.print(" Server Upload - Status: {}, Progress: {d:.1}%, Pieces: {d}/{d}\n", .{
info.status,
info.progress * 100,
info.pieces_completed,
info.piece_count,
});
} else {
std.debug.print(" Server session not found!\n", .{});
}
// Cleanup
std.debug.print("\n15. Cleaning up...\n", .{});
// Stop file sharing sessions before stopping P2P instances
// This prevents "transfers still active" warning during shutdown
server.stopSharing(session_id) catch {};
client.stopSharing(download_session_id) catch {};
try client.stop();
try server.stop();
// Delete download file only (keep source for faster re-runs)
// std.fs.cwd().deleteFile(test_file_path) catch {};
std.fs.cwd().deleteFile(download_path) catch {};
std.debug.print("\n=== File Transfer Test Complete ===\n", .{});
}