//! Comprehensive thread safety tests for the protocol module //! Tests concurrent access to MessageRouter, CryptoManager, and HandlerRegistry const std = @import("std"); const testing = std.testing; const protocol = @import("../../src/protocol/protocol.zig"); const router_mod = @import("../../src/protocol/router.zig"); const crypto_mod = @import("../../src/protocol/crypto.zig"); const handler_mod = @import("../../src/protocol/handler.zig"); const message = @import("../../src/protocol/message.zig"); const NUM_THREADS = 8; const OPERATIONS_PER_THREAD = 1000; /// Test concurrent message routing test "concurrent message routing" { const allocator = testing.allocator; var msg_router = router_mod.MessageRouter.init(allocator); defer msg_router.deinit(); // Setup some initial routes var dest1: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE; var dest2: message.NodeId = [_]u8{2} ** protocol.Network.NODE_ID_SIZE; var dest3: message.NodeId = [_]u8{3} ** protocol.Network.NODE_ID_SIZE; try msg_router.addRoute(dest1, dest1, 1); try msg_router.addRoute(dest2, dest2, 2); try msg_router.addRoute(dest3, dest3, 3); // Spawn multiple threads that perform routing operations var threads: [NUM_THREADS]std.Thread = undefined; const ThreadContext = struct { router: *router_mod.MessageRouter, thread_id: usize, }; const routingThread = struct { fn run(ctx: ThreadContext) void { var source: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE; source[0] = @as(u8, @intCast(ctx.thread_id)); var i: usize = 0; while (i < OPERATIONS_PER_THREAD) : (i += 1) { // Rotate through destinations const dest_idx = i % 3; var dest: message.NodeId = undefined; if (dest_idx == 0) { dest = [_]u8{1} ** protocol.Network.NODE_ID_SIZE; } else if (dest_idx == 1) { dest = [_]u8{2} ** protocol.Network.NODE_ID_SIZE; } else { dest = [_]u8{3} ** protocol.Network.NODE_ID_SIZE; } const header = message.MessageHeader.init(.ping, i, source, dest); const base_msg = message.BaseMessage{ .header = header, .payload = &.{} }; // Perform routing const result = ctx.router.routeMessage(base_msg); _ = result; // Also test other read operations _ = ctx.router.isReachable(dest); _ = ctx.router.getNextHop(dest); // Occasionally add/remove routes if (i % 100 == 0) { var temp_dest: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE; temp_dest[0] = @as(u8, @intCast((ctx.thread_id + i) % 256)); ctx.router.addRoute(temp_dest, dest, 5) catch {}; } if (i % 150 == 0) { var temp_dest: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE; temp_dest[0] = @as(u8, @intCast((ctx.thread_id + i - 50) % 256)); ctx.router.removeRoute(temp_dest); } } } }.run; // Spawn threads for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .router = &msg_router, .thread_id = i }; thread.* = try std.Thread.spawn(.{}, routingThread, .{ctx}); } // Wait for all threads for (threads) |thread| { thread.join(); } // Verify metrics const metrics = msg_router.getMetrics(); const total_ops = NUM_THREADS * OPERATIONS_PER_THREAD; // Should have processed many lookups try testing.expect(metrics.successful_lookups > 0); try testing.expect(metrics.successful_lookups + metrics.failed_lookups == total_ops); // Should have added routes try testing.expect(metrics.total_routes > 3); std.debug.print("\nRouting Test Results:\n", .{}); std.debug.print(" Total Routes: {}\n", .{metrics.total_routes}); std.debug.print(" Active Routes: {}\n", .{metrics.active_routes}); std.debug.print(" Successful Lookups: {}\n", .{metrics.successful_lookups}); std.debug.print(" Failed Lookups: {}\n", .{metrics.failed_lookups}); std.debug.print(" Avg Lookup Time: {d:.6}s\n", .{metrics.average_lookup_time}); } /// Test concurrent encryption/decryption test "concurrent encryption and decryption" { const allocator = testing.allocator; var crypto = crypto_mod.CryptoManager.init(allocator); defer crypto.deinit(); // Setup peer keys const peer1_id = [_]u8{1} ** 32; const peer1_key = [_]u8{0x11} ** 32; const peer2_id = [_]u8{2} ** 32; const peer2_key = [_]u8{0x22} ** 32; try crypto.setKeyForPeer(peer1_id, peer1_key); try crypto.setKeyForPeer(peer2_id, peer2_key); var threads: [NUM_THREADS]std.Thread = undefined; const ThreadContext = struct { crypto_mgr: *crypto_mod.CryptoManager, thread_id: usize, alloc: std.mem.Allocator, }; const cryptoThread = struct { fn run(ctx: ThreadContext) void { var i: usize = 0; while (i < OPERATIONS_PER_THREAD / 10) : (i += 1) { // Fewer ops due to encryption cost // Alternate between peers const peer_id = if (i % 2 == 0) [_]u8{1} ** 32 else [_]u8{2} ** 32; // Create message var message_buf: [128]u8 = undefined; const msg = std.fmt.bufPrint(&message_buf, "Thread {} message {}", .{ ctx.thread_id, i }) catch unreachable; // Encrypt const ciphertext = ctx.crypto_mgr.encrypt(peer_id, msg) catch |err| { std.debug.print("Encrypt error: {}\n", .{err}); continue; }; defer ctx.alloc.free(ciphertext); // Decrypt const plaintext = ctx.crypto_mgr.decrypt(peer_id, ciphertext) catch |err| { std.debug.print("Decrypt error: {}\n", .{err}); continue; }; defer ctx.alloc.free(plaintext); // Verify if (!std.mem.eql(u8, msg, plaintext)) { std.debug.print("Decryption mismatch!\n", .{}); } } } }.run; // Spawn threads for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .crypto_mgr = &crypto, .thread_id = i, .alloc = allocator, }; thread.* = try std.Thread.spawn(.{}, cryptoThread, .{ctx}); } // Wait for all threads for (threads) |thread| { thread.join(); } std.debug.print("\nCrypto Test: Successfully completed {} concurrent encrypt/decrypt operations\n", .{NUM_THREADS * (OPERATIONS_PER_THREAD / 10)}); } /// Test concurrent handler registration and message processing test "concurrent handler operations" { const allocator = testing.allocator; var registry = try handler_mod.HandlerRegistry.init(allocator); defer registry.deinit(); // Register some initial handlers const test_handler_fn = struct { fn handler(msg: message.Message, ctx: *anyopaque) !void { const context = @as(*handler_mod.HandlerContext, @ptrCast(@alignCast(ctx))); _ = msg; context.metrics.recordMessageProcessed(0.001); } }.handler; // Register handlers for different message types const ping_handler = handler_mod.MessageHandler.init( test_handler_fn, registry.getContext(), .ping, ); try registry.registerHandler(.ping, ping_handler); const pong_handler = handler_mod.MessageHandler.init( test_handler_fn, registry.getContext(), .pong, ); try registry.registerHandler(.pong, pong_handler); var threads: [NUM_THREADS]std.Thread = undefined; const ThreadContext = struct { reg: *handler_mod.HandlerRegistry, thread_id: usize, }; const handlerThread = struct { fn run(ctx: ThreadContext) void { var i: usize = 0; while (i < OPERATIONS_PER_THREAD / 10) : (i += 1) { // Create and process messages const msg_type: protocol.MessageType = if (i % 2 == 0) .ping else .pong; const msg = if (msg_type == .ping) message.Message{ .ping = message.Ping.init(@as(u32, @intCast(i))) } else message.Message{ .pong = message.Pong.init(@as(u32, @intCast(i)), 10) }; // Process message ctx.reg.processMessage(msg) catch |err| { std.debug.print("Handler error: {}\n", .{err}); }; // Occasionally register new handlers (with different priorities) if (i % 50 == 0 and ctx.thread_id == 0) { var new_handler = handler_mod.MessageHandler.init( struct { fn h(m: message.Message, c: *anyopaque) !void { _ = m; _ = c; } }.h, ctx.reg.getContext(), msg_type, ); new_handler.priority = @as(u8, @intCast(i % 10)); ctx.reg.registerHandler(msg_type, new_handler) catch {}; } } } }.run; // Spawn threads for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .reg = ®istry, .thread_id = i }; thread.* = try std.Thread.spawn(.{}, handlerThread, .{ctx}); } // Wait for all threads for (threads) |thread| { thread.join(); } // Verify metrics const processed = registry.getContext().metrics.messages_processed; const failed = registry.getContext().metrics.messages_failed; try testing.expect(processed > 0); std.debug.print("\nHandler Test Results:\n", .{}); std.debug.print(" Messages Processed: {}\n", .{processed}); std.debug.print(" Messages Failed: {}\n", .{failed}); std.debug.print(" Handlers Registered: {}\n", .{registry.getContext().metrics.handlers_registered}); std.debug.print(" Success Rate: {d:.2}%\n", .{registry.getContext().metrics.getSuccessRate() * 100}); } /// Test metrics accuracy under concurrent access test "metrics accuracy under concurrent access" { const allocator = testing.allocator; var msg_router = router_mod.MessageRouter.init(allocator); defer msg_router.deinit(); // Add a single route var dest: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE; try msg_router.addRoute(dest, dest, 1); var threads: [NUM_THREADS]std.Thread = undefined; const expected_successful = NUM_THREADS * OPERATIONS_PER_THREAD; const ThreadContext = struct { router: *router_mod.MessageRouter, }; const metricsThread = struct { fn run(ctx: ThreadContext) void { var source: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE; var dest_val: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE; var i: usize = 0; while (i < OPERATIONS_PER_THREAD) : (i += 1) { const header = message.MessageHeader.init(.ping, i, source, dest_val); const base_msg = message.BaseMessage{ .header = header, .payload = &.{} }; const result = ctx.router.routeMessage(base_msg); _ = result; } } }.run; // Spawn threads for (&threads) |*thread| { const ctx = ThreadContext{ .router = &msg_router }; thread.* = try std.Thread.spawn(.{}, metricsThread, .{ctx}); } // Wait for all threads for (threads) |thread| { thread.join(); } // Verify metrics are accurate const metrics = msg_router.getMetrics(); std.debug.print("\nMetrics Accuracy Test:\n", .{}); std.debug.print(" Expected Successful Lookups: {}\n", .{expected_successful}); std.debug.print(" Actual Successful Lookups: {}\n", .{metrics.successful_lookups}); std.debug.print(" Difference: {}\n", .{ if (metrics.successful_lookups > expected_successful) metrics.successful_lookups - expected_successful else expected_successful - metrics.successful_lookups, }); // All lookups should be successful since route exists try testing.expectEqual(expected_successful, metrics.successful_lookups); try testing.expectEqual(@as(u64, 0), metrics.failed_lookups); } /// Test route table operations under high contention test "route table under high contention" { const allocator = testing.allocator; var msg_router = router_mod.MessageRouter.init(allocator); defer msg_router.deinit(); var threads: [NUM_THREADS]std.Thread = undefined; const ThreadContext = struct { router: *router_mod.MessageRouter, thread_id: usize, }; const contentionThread = struct { fn run(ctx: ThreadContext) void { var i: usize = 0; while (i < OPERATIONS_PER_THREAD / 10) : (i += 1) { var dest: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE; dest[0] = @as(u8, @intCast((ctx.thread_id + i) % 100)); // Mix of operations switch (i % 5) { 0 => { // Add route ctx.router.addRoute(dest, dest, @as(u32, @intCast(i % 10))) catch {}; }, 1 => { // Check reachability _ = ctx.router.isReachable(dest); }, 2 => { // Get next hop _ = ctx.router.getNextHop(dest); }, 3 => { // Invalidate route ctx.router.invalidateRoute(dest); }, 4 => { // Remove route ctx.router.removeRoute(dest); }, else => unreachable, } // Occasionally get all routes if (i % 100 == 0) { var routes = ctx.router.getAllRoutes(); routes.deinit(); } // Occasionally get stats if (i % 50 == 0) { _ = ctx.router.getRouteStats(); } } } }.run; // Spawn threads for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .router = &msg_router, .thread_id = i }; thread.* = try std.Thread.spawn(.{}, contentionThread, .{ctx}); } // Wait for all threads for (threads) |thread| { thread.join(); } const stats = msg_router.getRouteStats(); std.debug.print("\nContention Test Results:\n", .{}); std.debug.print(" Total Routes: {}\n", .{stats.total}); std.debug.print(" Active Routes: {}\n", .{stats.active}); std.debug.print(" Pending Queries: {}\n", .{stats.pending}); // Should have some routes added try testing.expect(stats.total > 0); }