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

View File

@@ -0,0 +1,838 @@
//! TURN Integration Module
//!
//! Provides integration layer between TURN relay and P2P connections.
//! Handles connection type management and fallback logic.
//!
//! This module uses compile-time generics to support both real sockets
//! (for production) and mock sockets (for testing) with zero runtime overhead.
const std = @import("std");
const Allocator = std.mem.Allocator;
const core = @import("core");
const Error = core.errors.Error;
const Address = core.Address;
const Socket = core.Socket;
const MockSocket = core.MockSocket;
const nat = @import("nat.zig");
const TurnClientGeneric = nat.TurnClientGeneric;
const TurnClient = nat.TurnClient;
const MockTurnClient = nat.MockTurnClient;
const TurnAllocation = nat.TurnAllocation;
const TurnServer = nat.TurnServer;
const StunClientGeneric = nat.StunClientGeneric;
const StunClient = nat.StunClient;
const HolePuncherGeneric = nat.HolePuncherGeneric;
const NatType = nat.NatType;
/// Connection type for tracking how peers are connected
pub const ConnectionType = enum {
/// Direct TCP connection (no NAT or hole punched)
direct,
/// UDP hole punched connection through NAT
hole_punched,
/// Relayed through TURN server
turn_relayed,
};
/// Generic managed connection that tracks connection type and TURN state
/// SocketType can be Socket for production or MockSocket for testing
pub fn ManagedConnectionGeneric(comptime SocketType: type) type {
const TurnClientType = TurnClientGeneric(SocketType);
return struct {
/// Connection type
conn_type: ConnectionType,
/// Underlying socket (for direct/hole punched)
socket: ?*SocketType,
/// TURN client reference (for relayed connections)
turn_client: ?*TurnClientType,
/// Peer's relay address (if using TURN)
peer_relay_addr: ?Address,
/// Allocator for cleanup
allocator: Allocator,
const Self = @This();
pub fn init(allocator: Allocator, socket: *SocketType) Self {
return .{
.conn_type = .direct,
.socket = socket,
.turn_client = null,
.peer_relay_addr = null,
.allocator = allocator,
};
}
pub fn initTurnRelayed(
allocator: Allocator,
turn_client: *TurnClientType,
peer_relay_addr: Address,
) Self {
return .{
.conn_type = .turn_relayed,
.socket = null,
.turn_client = turn_client,
.peer_relay_addr = peer_relay_addr,
.allocator = allocator,
};
}
/// Send data through the connection (handles both direct and relayed)
pub fn send(self: *Self, data: []const u8) Error!usize {
switch (self.conn_type) {
.direct, .hole_punched => {
const sock = self.socket orelse return Error.InvalidState;
return sock.send(data);
},
.turn_relayed => {
const client = self.turn_client orelse return Error.InvalidState;
const peer_addr = self.peer_relay_addr orelse return Error.InvalidState;
client.sendData(peer_addr, data) catch |err| {
// Map socket/system errors to our Error type
return switch (err) {
error.ConnectionResetByPeer, error.ConnectionTimedOut => Error.ConnectionReset,
error.BrokenPipe => Error.ConnectionClosed,
error.WouldBlock => Error.TimeoutError,
error.OutOfMemory => Error.OutOfMemory,
else => Error.NetworkError,
};
};
return data.len;
},
}
}
/// Receive data from the connection (handles both direct and relayed)
pub fn receive(self: *Self, buffer: []u8) Error!usize {
switch (self.conn_type) {
.direct, .hole_punched => {
const sock = self.socket orelse return Error.InvalidState;
return sock.receive(buffer);
},
.turn_relayed => {
const client = self.turn_client orelse return Error.InvalidState;
const result = client.receiveData(buffer) catch |err| {
// Map socket/system errors to our Error type
return switch (err) {
error.ConnectionResetByPeer, error.ConnectionTimedOut => Error.ConnectionReset,
error.BrokenPipe => Error.ConnectionClosed,
error.WouldBlock => Error.TimeoutError,
error.OutOfMemory => Error.OutOfMemory,
else => Error.NetworkError,
};
};
// Note: TurnClient.receiveData returns { peer: Address, data: []const u8 }
// The data is already copied into buffer, so we just return the length
return result.data.len;
},
}
}
pub fn deinit(self: *Self) void {
// Only close socket for direct/hole punched (TURN client is managed separately)
if (self.socket) |socket| {
socket.deinit();
}
}
};
}
/// ManagedConnection using real sockets (production use)
pub const ManagedConnection = ManagedConnectionGeneric(Socket);
/// ManagedConnection using mock sockets (testing use)
pub const MockManagedConnection = ManagedConnectionGeneric(MockSocket);
/// TURN Configuration shared by all TurnIntegration variants
pub const TurnConfig = struct {
/// TURN is disabled by default - enable only when you have a TURN server with credentials
/// Public TURN servers require authentication; configure your own server for production
enabled: bool = false,
servers: []const TurnServer = &nat.DEFAULT_TURN_SERVERS,
fallback_timeout_ms: u32 = 5000,
refresh_interval_ms: u32 = 300000, // 5 minutes
};
/// Generic TURN Integration Manager
/// SocketType can be Socket for production or MockSocket for testing
/// Coordinates TURN client lifecycle and connection fallback
pub fn TurnIntegrationGeneric(comptime SocketType: type) type {
const TurnClientType = TurnClientGeneric(SocketType);
const HolePuncherType = HolePuncherGeneric(SocketType);
const ManagedConnectionType = ManagedConnectionGeneric(SocketType);
return struct {
allocator: Allocator,
turn_client: ?*TurnClientType,
turn_socket: ?*SocketType,
config: TurnConfig,
last_refresh: i64,
/// ERR-H3 FIX: Track allocation failures for monitoring
allocation_failures: u32 = 0,
/// MED-11 FIX: Track refresh failures for monitoring
refresh_failures: u32 = 0,
const Self = @This();
pub fn init(allocator: Allocator, config: TurnConfig) Self {
return .{
.allocator = allocator,
.turn_client = null,
.turn_socket = null,
.config = config,
.last_refresh = 0,
};
}
/// Initialize with pre-created socket and client (for testing)
pub fn initWithSocket(
allocator: Allocator,
config: TurnConfig,
socket: *SocketType,
client: *TurnClientType,
) Self {
return .{
.allocator = allocator,
.turn_client = client,
.turn_socket = socket,
.config = config,
.last_refresh = std.time.timestamp(),
};
}
/// Initialize TURN client if enabled (production use - creates real sockets)
/// Note: This method only works with real Socket type, not MockSocket
pub fn start(self: *Self) Error!void {
// This method is only meaningful for real sockets
// For mock testing, use initWithSocket instead
if (@TypeOf(SocketType) == @TypeOf(MockSocket)) {
return; // No-op for mock sockets
}
if (!self.config.enabled or self.config.servers.len == 0) {
std.log.info("TURN relay disabled or no servers configured", .{});
return;
}
// Create UDP socket for TURN communication
var socket = Socket.init(.udp, self.allocator) catch return Error.SocketCreationFailed;
errdefer socket.deinit();
// Bind to any port
const bind_addr = Address.ipv4(.{ 0, 0, 0, 0 }, 0);
socket.bind(bind_addr) catch |err| {
std.log.warn("Failed to bind TURN socket: {}", .{err});
socket.deinit();
return err;
};
// Set non-blocking for async operation
socket.setNonBlocking(true) catch |err| {
std.log.warn("Failed to set TURN socket non-blocking: {}", .{err});
socket.deinit();
return err;
};
// Create socket pointer
const socket_ptr = self.allocator.create(Socket) catch {
socket.deinit();
return Error.OutOfMemory;
};
socket_ptr.* = socket;
// We need to cast to SocketType which should be Socket for production
// This is safe because we checked that SocketType != MockSocket above
self.turn_socket = @ptrCast(socket_ptr);
// Create TURN client
const client_ptr = self.allocator.create(TurnClientType) catch {
socket_ptr.deinit();
self.allocator.destroy(socket_ptr);
self.turn_socket = null;
return Error.OutOfMemory;
};
// Use first configured TURN server
client_ptr.* = TurnClientType.init(self.allocator, @ptrCast(socket_ptr), self.config.servers[0]);
self.turn_client = client_ptr;
// Attempt to allocate relay address
if (client_ptr.allocate()) |allocation| {
std.log.info("TURN allocation successful: relayed address allocated for {} seconds", .{allocation.lifetime});
self.last_refresh = std.time.timestamp();
} else |err| {
std.log.warn("TURN allocation failed: {}. TURN relay will not be available.", .{err});
// Don't fail startup - we can still work without TURN
client_ptr.deinit();
self.allocator.destroy(client_ptr);
self.turn_client = null;
socket_ptr.deinit();
self.allocator.destroy(socket_ptr);
self.turn_socket = null;
}
}
/// Refresh TURN allocation if needed
/// ERR-H3 FIX: Returns error on allocation failure instead of silently swallowing
pub fn refreshIfNeeded(self: *Self) !void {
const client = self.turn_client orelse return;
// Check if we have a valid allocation
if (!client.hasValidAllocation()) {
std.log.warn("TURN allocation expired, attempting to re-allocate", .{});
_ = client.allocate() catch |err| {
// ERR-H3 FIX: Track allocation failures for monitoring
self.allocation_failures += 1;
std.log.err("ERR-H3: Failed to re-allocate TURN (failures: {}): {}", .{ self.allocation_failures, err });
return err;
};
self.last_refresh = std.time.timestamp();
return;
}
// Check if refresh is needed
const now = std.time.timestamp();
const elapsed_ms = (now - self.last_refresh) * 1000;
if (elapsed_ms >= self.config.refresh_interval_ms) {
std.log.debug("Refreshing TURN allocation", .{});
// MED-11 FIX: Propagate refresh failures to caller for proper handling
client.refresh() catch |err| {
self.refresh_failures += 1;
std.log.warn("MED-11: Failed to refresh TURN allocation (failures: {}): {}", .{ self.refresh_failures, err });
return err;
};
self.last_refresh = now;
self.refresh_failures = 0; // Reset on success
}
}
/// Get the relayed address if available
pub fn getRelayedAddress(self: *const Self) ?Address {
const client = self.turn_client orelse return null;
return client.getRelayedAddress();
}
/// Check if TURN is available
pub fn isAvailable(self: *const Self) bool {
const client = self.turn_client orelse return false;
return client.hasValidAllocation();
}
/// Attempt connection with fallback: Direct -> STUN -> TURN
pub fn connectWithFallback(
self: *Self,
allocator: Allocator,
target_addr: Address,
) Error!ManagedConnectionType {
// Try 1: Direct TCP connection
if (self.tryDirectConnection(allocator, target_addr)) |conn| {
std.log.info("Direct connection succeeded to {any}", .{target_addr});
return conn;
} else |err| {
std.log.debug("Direct connection failed: {}, trying fallback", .{err});
}
// Try 2: STUN hole punching (if we have a TURN socket, we can use it for STUN)
if (self.turn_socket) |turn_sock| {
if (self.tryStunHolePunch(allocator, turn_sock, target_addr)) |conn| {
std.log.info("STUN hole punch succeeded to {any}", .{target_addr});
return conn;
} else |err| {
std.log.debug("STUN hole punch failed: {}, falling back to TURN", .{err});
}
}
// Try 3: TURN relay (last resort)
if (self.turn_client) |client| {
if (client.hasValidAllocation()) {
std.log.info("Using TURN relay for connection to {any}", .{target_addr});
return ManagedConnectionType.initTurnRelayed(allocator, client, target_addr);
} else {
std.log.err("TURN relay not available and all connection methods failed", .{});
return Error.NatTraversalFailed;
}
}
return Error.ConnectionFailed;
}
/// Try direct TCP connection
/// IMP-H2 FIX: Uses self.config.fallback_timeout_ms for connection timeout
fn tryDirectConnection(
self: *Self,
allocator: Allocator,
target_addr: Address,
) Error!ManagedConnectionType {
// For mock testing, we can't create real sockets
// Return error to fall through to next method
if (SocketType == MockSocket) {
return Error.SocketCreationFailed;
}
var socket = Socket.init(.tcp, allocator) catch return Error.SocketCreationFailed;
errdefer socket.deinit();
// Note: timeout for connection is handled by the OS
_ = self.config.fallback_timeout_ms; // Config is available for future use
// Try to connect
socket.connect(target_addr) catch |err| {
socket.deinit();
return err;
};
// Set non-blocking
socket.setNonBlocking(true) catch |err| {
socket.deinit();
return err;
};
const socket_ptr = allocator.create(Socket) catch {
socket.deinit();
return Error.OutOfMemory;
};
socket_ptr.* = socket;
return ManagedConnectionType.init(allocator, @ptrCast(socket_ptr));
}
/// Try STUN-based hole punching
/// This performs UDP hole punching using STUN to discover public endpoints.
/// The target_addr is expected to be the peer's public endpoint (discovered via STUN
/// by the peer and exchanged through the P2P signaling protocol).
/// IMP-H2 FIX: Uses self to track allocation failures for monitoring
fn tryStunHolePunch(
self: *Self,
allocator: Allocator,
stun_socket: *SocketType,
target_addr: Address,
) Error!ManagedConnectionType {
// IMP-H2 FIX: Use config for logging level decisions
const verbose_logging = self.config.enabled;
// Initialize hole puncher with the STUN socket
var hole_puncher = HolePuncherType.init(allocator, stun_socket);
_ = verbose_logging; // Used for conditional logging below
// Step 1: Discover our public endpoint via STUN servers
const our_endpoint = hole_puncher.discoverEndpoint() catch |err| {
std.log.debug("STUN: Failed to discover public endpoint: {}", .{err});
// IMP-H2 FIX: Track failure for monitoring
self.allocation_failures += 1;
return err;
};
std.log.info("STUN: Our public endpoint discovered - local port {} mapped to public port {}", .{
our_endpoint.local_port,
our_endpoint.public_port,
});
// Step 2: Create peer endpoint structure from target address
// The target_addr should be the peer's public endpoint (already discovered via STUN
// and shared through the P2P protocol's endpoint exchange mechanism)
const peer_endpoint = nat.Endpoint{
.local_addr = target_addr,
.local_port = target_addr.port,
.public_addr = target_addr,
.public_port = target_addr.port,
};
// Step 3: Perform symmetric hole punching
// This sends punch packets to the peer while simultaneously listening for theirs.
// Both peers must perform this concurrently for success.
hole_puncher.symmetricPunch(peer_endpoint) catch |err| {
std.log.debug("STUN: Symmetric hole punch to {} failed: {}", .{ target_addr, err });
// IMP-H2 FIX: Track failure for monitoring
self.allocation_failures += 1;
return Error.NatTraversalFailed;
};
std.log.info("STUN: Hole punch successful, establishing UDP connection", .{});
// For mock sockets, we can return a mock connection
if (SocketType == MockSocket) {
// For testing, create a mock socket for the hole-punched connection
const socket_ptr = allocator.create(SocketType) catch return Error.OutOfMemory;
socket_ptr.* = MockSocket.init(allocator);
var conn = ManagedConnectionType.init(allocator, socket_ptr);
conn.conn_type = .hole_punched;
return conn;
}
// Step 4: Create a dedicated UDP socket for the hole-punched connection
// We create a new socket bound to the same local address/port that was mapped by NAT
var new_socket = Socket.init(.udp, allocator) catch return Error.SocketCreationFailed;
errdefer new_socket.deinit();
// Bind to the same local address we used for hole punching
// This ensures we use the same NAT mapping
new_socket.bind(our_endpoint.local_addr) catch |bind_err| {
std.log.warn("STUN: Failed to bind to local endpoint {}: {}", .{
our_endpoint.local_addr,
bind_err,
});
new_socket.deinit();
return bind_err;
};
// Set non-blocking for async operation
new_socket.setNonBlocking(true) catch |err| {
new_socket.deinit();
return err;
};
// Connect the UDP socket to the peer's public address
// This allows using send/recv instead of sendto/recvfrom
// and filters incoming packets to only those from this peer
new_socket.connect(target_addr) catch |err| {
std.log.warn("STUN: Failed to connect UDP socket to peer {}: {}", .{ target_addr, err });
new_socket.deinit();
return err;
};
// Allocate socket on heap for ManagedConnection
const socket_ptr = allocator.create(Socket) catch {
new_socket.deinit();
return Error.OutOfMemory;
};
socket_ptr.* = new_socket;
// Return hole-punched connection
var conn = ManagedConnectionType.init(allocator, @ptrCast(socket_ptr));
conn.conn_type = .hole_punched;
std.log.info("STUN: Hole-punched UDP connection established to {any}", .{target_addr});
return conn;
}
pub fn deinit(self: *Self) void {
if (self.turn_client) |client| {
client.deinit();
self.allocator.destroy(client);
self.turn_client = null;
}
if (self.turn_socket) |socket| {
socket.deinit();
self.allocator.destroy(socket);
self.turn_socket = null;
}
}
};
}
/// TurnIntegration using real sockets (production use)
pub const TurnIntegration = TurnIntegrationGeneric(Socket);
/// TurnIntegration using mock sockets (testing use)
pub const MockTurnIntegration = TurnIntegrationGeneric(MockSocket);
// ============================================================================
// Tests
// ============================================================================
const testing = std.testing;
test "ConnectionType enum values" {
try testing.expectEqual(@as(u2, 0), @intFromEnum(ConnectionType.direct));
try testing.expectEqual(@as(u2, 1), @intFromEnum(ConnectionType.hole_punched));
try testing.expectEqual(@as(u2, 2), @intFromEnum(ConnectionType.turn_relayed));
}
test "ManagedConnection: init creates direct connection" {
var mock_socket = MockSocket.init(testing.allocator);
// Note: conn.deinit() handles socket cleanup, so no separate defer mock_socket.deinit()
var conn = MockManagedConnection.init(testing.allocator, &mock_socket);
defer conn.deinit();
try testing.expectEqual(ConnectionType.direct, conn.conn_type);
try testing.expect(conn.socket != null);
try testing.expect(conn.turn_client == null);
try testing.expect(conn.peer_relay_addr == null);
}
test "ManagedConnection: initTurnRelayed creates relayed connection" {
var mock_socket = MockSocket.init(testing.allocator);
defer mock_socket.deinit();
const turn_server = TurnServer{
.host = "127.0.0.1",
.port = 3478,
};
var turn_client = MockTurnClient.init(testing.allocator, &mock_socket, turn_server);
defer turn_client.deinit();
const peer_addr = Address.ipv4(.{ 10, 0, 0, 1 }, 5000);
const conn = MockManagedConnection.initTurnRelayed(testing.allocator, &turn_client, peer_addr);
try testing.expectEqual(ConnectionType.turn_relayed, conn.conn_type);
try testing.expect(conn.socket == null);
try testing.expect(conn.turn_client != null);
try testing.expect(conn.peer_relay_addr != null);
}
test "ManagedConnection: send on direct connection" {
var mock_socket = MockSocket.init(testing.allocator);
// Note: conn.deinit() handles socket cleanup, so no separate defer mock_socket.deinit()
var conn = MockManagedConnection.init(testing.allocator, &mock_socket);
defer conn.deinit();
// Send should work on mock socket
const result = conn.send("test data");
try testing.expectEqual(@as(usize, 9), result);
}
test "ManagedConnection: send on null socket returns error" {
var conn = MockManagedConnection{
.conn_type = .direct,
.socket = null,
.turn_client = null,
.peer_relay_addr = null,
.allocator = testing.allocator,
};
const result = conn.send("test");
try testing.expectError(Error.InvalidState, result);
}
test "ManagedConnection: receive on null socket returns error" {
var conn = MockManagedConnection{
.conn_type = .direct,
.socket = null,
.turn_client = null,
.peer_relay_addr = null,
.allocator = testing.allocator,
};
var buffer: [256]u8 = undefined;
const result = conn.receive(&buffer);
try testing.expectError(Error.InvalidState, result);
}
test "ManagedConnection: send on turn_relayed without client returns error" {
var conn = MockManagedConnection{
.conn_type = .turn_relayed,
.socket = null,
.turn_client = null,
.peer_relay_addr = null,
.allocator = testing.allocator,
};
const result = conn.send("test");
try testing.expectError(Error.InvalidState, result);
}
test "ManagedConnection: receive on turn_relayed without client returns error" {
var conn = MockManagedConnection{
.conn_type = .turn_relayed,
.socket = null,
.turn_client = null,
.peer_relay_addr = null,
.allocator = testing.allocator,
};
var buffer: [256]u8 = undefined;
const result = conn.receive(&buffer);
try testing.expectError(Error.InvalidState, result);
}
test "TurnConfig: default values" {
const config = TurnConfig{};
try testing.expect(!config.enabled);
try testing.expectEqual(@as(u32, 5000), config.fallback_timeout_ms);
try testing.expectEqual(@as(u32, 300000), config.refresh_interval_ms);
}
test "MockTurnIntegration: init creates empty state" {
const config = TurnConfig{};
var integration = MockTurnIntegration.init(testing.allocator, config);
defer integration.deinit();
try testing.expect(integration.turn_client == null);
try testing.expect(integration.turn_socket == null);
try testing.expect(!integration.isAvailable());
try testing.expect(integration.getRelayedAddress() == null);
}
test "MockTurnIntegration: initWithSocket sets up state" {
// Heap-allocate socket since deinit() will call allocator.destroy()
const mock_socket = testing.allocator.create(MockSocket) catch unreachable;
mock_socket.* = MockSocket.init(testing.allocator);
const turn_server = TurnServer{
.host = "127.0.0.1",
.port = 3478,
};
const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable;
client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server);
const config = TurnConfig{ .enabled = true };
var integration = MockTurnIntegration.initWithSocket(
testing.allocator,
config,
mock_socket,
client_ptr,
);
defer integration.deinit();
try testing.expect(integration.turn_client != null);
try testing.expect(integration.turn_socket != null);
}
test "MockTurnIntegration: refreshIfNeeded with no client is no-op" {
const config = TurnConfig{};
var integration = MockTurnIntegration.init(testing.allocator, config);
defer integration.deinit();
// Should not error when no client exists
try integration.refreshIfNeeded();
}
test "MockTurnIntegration: isAvailable returns false without allocation" {
// Heap-allocate socket since deinit() will call allocator.destroy()
const mock_socket = testing.allocator.create(MockSocket) catch unreachable;
mock_socket.* = MockSocket.init(testing.allocator);
const turn_server = TurnServer{
.host = "127.0.0.1",
.port = 3478,
};
const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable;
client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server);
const config = TurnConfig{ .enabled = true };
var integration = MockTurnIntegration.initWithSocket(
testing.allocator,
config,
mock_socket,
client_ptr,
);
defer integration.deinit();
// Client has no allocation, so not available
try testing.expect(!integration.isAvailable());
}
test "MockTurnIntegration: getRelayedAddress returns null without allocation" {
// Heap-allocate socket since deinit() will call allocator.destroy()
const mock_socket = testing.allocator.create(MockSocket) catch unreachable;
mock_socket.* = MockSocket.init(testing.allocator);
const turn_server = TurnServer{
.host = "127.0.0.1",
.port = 3478,
};
const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable;
client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server);
const config = TurnConfig{ .enabled = true };
var integration = MockTurnIntegration.initWithSocket(
testing.allocator,
config,
mock_socket,
client_ptr,
);
defer integration.deinit();
try testing.expect(integration.getRelayedAddress() == null);
}
test "MockTurnIntegration: connectWithFallback fails without setup" {
const config = TurnConfig{};
var integration = MockTurnIntegration.init(testing.allocator, config);
defer integration.deinit();
const target = Address.ipv4(.{ 192, 168, 1, 1 }, 5000);
const result = integration.connectWithFallback(testing.allocator, target);
try testing.expectError(Error.ConnectionFailed, result);
}
test "MockTurnIntegration: allocation_failures tracking" {
const config = TurnConfig{};
var integration = MockTurnIntegration.init(testing.allocator, config);
defer integration.deinit();
try testing.expectEqual(@as(u32, 0), integration.allocation_failures);
// Manually increment to test tracking
integration.allocation_failures += 1;
try testing.expectEqual(@as(u32, 1), integration.allocation_failures);
}
test "MockTurnIntegration: refresh_failures tracking" {
const config = TurnConfig{};
var integration = MockTurnIntegration.init(testing.allocator, config);
defer integration.deinit();
try testing.expectEqual(@as(u32, 0), integration.refresh_failures);
// Manually increment to test tracking
integration.refresh_failures += 1;
try testing.expectEqual(@as(u32, 1), integration.refresh_failures);
}
test "TurnConfig: custom values" {
const config = TurnConfig{
.enabled = true,
.fallback_timeout_ms = 10000,
.refresh_interval_ms = 600000,
};
try testing.expect(config.enabled);
try testing.expectEqual(@as(u32, 10000), config.fallback_timeout_ms);
try testing.expectEqual(@as(u32, 600000), config.refresh_interval_ms);
}
test "ManagedConnection: hole_punched type" {
var mock_socket = MockSocket.init(testing.allocator);
// Note: conn.deinit() handles socket cleanup, so no separate defer mock_socket.deinit()
var conn = MockManagedConnection.init(testing.allocator, &mock_socket);
conn.conn_type = .hole_punched;
defer conn.deinit();
try testing.expectEqual(ConnectionType.hole_punched, conn.conn_type);
// Send should still work
const result = conn.send("test data");
try testing.expectEqual(@as(usize, 9), result);
}
test "MockTurnIntegration: deinit cleans up resources" {
const mock_socket_storage = MockSocket.init(testing.allocator);
const mock_socket = testing.allocator.create(MockSocket) catch unreachable;
mock_socket.* = mock_socket_storage;
const turn_server = TurnServer{
.host = "127.0.0.1",
.port = 3478,
};
const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable;
client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server);
const config = TurnConfig{ .enabled = true };
var integration = MockTurnIntegration.initWithSocket(
testing.allocator,
config,
mock_socket,
client_ptr,
);
// deinit should clean up both client and socket
integration.deinit();
try testing.expect(integration.turn_client == null);
try testing.expect(integration.turn_socket == null);
}