bundled STUN. every DHT response now includes observed_addr field so nodes discover their public IP without external STUN servers
801 lines
30 KiB
Zig
801 lines
30 KiB
Zig
//! P2P Lifecycle Management
|
|
//!
|
|
//! This module contains free functions for managing P2P library lifecycle,
|
|
//! including start, stop, shutdown, maintenance mode, and error state handling.
|
|
//!
|
|
//! All functions take a `*P2P` as the first parameter.
|
|
|
|
const std = @import("std");
|
|
const Thread = std.Thread;
|
|
|
|
// Core components
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
const Address = core.Address;
|
|
|
|
// Network components
|
|
const network = @import("network");
|
|
const PeerId = network.peer.PeerId;
|
|
const Node = network.node.Node;
|
|
const DiscoveryManager = network.discovery.DiscoveryManager;
|
|
const NetworkTopology = network.topology.NetworkTopology;
|
|
const NetworkManager = network.network_manager.NetworkManager;
|
|
const PeerRateLimiter = core.rate_limiter.PeerRateLimiter;
|
|
const ConnectionRateLimiter = core.rate_limiter.ConnectionRateLimiter;
|
|
|
|
// Protocol components
|
|
const protocol = @import("protocol");
|
|
const HandlerRegistry = protocol.handler.HandlerRegistry;
|
|
const MessageHandler = protocol.handler.MessageHandler;
|
|
const MessageRouter = protocol.router.MessageRouter;
|
|
const handler_impl = protocol.handler_impl;
|
|
|
|
// Sibling impl modules
|
|
const messaging = @import("messaging.zig");
|
|
const file_ops = @import("file_ops.zig");
|
|
const dht_ops = @import("dht.zig");
|
|
|
|
// File sharing components
|
|
const files = @import("files");
|
|
const FileSharingManager = files.manager.FileSharingManager;
|
|
|
|
// P2P type and callbacks
|
|
const p2p_module = @import("p2p.zig");
|
|
const P2P = p2p_module.P2P;
|
|
const handleDataResponseCallback = p2p_module.handleDataResponseCallback;
|
|
const registerNodeIdCallback = p2p_module.registerNodeIdCallback;
|
|
const sendDhtMessageCallback = p2p_module.sendDhtMessageCallback;
|
|
const P2PEvent = @import("events.zig").P2PEvent;
|
|
const P2PConfig = @import("config.zig").P2PConfig;
|
|
|
|
// ============================================================================
|
|
// Lifecycle Functions
|
|
// ============================================================================
|
|
|
|
/// Start the P2P library
|
|
///
|
|
/// Initializes and starts all subsystems:
|
|
/// - Network stack (node, topology, discovery)
|
|
/// - Protocol handling (message router, handler registry)
|
|
/// - File sharing (file manager, transfer sessions)
|
|
/// - Rate limiting (if enabled)
|
|
/// - TURN integration (if enabled)
|
|
/// - DHT/Kademlia routing (for peer discovery)
|
|
///
|
|
/// # Returns
|
|
///
|
|
/// * `Error!void` - Success or one of:
|
|
/// * `InvalidState` - Library not initialized or already running
|
|
/// * `ConnectionAlreadyExists` - Already started
|
|
/// * `NetworkError` - Network initialization failed
|
|
/// * `SystemError` - System resource allocation failed
|
|
pub fn startImpl(p2p: *P2P) Error!void {
|
|
if (!p2p.initialized.load(.acquire)) return Error.InvalidState;
|
|
if (p2p.running.load(.acquire)) return Error.ConnectionAlreadyExists;
|
|
|
|
// LOCK ORDER: state_mutex (1st in hierarchy - highest priority)
|
|
p2p.state_mutex.lock();
|
|
const current_state = p2p.state;
|
|
if (current_state != .Initialized and current_state != .Stopped) {
|
|
p2p.state_mutex.unlock();
|
|
return Error.InvalidState;
|
|
}
|
|
p2p.state = .Starting;
|
|
p2p.state_mutex.unlock();
|
|
|
|
errdefer {
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Stopped;
|
|
p2p.state_mutex.unlock();
|
|
}
|
|
|
|
// Allocate and initialize network components
|
|
const peer_id = PeerId.init();
|
|
p2p.topology = p2p.allocator.create(NetworkTopology) catch return Error.SystemError;
|
|
errdefer {
|
|
if (p2p.topology) |topo| {
|
|
topo.deinit();
|
|
p2p.allocator.destroy(topo);
|
|
p2p.topology = null;
|
|
}
|
|
}
|
|
p2p.topology.?.* = NetworkTopology.init(p2p.allocator, .Mesh);
|
|
|
|
const node_config = network.node.NodeConfig{};
|
|
p2p.node = p2p.allocator.create(Node) catch return Error.SystemError;
|
|
errdefer {
|
|
if (p2p.node) |node_ptr| {
|
|
node_ptr.deinit();
|
|
p2p.allocator.destroy(node_ptr);
|
|
p2p.node = null;
|
|
}
|
|
if (p2p.topology) |topo| {
|
|
topo.deinit();
|
|
p2p.allocator.destroy(topo);
|
|
p2p.topology = null;
|
|
}
|
|
}
|
|
p2p.node.?.* = Node.init(p2p.allocator, peer_id, p2p.address, p2p.topology.?, node_config);
|
|
|
|
// Initialize discovery manager (optional - may fail if port in use)
|
|
const discovery_config = network.discovery.DiscoveryConfig{
|
|
.broadcast_address = p2p.address,
|
|
.discovery_port = if (p2p.config.network.listen_port == 0) 9999 else p2p.config.network.listen_port,
|
|
};
|
|
// First try to init, then allocate - this way if init fails, we don't have a dangling pointer
|
|
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;
|
|
} 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
|
|
p2p.handler_registry = p2p.allocator.create(HandlerRegistry) catch return Error.SystemError;
|
|
p2p.handler_registry.?.* = HandlerRegistry.init(p2p.allocator) catch return Error.SystemError;
|
|
|
|
// Register DHT message handlers
|
|
registerDhtHandlers(p2p.handler_registry.?) catch return Error.SystemError;
|
|
|
|
p2p.message_router = p2p.allocator.create(MessageRouter) catch return Error.SystemError;
|
|
// IMP-CRIT-2 FIX: Pass local node ID for proper message routing
|
|
p2p.message_router.?.* = MessageRouter.init(p2p.allocator, p2p.node.?.id.bytes);
|
|
|
|
// Initialize rate limiters if enabled
|
|
if (p2p.config.network.enable_rate_limiting) {
|
|
// Initialize peer rate limiter
|
|
p2p.peer_rate_limiter = p2p.allocator.create(PeerRateLimiter) catch return Error.SystemError;
|
|
// MED-1 FIX: Safe widening cast from u32 to u64
|
|
p2p.peer_rate_limiter.?.* = PeerRateLimiter.init(
|
|
p2p.allocator,
|
|
.{
|
|
.tokens_per_second = @as(u64, p2p.config.network.message_rate_limit),
|
|
.burst_size = @as(u64, p2p.config.network.message_burst_size),
|
|
},
|
|
);
|
|
|
|
// Initialize connection rate limiter
|
|
p2p.connection_rate_limiter = p2p.allocator.create(ConnectionRateLimiter) catch return Error.SystemError;
|
|
// MED-1 FIX: Safe widening cast from u32 to u64, multiply with u64 to prevent overflow
|
|
p2p.connection_rate_limiter.?.* = ConnectionRateLimiter.init(
|
|
p2p.allocator,
|
|
.{
|
|
.tokens_per_second = @as(u64, p2p.config.network.connection_rate_limit),
|
|
.burst_size = @as(u64, p2p.config.network.connection_burst_size),
|
|
},
|
|
.{
|
|
.tokens_per_second = @as(u64, p2p.config.network.connection_rate_limit) * 2,
|
|
.burst_size = @as(u64, p2p.config.network.connection_burst_size) * 2,
|
|
},
|
|
);
|
|
}
|
|
|
|
// Initialize network manager
|
|
p2p.network_manager = p2p.allocator.create(NetworkManager) catch return Error.SystemError;
|
|
p2p.network_manager.?.* = NetworkManager.init(p2p.allocator, &p2p.peer_connections);
|
|
|
|
// CRITICAL FIX: Set socket mutex to ensure atomic socket access
|
|
p2p.network_manager.?.setSocketMutex(&p2p.peer_connections_mutex);
|
|
|
|
// Wire up network callbacks
|
|
p2p.network_manager.?.setMessageCallback(messaging.handleNetworkMessageImpl, p2p);
|
|
p2p.network_manager.?.setDisconnectCallback(messaging.handleNetworkDisconnectImpl, p2p);
|
|
|
|
// Set rate limiter in network manager if enabled
|
|
if (p2p.peer_rate_limiter) |prl| {
|
|
p2p.network_manager.?.setPeerRateLimiter(prl);
|
|
}
|
|
|
|
// 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 {
|
|
p2p.allocator.destroy(fm_ptr);
|
|
return Error.SystemError;
|
|
};
|
|
p2p.file_manager = fm_ptr;
|
|
|
|
// Wire file transfer to network
|
|
if (p2p.file_manager) |fm| {
|
|
fm.p2p_context = p2p;
|
|
|
|
// Create and set the network sender
|
|
const sender = p2p.allocator.create(files.manager.NetworkSender) catch return Error.SystemError;
|
|
sender.* = file_ops.createFileTransferSenderImpl(p2p);
|
|
fm.setNetworkSender(sender);
|
|
|
|
// CRIT-1 FIX: Wire the data response handler callback
|
|
if (p2p.handler_registry) |hr| {
|
|
const ctx = hr.getContext();
|
|
ctx.setDataResponseHandler(.{
|
|
.handler_fn = handleDataResponseCallback,
|
|
.context = p2p,
|
|
});
|
|
// Wire the node ID registration callback
|
|
ctx.setNodeIdRegistrationCallback(.{
|
|
.register_fn = registerNodeIdCallback,
|
|
.context = p2p,
|
|
});
|
|
// Wire the DHT message sender callback for simple binary format responses
|
|
ctx.setDhtMessageSender(.{
|
|
.send_fn = sendDhtMessageCallback,
|
|
.context = p2p,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Initialize peer manager
|
|
p2p.peer_manager = p2p.allocator.create(network.peer.PeerManager) catch return Error.SystemError;
|
|
p2p.peer_manager.?.* = network.peer.PeerManager.init(p2p.allocator);
|
|
|
|
// Initialize connection pool
|
|
const connection_config = core.connection.ConnectionConfig{
|
|
.connection_type = .tcp,
|
|
.buffer_size = 4 * 1024 * 1024, // 4MB for high throughput
|
|
.timeout_ms = p2p.config.network.connection_timeout,
|
|
.keep_alive = true,
|
|
.no_delay = true,
|
|
};
|
|
p2p.connection_pool = p2p.allocator.create(core.connection.ConnectionPool) catch return Error.SystemError;
|
|
p2p.connection_pool.?.* = core.connection.ConnectionPool.init(connection_config, p2p.allocator);
|
|
|
|
// Start the node
|
|
try p2p.node.?.start();
|
|
|
|
// Initialize TURN integration if enabled
|
|
if (p2p.config.network.turn_enabled) {
|
|
const turn_config = network.turn_integration.TurnConfig{
|
|
.enabled = p2p.config.network.turn_enabled,
|
|
.servers = p2p.config.network.turn_servers,
|
|
.fallback_timeout_ms = p2p.config.network.turn_fallback_timeout_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;
|
|
};
|
|
}
|
|
}
|
|
|
|
// Initialize DHT (Distributed Hash Table) for peer discovery
|
|
{
|
|
const local_id = PeerId{ .bytes = p2p.local_node_id };
|
|
|
|
// Initialize Kademlia routing table
|
|
p2p.routing_table = p2p.allocator.create(network.KademliaRoutingTable) catch |err| blk: {
|
|
std.log.warn("Failed to allocate routing table: {}, continuing without DHT support", .{err});
|
|
break :blk null;
|
|
};
|
|
|
|
if (p2p.routing_table) |rt| {
|
|
rt.* = network.KademliaRoutingTable.init(p2p.allocator, local_id);
|
|
|
|
// Initialize DHT coordinator
|
|
p2p.dht_coordinator = p2p.allocator.create(network.DhtCoordinator) catch |err| blk: {
|
|
std.log.warn("Failed to allocate DHT coordinator: {}, continuing without DHT", .{err});
|
|
rt.deinit();
|
|
p2p.allocator.destroy(rt);
|
|
p2p.routing_table = null;
|
|
break :blk null;
|
|
};
|
|
|
|
if (p2p.dht_coordinator) |dht| {
|
|
dht.* = network.DhtCoordinator.initInsecureForDevelopment(p2p.allocator, rt, p2p.local_node_id);
|
|
std.log.info("DHT coordinator initialized with node ID (from identity): ", .{});
|
|
|
|
// Wire DHT coordinator to handler context
|
|
if (p2p.handler_registry) |hr| {
|
|
const ctx = hr.getContext();
|
|
ctx.dht_coordinator = dht;
|
|
ctx.routing_table = rt;
|
|
ctx.local_node_id = p2p.local_node_id;
|
|
}
|
|
|
|
// Wire DHT network sender
|
|
const dht_sender = dht_ops.createDhtNetworkSenderImpl(p2p);
|
|
dht.setNetworkSender(dht_sender);
|
|
std.log.info("DHT network sender wired - DHT can now send messages", .{});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Mark as running before connecting to bootstrap nodes
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Running;
|
|
p2p.state_mutex.unlock();
|
|
|
|
p2p.running.store(true, .release);
|
|
p2p.start_time = std.time.timestamp();
|
|
|
|
// PERF: Start verification thread pool for parallel SHA-256
|
|
if (p2p.file_manager) |fm| {
|
|
fm.startVerificationPool() catch |err| {
|
|
std.log.warn("Failed to start verification pool: {}. Using synchronous verification.", .{err});
|
|
};
|
|
// PERF: Start piece processing pipeline
|
|
fm.startPiecePipeline() catch |err| {
|
|
std.log.warn("Failed to start piece pipeline: {}. Using direct processing.", .{err});
|
|
};
|
|
}
|
|
|
|
// Connect to bootstrap nodes if configured
|
|
if (p2p.config.network.bootstrap_nodes.len > 0) {
|
|
connectToBootstrapNodesImpl(p2p);
|
|
}
|
|
|
|
// Emit start event
|
|
try p2p.emitEvent(P2PEvent.create(.library_started, .library_started));
|
|
}
|
|
|
|
/// Stop the P2P library
|
|
///
|
|
/// Gracefully stops all subsystems and closes connections.
|
|
/// The library can be restarted with `start()` after stopping.
|
|
///
|
|
/// # Returns
|
|
///
|
|
/// * `Error!void` - Success or error code
|
|
pub fn stopImpl(p2p: *P2P) Error!void {
|
|
if (!p2p.running.load(.acquire)) return Error.InvalidState;
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Stopping;
|
|
p2p.state_mutex.unlock();
|
|
|
|
// Wait for active transfers to complete (with configurable timeout)
|
|
if (p2p.file_manager) |fm| {
|
|
// MED-1 FIX: Safe widening cast from u32 to i64
|
|
const shutdown_timeout_ms: i64 = @as(i64, p2p.config.library.shutdown_timeout_ms);
|
|
const deadline = std.time.milliTimestamp() + shutdown_timeout_ms;
|
|
var initial_active_count: usize = 0;
|
|
|
|
// Get initial transfer count for logging
|
|
const initial_stats = fm.getStats();
|
|
initial_active_count = initial_stats.downloading_sessions + initial_stats.uploading_sessions;
|
|
|
|
if (initial_active_count > 0) {
|
|
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) {
|
|
// Check if there are any active transfers
|
|
const fm_stats = fm.getStats();
|
|
const has_active = fm_stats.downloading_sessions > 0 or fm_stats.uploading_sessions > 0;
|
|
|
|
if (!has_active) {
|
|
if (initial_active_count > 0) {
|
|
std.log.info("All active transfers completed successfully", .{});
|
|
}
|
|
break;
|
|
}
|
|
|
|
// Process sessions to allow transfers to complete
|
|
fm.processSessions() catch |err| {
|
|
core.errors.recordAndLogError("processSessions during stop", err);
|
|
break;
|
|
};
|
|
|
|
// Sleep briefly to avoid spinning
|
|
Thread.sleep(p2p.config.library.shutdown_poll_interval_ms * std.time.ns_per_ms);
|
|
}
|
|
|
|
// Check if timeout was reached
|
|
if (std.time.milliTimestamp() >= deadline) {
|
|
const remaining_stats = fm.getStats();
|
|
const remaining = remaining_stats.downloading_sessions + remaining_stats.uploading_sessions;
|
|
if (remaining > 0) {
|
|
std.log.warn("Shutdown timeout reached: {} transfers still active, forcing shutdown", .{remaining});
|
|
}
|
|
}
|
|
|
|
// Final cleanup of all sessions
|
|
fm.processSessions() catch |err| {
|
|
core.errors.recordAndLogError("final session cleanup", err);
|
|
};
|
|
}
|
|
|
|
// Stop the node
|
|
if (p2p.node) |node_ptr| {
|
|
node_ptr.stop();
|
|
}
|
|
|
|
// Stop discovery
|
|
if (p2p.discovery_manager) |discovery| {
|
|
discovery.stop();
|
|
}
|
|
|
|
// PERF: Stop piece processing pipeline and verification thread pool
|
|
if (p2p.file_manager) |fm| {
|
|
fm.stopPiecePipeline();
|
|
fm.stopVerificationPool();
|
|
}
|
|
|
|
p2p.running.store(false, .release);
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Stopped;
|
|
p2p.state_mutex.unlock();
|
|
|
|
// Emit stop event
|
|
try p2p.emitEvent(P2PEvent.create(.library_stopped, .library_stopped));
|
|
}
|
|
|
|
/// Shutdown the P2P library completely
|
|
///
|
|
/// This is a more forceful shutdown than `stop()` - it immediately
|
|
/// terminates all operations and connections.
|
|
pub fn shutdownImpl(p2p: *P2P) void {
|
|
if (!p2p.initialized.load(.acquire)) return;
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Stopping;
|
|
p2p.state_mutex.unlock();
|
|
|
|
// Force stop all components
|
|
if (p2p.node) |node_ptr| {
|
|
node_ptr.stop();
|
|
}
|
|
|
|
if (p2p.discovery_manager) |discovery| {
|
|
discovery.stop();
|
|
}
|
|
|
|
p2p.running.store(false, .release);
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Stopped;
|
|
p2p.state_mutex.unlock();
|
|
|
|
// Clear event queue
|
|
p2p.event_mutex.lock();
|
|
defer p2p.event_mutex.unlock();
|
|
p2p.event_queue.clearRetainingCapacity();
|
|
|
|
// Emit final event (ignore errors during shutdown)
|
|
p2p.emitEvent(P2PEvent.create(.library_stopped, .library_stopped)) catch |err| {
|
|
std.log.warn("Failed to emit shutdown event: {}", .{err});
|
|
};
|
|
}
|
|
|
|
// ============================================================================
|
|
// Maintenance Mode Functions
|
|
// ============================================================================
|
|
|
|
/// Enter maintenance mode
|
|
pub fn enterMaintenanceModeImpl(p2p: *P2P) Error!void {
|
|
if (!p2p.running.load(.acquire)) return Error.InvalidState;
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Maintenance;
|
|
p2p.state_mutex.unlock();
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_error, .{ .library_error = .{
|
|
.err = Error.InvalidState,
|
|
.message = "Entered maintenance mode",
|
|
} }));
|
|
}
|
|
|
|
/// Exit maintenance mode
|
|
pub fn exitMaintenanceModeImpl(p2p: *P2P) Error!void {
|
|
p2p.state_mutex.lock();
|
|
const current_state = p2p.state;
|
|
if (current_state != .Maintenance) {
|
|
p2p.state_mutex.unlock();
|
|
return Error.InvalidState;
|
|
}
|
|
p2p.state = .Running;
|
|
p2p.state_mutex.unlock();
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_started, .library_started));
|
|
}
|
|
|
|
// ============================================================================
|
|
// Error State Functions
|
|
// ============================================================================
|
|
|
|
/// Set error state
|
|
pub fn setErrorStateImpl(p2p: *P2P, err: Error, message: []const u8) Error!void {
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Error;
|
|
p2p.state_mutex.unlock();
|
|
|
|
p2p.stats.last_error = err;
|
|
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_error, .{ .library_error = .{
|
|
.err = err,
|
|
.message = message,
|
|
} }));
|
|
}
|
|
|
|
/// Recover from error state
|
|
pub fn recoverFromErrorImpl(p2p: *P2P) Error!void {
|
|
p2p.state_mutex.lock();
|
|
const current_state = p2p.state;
|
|
if (current_state != .Error) {
|
|
p2p.state_mutex.unlock();
|
|
return Error.InvalidState;
|
|
}
|
|
|
|
if (!p2p.initialized.load(.acquire)) {
|
|
p2p.state_mutex.unlock();
|
|
return Error.InvalidState;
|
|
}
|
|
|
|
p2p.state = .Initialized;
|
|
p2p.state_mutex.unlock();
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_initialized, .library_initialized));
|
|
}
|
|
|
|
// ============================================================================
|
|
// Configuration Functions
|
|
// ============================================================================
|
|
|
|
/// Update library configuration
|
|
pub fn updateConfigImpl(p2p: *P2P, new_config: P2PConfig) Error!void {
|
|
if (!std.mem.eql(u8, std.mem.asBytes(&p2p.config.file_sharing), std.mem.asBytes(&new_config.file_sharing))) {
|
|
if (p2p.file_manager) |manager| {
|
|
manager.setSelectionStrategy(new_config.file_sharing.selection_strategy);
|
|
manager.updateBandwidthLimits(new_config.file_sharing.max_bandwidth_download, new_config.file_sharing.max_bandwidth_upload);
|
|
manager.setFeatures(new_config.file_sharing.enable_upload, new_config.file_sharing.enable_download);
|
|
}
|
|
}
|
|
|
|
p2p.config = new_config;
|
|
}
|
|
|
|
// ============================================================================
|
|
// Internal Helper Functions
|
|
// ============================================================================
|
|
|
|
/// Connect to bootstrap nodes
|
|
pub fn connectToBootstrapNodesImpl(p2p: *P2P) void {
|
|
// First, connect to legacy bootstrap nodes
|
|
for (p2p.config.network.bootstrap_nodes) |node_addr_str| {
|
|
std.log.warn("THR-M2: Using unpinned bootstrap node {s} - consider using pinned_bootstrap_nodes", .{node_addr_str});
|
|
|
|
const address = Address.parse(node_addr_str) catch |err| {
|
|
std.log.warn("Invalid bootstrap address {s}: {}", .{ node_addr_str, err });
|
|
continue;
|
|
};
|
|
|
|
const peer_id = p2p.connectToPeer(address) catch |err| {
|
|
std.log.warn("Failed to connect to bootstrap {s}: {}", .{ node_addr_str, err });
|
|
continue;
|
|
};
|
|
|
|
std.log.info("Connected to bootstrap node {s}, peer_id={}", .{ node_addr_str, peer_id });
|
|
}
|
|
|
|
// Connect to pinned bootstrap nodes
|
|
for (p2p.config.network.pinned_bootstrap_nodes) |bootstrap_node| {
|
|
const address = Address.parse(bootstrap_node.address) catch |err| {
|
|
std.log.warn("Invalid pinned bootstrap address {s}: {}", .{ bootstrap_node.address, err });
|
|
continue;
|
|
};
|
|
|
|
const peer_id = p2p.connectToPeer(address) catch |err| {
|
|
std.log.warn("Failed to connect to pinned bootstrap {s}: {}", .{ bootstrap_node.address, err });
|
|
continue;
|
|
};
|
|
|
|
if (bootstrap_node.hasKeyPinning()) {
|
|
std.log.info("THR-M2: Key pinning enabled for bootstrap {s}", .{bootstrap_node.address});
|
|
}
|
|
|
|
std.log.info("Connected to pinned bootstrap node {s}, peer_id={}", .{ bootstrap_node.address, peer_id });
|
|
}
|
|
}
|
|
|
|
/// Perform health checks on all connections
|
|
pub fn performHealthChecksImpl(p2p: *P2P) Error!void {
|
|
var dead_peers: std.ArrayListUnmanaged(PeerId) = .{};
|
|
defer dead_peers.deinit(p2p.allocator);
|
|
|
|
p2p.peer_connections_mutex.lock();
|
|
var iter = p2p.peer_connections.iterator();
|
|
while (iter.next()) |entry| {
|
|
const peer_id = entry.key_ptr.*;
|
|
const peer_conn = entry.value_ptr.*;
|
|
const socket = peer_conn.socket;
|
|
|
|
if (socket.state == .closed) {
|
|
std.log.debug("Health check: peer {x} has closed socket, marking dead", .{peer_id.bytes[0..8].*});
|
|
dead_peers.append(p2p.allocator, peer_id) catch |err| {
|
|
std.log.warn("Failed to track dead peer during health check (closed socket): {}", .{err});
|
|
continue;
|
|
};
|
|
continue;
|
|
}
|
|
|
|
const idle_ms = std.time.milliTimestamp() - socket.stats.getLastActivity();
|
|
if (idle_ms > p2p.config.network.idle_timeout_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| {
|
|
std.log.warn("Failed to track idle peer during health check (idle: {}ms): {}", .{ idle_ms, err });
|
|
continue;
|
|
};
|
|
}
|
|
}
|
|
p2p.peer_connections_mutex.unlock();
|
|
|
|
for (dead_peers.items) |peer_id| {
|
|
p2p.disconnectPeer(peer_id) catch |err| {
|
|
std.log.warn("Failed to disconnect dead peer during health check: {}", .{err});
|
|
};
|
|
}
|
|
}
|
|
|
|
/// Check error rate and transition to maintenance/error state if needed
|
|
pub fn checkErrorRateAndTransitionStateImpl(p2p: *P2P) Error!void {
|
|
const now = std.time.milliTimestamp();
|
|
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) {
|
|
p2p.error_window_start = now;
|
|
_ = p2p.errors_in_window.swap(0, .monotonic);
|
|
return;
|
|
}
|
|
|
|
const errors = p2p.errors_in_window.load(.monotonic);
|
|
const threshold = p2p.config.library.error_threshold;
|
|
const critical_threshold = threshold * 3;
|
|
|
|
p2p.state_mutex.lock();
|
|
const current_state = p2p.state;
|
|
p2p.state_mutex.unlock();
|
|
|
|
if (errors >= critical_threshold and current_state != .Error) {
|
|
std.log.err("CRITICAL: Error rate catastrophic: {} errors in last {}ms (critical threshold: {}), entering error state", .{ errors, window_duration_ms, critical_threshold });
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Error;
|
|
p2p.state_mutex.unlock();
|
|
|
|
p2p.stats.last_error = Error.ResourceExhausted;
|
|
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_error, .{ .library_error = .{
|
|
.err = Error.ResourceExhausted,
|
|
.message = "Critical error state: catastrophic error rate",
|
|
} }));
|
|
|
|
_ = p2p.errors_in_window.swap(0, .monotonic);
|
|
p2p.error_window_start = now;
|
|
} else if (errors >= threshold and current_state == .Running) {
|
|
std.log.warn("Error threshold exceeded: {} errors in last {}ms (threshold: {}), entering maintenance mode", .{ errors, window_duration_ms, threshold });
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Maintenance;
|
|
p2p.state_mutex.unlock();
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_error, .{ .library_error = .{
|
|
.err = Error.ResourceExhausted,
|
|
.message = "Automatic maintenance mode: error rate too high",
|
|
} }));
|
|
|
|
_ = p2p.errors_in_window.swap(0, .monotonic);
|
|
p2p.error_window_start = now;
|
|
} else if (errors < (threshold / 2) and current_state == .Maintenance) {
|
|
std.log.info("Error rate normalized: {} errors in last minute, recovering from maintenance mode", .{errors});
|
|
|
|
p2p.state_mutex.lock();
|
|
p2p.state = .Running;
|
|
p2p.state_mutex.unlock();
|
|
|
|
try p2p.emitEvent(P2PEvent.create(.library_started, .library_started));
|
|
|
|
_ = p2p.errors_in_window.swap(0, .monotonic);
|
|
p2p.error_window_start = now;
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// DHT Handler Registration
|
|
// ============================================================================
|
|
|
|
/// Register DHT message handlers with the handler registry
|
|
fn registerDhtHandlers(registry: *HandlerRegistry) !void {
|
|
const context = registry.getContext();
|
|
const message = protocol.message;
|
|
|
|
// DHT FIND_NODE handler
|
|
const find_node_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr: *protocol.handler.HandlerContext = @ptrCast(@alignCast(ctx));
|
|
try handler_impl.handleDhtFindNode(msg.dht_find_node, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_node,
|
|
);
|
|
|
|
// DHT FIND_NODE response handler
|
|
const find_node_response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr: *protocol.handler.HandlerContext = @ptrCast(@alignCast(ctx));
|
|
try handler_impl.handleDhtFindNodeResponse(msg.dht_find_node_response, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_node_response,
|
|
);
|
|
|
|
// DHT STORE handler
|
|
const store_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr: *protocol.handler.HandlerContext = @ptrCast(@alignCast(ctx));
|
|
try handler_impl.handleDhtStore(msg.dht_store, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_store,
|
|
);
|
|
|
|
// DHT STORE response handler
|
|
const store_response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr: *protocol.handler.HandlerContext = @ptrCast(@alignCast(ctx));
|
|
try handler_impl.handleDhtStoreResponse(msg.dht_store_response, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_store_response,
|
|
);
|
|
|
|
// DHT FIND_VALUE handler
|
|
const find_value_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr: *protocol.handler.HandlerContext = @ptrCast(@alignCast(ctx));
|
|
try handler_impl.handleDhtFindValue(msg.dht_find_value, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_value,
|
|
);
|
|
|
|
// DHT FIND_VALUE response handler
|
|
const find_value_response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr: *protocol.handler.HandlerContext = @ptrCast(@alignCast(ctx));
|
|
try handler_impl.handleDhtFindValueResponse(msg.dht_find_value_response, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_value_response,
|
|
);
|
|
|
|
// Register all DHT handlers
|
|
try registry.registerHandler(.dht_find_node, find_node_handler);
|
|
try registry.registerHandler(.dht_find_node_response, find_node_response_handler);
|
|
try registry.registerHandler(.dht_store, store_handler);
|
|
try registry.registerHandler(.dht_store_response, store_response_handler);
|
|
try registry.registerHandler(.dht_find_value, find_value_handler);
|
|
try registry.registerHandler(.dht_find_value_response, find_value_response_handler);
|
|
|
|
std.log.debug("DHT handlers registered successfully", .{});
|
|
}
|