336 lines
12 KiB
Zig
336 lines
12 KiB
Zig
//! 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;
|
|
}
|
|
|
|
// DHT messages - deserialize and route through handler_registry
|
|
if (data.len > 1 and app_id == 0x02) {
|
|
handleDhtMessageImpl(p2p, peer_id, 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);
|
|
};
|
|
}
|
|
|
|
/// Handle incoming DHT protocol messages (app_id = 0x02)
|
|
/// This deserializes the message and routes it through the handler registry,
|
|
/// setting the connection peer ID as source_peer_id for auto-registration.
|
|
fn handleDhtMessageImpl(p2p: *P2P, connection_peer_id: PeerId, payload: []const u8) void {
|
|
const registry = p2p.handler_registry orelse {
|
|
std.log.warn("DHT: Received message but no handler registry initialized", .{});
|
|
return;
|
|
};
|
|
|
|
// Use simple binary deserialization (no HMAC - Noise transport provides security)
|
|
const dht = @import("dht.zig");
|
|
const msg = dht.deserializeDhtMessage(payload, p2p.allocator) orelse {
|
|
std.log.warn("DHT: Failed to deserialize message (len={})", .{payload.len});
|
|
return;
|
|
};
|
|
|
|
// CRITICAL: Set the connection peer ID as source before processing
|
|
// This allows DHT handlers to auto-register the node_id -> peer_id mapping
|
|
registry.context.setSource(connection_peer_id.bytes);
|
|
defer registry.context.clearSource();
|
|
|
|
// Process the message through the handler registry
|
|
registry.processMessage(msg) catch |err| {
|
|
std.log.warn("DHT: Failed to process message: {}", .{err});
|
|
};
|
|
|
|
std.log.debug("DHT: Processed message from peer", .{});
|
|
}
|
|
|
|
/// 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);
|
|
}
|
|
}
|