Interface Transport

All Superinterfaces:
AutoCloseable
All Known Implementing Classes:
TcpTransport

public interface Transport extends AutoCloseable
Core transport abstraction for bidirectional byte streaming.

This interface provides a high-level, codec-agnostic API for network communication with support for zero-copy I/O using registered buffers. It abstracts over different I/O backends (io_uring, NIO) while exposing maximum performance.

Architecture

┌─────────────────────────────────────────────────────────┐
│                      Transport                          │
├─────────────────────────────────────────────────────────┤
│  • High-level API (connect, send, receive)             │
│  • Buffer pool management                               │
│  • Connection lifecycle                                 │
│  • Health monitoring                                    │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│                   TransportBackend                      │
├─────────────────────────────────────────────────────────┤
│  io_uring (Linux)  │  NIO (fallback)  │  XDP (future)  │
└─────────────────────────────────────────────────────────┘

Asynchronous Operation Model

All I/O operations are asynchronous and return a token for tracking:

  1. Submit: Call send(MemorySegment) or connect(SocketAddress)
  2. Track: Use the returned token to correlate with completions
  3. Complete: Receive callbacks via TransportHandler

Zero-Copy I/O

For maximum performance, use registered buffers:

RegisteredBuffer buffer = transport.acquireBuffer();
try {
    // Write data directly to off-heap memory
    buffer.segment().copyFrom(data);
    buffer.position(data.byteSize());
    buffer.flip();

    // Zero-copy send
    transport.send(buffer.segment());
} finally {
    buffer.close(); // Return to pool
}

Usage Example

TransportConfig config = TransportConfig.builder()
    .bufferCount(256)
    .bufferSize(65536)
    .build();

try (Transport transport = TransportFactory.create(config)) {
    transport.start(new TransportHandler() {
        @Override
        public void onConnect(long token, int result) {
            if (result >= 0) {
                System.out.println("Connected!");
            }
        }

        @Override
        public void onReceive(RegisteredBuffer buffer, int bytesReceived) {
            // Process received data
        }
    });

    transport.connect(new InetSocketAddress("localhost", 8080));

    // Event loop
    while (transport.isConnected()) {
        // Process completions...
    }
}

Thread Safety

Implementations must be thread-safe for concurrent I/O operations from multiple threads. Buffer acquisition and release are thread-safe.

See Also:
  • Method Details

    • connect

      long connect(SocketAddress remoteAddress)
      Initiates an asynchronous connection to a remote endpoint.

      The connection attempt runs asynchronously. When complete, the TransportHandler.onConnected(long) callback is invoked with the result (0 for success, negative errno for failure).

      Token Usage

      The returned token is passed to the completion handler and can be used to correlate this operation with application-level state.

      Parameters:
      remoteAddress - the remote address to connect to (e.g., InetSocketAddress)
      Returns:
      a token identifying this operation for correlation in completion callbacks
      Throws:
      TransportException - if the operation cannot be submitted
      See Also:
    • send

      long send(MemorySegment data)
      Sends data asynchronously.

      The send operation is queued and executed asynchronously. For best performance, use buffers obtained from acquireBuffer() which enables zero-copy I/O.

      Memory Ownership: The caller retains ownership of the data segment. The data is copied (or pinned for zero-copy) before this method returns, so the segment can be reused immediately.

      Parameters:
      data - the memory segment containing data to send
      Returns:
      a token identifying this operation for correlation in completion callbacks
      Throws:
      TransportException - if the operation cannot be submitted
      IllegalStateException - if not connected
      See Also:
    • start

      void start(TransportHandler handler)
      Starts the transport with the specified handler for receiving callbacks.

      This method must be called before any I/O operations. The handler receives all completion callbacks (connect, send, receive, errors).

      Lifecycle: After calling start, the transport is ready for I/O. Call close() to shut down cleanly.

      Parameters:
      handler - the callback handler for I/O completion events
      Throws:
      IllegalStateException - if already started
      TransportException - if initialization fails
    • acquireBuffer

      RegisteredBuffer acquireBuffer()
      Acquires a registered buffer for zero-copy I/O.

      Registered buffers are pre-validated by the kernel, eliminating per-operation address validation overhead. This provides approximately 1.7x throughput improvement with io_uring.

      Blocking Behavior: This method blocks if no buffers are available until one is released.

      Resource Management: Always release buffers via RegisteredBuffer.close() when done, typically in a try-with-resources block.

      Returns:
      a registered buffer from the pool, ready for use
      Throws:
      TransportException - if interrupted while waiting
      See Also:
    • availableBufferSpace

      int availableBufferSpace()
      Returns the number of buffers currently available in the pool.

      This can be used to implement backpressure or monitoring. Note that the value may change immediately after the call returns.

      Returns:
      the number of available buffers
    • getConnectionPool

      ConnectionPool getConnectionPool()
      Returns the connection pool managing connections for this transport.

      The connection pool tracks active connections and provides metrics about connection state.

      Returns:
      the connection pool (never null)
    • getHealth

      TransportHealth getHealth()
      Returns health metrics for this transport.

      Health information includes buffer utilization, error rates, and throughput metrics.

      Returns:
      transport health information (never null)
    • isConnected

      boolean isConnected()
      Checks if the transport has an active connection.
      Returns:
      true if connected to a remote endpoint
    • getLocalAddress

      SocketAddress getLocalAddress()
      Returns the local socket address.
      Returns:
      the local address, or null if not bound
    • getRemoteAddress

      SocketAddress getRemoteAddress()
      Returns the remote socket address.
      Returns:
      the remote address, or null if not connected
    • close

      void close()
      Closes the transport and releases all resources.

      This method:

      • Closes all active connections gracefully
      • Releases the buffer pool
      • Shuts down the I/O backend
      • Frees all off-heap memory

      After closing, the transport cannot be reused. Create a new instance if needed.

      Specified by:
      close in interface AutoCloseable