Files
zigp2p/docs/HANDLER_INTEGRATION_GUIDE.md
2026-02-06 21:03:59 -03:00

8.0 KiB

Protocol Handler Integration Guide

Quick Integration Steps

This guide shows how to integrate the completed protocol handlers into your P2P system.

Step 1: Import Complete Handlers

const handler = @import("protocol/handler.zig");
const handler_complete = @import("protocol/handler_complete.zig");

Step 2: Initialize Handler Context with Network Sender

When creating your P2P node, wire up the handler context:

// During P2P initialization
pub fn initP2P(allocator: std.mem.Allocator) !P2PNode {
    var node = P2PNode{
        .allocator = allocator,
        .network_manager = try NetworkManager.init(allocator, &connections),
        .peer_manager = try PeerManager.init(allocator, config),
        .file_manager = try FileSharingManager.init(allocator, config),
        .routing_table = try KademliaRoutingTable.init(allocator, local_id),
        // ... other components
    };

    // Create handler registry
    node.handler_registry = try handler.HandlerRegistry.init(allocator);

    // Get handler context
    var ctx = node.handler_registry.getContext();

    // CRITICAL: Set network sender for message sending
    ctx.network_sender = @ptrCast(&node.network_manager);

    // Set P2P component references
    ctx.setP2PComponents(
        @ptrCast(&node.peer_manager),
        @ptrCast(&node.file_manager),
        @ptrCast(&node.routing_table),
        @ptrCast(&node.topology),
        @ptrCast(&node.network_manager),
    );

    // Register handlers
    var builder = handler.HandlerBuilder.init(&node.handler_registry);
    try builder.registerDefaultHandlers();

    return node;
}

Step 3: Route Incoming Messages to Handlers

When receiving messages from the network:

pub fn handleIncomingMessage(
    node: *P2PNode,
    peer_id: NodeId,
    data: []const u8,
) !void {
    // Deserialize message
    var serializer = MessageSerializer.init(node.allocator);
    const msg = try serializer.deserialize(data);

    // Set source peer for context
    var ctx = node.handler_registry.getContext();
    ctx.setSource(peer_id);
    defer ctx.clearSource();

    // Process message through handler registry
    try node.handler_registry.processMessage(msg);
}

Step 4: Use Complete Handlers for Specific Operations

For operations that need explicit handler calls:

// Example: Handle ping explicitly
pub fn processPing(node: *P2PNode, peer_id: NodeId, ping: message.Ping) !void {
    var ctx = node.handler_registry.getContext();
    ctx.setSource(peer_id);
    defer ctx.clearSource();

    // Use complete handler implementation
    try handler_complete.ControlHandlerImpl.handlePing(ping, ctx);
}

// Example: Handle data request explicitly
pub fn processDataRequest(
    node: *P2PNode,
    peer_id: NodeId,
    request: message.DataRequest,
) !void {
    var ctx = node.handler_registry.getContext();
    ctx.setSource(peer_id);
    defer ctx.clearSource();

    try handler_complete.DataHandlerImpl.handleRequest(request, ctx);
}

Step 5: Verify Network Sender is Working

Add logging to verify messages are being sent:

// In HandlerContext.sendResponse (handler.zig)
pub fn sendResponse(self: *HandlerContext, peer_id: message.NodeId, msg: message.Message) !void {
    if (self.network_sender == null) {
        std.debug.print("ERROR: No network sender configured!\n", .{});
        return error.NoNetworkSender;
    }

    std.debug.print("Sending {s} to peer {any}\n", .{
        @tagName(msg.getType()),
        peer_id[0..8],
    });

    // ... rest of sendResponse implementation
}

Common Issues and Solutions

Issue 1: "NoNetworkSender" Error

Symptom: Handlers return error.NoNetworkSender

Solution: Ensure context.network_sender is set during initialization:

ctx.network_sender = @ptrCast(&node.network_manager);

Issue 2: Messages Not Being Sent

Symptom: Handlers execute but no network traffic

Solution:

  1. Verify NetworkManager has active connections
  2. Check that sockets are properly initialized
  3. Add debug logging to NetworkManager.sendMessage()

Issue 3: Source Peer ID is Null

Symptom: Handlers return error.InvalidMessage

Solution: Set source before calling handler:

ctx.setSource(peer_id);
defer ctx.clearSource();

Issue 4: Component References are Null

Symptom: Handlers skip logic due to null checks

Solution: Call setP2PComponents() after initialization:

ctx.setP2PComponents(
    @ptrCast(&peer_manager),
    @ptrCast(&file_manager),
    @ptrCast(&routing_table),
    @ptrCast(&topology),
    @ptrCast(&network_manager),
);

Testing Integration

Unit Test

test "handler integration with mock network" {
    const allocator = testing.allocator;

    // Setup components
    var network_manager = MockNetworkManager.init(allocator);
    defer network_manager.deinit();

    var metrics = handler.HandlerMetrics.init();
    var context = handler.HandlerContext.init(allocator, &metrics);

    // Wire up network sender
    context.network_sender = @ptrCast(&network_manager);

    // Set source
    var peer_id: message.NodeId = [_]u8{1} ** 32;
    context.setSource(peer_id);

    // Test ping handler
    const ping = message.Ping{ .sequence = 123 };
    try handler_complete.ControlHandlerImpl.handlePing(ping, &context);

    // Verify message was sent
    try testing.expectEqual(@as(usize, 1), network_manager.sent_count);
}

Integration Test

test "full ping-pong roundtrip" {
    const allocator = testing.allocator;

    // Create two P2P nodes
    var node1 = try initTestP2PNode(allocator);
    defer node1.deinit();

    var node2 = try initTestP2PNode(allocator);
    defer node2.deinit();

    // Connect nodes
    try node1.connectToPeer(node2.getAddress());

    // Node1 sends ping
    const ping = message.Ping{ .sequence = 42 };
    try node1.sendPing(node2.id, ping);

    // Node2 should receive ping and send pong automatically
    // (via handler)
    try node2.processIncomingMessages();

    // Node1 should receive pong
    try node1.processIncomingMessages();

    // Verify RTT was updated
    const peer = node1.peer_manager.getPeerById(node2.id).?;
    try testing.expect(peer.metrics.rtt > 0);
}

Performance Considerations

Message Allocation

Handlers allocate buffers for message serialization. For high-throughput scenarios:

// Option 1: Reuse buffer pool
var buffer_pool = MessageBufferPool.init(allocator, 100);
defer buffer_pool.deinit();

// Option 2: Use arena allocator for batch processing
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();

Async Processing

For non-blocking message handling:

pub fn processMessageAsync(
    node: *P2PNode,
    peer_id: NodeId,
    data: []const u8,
) !void {
    // Queue message for async processing
    try node.async_processor.queueMessage(
        message.Message.fromBytes(data)
    );
}

Monitoring and Debugging

Handler Metrics

Access handler metrics for monitoring:

const metrics = node.handler_registry.getContext().metrics;
std.debug.print("Messages processed: {d}\n", .{metrics.messages_processed});
std.debug.print("Messages failed: {d}\n", .{metrics.messages_failed});
std.debug.print("Success rate: {d:.2}%\n", .{metrics.getSuccessRate() * 100});

Network Sender Metrics

Monitor network sending:

const stats = node.network_manager.stats.getSnapshot();
std.debug.print("Messages sent: {d}\n", .{stats.messages_sent});
std.debug.print("Bytes sent: {d}\n", .{stats.bytes_sent});
std.debug.print("Send errors: {d}\n", .{stats.send_errors});

Summary

Key integration points:

  1. ✅ Set context.network_sender during initialization
  2. ✅ Call setP2PComponents() to wire up dependencies
  3. ✅ Set source peer ID before processing messages
  4. ✅ Route incoming messages through handler registry
  5. ✅ Use complete handlers for explicit operations
  6. ✅ Monitor metrics for debugging

With these steps, your P2P network will have fully functional message handling with actual request/response flows!