Package com.lucimber.dbus.netty
This package provides the concrete implementation of the D-Bus client using the Netty framework for efficient, asynchronous network communication. It handles low-level transport details including connection management, message framing, and protocol handling.
Getting Started
For first-time users: The main class you'll use is NettyConnection
.
Use NettyConnection.newSystemBusConnection()
or NettyConnection.newSessionBusConnection()
to create connections. Most other classes in this
package are internal implementation details.
Core Components
Connection Implementation
The NettyConnection
class provides the main entry point for D-Bus connections,
implementing the Connection
interface with Netty-based
transport:
// System bus connection
Connection systemBus = NettyConnection.newSystemBusConnection();
// Session bus connection
Connection sessionBus = NettyConnection.newSessionBusConnection();
// Custom connection with configuration
ConnectionConfig config = ConnectionConfig.builder()
.withAutoReconnectEnabled(true)
.withConnectTimeout(Duration.ofSeconds(10))
.build();
Connection connection = NettyConnection.newConnection(socketAddress, config);
Transport Configuration
The Netty transport can be configured for optimal performance:
// Configure transport-specific options
NettyConnectionConfig config = NettyConnectionConfig.builder()
.withChannelOption(ChannelOption.TCP_NODELAY, true)
.withChannelOption(ChannelOption.SO_KEEPALIVE, true)
.withChannelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.withWorkerThreads(4)
.withBossThreads(1)
.build();
Pipeline Architecture
The Netty implementation uses a handler pipeline for processing D-Bus messages:
// Pipeline structure (inbound direction):
Socket → FrameDecoder → MessageDecoder → AuthHandler → UserHandlers → Application
// Pipeline structure (outbound direction):
Application → UserHandlers → AuthHandler → MessageEncoder → FrameEncoder → Socket
Built-in Handlers
- Frame Decoder/Encoder: Handles D-Bus message framing
- Message Decoder/Encoder: Converts between bytes and D-Bus messages
- Authentication Handler: Manages SASL authentication
- Error Handler: Handles protocol and network errors
- Health Check Handler: Monitors connection health
Performance Features
Connection Pooling
// Connection pool for shared resources
ConnectionPool pool = NettyConnectionPool.builder()
.withMinConnections(2)
.withMaxConnections(10)
.withConnectionTimeout(Duration.ofSeconds(30))
.build();
Connection connection = pool.acquire();
try {
// Use connection
} finally {
pool.release(connection);
}
Native Transport
Automatic detection and use of native transport libraries:
// Uses epoll on Linux, kqueue on macOS, NIO on other platforms
TransportFactory factory = TransportFactory.getBestAvailable();
EventLoopGroup group = factory.createEventLoopGroup(4);
Message Processing
Asynchronous Operations
All operations are non-blocking and return CompletableFuture:
// Asynchronous connection establishment
CompletableFuture<Void> connectFuture = connection.connect();
// Asynchronous method calls
CompletableFuture<InboundMessage> responseFuture = connection.sendRequest(methodCall);
// Chaining operations
connectFuture
.thenCompose(v -> connection.sendRequest(methodCall))
.thenAccept(response -> processResponse(response))
.exceptionally(throwable -> {
handleError(throwable);
return null;
});
Backpressure Handling
Built-in backpressure mechanisms prevent memory overflow:
// Configure backpressure settings
NettyConnectionConfig config = NettyConnectionConfig.builder()
.withWriteBufferHighWaterMark(64 * 1024)
.withWriteBufferLowWaterMark(32 * 1024)
.withMaxPendingWrites(1000)
.build();
Error Handling
Comprehensive error handling for network and protocol issues:
// Connection event listener
connection.addConnectionEventListener((conn, event) -> {
switch (event.getType()) {
case CONNECTION_LOST:
System.err.println("Connection lost: " + event.getCause());
break;
case RECONNECTION_FAILED:
System.err.println("Reconnection failed: " + event.getCause());
break;
case PROTOCOL_ERROR:
System.err.println("Protocol error: " + event.getCause());
break;
}
});
Transport Types
Unix Domain Sockets
Primary transport for local D-Bus communication:
// Connect to system bus via Unix domain socket
SocketAddress systemBusAddress = new DomainSocketAddress("/var/run/dbus/system_bus_socket");
Connection connection = NettyConnection.newConnection(systemBusAddress);
TCP Sockets
Network transport for remote D-Bus communication:
// Connect to remote D-Bus daemon via TCP
SocketAddress tcpAddress = new InetSocketAddress("remote-host", 55556);
Connection connection = NettyConnection.newConnection(tcpAddress);
Resource Management
Proper resource cleanup and lifecycle management:
// Graceful shutdown
connection.close().toCompletableFuture().get(5, TimeUnit.SECONDS);
// Shutdown with timeout
connection.closeGracefully(Duration.ofSeconds(5))
.exceptionally(throwable -> {
// Force shutdown if graceful shutdown fails
connection.closeNow();
return null;
});
Monitoring and Debugging
Built-in support for monitoring and debugging:
// Enable wire-level logging
NettyConnectionConfig config = NettyConnectionConfig.builder()
.withWireLoggingEnabled(true)
.withWireLogLevel(LogLevel.DEBUG)
.build();
// Connection metrics
ConnectionMetrics metrics = connection.getMetrics();
System.out.println("Messages sent: " + metrics.getMessagesSent());
System.out.println("Messages received: " + metrics.getMessagesReceived());
System.out.println("Connection uptime: " + metrics.getUptime());
Thread Model
Netty's event-driven thread model provides high concurrency:
- Boss Thread: Accepts incoming connections
- Worker Threads: Handle I/O operations and message processing
- Application Threads: Handle user callbacks and business logic
// Custom thread pool configuration
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(4);
NettyConnectionConfig config = NettyConnectionConfig.builder()
.withBossGroup(bossGroup)
.withWorkerGroup(workerGroup)
.build();
- Since:
- 1.0
- See Also:
-
ClassDescriptionCentralized configuration for D-Bus pipeline handlers.Utility class containing standardized names for D-Bus pipeline handlers.After SASL authentication completes and the DBus message pipeline is configured, this handler sends the mandatory org.freedesktop.DBus.Hello method call to request a unique bus name.Netty-based implementation of ConnectionHandle.Netty-based connection strategy for TCP transport.Netty-based connection strategy for Unix domain socket transport.The critical bridge between the Netty pipeline and public API pipeline systems.Handler responsible for managing pipeline handlers during reconnection.WriteOperationListener<T extends io.netty.util.concurrent.Future<?>>A
GenericFutureListener
that provides consistent logging for write operations and optionally chains custom completion logic.