This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

310
src/p2p/circuit_breaker.zig Normal file
View File

@@ -0,0 +1,310 @@
//! Circuit Breaker Pattern Implementation
//!
//! Implements the circuit breaker pattern to prevent cascading failures
//! in distributed systems. The breaker transitions through three states:
//! - Closed: Normal operation, requests pass through
//! - Open: Failures exceeded threshold, requests are rejected
//! - HalfOpen: Testing if service has recovered
const std = @import("std");
/// Circuit breaker to prevent cascading failures
///
/// IMP-2 FIX: Implements the circuit breaker pattern with three states.
///
/// THR-CRIT-1 FIX: All mutable state is now protected by a mutex to prevent
/// race conditions when accessed from multiple threads.
pub const CircuitBreaker = struct {
// THR-CRIT-1 FIX: Mutex to protect all mutable state
mutex: std.Thread.Mutex = .{},
state: State = .closed,
failure_count: u32 = 0,
success_count: u32 = 0,
last_failure_time: i64 = 0,
last_state_change: i64 = 0,
// Configuration (immutable after init, no mutex needed for reads)
failure_threshold: u32 = 5, // Number of failures before opening
success_threshold: u32 = 3, // Successes needed to close from half-open
timeout_ms: i64 = 30000, // Time before trying half-open (30 seconds)
pub const State = enum {
closed,
open,
half_open,
};
pub fn init(failure_threshold: u32, success_threshold: u32, timeout_ms: i64) CircuitBreaker {
return .{
.failure_threshold = failure_threshold,
.success_threshold = success_threshold,
.timeout_ms = timeout_ms,
};
}
/// Check if a request should be allowed (thread-safe)
pub fn allowRequest(self: *CircuitBreaker) bool {
self.mutex.lock();
defer self.mutex.unlock();
const now = std.time.milliTimestamp();
switch (self.state) {
.closed => return true,
.open => {
// Check if timeout has passed
if (now - self.last_state_change >= self.timeout_ms) {
self.state = .half_open;
self.last_state_change = now;
self.success_count = 0;
std.log.info("CircuitBreaker: Transitioning to half-open state", .{});
return true; // Allow one test request
}
return false;
},
.half_open => {
// In half-open, we allow limited requests to test
return true;
},
}
}
/// Record a successful operation (thread-safe)
pub fn recordSuccess(self: *CircuitBreaker) void {
self.mutex.lock();
defer self.mutex.unlock();
const now = std.time.milliTimestamp();
switch (self.state) {
.closed => {
// Reset failure count on success
self.failure_count = 0;
},
.half_open => {
self.success_count += 1;
if (self.success_count >= self.success_threshold) {
self.state = .closed;
self.last_state_change = now;
self.failure_count = 0;
std.log.info("CircuitBreaker: Service recovered, transitioning to closed state", .{});
}
},
.open => {
// Shouldn't happen, but handle gracefully
},
}
}
/// Record a failed operation (thread-safe)
pub fn recordFailure(self: *CircuitBreaker) void {
self.mutex.lock();
defer self.mutex.unlock();
const now = std.time.milliTimestamp();
self.last_failure_time = now;
switch (self.state) {
.closed => {
self.failure_count += 1;
if (self.failure_count >= self.failure_threshold) {
self.state = .open;
self.last_state_change = now;
std.log.warn("CircuitBreaker: Failure threshold reached, transitioning to open state", .{});
}
},
.half_open => {
// Single failure in half-open returns to open
self.state = .open;
self.last_state_change = now;
std.log.warn("CircuitBreaker: Failure in half-open, returning to open state", .{});
},
.open => {
// Already open, nothing to do
},
}
}
/// Get current state (thread-safe)
pub fn getState(self: *CircuitBreaker) State {
self.mutex.lock();
defer self.mutex.unlock();
return self.state;
}
/// Reset the circuit breaker (thread-safe)
pub fn reset(self: *CircuitBreaker) void {
self.mutex.lock();
defer self.mutex.unlock();
self.state = .closed;
self.failure_count = 0;
self.success_count = 0;
self.last_failure_time = 0;
self.last_state_change = std.time.milliTimestamp();
}
};
// Tests
test "CircuitBreaker: basic functionality" {
var cb = CircuitBreaker.init(3, 2, 100); // 3 failures to open, 2 successes to close, 100ms timeout
// Initially closed, should allow requests
try std.testing.expect(cb.allowRequest());
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
// Record success resets failure count
cb.recordSuccess();
try std.testing.expectEqual(@as(u32, 0), cb.failure_count);
// Record failures
cb.recordFailure();
try std.testing.expectEqual(@as(u32, 1), cb.failure_count);
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
cb.recordFailure();
cb.recordFailure(); // Third failure triggers open
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
try std.testing.expect(!cb.allowRequest()); // Requests blocked when open
}
test "CircuitBreaker: half-open recovery" {
var cb = CircuitBreaker.init(2, 2, 1); // Very short timeout for test
// Trigger open state
cb.recordFailure();
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
// Wait for timeout
std.Thread.sleep(5 * std.time.ns_per_ms);
// Should transition to half-open and allow request
try std.testing.expect(cb.allowRequest());
try std.testing.expectEqual(CircuitBreaker.State.half_open, cb.getState());
// Success in half-open
cb.recordSuccess();
cb.recordSuccess(); // Second success should close
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
}
test "CircuitBreaker: failure in half-open returns to open" {
var cb = CircuitBreaker.init(2, 2, 1);
// Trigger open state
cb.recordFailure();
cb.recordFailure();
// Wait for timeout and transition to half-open
std.Thread.sleep(5 * std.time.ns_per_ms);
_ = cb.allowRequest();
try std.testing.expectEqual(CircuitBreaker.State.half_open, cb.getState());
// Single failure returns to open
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
}
test "CircuitBreaker: reset" {
var cb = CircuitBreaker.init(2, 2, 1000);
// Put into open state
cb.recordFailure();
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
// Reset should return to closed
cb.reset();
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
try std.testing.expectEqual(@as(u32, 0), cb.failure_count);
try std.testing.expectEqual(@as(u32, 0), cb.success_count);
}
test "CircuitBreaker: initial state is closed" {
var breaker = CircuitBreaker{};
// Initial state should be closed
try std.testing.expectEqual(CircuitBreaker.State.closed, breaker.getState());
}
test "CircuitBreaker: success resets state" {
var breaker = CircuitBreaker{};
// Record some failures
breaker.recordFailure();
breaker.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.closed, breaker.getState());
// Success should keep closed state
breaker.recordSuccess();
try std.testing.expectEqual(CircuitBreaker.State.closed, breaker.getState());
}
test "CircuitBreaker: allowRequest returns true in half-open" {
var cb = CircuitBreaker.init(2, 2, 1); // 1ms timeout
// Trigger open state
cb.recordFailure();
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
// Wait for timeout to allow transition to half-open
std.Thread.sleep(5 * std.time.ns_per_ms);
// allowRequest should return true and transition to half-open
const allowed = cb.allowRequest();
try std.testing.expect(allowed);
try std.testing.expectEqual(CircuitBreaker.State.half_open, cb.getState());
// Second call in half-open should also return true (allowing test request)
const second_allowed = cb.allowRequest();
try std.testing.expect(second_allowed);
}
test "CircuitBreaker: multiple failures reaching threshold" {
var cb = CircuitBreaker.init(3, 2, 1000);
// Initial state should be closed
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
try std.testing.expect(cb.allowRequest());
// Record failures up to threshold
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
cb.recordFailure();
// Should be open now
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
try std.testing.expect(!cb.allowRequest());
}
test "CircuitBreaker: success threshold recovery" {
var cb = CircuitBreaker.init(1, 3, 1); // 1ms timeout for fast test
// Open the circuit
cb.recordFailure();
try std.testing.expectEqual(CircuitBreaker.State.open, cb.getState());
// Wait for timeout
std.Thread.sleep(5 * std.time.ns_per_ms);
// First request should be allowed (half-open)
try std.testing.expect(cb.allowRequest());
try std.testing.expectEqual(CircuitBreaker.State.half_open, cb.getState());
// Record successes up to threshold
cb.recordSuccess();
try std.testing.expectEqual(CircuitBreaker.State.half_open, cb.getState());
cb.recordSuccess();
try std.testing.expectEqual(CircuitBreaker.State.half_open, cb.getState());
cb.recordSuccess();
// Should be closed now
try std.testing.expectEqual(CircuitBreaker.State.closed, cb.getState());
}

399
src/p2p/config.zig Normal file
View File

@@ -0,0 +1,399 @@
//! P2P Configuration Module
//!
//! This module defines all configuration structures for the P2P library,
//! including network, protocol, event, and file sharing configurations.
const std = @import("std");
const core = @import("core");
const network = @import("network");
const files = @import("files");
/// Main configuration for the P2P library
pub const P2PConfig = struct {
/// Library configuration
library: LibraryConfig = .{},
/// Network configuration
network: NetworkConfig = .{},
/// Protocol configuration
protocol: ProtocolConfig = .{},
/// File sharing configuration
file_sharing: FileSharingConfig = .{},
/// Event system configuration
events: EventConfig = .{},
/// Default configuration for most use cases
pub fn default() P2PConfig {
return P2PConfig{};
}
/// Configuration optimized for high performance
pub fn high_performance() P2PConfig {
return P2PConfig{
.library = LibraryConfig{
.max_threads = 8,
.enable_statistics = true,
},
.network = NetworkConfig{
.max_connections = 1000,
.connection_timeout = 30000,
.max_bandwidth = 100 * 1024 * 1024, // 100MB/s
},
.file_sharing = files.manager.FileSharingConfig.high_performance(),
.protocol = ProtocolConfig{
.message_timeout = 5000,
.max_message_size = 2 * 1024 * 1024, // 2MB for large pieces
},
};
}
/// Configuration optimized for low resource usage
pub fn low_resource() P2PConfig {
return P2PConfig{
.library = LibraryConfig{
.max_threads = 2,
.enable_statistics = false,
},
.network = NetworkConfig{
.max_connections = 100,
.connection_timeout = 60000,
.max_bandwidth = 1024 * 1024, // 1MB/s
},
.file_sharing = files.manager.FileSharingConfig.low_bandwidth(),
.protocol = ProtocolConfig{
.message_timeout = 15000,
.max_message_size = 64 * 1024, // 64KB
},
};
}
};
/// Library-level configuration
pub const LibraryConfig = struct {
/// Maximum number of worker threads
max_threads: u16 = 4,
/// Enable comprehensive statistics
enable_statistics: bool = true,
/// Maximum memory usage (bytes)
max_memory: usize = 256 * 1024 * 1024, // 256MB
/// Enable debug logging
debug_logging: bool = false,
/// Auto-start services on library start
auto_start: bool = true,
/// Graceful shutdown timeout in milliseconds (how long to wait for active transfers)
shutdown_timeout_ms: u32 = 30000,
/// Shutdown poll interval in milliseconds (how often to check for active transfers during shutdown)
shutdown_poll_interval_ms: u32 = 100,
/// Maintenance check interval in milliseconds (how often to check error rates)
maintenance_check_interval_ms: u32 = 5000,
/// Error threshold before entering maintenance mode (errors per minute)
error_threshold: u32 = 100,
/// Enable automatic state transitions based on error rates
enable_auto_maintenance: bool = true,
};
/// THR-M2 FIX: Bootstrap node with optional key pinning for MITM protection
/// When a public_key is provided, the node's identity will be verified during connection.
/// This prevents attackers from impersonating bootstrap nodes.
pub const BootstrapNode = struct {
/// Address string (e.g., "192.168.1.100:9999" or "bootstrap.example.com:9999")
address: []const u8,
/// Optional pinned public key (Ed25519, 32 bytes hex-encoded = 64 chars)
/// If provided, connection will fail if node presents a different key
/// Format: 64 hex characters representing the 32-byte Ed25519 public key
pinned_public_key: ?[]const u8 = null,
/// Check if this bootstrap node has key pinning enabled
pub fn hasKeyPinning(self: BootstrapNode) bool {
return self.pinned_public_key != null;
}
/// Verify a presented public key against the pinned key
/// Returns true if no pinning is configured (permissive) or key matches
pub fn verifyPublicKey(self: BootstrapNode, presented_key: [32]u8) bool {
const pinned = self.pinned_public_key orelse return true; // No pinning = accept
if (pinned.len != 64) {
core.log.err("THR-M2: Invalid pinned key length (expected 64 hex chars, got {})", .{pinned.len});
return false;
}
// Decode hex and compare
var expected_key: [32]u8 = undefined;
var i: usize = 0;
while (i < 32) : (i += 1) {
const high = std.fmt.charToDigit(pinned[i * 2], 16) catch return false;
const low = std.fmt.charToDigit(pinned[i * 2 + 1], 16) catch return false;
expected_key[i] = (@as(u8, high) << 4) | @as(u8, low);
}
// Timing-safe comparison for security-critical key verification
if (!std.crypto.timing_safe.eql([32]u8, expected_key, presented_key)) {
core.log.err("SECURITY: Bootstrap key mismatch - possible MITM attack!", .{});
return false;
}
std.log.info("THR-M2: Bootstrap node key verified successfully", .{});
return true;
}
};
/// Network layer configuration
pub const NetworkConfig = struct {
/// Listen port (0 for auto-assign)
listen_port: u16 = 0,
/// Maximum simultaneous connections
max_connections: u32 = 500,
/// Connection timeout in milliseconds
connection_timeout: u32 = 30000,
/// Maximum bandwidth in bytes/second
max_bandwidth: u64 = 10 * 1024 * 1024, // 10MB/s
/// Enable NAT traversal
enable_nat_traversal: bool = true,
/// Bootstrap nodes for initial discovery (legacy, no key pinning)
/// DEPRECATED: Use pinned_bootstrap_nodes for security
bootstrap_nodes: []const []const u8 = &.{},
/// THR-M2 FIX: Bootstrap nodes with optional key pinning
pinned_bootstrap_nodes: []const BootstrapNode = &.{},
/// Health check interval in milliseconds
health_check_interval_ms: i64 = 5000,
/// Idle timeout in milliseconds (connection considered dead after this period of inactivity)
idle_timeout_ms: u32 = 60000,
/// Keepalive interval in milliseconds
keepalive_interval_ms: u32 = 30000,
/// Session cleanup interval in milliseconds (for error rate tracking window)
session_cleanup_interval_ms: u32 = 60000,
/// Enable rate limiting
enable_rate_limiting: bool = true,
/// Message rate limit (messages per second per peer) - from central config
message_rate_limit: u32 = core.limits.defaults.network.message_rate_limit,
/// Message burst size (max messages in burst) - from central config
message_burst_size: u32 = core.limits.defaults.network.message_burst_size,
/// Connection rate limit (new connections per second globally)
connection_rate_limit: u32 = 10,
/// Connection burst size
connection_burst_size: u32 = 5,
/// TURN relay configuration
turn_enabled: bool = true,
/// TURN servers for relay fallback
turn_servers: []const network.nat.TurnServer = &network.nat.DEFAULT_TURN_SERVERS,
/// Timeout before falling back to TURN (milliseconds)
turn_fallback_timeout_ms: u32 = 5000,
/// TURN allocation refresh interval (milliseconds)
turn_refresh_interval_ms: u32 = 300000, // 5 minutes
/// Enable Noise protocol encryption for all connections
enable_noise_encryption: bool = false,
/// Optional static private key for Noise protocol (32 bytes)
/// If null, a random keypair will be generated on init
noise_static_key: ?[32]u8 = null,
/// Enable DoS protection with stateless cookies (WireGuard-style)
/// Disabled by default - enable for production servers exposed to internet
enable_dos_protection: bool = false,
/// DoS protection threshold - connections per second before requiring cookies
dos_cookie_threshold: u32 = network.dos_protection.DEFAULT_COOKIE_THRESHOLD,
/// Key pinning mode for Noise connections
/// - disabled: No key pinning (accept any key)
/// - tofu: Trust On First Use (pin first seen key, detect changes)
/// - strict: Only allow pre-configured known peers
key_pinning_mode: network.key_pinning.PinningMode = .tofu,
/// Maximum number of pinned keys (0 = unlimited)
max_pinned_keys: usize = 10000,
/// Path to save/load pinned keys (null = no persistence)
key_pin_file: ?[]const u8 = null,
/// Enable retry with exponential backoff for failed handshakes
handshake_retry_enabled: bool = true,
/// Maximum number of connection/handshake retry attempts
handshake_max_attempts: u32 = 3,
/// Initial backoff delay in milliseconds
handshake_initial_backoff_ms: u32 = 100,
/// Maximum backoff delay in milliseconds
handshake_max_backoff_ms: u32 = 10000,
/// Backoff multiplier (e.g., 2.0 = double each time)
handshake_backoff_multiplier: f32 = 2.0,
};
/// Protocol configuration
pub const ProtocolConfig = struct {
/// Message timeout in milliseconds
message_timeout: u32 = 10000,
/// Maximum message size (2MB for large piece transfers)
max_message_size: u32 = 2 * 1024 * 1024, // 2MB
/// Enable message encryption
enable_encryption: bool = true,
/// Protocol version
protocol_version: u16 = 1,
/// Maximum hops for routing
max_hops: u8 = 16,
/// Replay protection cleanup interval in seconds
replay_protection_cleanup_interval: i64 = 60,
};
/// File sharing configuration type (alias for existing component)
pub const FileSharingConfig = files.manager.FileSharingConfig;
/// Event system configuration
pub const EventConfig = struct {
/// Maximum event queue size
max_event_queue: usize = 10000,
/// Enable event logging
enable_logging: bool = true,
/// Event processing interval in milliseconds
processing_interval: u32 = 100,
};
// Tests
test "BootstrapNode: key pinning" {
const node_no_key = BootstrapNode{
.address = "127.0.0.1:9999",
.pinned_public_key = null,
};
try std.testing.expect(!node_no_key.hasKeyPinning());
// Hex-encoded 32-byte key (64 hex chars)
const pinned_key_hex = "abababababababababababababababababababababababababababababababab";
const node_with_key = BootstrapNode{
.address = "127.0.0.1:9999",
.pinned_public_key = pinned_key_hex,
};
try std.testing.expect(node_with_key.hasKeyPinning());
// Verify matching key
const matching_key = [_]u8{0xAB} ** 32;
try std.testing.expect(node_with_key.verifyPublicKey(matching_key));
// Verify non-matching key
const wrong_key = [_]u8{0xCD} ** 32;
try std.testing.expect(!node_with_key.verifyPublicKey(wrong_key));
// Node without pinning accepts any key
try std.testing.expect(node_no_key.verifyPublicKey(wrong_key));
}
test "BootstrapNode: hasKeyPinning" {
// Node without key pinning
const node_no_key = BootstrapNode{
.address = "127.0.0.1:9999",
.pinned_public_key = null,
};
try std.testing.expect(!node_no_key.hasKeyPinning());
// Node with key pinning
const node_with_key = BootstrapNode{
.address = "127.0.0.1:9999",
.pinned_public_key = "abababababababababababababababababababababababababababababababab",
};
try std.testing.expect(node_with_key.hasKeyPinning());
}
test "BootstrapNode: verifyPublicKey with invalid hex characters" {
// Key with invalid hex characters
const node_invalid_hex = BootstrapNode{
.address = "127.0.0.1:9999",
.pinned_public_key = "gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg", // 'g' is not hex
};
const any_key = [_]u8{0x00} ** 32;
// Should return false due to invalid hex
try std.testing.expect(!node_invalid_hex.verifyPublicKey(any_key));
}
test "NetworkConfig: defaults" {
const config = NetworkConfig{};
try std.testing.expect(config.max_connections > 0);
try std.testing.expect(config.connection_timeout > 0);
try std.testing.expect(config.max_bandwidth > 0);
}
test "NetworkConfig: custom values" {
const config = NetworkConfig{
.max_connections = 500,
.connection_timeout = 15000,
.enable_rate_limiting = false,
.enable_dos_protection = false,
.enable_nat_traversal = false,
.enable_noise_encryption = true,
.key_pinning_mode = .strict,
};
try std.testing.expectEqual(@as(u32, 500), config.max_connections);
try std.testing.expectEqual(@as(u32, 15000), config.connection_timeout);
try std.testing.expect(!config.enable_rate_limiting);
try std.testing.expectEqual(network.key_pinning.PinningMode.strict, config.key_pinning_mode);
}
test "ProtocolConfig: defaults" {
const config = ProtocolConfig{};
try std.testing.expect(config.message_timeout > 0);
try std.testing.expect(config.max_message_size > 0);
}
test "ProtocolConfig: custom values" {
const config = ProtocolConfig{
.message_timeout = 20000,
.max_message_size = 4 * 1024 * 1024,
.enable_encryption = false,
.protocol_version = 2,
.max_hops = 32,
.replay_protection_cleanup_interval = 120,
};
try std.testing.expectEqual(@as(u32, 20000), config.message_timeout);
try std.testing.expectEqual(@as(u16, 2), config.protocol_version);
try std.testing.expectEqual(@as(u8, 32), config.max_hops);
try std.testing.expect(!config.enable_encryption);
}
test "EventConfig: defaults" {
const config = EventConfig{};
try std.testing.expect(config.max_event_queue > 0);
}
test "EventConfig: custom values" {
const config = EventConfig{
.max_event_queue = 5000,
.enable_logging = false,
.processing_interval = 50,
};
try std.testing.expectEqual(@as(usize, 5000), config.max_event_queue);
try std.testing.expect(!config.enable_logging);
try std.testing.expectEqual(@as(u32, 50), config.processing_interval);
}
test "FileSharingConfig: defaults" {
const config = FileSharingConfig{};
try std.testing.expect(config.max_concurrent_downloads > 0);
}
test "LibraryConfig: defaults" {
const config = LibraryConfig{};
try std.testing.expect(config.max_threads > 0);
try std.testing.expect(config.max_memory > 0);
try std.testing.expect(config.shutdown_timeout_ms > 0);
try std.testing.expect(config.maintenance_check_interval_ms > 0);
try std.testing.expect(config.error_threshold > 0);
}
test "P2PConfig: high_performance preset" {
const config = P2PConfig.high_performance();
// High performance should have larger limits
// CASCADE PERF: High performance preset uses 256 concurrent transfers
try std.testing.expect(config.network.max_connections >= 1000);
try std.testing.expectEqual(@as(usize, 256), config.file_sharing.max_concurrent_downloads);
}
test "P2PConfig: low_resource preset" {
const config = P2PConfig.low_resource();
// Low resource should have smaller limits (uses low_bandwidth preset)
try std.testing.expectEqual(@as(u32, 100), config.network.max_connections);
try std.testing.expectEqual(@as(usize, 2), config.file_sharing.max_concurrent_downloads);
}
test "network.key_pinning.PinningMode: all values" {
try std.testing.expect(network.key_pinning.PinningMode.disabled != network.key_pinning.PinningMode.tofu);
try std.testing.expect(network.key_pinning.PinningMode.tofu != network.key_pinning.PinningMode.strict);
try std.testing.expect(network.key_pinning.PinningMode.strict != network.key_pinning.PinningMode.disabled);
}

1042
src/p2p/connection.zig Normal file

File diff suppressed because it is too large Load Diff

211
src/p2p/dht.zig Normal file
View File

@@ -0,0 +1,211 @@
//! DHT (Distributed Hash Table) Operations Module
//!
//! This module contains implementations for P2P DHT methods as free functions
//! that take `*P2P` as the first parameter. These functions handle DHT routing
//! table management, value storage/retrieval, and network message propagation.
const std = @import("std");
// Core components (via module import)
const core = @import("core");
const Error = core.errors.Error;
// Network components (via module import)
const network = @import("network");
const PeerId = network.peer.PeerId;
const Address = core.Address;
// Protocol components (via module import)
const protocol = @import("protocol");
// Import P2P type from sibling module
const P2P = @import("p2p.zig").P2P;
// =========================================================================
// DHT (Distributed Hash Table) API
// =========================================================================
/// Get the number of peers in the DHT routing table
pub fn getDhtPeerCountImpl(p2p: *P2P) usize {
const rt = p2p.routing_table orelse return 0;
return rt.total_peers.load(.monotonic);
}
/// Store a value in the DHT
pub fn dhtStoreImpl(p2p: *P2P, key: [32]u8, value: []const u8, ttl: u32) Error!void {
const dht = p2p.dht_coordinator orelse return Error.InvalidState;
dht.store(key, value, ttl) catch |err| {
std.log.err("DHT store failed: {}", .{err});
return Error.InternalError;
};
}
/// Find a value in the DHT
pub fn dhtFindValueImpl(p2p: *P2P, key: [32]u8) Error!?[]u8 {
const dht = p2p.dht_coordinator orelse return Error.InvalidState;
return dht.findValue(key) catch |err| {
std.log.err("DHT findValue failed: {}", .{err});
return Error.InternalError;
};
}
/// Find nodes close to a target ID
pub fn dhtFindNodeImpl(p2p: *P2P, target_id: [32]u8) Error![]const [32]u8 {
const dht = p2p.dht_coordinator orelse return Error.InvalidState;
return dht.findNode(target_id) catch |err| {
std.log.err("DHT findNode failed: {}", .{err});
return Error.InternalError;
};
}
/// Get the local DHT node ID
pub fn getDhtLocalIdImpl(p2p: *P2P) ?[32]u8 {
const rt = p2p.routing_table orelse return null;
return rt.local_id.bytes;
}
/// Register a mapping from DHT node ID to connection peer ID
pub fn registerDhtNodeIdImpl(p2p: *P2P, node_id: [32]u8, connection_peer_id: PeerId) Error!void {
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
p2p.dht_node_to_peer.put(node_id, connection_peer_id) catch return Error.OutOfMemory;
std.log.info("Manually registered DHT node ID mapping: {x} -> peer {x}", .{ node_id[0..8].*, connection_peer_id.bytes[0..8].* });
}
/// Add a peer to the DHT routing table
pub fn dhtAddPeerImpl(p2p: *P2P, peer_id: [32]u8, address: Address) Error!void {
const rt = p2p.routing_table orelse return Error.InvalidState;
const peer_id_struct = PeerId{ .bytes = peer_id };
const peer = p2p.allocator.create(network.peer.Peer) catch return Error.OutOfMemory;
peer.* = network.peer.Peer.init(peer_id_struct, address);
const position = p2p.allocator.create(network.topology.NodePosition) catch {
p2p.allocator.destroy(peer);
return Error.OutOfMemory;
};
position.* = network.topology.NodePosition.init(p2p.allocator, peer_id_struct);
rt.addPeer(peer, position) catch |err| {
p2p.allocator.destroy(peer);
position.deinit();
p2p.allocator.destroy(position);
std.log.warn("Failed to add peer to DHT routing table: {}", .{err});
return Error.InternalError;
};
position.deinit();
p2p.allocator.destroy(position);
p2p.allocator.destroy(peer);
}
/// Create DHT network sender for DHT message propagation
pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
const DhtSendContext = struct {
fn sendFindNode(peer_id: network.dht.NodeId, msg: network.dht.DhtFindNode, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
const proto_msg = protocol.message.Message{
.dht_find_node = protocol.message.DhtFindNode{
.request_id = msg.request_id,
.target_id = msg.target_id,
.sender_id = msg.sender_id,
},
};
return sendDhtMessageImpl(p2p_ptr, peer_id, proto_msg);
}
fn sendStore(peer_id: network.dht.NodeId, msg: network.dht.DhtStore, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
const proto_msg = protocol.message.Message{
.dht_store = protocol.message.DhtStore{
.request_id = msg.request_id,
.key = msg.key,
.value = msg.value,
.ttl = msg.ttl,
.sender_id = msg.sender_id,
},
};
return sendDhtMessageImpl(p2p_ptr, peer_id, proto_msg);
}
fn sendFindValue(peer_id: network.dht.NodeId, msg: network.dht.DhtFindValue, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
const proto_msg = protocol.message.Message{
.dht_find_value = protocol.message.DhtFindValue{
.request_id = msg.request_id,
.key = msg.key,
.sender_id = msg.sender_id,
},
};
return sendDhtMessageImpl(p2p_ptr, peer_id, proto_msg);
}
};
return .{
.context = p2p,
.send_find_node = DhtSendContext.sendFindNode,
.send_store = DhtSendContext.sendStore,
.send_find_value = DhtSendContext.sendFindValue,
};
}
/// Internal helper to send a DHT protocol message to a peer
pub fn sendDhtMessageImpl(p2p: *P2P, dht_node_id: [32]u8, msg: protocol.message.Message) bool {
const connection_peer_id: PeerId = blk: {
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
break :blk p2p.dht_node_to_peer.get(dht_node_id) orelse {
std.log.warn("DHT: No connection peer ID found for node ID {x}", .{dht_node_id[0..8].*});
return false;
};
};
var temp_serializer = protocol.serializer.MessageSerializer.initInsecureForTesting(p2p.allocator);
const payload_size = temp_serializer.getPayloadSizePublic(msg);
const header_overhead: usize = 256;
const required_size = std.math.add(usize, payload_size, header_overhead) catch {
std.log.warn("DHT: Buffer size overflow calculating message size", .{});
return false;
};
const buffer_size = @min(required_size, protocol.serializer.Limits.MAX_MESSAGE_SIZE);
const buffer = p2p.allocator.alloc(u8, buffer_size) catch {
std.log.warn("DHT: Failed to allocate buffer for message (size={})", .{buffer_size});
return false;
};
defer p2p.allocator.free(buffer);
const len = temp_serializer.serialize(msg, buffer) catch |err| {
std.log.warn("DHT: Failed to serialize message: {}", .{err});
return false;
};
if (len > std.math.maxInt(u32)) {
std.log.warn("DHT: Message too large (len={})", .{len});
return false;
}
const msg_len: u32 = @intCast(len);
var header: [4]u8 = undefined;
std.mem.writeInt(u32, &header, msg_len, .big);
const segments = [_][]const u8{ &header, buffer[0..len] };
const result = p2p.sendSegmentsToPeerAtomic(connection_peer_id, &segments) catch |err| {
std.log.warn("DHT: sendSegmentsToPeerAtomic error: {}", .{err});
return false;
};
if (result) {
std.log.debug("DHT: Sent message to node {x} (connection peer {x})", .{ dht_node_id[0..8].*, connection_peer_id.bytes[0..8].* });
} else {
std.log.warn("DHT: Connection peer not found for node {x}", .{dht_node_id[0..8].*});
}
return result;
}

158
src/p2p/event_handling.zig Normal file
View File

@@ -0,0 +1,158 @@
//! P2P Event Handling Implementation
//!
//! This module contains implementations for P2P event processing methods
//! as free functions that take `*P2P` as the first parameter.
//!
//! Functions included:
//! - registerCallbackImpl: Register event callback
//! - unregisterCallbackImpl: Unregister event callback
//! - getEventCountImpl: Get event queue size
//! - getNextEventImpl: Get next event from queue
//! - processNextEventImpl: Process next event
//! - processAllEventsImpl: Process all pending events
//! - getStatsImpl: Get P2P statistics
//! - isOperationalImpl: Check if operational
//! - getStateImpl: Get current state
const std = @import("std");
// Core components
const core = @import("core");
const Error = core.errors.Error;
// Import P2P type
const P2P = @import("p2p.zig").P2P;
// Import sibling types
const events = @import("events.zig");
const P2PEvent = events.P2PEvent;
const EventCallback = events.EventCallback;
const UserContext = events.UserContext;
const stats = @import("stats.zig");
const P2PStats = stats.P2PStats;
const types = @import("types.zig");
const P2PState = types.P2PState;
/// Register an event callback
pub fn registerCallbackImpl(p2p: *P2P, callback: EventCallback, context_data: ?*anyopaque) Error!void {
const user_context = UserContext{
.callback = callback,
.context_data = context_data,
};
p2p.callbacks_mutex.lock();
defer p2p.callbacks_mutex.unlock();
p2p.user_contexts.append(p2p.allocator, user_context) catch return Error.OutOfMemory;
}
/// Unregister an event callback
pub fn unregisterCallbackImpl(p2p: *P2P, callback: EventCallback) Error!void {
p2p.callbacks_mutex.lock();
defer p2p.callbacks_mutex.unlock();
var i: usize = 0;
while (i < p2p.user_contexts.items.len) {
if (p2p.user_contexts.items[i].callback == callback) {
_ = p2p.user_contexts.orderedRemove(i);
} else {
i += 1;
}
}
}
/// Get the number of events in the queue
pub fn getEventCountImpl(p2p: *P2P) usize {
p2p.event_mutex.lock();
defer p2p.event_mutex.unlock();
return p2p.event_queue.items.len;
}
/// Get the next event from the queue
pub fn getNextEventImpl(p2p: *P2P) ?P2PEvent {
p2p.event_mutex.lock();
defer p2p.event_mutex.unlock();
if (p2p.event_queue.items.len == 0) return null;
return p2p.event_queue.orderedRemove(0);
}
/// Process the next event
pub fn processNextEventImpl(p2p: *P2P) bool {
var evt: P2PEvent = undefined;
{
p2p.event_mutex.lock();
defer p2p.event_mutex.unlock();
if (p2p.event_queue.items.len == 0) {
return false;
}
evt = p2p.event_queue.orderedRemove(0);
}
defer evt.deinit();
var callbacks_copy: [64]UserContext = undefined;
var callback_count: usize = 0;
{
p2p.callbacks_mutex.lock();
defer p2p.callbacks_mutex.unlock();
callback_count = @min(p2p.user_contexts.items.len, 64);
for (p2p.user_contexts.items[0..callback_count], 0..) |context, i| {
callbacks_copy[i] = context;
}
}
for (callbacks_copy[0..callback_count]) |context| {
context.callback(evt);
}
_ = p2p.stats.events_processed.fetchAdd(1, .monotonic);
return true;
}
/// Process all pending events
pub fn processAllEventsImpl(p2p: *P2P) usize {
var processed: usize = 0;
while (processNextEventImpl(p2p)) {
processed += 1;
}
return processed;
}
/// Get current library statistics
pub fn getStatsImpl(p2p: *P2P) P2PStats {
if (p2p.file_manager) |manager| {
const file_stats = manager.getStats();
const max_u32: usize = std.math.maxInt(u32);
p2p.stats.active_downloads.store(@intCast(@min(file_stats.downloading_sessions, max_u32)), .monotonic);
p2p.stats.active_uploads.store(@intCast(@min(file_stats.uploading_sessions, max_u32)), .monotonic);
p2p.stats.total_downloaded.store(file_stats.total_downloaded, .monotonic);
p2p.stats.total_uploaded.store(file_stats.total_uploaded, .monotonic);
}
p2p.stats.event_queue_size = getEventCountImpl(p2p);
p2p.state_mutex.lock();
p2p.stats.state = p2p.state;
p2p.state_mutex.unlock();
return p2p.stats;
}
/// Check if the library is operational
pub fn isOperationalImpl(p2p: *P2P) bool {
p2p.state_mutex.lock();
defer p2p.state_mutex.unlock();
return p2p.running.load(.acquire) and p2p.state == .Running;
}
/// Get the library's current state
pub fn getStateImpl(p2p: *P2P) P2PState {
p2p.state_mutex.lock();
defer p2p.state_mutex.unlock();
return p2p.state;
}

279
src/p2p/events.zig Normal file
View File

@@ -0,0 +1,279 @@
//! P2P Events Module
//!
//! This module defines the event system for the P2P library, including
//! event types, event data unions, and event creation utilities.
const std = @import("std");
const Allocator = std.mem.Allocator;
const core = @import("core");
const network = @import("network");
const Error = core.errors.Error;
const PeerId = network.peer.PeerId;
const Address = core.Address;
/// P2P library events
pub const P2PEvent = struct {
/// Event type
event_type: EventType,
/// Event data
data: EventData,
/// Timestamp when event occurred
timestamp: i64,
/// Session ID (if applicable)
session_id: ?u64 = null,
/// Whether this event owns its payload data (must free on deinit)
owns_payload: bool = false,
/// Allocator for freeing owned data
allocator: ?Allocator = null,
/// Event types supported by the library
pub const EventType = enum(u16) {
/// Library lifecycle events
library_initialized = 0x1000,
library_started = 0x1001,
library_stopped = 0x1002,
library_error = 0x1003,
/// Network events
peer_connected = 0x2000,
peer_disconnected = 0x2001,
node_discovered = 0x2002,
connection_established = 0x2003,
connection_failed = 0x2004,
/// File sharing events
file_shared = 0x3000,
file_download_started = 0x3001,
file_download_completed = 0x3002,
file_download_failed = 0x3003,
upload_started = 0x3004,
upload_completed = 0x3005,
upload_failed = 0x3006,
/// Protocol events
message_sent = 0x4000,
message_received = 0x4001,
message_routed = 0x4002,
routing_error = 0x4003,
/// Statistics events
bandwidth_updated = 0x5000,
connection_stats_updated = 0x5001,
transfer_stats_updated = 0x5002,
};
/// Event data union
pub const EventData = union(EventType) {
library_initialized,
library_started,
library_stopped,
library_error: struct { err: Error, message: []const u8 },
peer_connected: struct { peer_id: PeerId, address: Address },
peer_disconnected: struct { peer_id: PeerId, reason: []const u8 },
node_discovered: struct { node_id: PeerId, address: Address },
connection_established: struct { peer_id: PeerId, latency: u32 },
connection_failed: struct { peer_id: PeerId, err: Error },
file_shared: struct { file_path: []const u8, session_id: u64 },
file_download_started: struct { session_id: u64, file_name: []const u8 },
file_download_completed: struct { session_id: u64, file_path: []const u8 },
file_download_failed: struct { session_id: u64, err: Error },
upload_started: struct { session_id: u64, file_path: []const u8 },
upload_completed: struct { session_id: u64, bytes_uploaded: u64 },
upload_failed: struct { session_id: u64, err: Error },
message_sent: struct { message_type: u8, destination: ?PeerId },
message_received: struct { message_type: u8, source: PeerId, data: []const u8 },
message_routed: struct { message_id: u64, hops: u8 },
routing_error: struct { destination: PeerId, err: Error },
bandwidth_updated: struct { download_rate: u64, upload_rate: u64 },
connection_stats_updated: struct { active_connections: u32, total_connections: u32 },
transfer_stats_updated: struct { total_downloaded: u64, total_uploaded: u64 },
};
/// Create a new event
pub fn create(event_type: EventType, data: EventData) P2PEvent {
return P2PEvent{
.event_type = event_type,
.data = data,
.timestamp = std.time.timestamp(),
.session_id = null,
};
}
/// Create event with session ID
pub fn createWithSession(event_type: EventType, data: EventData, session_id: u64) P2PEvent {
return P2PEvent{
.event_type = event_type,
.data = data,
.timestamp = std.time.timestamp(),
.session_id = session_id,
};
}
/// Free owned event data
pub fn deinit(self: *P2PEvent) void {
if (!self.owns_payload or self.allocator == null) return;
if (self.allocator) |alloc| {
switch (self.data) {
.message_received => |msg| {
alloc.free(msg.data);
},
.library_error => |err_data| {
alloc.free(err_data.message);
},
.peer_disconnected => |disc| {
alloc.free(disc.reason);
},
else => {},
}
}
}
};
/// User callback function type
pub const EventCallback = *const fn (event: P2PEvent) void;
/// User context for callbacks
pub const UserContext = struct {
callback: EventCallback,
context_data: ?*anyopaque = null,
};
// Tests
test "P2PEvent: create and createWithSession" {
const event1 = P2PEvent.create(.library_initialized, .library_initialized);
try std.testing.expectEqual(P2PEvent.EventType.library_initialized, event1.event_type);
try std.testing.expect(event1.session_id == null);
try std.testing.expect(event1.timestamp > 0);
const event2 = P2PEvent.createWithSession(.library_started, .library_started, 12345);
try std.testing.expectEqual(P2PEvent.EventType.library_started, event2.event_type);
try std.testing.expectEqual(@as(u64, 12345), event2.session_id.?);
}
test "P2PEvent.EventType: common types" {
const types = [_]P2PEvent.EventType{
.peer_connected,
.peer_disconnected,
.message_received,
.message_sent,
.library_started,
.library_stopped,
};
for (types) |t| {
// Just verify these are valid enum values (< 0x5000 covers all current ranges)
try std.testing.expect(@intFromEnum(t) < 0x5000);
}
}
test "P2PEvent.EventType: all enum values cover full range" {
// Library events
try std.testing.expectEqual(@as(u16, 0x1000), @intFromEnum(P2PEvent.EventType.library_initialized));
try std.testing.expectEqual(@as(u16, 0x1001), @intFromEnum(P2PEvent.EventType.library_started));
try std.testing.expectEqual(@as(u16, 0x1002), @intFromEnum(P2PEvent.EventType.library_stopped));
try std.testing.expectEqual(@as(u16, 0x1003), @intFromEnum(P2PEvent.EventType.library_error));
// Network events
try std.testing.expectEqual(@as(u16, 0x2000), @intFromEnum(P2PEvent.EventType.peer_connected));
try std.testing.expectEqual(@as(u16, 0x2001), @intFromEnum(P2PEvent.EventType.peer_disconnected));
try std.testing.expectEqual(@as(u16, 0x2002), @intFromEnum(P2PEvent.EventType.node_discovered));
try std.testing.expectEqual(@as(u16, 0x2003), @intFromEnum(P2PEvent.EventType.connection_established));
try std.testing.expectEqual(@as(u16, 0x2004), @intFromEnum(P2PEvent.EventType.connection_failed));
// File sharing events
try std.testing.expectEqual(@as(u16, 0x3000), @intFromEnum(P2PEvent.EventType.file_shared));
try std.testing.expectEqual(@as(u16, 0x3001), @intFromEnum(P2PEvent.EventType.file_download_started));
try std.testing.expectEqual(@as(u16, 0x3002), @intFromEnum(P2PEvent.EventType.file_download_completed));
try std.testing.expectEqual(@as(u16, 0x3003), @intFromEnum(P2PEvent.EventType.file_download_failed));
try std.testing.expectEqual(@as(u16, 0x3004), @intFromEnum(P2PEvent.EventType.upload_started));
try std.testing.expectEqual(@as(u16, 0x3005), @intFromEnum(P2PEvent.EventType.upload_completed));
try std.testing.expectEqual(@as(u16, 0x3006), @intFromEnum(P2PEvent.EventType.upload_failed));
// Protocol events
try std.testing.expectEqual(@as(u16, 0x4000), @intFromEnum(P2PEvent.EventType.message_sent));
try std.testing.expectEqual(@as(u16, 0x4001), @intFromEnum(P2PEvent.EventType.message_received));
try std.testing.expectEqual(@as(u16, 0x4002), @intFromEnum(P2PEvent.EventType.message_routed));
try std.testing.expectEqual(@as(u16, 0x4003), @intFromEnum(P2PEvent.EventType.routing_error));
// Stats events
try std.testing.expectEqual(@as(u16, 0x5000), @intFromEnum(P2PEvent.EventType.bandwidth_updated));
try std.testing.expectEqual(@as(u16, 0x5001), @intFromEnum(P2PEvent.EventType.connection_stats_updated));
try std.testing.expectEqual(@as(u16, 0x5002), @intFromEnum(P2PEvent.EventType.transfer_stats_updated));
}
test "P2PEvent: deinit with owned message_received" {
const allocator = std.testing.allocator;
// Allocate owned data
const owned_data = try allocator.dupe(u8, "test message");
var event = P2PEvent{
.event_type = .message_received,
.data = .{
.message_received = .{
.source = network.peer.PeerId{ .bytes = [_]u8{1} ** 32 },
.message_type = 0x01,
.data = owned_data,
},
},
.timestamp = std.time.timestamp(),
.owns_payload = true,
.allocator = allocator,
};
event.deinit();
}
test "P2PEvent: deinit with owned library_error" {
const allocator = std.testing.allocator;
// Allocate owned error message
const owned_msg = try allocator.dupe(u8, "error occurred");
var event = P2PEvent{
.event_type = .library_error,
.data = .{
.library_error = .{
.err = Error.SystemError,
.message = owned_msg,
},
},
.timestamp = std.time.timestamp(),
.owns_payload = true,
.allocator = allocator,
};
event.deinit();
}
test "P2PEvent: deinit with owned peer_disconnected" {
const allocator = std.testing.allocator;
// Allocate owned disconnect reason
const owned_reason = try allocator.dupe(u8, "connection timeout");
var event = P2PEvent{
.event_type = .peer_disconnected,
.data = .{
.peer_disconnected = .{
.peer_id = network.peer.PeerId{ .bytes = [_]u8{2} ** 32 },
.reason = owned_reason,
},
},
.timestamp = std.time.timestamp(),
.owns_payload = true,
.allocator = allocator,
};
event.deinit();
}
test "P2PEvent: deinit without owned data does nothing" {
var event = P2PEvent.create(.library_initialized, .library_initialized);
event.deinit(); // Should not crash
}

380
src/p2p/file_ops.zig Normal file
View File

@@ -0,0 +1,380 @@
//! File Operations Implementation
//!
//! This module contains implementations for P2P file sharing methods as free functions.
//! These functions handle file addition, sharing, downloading, and transfer message processing.
const std = @import("std");
// Core components (via module import)
const core = @import("core");
const Error = core.errors.Error;
// Network components (via module import)
const network = @import("network");
const PeerId = network.peer.PeerId;
// Protocol components (via module import)
const protocol = @import("protocol");
// File sharing components (via module import)
const files = @import("files");
const FileMetadata = files.hash.FileMetadata;
// Import P2P type
const P2P = @import("p2p.zig").P2P;
// Import sibling types
const events = @import("events.zig");
const P2PEvent = events.P2PEvent;
const messaging = @import("messaging.zig");
/// Add a file to the sharing system
///
/// This function makes a file available for sharing with other peers.
pub fn addFileImpl(p2p: *P2P, file_path: []const u8) Error!u64 {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
if (file_path.len == 0) return Error.InvalidArgument;
const manager = p2p.file_manager orelse return Error.InvalidState;
const session_id = try manager.addFile(file_path);
// Emit event
try p2p.emitEvent(P2PEvent.createWithSession(.file_shared, .{ .file_shared = .{ .file_path = file_path, .session_id = session_id } }, session_id));
return session_id;
}
/// Add file for sharing with pre-computed metadata (skips expensive hashing)
pub fn addFileWithMetadataImpl(p2p: *P2P, file_path: []const u8, metadata: FileMetadata) Error!u64 {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
if (file_path.len == 0) return Error.InvalidArgument;
const manager = p2p.file_manager orelse return Error.InvalidState;
const session_id = try manager.addFileWithMetadata(file_path, metadata);
try p2p.emitEvent(P2PEvent.createWithSession(.file_shared, .{ .file_shared = .{ .file_path = file_path, .session_id = session_id } }, session_id));
return session_id;
}
/// Download a file from peers
pub fn downloadFileImpl(p2p: *P2P, metadata: FileMetadata, output_path: []const u8) Error!u64 {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
if (output_path.len == 0) return Error.InvalidArgument;
const manager = p2p.file_manager orelse return Error.InvalidState;
const session_id = try manager.downloadFile(metadata, output_path);
try p2p.emitEvent(P2PEvent.createWithSession(.file_download_started, .{ .file_download_started = .{ .session_id = session_id, .file_name = metadata.name } }, session_id));
return session_id;
}
/// Start a file sharing session
pub fn startSharingImpl(p2p: *P2P, session_id: u64) Error!void {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
const manager = p2p.file_manager orelse return Error.InvalidState;
try manager.startSharing(session_id);
}
/// Stop a file sharing session
pub fn stopSharingImpl(p2p: *P2P, session_id: u64) Error!void {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
const manager = p2p.file_manager orelse return Error.InvalidState;
try manager.stopSharing(session_id);
}
/// Get file metadata for a session
pub fn getFileMetadataImpl(p2p: *P2P, session_id: u64) Error!?FileMetadata {
const manager = p2p.file_manager orelse return Error.InvalidState;
return manager.getFileMetadataBySessionId(session_id, p2p.allocator);
}
/// Create file transfer sender for network integration
pub fn createFileTransferSenderImpl(p2p: *P2P) files.manager.NetworkSender {
const SendContext = struct {
fn sendCallback(peer_id_bytes: []const u8, data: []const u8, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
if (peer_id_bytes.len < 32) return false;
var peer_id: [32]u8 = [_]u8{0} ** 32;
@memcpy(&peer_id, peer_id_bytes[0..32]);
var network_peer_id: PeerId = PeerId{ .bytes = [_]u8{0} ** 32 };
@memcpy(&network_peer_id.bytes, &peer_id);
if (data.len > std.math.maxInt(u32)) return false;
const len: u32 = @intCast(data.len);
var header: [4]u8 = [_]u8{0} ** 4;
std.mem.writeInt(u32, &header, len, .big);
const segments = [_][]const u8{ &header, data };
const result = p2p_ptr.sendSegmentsToPeerAtomic(network_peer_id, &segments) catch |err| {
std.log.warn("sendCallback: sendSegmentsToPeerAtomic error: {}", .{err});
// SOCKET FIX: When send fails with permanent error, trigger peer disconnect to clean up.
// This removes the dead connection and notifies file manager to reassign requests.
// Errors that indicate permanent connection failure:
// - SocketSendFailed: Encrypted send failed (secure.send error)
// - ConnectionClosed: Peer has closed the connection
// - InvalidState: P2P system is shutting down
if (err == Error.SocketSendFailed or err == Error.ConnectionClosed or err == Error.InvalidState) {
std.log.info("SOCKET FIX: Triggering disconnect for failed peer {x}", .{peer_id[0..8].*});
messaging.handleNetworkDisconnectImpl(network_peer_id, p2p_ptr);
}
return false;
};
if (!result) {
// Peer not found in peer_connections - this means:
// 1. Peer was already disconnected and removed, OR
// 2. Peer was never connected
// Either way, the file manager should NOT be notified again because:
// - If already disconnected, handlePeerDisconnect was already called
// - If never connected, there's nothing to clean up
// Previously this called handleNetworkDisconnectImpl which caused O(n*m) redundant work
// for EVERY failed send after the first one, causing throughput death spiral.
std.log.debug("sendCallback: peer not found in peer_connections (peer_id={x}), already disconnected", .{peer_id[0..8].*});
}
return result;
}
/// ZERO-COPY: Send multiple segments directly without concatenating
/// This is the key to eliminating memory copies for large piece data
fn sendSegmentsCallback(peer_id_bytes: []const u8, segments: []const []const u8, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
if (peer_id_bytes.len < 32) return false;
var peer_id: [32]u8 = [_]u8{0} ** 32;
@memcpy(&peer_id, peer_id_bytes[0..32]);
var network_peer_id: PeerId = PeerId{ .bytes = [_]u8{0} ** 32 };
@memcpy(&network_peer_id.bytes, &peer_id);
// Calculate total length for the framing header
var total_len: usize = 0;
for (segments) |seg| {
total_len += seg.len;
}
if (total_len > std.math.maxInt(u32)) return false;
// Create framing header (4 bytes length prefix)
const len: u32 = @intCast(total_len);
var header: [4]u8 = [_]u8{0} ** 4;
std.mem.writeInt(u32, &header, len, .big);
// Build segments array with header prepended
// Use stack allocation for small segment arrays (typical: 3-4 segments)
var all_segments: [8][]const u8 = undefined;
if (segments.len + 1 > all_segments.len) {
std.log.warn("sendSegmentsCallback: too many segments ({})", .{segments.len});
return false;
}
all_segments[0] = &header;
for (segments, 0..) |seg, i| {
all_segments[i + 1] = seg;
}
const result = p2p_ptr.sendSegmentsToPeerAtomic(network_peer_id, all_segments[0 .. segments.len + 1]) catch |err| {
std.log.warn("sendSegmentsCallback: sendSegmentsToPeerAtomic error: {}", .{err});
if (err == Error.SocketSendFailed or err == Error.ConnectionClosed or err == Error.InvalidState) {
std.log.info("SOCKET FIX: Triggering disconnect for failed peer {x}", .{peer_id[0..8].*});
messaging.handleNetworkDisconnectImpl(network_peer_id, p2p_ptr);
}
return false;
};
if (!result) {
std.log.debug("sendSegmentsCallback: peer not found (peer_id={x})", .{peer_id[0..8].*});
}
return result;
}
/// CASCADE FIX: Get all connected peer IDs for broadcasting "have" messages
fn getPeersCallback(out_peers: [][32]u8, ctx: ?*anyopaque) usize {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return 0));
p2p_ptr.peer_connections_mutex.lock();
defer p2p_ptr.peer_connections_mutex.unlock();
var count: usize = 0;
var iter = p2p_ptr.peer_connections.keyIterator();
while (iter.next()) |peer_id| {
if (count >= out_peers.len) break;
out_peers[count] = peer_id.bytes;
count += 1;
}
return count;
}
};
return files.manager.NetworkSender.initWithSegments(
SendContext.sendCallback,
SendContext.sendSegmentsCallback,
SendContext.getPeersCallback,
p2p,
p2p.allocator,
);
}
/// Handle file transfer message from network
pub fn handleFileTransferMessageImpl(p2p: *P2P, peer_id: [32]u8, data: []const u8) void {
const fm = p2p.file_manager orelse {
std.log.warn("File transfer message received but no file manager initialized", .{});
return;
};
const transfer_msg = files.transfer.TransferMessage.deserialize(data, p2p.allocator) catch |err| {
if (err == error.OutOfMemory) {
std.log.err("MED-8: File transfer message DROPPED due to OutOfMemory (data_len={})", .{data.len});
_ = p2p.stats.events_dropped.fetchAdd(1, .monotonic);
} else {
std.log.warn("Failed to deserialize file transfer message: {}", .{err});
}
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
defer {
var msg = transfer_msg;
msg.deinit(p2p.allocator);
}
switch (transfer_msg.message_type) {
.handshake => {
var it = fm.sessions.valueIterator();
if (it.next()) |session| {
session.transfer_protocol.handleMessage(transfer_msg) catch |err| {
std.log.warn("Failed to handle file transfer handshake: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
}
},
.metadata_request => {
const content_hash = if (transfer_msg.data.len >= 32) transfer_msg.data[0..32].* else {
std.log.warn("File transfer metadata request has invalid data length", .{});
return;
};
const metadata_opt = fm.getFileMetadataByHash(content_hash, p2p.allocator) catch |err| {
std.log.err("Failed to get file metadata: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
if (metadata_opt) |metadata| {
defer {
p2p.allocator.free(metadata.name);
p2p.allocator.free(metadata.piece_hashes);
}
const response = files.transfer.TransferMessage.metadataResponse(&peer_id, metadata, p2p.allocator);
const response_data = response.serialize(p2p.allocator) catch |err| {
std.log.err("Failed to serialize metadata response: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
defer p2p.allocator.free(response_data);
const full_msg = p2p.allocator.alloc(u8, 1 + response_data.len) catch |err| {
std.log.err("Failed to allocate metadata response buffer: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
defer p2p.allocator.free(full_msg);
full_msg[0] = 0x01;
@memcpy(full_msg[1..], response_data);
if (fm.network_sender) |sender| {
const sent = sender.send_fn(&peer_id, full_msg, sender.context);
if (!sent) {
std.log.warn("Failed to send metadata response to peer", .{});
}
}
} else {
std.log.warn("Metadata request for unknown content hash", .{});
}
},
.piece_request => {
fm.handlePieceRequest(peer_id, transfer_msg.data) catch |err| {
std.log.debug("Failed to handle piece request: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
// THROUGHPUT FIX: Send piece_reject so client can immediately retry
// instead of waiting 16 seconds for stuck timeout
if (transfer_msg.data.len >= 36) {
const reason: u8 = switch (err) {
Error.ResourceExhausted => 0, // busy
Error.FileError, Error.OperationNotSupported => 1, // not_available
else => 2, // rate_limited/other
};
// Build reject message: content_hash(32) + piece_index(4) + reason(1)
var reject_payload: [37]u8 = undefined;
@memcpy(reject_payload[0..36], transfer_msg.data[0..36]);
reject_payload[36] = reason;
// Send reject response
const reject_msg = files.transfer.TransferMessage{
.message_type = .piece_reject,
.message_id = 0,
.peer_id = &peer_id,
.data = &reject_payload,
.timestamp = std.time.timestamp(),
};
if (fm.network_sender) |sender| {
_ = sender.sendMessage(reject_msg) catch {};
}
}
return;
};
},
.batch_piece_request => {
fm.handleBatchPieceRequest(peer_id, transfer_msg.data) catch |err| {
std.log.warn("Failed to handle batch piece request: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
},
.piece_data => {
fm.handlePieceData(peer_id, transfer_msg.data) catch |err| {
std.log.warn("Failed to handle piece data: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
},
.bitfield => {
fm.handleBitfield(peer_id, transfer_msg.data) catch |err| {
std.log.warn("Failed to handle bitfield: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
},
.have => {
fm.handleHave(peer_id, transfer_msg.data) catch |err| {
std.log.warn("Failed to handle have message: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
},
.metadata_response => {
fm.handleMetadataResponse(peer_id, transfer_msg.data) catch |err| {
std.log.warn("Failed to handle metadata response: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
},
.piece_response => {
fm.handlePieceResponse(peer_id, transfer_msg.data) catch |err| {
std.log.warn("Failed to handle piece response: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return;
};
},
.piece_reject => {
// THROUGHPUT FIX: Handle reject from busy seeder - immediately retry
fm.handlePieceReject(peer_id, transfer_msg.data) catch |err| {
std.log.debug("Failed to handle piece reject: {}", .{err});
return;
};
},
else => {
std.log.debug("Unhandled file transfer message type: {}", .{transfer_msg.message_type});
},
}
}

697
src/p2p/lifecycle.zig Normal file
View File

@@ -0,0 +1,697 @@
//! 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 MessageRouter = protocol.router.MessageRouter;
// 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 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;
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,
});
}
}
// 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): {x}", .{p2p.local_node_id[0..8].*});
// 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;
}
}

300
src/p2p/messaging.zig Normal file
View File

@@ -0,0 +1,300 @@
//! P2P Messaging Implementation
//!
//! This module contains implementations for P2P messaging operations including
//! sending messages, emitting events, the main update loop, statistics updates,
//! and network message/disconnect handling callbacks.
const std = @import("std");
const Allocator = std.mem.Allocator;
// Core components
const core = @import("core");
const Error = core.errors.Error;
// Network components
const network = @import("network");
const PeerId = network.peer.PeerId;
// Protocol components
const protocol = @import("protocol");
// File sharing components
const files = @import("files");
// Import P2P type
const P2P = @import("p2p.zig").P2P;
// Sibling module imports
const events = @import("events.zig");
const P2PEvent = events.P2PEvent;
const lifecycle = @import("lifecycle.zig");
const file_ops = @import("file_ops.zig");
// ============================================================================
// Message Sending
// ============================================================================
/// Send a custom message to a peer
pub fn sendMessageImpl(p2p: *P2P, destination: ?PeerId, message_type: u8, data: []const u8) Error!u64 {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
if (data.len == 0) return Error.InvalidArgument;
if (data.len > p2p.config.protocol.max_message_size) {
return Error.MessageTooLarge;
}
const nm = p2p.network_manager orelse return Error.InvalidState;
var full_msg = p2p.allocator.alloc(u8, data.len + 1) catch return Error.OutOfMemory;
defer p2p.allocator.free(full_msg);
full_msg[0] = message_type;
@memcpy(full_msg[1..], data);
if (destination) |peer_id| {
const msg_id = try nm.sendMessage(peer_id, full_msg);
try emitEventImpl(p2p, P2PEvent.create(.message_sent, .{ .message_sent = .{
.message_type = message_type,
.destination = destination,
} }));
return msg_id;
} else {
_ = try nm.broadcastMessage(full_msg);
try emitEventImpl(p2p, P2PEvent.create(.message_sent, .{ .message_sent = .{
.message_type = message_type,
.destination = null,
} }));
return 0;
}
}
// ============================================================================
// Event Emission
// ============================================================================
/// Emit an internal event
pub fn emitEventImpl(p2p: *P2P, event: P2PEvent) Error!void {
p2p.event_mutex.lock();
defer p2p.event_mutex.unlock();
if (p2p.event_queue.items.len >= p2p.config.events.max_event_queue) {
std.log.warn("Event queue overflow - dropping oldest event (queue size: {})", .{p2p.event_queue.items.len});
_ = p2p.stats.events_dropped.fetchAdd(1, .monotonic);
if (p2p.event_queue.items.len > 0) {
var dropped = p2p.event_queue.orderedRemove(0);
dropped.deinit();
}
}
p2p.event_queue.append(p2p.allocator, event) catch return Error.OutOfMemory;
if (p2p.config.events.enable_logging) {
std.debug.print("P2P Event: {s}\n", .{@tagName(event.event_type)});
}
}
/// Emit an error event
pub fn emitErrorEventImpl(p2p: *P2P, err: anyerror, message: []const u8) Error!void {
const error_value: Error = @errorCast(err);
const event = P2PEvent{
.event_type = .library_error,
.data = .{
.library_error = .{
.err = error_value,
.message = message,
},
},
.timestamp = std.time.timestamp(),
.session_id = null,
};
try emitEventImpl(p2p, event);
}
// ============================================================================
// Update Loop
// ============================================================================
/// Internal update function called periodically
pub fn updateImpl(p2p: *P2P) Error!void {
if (!p2p.running.load(.acquire)) return;
// 1. Accept incoming connections
if (p2p.listen_socket != null) {
p2p.acceptConnections() catch |err| {
std.log.warn("Accept connections failed: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
};
}
// 2. Process network I/O
if (p2p.network_manager) |nm| {
nm.processReceive() catch |err| {
std.log.warn("Network receive failed: {}", .{err});
_ = p2p.stats.receive_errors.fetchAdd(1, .monotonic);
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
};
nm.processSendQueue();
}
// 2b. Drain pending sends
p2p.drainPendingSends();
// 3. File sharing operations
if (p2p.file_manager) |fm| {
fm.processSessions() catch |err| {
std.log.err("File manager error: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
emitErrorEventImpl(p2p, err, "File manager error") catch |emit_err| {
std.log.warn("Failed to emit error event: {}", .{emit_err});
};
};
fm.processVerificationResults();
}
// 4. Health checks
const now = std.time.milliTimestamp();
if (now - p2p.last_health_check > p2p.config.network.health_check_interval_ms) {
lifecycle.performHealthChecksImpl(p2p) catch |err| {
std.log.warn("Health checks failed: {}", .{err});
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
};
p2p.last_health_check = now;
}
// 5. TURN allocation refresh
if (p2p.turn_integration) |integration| {
integration.refreshIfNeeded() catch |err| {
std.log.warn("TURN refresh failed: {} - NAT traversal may be degraded", .{err});
};
}
// 6. Replay protection cleanup
const cleanup_interval_ms = p2p.config.protocol.replay_protection_cleanup_interval * 1000;
if ((now - p2p.last_replay_cleanup) > cleanup_interval_ms) {
if (p2p.handler_registry) |registry| {
registry.cleanupReplayProtection();
}
p2p.last_replay_cleanup = now;
}
// 7. Check error rates and manage state transitions
if (p2p.config.library.enable_auto_maintenance) {
const check_interval: i64 = @as(i64, p2p.config.library.maintenance_check_interval_ms);
if (now - p2p.last_maintenance_check > check_interval) {
lifecycle.checkErrorRateAndTransitionStateImpl(p2p) catch |err| {
std.log.warn("Failed to check error rate: {}", .{err});
};
p2p.last_maintenance_check = now;
}
}
// 8. Update statistics
updateStatsImpl(p2p);
}
// ============================================================================
// Statistics
// ============================================================================
/// Update statistics from various sources
pub fn updateStatsImpl(p2p: *P2P) void {
if (p2p.start_time > 0) {
const now = std.time.timestamp();
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.peer_connections_mutex.lock();
const count = p2p.peer_connections.count();
const conn_count: u32 = if (count > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(count);
p2p.peer_connections_mutex.unlock();
p2p.stats.active_connections.store(conn_count, .monotonic);
if (p2p.network_manager) |nm| {
const nm_stats = nm.getStats();
p2p.stats.messages_sent.store(nm_stats.messages_sent.load(.acquire), .release);
p2p.stats.messages_received.store(nm_stats.messages_received.load(.acquire), .release);
}
}
// ============================================================================
// Network Callbacks
// ============================================================================
/// Callback for receiving messages from NetworkManager
pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*anyopaque) void {
const p2p: *P2P = @ptrCast(@alignCast(context orelse return));
const app_id: u8 = if (data.len > 0) data[0] else 0;
// File transfer messages bypass event system
if (data.len > 1 and app_id == 0x01) {
file_ops.handleFileTransferMessageImpl(p2p, peer_id.bytes, data[1..]);
return;
}
const payload_src: []const u8 = if (data.len > 1) data[1..] else &[_]u8{};
const payload = p2p.allocator.dupe(u8, payload_src) catch return;
var event = P2PEvent.create(.message_received, .{
.message_received = .{
.message_type = app_id,
.source = peer_id,
.data = payload,
},
});
event.owns_payload = true;
event.allocator = p2p.allocator;
emitEventImpl(p2p, event) catch |err| {
std.log.warn("Failed to emit message_received event: {}", .{err});
p2p.allocator.free(payload);
};
}
/// Callback for peer disconnection from NetworkManager
pub fn handleNetworkDisconnectImpl(peer_id: PeerId, context: ?*anyopaque) void {
const p2p: *P2P = @ptrCast(@alignCast(context orelse return));
// SOCKET FIX: Remove from peer_connections FIRST to stop further send attempts
// This must happen before notifying file manager to prevent race conditions
const connection = @import("connection.zig");
if (connection.removePeerConnectionImpl(p2p, peer_id)) |socket| {
socket.close() catch {};
socket.deinit();
p2p.allocator.destroy(socket);
}
emitEventImpl(p2p, P2PEvent.create(.peer_disconnected, .{
.peer_disconnected = .{
.peer_id = peer_id,
.reason = "network disconnect",
},
})) catch |err| {
std.log.warn("Failed to emit disconnect event: {}", .{err});
};
const current = p2p.stats.active_connections.load(.monotonic);
if (current > 0) {
_ = p2p.stats.active_connections.fetchSub(1, .monotonic);
}
// CRITICAL FIX: Use removePeerById to properly clean up both peer_ids and peers maps.
// The old code was buggy - pm.peers is keyed by address string, not peer_id bytes.
if (p2p.peer_manager) |pm| {
_ = pm.removePeerById(peer_id);
}
if (p2p.peer_rate_limiter) |limiter| {
limiter.removePeer(peer_id.bytes);
}
// CASCADE PERF: Notify file manager to immediately cancel requests to this peer
if (p2p.file_manager) |fm| {
fm.handlePeerDisconnect(peer_id.bytes);
}
}

1141
src/p2p/p2p.zig Normal file

File diff suppressed because it is too large Load Diff

174
src/p2p/stats.zig Normal file
View File

@@ -0,0 +1,174 @@
//! P2P Statistics Module
//!
//! This module defines the statistics tracking structure for the P2P library,
//! including connection counts, bandwidth metrics, and error tracking.
const std = @import("std");
const Allocator = std.mem.Allocator;
const atomic = std.atomic;
const types = @import("types.zig");
const P2PState = types.P2PState;
const core = @import("core");
const Error = core.errors.Error;
/// P2P library statistics
///
/// NOTE: This struct contains a mix of atomic and non-atomic fields:
/// - errors_total, receive_errors, events_dropped, active_connections, and total_connections
/// are atomic.Value and thread-safe
/// - All other fields are plain values, updated from the main thread
///
/// The atomic fields are used for counters that may be updated from multiple
/// threads concurrently (e.g., error counting from I/O threads, connection counting
/// from connection threads). Other statistics are gathered and updated from the
/// main update() function, so they don't need atomic protection.
///
/// When reading statistics via getStats(), the atomic values are loaded with
/// .monotonic ordering, which provides a consistent snapshot of concurrent counters.
pub const P2PStats = struct {
/// Library state
state: P2PState,
/// Uptime in seconds
uptime_seconds: u64,
/// Total memory allocated
memory_allocated: usize,
/// Active connections (atomic for thread-safe concurrent updates)
active_connections: atomic.Value(u32),
/// Total connections established (atomic for thread-safe concurrent updates)
total_connections: atomic.Value(u64),
/// Messages sent/received (atomic for thread-safe concurrent updates)
messages_sent: atomic.Value(u64),
messages_received: atomic.Value(u64),
/// Bandwidth usage (atomic for thread-safe concurrent updates)
current_download_rate: atomic.Value(u64), // bytes/second
current_upload_rate: atomic.Value(u64), // bytes/second
/// File sharing statistics (atomic for thread-safe concurrent updates)
active_downloads: atomic.Value(u32),
active_uploads: atomic.Value(u32),
total_downloaded: atomic.Value(u64),
total_uploaded: atomic.Value(u64),
/// Event queue statistics
event_queue_size: usize,
/// Atomic counter for events processed (thread-safe)
events_processed: atomic.Value(u64),
/// Atomic counter for events dropped due to queue full (thread-safe)
events_dropped: atomic.Value(u64),
/// Error statistics (atomic for thread-safe concurrent updates)
errors_total: atomic.Value(u64),
receive_errors: atomic.Value(u64),
last_error: ?Error = null,
/// Get formatted statistics string
pub fn formatString(self: P2PStats, allocator: Allocator) ![]const u8 {
const uptime_hours = @as(f32, @floatFromInt(self.uptime_seconds)) / 3600.0;
const download_mb = @as(f32, @floatFromInt(self.total_downloaded.load(.monotonic))) / (1024 * 1024);
const upload_mb = @as(f32, @floatFromInt(self.total_uploaded.load(.monotonic))) / (1024 * 1024);
return std.fmt.allocPrint(
allocator,
\\P2P Library Statistics
\\ State: {s}
\\ Uptime: {d:.1} hours
\\ Memory: {d:.1} MB
\\ Connections: {d}/{d} active/total
\\ Messages: {d} sent, {d} received
\\ Bandwidth: {d:.1} MB/s down, {d:.1} MB/s up
\\ Downloads: {d} active, {d:.1} MB total
\\ Uploads: {d} active, {d:.1} MB total
\\ Events: {d} processed, {d} in queue
\\ Errors: {d} total, {d} receive errors
\\
,
.{
@tagName(self.state),
uptime_hours,
@as(f32, @floatFromInt(self.memory_allocated)) / (1024 * 1024),
self.active_connections.load(.monotonic),
self.total_connections.load(.monotonic),
self.messages_sent.load(.monotonic),
self.messages_received.load(.monotonic),
@as(f32, @floatFromInt(self.current_download_rate.load(.monotonic))) / (1024 * 1024),
@as(f32, @floatFromInt(self.current_upload_rate.load(.monotonic))) / (1024 * 1024),
self.active_downloads.load(.monotonic),
download_mb,
self.active_uploads.load(.monotonic),
upload_mb,
self.events_processed.load(.monotonic),
self.event_queue_size,
self.errors_total.load(.monotonic),
self.receive_errors.load(.monotonic),
},
);
}
};
// Tests
test "P2PStats: formatString" {
const allocator = std.testing.allocator;
const stats = P2PStats{
.state = .Running,
.uptime_seconds = 3600,
.memory_allocated = 1024 * 1024,
.active_connections = .{ .raw = 5 },
.total_connections = .{ .raw = 100 },
.messages_sent = .{ .raw = 200 },
.messages_received = .{ .raw = 150 },
.current_download_rate = .{ .raw = 1000 },
.current_upload_rate = .{ .raw = 500 },
.active_downloads = .{ .raw = 2 },
.active_uploads = .{ .raw = 1 },
.total_downloaded = .{ .raw = 1024 * 1024 },
.total_uploaded = .{ .raw = 512 * 1024 },
.event_queue_size = 10,
.events_processed = .{ .raw = 500 },
.events_dropped = .{ .raw = 2 },
.errors_total = .{ .raw = 10 },
.receive_errors = .{ .raw = 3 },
.last_error = null,
};
const str = try stats.formatString(allocator);
defer allocator.free(str);
try std.testing.expect(std.mem.indexOf(u8, str, "P2P Library Statistics") != null);
try std.testing.expect(std.mem.indexOf(u8, str, "Running") != null);
}
test "P2PStats: atomic counter operations" {
var stats = P2PStats{
.state = .Initialized,
.uptime_seconds = 0,
.memory_allocated = 0,
.active_connections = atomic.Value(u32).init(0),
.total_connections = atomic.Value(u64).init(0),
.messages_sent = atomic.Value(u64).init(0),
.messages_received = atomic.Value(u64).init(0),
.current_download_rate = atomic.Value(u64).init(0),
.current_upload_rate = atomic.Value(u64).init(0),
.active_downloads = atomic.Value(u32).init(0),
.active_uploads = atomic.Value(u32).init(0),
.total_downloaded = atomic.Value(u64).init(0),
.total_uploaded = atomic.Value(u64).init(0),
.event_queue_size = 0,
.events_processed = atomic.Value(u64).init(0),
.events_dropped = atomic.Value(u64).init(0),
.errors_total = atomic.Value(u64).init(0),
.receive_errors = atomic.Value(u64).init(0),
};
// Test increment operations
_ = stats.messages_sent.fetchAdd(5, .monotonic);
_ = stats.messages_received.fetchAdd(10, .monotonic);
_ = stats.active_connections.fetchAdd(3, .monotonic);
_ = stats.total_connections.fetchAdd(5, .monotonic);
_ = stats.total_downloaded.fetchAdd(1024 * 1024, .monotonic);
_ = stats.total_uploaded.fetchAdd(512 * 1024, .monotonic);
_ = stats.errors_total.fetchAdd(2, .monotonic);
_ = stats.receive_errors.fetchAdd(1, .monotonic);
try std.testing.expectEqual(@as(u64, 5), stats.messages_sent.load(.monotonic));
try std.testing.expectEqual(@as(u64, 10), stats.messages_received.load(.monotonic));
try std.testing.expectEqual(@as(u32, 3), stats.active_connections.load(.monotonic));
try std.testing.expectEqual(@as(u64, 2), stats.errors_total.load(.monotonic));
}

44
src/p2p/types.zig Normal file
View File

@@ -0,0 +1,44 @@
//! P2P Core Types
//!
//! This module defines the fundamental types used throughout the P2P library,
//! including state enums.
const std = @import("std");
/// P2P library states
pub const P2PState = enum(u8) {
/// Library is not initialized
Uninitialized = 0,
/// Library is initialized but not running
Initialized = 1,
/// Library is starting up
Starting = 2,
/// Library is running and operational
Running = 3,
/// Library is stopping
Stopping = 4,
/// Library is stopped
Stopped = 5,
/// Library is in maintenance mode
Maintenance = 6,
/// Library has encountered an error
Error = 7,
};
// Tests
test "P2PState: all enum values" {
const states = [_]P2PState{
.Uninitialized,
.Initialized,
.Starting,
.Running,
.Stopping,
.Stopped,
.Maintenance,
.Error,
};
for (states) |state| {
try std.testing.expect(@intFromEnum(state) < 10);
}
}