Files
zigp2p/tests/network/test_thread_safety.zig
2026-02-06 21:03:59 -03:00

424 lines
13 KiB
Zig

//! Thread safety tests for network module
//!
//! This module tests concurrent access to network components to verify
//! that all thread safety mechanisms (mutexes, RwLocks, atomics) work correctly.
const std = @import("std");
const testing = std.testing;
const Thread = std.Thread;
// Import network modules
const core = @import("core");
const Address = core.address.Address;
const topology_mod = @import("../../src/network/topology.zig");
const NetworkTopology = topology_mod.NetworkTopology;
const TopologyRole = topology_mod.TopologyRole;
const peer_mod = @import("../../src/network/peer.zig");
const PeerId = peer_mod.PeerId;
const Peer = peer_mod.Peer;
const PeerManager = peer_mod.PeerManager;
const node_mod = @import("../../src/network/node.zig");
const Node = node_mod.Node;
const NodeConfig = node_mod.NodeConfig;
const routing_mod = @import("../../src/network/routing.zig");
const KademliaRoutingTable = routing_mod.KademliaRoutingTable;
const NodePosition = topology_mod.NodePosition;
/// Test context for concurrent topology operations
const TopologyTestContext = struct {
topology: *NetworkTopology,
allocator: std.mem.Allocator,
iterations: usize,
thread_id: usize,
};
/// Worker thread that adds and removes nodes concurrently
fn topologyWorker(context: *TopologyTestContext) !void {
var prng = std.Random.DefaultPrng.init(@intCast(context.thread_id));
const random = prng.random();
var peer_ids = std.ArrayList(PeerId).init(context.allocator);
defer peer_ids.deinit();
// Add nodes
for (0..context.iterations) |_| {
const peer_id = PeerId.init();
const role = if (random.boolean()) TopologyRole.Regular else TopologyRole.Hub;
_ = context.topology.addNode(peer_id, role) catch |err| {
std.log.warn("Thread {} failed to add node: {}", .{ context.thread_id, err });
continue;
};
try peer_ids.append(peer_id);
// Random small sleep to increase contention
std.time.sleep(1 * std.time.ns_per_ms);
}
// Remove half the nodes
for (0..peer_ids.items.len / 2) |i| {
context.topology.removeNode(peer_ids.items[i]) catch |err| {
std.log.warn("Thread {} failed to remove node: {}", .{ context.thread_id, err });
};
}
}
test "NetworkTopology concurrent node additions and removals" {
const allocator = testing.allocator;
var topology = NetworkTopology.init(allocator, .Mesh);
defer topology.deinit();
const num_threads = 8;
const iterations_per_thread = 50;
var threads: [num_threads]Thread = undefined;
var contexts: [num_threads]TopologyTestContext = undefined;
// Start worker threads
for (&threads, 0..) |*thread, i| {
contexts[i] = TopologyTestContext{
.topology = &topology,
.allocator = allocator,
.iterations = iterations_per_thread,
.thread_id = i,
};
thread.* = try Thread.spawn(.{}, topologyWorker, .{&contexts[i]});
}
// Wait for all threads to complete
for (&threads) |*thread| {
thread.join();
}
// Topology should be in a valid state
const stats = topology.getStats();
try testing.expect(stats.node_count < num_threads * iterations_per_thread);
}
/// Test context for concurrent peer manager operations
const PeerManagerTestContext = struct {
manager: *PeerManager,
allocator: std.mem.Allocator,
iterations: usize,
thread_id: usize,
};
/// Worker thread that adds, queries, and removes peers concurrently
fn peerManagerWorker(context: *PeerManagerTestContext) !void {
var prng = std.Random.DefaultPrng.init(@intCast(context.thread_id));
const random = prng.random();
var addresses = std.ArrayList(Address).init(context.allocator);
defer addresses.deinit();
// Add peers
for (0..context.iterations) |i| {
var addr = Address.init();
addr.port = @intCast(10000 + (context.thread_id * 1000) + i);
_ = context.manager.addPeer(addr) catch |err| {
std.log.warn("Thread {} failed to add peer: {}", .{ context.thread_id, err });
continue;
};
try addresses.append(addr);
// Random operations
if (random.boolean()) {
// Query by address
_ = context.manager.getPeerByAddress(addr);
}
std.time.sleep(1 * std.time.ns_per_ms);
}
// Remove some peers
for (0..addresses.items.len / 2) |i| {
_ = context.manager.removePeerByAddress(addresses.items[i]) catch |err| {
std.log.warn("Thread {} failed to remove peer: {}", .{ context.thread_id, err });
};
}
}
test "PeerManager concurrent operations" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
const num_threads = 8;
const iterations_per_thread = 50;
var threads: [num_threads]Thread = undefined;
var contexts: [num_threads]PeerManagerTestContext = undefined;
// Start worker threads
for (&threads, 0..) |*thread, i| {
contexts[i] = PeerManagerTestContext{
.manager = &manager,
.allocator = allocator,
.iterations = iterations_per_thread,
.thread_id = i,
};
thread.* = try Thread.spawn(.{}, peerManagerWorker, .{&contexts[i]});
}
// Wait for all threads to complete
for (&threads) |*thread| {
thread.join();
}
// Manager should be in a valid state
const count = manager.getPeerCount();
try testing.expect(count < num_threads * iterations_per_thread);
}
/// Test context for concurrent routing table operations
const RoutingTableTestContext = struct {
table: *KademliaRoutingTable,
allocator: std.mem.Allocator,
iterations: usize,
thread_id: usize,
};
/// Worker thread that adds, queries, and removes peers from routing table
fn routingTableWorker(context: *RoutingTableTestContext) !void {
var prng = std.Random.DefaultPrng.init(@intCast(context.thread_id));
const random = prng.random();
var peer_ids = std.ArrayList(PeerId).init(context.allocator);
defer peer_ids.deinit();
var peers = std.ArrayList(*Peer).init(context.allocator);
defer {
for (peers.items) |peer| {
context.allocator.destroy(peer);
}
peers.deinit();
}
var positions = std.ArrayList(*NodePosition).init(context.allocator);
defer {
for (positions.items) |pos| {
pos.deinit();
context.allocator.destroy(pos);
}
positions.deinit();
}
// Add peers
for (0..context.iterations) |i| {
const peer_id = PeerId.init();
var addr = Address.init();
addr.port = @intCast(20000 + (context.thread_id * 1000) + i);
const peer = try context.allocator.create(Peer);
peer.* = Peer.init(peer_id, addr);
const position = try context.allocator.create(NodePosition);
position.* = NodePosition.init(context.allocator, peer_id);
context.table.addPeer(peer, position) catch |err| {
context.allocator.destroy(peer);
position.deinit();
context.allocator.destroy(position);
std.log.warn("Thread {} failed to add peer to routing table: {}", .{ context.thread_id, err });
continue;
};
try peer_ids.append(peer_id);
try peers.append(peer);
try positions.append(position);
// Random operations
if (random.boolean()) {
_ = context.table.containsPeer(peer_id);
}
if (random.boolean()) {
const target = PeerId.init();
const closest = context.table.findClosestPeers(target, 5) catch continue;
context.allocator.free(closest);
}
std.time.sleep(1 * std.time.ns_per_ms);
}
// Remove some peers
for (0..peer_ids.items.len / 2) |i| {
context.table.removePeer(peer_ids.items[i]);
}
}
test "KademliaRoutingTable concurrent operations" {
const allocator = testing.allocator;
const local_id = PeerId.init();
var table = KademliaRoutingTable.init(allocator, local_id);
defer table.deinit();
const num_threads = 8;
const iterations_per_thread = 30;
var threads: [num_threads]Thread = undefined;
var contexts: [num_threads]RoutingTableTestContext = undefined;
// Start worker threads
for (&threads, 0..) |*thread, i| {
contexts[i] = RoutingTableTestContext{
.table = &table,
.allocator = allocator,
.iterations = iterations_per_thread,
.thread_id = i,
};
thread.* = try Thread.spawn(.{}, routingTableWorker, .{&contexts[i]});
}
// Wait for all threads to complete
for (&threads) |*thread| {
thread.join();
}
// Routing table should be in a valid state
const peer_count = table.total_peers.load(.monotonic);
try testing.expect(peer_count < num_threads * iterations_per_thread);
}
/// Test context for concurrent node operations
const NodeTestContext = struct {
node: *Node,
allocator: std.mem.Allocator,
iterations: usize,
thread_id: usize,
};
/// Worker thread that adds and removes neighbors
fn nodeWorker(context: *NodeTestContext) !void {
var peer_ids = std.ArrayList(PeerId).init(context.allocator);
defer peer_ids.deinit();
// Add neighbors
for (0..context.iterations) |_| {
const neighbor_id = PeerId.init();
context.node.addNeighbor(neighbor_id) catch |err| {
std.log.warn("Thread {} failed to add neighbor: {}", .{ context.thread_id, err });
continue;
};
try peer_ids.append(neighbor_id);
std.time.sleep(1 * std.time.ns_per_ms);
}
// Remove half the neighbors
for (0..peer_ids.items.len / 2) |i| {
context.node.removeNeighbor(peer_ids.items[i]);
}
}
test "Node concurrent neighbor operations" {
const allocator = testing.allocator;
const node_id = PeerId.init();
var addr = Address.init();
addr.port = 8080;
var topology = NetworkTopology.init(allocator, .Mesh);
defer topology.deinit();
const config = NodeConfig{};
var node = Node.init(allocator, node_id, addr, &topology, config);
defer node.deinit();
try node.start();
defer node.stop();
const num_threads = 8;
const iterations_per_thread = 20;
var threads: [num_threads]Thread = undefined;
var contexts: [num_threads]NodeTestContext = undefined;
// Start worker threads
for (&threads, 0..) |*thread, i| {
contexts[i] = NodeTestContext{
.node = &node,
.allocator = allocator,
.iterations = iterations_per_thread,
.thread_id = i,
};
thread.* = try Thread.spawn(.{}, nodeWorker, .{&contexts[i]});
}
// Wait for all threads to complete
for (&threads) |*thread| {
thread.join();
}
// Node should be in a valid state
try testing.expect(node.neighbors.items.len < num_threads * iterations_per_thread);
}
test "Topology connection stress test" {
const allocator = testing.allocator;
var topology = NetworkTopology.init(allocator, .Mesh);
defer topology.deinit();
// Add initial nodes
const peer1 = PeerId.init();
const peer2 = PeerId.init();
const peer3 = PeerId.init();
_ = try topology.addNode(peer1, .Regular);
_ = try topology.addNode(peer2, .Regular);
_ = try topology.addNode(peer3, .Hub);
// Concurrently add and remove connections
const TestContext = struct {
topo: *NetworkTopology,
p1: PeerId,
p2: PeerId,
p3: PeerId,
thread_num: usize,
};
const worker = struct {
fn run(ctx: *TestContext) !void {
for (0..100) |_| {
// Add connections
ctx.topo.addConnection(ctx.p1, ctx.p2, 80) catch {};
ctx.topo.addConnection(ctx.p2, ctx.p3, 70) catch {};
ctx.topo.addConnection(ctx.p1, ctx.p3, 90) catch {};
std.time.sleep(1 * std.time.ns_per_ms);
// Remove connections
ctx.topo.removeConnection(ctx.p1, ctx.p2);
ctx.topo.removeConnection(ctx.p2, ctx.p3);
}
}
};
var context = TestContext{
.topo = &topology,
.p1 = peer1,
.p2 = peer2,
.p3 = peer3,
.thread_num = 0,
};
var threads: [4]Thread = undefined;
for (&threads, 0..) |*thread, i| {
context.thread_num = i;
thread.* = try Thread.spawn(.{}, worker.run, .{&context});
}
for (&threads) |*thread| {
thread.join();
}
// Topology should still be valid
const stats = topology.getStats();
try testing.expect(stats.node_count == 3);
}