1156 lines
43 KiB
Zig
1156 lines
43 KiB
Zig
//! Swarm Chaos Test - Comprehensive P2P Resilience Testing
|
|
//!
|
|
//! This test simulates a realistic P2P swarm lifecycle with multiple edge cases:
|
|
//!
|
|
//! Timeline:
|
|
//! =========
|
|
//! [Phase 1] GENESIS - Primary seeder A starts sharing
|
|
//! [Phase 2] INITIAL SWARM - B, C, D start downloading from A
|
|
//! [Phase 3] CASCADE - B completes, becomes seeder; E, F join
|
|
//! [Phase 4] FAILURE - A goes offline; swarm continues from B
|
|
//! [Phase 5] GROWTH - C completes, becomes seeder
|
|
//! [Phase 6] RECOVERY - A comes back; G joins late
|
|
//! [Phase 7] COMPLETION - All transfers complete
|
|
//! [Phase 8] VERIFICATION - Verify all files match original
|
|
//!
|
|
//! Metrics tracked:
|
|
//! - Per-peer download speed and completion time
|
|
//! - Swarm throughput over time
|
|
//! - Resilience metrics (time to recover from failure)
|
|
//! - Cascade efficiency (how quickly downloaders become seeders)
|
|
|
|
const std = @import("std");
|
|
const p2p_mod = @import("p2p");
|
|
const files = @import("files");
|
|
const core = @import("core");
|
|
|
|
const P2P = p2p_mod.P2P;
|
|
const P2PConfig = p2p_mod.P2PConfig;
|
|
const FileMetadata = files.hash.FileMetadata;
|
|
const Address = core.Address;
|
|
|
|
// ============================================================================
|
|
// CONFIGURATION
|
|
// ============================================================================
|
|
|
|
const Config = struct {
|
|
// File settings
|
|
const FILE_SIZE: u64 = 1 * 1024 * 1024 * 1024; // 1GB for reasonable test time
|
|
const PIECE_SIZE: u32 = 1024 * 1024; // 1MB pieces
|
|
const PIECE_COUNT: u32 = FILE_SIZE / PIECE_SIZE;
|
|
|
|
// Timing settings
|
|
const PHASE_SETTLE_TIME: u64 = 500; // Time to let connections establish (ms)
|
|
const UPDATE_INTERVAL_US: u64 = 100; // How often to call peer.update() (microseconds)
|
|
const PROGRESS_POLL_INTERVAL: u64 = 100; // How often to check progress (ms)
|
|
const PROGRESS_PRINT_INTERVAL: u64 = 2000; // How often to print progress (ms)
|
|
const CASCADE_THRESHOLD: f32 = 30.0; // % complete before becoming seeder
|
|
const LATE_JOIN_THRESHOLD: f32 = 50.0; // % complete before late joiners
|
|
const FAILURE_THRESHOLD: f32 = 40.0; // % complete when primary seeder fails
|
|
const SEEDER_OFFLINE_DURATION: u64 = 10_000; // How long seeder stays offline (ms)
|
|
const MAX_TEST_DURATION: u64 = 600_000; // 10 minute timeout (increased for thorough cascade)
|
|
|
|
// Network settings
|
|
const BASE_PORT: u16 = 47000;
|
|
};
|
|
|
|
// ============================================================================
|
|
// METRICS
|
|
// ============================================================================
|
|
|
|
const PeerMetrics = struct {
|
|
name: []const u8,
|
|
role: PeerRole,
|
|
start_time: ?i64 = null,
|
|
completion_time: ?i64 = null,
|
|
became_seeder_time: ?i64 = null,
|
|
pieces_from_each_peer: std.AutoHashMap([32]u8, u32),
|
|
peak_download_speed: f64 = 0, // MB/s
|
|
allocator: std.mem.Allocator,
|
|
|
|
fn init(allocator: std.mem.Allocator, name: []const u8, role: PeerRole) PeerMetrics {
|
|
return .{
|
|
.name = name,
|
|
.role = role,
|
|
.pieces_from_each_peer = std.AutoHashMap([32]u8, u32).init(allocator),
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
fn deinit(self: *PeerMetrics) void {
|
|
self.pieces_from_each_peer.deinit();
|
|
}
|
|
|
|
fn downloadDuration(self: PeerMetrics) ?f64 {
|
|
if (self.start_time) |start| {
|
|
if (self.completion_time) |end| {
|
|
return @as(f64, @floatFromInt(end - start)) / 1000.0;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
fn averageSpeed(self: PeerMetrics) ?f64 {
|
|
if (self.downloadDuration()) |duration| {
|
|
if (duration > 0) {
|
|
return @as(f64, Config.FILE_SIZE) / (1024 * 1024) / duration;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
};
|
|
|
|
const SwarmMetrics = struct {
|
|
test_start_time: i64,
|
|
phase_times: [8]?i64 = [_]?i64{null} ** 8,
|
|
phase_names: [8][]const u8 = .{
|
|
"Genesis",
|
|
"Initial Swarm",
|
|
"Cascade",
|
|
"Failure",
|
|
"Growth",
|
|
"Recovery",
|
|
"Completion",
|
|
"Verification",
|
|
},
|
|
failure_duration: ?i64 = null, // How long primary seeder was offline
|
|
total_data_transferred: u64 = 0,
|
|
peak_concurrent_downloads: u32 = 0,
|
|
cascade_count: u32 = 0, // How many downloaders became seeders
|
|
|
|
fn recordPhaseStart(self: *SwarmMetrics, phase: usize) void {
|
|
self.phase_times[phase] = std.time.milliTimestamp();
|
|
}
|
|
|
|
fn phaseDuration(self: SwarmMetrics, phase: usize) ?f64 {
|
|
if (phase == 0) {
|
|
if (self.phase_times[0]) |start| {
|
|
return @as(f64, @floatFromInt(start - self.test_start_time)) / 1000.0;
|
|
}
|
|
} else if (phase > 0 and phase < 8) {
|
|
if (self.phase_times[phase]) |end| {
|
|
if (self.phase_times[phase - 1]) |start| {
|
|
return @as(f64, @floatFromInt(end - start)) / 1000.0;
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
fn totalDuration(self: SwarmMetrics) f64 {
|
|
const now = std.time.milliTimestamp();
|
|
return @as(f64, @floatFromInt(now - self.test_start_time)) / 1000.0;
|
|
}
|
|
};
|
|
|
|
// ============================================================================
|
|
// PEER MANAGEMENT
|
|
// ============================================================================
|
|
|
|
const PeerRole = enum {
|
|
primary_seeder, // A - original seeder, will go offline
|
|
initial_downloader, // B, C, D - start immediately
|
|
late_joiner_wave1, // E, F - join at CASCADE_THRESHOLD
|
|
late_joiner_wave2, // G - joins at RECOVERY_THRESHOLD
|
|
};
|
|
|
|
const PeerState = struct {
|
|
instance: P2P,
|
|
name: []const u8,
|
|
role: PeerRole,
|
|
port: u16,
|
|
metrics: PeerMetrics,
|
|
|
|
// State tracking
|
|
is_online: bool = true,
|
|
is_seeding: bool = false,
|
|
is_downloading: bool = false,
|
|
download_session_id: ?u64 = null,
|
|
upload_session_id: ?u64 = null,
|
|
|
|
// Progress tracking
|
|
pieces_completed: u32 = 0,
|
|
last_progress_update: i64 = 0,
|
|
|
|
fn progressPercent(self: PeerState) f32 {
|
|
return @as(f32, @floatFromInt(self.pieces_completed)) /
|
|
@as(f32, @floatFromInt(Config.PIECE_COUNT)) * 100.0;
|
|
}
|
|
|
|
fn isComplete(self: PeerState) bool {
|
|
return self.pieces_completed >= Config.PIECE_COUNT;
|
|
}
|
|
};
|
|
|
|
const PeerManager = struct {
|
|
peers: std.ArrayList(*PeerState),
|
|
allocator: std.mem.Allocator,
|
|
file_metadata: ?FileMetadata = null,
|
|
metadata_owner: ?*P2P = null,
|
|
file_path: []const u8,
|
|
allowed_dirs: []const []const u8,
|
|
|
|
fn init(allocator: std.mem.Allocator, file_path: []const u8, allowed_dirs: []const []const u8) PeerManager {
|
|
return .{
|
|
.peers = .{}, // Zig 0.15: ArrayList uses struct literal init
|
|
.allocator = allocator,
|
|
.file_path = file_path,
|
|
.allowed_dirs = allowed_dirs,
|
|
};
|
|
}
|
|
|
|
fn deinit(self: *PeerManager) void {
|
|
// Free metadata if we have it
|
|
if (self.file_metadata) |meta| {
|
|
if (self.metadata_owner) |owner| {
|
|
owner.freeFileMetadata(meta);
|
|
}
|
|
}
|
|
|
|
// Cleanup all peers
|
|
for (self.peers.items) |peer| {
|
|
peer.metrics.deinit();
|
|
peer.instance.stop() catch {};
|
|
peer.instance.deinit();
|
|
self.allocator.destroy(peer);
|
|
}
|
|
self.peers.deinit(self.allocator);
|
|
}
|
|
|
|
fn createPeer(self: *PeerManager, name: []const u8, role: PeerRole, port: u16) !*PeerState {
|
|
var config = P2PConfig.default();
|
|
config.network.listen_port = port;
|
|
config.network.enable_noise_encryption = false;
|
|
config.protocol.enable_encryption = false;
|
|
config.events.enable_logging = false;
|
|
// CASCADE FIX: Disable rate limiting for test to allow mesh topology establishment
|
|
config.network.enable_rate_limiting = false;
|
|
config.file_sharing.piece_size = Config.PIECE_SIZE;
|
|
config.file_sharing.max_concurrent_downloads = 64;
|
|
config.file_sharing.max_concurrent_uploads = 64;
|
|
config.file_sharing.allowed_share_directories = self.allowed_dirs;
|
|
|
|
const peer = try self.allocator.create(PeerState);
|
|
peer.* = .{
|
|
.instance = try P2P.init(self.allocator, config),
|
|
.name = name,
|
|
.role = role,
|
|
.port = port,
|
|
.metrics = PeerMetrics.init(self.allocator, name, role),
|
|
};
|
|
|
|
try peer.instance.start();
|
|
|
|
const listen_addr = Address.ipv4(.{ 127, 0, 0, 1 }, port);
|
|
try peer.instance.startListening(listen_addr);
|
|
|
|
try self.peers.append(self.allocator, peer);
|
|
return peer;
|
|
}
|
|
|
|
fn setupSeeder(self: *PeerManager, peer: *PeerState) !void {
|
|
const session_id = if (self.file_metadata) |meta|
|
|
try peer.instance.addFileWithMetadata(self.file_path, meta)
|
|
else
|
|
try peer.instance.addFile(self.file_path);
|
|
|
|
try peer.instance.startSharing(session_id);
|
|
peer.upload_session_id = session_id;
|
|
peer.is_seeding = true;
|
|
|
|
// Capture metadata from first seeder
|
|
if (self.file_metadata == null) {
|
|
if (try peer.instance.getFileMetadata(session_id)) |meta| {
|
|
self.file_metadata = meta;
|
|
self.metadata_owner = &peer.instance;
|
|
}
|
|
}
|
|
}
|
|
|
|
fn setupDownloader(self: *PeerManager, peer: *PeerState, output_path: []const u8) !void {
|
|
const meta = self.file_metadata orelse return error.NoMetadata;
|
|
|
|
const session_id = try peer.instance.downloadFile(meta, output_path);
|
|
try peer.instance.startSharing(session_id); // Must call startSharing to activate the session
|
|
peer.download_session_id = session_id;
|
|
peer.is_downloading = true;
|
|
peer.metrics.start_time = std.time.milliTimestamp();
|
|
}
|
|
|
|
fn promoteToSeeder(self: *PeerManager, peer: *PeerState) !void {
|
|
if (peer.is_seeding) return;
|
|
|
|
// CASCADE FIX: Don't create a separate upload session!
|
|
// The download session already has cascade capability via initUploadForCascade.
|
|
// Creating a separate upload session causes session ID conflicts when
|
|
// other peers connect - they might get the wrong session.
|
|
//
|
|
// Just mark the peer as seeding for test tracking purposes.
|
|
// The cascade mechanism in the download session handles serving pieces.
|
|
peer.is_seeding = true;
|
|
peer.metrics.became_seeder_time = std.time.milliTimestamp();
|
|
|
|
// Note: We don't need setupSeeder() because:
|
|
// 1. initUploadForCascade() was called when downloadFile() was called
|
|
// 2. Pieces are added to the upload manager as they're verified
|
|
// 3. "have" messages are broadcast to connected peers
|
|
_ = self;
|
|
}
|
|
|
|
fn connectPeerToSeeders(self: *PeerManager, downloader: *PeerState) !u32 {
|
|
var connections: u32 = 0;
|
|
for (self.peers.items) |peer| {
|
|
if (peer == downloader) continue;
|
|
if (!peer.is_online) continue;
|
|
if (!peer.is_seeding) continue;
|
|
|
|
const addr = Address.ipv4(.{ 127, 0, 0, 1 }, peer.port);
|
|
_ = downloader.instance.connectToPeer(addr) catch continue;
|
|
connections += 1;
|
|
}
|
|
return connections;
|
|
}
|
|
|
|
/// CASCADE FIX: Connect peer to ALL online peers (mesh topology for effective cascade)
|
|
fn connectPeerToAllPeers(self: *PeerManager, peer: *PeerState) !u32 {
|
|
var connections: u32 = 0;
|
|
for (self.peers.items) |other| {
|
|
if (other == peer) continue;
|
|
if (!other.is_online) continue;
|
|
|
|
const addr = Address.ipv4(.{ 127, 0, 0, 1 }, other.port);
|
|
_ = peer.instance.connectToPeer(addr) catch continue;
|
|
connections += 1;
|
|
}
|
|
return connections;
|
|
}
|
|
|
|
/// CASCADE FIX: Connect all downloading peers to each other (mesh topology)
|
|
fn establishMeshTopology(self: *PeerManager) !void {
|
|
var total_new_connections: u32 = 0;
|
|
for (self.peers.items) |peer| {
|
|
if (!peer.is_online) continue;
|
|
if (!peer.is_downloading) continue;
|
|
|
|
const conns = try self.connectPeerToAllPeers(peer);
|
|
total_new_connections += conns;
|
|
}
|
|
if (total_new_connections > 0) {
|
|
std.debug.print(" CASCADE: Established mesh topology with {d} new connections\n", .{total_new_connections});
|
|
}
|
|
}
|
|
|
|
fn getOnlineSeeders(self: *PeerManager) u32 {
|
|
var count: u32 = 0;
|
|
for (self.peers.items) |peer| {
|
|
if (peer.is_online and peer.is_seeding) count += 1;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
fn getActiveDownloaders(self: *PeerManager) u32 {
|
|
var count: u32 = 0;
|
|
for (self.peers.items) |peer| {
|
|
if (peer.is_downloading and !peer.isComplete()) count += 1;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
fn getAverageProgress(self: *PeerManager) f32 {
|
|
var total: f32 = 0;
|
|
var count: u32 = 0;
|
|
for (self.peers.items) |peer| {
|
|
if (peer.is_downloading) {
|
|
total += peer.progressPercent();
|
|
count += 1;
|
|
}
|
|
}
|
|
return if (count > 0) total / @as(f32, @floatFromInt(count)) else 0;
|
|
}
|
|
|
|
fn allDownloadsComplete(self: *PeerManager) bool {
|
|
for (self.peers.items) |peer| {
|
|
if (peer.is_downloading and !peer.isComplete()) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
fn updatePeerProgress(self: *PeerManager, peer: *PeerState) void {
|
|
_ = self;
|
|
if (peer.download_session_id) |session_id| {
|
|
if (peer.instance.file_manager) |fm| {
|
|
if (fm.getSessionInfo(session_id)) |info| {
|
|
peer.pieces_completed = info.pieces_completed;
|
|
if (info.pieces_completed >= info.piece_count and peer.metrics.completion_time == null) {
|
|
peer.metrics.completion_time = std.time.milliTimestamp();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
// ============================================================================
|
|
// TEST ORCHESTRATION
|
|
// ============================================================================
|
|
|
|
const TestPhase = enum(usize) {
|
|
genesis = 0,
|
|
initial_swarm = 1,
|
|
cascade = 2,
|
|
failure = 3,
|
|
growth = 4,
|
|
recovery = 5,
|
|
completion = 6,
|
|
verification = 7,
|
|
};
|
|
|
|
const SwarmChaosTest = struct {
|
|
peer_manager: PeerManager,
|
|
swarm_metrics: SwarmMetrics,
|
|
allocator: std.mem.Allocator,
|
|
current_phase: TestPhase = .genesis,
|
|
stop_signal: std.atomic.Value(bool),
|
|
update_thread: ?std.Thread = null,
|
|
|
|
// Named peer references for easy access
|
|
peer_a: ?*PeerState = null, // Primary seeder
|
|
peer_b: ?*PeerState = null, // Initial downloader -> seeder
|
|
peer_c: ?*PeerState = null, // Initial downloader -> seeder
|
|
peer_d: ?*PeerState = null, // Initial downloader
|
|
peer_e: ?*PeerState = null, // Late joiner wave 1
|
|
peer_f: ?*PeerState = null, // Late joiner wave 1
|
|
peer_g: ?*PeerState = null, // Late joiner wave 2
|
|
|
|
fn init(allocator: std.mem.Allocator, file_path: []const u8, allowed_dirs: []const []const u8) SwarmChaosTest {
|
|
return .{
|
|
.peer_manager = PeerManager.init(allocator, file_path, allowed_dirs),
|
|
.swarm_metrics = .{ .test_start_time = std.time.milliTimestamp() },
|
|
.allocator = allocator,
|
|
.stop_signal = std.atomic.Value(bool).init(false),
|
|
};
|
|
}
|
|
|
|
fn deinit(self: *SwarmChaosTest) void {
|
|
self.stopUpdateThread();
|
|
self.peer_manager.deinit();
|
|
}
|
|
|
|
fn startUpdateThread(self: *SwarmChaosTest) !void {
|
|
self.update_thread = try std.Thread.spawn(.{}, updateThreadFn, .{self});
|
|
}
|
|
|
|
fn stopUpdateThread(self: *SwarmChaosTest) void {
|
|
self.stop_signal.store(true, .release);
|
|
if (self.update_thread) |t| {
|
|
t.join();
|
|
self.update_thread = null;
|
|
}
|
|
}
|
|
|
|
fn updateThreadFn(self: *SwarmChaosTest) void {
|
|
var last_progress_update: i64 = std.time.milliTimestamp();
|
|
const progress_interval_ms: i64 = @intCast(Config.PROGRESS_POLL_INTERVAL);
|
|
|
|
while (!self.stop_signal.load(.acquire)) {
|
|
// Update all peers at high frequency (like the working swarm test)
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
if (peer.is_online) {
|
|
peer.instance.update() catch {};
|
|
}
|
|
}
|
|
|
|
// Update progress tracking less frequently to reduce overhead
|
|
const now = std.time.milliTimestamp();
|
|
if (now - last_progress_update >= progress_interval_ms) {
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
if (peer.is_online) {
|
|
self.peer_manager.updatePeerProgress(peer);
|
|
}
|
|
}
|
|
last_progress_update = now;
|
|
}
|
|
|
|
// Sleep at high frequency like the working swarm test (100 microseconds)
|
|
std.Thread.sleep(Config.UPDATE_INTERVAL_US * std.time.ns_per_us);
|
|
}
|
|
}
|
|
|
|
fn transitionTo(self: *SwarmChaosTest, phase: TestPhase) void {
|
|
self.current_phase = phase;
|
|
self.swarm_metrics.recordPhaseStart(@intFromEnum(phase));
|
|
printPhaseHeader(phase);
|
|
}
|
|
|
|
fn printPhaseHeader(phase: TestPhase) void {
|
|
const names = [_][]const u8{
|
|
"GENESIS - Primary seeder starts",
|
|
"INITIAL SWARM - First downloaders join",
|
|
"CASCADE - Downloaders become seeders",
|
|
"FAILURE - Primary seeder goes offline",
|
|
"GROWTH - More peers become seeders",
|
|
"RECOVERY - Primary seeder returns",
|
|
"COMPLETION - All downloads finish",
|
|
"VERIFICATION - Checking file integrity",
|
|
};
|
|
std.debug.print("\n", .{});
|
|
printSeparator(60);
|
|
std.debug.print(" Phase {d}: {s}\n", .{ @intFromEnum(phase) + 1, names[@intFromEnum(phase)] });
|
|
printSeparator(60);
|
|
std.debug.print("\n", .{});
|
|
}
|
|
|
|
fn printProgress(self: *SwarmChaosTest) void {
|
|
const avg = self.peer_manager.getAverageProgress();
|
|
const seeders = self.peer_manager.getOnlineSeeders();
|
|
const downloaders = self.peer_manager.getActiveDownloaders();
|
|
const elapsed = self.swarm_metrics.totalDuration();
|
|
|
|
std.debug.print("[{d:6.1}s] Avg: {d:5.1}% | Seeders: {d} | Active DL: {d} | ", .{
|
|
elapsed,
|
|
avg,
|
|
seeders,
|
|
downloaders,
|
|
});
|
|
|
|
// Print per-peer progress
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
if (peer.is_downloading) {
|
|
const symbol: []const u8 = if (peer.isComplete()) "Done" else if (!peer.is_online) "OFF" else "";
|
|
if (symbol.len > 0) {
|
|
std.debug.print("{s}:{s} ", .{ peer.name, symbol });
|
|
} else {
|
|
std.debug.print("{s}:{d:.0}% ", .{ peer.name, peer.progressPercent() });
|
|
}
|
|
}
|
|
}
|
|
std.debug.print("\n", .{});
|
|
}
|
|
|
|
// =======================================================================
|
|
// PHASE IMPLEMENTATIONS
|
|
// =======================================================================
|
|
|
|
fn runPhaseGenesis(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.genesis);
|
|
|
|
// Create primary seeder A
|
|
var rng = std.Random.DefaultPrng.init(@intCast(std.time.milliTimestamp()));
|
|
const base_port = Config.BASE_PORT + @as(u16, @intCast(rng.random().int(u16) % 2000));
|
|
|
|
self.peer_a = try self.peer_manager.createPeer("A", .primary_seeder, base_port);
|
|
try self.peer_manager.setupSeeder(self.peer_a.?);
|
|
|
|
std.debug.print(" Peer A: Primary seeder online on port {d}\n", .{base_port});
|
|
std.debug.print(" File: {d} MB ({d} pieces)\n", .{
|
|
Config.FILE_SIZE / (1024 * 1024),
|
|
Config.PIECE_COUNT,
|
|
});
|
|
|
|
std.Thread.sleep(Config.PHASE_SETTLE_TIME * std.time.ns_per_ms);
|
|
}
|
|
|
|
fn runPhaseInitialSwarm(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.initial_swarm);
|
|
|
|
const base_port = self.peer_a.?.port;
|
|
|
|
// Create initial downloaders B, C, D
|
|
self.peer_b = try self.peer_manager.createPeer("B", .initial_downloader, base_port + 1);
|
|
self.peer_c = try self.peer_manager.createPeer("C", .initial_downloader, base_port + 2);
|
|
self.peer_d = try self.peer_manager.createPeer("D", .initial_downloader, base_port + 3);
|
|
|
|
// Setup downloads
|
|
try self.peer_manager.setupDownloader(self.peer_b.?, "./tests/test_data/chaos_download_B.bin");
|
|
try self.peer_manager.setupDownloader(self.peer_c.?, "./tests/test_data/chaos_download_C.bin");
|
|
try self.peer_manager.setupDownloader(self.peer_d.?, "./tests/test_data/chaos_download_D.bin");
|
|
|
|
std.debug.print(" Peers B, C, D: Started downloading\n", .{});
|
|
|
|
// Connect to seeder A
|
|
for ([_]*PeerState{ self.peer_b.?, self.peer_c.?, self.peer_d.? }) |peer| {
|
|
const conns = try self.peer_manager.connectPeerToSeeders(peer);
|
|
std.debug.print(" {s} connected to {d} seeder(s)\n", .{ peer.name, conns });
|
|
}
|
|
|
|
std.Thread.sleep(Config.PHASE_SETTLE_TIME * std.time.ns_per_ms);
|
|
}
|
|
|
|
fn runPhaseCascade(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.cascade);
|
|
|
|
const base_port = self.peer_a.?.port;
|
|
|
|
// Create late joiners E, F
|
|
self.peer_e = try self.peer_manager.createPeer("E", .late_joiner_wave1, base_port + 4);
|
|
self.peer_f = try self.peer_manager.createPeer("F", .late_joiner_wave1, base_port + 5);
|
|
|
|
try self.peer_manager.setupDownloader(self.peer_e.?, "./tests/test_data/chaos_download_E.bin");
|
|
try self.peer_manager.setupDownloader(self.peer_f.?, "./tests/test_data/chaos_download_F.bin");
|
|
|
|
std.debug.print(" Peers E, F: Late joiners started downloading\n", .{});
|
|
|
|
// Promote B to seeder (they should have enough pieces by now)
|
|
if (self.peer_b.?.progressPercent() >= Config.CASCADE_THRESHOLD) {
|
|
try self.peer_manager.promoteToSeeder(self.peer_b.?);
|
|
self.swarm_metrics.cascade_count += 1;
|
|
std.debug.print(" Peer B: Promoted to seeder at {d:.1}%\n", .{self.peer_b.?.progressPercent()});
|
|
}
|
|
|
|
// CASCADE FIX: Establish mesh topology - connect ALL peers to each other
|
|
// This enables true cascade distribution where every peer can share with every other peer
|
|
try self.peer_manager.establishMeshTopology();
|
|
|
|
// Also connect late joiners to seeders explicitly
|
|
for ([_]*PeerState{ self.peer_e.?, self.peer_f.? }) |peer| {
|
|
const conns = try self.peer_manager.connectPeerToSeeders(peer);
|
|
std.debug.print(" {s} connected to {d} seeder(s)\n", .{ peer.name, conns });
|
|
}
|
|
|
|
std.Thread.sleep(Config.PHASE_SETTLE_TIME * std.time.ns_per_ms);
|
|
}
|
|
|
|
fn runPhaseFailure(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.failure);
|
|
|
|
// Take primary seeder A offline
|
|
const peer_a = self.peer_a.?;
|
|
peer_a.is_online = false;
|
|
peer_a.instance.stop() catch {};
|
|
|
|
std.debug.print(" Peer A: PRIMARY SEEDER OFFLINE\n", .{});
|
|
std.debug.print(" Remaining seeders: {d}\n", .{self.peer_manager.getOnlineSeeders()});
|
|
|
|
// Record failure start time for metrics
|
|
self.swarm_metrics.failure_duration = std.time.milliTimestamp();
|
|
}
|
|
|
|
fn runPhaseGrowth(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.growth);
|
|
|
|
// Promote C to seeder if ready
|
|
if (self.peer_c.?.progressPercent() >= Config.CASCADE_THRESHOLD) {
|
|
try self.peer_manager.promoteToSeeder(self.peer_c.?);
|
|
self.swarm_metrics.cascade_count += 1;
|
|
std.debug.print(" Peer C: Promoted to seeder at {d:.1}%\n", .{self.peer_c.?.progressPercent()});
|
|
}
|
|
|
|
// CASCADE FIX: Re-establish mesh topology (A is now offline, so connect remaining peers)
|
|
try self.peer_manager.establishMeshTopology();
|
|
}
|
|
|
|
fn runPhaseRecovery(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.recovery);
|
|
|
|
const base_port = self.peer_a.?.port;
|
|
|
|
// Bring A back online
|
|
const peer_a = self.peer_a.?;
|
|
|
|
// Use a different port to avoid AddressInUse (TCP TIME_WAIT on old port)
|
|
const recovery_port = peer_a.port + 100;
|
|
|
|
// Reinitialize A
|
|
var config = P2PConfig.default();
|
|
config.network.listen_port = recovery_port;
|
|
config.network.enable_noise_encryption = false;
|
|
config.protocol.enable_encryption = false;
|
|
config.events.enable_logging = false;
|
|
config.file_sharing.piece_size = Config.PIECE_SIZE;
|
|
config.file_sharing.allowed_share_directories = self.peer_manager.allowed_dirs;
|
|
|
|
peer_a.instance = try P2P.init(self.allocator, config);
|
|
try peer_a.instance.start();
|
|
try peer_a.instance.startListening(Address.ipv4(.{ 127, 0, 0, 1 }, recovery_port));
|
|
peer_a.port = recovery_port; // Update port so other peers can connect
|
|
|
|
try self.peer_manager.setupSeeder(peer_a);
|
|
peer_a.is_online = true;
|
|
|
|
// Calculate how long A was offline
|
|
if (self.swarm_metrics.failure_duration) |start| {
|
|
self.swarm_metrics.failure_duration = std.time.milliTimestamp() - start;
|
|
}
|
|
|
|
std.debug.print(" Peer A: PRIMARY SEEDER BACK ONLINE\n", .{});
|
|
std.debug.print(" Offline duration: {d:.1}s\n", .{
|
|
@as(f64, @floatFromInt(self.swarm_metrics.failure_duration orelse 0)) / 1000.0,
|
|
});
|
|
|
|
// Create very late joiner G
|
|
self.peer_g = try self.peer_manager.createPeer("G", .late_joiner_wave2, base_port + 6);
|
|
try self.peer_manager.setupDownloader(self.peer_g.?, "./tests/test_data/chaos_download_G.bin");
|
|
|
|
std.debug.print(" Peer G: Very late joiner started\n", .{});
|
|
|
|
// CASCADE FIX: Establish full mesh topology with all peers including recovered A and new G
|
|
try self.peer_manager.establishMeshTopology();
|
|
|
|
const conns = try self.peer_manager.connectPeerToSeeders(self.peer_g.?);
|
|
std.debug.print(" G connected to {d} seeder(s)\n", .{conns});
|
|
}
|
|
|
|
fn runPhaseCompletion(self: *SwarmChaosTest) !void {
|
|
self.transitionTo(.completion);
|
|
std.debug.print(" Waiting for all downloads to complete...\n\n", .{});
|
|
}
|
|
|
|
/// SYNC FIX: Ensure all download files are fully synced to disk
|
|
/// This is needed because pwrite data may still be in OS buffers
|
|
/// even after the pieces_completed counter reaches PIECE_COUNT.
|
|
fn syncAllDownloads(self: *SwarmChaosTest) void {
|
|
std.debug.print(" Syncing all download files to disk...\n", .{});
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
if (peer.is_downloading) {
|
|
var path_buf: [64]u8 = undefined;
|
|
const path = std.fmt.bufPrint(&path_buf, "./tests/test_data/chaos_download_{s}.bin", .{peer.name}) catch continue;
|
|
|
|
// Open, sync, and close the file to ensure all data is on disk
|
|
const file = std.fs.cwd().openFile(path, .{ .mode = .read_write }) catch continue;
|
|
defer file.close();
|
|
file.sync() catch {};
|
|
}
|
|
}
|
|
std.debug.print(" All files synced.\n", .{});
|
|
}
|
|
|
|
fn runPhaseVerification(self: *SwarmChaosTest) !bool {
|
|
self.transitionTo(.verification);
|
|
|
|
var all_passed = true;
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
if (peer.is_downloading) {
|
|
var path_buf: [64]u8 = undefined;
|
|
const path = std.fmt.bufPrint(&path_buf, "./tests/test_data/chaos_download_{s}.bin", .{peer.name}) catch continue;
|
|
|
|
const passed = verifyFile(path, self.peer_manager.file_path);
|
|
if (passed) {
|
|
std.debug.print(" {s}: PASS\n", .{peer.name});
|
|
} else {
|
|
std.debug.print(" {s}: FAIL\n", .{peer.name});
|
|
all_passed = false;
|
|
}
|
|
}
|
|
}
|
|
return all_passed;
|
|
}
|
|
|
|
// =======================================================================
|
|
// MAIN TEST LOOP
|
|
// =======================================================================
|
|
|
|
fn run(self: *SwarmChaosTest) !bool {
|
|
// Start the update thread
|
|
try self.startUpdateThread();
|
|
|
|
// Phase 1: Genesis
|
|
try self.runPhaseGenesis();
|
|
|
|
// Phase 2: Initial Swarm
|
|
try self.runPhaseInitialSwarm();
|
|
|
|
// Wait until we reach CASCADE_THRESHOLD
|
|
try self.waitForProgress(Config.CASCADE_THRESHOLD, "cascade threshold");
|
|
|
|
// Phase 3: Cascade
|
|
try self.runPhaseCascade();
|
|
|
|
// Wait until we reach FAILURE_THRESHOLD
|
|
try self.waitForProgress(Config.FAILURE_THRESHOLD, "failure threshold");
|
|
|
|
// Phase 4: Failure
|
|
try self.runPhaseFailure();
|
|
|
|
// Phase 5: Growth - observe cascade distribution without primary seeder
|
|
try self.runPhaseGrowth();
|
|
|
|
// Wait for seeder offline duration to test cascade resilience
|
|
// The swarm should distribute available pieces during this time
|
|
std.debug.print(" Seeder offline for {d}s - testing cascade distribution...\n", .{Config.SEEDER_OFFLINE_DURATION / 1000});
|
|
const offline_start = std.time.milliTimestamp();
|
|
var last_reconnect: i64 = 0;
|
|
const reconnect_interval: i64 = 2000;
|
|
while (std.time.milliTimestamp() - offline_start < Config.SEEDER_OFFLINE_DURATION) {
|
|
const now = std.time.milliTimestamp();
|
|
|
|
// CASCADE FIX: Also check for newly completed peers during offline phase
|
|
if (now - last_reconnect >= reconnect_interval) {
|
|
try self.promoteAndReconnectCompleted();
|
|
last_reconnect = now;
|
|
}
|
|
|
|
self.printProgress();
|
|
std.Thread.sleep(Config.PROGRESS_PRINT_INTERVAL * std.time.ns_per_ms);
|
|
}
|
|
|
|
// Phase 6: Recovery - bring seeder back online
|
|
try self.runPhaseRecovery();
|
|
|
|
// Phase 7: Completion
|
|
try self.runPhaseCompletion();
|
|
|
|
// Wait for all downloads to complete
|
|
try self.waitForCompletion();
|
|
|
|
// Stop update thread before verification
|
|
self.stopUpdateThread();
|
|
|
|
// SYNC FIX: Ensure all file data is flushed to disk before verification
|
|
// The pieces_completed counter can reach PIECE_COUNT before pwrite data
|
|
// is synced to disk. We need to explicitly sync all download files.
|
|
self.syncAllDownloads();
|
|
|
|
// Phase 8: Verification
|
|
const passed = try self.runPhaseVerification();
|
|
|
|
return passed;
|
|
}
|
|
|
|
fn waitForProgress(self: *SwarmChaosTest, target_percent: f32, description: []const u8) !void {
|
|
const start = std.time.milliTimestamp();
|
|
var last_print: i64 = 0;
|
|
|
|
while (self.peer_manager.getAverageProgress() < target_percent) {
|
|
const now = std.time.milliTimestamp();
|
|
|
|
// Timeout check
|
|
if (now - start > Config.MAX_TEST_DURATION) {
|
|
return error.TestTimeout;
|
|
}
|
|
|
|
// Progress print
|
|
if (now - last_print >= Config.PROGRESS_PRINT_INTERVAL) {
|
|
self.printProgress();
|
|
last_print = now;
|
|
}
|
|
|
|
std.Thread.sleep(Config.PROGRESS_POLL_INTERVAL * std.time.ns_per_ms);
|
|
}
|
|
|
|
std.debug.print(" Reached {s} ({d:.1}%)\n", .{ description, target_percent });
|
|
}
|
|
|
|
fn waitForCompletion(self: *SwarmChaosTest) !void {
|
|
const start = std.time.milliTimestamp();
|
|
var last_print: i64 = 0;
|
|
var last_reconnect: i64 = 0;
|
|
const reconnect_interval: i64 = 2000; // Check for new completed peers every 2 seconds
|
|
|
|
while (!self.peer_manager.allDownloadsComplete()) {
|
|
const now = std.time.milliTimestamp();
|
|
|
|
// Timeout check
|
|
if (now - start > Config.MAX_TEST_DURATION) {
|
|
return error.TestTimeout;
|
|
}
|
|
|
|
// Progress print
|
|
if (now - last_print >= Config.PROGRESS_PRINT_INTERVAL) {
|
|
self.printProgress();
|
|
last_print = now;
|
|
}
|
|
|
|
// CASCADE FIX: Periodically check for newly completed peers and reconnect
|
|
// This ensures that as peers complete, remaining downloaders connect to them
|
|
if (now - last_reconnect >= reconnect_interval) {
|
|
try self.promoteAndReconnectCompleted();
|
|
last_reconnect = now;
|
|
}
|
|
|
|
std.Thread.sleep(Config.PROGRESS_POLL_INTERVAL * std.time.ns_per_ms);
|
|
}
|
|
|
|
std.debug.print("\n All downloads complete!\n", .{});
|
|
}
|
|
|
|
/// CASCADE FIX: Promote completed downloaders to seeders and reconnect incomplete peers
|
|
fn promoteAndReconnectCompleted(self: *SwarmChaosTest) !void {
|
|
var new_seeders: u32 = 0;
|
|
|
|
// First pass: promote completed peers to seeders
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
if (peer.is_downloading and peer.isComplete() and !peer.is_seeding) {
|
|
try self.peer_manager.promoteToSeeder(peer);
|
|
self.swarm_metrics.cascade_count += 1;
|
|
new_seeders += 1;
|
|
std.debug.print(" CASCADE: {s} completed, promoted to seeder\n", .{peer.name});
|
|
}
|
|
}
|
|
|
|
// SOCKET FIX: Always re-establish mesh topology to recover broken connections
|
|
// Connections can break due to socket errors and need periodic re-establishment
|
|
try self.peer_manager.establishMeshTopology();
|
|
}
|
|
|
|
// =======================================================================
|
|
// BENCHMARK REPORT
|
|
// =======================================================================
|
|
|
|
fn printBenchmarkReport(self: *SwarmChaosTest, passed: bool) void {
|
|
std.debug.print("\n", .{});
|
|
printSeparator(70);
|
|
std.debug.print(" BENCHMARK REPORT\n", .{});
|
|
printSeparator(70);
|
|
std.debug.print("\n", .{});
|
|
|
|
// Test Configuration
|
|
std.debug.print("Configuration:\n", .{});
|
|
std.debug.print(" File size: {d} MB\n", .{Config.FILE_SIZE / (1024 * 1024)});
|
|
std.debug.print(" Piece size: {d} MB\n", .{Config.PIECE_SIZE / (1024 * 1024)});
|
|
std.debug.print(" Piece count: {d}\n", .{Config.PIECE_COUNT});
|
|
std.debug.print(" Total peers: {d}\n\n", .{self.peer_manager.peers.items.len});
|
|
|
|
// Phase Timings
|
|
std.debug.print("Phase Timings:\n", .{});
|
|
var total_time: f64 = 0;
|
|
for (self.swarm_metrics.phase_names, 0..) |name, i| {
|
|
if (self.swarm_metrics.phaseDuration(i)) |duration| {
|
|
std.debug.print(" {d}. {s:20} {d:6.1}s\n", .{ i + 1, name, duration });
|
|
total_time += duration;
|
|
}
|
|
}
|
|
std.debug.print(" {s:23} {d:6.1}s\n\n", .{ "TOTAL", self.swarm_metrics.totalDuration() });
|
|
|
|
// Resilience Metrics
|
|
std.debug.print("Resilience Metrics:\n", .{});
|
|
std.debug.print(" Seeder offline duration: {d:.1}s\n", .{
|
|
@as(f64, @floatFromInt(self.swarm_metrics.failure_duration orelse 0)) / 1000.0,
|
|
});
|
|
std.debug.print(" Cascade events: {d} (downloaders became seeders)\n", .{
|
|
self.swarm_metrics.cascade_count,
|
|
});
|
|
std.debug.print(" Swarm survived failure: {s}\n\n", .{
|
|
if (passed) "YES" else "NO",
|
|
});
|
|
|
|
// Per-Peer Performance
|
|
std.debug.print("Per-Peer Performance:\n", .{});
|
|
std.debug.print(" {s:6} {s:12} {s:12} {s:12} {s:15}\n", .{
|
|
"Peer", "Role", "Duration", "Avg Speed", "Became Seeder",
|
|
});
|
|
std.debug.print(" ------ ------------ ------------ ------------ ---------------\n", .{});
|
|
|
|
for (self.peer_manager.peers.items) |peer| {
|
|
const role_str = switch (peer.role) {
|
|
.primary_seeder => "seeder",
|
|
.initial_downloader => "initial",
|
|
.late_joiner_wave1 => "late-1",
|
|
.late_joiner_wave2 => "late-2",
|
|
};
|
|
|
|
const duration_str = if (peer.metrics.downloadDuration()) |d|
|
|
std.fmt.allocPrint(self.allocator, "{d:.1}s", .{d}) catch "-"
|
|
else
|
|
"-";
|
|
defer if (peer.metrics.downloadDuration() != null) self.allocator.free(duration_str);
|
|
|
|
const speed_str = if (peer.metrics.averageSpeed()) |s|
|
|
std.fmt.allocPrint(self.allocator, "{d:.1} MB/s", .{s}) catch "-"
|
|
else
|
|
"-";
|
|
defer if (peer.metrics.averageSpeed() != null) self.allocator.free(speed_str);
|
|
|
|
const seeder_str = if (peer.metrics.became_seeder_time != null) "Yes" else if (peer.role == .primary_seeder) "Original" else "No";
|
|
|
|
std.debug.print(" {s:6} {s:12} {s:12} {s:12} {s:15}\n", .{
|
|
peer.name,
|
|
role_str,
|
|
duration_str,
|
|
speed_str,
|
|
seeder_str,
|
|
});
|
|
}
|
|
|
|
// Final Result
|
|
std.debug.print("\n", .{});
|
|
printSeparator(70);
|
|
if (passed) {
|
|
std.debug.print(" RESULT: ALL TESTS PASSED\n", .{});
|
|
} else {
|
|
std.debug.print(" RESULT: TESTS FAILED\n", .{});
|
|
}
|
|
printSeparator(70);
|
|
}
|
|
};
|
|
|
|
// ============================================================================
|
|
// UTILITY FUNCTIONS
|
|
// ============================================================================
|
|
|
|
fn printSeparator(comptime width: usize) void {
|
|
std.debug.print("{s}\n", .{("=" ** width)[0..width]});
|
|
}
|
|
|
|
fn printDashes(comptime width: usize) void {
|
|
std.debug.print("{s}\n", .{("-" ** width)[0..width]});
|
|
}
|
|
|
|
fn createTestFile(path: []const u8, size: u64) !void {
|
|
// Check if file exists with correct size
|
|
if (std.fs.cwd().statFile(path)) |stat| {
|
|
if (stat.size == size) {
|
|
std.debug.print(" Reusing existing test file ({d} MB)\n", .{size / (1024 * 1024)});
|
|
return;
|
|
}
|
|
} else |_| {}
|
|
|
|
std.debug.print(" Creating test file ({d} MB)...\n", .{size / (1024 * 1024)});
|
|
|
|
const file = try std.fs.cwd().createFile(path, .{});
|
|
defer file.close();
|
|
|
|
try file.setEndPos(size);
|
|
try file.seekTo(0);
|
|
|
|
// Write pattern data
|
|
const pattern = "SwarmChaosTest_0123456789ABCDEF";
|
|
var buffer: [1024 * 1024]u8 = undefined;
|
|
for (&buffer, 0..) |*b, i| {
|
|
b.* = pattern[i % pattern.len];
|
|
}
|
|
|
|
var written: u64 = 0;
|
|
while (written < size) {
|
|
const to_write = @min(buffer.len, size - written);
|
|
try file.writeAll(buffer[0..to_write]);
|
|
written += to_write;
|
|
}
|
|
|
|
try file.sync();
|
|
}
|
|
|
|
fn verifyFile(download_path: []const u8, source_path: []const u8) bool {
|
|
const download_file = std.fs.cwd().openFile(download_path, .{}) catch |err| {
|
|
std.debug.print(" [VERIFY] Cannot open download: {}\n", .{err});
|
|
return false;
|
|
};
|
|
defer download_file.close();
|
|
|
|
const source_file = std.fs.cwd().openFile(source_path, .{}) catch |err| {
|
|
std.debug.print(" [VERIFY] Cannot open source: {}\n", .{err});
|
|
return false;
|
|
};
|
|
defer source_file.close();
|
|
|
|
const download_stat = download_file.stat() catch return false;
|
|
const source_stat = source_file.stat() catch return false;
|
|
|
|
if (download_stat.size != source_stat.size) {
|
|
std.debug.print(" [VERIFY] Size mismatch: download={d} source={d}\n", .{
|
|
download_stat.size,
|
|
source_stat.size,
|
|
});
|
|
return false;
|
|
}
|
|
|
|
var download_buf: [65536]u8 = undefined;
|
|
var source_buf: [65536]u8 = undefined;
|
|
var offset: u64 = 0;
|
|
|
|
while (true) {
|
|
const download_read = download_file.read(&download_buf) catch return false;
|
|
const source_read = source_file.read(&source_buf) catch return false;
|
|
|
|
if (download_read != source_read) {
|
|
std.debug.print(" [VERIFY] Read size mismatch at offset {d}\n", .{offset});
|
|
return false;
|
|
}
|
|
if (download_read == 0) break;
|
|
|
|
if (!std.mem.eql(u8, download_buf[0..download_read], source_buf[0..source_read])) {
|
|
// Find first differing byte
|
|
var diff_offset: usize = 0;
|
|
for (download_buf[0..download_read], source_buf[0..source_read], 0..) |d, s, i| {
|
|
if (d != s) {
|
|
diff_offset = i;
|
|
break;
|
|
}
|
|
}
|
|
const abs_offset = offset + diff_offset;
|
|
const piece_index = abs_offset / Config.PIECE_SIZE;
|
|
const offset_in_piece = abs_offset % Config.PIECE_SIZE;
|
|
|
|
// Count how many bytes at the start of this piece are zero
|
|
var zero_count: usize = 0;
|
|
const piece_start_in_buf = if (abs_offset >= offset) abs_offset - offset else 0;
|
|
for (download_buf[piece_start_in_buf..download_read]) |b| {
|
|
if (b == 0) {
|
|
zero_count += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
std.debug.print(" [VERIFY] Content mismatch at offset {d} (piece {d}, offset {d} in piece)\n", .{ abs_offset, piece_index, offset_in_piece });
|
|
std.debug.print(" Download byte: 0x{X:0>2}, Source byte: 0x{X:0>2}\n", .{
|
|
download_buf[diff_offset],
|
|
source_buf[diff_offset],
|
|
});
|
|
std.debug.print(" Zero bytes from mismatch: {d}\n", .{zero_count});
|
|
return false;
|
|
}
|
|
offset += download_read;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
fn cleanupDownloadFiles() void {
|
|
const files_to_delete = [_][]const u8{
|
|
"./tests/test_data/chaos_download_B.bin",
|
|
"./tests/test_data/chaos_download_C.bin",
|
|
"./tests/test_data/chaos_download_D.bin",
|
|
"./tests/test_data/chaos_download_E.bin",
|
|
"./tests/test_data/chaos_download_F.bin",
|
|
"./tests/test_data/chaos_download_G.bin",
|
|
};
|
|
|
|
for (files_to_delete) |path| {
|
|
std.fs.cwd().deleteFile(path) catch {};
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// MAIN
|
|
// ============================================================================
|
|
|
|
pub fn main() !void {
|
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
|
defer _ = gpa.deinit();
|
|
const allocator = gpa.allocator();
|
|
|
|
std.debug.print("\n", .{});
|
|
printSeparator(70);
|
|
std.debug.print(" SWARM CHAOS TEST - P2P Resilience Benchmark\n", .{});
|
|
printSeparator(70);
|
|
std.debug.print("\n", .{});
|
|
|
|
// Setup
|
|
const test_file_path = "./tests/test_data/chaos_test_source.bin";
|
|
|
|
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 test file
|
|
std.debug.print("Setup:\n", .{});
|
|
try createTestFile(test_file_path, Config.FILE_SIZE);
|
|
|
|
// Run test
|
|
var test_instance = SwarmChaosTest.init(allocator, test_file_path, &allowed_dirs);
|
|
defer test_instance.deinit();
|
|
defer cleanupDownloadFiles();
|
|
|
|
const passed = test_instance.run() catch |err| {
|
|
std.debug.print("\nTest failed with error: {}\n", .{err});
|
|
return err;
|
|
};
|
|
|
|
// Print report
|
|
test_instance.printBenchmarkReport(passed);
|
|
|
|
if (!passed) {
|
|
return error.TestFailed;
|
|
}
|
|
}
|