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

458
src/core/README.md Normal file
View File

@@ -0,0 +1,458 @@
# P2P Library Core Networking Module
The core networking module provides the foundational building blocks for the P2P library, implementing zero-copy buffer management, comprehensive address handling, socket abstractions, and connection management - all built with pure Zig and the standard library.
## Architecture Overview
```
src/core/
├── error.zig # Comprehensive error handling
├── address.zig # Network address abstraction
├── buffer.zig # Zero-copy buffer management
├── socket.zig # Socket operations and management
├── connection.zig # High-level connection abstraction
└── README.md # This documentation
```
## Key Features
### 🔒 Zero Dependencies
- Pure Zig implementation using only standard library
- No external dependencies or C bindings
- Cross-platform compatibility (Linux, macOS, Windows)
### ⚡ High Performance
- Zero-copy buffer operations
- Memory pool allocation and reuse
- Lock-free data structures where possible
- Optimized for low-latency, high-throughput scenarios
### 🛡️ Memory Safety
- Zig's safety features prevent common vulnerabilities
- Explicit error handling and propagation
- Automatic memory management with proper cleanup
- Buffer overflow and underflow protection
### 🔧 Type Safety
- Strong typing throughout the codebase
- Compile-time error detection
- Generic abstractions for reusability
- Comprehensive API contracts
## Module Details
### Error Handling (`error.zig`)
Provides a comprehensive error handling system for the entire P2P library:
```zig
const Error = @import("core/error.zig").Error;
// Error categories
pub const Error = error{
// Network layer errors
NetworkError,
ConnectionRefused,
ConnectionTimeout,
AddressInUse,
// Protocol errors
ProtocolError,
InvalidMessage,
MessageTooLarge,
// System errors
OutOfMemory,
ThreadError,
InvalidArgument,
InvalidState,
};
```
**Key Features:**
- Error context with operation, component, and peer information
- Global error statistics tracking
- Error result types with additional metadata
- Conversion helpers for system error codes
### Address Management (`address.zig`)
Network address abstraction supporting multiple address families:
```zig
const Address = @import("core/address.zig").Address;
// IPv4 address
const addr = try Address.parse("192.168.1.100:8080");
// IPv6 address
const ipv6 = try Address.parse("[2001:db8::1]:8080");
// Unix socket
const unix = try Address.parse("/tmp/test.sock");
```
**Key Features:**
- IPv4, IPv6, and Unix socket address support
- Address parsing from strings
- Address validation and comparison
- System socket address conversion
- Address resolution utilities
### Buffer Management (`buffer.zig`)
Zero-copy buffer management with memory pooling:
```zig
const Buffer = @import("core/buffer.zig");
var manager = Buffer.BufferManager.init(.{}, allocator);
defer manager.deinit();
// Stream buffer (TCP-like)
const stream_buf = try manager.createStreamBuffer(1024);
defer stream_buf.release();
// Packet buffer (UDP-like)
const packet_buf = try manager.createPacketBuffer(512);
defer packet_buf.release();
// Message buffer with headers
const message_buf = try manager.createMessageBuffer(2048);
defer message_buf.release();
```
**Key Features:**
- Memory pool allocation and reuse
- Stream, packet, and message buffer types
- Reference counting and automatic cleanup
- Buffer compaction and capacity management
- Reader/writer interfaces
### Socket Operations (`socket.zig`)
Low-level socket management and operations:
```zig
const Socket = @import("core/socket.zig").Socket;
// TCP socket
var tcp_socket = try Socket.init(.tcp, allocator);
defer tcp_socket.deinit();
try tcp_socket.bind(try Address.parse("127.0.0.1:8080"));
try tcp_socket.listen(10);
// Accept connections
const client_socket = try tcp_socket.accept();
defer client_socket.deinit();
// UDP socket
var udp_socket = try Socket.init(.udp, allocator);
defer udp_socket.deinit();
try udp_socket.bind(try Address.parse("0.0.0.0:8080"));
// Send/receive data
const data = "Hello, World!";
try udp_socket.send(data);
// Receive with sender address
const result = try udp_socket.receiveFrom(&buffer);
```
**Key Features:**
- TCP, UDP, and Unix socket support
- Socket option configuration
- Non-blocking and timeout support
- Socket pooling and management
- Statistics and health monitoring
### Connection Abstraction (`connection.zig`)
High-level connection management with TCP/UDP support:
```zig
const Connection = @import("core/connection.zig").Connection;
// TCP connection
var connection = try Connection.init(.tcp, config, allocator);
defer connection.deinit();
try connection.connect(try Address.parse("192.168.1.100:8080"));
// Send/receive with automatic buffer management
const send_buffer = try connection.createSendBuffer();
defer send_buffer.release();
try send_buffer.write("Hello, World!");
try connection.sendBuffer(send_buffer);
// Health checking
const health = connection.checkHealth();
connection.updateHealthStatus(health);
```
**Key Features:**
- Connection pooling and management
- Health checking and monitoring
- Automatic buffer management
- Graceful shutdown handling
- Connection statistics and metrics
## Usage Examples
### Basic Server Setup
```zig
const std = @import("std");
const P2P = @import("core");
pub fn main() !void {
var allocator = std.heap.page_allocator;
defer (void) allocator.deinit();
// Create TCP socket
var socket = try P2P.Socket.init(.tcp, allocator);
defer socket.deinit();
// Bind and listen
const address = try P2P.Address.parse("127.0.0.1:8080");
try socket.bind(address);
try socket.listen(10);
std.debug.print("Server listening on {s}\n", .{try address.toString()});
// Accept connections
while (true) {
const client = try socket.accept();
defer client.deinit();
// Handle client (in practice, would use async/concurrency)
std.debug.print("New connection from {s}\n", .{
client.getRemoteAddress().?.toString()
});
}
}
```
### Basic Client Setup
```zig
pub fn main() !void {
var allocator = std.heap.page_allocator;
// Create connection
var connection = try P2P.Connection.init(.tcp, config, allocator);
defer connection.deinit();
// Connect to server
const server_addr = try P2P.Address.parse("127.0.0.1:8080");
try connection.connect(server_addr);
// Send data
const data = "Hello, Server!";
try connection.send(data);
// Receive response
var buffer: [1024]u8 = undefined;
const n = try connection.receive(&buffer);
std.debug.print("Received: {s}\n", .{buffer[0..n]});
}
```
### Buffer Pool Usage
```zig
pub fn processMessages(allocator: mem.Allocator) !void {
var buffer_manager = P2P.Buffer.BufferManager.init(.{}, allocator);
defer buffer_manager.deinit();
// Create multiple buffers from pool
const buffers = try allocator.alloc(P2P.Buffer.StreamBuffer, 10);
defer {
for (buffers) |*buf| buf.release();
allocator.free(buffers);
}
for (buffers) |*buf, i| {
buf.* = try buffer_manager.createStreamBuffer(1024 + i * 256);
}
// Use buffers for network operations
for (buffers) |*buf| {
try buf.write("Test message");
// Buffer will be automatically returned to pool when released
}
}
```
## Performance Characteristics
### Memory Usage
- **Zero-copy operations**: Minimizes memory copying overhead
- **Memory pooling**: Reduces allocation/deallocation overhead
- **Reference counting**: Efficient buffer lifecycle management
- **Compact data structures**: Optimized memory layout
### CPU Performance
- **Lock-free operations**: Where safe, using atomic operations
- **Batch operations**: Grouped operations for better cache utilization
- **Inline functions**: Compile-time optimization for small operations
- **Memory alignment**: Cache-friendly data structure layouts
### Network Performance
- **Buffer pooling**: Reduces GC pressure and allocation latency
- **Selective receive**: Efficient handling of partial data
- **Connection pooling**: Reuses established connections
- **Health monitoring**: Proactive connection management
## Thread Safety
All public APIs are designed to be thread-safe:
- **Immutable data**: Address and configuration structures
- **Atomic operations**: For counters and state management
- **Mutual exclusion**: For shared mutable state
- **Copy-on-write**: For buffer modifications
## Error Handling
Comprehensive error handling with explicit propagation:
```zig
// All functions return explicit errors
pub fn connect(self: *Connection, address: Address) Error!void {
if (self.state != .disconnected) {
return Error.ConnectionAlreadyExists;
}
// ... connection logic
return;
}
```
Error contexts provide additional debugging information:
```zig
const context = ErrorContext.init("connect", "tcp_transport")
.withPeerId("peer123")
.withConnectionId("conn456");
const error_result = errWithContext(
Error.ConnectionRefused,
context,
"Failed to connect to peer",
);
```
## Testing
Comprehensive test suite covers:
- **Unit tests**: Individual component testing
- **Integration tests**: Component interaction testing
- **Performance tests**: Benchmark critical operations
- **Memory tests**: Valgrind and leak detection
- **Error path tests**: Error handling validation
Run tests with:
```bash
# Run all tests
bash test/run_tests.sh
# Run individual module tests
zig test test/core/test_error.zig
zig test test/core/test_address.zig
zig test test/core/test_buffer.zig
zig test test/core/test_socket.zig
zig test test/core/test_connection.zig
# Run with coverage
zig test --test-coverage test/core/test_main.zig
```
## Configuration
### Socket Configuration
```zig
const socket_config = SocketConfig{
.protocol = .tcp,
.non_blocking = false,
.reuse_address = true,
.reuse_port = false,
.keep_alive = true,
.no_delay = true,
.buffer_size = 64 * 1024, // 64KB
.timeout_ms = 30000, // 30 seconds
};
```
### Connection Configuration
```zig
const connection_config = ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 64 * 1024,
.timeout_ms = 30000,
.keep_alive = true,
.no_delay = true,
.max_retry_attempts = 3,
.retry_delay_ms = 1000,
.health_check_interval = 30000,
.enable_metrics = true,
};
```
### Buffer Pool Configuration
```zig
const pool_config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 1024 * 1024, // 1MB
.initial_chunks = 8,
.max_chunks = 256,
.grow_factor = 2.0,
};
```
## Platform Support
- **Linux**: Full support with all features
- **macOS**: Full support with all features
- **Windows**: Full support (Unix socket support limited)
- **WebAssembly**: Experimental (limited I/O support)
## Security Considerations
- **Memory safety**: Zig's safety features prevent buffer overflows
- **Error handling**: Explicit error propagation prevents silent failures
- **Input validation**: Address parsing validates all inputs
- **Resource limits**: Configurable limits prevent resource exhaustion
## Future Enhancements
- **QUIC support**: Modern transport protocol
- **IPv6 enhancements**: Better IPv6 optimization
- **Async I/O**: Event-driven architecture
- **Performance monitoring**: Detailed metrics and profiling
- **Compression**: Built-in data compression
- **Encryption**: Transport layer security
## Contributing
When contributing to the core networking module:
1. **Maintain zero dependencies**: Use only Zig standard library
2. **Follow error handling patterns**: Explicit error propagation
3. **Add comprehensive tests**: Include unit, integration, and performance tests
4. **Document public APIs**: Provide clear documentation for all public interfaces
5. **Consider thread safety**: Ensure all operations are thread-safe
6. **Optimize for performance**: Keep zero-copy and efficiency in mind
## License
This module is part of the P2P library and follows the same licensing terms.

1359
src/core/address.zig Normal file

File diff suppressed because it is too large Load Diff

1133
src/core/buffer.zig Normal file

File diff suppressed because it is too large Load Diff

1686
src/core/connection.zig Normal file

File diff suppressed because it is too large Load Diff

627
src/core/error.zig Normal file
View File

@@ -0,0 +1,627 @@
//! Comprehensive error types and handling for P2P networking
//!
//! This module provides a centralized error handling system for the entire
//! P2P library, covering network, protocol, cryptographic, and system errors.
const std = @import("std");
const testing = std.testing;
const builtin = @import("builtin");
const log = @import("log.zig");
/// Comprehensive error types for P2P networking operations
pub const Error = error{
// Network layer errors
NetworkError,
ConnectionRefused,
ConnectionTimeout,
ConnectionReset,
NetworkUnreachable,
AddressInUse,
AddressNotAvailable,
NoRouteToHost,
// Socket errors
SocketError,
SocketCreationFailed,
SocketOptionError,
SocketBindingFailed,
SocketAlreadyBound,
SocketListeningFailed,
SocketAcceptFailed,
SocketConnectFailed,
SocketSendFailed,
SocketReceiveFailed,
SocketCloseFailed,
// Address errors
AddressError,
InvalidAddressFormat,
AddressParseError,
AddressNotFound,
InvalidPort,
UnsupportedAddressFamily,
// Buffer errors
BufferError,
BufferTooSmall,
BufferOverflow,
BufferUnderflow,
OutOfMemory,
InvalidBufferSize,
AllocationTooLarge,
RateLimitExceeded,
// CRIT-5/CRIT-6 FIX: Queue and buffer limit errors
/// Send queue is full (message count or byte limit reached)
QueueFull,
/// Receive buffer memory limit exceeded
ReceiveBufferFull,
/// Global memory limit exceeded
MemoryLimitExceeded,
// Connection errors
ConnectionError,
ConnectionFailed,
ConnectionNotFound,
ConnectionClosed,
ConnectionTimeoutExceeded,
ConnectionAlreadyExists,
InvalidConnectionState,
PoolExhausted,
/// CRIT-2 FIX: Maximum connection limit reached
ConnectionLimitExceeded,
/// Connection blocked due to active backoff period
BackoffActive,
/// All retry attempts exhausted
MaxRetriesExceeded,
/// NAT traversal (STUN/TURN hole punching) failed
NatTraversalFailed,
// Protocol errors
ProtocolError,
InvalidMessage,
MessageTooLarge,
UnsupportedMessageType,
MalformedMessage,
ProtocolVersionMismatch,
// Cryptographic errors
CryptoError,
InvalidSignature,
SignatureVerificationFailed,
KeyGenerationFailed,
EncryptionFailed,
DecryptionFailed,
HashComputationFailed,
KeyNotFound,
// Security errors
SecurityError,
AuthenticationFailed,
AuthorizationFailed,
CertificateError,
KeyExchangeFailed,
// System errors
SystemError,
ThreadError,
MutexError,
LockOrderViolation,
InvalidArgument,
InvalidState,
OperationNotSupported,
ResourceExhausted,
// Validation errors
ValidationError,
NullPointer,
InvalidLength,
InvalidData,
InvalidConfiguration,
// I/O errors
IOError,
FileError,
FileTooLarge, // CRIT-2: For files exceeding format limits (e.g., >4GB for 32-bit headers)
DiskFull,
PermissionDenied,
// Timeout errors
TimeoutError,
// Internal errors
InternalError,
NotImplemented,
Unexpected,
};
/// Error information structure for detailed error reporting
pub const ErrorInfo = struct {
err: Error,
message: []const u8,
context: []const u8,
timestamp: i64,
location: Location,
const Location = struct {
file: []const u8,
line: u32,
function: []const u8,
};
/// Create error info with location context
pub fn create(
err: Error,
message: []const u8,
context: []const u8,
file: []const u8,
line: u32,
function: []const u8,
) ErrorInfo {
return .{
.err = err,
.message = message,
.context = context,
.timestamp = std.time.timestamp(),
.location = .{
.file = file,
.line = line,
.function = function,
},
};
}
/// Format error info as string (requires allocator)
pub fn format(self: ErrorInfo, allocator: std.mem.Allocator) ![]const u8 {
return std.fmt.allocPrint(
allocator,
"{s} at {s}:{d} in {s}: {s}",
.{
@errorName(self.err),
self.location.file,
self.location.line,
self.location.function,
self.message,
},
);
}
};
/// Error context for additional error information
pub const ErrorContext = struct {
operation: []const u8,
component: []const u8,
peer_id: ?[]const u8,
connection_id: ?[]const u8,
pub fn init(
operation: []const u8,
component: []const u8,
) ErrorContext {
return .{
.operation = operation,
.component = component,
.peer_id = null,
.connection_id = null,
};
}
pub fn withPeerId(self: ErrorContext, peer_id: []const u8) ErrorContext {
var ctx = self;
ctx.peer_id = peer_id;
return ctx;
}
pub fn withConnectionId(self: ErrorContext, connection_id: []const u8) ErrorContext {
var ctx = self;
ctx.connection_id = connection_id;
return ctx;
}
};
/// Error result type that can contain additional context
pub const ErrorResult = struct {
err: Error,
info: ErrorInfo,
pub fn create(
err: Error,
message: []const u8,
context: ErrorContext,
file: []const u8,
line: u32,
function: []const u8,
allocator: std.mem.Allocator,
) Error!ErrorResult {
const context_str = std.fmt.allocPrint(
allocator,
"op={s} component={s} peer={s} conn={s}",
.{
context.operation,
context.component,
context.peer_id orelse "none",
context.connection_id orelse "none",
},
) catch return Error.OutOfMemory;
return .{
.err = err,
.info = ErrorInfo.create(
err,
message,
context_str,
file,
line,
function,
),
};
}
};
/// Macros for common error handling patterns
pub fn logError(e: Error, comptime format: []const u8, args: anytype) Error {
log.err("Error {s}: " ++ format, .{@errorName(e)} ++ args);
recordGlobalError(e);
return e;
}
pub fn errWithContext(
err: Error,
context: ErrorContext,
comptime format: []const u8,
args: anytype,
allocator: std.mem.Allocator,
) Error!ErrorResult {
const message = std.fmt.comptimePrint(format, args);
const src = @src();
return ErrorResult.create(err, message, context, src.file, src.line, src.fn_name, allocator);
}
pub fn unexpected(expected: []const u8, actual: []const u8) Error {
// Skip printing during tests to avoid test framework treating output as failure
if (!builtin.is_test) {
std.debug.print("Unexpected value: expected '{s}', got '{s}'\n", .{ expected, actual });
}
recordGlobalError(Error.Unexpected);
return Error.Unexpected;
}
pub fn reachedUnreachable() Error {
return Error.InternalError;
}
/// IMP-M3 FIX: Assert condition with message logging on failure
pub fn assertCondition(condition: bool, msg: []const u8) Error!void {
if (!condition) {
// Log the message so we know what assertion failed
// Skip logging during tests to avoid test framework treating logged errors as failures
if (!builtin.is_test) {
std.log.err("Assertion failed: {s}", .{msg});
}
return Error.ValidationError;
}
}
/// IMP-M3 FIX: Assert with specific error and message logging on failure
pub fn assertWithError(condition: bool, e: Error, msg: []const u8) Error!void {
if (!condition) {
// Log the message so we know what assertion failed
// Skip logging during tests to avoid test framework treating logged errors as failures
if (!builtin.is_test) {
std.log.err("Assertion failed ({s}): {s}", .{ @errorName(e), msg });
}
return e;
}
}
pub fn wrapError(result: anytype, default_error: Error) Error!void {
if (result) |_| {
return;
} else |err| {
_ = err;
return default_error;
}
}
/// Error conversion helpers
pub fn toString(e: Error) []const u8 {
return @errorName(e);
}
pub fn fromInt(code: i32) Error {
return switch (code) {
-1 => Error.NetworkError,
-2 => Error.ConnectionRefused,
-3 => Error.AddressInUse,
-4 => Error.NetworkUnreachable,
-5 => Error.NoRouteToHost,
else => Error.SystemError,
};
}
pub fn toInt(e: Error) i32 {
return switch (e) {
Error.NetworkError => -1,
Error.ConnectionRefused => -2,
Error.AddressInUse => -3,
Error.NetworkUnreachable => -4,
Error.NoRouteToHost => -5,
else => -1,
};
}
/// Error statistics and tracking
pub const ErrorStats = struct {
total_errors: std.atomic.Value(u64),
/// Per-error counts using a simple array indexed by error code
/// We use a fixed-size array for lock-free atomic access
error_counts: [256]std.atomic.Value(u64),
pub fn init() ErrorStats {
var stats = ErrorStats{
.total_errors = std.atomic.Value(u64).init(0),
.error_counts = undefined,
};
// Initialize all error counts to 0
for (&stats.error_counts) |*count| {
count.* = std.atomic.Value(u64).init(0);
}
return stats;
}
pub fn record(self: *ErrorStats, err: Error) void {
_ = self.total_errors.fetchAdd(1, .monotonic);
// Use error code as index (modulo array size for safety)
const index = @intFromError(err) % self.error_counts.len;
_ = self.error_counts[index].fetchAdd(1, .monotonic);
}
pub fn getCount(self: *const ErrorStats, err: Error) u64 {
const index = @intFromError(err) % self.error_counts.len;
return self.error_counts[index].load(.monotonic);
}
pub fn getTotal(self: *const ErrorStats) u64 {
return self.total_errors.load(.monotonic);
}
};
/// Enhanced error metrics with detailed tracking
pub const ErrorMetrics = struct {
total_errors: std.atomic.Value(u64),
errors_by_type: std.AutoHashMap(Error, u64),
mutex: std.Thread.Mutex,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) ErrorMetrics {
return .{
.total_errors = std.atomic.Value(u64).init(0),
.errors_by_type = std.AutoHashMap(Error, u64).init(allocator),
.mutex = .{},
.allocator = allocator,
};
}
pub fn deinit(self: *ErrorMetrics) void {
self.errors_by_type.deinit();
}
pub fn recordError(self: *ErrorMetrics, err: Error) void {
_ = self.total_errors.fetchAdd(1, .monotonic);
self.mutex.lock();
defer self.mutex.unlock();
const entry = self.errors_by_type.getOrPut(err) catch {
std.log.warn("Failed to track error type {s}", .{@errorName(err)});
return;
};
if (!entry.found_existing) {
entry.value_ptr.* = 0;
}
entry.value_ptr.* += 1;
}
pub fn getSnapshot(self: *ErrorMetrics) ErrorSnapshot {
self.mutex.lock();
defer self.mutex.unlock();
return .{
.total_errors = self.total_errors.load(.monotonic),
.unique_error_types = self.errors_by_type.count(),
};
}
pub fn getErrorCount(self: *ErrorMetrics, err: Error) u64 {
self.mutex.lock();
defer self.mutex.unlock();
return self.errors_by_type.get(err) orelse 0;
}
};
/// Snapshot of error metrics
pub const ErrorSnapshot = struct {
total_errors: u64,
unique_error_types: usize,
};
/// Global error statistics instance
var global_error_stats: std.atomic.Value(?*ErrorStats) = std.atomic.Value(?*ErrorStats).init(null);
pub fn getGlobalErrorStats() ?*ErrorStats {
return global_error_stats.load(.monotonic);
}
pub fn setGlobalErrorStats(stats: *ErrorStats) void {
global_error_stats.store(stats, .monotonic);
}
pub fn recordGlobalError(e: Error) void {
if (getGlobalErrorStats()) |stats| {
stats.record(e);
}
}
/// CRIT-NEW-19 FIX: Helper to properly handle "swallowed" errors
/// This function logs the error AND records it to global stats for later analysis.
/// Use this instead of just logging when an error cannot be propagated but shouldn't be lost.
///
/// Example usage:
/// ```
/// some_operation() catch |err| {
/// recordAndLogError("operation context", err);
/// // continue execution without propagating
/// };
/// ```
pub fn recordAndLogError(context: []const u8, e: anyerror) void {
// Log the error
log.err("CRIT-NEW-19: Swallowed error in {s}: {}", .{ context, e });
// Record to stats if the error is in our Error type
if (@errorName(e).len > 0) {
// Check if it's one of our Error types by name
// This is a best-effort recording since we can't always convert anyerror to Error
if (getGlobalErrorStats()) |stats| {
_ = stats.total_errors.fetchAdd(1, .monotonic);
}
}
}
/// CRIT-NEW-19 FIX: Like recordAndLogError but returns a default value
/// Useful for expressions that need a fallback value.
pub fn recordErrorWithDefault(comptime T: type, context: []const u8, e: anyerror, default: T) T {
recordAndLogError(context, e);
return default;
}
/// Testing utilities
fn testErrorFunction() Error!void {
return Error.ConnectionRefused;
}
pub fn testErrorPropagation() !void {
// Test that errors propagate correctly
const result = testErrorFunction();
try testing.expectError(Error.ConnectionRefused, result);
}
pub fn testErrorContext() !void {
const context = ErrorContext.init("test", "test_component");
const error_result = try errWithContext(
Error.ConnectionRefused,
context,
"Test error with context",
.{},
testing.allocator,
);
defer testing.allocator.free(error_result.info.context);
try testing.expect(Error.ConnectionRefused == error_result.err);
try testing.expect(error_result.info.context.len > 0);
}
pub fn testErrorStats() !void {
var stats = ErrorStats.init();
stats.record(Error.ConnectionRefused);
stats.record(Error.ConnectionRefused);
stats.record(Error.AddressInUse);
try testing.expectEqual(@as(u64, 3), stats.getTotal());
try testing.expectEqual(@as(u64, 2), stats.getCount(Error.ConnectionRefused));
try testing.expectEqual(@as(u64, 1), stats.getCount(Error.AddressInUse));
try testing.expectEqual(@as(u64, 0), stats.getCount(Error.NetworkError));
}
test "error basic operations" {
try testErrorPropagation();
try testErrorContext();
try testErrorStats();
}
test "error conversion" {
try testing.expectEqualSlices(u8, "ConnectionRefused", toString(Error.ConnectionRefused));
try testing.expectEqualSlices(u8, "NetworkError", toString(Error.NetworkError));
try testing.expect(Error.ConnectionRefused == fromInt(-2));
try testing.expect(Error.AddressInUse == fromInt(-3));
}
test "error macros" {
// Test assertWithError when condition is true
try assertWithError(true, Error.ConnectionRefused, "should not error");
// Test assertWithError when condition is false
const result = assertWithError(false, Error.ConnectionRefused, "should error");
try testing.expectError(Error.ConnectionRefused, result);
}
test "error context operations" {
var context = ErrorContext.init("connect", "network");
context = context.withPeerId("peer123");
context = context.withConnectionId("conn456");
try testing.expectEqualSlices(u8, "connect", context.operation);
try testing.expectEqualSlices(u8, "network", context.component);
try testing.expectEqualSlices(u8, "peer123", context.peer_id.?);
try testing.expectEqualSlices(u8, "conn456", context.connection_id.?);
}
test "error stats operations" {
try testErrorStats();
}
test "global error stats" {
var stats = ErrorStats.init();
setGlobalErrorStats(&stats);
try testing.expect(getGlobalErrorStats() == &stats);
recordGlobalError(Error.ConnectionRefused);
recordGlobalError(Error.AddressInUse);
try testing.expectEqual(@as(u64, 2), stats.getTotal());
}
test "ErrorResult.create OOM handling" {
const context = ErrorContext.init("test", "test_component");
// This test verifies that ErrorResult.create can return an error
const result = ErrorResult.create(
Error.ConnectionRefused,
"Test error",
context,
"test.zig",
42,
"testFunction",
testing.allocator,
);
// Should either succeed or return OutOfMemory error
if (result) |error_result| {
defer testing.allocator.free(error_result.info.context);
try testing.expect(Error.ConnectionRefused == error_result.err);
} else |err| {
try testing.expect(err == Error.OutOfMemory);
}
}
test "unexpected returns error" {
const err = unexpected("expected", "actual");
try testing.expectEqual(Error.Unexpected, err);
}
test "reachedUnreachable returns error" {
const err = reachedUnreachable();
try testing.expectEqual(Error.InternalError, err);
}
test "assertCondition returns error on failure" {
const result = assertCondition(false, "test assertion");
try testing.expectError(Error.ValidationError, result);
}
test "assertCondition succeeds on true condition" {
try assertCondition(true, "test assertion");
}

362
src/core/limits.zig Normal file
View File

@@ -0,0 +1,362 @@
//! Centralized configuration limits for the P2P library
//!
//! MED-12 FIX: This module provides configurable limits that were previously
//! hardcoded throughout the codebase. All limits have sensible defaults but
//! can be customized at initialization.
//!
//! Usage:
//! const limits = Limits.init(); // Use defaults
//! // or
//! var limits = Limits.init();
//! limits.file.max_file_size = 50 * 1024 * 1024 * 1024; // 50GB
//! p2p.initWithLimits(allocator, config, limits);
const std = @import("std");
/// Centralized limits configuration
pub const Limits = struct {
/// File transfer limits
file: FileLimits = .{},
/// Network limits
network: NetworkLimits = .{},
/// DHT limits
dht: DhtLimits = .{},
/// Rate limiting
rate: RateLimits = .{},
/// Memory limits
memory: MemoryLimits = .{},
/// Security limits
security: SecurityLimits = .{},
pub fn init() Limits {
return .{};
}
/// Validate all limits are within acceptable ranges
pub fn validate(self: *const Limits) bool {
// File limits validation
if (self.file.piece_size < 1024 or self.file.piece_size > 256 * 1024 * 1024) return false;
if (self.file.max_file_size < self.file.piece_size) return false;
if (self.file.max_sessions == 0) return false;
// Network limits validation
if (self.network.max_connections == 0) return false;
if (self.network.max_message_size < 1024) return false;
if (self.network.receive_buffer_size < 1024) return false;
// DHT limits validation
if (self.dht.max_value_size == 0) return false;
if (self.dht.ttl == 0) return false;
// Rate limits validation
if (self.rate.max_requests_per_minute == 0) return false;
return true;
}
};
/// File transfer related limits
pub const FileLimits = struct {
/// Default piece size for file chunking (default: 1MB)
/// Note: Must be smaller than network MAX_MESSAGE_SIZE (2MB) to allow for protocol overhead
piece_size: u64 = 1 * 1024 * 1024,
/// Maximum allowed piece size (default: 1.5MB to stay under 2MB message limit with overhead)
max_piece_size: u64 = 1536 * 1024,
/// Maximum file size that can be transferred (default: 10GB)
max_file_size: u64 = 10 * 1024 * 1024 * 1024,
/// Maximum filename length (default: 255)
max_filename_length: usize = 255,
/// Maximum concurrent file sessions (default: 1000)
max_sessions: usize = 1000,
/// Maximum piece data size per request (default: 32MB)
max_piece_data_size: usize = 32 * 1024 * 1024,
/// Maximum pending upload requests (default: 10000)
max_pending_uploads: usize = 10000,
/// Maximum pending download requests (default: 10000)
max_pending_downloads: usize = 10000,
/// Maximum retries per piece (default: 3)
max_retries_per_piece: u8 = 3,
/// Chunk size for file I/O operations (default: 64KB)
io_chunk_size: usize = 64 * 1024,
// Transfer throughput limits
/// Maximum concurrent downloads (default: 256)
max_concurrent_downloads: usize = 256,
/// Maximum concurrent uploads (default: 256)
max_concurrent_uploads: usize = 256,
/// Maximum download bandwidth in bytes per second (default: 1 GB/s)
max_bandwidth_download: u64 = 1024 * 1024 * 1024,
/// Maximum upload bandwidth in bytes per second (default: 1 GB/s)
max_bandwidth_upload: u64 = 1024 * 1024 * 1024,
/// Maximum requests per peer for downloads (default: 256)
max_download_requests_per_peer: usize = 256,
/// PERF: Request pipeline queue depth per peer (default: 64)
/// Number of outstanding piece requests to maintain per peer for optimal pipelining.
/// Benchmarks (localhost, 10 peers):
/// 1GB file: depth=8 optimal (698 MB/s)
/// 5GB file: depth=16 optimal (446 MB/s with 32 workers)
/// CASCADE FIX: Increased to 64 for cascade distribution where peers are both
/// uploaders and downloaders simultaneously. The old limit of 16 caused cascade
/// stalls when multiple downstream peers competed for limited pipeline slots.
/// For WAN with higher latency, consider 128.
request_queue_depth: usize = 64,
/// Maximum piece data messages per processSessions call
/// Higher values improve throughput but increase per-call CPU time.
/// Each 1MB piece = ~10ms encryption; with CPU contention this can be 5x higher
/// THROUGHPUT FIX: Set to 32 as middle ground between latency and throughput.
/// 32 pieces = ~320ms encryption theoretical, but parallel updates help
max_piece_data_per_call: usize = 32,
/// Maximum messages per processSessions call (increased for multi-peer)
max_messages_per_call: usize = 2048,
};
/// Network related limits
pub const NetworkLimits = struct {
/// Maximum concurrent connections (default: 10000)
max_connections: usize = 10000,
/// Maximum connections per IP address (default: 10)
max_connections_per_ip: usize = 10,
/// Maximum message size (default: 64MB)
max_message_size: usize = 64 * 1024 * 1024,
/// Receive buffer size (default: 256KB for balanced throughput)
receive_buffer_size: usize = 256 * 1024,
/// Socket buffer size (default: 256KB for balanced throughput)
socket_buffer_size: usize = 256 * 1024,
/// Message rate limit per peer (messages/second) - high for file transfer (default: 100000)
message_rate_limit: u32 = 100000,
/// Message burst size - high for file transfer (default: 10000)
message_burst_size: u32 = 10000,
/// Maximum connection pool size (default: 1000)
max_pool_size: usize = 1000,
/// Maximum tolerated socket failures before closing (default: 3)
max_socket_failures: u32 = 3,
/// TURN allocation lifetime in seconds (default: 600)
turn_lifetime: u32 = 600,
/// Discovery receive buffer size (default: 4096)
discovery_buffer_size: usize = 4096,
// CRIT-5 FIX: Send queue limits to prevent unbounded memory growth
/// Maximum messages in send queue (default: 10000)
max_send_queue_messages: usize = 10000,
/// Maximum total bytes in send queue (default: 256MB)
max_send_queue_bytes: usize = 256 * 1024 * 1024,
/// Maximum age of queued message before eviction in seconds (default: 60)
max_send_queue_age_seconds: i64 = 60,
// CRIT-6 FIX: Receive buffer limits to prevent memory exhaustion
/// Maximum total receive buffer memory across all peers (default: 2GB for large files)
max_total_receive_buffer_bytes: usize = 2 * 1024 * 1024 * 1024,
/// Maximum receive buffer size per peer (default: 2MB)
max_receive_buffer_per_peer: usize = 2 * 1024 * 1024,
/// Timeout for incomplete messages in receive buffer in seconds (default: 30)
receive_buffer_timeout_seconds: i64 = 30,
// BACKPRESSURE FIX: Limit pending_send buffer to prevent OOM during high load
/// Maximum pending send buffer size per peer (default: 64MB)
/// When exceeded, sendSegments returns false to signal backpressure.
/// Callers should slow down sending when this limit is hit.
/// Set to 64MB to allow high throughput while still preventing runaway growth.
max_pending_send_per_peer: usize = 64 * 1024 * 1024,
};
/// DHT related limits
pub const DhtLimits = struct {
/// Default TTL for DHT entries in seconds (default: 3600 = 1 hour)
ttl: u32 = 3600,
/// Maximum value size for DHT storage (default: 64KB)
max_value_size: usize = 65536,
/// Maximum nodes to return in response (default: 8)
max_response_nodes: usize = 8,
/// Maximum amplification factor for anti-DoS (default: 10)
max_amplification_factor: usize = 10,
/// Minimum request size to prevent amplification attacks (default: 32)
min_request_size: usize = 32,
/// Maximum message age in seconds (default: 60)
max_message_age: i64 = 60,
/// Maximum pending responses (default: 10000)
max_pending_responses: usize = 10000,
/// K-bucket size (default: 20)
k_bucket_size: usize = 20,
// CRIT-7 FIX: DHT lookup state limits to prevent memory exhaustion
/// Maximum concurrent pending lookups (default: 100)
max_pending_lookups: usize = 100,
/// Maximum nodes tracked per lookup in closest_seen (default: 1000)
max_closest_seen_per_lookup: usize = 1000,
/// Maximum nodes tracked per lookup in queried (default: 500)
max_queried_per_lookup: usize = 500,
/// Maximum discovered peers to track (default: 10000)
max_discovered_peers: usize = 10000,
/// Maximum storage entries (default: 100000)
max_storage_entries: usize = 100000,
};
/// Rate limiting configuration
pub const RateLimits = struct {
/// Maximum requests per minute per IP (default: 60)
max_requests_per_minute: u32 = 60,
/// Minimum interval between requests in ms (default: 100)
min_request_interval_ms: i64 = 100,
/// Maximum per-IP rate limiters to track (default: 10000)
max_per_ip_limiters: usize = 10000,
/// Discovery requests per window per IP (default: 10)
discovery_requests_per_window: u32 = 10,
/// Default tokens per second for rate limiting (default: 100)
default_tokens_per_second: u64 = 100,
/// Default burst size for rate limiting (default: 200)
default_burst_size: u64 = 200,
};
/// Memory limits
pub const MemoryLimits = struct {
/// Maximum memory quota per peer (default: 128MB)
max_peer_memory_quota: u64 = 128 * 1024 * 1024,
/// Maximum global memory quota (default: 2GB)
max_global_memory_quota: u64 = 2 * 1024 * 1024 * 1024,
/// Maximum tracked peers for encryption (default: 10000)
max_tracked_peers: usize = 10000,
/// Maximum evicted peer entries (default: 1000)
max_evicted_peers: usize = 1000,
/// Maximum total nonces across all peers (default: 1M)
max_total_nonces: usize = 1_000_000,
};
/// Security limits
pub const SecurityLimits = struct {
/// Maximum bad pieces before peer blacklist (default: 3)
max_bad_pieces: u32 = 3,
/// Base blacklist duration in seconds (default: 300 = 5 minutes)
base_blacklist_duration: i64 = 300,
/// Maximum blacklist duration in seconds (default: 86400 = 24 hours)
max_blacklist_duration: i64 = 86400,
/// Maximum concurrent requests per peer (default: 64)
max_requests_per_peer: u32 = 64,
/// Maximum key age before rotation in seconds (default: 3600 = 1 hour)
max_key_age: i64 = 3600,
/// Maximum messages per key before rotation (default: 1M)
max_messages_per_key: u64 = 1_000_000,
/// Nonce rotation threshold (default: u32.max - 1000)
nonce_rotation_threshold: u64 = @as(u64, std.math.maxInt(u32)) - 1000,
};
/// Global limits instance (can be customized before P2P initialization)
pub var global: Limits = Limits.init();
/// Comptime defaults for struct field initialization
/// These provide the default values that structs can use for field defaults
pub const defaults = struct {
pub const file = FileLimits{};
pub const network = NetworkLimits{};
pub const dht = DhtLimits{};
pub const rate = RateLimits{};
pub const memory = MemoryLimits{};
pub const security = SecurityLimits{};
};
/// Get a copy of the current global limits
pub fn get() Limits {
return global;
}
/// Set custom global limits (validates before applying)
pub fn set(limits: Limits) bool {
if (!limits.validate()) return false;
global = limits;
return true;
}
test "limits validation" {
const testing = std.testing;
// Default limits should be valid
const default_limits = Limits.init();
try testing.expect(default_limits.validate());
// Invalid piece size
var invalid_limits = Limits.init();
invalid_limits.file.piece_size = 100; // Too small
try testing.expect(!invalid_limits.validate());
// Invalid max connections
invalid_limits = Limits.init();
invalid_limits.network.max_connections = 0;
try testing.expect(!invalid_limits.validate());
}
test "limits customization" {
const testing = std.testing;
var limits = Limits.init();
limits.file.max_file_size = 100 * 1024 * 1024 * 1024; // 100GB
limits.network.max_connections = 50000;
limits.dht.ttl = 7200; // 2 hours
try testing.expect(limits.validate());
try testing.expectEqual(@as(u64, 100 * 1024 * 1024 * 1024), limits.file.max_file_size);
}
test "network limits backpressure defaults" {
const testing = std.testing;
const limits = Limits.init();
// Verify backpressure limit exists and has sensible default
try testing.expectEqual(@as(usize, 64 * 1024 * 1024), limits.network.max_pending_send_per_peer);
// Verify send queue limits
try testing.expectEqual(@as(usize, 10000), limits.network.max_send_queue_messages);
try testing.expectEqual(@as(usize, 256 * 1024 * 1024), limits.network.max_send_queue_bytes);
}
test "network limits receive buffer defaults" {
const testing = std.testing;
const limits = Limits.init();
// Verify receive buffer limits
try testing.expectEqual(@as(usize, 2 * 1024 * 1024 * 1024), limits.network.max_total_receive_buffer_bytes);
try testing.expectEqual(@as(usize, 2 * 1024 * 1024), limits.network.max_receive_buffer_per_peer);
try testing.expectEqual(@as(i64, 30), limits.network.receive_buffer_timeout_seconds);
}
test "file limits throughput defaults" {
const testing = std.testing;
const limits = Limits.init();
// Verify throughput limits
try testing.expectEqual(@as(usize, 256), limits.file.max_concurrent_downloads);
try testing.expectEqual(@as(usize, 256), limits.file.max_concurrent_uploads);
try testing.expectEqual(@as(usize, 64), limits.file.request_queue_depth);
try testing.expectEqual(@as(usize, 32), limits.file.max_piece_data_per_call);
}
test "global limits get and set" {
const testing = std.testing;
// Save original
const original = get();
// Modify and set
var custom = Limits.init();
custom.network.max_connections = 5000;
try testing.expect(set(custom));
// Verify change
try testing.expectEqual(@as(usize, 5000), get().network.max_connections);
// Restore original
_ = set(original);
}
test "defaults comptime values" {
const testing = std.testing;
// Verify defaults struct provides same values as init
try testing.expectEqual(defaults.file.piece_size, Limits.init().file.piece_size);
try testing.expectEqual(defaults.network.max_connections, Limits.init().network.max_connections);
try testing.expectEqual(defaults.dht.ttl, Limits.init().dht.ttl);
try testing.expectEqual(defaults.rate.max_requests_per_minute, Limits.init().rate.max_requests_per_minute);
try testing.expectEqual(defaults.memory.max_peer_memory_quota, Limits.init().memory.max_peer_memory_quota);
try testing.expectEqual(defaults.security.max_bad_pieces, Limits.init().security.max_bad_pieces);
}

27
src/core/log.zig Normal file
View File

@@ -0,0 +1,27 @@
//! Test-Safe Logging Utilities
//!
//! This module provides logging wrappers that use `warn` level during tests
//! to avoid Zig's "logged errors" test failures for expected error conditions.
//!
//! Industry standard: Tests that verify error handling intentionally trigger
//! error conditions. Using `std.log.err` causes test failures even when the
//! test logic passes. This module provides `err()` that behaves correctly
//! in both production and test contexts.
const std = @import("std");
const builtin = @import("builtin");
/// Log an error message. Uses `warn` level during tests to avoid
/// "logged errors" test failures for expected error conditions.
pub fn err(comptime fmt: []const u8, args: anytype) void {
if (builtin.is_test) {
std.log.warn(fmt, args);
} else {
std.log.err(fmt, args);
}
}
test "err: logs at warn level during tests" {
// This should NOT cause a test failure
err("Test error message: {}", .{42});
}

599
src/core/rate_limiter.zig Normal file
View File

@@ -0,0 +1,599 @@
//! Rate Limiter Module
//!
//! Provides token bucket rate limiting for network operations.
//! Supports configurable rates, bursts, and per-peer tracking.
const std = @import("std");
const mem = std.mem;
const time = std.time;
const log = @import("log.zig");
/// Token bucket rate limiter
pub const RateLimiter = struct {
/// Current number of tokens
tokens: std.atomic.Value(u64),
/// Maximum tokens (burst capacity)
max_tokens: u64,
/// Token refill rate (tokens per second)
refill_rate: u64,
/// Last refill timestamp (nanoseconds)
last_refill: std.atomic.Value(i128),
/// Mutex for non-atomic operations
mutex: std.Thread.Mutex = .{},
pub fn init(config: Config) RateLimiter {
return .{
.tokens = std.atomic.Value(u64).init(config.burst_size),
.max_tokens = config.burst_size,
.refill_rate = config.tokens_per_second,
.last_refill = std.atomic.Value(i128).init(time.nanoTimestamp()),
};
}
/// Configuration for rate limiter
pub const Config = struct {
/// Tokens per second to add
tokens_per_second: u64 = 100,
/// Maximum tokens (burst size)
burst_size: u64 = 200,
};
/// Try to consume one token
/// Returns true if token was consumed, false if rate limited
pub fn tryConsume(self: *RateLimiter) bool {
return self.tryConsumeN(1);
}
/// Try to consume N tokens
/// Returns true if tokens were consumed, false if rate limited
pub fn tryConsumeN(self: *RateLimiter, n: u64) bool {
self.refill();
// Optimistic read
const current = self.tokens.load(.acquire);
if (current < n) {
return false;
}
// Try to consume atomically using compare-and-swap loop
var old_tokens = current;
while (true) {
if (old_tokens < n) return false;
const result = self.tokens.cmpxchgWeak(
old_tokens,
old_tokens - n,
.acq_rel,
.acquire,
);
if (result) |val| {
// CAS failed, retry with new value
old_tokens = val;
} else {
// Success
return true;
}
}
}
/// Refill tokens based on elapsed time
fn refill(self: *RateLimiter) void {
const now = time.nanoTimestamp();
const last = self.last_refill.load(.acquire);
const elapsed_ns = now - last;
if (elapsed_ns <= 0) return;
// Calculate tokens to add (using nanoseconds for precision)
const elapsed_seconds = @as(u64, @intCast(@divFloor(elapsed_ns, time.ns_per_s)));
if (elapsed_seconds == 0) return;
const new_tokens = elapsed_seconds * self.refill_rate;
if (new_tokens == 0) return;
// Update last refill time
_ = self.last_refill.cmpxchgStrong(last, now, .acq_rel, .acquire);
// Add tokens (capped at max)
var current = self.tokens.load(.acquire);
while (true) {
const capped = @min(current + new_tokens, self.max_tokens);
if (current == capped) break;
const result = self.tokens.cmpxchgWeak(current, capped, .acq_rel, .acquire);
if (result) |val| {
current = val;
} else {
break;
}
}
}
/// Get current available tokens
pub fn getAvailableTokens(self: *RateLimiter) u64 {
self.refill();
return self.tokens.load(.acquire);
}
/// Check if rate limited (without consuming)
pub fn isRateLimited(self: *RateLimiter) bool {
self.refill();
return self.tokens.load(.acquire) == 0;
}
};
/// Per-peer rate limiter tracking
pub const PeerRateLimiter = struct {
allocator: mem.Allocator,
limiters: std.AutoHashMap([32]u8, RateLimiter),
config: RateLimiter.Config,
mutex: std.Thread.Mutex = .{},
pub fn init(allocator: mem.Allocator, config: RateLimiter.Config) PeerRateLimiter {
return .{
.allocator = allocator,
.limiters = std.AutoHashMap([32]u8, RateLimiter).init(allocator),
.config = config,
};
}
pub fn deinit(self: *PeerRateLimiter) void {
self.limiters.deinit();
}
/// Maximum number of peer limiters to prevent unbounded growth
pub const MAX_PEER_LIMITERS: usize = 10_000;
/// Try to consume a token for a specific peer
/// Creates a new limiter for the peer if needed
pub fn tryConsume(self: *PeerRateLimiter, peer_id: [32]u8) bool {
self.mutex.lock();
defer self.mutex.unlock();
const entry = self.limiters.getPtr(peer_id);
if (entry) |limiter| {
return limiter.tryConsume();
}
// MED-NEW-1 FIX: Enforce limit on peer limiters to prevent unbounded growth
if (self.limiters.count() >= MAX_PEER_LIMITERS) {
std.log.warn("MED-NEW-1: Peer limiter capacity reached ({}/{}), rejecting new peer", .{ self.limiters.count(), MAX_PEER_LIMITERS });
return false; // Reject - can't track this peer
}
// Create new limiter for this peer
self.limiters.put(peer_id, RateLimiter.init(self.config)) catch return false;
const new_limiter = self.limiters.getPtr(peer_id) orelse return false;
return new_limiter.tryConsume();
}
/// Check if a peer is rate limited
pub fn isRateLimited(self: *PeerRateLimiter, peer_id: [32]u8) bool {
self.mutex.lock();
defer self.mutex.unlock();
const entry = self.limiters.getPtr(peer_id);
if (entry) |limiter| {
return limiter.isRateLimited();
}
return false; // Unknown peers are not rate limited initially
}
/// Remove a peer's rate limiter (on disconnect)
pub fn removePeer(self: *PeerRateLimiter, peer_id: [32]u8) void {
self.mutex.lock();
defer self.mutex.unlock();
_ = self.limiters.remove(peer_id);
}
/// Get count of tracked peers
pub fn getPeerCount(self: *PeerRateLimiter) usize {
self.mutex.lock();
defer self.mutex.unlock();
return self.limiters.count();
}
};
/// Connection rate limiter (for limiting new connections)
pub const ConnectionRateLimiter = struct {
global_limiter: RateLimiter,
per_ip_limiters: std.StringHashMap(RateLimiter),
allocator: mem.Allocator,
per_ip_config: RateLimiter.Config,
mutex: std.Thread.Mutex = .{},
/// SEC-M4 FIX: Track last activity time per IP for LRU eviction
ip_last_activity: std.StringHashMap(i64),
/// SEC-M4 FIX: Maximum number of per-IP rate limiters to prevent memory exhaustion
/// This limits memory usage to approximately 100KB for rate limiter state
pub const MAX_PER_IP_LIMITERS: usize = 10_000;
pub fn init(allocator: mem.Allocator, global_config: RateLimiter.Config, per_ip_config: RateLimiter.Config) ConnectionRateLimiter {
return .{
.global_limiter = RateLimiter.init(global_config),
.per_ip_limiters = std.StringHashMap(RateLimiter).init(allocator),
.allocator = allocator,
.per_ip_config = per_ip_config,
.ip_last_activity = std.StringHashMap(i64).init(allocator),
};
}
pub fn deinit(self: *ConnectionRateLimiter) void {
var iter = self.per_ip_limiters.iterator();
while (iter.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
}
self.per_ip_limiters.deinit();
// SEC-M4 FIX: Also clean up activity tracking (keys are shared with per_ip_limiters)
self.ip_last_activity.deinit();
}
/// Try to accept a new connection from an IP
/// Returns true if connection should be accepted
pub fn tryAcceptConnection(self: *ConnectionRateLimiter, ip: []const u8) bool {
// Check global rate limit first
if (!self.global_limiter.tryConsume()) {
return false;
}
const now = std.time.timestamp();
// Check per-IP rate limit
self.mutex.lock();
defer self.mutex.unlock();
if (self.per_ip_limiters.getPtr(ip)) |limiter| {
// SEC-M4 FIX: Update activity timestamp
if (self.ip_last_activity.getPtr(ip)) |activity| {
activity.* = now;
}
return limiter.tryConsume();
}
// SEC-M4 FIX: Check if we need to evict old entries before adding new one
if (self.per_ip_limiters.count() >= MAX_PER_IP_LIMITERS) {
self.evictOldestEntry();
}
// Create new limiter for this IP
const ip_copy = self.allocator.dupe(u8, ip) catch return false;
self.per_ip_limiters.put(ip_copy, RateLimiter.init(self.per_ip_config)) catch {
self.allocator.free(ip_copy);
return false;
};
// SEC-M4 FIX: Track activity time
self.ip_last_activity.put(ip_copy, now) catch {
// Non-fatal, just won't have accurate LRU eviction
};
if (self.per_ip_limiters.getPtr(ip_copy)) |limiter| {
return limiter.tryConsume();
}
return true;
}
/// SEC-M4 FIX: Evict the oldest (least recently active) IP limiter
fn evictOldestEntry(self: *ConnectionRateLimiter) void {
var oldest_ip: ?[]const u8 = null;
var oldest_time: i64 = std.math.maxInt(i64);
var iter = self.ip_last_activity.iterator();
while (iter.next()) |entry| {
if (entry.value_ptr.* < oldest_time) {
oldest_time = entry.value_ptr.*;
oldest_ip = entry.key_ptr.*;
}
}
if (oldest_ip) |ip| {
// Remove from both maps
_ = self.per_ip_limiters.remove(ip);
_ = self.ip_last_activity.remove(ip);
self.allocator.free(ip);
std.log.debug("SEC-M4: Evicted oldest IP rate limiter entry", .{});
}
}
/// Clean up stale per-IP limiters
pub fn cleanup(self: *ConnectionRateLimiter) void {
self.mutex.lock();
defer self.mutex.unlock();
var to_remove: std.ArrayList([]const u8) = .{};
defer to_remove.deinit(self.allocator);
// Pre-allocate capacity for cleanup list
to_remove.ensureTotalCapacity(self.allocator, self.per_ip_limiters.count()) catch |err| {
log.err("Failed to pre-allocate IP cleanup list (capacity {}): {}", .{ self.per_ip_limiters.count(), err });
};
var cleanup_failures: usize = 0;
var iter = self.per_ip_limiters.iterator();
while (iter.next()) |entry| {
// Remove limiters that have full tokens (no recent activity)
if (entry.value_ptr.getAvailableTokens() >= entry.value_ptr.max_tokens) {
to_remove.append(self.allocator, entry.key_ptr.*) catch |err| {
log.err("Failed to track stale IP limiter during cleanup: {}", .{err});
cleanup_failures += 1;
continue;
};
}
}
if (cleanup_failures > 0) {
std.log.warn("IP limiter cleanup encountered {} failures", .{cleanup_failures});
}
for (to_remove.items) |ip| {
_ = self.per_ip_limiters.remove(ip);
// SEC-M4 FIX: Also remove from activity tracking
_ = self.ip_last_activity.remove(ip);
self.allocator.free(ip);
}
}
};
test "RateLimiter basic functionality" {
var limiter = RateLimiter.init(.{
.tokens_per_second = 10,
.burst_size = 5,
});
// Should be able to consume burst
for (0..5) |_| {
try std.testing.expect(limiter.tryConsume());
}
// Should be rate limited now
try std.testing.expect(!limiter.tryConsume());
try std.testing.expect(limiter.isRateLimited());
}
test "RateLimiter consume multiple" {
var limiter = RateLimiter.init(.{
.tokens_per_second = 100,
.burst_size = 10,
});
// Consume 5 tokens
try std.testing.expect(limiter.tryConsumeN(5));
try std.testing.expectEqual(@as(u64, 5), limiter.getAvailableTokens());
// Can't consume 6 more
try std.testing.expect(!limiter.tryConsumeN(6));
// Can consume 5 more
try std.testing.expect(limiter.tryConsumeN(5));
}
test "PeerRateLimiter per-peer tracking" {
const allocator = std.testing.allocator;
var peer_limiter = PeerRateLimiter.init(allocator, .{
.tokens_per_second = 10,
.burst_size = 2,
});
defer peer_limiter.deinit();
const peer1 = [_]u8{1} ** 32;
const peer2 = [_]u8{2} ** 32;
// Each peer has independent limit
try std.testing.expect(peer_limiter.tryConsume(peer1));
try std.testing.expect(peer_limiter.tryConsume(peer1));
try std.testing.expect(!peer_limiter.tryConsume(peer1)); // rate limited
// peer2 should still have tokens
try std.testing.expect(peer_limiter.tryConsume(peer2));
}
test "RateLimiter.Config defaults" {
const config = RateLimiter.Config{};
try std.testing.expectEqual(@as(u64, 100), config.tokens_per_second);
try std.testing.expectEqual(@as(u64, 200), config.burst_size);
}
test "RateLimiter getAvailableTokens" {
var limiter = RateLimiter.init(.{
.tokens_per_second = 50,
.burst_size = 100,
});
// Initially should have burst_size tokens
try std.testing.expectEqual(@as(u64, 100), limiter.getAvailableTokens());
// After consuming some
_ = limiter.tryConsumeN(30);
try std.testing.expectEqual(@as(u64, 70), limiter.getAvailableTokens());
}
test "RateLimiter isRateLimited" {
var limiter = RateLimiter.init(.{
.tokens_per_second = 10,
.burst_size = 3,
});
// Initially not rate limited
try std.testing.expect(!limiter.isRateLimited());
// Consume all tokens
_ = limiter.tryConsumeN(3);
// Now should be rate limited
try std.testing.expect(limiter.isRateLimited());
}
test "RateLimiter tryConsumeN zero tokens" {
var limiter = RateLimiter.init(.{
.tokens_per_second = 10,
.burst_size = 5,
});
// Consuming 0 should always succeed
try std.testing.expect(limiter.tryConsumeN(0));
}
test "RateLimiter tryConsumeN more than available" {
var limiter = RateLimiter.init(.{
.tokens_per_second = 10,
.burst_size = 5,
});
// Try to consume more than available
try std.testing.expect(!limiter.tryConsumeN(10));
// Tokens should be unchanged
try std.testing.expectEqual(@as(u64, 5), limiter.getAvailableTokens());
}
test "PeerRateLimiter isRateLimited" {
const allocator = std.testing.allocator;
var peer_limiter = PeerRateLimiter.init(allocator, .{
.tokens_per_second = 10,
.burst_size = 2,
});
defer peer_limiter.deinit();
const peer1 = [_]u8{0xCD} ** 32;
// Initially not rate limited
try std.testing.expect(!peer_limiter.isRateLimited(peer1));
// Consume all tokens
_ = peer_limiter.tryConsume(peer1);
_ = peer_limiter.tryConsume(peer1);
// Now should be rate limited
try std.testing.expect(peer_limiter.isRateLimited(peer1));
}
test "PeerRateLimiter removePeer" {
const allocator = std.testing.allocator;
var peer_limiter = PeerRateLimiter.init(allocator, .{
.tokens_per_second = 10,
.burst_size = 5,
});
defer peer_limiter.deinit();
const peer1 = [_]u8{0x11} ** 32;
// Add peer by consuming
_ = peer_limiter.tryConsume(peer1);
try std.testing.expectEqual(@as(usize, 1), peer_limiter.getPeerCount());
// Remove peer
peer_limiter.removePeer(peer1);
try std.testing.expectEqual(@as(usize, 0), peer_limiter.getPeerCount());
}
test "PeerRateLimiter getPeerCount" {
const allocator = std.testing.allocator;
var peer_limiter = PeerRateLimiter.init(allocator, .{
.tokens_per_second = 10,
.burst_size = 5,
});
defer peer_limiter.deinit();
// Initially no peers
try std.testing.expectEqual(@as(usize, 0), peer_limiter.getPeerCount());
// Add peers
const peer1 = [_]u8{0x11} ** 32;
const peer2 = [_]u8{0x22} ** 32;
_ = peer_limiter.tryConsume(peer1);
try std.testing.expectEqual(@as(usize, 1), peer_limiter.getPeerCount());
_ = peer_limiter.tryConsume(peer2);
try std.testing.expectEqual(@as(usize, 2), peer_limiter.getPeerCount());
}
test "ConnectionRateLimiter basic operations" {
const allocator = std.testing.allocator;
var conn_limiter = ConnectionRateLimiter.init(
allocator,
.{ .tokens_per_second = 100, .burst_size = 10 },
.{ .tokens_per_second = 10, .burst_size = 3 },
);
defer conn_limiter.deinit();
// Should be able to accept connections initially
try std.testing.expect(conn_limiter.tryAcceptConnection("192.168.1.1"));
try std.testing.expect(conn_limiter.tryAcceptConnection("192.168.1.2"));
}
test "ConnectionRateLimiter cleanup" {
const allocator = std.testing.allocator;
var conn_limiter = ConnectionRateLimiter.init(
allocator,
.{ .tokens_per_second = 100, .burst_size = 10 },
.{ .tokens_per_second = 10, .burst_size = 3 },
);
defer conn_limiter.deinit();
// Add some IPs
_ = conn_limiter.tryAcceptConnection("10.0.0.1");
_ = conn_limiter.tryAcceptConnection("10.0.0.2");
// Cleanup should not crash
conn_limiter.cleanup();
}
test "RateLimiter Config custom values" {
const config = RateLimiter.Config{
.tokens_per_second = 50,
.burst_size = 20,
};
try std.testing.expectEqual(@as(u64, 50), config.tokens_per_second);
try std.testing.expectEqual(@as(u64, 20), config.burst_size);
}
test "RateLimiter refill adds tokens" {
var limiter = RateLimiter.init(.{ .tokens_per_second = 10, .burst_size = 100 });
// Consume some tokens
try std.testing.expect(limiter.tryConsume());
try std.testing.expect(limiter.tryConsume());
// Force refill by adjusting last_refill time (tokens should have been consumed)
const before = limiter.getAvailableTokens();
try std.testing.expect(before < 100);
}
test "ConnectionRateLimiter tryAcceptConnection" {
const allocator = std.testing.allocator;
var conn_limiter = ConnectionRateLimiter.init(
allocator,
.{ .tokens_per_second = 100, .burst_size = 10 },
.{ .tokens_per_second = 10, .burst_size = 5 },
);
defer conn_limiter.deinit();
// First few connections should succeed
try std.testing.expect(conn_limiter.tryAcceptConnection("192.168.1.1"));
try std.testing.expect(conn_limiter.tryAcceptConnection("192.168.1.2"));
}
test "PeerRateLimiter tryConsume returns result" {
const allocator = std.testing.allocator;
var peer_limiter = PeerRateLimiter.init(
allocator,
.{ .tokens_per_second = 100, .burst_size = 10 },
);
defer peer_limiter.deinit();
const peer_id = [_]u8{0x11} ** 32;
const result = peer_limiter.tryConsume(peer_id);
try std.testing.expect(result);
}

1534
src/core/socket.zig Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,642 @@
//! CRIT-8 FIX: Global Memory Tracking Allocator
//!
//! This allocator wraps another allocator and enforces a global memory budget.
//! It tracks all allocations atomically for thread safety and rejects allocations
//! that would exceed the configured limit.
//!
//! Usage:
//! var tracker = TrackingAllocator.init(base_allocator, max_bytes);
//! const allocator = tracker.allocator();
//! // Use allocator for all P2P operations
//! // Check tracker.allocated_bytes for current usage
const std = @import("std");
const Allocator = std.mem.Allocator;
const limits = @import("limits.zig");
/// Thread-safe global memory tracking allocator
pub const TrackingAllocator = struct {
/// The underlying allocator to forward requests to
backing_allocator: Allocator,
/// Maximum allowed bytes (from limits.memory.max_global_memory_quota)
max_bytes: u64,
/// Current allocated bytes (atomic for thread safety)
allocated_bytes: std.atomic.Value(u64),
/// Peak allocation (for diagnostics)
peak_bytes: std.atomic.Value(u64),
/// Number of rejected allocations (for diagnostics)
rejected_count: std.atomic.Value(u64),
/// Number of successful allocations (for diagnostics)
allocation_count: std.atomic.Value(u64),
/// Number of frees (for diagnostics)
free_count: std.atomic.Value(u64),
const Self = @This();
/// Initialize a tracking allocator with a backing allocator and memory limit
pub fn init(backing_allocator: Allocator, max_bytes: u64) Self {
return .{
.backing_allocator = backing_allocator,
.max_bytes = max_bytes,
.allocated_bytes = std.atomic.Value(u64).init(0),
.peak_bytes = std.atomic.Value(u64).init(0),
.rejected_count = std.atomic.Value(u64).init(0),
.allocation_count = std.atomic.Value(u64).init(0),
.free_count = std.atomic.Value(u64).init(0),
};
}
/// Initialize with default limits from global configuration
pub fn initWithDefaults(backing_allocator: Allocator) Self {
return init(backing_allocator, limits.global.memory.max_global_memory_quota);
}
/// Get the allocator interface
pub fn allocator(self: *Self) Allocator {
return .{
.ptr = self,
.vtable = &.{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
},
};
}
/// Remap implementation - delegates to backing allocator
fn remap(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
const old_size = buf.len;
if (new_len > old_size) {
// Growing - check if we have room
const delta = new_len - old_size;
while (true) {
const current = self.allocated_bytes.load(.acquire);
const new_total = current + delta;
if (new_total > self.max_bytes) {
_ = self.rejected_count.fetchAdd(1, .monotonic);
return null;
}
if (self.allocated_bytes.cmpxchgWeak(current, new_total, .acq_rel, .acquire)) |_| {
continue;
} else {
break;
}
}
// Try the actual remap
const result = self.backing_allocator.rawRemap(buf, buf_align, new_len, ret_addr);
if (result == null) {
// Failed - release reserved memory
_ = self.allocated_bytes.fetchSub(delta, .release);
return null;
}
// Update peak
const new_total_bytes = self.allocated_bytes.load(.monotonic);
while (true) {
const peak = self.peak_bytes.load(.monotonic);
if (new_total_bytes <= peak) break;
if (self.peak_bytes.cmpxchgWeak(peak, new_total_bytes, .monotonic, .monotonic)) |_| {
continue;
} else {
break;
}
}
return result;
} else if (new_len < old_size) {
// Shrinking - always allowed
const result = self.backing_allocator.rawRemap(buf, buf_align, new_len, ret_addr);
if (result != null) {
const delta = old_size - new_len;
_ = self.allocated_bytes.fetchSub(delta, .release);
}
return result;
} else {
// Same size
return buf.ptr;
}
}
/// Get current memory statistics
pub const Stats = struct {
allocated_bytes: u64,
max_bytes: u64,
peak_bytes: u64,
rejected_count: u64,
allocation_count: u64,
free_count: u64,
utilization_percent: f64,
};
pub fn getStats(self: *const Self) Stats {
const allocated = self.allocated_bytes.load(.monotonic);
return .{
.allocated_bytes = allocated,
.max_bytes = self.max_bytes,
.peak_bytes = self.peak_bytes.load(.monotonic),
.rejected_count = self.rejected_count.load(.monotonic),
.allocation_count = self.allocation_count.load(.monotonic),
.free_count = self.free_count.load(.monotonic),
.utilization_percent = if (self.max_bytes > 0)
@as(f64, @floatFromInt(allocated)) / @as(f64, @floatFromInt(self.max_bytes)) * 100.0
else
0.0,
};
}
/// Check if we can allocate the given number of bytes
pub fn canAllocate(self: *const Self, bytes: u64) bool {
const current = self.allocated_bytes.load(.monotonic);
return current + bytes <= self.max_bytes;
}
/// Get remaining available bytes
pub fn availableBytes(self: *const Self) u64 {
const current = self.allocated_bytes.load(.monotonic);
return if (current >= self.max_bytes) 0 else self.max_bytes - current;
}
fn alloc(ctx: *anyopaque, len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
const size = len;
// Try to reserve the memory atomically
while (true) {
const current = self.allocated_bytes.load(.acquire);
const new_total = current + size;
if (new_total > self.max_bytes) {
// Would exceed limit - reject allocation
_ = self.rejected_count.fetchAdd(1, .monotonic);
std.log.warn("CRIT-8: Memory allocation rejected: requested {d} bytes, current {d}/{d} bytes ({d:.1}% used)", .{
size,
current,
self.max_bytes,
@as(f64, @floatFromInt(current)) / @as(f64, @floatFromInt(self.max_bytes)) * 100.0,
});
return null;
}
// Try to atomically update the counter
if (self.allocated_bytes.cmpxchgWeak(current, new_total, .acq_rel, .acquire)) |_| {
// CAS failed, retry
continue;
} else {
// Successfully reserved memory
break;
}
}
// Update peak if necessary
const new_total = self.allocated_bytes.load(.monotonic);
while (true) {
const peak = self.peak_bytes.load(.monotonic);
if (new_total <= peak) break;
if (self.peak_bytes.cmpxchgWeak(peak, new_total, .monotonic, .monotonic)) |_| {
continue;
} else {
break;
}
}
// Perform the actual allocation
const result = self.backing_allocator.rawAlloc(len, ptr_align, ret_addr);
if (result == null) {
// Allocation failed - release the reserved memory
_ = self.allocated_bytes.fetchSub(size, .release);
std.log.debug("CRIT-8: Backing allocator failed for {d} bytes", .{size});
return null;
}
_ = self.allocation_count.fetchAdd(1, .monotonic);
return result;
}
fn resize(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
const self: *Self = @ptrCast(@alignCast(ctx));
const old_size = buf.len;
if (new_len > old_size) {
// Growing - check if we have room
const delta = new_len - old_size;
while (true) {
const current = self.allocated_bytes.load(.acquire);
const new_total = current + delta;
if (new_total > self.max_bytes) {
_ = self.rejected_count.fetchAdd(1, .monotonic);
std.log.warn("CRIT-8: Memory resize rejected: delta {d} bytes, current {d}/{d} bytes", .{
delta,
current,
self.max_bytes,
});
return false;
}
if (self.allocated_bytes.cmpxchgWeak(current, new_total, .acq_rel, .acquire)) |_| {
continue;
} else {
break;
}
}
// Try the actual resize
if (!self.backing_allocator.rawResize(buf, buf_align, new_len, ret_addr)) {
// Failed - release reserved memory
_ = self.allocated_bytes.fetchSub(delta, .release);
return false;
}
// Update peak
const new_total = self.allocated_bytes.load(.monotonic);
while (true) {
const peak = self.peak_bytes.load(.monotonic);
if (new_total <= peak) break;
if (self.peak_bytes.cmpxchgWeak(peak, new_total, .monotonic, .monotonic)) |_| {
continue;
} else {
break;
}
}
return true;
} else if (new_len < old_size) {
// Shrinking - always allowed
const delta = old_size - new_len;
if (self.backing_allocator.rawResize(buf, buf_align, new_len, ret_addr)) {
_ = self.allocated_bytes.fetchSub(delta, .release);
return true;
}
return false;
} else {
// Same size - no change needed
return true;
}
}
fn free(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, ret_addr: usize) void {
const self: *Self = @ptrCast(@alignCast(ctx));
const size = buf.len;
// Free from backing allocator
self.backing_allocator.rawFree(buf, buf_align, ret_addr);
// Release tracked memory
_ = self.allocated_bytes.fetchSub(size, .release);
_ = self.free_count.fetchAdd(1, .monotonic);
}
};
/// Global tracking allocator instance (optional singleton pattern)
var global_tracker: ?TrackingAllocator = null;
var global_tracker_mutex: std.Thread.Mutex = .{};
/// Initialize the global tracking allocator
/// Thread-safe, can be called multiple times (only first call takes effect)
pub fn initGlobal(backing_allocator: Allocator) *TrackingAllocator {
global_tracker_mutex.lock();
defer global_tracker_mutex.unlock();
if (global_tracker == null) {
global_tracker = TrackingAllocator.initWithDefaults(backing_allocator);
}
return &global_tracker.?;
}
/// Initialize the global tracking allocator with custom limit
pub fn initGlobalWithLimit(backing_allocator: Allocator, max_bytes: u64) *TrackingAllocator {
global_tracker_mutex.lock();
defer global_tracker_mutex.unlock();
if (global_tracker == null) {
global_tracker = TrackingAllocator.init(backing_allocator, max_bytes);
}
return &global_tracker.?;
}
/// Get the global tracking allocator (returns null if not initialized)
pub fn getGlobal() ?*TrackingAllocator {
global_tracker_mutex.lock();
defer global_tracker_mutex.unlock();
return if (global_tracker != null) &global_tracker.? else null;
}
/// Reset the global tracker (for testing)
pub fn resetGlobal() void {
global_tracker_mutex.lock();
defer global_tracker_mutex.unlock();
global_tracker = null;
}
test "TrackingAllocator basic operations" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1024 * 1024); // 1MB limit
const alloc = tracker.allocator();
// Basic allocation
const buf = try alloc.alloc(u8, 1000);
defer alloc.free(buf);
const stats = tracker.getStats();
try testing.expectEqual(@as(u64, 1000), stats.allocated_bytes);
try testing.expectEqual(@as(u64, 1), stats.allocation_count);
}
test "TrackingAllocator rejects over limit" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1000); // 1000 byte limit
const alloc = tracker.allocator();
// This should fail with OutOfMemory
const result = alloc.alloc(u8, 2000);
try testing.expectError(error.OutOfMemory, result);
const stats = tracker.getStats();
try testing.expectEqual(@as(u64, 1), stats.rejected_count);
}
test "TrackingAllocator tracks peak" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1024 * 1024);
const alloc = tracker.allocator();
const buf1 = try alloc.alloc(u8, 1000);
const buf2 = try alloc.alloc(u8, 2000);
alloc.free(buf1);
alloc.free(buf2);
const stats = tracker.getStats();
try testing.expectEqual(@as(u64, 0), stats.allocated_bytes);
try testing.expectEqual(@as(u64, 3000), stats.peak_bytes);
}
test "TrackingAllocator initWithDefaults" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.initWithDefaults(page_allocator);
const alloc = tracker.allocator();
// Should use limits from global config
try testing.expect(tracker.max_bytes > 0);
// Basic allocation should work
const buf = try alloc.alloc(u8, 100);
defer alloc.free(buf);
try testing.expectEqual(@as(u64, 100), tracker.allocated_bytes.load(.monotonic));
}
test "TrackingAllocator canAllocate" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1000);
const alloc = tracker.allocator();
// Initially can allocate up to limit
try testing.expect(tracker.canAllocate(500));
try testing.expect(tracker.canAllocate(1000));
try testing.expect(!tracker.canAllocate(1001));
// Allocate some memory
const buf = try alloc.alloc(u8, 600);
defer alloc.free(buf);
// Now can only allocate remaining
try testing.expect(tracker.canAllocate(400));
try testing.expect(!tracker.canAllocate(401));
}
test "TrackingAllocator availableBytes" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1000);
const alloc = tracker.allocator();
// Initially all bytes available
try testing.expectEqual(@as(u64, 1000), tracker.availableBytes());
// Allocate some memory
const buf = try alloc.alloc(u8, 300);
defer alloc.free(buf);
try testing.expectEqual(@as(u64, 700), tracker.availableBytes());
}
test "TrackingAllocator availableBytes at limit" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1000);
const alloc = tracker.allocator();
// Allocate exactly to limit
const buf = try alloc.alloc(u8, 1000);
defer alloc.free(buf);
try testing.expectEqual(@as(u64, 0), tracker.availableBytes());
}
test "TrackingAllocator resize grow" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 10000);
const alloc = tracker.allocator();
const buf = try alloc.alloc(u8, 100);
defer alloc.free(buf);
try testing.expectEqual(@as(u64, 100), tracker.allocated_bytes.load(.monotonic));
// Try to resize (may or may not succeed depending on allocator)
if (alloc.resize(buf, 200)) {
try testing.expectEqual(@as(u64, 200), tracker.allocated_bytes.load(.monotonic));
}
}
test "TrackingAllocator resize grow rejected over limit" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 150);
const alloc = tracker.allocator();
const buf = try alloc.alloc(u8, 100);
defer alloc.free(buf);
// Try to resize beyond limit - should fail
const resized = alloc.resize(buf, 200);
try testing.expect(!resized);
// Should have recorded rejection
const stats = tracker.getStats();
try testing.expect(stats.rejected_count >= 1);
}
test "TrackingAllocator resize shrink" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 10000);
const alloc = tracker.allocator();
const buf = try alloc.alloc(u8, 200);
defer alloc.free(buf);
try testing.expectEqual(@as(u64, 200), tracker.allocated_bytes.load(.monotonic));
// Shrinking should always be allowed
if (alloc.resize(buf, 100)) {
try testing.expectEqual(@as(u64, 100), tracker.allocated_bytes.load(.monotonic));
}
}
test "TrackingAllocator resize same size" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 10000);
const alloc = tracker.allocator();
const buf = try alloc.alloc(u8, 100);
defer alloc.free(buf);
// Resize to same size should succeed
const resized = alloc.resize(buf, 100);
try testing.expect(resized);
try testing.expectEqual(@as(u64, 100), tracker.allocated_bytes.load(.monotonic));
}
test "TrackingAllocator realloc" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 10000);
const alloc = tracker.allocator();
// Allocate initial buffer
const buf = try alloc.alloc(u8, 100);
try testing.expectEqual(@as(u64, 100), tracker.allocated_bytes.load(.monotonic));
// Realloc to larger size
const new_buf = try alloc.realloc(buf, 200);
defer alloc.free(new_buf);
try testing.expectEqual(@as(u64, 200), tracker.allocated_bytes.load(.monotonic));
}
test "TrackingAllocator getStats utilization" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 1000);
const alloc = tracker.allocator();
const buf = try alloc.alloc(u8, 500);
defer alloc.free(buf);
const stats = tracker.getStats();
try testing.expectEqual(@as(u64, 500), stats.allocated_bytes);
try testing.expectEqual(@as(u64, 1000), stats.max_bytes);
try testing.expect(stats.utilization_percent >= 49.0 and stats.utilization_percent <= 51.0);
}
test "TrackingAllocator getStats zero max" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 0);
const stats = tracker.getStats();
try testing.expectEqual(@as(f64, 0.0), stats.utilization_percent);
}
test "TrackingAllocator free count" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
var tracker = TrackingAllocator.init(page_allocator, 10000);
const alloc = tracker.allocator();
const buf1 = try alloc.alloc(u8, 100);
const buf2 = try alloc.alloc(u8, 200);
try testing.expectEqual(@as(u64, 2), tracker.allocation_count.load(.monotonic));
try testing.expectEqual(@as(u64, 0), tracker.free_count.load(.monotonic));
alloc.free(buf1);
try testing.expectEqual(@as(u64, 1), tracker.free_count.load(.monotonic));
alloc.free(buf2);
try testing.expectEqual(@as(u64, 2), tracker.free_count.load(.monotonic));
}
test "global tracker initGlobal" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
// Reset first to ensure clean state
resetGlobal();
// Initially null
try testing.expect(getGlobal() == null);
// Initialize - returns non-optional pointer
const tracker = initGlobal(page_allocator);
// Should return same instance on second call
const tracker2 = initGlobal(page_allocator);
try testing.expect(tracker == tracker2);
// getGlobal should return it (non-null)
try testing.expect(getGlobal() != null);
// Clean up
resetGlobal();
try testing.expect(getGlobal() == null);
}
test "global tracker initGlobalWithLimit" {
const testing = std.testing;
const page_allocator = std.heap.page_allocator;
// Reset first
resetGlobal();
// Initialize with custom limit
const tracker = initGlobalWithLimit(page_allocator, 5000);
try testing.expectEqual(@as(u64, 5000), tracker.max_bytes);
// Second call should return same instance (ignoring new limit)
const tracker2 = initGlobalWithLimit(page_allocator, 10000);
try testing.expect(tracker == tracker2);
try testing.expectEqual(@as(u64, 5000), tracker2.max_bytes); // Original limit preserved
// Clean up
resetGlobal();
}