refactor p2p: keepalive pings, WASM-safe messaging, non-blocking

connections
This commit is contained in:
2026-02-19 11:36:11 -03:00
parent 75087fb635
commit 7b120731a6
10 changed files with 288 additions and 142 deletions

View File

@@ -60,6 +60,7 @@ pub const circuit_breaker = @import("p2p/circuit_breaker.zig");
pub const p2p_impl = @import("p2p/p2p.zig"); pub const p2p_impl = @import("p2p/p2p.zig");
pub const dht = @import("p2p/dht.zig"); pub const dht = @import("p2p/dht.zig");
pub const messaging = @import("p2p/messaging.zig"); pub const messaging = @import("p2p/messaging.zig");
pub const file_ops = @import("p2p/file_ops.zig");
// Re-export main types // Re-export main types
pub const P2P = p2p_impl.P2P; pub const P2P = p2p_impl.P2P;

View File

@@ -7,6 +7,8 @@
//! - HalfOpen: Testing if service has recovered //! - HalfOpen: Testing if service has recovered
const std = @import("std"); const std = @import("std");
const Mutex = @import("sync").Mutex;
const platform_time = @import("platform").time;
/// Circuit breaker to prevent cascading failures /// Circuit breaker to prevent cascading failures
/// ///
@@ -16,7 +18,7 @@ const std = @import("std");
/// race conditions when accessed from multiple threads. /// race conditions when accessed from multiple threads.
pub const CircuitBreaker = struct { pub const CircuitBreaker = struct {
// THR-CRIT-1 FIX: Mutex to protect all mutable state // THR-CRIT-1 FIX: Mutex to protect all mutable state
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
state: State = .closed, state: State = .closed,
failure_count: u32 = 0, failure_count: u32 = 0,
@@ -48,7 +50,7 @@ pub const CircuitBreaker = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
switch (self.state) { switch (self.state) {
.closed => return true, .closed => return true,
@@ -75,7 +77,7 @@ pub const CircuitBreaker = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
switch (self.state) { switch (self.state) {
.closed => { .closed => {
@@ -102,7 +104,7 @@ pub const CircuitBreaker = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
self.last_failure_time = now; self.last_failure_time = now;
switch (self.state) { switch (self.state) {
@@ -142,7 +144,7 @@ pub const CircuitBreaker = struct {
self.failure_count = 0; self.failure_count = 0;
self.success_count = 0; self.success_count = 0;
self.last_failure_time = 0; self.last_failure_time = 0;
self.last_state_change = std.time.milliTimestamp(); self.last_state_change = platform_time.milliTimestamp();
} }
}; };

View File

@@ -223,6 +223,13 @@ pub const NetworkConfig = struct {
handshake_max_backoff_ms: u32 = 10000, handshake_max_backoff_ms: u32 = 10000,
/// Backoff multiplier (e.g., 2.0 = double each time) /// Backoff multiplier (e.g., 2.0 = double each time)
handshake_backoff_multiplier: f32 = 2.0, handshake_backoff_multiplier: f32 = 2.0,
/// Enable the UDP listener and related subsystems (discovery, TURN, bootstrap).
/// Set to false for WebRTC-only operation where no POSIX sockets are needed.
/// Desktop/mobile can run both UDP and WebRTC simultaneously (default).
enable_udp_listener: bool = true,
/// Enable WebRTC transport for browser peer connectivity.
/// Requires building with -Denable-webrtc=true to have effect.
webrtc_enabled: bool = false,
}; };
/// Protocol configuration /// Protocol configuration

View File

@@ -5,6 +5,8 @@
//! table management, value storage/retrieval, and network message propagation. //! table management, value storage/retrieval, and network message propagation.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
// Core components (via module import) // Core components (via module import)
const core = @import("core"); const core = @import("core");
@@ -30,7 +32,7 @@ const MAX_DHT_VALUE_SIZE: u32 = 1024 * 1024;
/// Generate a cryptographically random wire nonce for replay detection /// Generate a cryptographically random wire nonce for replay detection
fn generateWireNonce() u64 { fn generateWireNonce() u64 {
var bytes: [8]u8 = undefined; var bytes: [8]u8 = undefined;
std.crypto.random.bytes(&bytes); platform_random.bytes(&bytes);
return std.mem.readInt(u64, &bytes, .little); return std.mem.readInt(u64, &bytes, .little);
} }
@@ -208,7 +210,7 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.target_observed_addr = target_observed.addr, .target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len, .target_observed_addr_len = target_observed.len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };
@@ -231,7 +233,7 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.target_observed_addr = target_observed.addr, .target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len, .target_observed_addr_len = target_observed.len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };
@@ -252,7 +254,7 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.target_observed_addr = target_observed.addr, .target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len, .target_observed_addr_len = target_observed.len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };

View File

@@ -6,6 +6,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const core = @import("core"); const core = @import("core");
const platform = @import("platform");
const network = @import("network"); const network = @import("network");
const Error = core.errors.Error; const Error = core.errors.Error;
const PeerId = network.peer.PeerId; const PeerId = network.peer.PeerId;
@@ -49,6 +50,7 @@ pub const P2PEvent = struct {
upload_started = 0x3004, upload_started = 0x3004,
upload_completed = 0x3005, upload_completed = 0x3005,
upload_failed = 0x3006, upload_failed = 0x3006,
file_transfer_progress = 0x3007,
/// Protocol events /// Protocol events
message_sent = 0x4000, message_sent = 0x4000,
@@ -82,6 +84,13 @@ pub const P2PEvent = struct {
upload_started: struct { session_id: u64, file_path: []const u8 }, upload_started: struct { session_id: u64, file_path: []const u8 },
upload_completed: struct { session_id: u64, bytes_uploaded: u64 }, upload_completed: struct { session_id: u64, bytes_uploaded: u64 },
upload_failed: struct { session_id: u64, err: Error }, upload_failed: struct { session_id: u64, err: Error },
file_transfer_progress: struct {
session_id: u64,
direction: enum { send, receive },
bytes_transferred: u64,
total_bytes: u64,
speed_bps: u64,
},
message_sent: struct { message_type: u8, destination: ?PeerId }, message_sent: struct { message_type: u8, destination: ?PeerId },
message_received: struct { message_type: u8, source: PeerId, data: []const u8 }, message_received: struct { message_type: u8, source: PeerId, data: []const u8 },
@@ -98,7 +107,7 @@ pub const P2PEvent = struct {
return P2PEvent{ return P2PEvent{
.event_type = event_type, .event_type = event_type,
.data = data, .data = data,
.timestamp = std.time.timestamp(), .timestamp = platform.time.timestamp(),
.session_id = null, .session_id = null,
}; };
} }
@@ -108,7 +117,7 @@ pub const P2PEvent = struct {
return P2PEvent{ return P2PEvent{
.event_type = event_type, .event_type = event_type,
.data = data, .data = data,
.timestamp = std.time.timestamp(), .timestamp = platform.time.timestamp(),
.session_id = session_id, .session_id = session_id,
}; };
} }
@@ -221,7 +230,7 @@ test "P2PEvent: deinit with owned message_received" {
.data = owned_data, .data = owned_data,
}, },
}, },
.timestamp = std.time.timestamp(), .timestamp = platform.time.timestamp(),
.owns_payload = true, .owns_payload = true,
.allocator = allocator, .allocator = allocator,
}; };
@@ -243,7 +252,7 @@ test "P2PEvent: deinit with owned library_error" {
.message = owned_msg, .message = owned_msg,
}, },
}, },
.timestamp = std.time.timestamp(), .timestamp = platform.time.timestamp(),
.owns_payload = true, .owns_payload = true,
.allocator = allocator, .allocator = allocator,
}; };
@@ -265,7 +274,7 @@ test "P2PEvent: deinit with owned peer_disconnected" {
.reason = owned_reason, .reason = owned_reason,
}, },
}, },
.timestamp = std.time.timestamp(), .timestamp = platform.time.timestamp(),
.owns_payload = true, .owns_payload = true,
.allocator = allocator, .allocator = allocator,
}; };

View File

@@ -4,6 +4,7 @@
//! These functions handle file addition, sharing, downloading, and transfer message processing. //! These functions handle file addition, sharing, downloading, and transfer message processing.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
// Core components (via module import) // Core components (via module import)
const core = @import("core"); const core = @import("core");
@@ -315,7 +316,7 @@ pub fn handleFileTransferMessageImpl(p2p: *P2P, peer_id: [32]u8, data: []const u
.message_id = 0, .message_id = 0,
.peer_id = &peer_id, .peer_id = &peer_id,
.data = &reject_payload, .data = &reject_payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
if (fm.network_sender) |sender| { if (fm.network_sender) |sender| {
_ = sender.sendMessage(reject_msg) catch {}; _ = sender.sendMessage(reject_msg) catch {};

View File

@@ -6,10 +6,14 @@
//! All functions take a `*P2P` as the first parameter. //! All functions take a `*P2P` as the first parameter.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const Thread = std.Thread; const Thread = std.Thread;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
// Core components // Core components
const core = @import("core"); const core = @import("core");
const platform = @import("platform");
const platform_time = platform.time;
const Error = core.errors.Error; const Error = core.errors.Error;
const Address = core.Address; const Address = core.Address;
@@ -126,23 +130,26 @@ pub fn startImpl(p2p: *P2P) Error!void {
p2p.node.?.* = Node.init(p2p.allocator, peer_id, p2p.address, p2p.topology.?, node_config); p2p.node.?.* = Node.init(p2p.allocator, peer_id, p2p.address, p2p.topology.?, node_config);
// Initialize discovery manager (optional - may fail if port in use) // Initialize discovery manager (optional - may fail if port in use)
const discovery_config = network.discovery.DiscoveryConfig{ // Only when UDP listener is enabled (discovery uses broadcast sockets)
.broadcast_address = p2p.address, if (p2p.config.network.enable_udp_listener) {
.discovery_port = if (p2p.config.network.listen_port == 0) 9999 else p2p.config.network.listen_port, const discovery_config = network.discovery.DiscoveryConfig{
}; .broadcast_address = p2p.address,
// First try to init, then allocate - this way if init fails, we don't have a dangling pointer .discovery_port = if (p2p.config.network.listen_port == 0) 9999 else p2p.config.network.listen_port,
if (DiscoveryManager.init(p2p.allocator, discovery_config)) |discovery_mgr| {
p2p.discovery_manager = p2p.allocator.create(DiscoveryManager) catch {
// discovery_mgr was successfully initialized, need to clean up
var temp = discovery_mgr;
temp.deinit();
return Error.SystemError;
}; };
p2p.discovery_manager.?.* = discovery_mgr; // First try to init, then allocate - this way if init fails, we don't have a dangling pointer
} else |err| { if (DiscoveryManager.init(p2p.allocator, discovery_config)) |discovery_mgr| {
// Discovery failed to initialize - continue without it p2p.discovery_manager = p2p.allocator.create(DiscoveryManager) catch {
std.log.warn("Discovery manager failed to initialize: {}. Continuing without discovery.", .{err}); // discovery_mgr was successfully initialized, need to clean up
p2p.discovery_manager = null; var temp = discovery_mgr;
temp.deinit();
return Error.SystemError;
};
p2p.discovery_manager.?.* = discovery_mgr;
} else |err| {
// Discovery failed to initialize - continue without it
std.log.warn("Discovery manager failed to initialize: {}. Continuing without discovery.", .{err});
p2p.discovery_manager = null;
}
} }
// Initialize protocol components // Initialize protocol components
@@ -202,12 +209,14 @@ pub fn startImpl(p2p: *P2P) Error!void {
} }
// Initialize file sharing manager // Initialize file sharing manager
const fm_ptr = p2p.allocator.create(FileSharingManager) catch return Error.SystemError; {
fm_ptr.* = FileSharingManager.init(p2p.config.file_sharing, p2p.allocator) catch { const fm_ptr = p2p.allocator.create(FileSharingManager) catch return Error.SystemError;
p2p.allocator.destroy(fm_ptr); fm_ptr.* = FileSharingManager.init(p2p.config.file_sharing, p2p.allocator) catch {
return Error.SystemError; p2p.allocator.destroy(fm_ptr);
}; return Error.SystemError;
p2p.file_manager = fm_ptr; };
p2p.file_manager = fm_ptr;
}
// Wire file transfer to network // Wire file transfer to network
if (p2p.file_manager) |fm| { if (p2p.file_manager) |fm| {
@@ -263,31 +272,33 @@ pub fn startImpl(p2p: *P2P) Error!void {
p2p.connection_pool = p2p.allocator.create(core.connection.ConnectionPool) catch return Error.SystemError; p2p.connection_pool = p2p.allocator.create(core.connection.ConnectionPool) catch return Error.SystemError;
p2p.connection_pool.?.* = core.connection.ConnectionPool.init(connection_config, p2p.allocator); p2p.connection_pool.?.* = core.connection.ConnectionPool.init(connection_config, p2p.allocator);
// Start the node // Start the node (binds UDP socket) — only when UDP listener is enabled
try p2p.node.?.start(); if (p2p.config.network.enable_udp_listener) {
try p2p.node.?.start();
// Initialize TURN integration if enabled // Initialize TURN integration if enabled
if (p2p.config.network.turn_enabled) { if (p2p.config.network.turn_enabled) {
const turn_config = network.turn_integration.TurnConfig{ const turn_config = network.turn_integration.TurnConfig{
.enabled = p2p.config.network.turn_enabled, .enabled = p2p.config.network.turn_enabled,
.servers = p2p.config.network.turn_servers, .servers = p2p.config.network.turn_servers,
.fallback_timeout_ms = p2p.config.network.turn_fallback_timeout_ms, .fallback_timeout_ms = p2p.config.network.turn_fallback_timeout_ms,
.refresh_interval_ms = p2p.config.network.turn_refresh_interval_ms, .refresh_interval_ms = p2p.config.network.turn_refresh_interval_ms,
};
p2p.turn_integration = p2p.allocator.create(network.TurnIntegration) catch |err| blk: {
std.log.warn("Failed to allocate TURN integration: {}, continuing without TURN support", .{err});
break :blk null;
};
if (p2p.turn_integration) |integration| {
integration.* = network.TurnIntegration.init(p2p.allocator, turn_config);
integration.start() catch |err| {
std.log.warn("TURN integration failed to start: {}. TURN relay unavailable.", .{err});
integration.deinit();
p2p.allocator.destroy(integration);
p2p.turn_integration = null;
}; };
p2p.turn_integration = p2p.allocator.create(network.TurnIntegration) catch |err| blk: {
std.log.warn("Failed to allocate TURN integration: {}, continuing without TURN support", .{err});
break :blk null;
};
if (p2p.turn_integration) |integration| {
integration.* = network.TurnIntegration.init(p2p.allocator, turn_config);
integration.start() catch |err| {
std.log.warn("TURN integration failed to start: {}. TURN relay unavailable.", .{err});
integration.deinit();
p2p.allocator.destroy(integration);
p2p.turn_integration = null;
};
}
} }
} }
@@ -349,7 +360,11 @@ pub fn startImpl(p2p: *P2P) Error!void {
p2p.state_mutex.unlock(); p2p.state_mutex.unlock();
p2p.running.store(true, .release); p2p.running.store(true, .release);
p2p.start_time = std.time.timestamp(); p2p.start_time = platform_time.timestamp();
if (!p2p.config.network.enable_udp_listener) {
std.log.info("P2P started with UDP listener disabled (WebRTC-only mode)", .{});
}
// PERF: Start verification thread pool for parallel SHA-256 // PERF: Start verification thread pool for parallel SHA-256
if (p2p.file_manager) |fm| { if (p2p.file_manager) |fm| {
@@ -362,8 +377,10 @@ pub fn startImpl(p2p: *P2P) Error!void {
}; };
} }
// Connect to bootstrap nodes if configured // Connect to bootstrap nodes if configured (requires UDP listener)
if (p2p.config.network.bootstrap_nodes.len > 0) { if (p2p.config.network.enable_udp_listener and
(p2p.config.network.bootstrap_nodes.len > 0 or p2p.config.network.pinned_bootstrap_nodes.len > 0))
{
connectToBootstrapNodesImpl(p2p); connectToBootstrapNodesImpl(p2p);
} }
@@ -390,7 +407,7 @@ pub fn stopImpl(p2p: *P2P) Error!void {
if (p2p.file_manager) |fm| { if (p2p.file_manager) |fm| {
// MED-1 FIX: Safe widening cast from u32 to i64 // MED-1 FIX: Safe widening cast from u32 to i64
const shutdown_timeout_ms: i64 = @as(i64, p2p.config.library.shutdown_timeout_ms); const shutdown_timeout_ms: i64 = @as(i64, p2p.config.library.shutdown_timeout_ms);
const deadline = std.time.milliTimestamp() + shutdown_timeout_ms; const deadline = platform_time.milliTimestamp() + shutdown_timeout_ms;
var initial_active_count: usize = 0; var initial_active_count: usize = 0;
// Get initial transfer count for logging // Get initial transfer count for logging
@@ -401,7 +418,7 @@ pub fn stopImpl(p2p: *P2P) Error!void {
std.log.info("Gracefully stopping: waiting up to {}ms for {} active transfers to complete", .{ shutdown_timeout_ms, initial_active_count }); std.log.info("Gracefully stopping: waiting up to {}ms for {} active transfers to complete", .{ shutdown_timeout_ms, initial_active_count });
} }
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
// Check if there are any active transfers // Check if there are any active transfers
const fm_stats = fm.getStats(); const fm_stats = fm.getStats();
const has_active = fm_stats.downloading_sessions > 0 or fm_stats.uploading_sessions > 0; const has_active = fm_stats.downloading_sessions > 0 or fm_stats.uploading_sessions > 0;
@@ -420,11 +437,11 @@ pub fn stopImpl(p2p: *P2P) Error!void {
}; };
// Sleep briefly to avoid spinning // Sleep briefly to avoid spinning
Thread.sleep(p2p.config.library.shutdown_poll_interval_ms * std.time.ns_per_ms); platform.time.sleep(p2p.config.library.shutdown_poll_interval_ms * std.time.ns_per_ms);
} }
// Check if timeout was reached // Check if timeout was reached
if (std.time.milliTimestamp() >= deadline) { if (platform_time.milliTimestamp() >= deadline) {
const remaining_stats = fm.getStats(); const remaining_stats = fm.getStats();
const remaining = remaining_stats.downloading_sessions + remaining_stats.uploading_sessions; const remaining = remaining_stats.downloading_sessions + remaining_stats.uploading_sessions;
if (remaining > 0) { if (remaining > 0) {
@@ -635,34 +652,46 @@ pub fn connectToBootstrapNodesImpl(p2p: *P2P) void {
} }
} }
/// Perform health checks on all connections /// Perform health checks on all connections.
/// Sends keepalive pings to idle-but-alive connections to prevent premature timeout.
pub fn performHealthChecksImpl(p2p: *P2P) Error!void { pub fn performHealthChecksImpl(p2p: *P2P) Error!void {
var dead_peers: std.ArrayListUnmanaged(PeerId) = .{}; var dead_peers: std.ArrayListUnmanaged(PeerId) = .{};
defer dead_peers.deinit(p2p.allocator); defer dead_peers.deinit(p2p.allocator);
var keepalive_peers: std.ArrayListUnmanaged(PeerId) = .{};
defer keepalive_peers.deinit(p2p.allocator);
const keepalive_ms: i64 = @intCast(p2p.config.network.keepalive_interval_ms);
const idle_timeout_ms: i64 = @intCast(p2p.config.network.idle_timeout_ms);
p2p.peer_connections_mutex.lock(); p2p.peer_connections_mutex.lock();
var iter = p2p.peer_connections.iterator(); var iter = p2p.peer_connections.iterator();
while (iter.next()) |entry| { while (iter.next()) |entry| {
const peer_id = entry.key_ptr.*; const peer_id = entry.key_ptr.*;
const peer_conn = entry.value_ptr.*; const peer_conn = entry.value_ptr.*;
const socket = peer_conn.socket;
if (socket.state == .closed) { if (peer_conn.transport_handle.getState() == .closed) {
std.log.debug("Health check: peer {x} has closed socket, marking dead", .{peer_id.bytes[0..8].*}); std.log.debug("Health check: peer {x} has closed transport, marking dead", .{peer_id.bytes[0..8].*});
dead_peers.append(p2p.allocator, peer_id) catch |err| { dead_peers.append(p2p.allocator, peer_id) catch |err| {
std.log.warn("Failed to track dead peer during health check (closed socket): {}", .{err}); std.log.warn("Failed to track dead peer during health check (closed transport): {}", .{err});
continue; continue;
}; };
continue; continue;
} }
const idle_ms = std.time.milliTimestamp() - socket.stats.getLastActivity(); // Use socket stats for idle detection (transport abstraction doesn't track stats yet)
if (idle_ms > p2p.config.network.idle_timeout_ms) { // WebRTC connections (socket == null) skip socket-based idle detection.
const socket = peer_conn.socket orelse continue;
const idle_ms = platform_time.milliTimestamp() - socket.stats.getLastActivity();
if (idle_ms > idle_timeout_ms) {
std.log.debug("Health check: peer {x} idle for {}ms, marking dead", .{ peer_id.bytes[0..8].*, idle_ms }); std.log.debug("Health check: peer {x} idle for {}ms, marking dead", .{ peer_id.bytes[0..8].*, idle_ms });
dead_peers.append(p2p.allocator, peer_id) catch |err| { dead_peers.append(p2p.allocator, peer_id) catch |err| {
std.log.warn("Failed to track idle peer during health check (idle: {}ms): {}", .{ idle_ms, err }); std.log.warn("Failed to track idle peer during health check (idle: {}ms): {}", .{ idle_ms, err });
continue; continue;
}; };
} else if (idle_ms > keepalive_ms) {
// Connection is idle but not dead yet — send keepalive to prevent timeout
keepalive_peers.append(p2p.allocator, peer_id) catch {};
} }
} }
p2p.peer_connections_mutex.unlock(); p2p.peer_connections_mutex.unlock();
@@ -672,11 +701,24 @@ pub fn performHealthChecksImpl(p2p: *P2P) Error!void {
std.log.warn("Failed to disconnect dead peer during health check: {}", .{err}); std.log.warn("Failed to disconnect dead peer during health check: {}", .{err});
}; };
} }
// Send keepalive pings to idle-but-alive peers.
// The send updates socket.stats.last_activity on both sender (via Socket.send)
// and receiver (via Socket.receive), preventing idle timeout on both sides.
if (keepalive_peers.items.len > 0) {
const nm = p2p.network_manager orelse return;
const keepalive_frame = [_]u8{messaging.KEEPALIVE_APP_ID};
for (keepalive_peers.items) |peer_id| {
_ = nm.sendMessage(peer_id, &keepalive_frame) catch |err| {
std.log.debug("Keepalive send failed for peer {x}: {}", .{ peer_id.bytes[0..8].*, err });
};
}
}
} }
/// Check error rate and transition to maintenance/error state if needed /// Check error rate and transition to maintenance/error state if needed
pub fn checkErrorRateAndTransitionStateImpl(p2p: *P2P) Error!void { pub fn checkErrorRateAndTransitionStateImpl(p2p: *P2P) Error!void {
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
const window_duration_ms: i64 = @as(i64, p2p.config.network.session_cleanup_interval_ms); const window_duration_ms: i64 = @as(i64, p2p.config.network.session_cleanup_interval_ms);
if (p2p.error_window_start == 0 or (now - p2p.error_window_start) >= window_duration_ms) { if (p2p.error_window_start == 0 or (now - p2p.error_window_start) >= window_duration_ms) {

View File

@@ -5,7 +5,9 @@
//! and network message/disconnect handling callbacks. //! and network message/disconnect handling callbacks.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
// Core components // Core components
const core = @import("core"); const core = @import("core");
@@ -18,6 +20,9 @@ const PeerId = network.peer.PeerId;
// Protocol components // Protocol components
const protocol = @import("protocol"); const protocol = @import("protocol");
// Platform components
const platform = @import("platform");
// File sharing components // File sharing components
const files = @import("files"); const files = @import("files");
@@ -81,13 +86,15 @@ fn getPerSessionEnvelopeKey(p2p: *P2P, peer_id: PeerId) ?[16]u8 {
} }
/// Reserved app_ids that have their own send paths and replay protection. /// Reserved app_ids that have their own send paths and replay protection.
/// Keepalive (0x00): internal ping to prevent idle timeout, silently discarded on receive.
/// File transfer (0x01): own integrity via piece hashing / session tracking. /// File transfer (0x01): own integrity via piece hashing / session tracking.
/// DHT (0x02): own wire_nonce/wire_timestamp embedded in serialization. /// DHT (0x02): own wire_nonce/wire_timestamp embedded in serialization.
pub const KEEPALIVE_APP_ID: u8 = 0x00;
const RESERVED_FILE_TRANSFER: u8 = 0x01; const RESERVED_FILE_TRANSFER: u8 = 0x01;
const RESERVED_DHT: u8 = 0x02; const RESERVED_DHT: u8 = 0x02;
fn isReservedAppId(app_id: u8) bool { fn isReservedAppId(app_id: u8) bool {
return app_id == RESERVED_FILE_TRANSFER or app_id == RESERVED_DHT; return app_id == KEEPALIVE_APP_ID or app_id == RESERVED_FILE_TRANSFER or app_id == RESERVED_DHT;
} }
/// Send a custom message to a peer /// Send a custom message to a peer
@@ -116,7 +123,7 @@ pub fn sendMessageImpl(p2p: *P2P, destination: ?PeerId, message_type: u8, data:
// - Noise ON: SipHash(session_key, salt || ts || app_id || payload) // - Noise ON: SipHash(session_key, salt || ts || app_id || payload)
// - Noise OFF: raw salt (passive replay protection only) // - Noise OFF: raw salt (passive replay protection only)
const wire_salt = protocol.message.generateWireNonce(); // 8 random bytes const wire_salt = protocol.message.generateWireNonce(); // 8 random bytes
const wire_timestamp = std.time.timestamp(); const wire_timestamp = platform.time.timestamp();
std.mem.writeInt(u64, full_msg[1..9], wire_salt, .little); std.mem.writeInt(u64, full_msg[1..9], wire_salt, .little);
std.mem.writeInt(i64, full_msg[9..17], wire_timestamp, .little); std.mem.writeInt(i64, full_msg[9..17], wire_timestamp, .little);
} }
@@ -178,7 +185,7 @@ pub fn emitEventImpl(p2p: *P2P, event: P2PEvent) Error!void {
p2p.event_queue.append(p2p.allocator, event) catch return Error.OutOfMemory; p2p.event_queue.append(p2p.allocator, event) catch return Error.OutOfMemory;
if (p2p.config.events.enable_logging) { if (!is_wasm and p2p.config.events.enable_logging) {
std.debug.print("P2P Event: {s}\n", .{@tagName(event.event_type)}); std.debug.print("P2P Event: {s}\n", .{@tagName(event.event_type)});
} }
} }
@@ -195,7 +202,7 @@ pub fn emitErrorEventImpl(p2p: *P2P, err: anyerror, message: []const u8) Error!v
.message = message, .message = message,
}, },
}, },
.timestamp = std.time.timestamp(), .timestamp = platform.time.timestamp(),
.session_id = null, .session_id = null,
}; };
try emitEventImpl(p2p, event); try emitEventImpl(p2p, event);
@@ -218,6 +225,9 @@ pub fn updateImpl(p2p: *P2P) Error!void {
}; };
} }
// 1b. Advance pending (non-blocking) connections
p2p.advancePendingConnections();
// 2. Process network I/O // 2. Process network I/O
if (p2p.network_manager) |nm| { if (p2p.network_manager) |nm| {
nm.processReceive() catch |err| { nm.processReceive() catch |err| {
@@ -246,7 +256,7 @@ pub fn updateImpl(p2p: *P2P) Error!void {
} }
// 4. Health checks // 4. Health checks
const now = std.time.milliTimestamp(); const now = platform.time.milliTimestamp();
if (now - p2p.last_health_check > p2p.config.network.health_check_interval_ms) { if (now - p2p.last_health_check > p2p.config.network.health_check_interval_ms) {
lifecycle.performHealthChecksImpl(p2p) catch |err| { lifecycle.performHealthChecksImpl(p2p) catch |err| {
std.log.warn("Health checks failed: {}", .{err}); std.log.warn("Health checks failed: {}", .{err});
@@ -256,12 +266,12 @@ pub fn updateImpl(p2p: *P2P) Error!void {
p2p.last_health_check = now; p2p.last_health_check = now;
} }
// 5. TURN allocation refresh // 5. TURN allocation refresh (not available on WASM)
if (p2p.turn_integration) |integration| { if (!is_wasm) if (p2p.turn_integration) |integration| {
integration.refreshIfNeeded() catch |err| { integration.refreshIfNeeded() catch |err| {
std.log.warn("TURN refresh failed: {} - NAT traversal may be degraded", .{err}); std.log.warn("TURN refresh failed: {} - NAT traversal may be degraded", .{err});
}; };
} };
// 6. Replay protection cleanup // 6. Replay protection cleanup
const cleanup_interval_ms = p2p.config.protocol.replay_protection_cleanup_interval * 1000; const cleanup_interval_ms = p2p.config.protocol.replay_protection_cleanup_interval * 1000;
@@ -294,7 +304,7 @@ pub fn updateImpl(p2p: *P2P) Error!void {
/// Update statistics from various sources /// Update statistics from various sources
pub fn updateStatsImpl(p2p: *P2P) void { pub fn updateStatsImpl(p2p: *P2P) void {
if (p2p.start_time > 0) { if (p2p.start_time > 0) {
const now = std.time.timestamp(); const now = platform.time.timestamp();
const elapsed = now - p2p.start_time; const elapsed = now - p2p.start_time;
p2p.stats.uptime_seconds = if (elapsed < 0) 0 else if (elapsed > std.math.maxInt(u64)) std.math.maxInt(u64) else @intCast(elapsed); p2p.stats.uptime_seconds = if (elapsed < 0) 0 else if (elapsed > std.math.maxInt(u64)) std.math.maxInt(u64) else @intCast(elapsed);
} }
@@ -322,6 +332,10 @@ pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*an
const app_id: u8 = if (data.len > 0) data[0] else 0; const app_id: u8 = if (data.len > 0) data[0] else 0;
// Keepalive ping — silently discard. The receive itself already
// updated socket.stats.last_activity, which is all we need.
if (app_id == KEEPALIVE_APP_ID) return;
// File transfer messages bypass event system // File transfer messages bypass event system
if (data.len > 1 and app_id == 0x01) { if (data.len > 1 and app_id == 0x01) {
file_ops.handleFileTransferMessageImpl(p2p, peer_id.bytes, data[1..]); file_ops.handleFileTransferMessageImpl(p2p, peer_id.bytes, data[1..]);
@@ -372,11 +386,17 @@ pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*an
return; return;
}; };
} else { } else {
// SECURITY: No handler registry means no replay protection. Drop the message. if (is_wasm) {
// This should never happen after start() completes (handler_registry is initialized // WASM mode: no HandlerRegistry (would pull in POSIX deps).
// in startImpl before network callbacks are wired), but guard against it defensively. // Skip replay protection — WebRTC DataChannels are already encrypted
std.log.warn("SECURITY: Non-DHT message DROPPED — no handler registry for replay protection (app_id={})", .{app_id}); // and integrity-protected by DTLS, so passive replay is not a concern.
return; } else {
// SECURITY: No handler registry means no replay protection. Drop the message.
// This should never happen after start() completes (handler_registry is initialized
// in startImpl before network callbacks are wired), but guard against it defensively.
std.log.warn("SECURITY: Non-DHT message DROPPED — no handler registry for replay protection (app_id={})", .{app_id});
return;
}
} }
const payload = p2p.allocator.dupe(u8, payload_src) catch return; const payload = p2p.allocator.dupe(u8, payload_src) catch return;
@@ -436,7 +456,7 @@ pub fn handleNetworkDisconnectImpl(peer_id: PeerId, context: ?*anyopaque) void {
socket.close() catch {}; socket.close() catch {};
socket.deinit(); socket.deinit();
p2p.allocator.destroy(socket); p2p.allocator.destroy(socket);
} } // null: either peer not found or WebRTC (no socket to clean up)
emitEventImpl(p2p, P2PEvent.create(.peer_disconnected, .{ emitEventImpl(p2p, P2PEvent.create(.peer_disconnected, .{
.peer_disconnected = .{ .peer_disconnected = .{

View File

@@ -22,9 +22,13 @@ const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList; const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap; const AutoHashMap = std.AutoHashMap;
const Thread = std.Thread; const Thread = std.Thread;
const Mutex = std.Thread.Mutex; const sync = @import("sync");
const atomic = std.atomic; const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const Ed25519 = std.crypto.sign.Ed25519; const Ed25519 = std.crypto.sign.Ed25519;
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
// Core components (via module import) // Core components (via module import)
const core = @import("core"); const core = @import("core");
@@ -55,6 +59,9 @@ const VerifyResult = network.VerifyResult;
const NatPmp = network.NatPmp; const NatPmp = network.NatPmp;
const Upnp = network.Upnp; const Upnp = network.Upnp;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
// Protocol components (via module import) // Protocol components (via module import)
const protocol = @import("protocol"); const protocol = @import("protocol");
const MessageHandler = protocol.handler.MessageHandler; const MessageHandler = protocol.handler.MessageHandler;
@@ -119,7 +126,7 @@ pub const ObservedAddress = struct {
if (addr_len == 0) return null; if (addr_len == 0) return null;
var result: ObservedAddress = undefined; var result: ObservedAddress = undefined;
result.timestamp = std.time.milliTimestamp(); result.timestamp = platform_time.milliTimestamp();
result.observer_id = observer; result.observer_id = observer;
if (addr_len == 6) { if (addr_len == 6) {
@@ -424,8 +431,8 @@ pub const P2P = struct {
/// Statistics /// Statistics
stats: P2PStats, stats: P2PStats,
/// Internal flags (THREAD SAFETY: atomic for lock-free access from multiple threads) /// Internal flags (THREAD SAFETY: atomic for lock-free access from multiple threads)
initialized: atomic.Value(bool) = atomic.Value(bool).init(false), initialized: AtomicValue(bool) = AtomicValue(bool).init(false),
running: atomic.Value(bool) = atomic.Value(bool).init(false), running: AtomicValue(bool) = AtomicValue(bool).init(false),
/// Start time for uptime tracking /// Start time for uptime tracking
start_time: i64 = 0, start_time: i64 = 0,
/// Last health check timestamp /// Last health check timestamp
@@ -434,7 +441,7 @@ pub const P2P = struct {
last_replay_cleanup: i64 = 0, last_replay_cleanup: i64 = 0,
/// Error rate tracking for maintenance mode /// Error rate tracking for maintenance mode
error_window_start: i64 = 0, error_window_start: i64 = 0,
errors_in_window: atomic.Value(u32) = atomic.Value(u32).init(0), errors_in_window: AtomicValue(u32) = AtomicValue(u32).init(0),
/// Last maintenance check timestamp /// Last maintenance check timestamp
last_maintenance_check: i64 = 0, last_maintenance_check: i64 = 0,
/// IMP-2 FIX: Circuit breaker for preventing cascading failures /// IMP-2 FIX: Circuit breaker for preventing cascading failures
@@ -443,6 +450,11 @@ pub const P2P = struct {
/// Last error summary emission /// Last error summary emission
last_error_summary: i64 = 0, last_error_summary: i64 = 0,
/// Non-blocking connections in progress (DoS exchange + Noise handshake)
pending_connections: std.ArrayList(connection.PendingConnection),
/// Mutex for pending_connections list
pending_connections_mutex: Mutex,
// ========================================================================= // =========================================================================
// Init/Deinit Methods (kept inline - complex initialization logic) // Init/Deinit Methods (kept inline - complex initialization logic)
// ========================================================================= // =========================================================================
@@ -482,7 +494,7 @@ pub const P2P = struct {
.turn_integration = null, .turn_integration = null,
.routing_table = null, .routing_table = null,
.dht_coordinator = null, .dht_coordinator = null,
.identity_keypair = Ed25519.KeyPair.generate(), .identity_keypair = generateEd25519KeyPair(),
.local_node_id = undefined, .local_node_id = undefined,
.noise_keypair = if (p2p_config.network.enable_noise_encryption) .noise_keypair = if (p2p_config.network.enable_noise_encryption)
(if (p2p_config.network.noise_static_key) |key| (if (p2p_config.network.noise_static_key) |key|
@@ -504,27 +516,29 @@ pub const P2P = struct {
.state = .Uninitialized, .state = .Uninitialized,
.uptime_seconds = 0, .uptime_seconds = 0,
.memory_allocated = 0, .memory_allocated = 0,
.active_connections = atomic.Value(u32).init(0), .active_connections = AtomicValue(u32).init(0),
.total_connections = atomic.Value(u64).init(0), .total_connections = AtomicValue(u64).init(0),
.messages_sent = atomic.Value(u64).init(0), .messages_sent = AtomicValue(u64).init(0),
.messages_received = atomic.Value(u64).init(0), .messages_received = AtomicValue(u64).init(0),
.current_download_rate = atomic.Value(u64).init(0), .current_download_rate = AtomicValue(u64).init(0),
.current_upload_rate = atomic.Value(u64).init(0), .current_upload_rate = AtomicValue(u64).init(0),
.active_downloads = atomic.Value(u32).init(0), .active_downloads = AtomicValue(u32).init(0),
.active_uploads = atomic.Value(u32).init(0), .active_uploads = AtomicValue(u32).init(0),
.total_downloaded = atomic.Value(u64).init(0), .total_downloaded = AtomicValue(u64).init(0),
.total_uploaded = atomic.Value(u64).init(0), .total_uploaded = AtomicValue(u64).init(0),
.event_queue_size = 0, .event_queue_size = 0,
.events_processed = atomic.Value(u64).init(0), .events_processed = AtomicValue(u64).init(0),
.events_dropped = atomic.Value(u64).init(0), .events_dropped = AtomicValue(u64).init(0),
.errors_total = atomic.Value(u64).init(0), .errors_total = AtomicValue(u64).init(0),
.receive_errors = atomic.Value(u64).init(0), .receive_errors = AtomicValue(u64).init(0),
}, },
.start_time = 0, .start_time = 0,
.last_health_check = 0, .last_health_check = 0,
.last_replay_cleanup = 0, .last_replay_cleanup = 0,
.error_window_start = 0, .error_window_start = 0,
.last_maintenance_check = 0, .last_maintenance_check = 0,
.pending_connections = .{},
.pending_connections_mutex = Mutex{},
}; };
errdefer p2p.peer_connections.deinit(); errdefer p2p.peer_connections.deinit();
errdefer p2p.event_queue.deinit(allocator); errdefer p2p.event_queue.deinit(allocator);
@@ -767,13 +781,21 @@ pub const P2P = struct {
p2p.allocator.destroy(pm); p2p.allocator.destroy(pm);
} }
// Clean up pending (in-progress) connections
for (p2p.pending_connections.items) |*pending| {
pending.deinit();
}
p2p.pending_connections.deinit(p2p.allocator);
// Close and cleanup peer connections // Close and cleanup peer connections
p2p.peer_connections_mutex.lock(); p2p.peer_connections_mutex.lock();
var iter = p2p.peer_connections.iterator(); var iter = p2p.peer_connections.iterator();
while (iter.next()) |entry| { while (iter.next()) |entry| {
const peer_conn = entry.value_ptr.*; const peer_conn = entry.value_ptr.*;
peer_conn.socket.deinit(); if (peer_conn.socket) |socket| {
p2p.allocator.destroy(peer_conn.socket); socket.deinit();
p2p.allocator.destroy(socket);
}
peer_conn.deinit(); peer_conn.deinit();
} }
p2p.peer_connections.deinit(); p2p.peer_connections.deinit();
@@ -864,6 +886,16 @@ pub const P2P = struct {
return connection.acceptConnectionsImpl(p2p); return connection.acceptConnectionsImpl(p2p);
} }
/// Start a non-blocking outbound connection (async DoS + Noise handshake).
pub fn startNonBlockingConnect(p2p: *P2P, address: Address) Error!void {
return connection.startNonBlockingConnectImpl(p2p, address);
}
/// Advance all pending (non-blocking) connections by one step.
pub fn advancePendingConnections(p2p: *P2P) void {
connection.advancePendingConnectionsImpl(p2p);
}
pub fn startListening(p2p: *P2P, address: Address) Error!void { pub fn startListening(p2p: *P2P, address: Address) Error!void {
return connection.startListeningImpl(p2p, address); return connection.startListeningImpl(p2p, address);
} }
@@ -884,6 +916,22 @@ pub const P2P = struct {
return connection.removePeerConnectionImpl(p2p, peer_id); return connection.removePeerConnectionImpl(p2p, peer_id);
} }
/// Add a peer connection backed by a pre-built Transport (e.g. WebRTC DataChannel).
pub fn addPeerConnectionWithTransport(p2p: *P2P, peer_id: PeerId, transport_handle: core.transport.Transport) Error!void {
return connection.addPeerConnectionWithTransportImpl(p2p, peer_id, transport_handle);
}
/// Add a peer connection with a pre-built Transport and Noise encryption (e.g. WebRTC + Noise).
pub fn addPeerConnectionWithTransportSecure(p2p: *P2P, peer_id: PeerId, transport_handle: core.transport.Transport, secure: *SecureConnection) Error!void {
return connection.addPeerConnectionWithTransportSecureImpl(p2p, peer_id, transport_handle, secure);
}
/// Get the Noise keypair if Noise encryption is enabled.
pub fn getNoiseKeyPair(self: *P2P) ?NoiseKeyPair {
if (self.noise_enabled) return self.noise_keypair;
return null;
}
pub fn sendToPeerAtomic(p2p: *P2P, peer_id: PeerId, data: []const u8) Error!bool { pub fn sendToPeerAtomic(p2p: *P2P, peer_id: PeerId, data: []const u8) Error!bool {
return connection.sendToPeerAtomicImpl(p2p, peer_id, data); return connection.sendToPeerAtomicImpl(p2p, peer_id, data);
} }
@@ -1660,6 +1708,7 @@ test "P2P: reference all decls" {
_ = P2P.addPeerConnection; _ = P2P.addPeerConnection;
_ = P2P.addPeerConnectionSecure; _ = P2P.addPeerConnectionSecure;
_ = P2P.removePeerConnection; _ = P2P.removePeerConnection;
_ = P2P.addPeerConnectionWithTransport;
_ = P2P.sendToPeerAtomic; _ = P2P.sendToPeerAtomic;
_ = P2P.sendSegmentsToPeerAtomic; _ = P2P.sendSegmentsToPeerAtomic;
_ = P2P.drainPendingSends; _ = P2P.drainPendingSends;
@@ -1705,3 +1754,16 @@ test "P2P: reference all decls" {
_ = registerNodeIdCallback; _ = registerNodeIdCallback;
_ = handleDataResponseCallback; _ = handleDataResponseCallback;
} }
/// Generate an Ed25519 keypair using platform random (WASM-compatible).
/// Equivalent to Ed25519.KeyPair.generate() but uses platform_random instead of std.crypto.random.
fn generateEd25519KeyPair() Ed25519.KeyPair {
while (true) {
var seed: [Ed25519.KeyPair.seed_length]u8 = undefined;
platform_random.bytes(&seed);
return Ed25519.KeyPair.generateDeterministic(seed) catch {
@branchHint(.unlikely);
continue;
};
}
}

View File

@@ -5,7 +5,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const atomic = std.atomic; const AtomicValue = @import("sync").AtomicValue;
const types = @import("types.zig"); const types = @import("types.zig");
const P2PState = types.P2PState; const P2PState = types.P2PState;
const core = @import("core"); const core = @import("core");
@@ -33,29 +33,29 @@ pub const P2PStats = struct {
/// Total memory allocated /// Total memory allocated
memory_allocated: usize, memory_allocated: usize,
/// Active connections (atomic for thread-safe concurrent updates) /// Active connections (atomic for thread-safe concurrent updates)
active_connections: atomic.Value(u32), active_connections: AtomicValue(u32),
/// Total connections established (atomic for thread-safe concurrent updates) /// Total connections established (atomic for thread-safe concurrent updates)
total_connections: atomic.Value(u64), total_connections: AtomicValue(u64),
/// Messages sent/received (atomic for thread-safe concurrent updates) /// Messages sent/received (atomic for thread-safe concurrent updates)
messages_sent: atomic.Value(u64), messages_sent: AtomicValue(u64),
messages_received: atomic.Value(u64), messages_received: AtomicValue(u64),
/// Bandwidth usage (atomic for thread-safe concurrent updates) /// Bandwidth usage (atomic for thread-safe concurrent updates)
current_download_rate: atomic.Value(u64), // bytes/second current_download_rate: AtomicValue(u64), // bytes/second
current_upload_rate: atomic.Value(u64), // bytes/second current_upload_rate: AtomicValue(u64), // bytes/second
/// File sharing statistics (atomic for thread-safe concurrent updates) /// File sharing statistics (atomic for thread-safe concurrent updates)
active_downloads: atomic.Value(u32), active_downloads: AtomicValue(u32),
active_uploads: atomic.Value(u32), active_uploads: AtomicValue(u32),
total_downloaded: atomic.Value(u64), total_downloaded: AtomicValue(u64),
total_uploaded: atomic.Value(u64), total_uploaded: AtomicValue(u64),
/// Event queue statistics /// Event queue statistics
event_queue_size: usize, event_queue_size: usize,
/// Atomic counter for events processed (thread-safe) /// Atomic counter for events processed (thread-safe)
events_processed: atomic.Value(u64), events_processed: AtomicValue(u64),
/// Atomic counter for events dropped due to queue full (thread-safe) /// Atomic counter for events dropped due to queue full (thread-safe)
events_dropped: atomic.Value(u64), events_dropped: AtomicValue(u64),
/// Error statistics (atomic for thread-safe concurrent updates) /// Error statistics (atomic for thread-safe concurrent updates)
errors_total: atomic.Value(u64), errors_total: AtomicValue(u64),
receive_errors: atomic.Value(u64), receive_errors: AtomicValue(u64),
last_error: ?Error = null, last_error: ?Error = null,
/// Get formatted statistics string /// Get formatted statistics string
@@ -140,21 +140,21 @@ test "P2PStats: atomic counter operations" {
.state = .Initialized, .state = .Initialized,
.uptime_seconds = 0, .uptime_seconds = 0,
.memory_allocated = 0, .memory_allocated = 0,
.active_connections = atomic.Value(u32).init(0), .active_connections = AtomicValue(u32).init(0),
.total_connections = atomic.Value(u64).init(0), .total_connections = AtomicValue(u64).init(0),
.messages_sent = atomic.Value(u64).init(0), .messages_sent = AtomicValue(u64).init(0),
.messages_received = atomic.Value(u64).init(0), .messages_received = AtomicValue(u64).init(0),
.current_download_rate = atomic.Value(u64).init(0), .current_download_rate = AtomicValue(u64).init(0),
.current_upload_rate = atomic.Value(u64).init(0), .current_upload_rate = AtomicValue(u64).init(0),
.active_downloads = atomic.Value(u32).init(0), .active_downloads = AtomicValue(u32).init(0),
.active_uploads = atomic.Value(u32).init(0), .active_uploads = AtomicValue(u32).init(0),
.total_downloaded = atomic.Value(u64).init(0), .total_downloaded = AtomicValue(u64).init(0),
.total_uploaded = atomic.Value(u64).init(0), .total_uploaded = AtomicValue(u64).init(0),
.event_queue_size = 0, .event_queue_size = 0,
.events_processed = atomic.Value(u64).init(0), .events_processed = AtomicValue(u64).init(0),
.events_dropped = atomic.Value(u64).init(0), .events_dropped = AtomicValue(u64).init(0),
.errors_total = atomic.Value(u64).init(0), .errors_total = AtomicValue(u64).init(0),
.receive_errors = atomic.Value(u64).init(0), .receive_errors = AtomicValue(u64).init(0),
}; };
// Test increment operations // Test increment operations