Separate Connection, ConnectionHandler, Server

This commit is contained in:
2025-08-19 13:23:18 -04:00
parent addac1b0b7
commit cb322bbb2b
7 changed files with 888 additions and 492 deletions

View File

@@ -0,0 +1,72 @@
#pragma once
#include <memory>
#include <string_view>
// Forward declaration to avoid circular dependency
struct Connection;
enum class ProcessResult {
Continue, // Keep connection open, continue processing
CloseAfterSend, // Send response then close connection
CloseNow // Close connection immediately
};
/**
* Abstract interface for handling connection data processing.
*
* This interface decouples protocol-specific logic (HTTP, WebSocket, etc.)
* from the underlying networking infrastructure. Implementations handle
* parsing incoming data and generating appropriate responses.
*
* The networking layer manages connection lifecycle, I/O multiplexing,
* and efficient data transfer, while handlers focus purely on protocol logic.
*/
class ConnectionHandler {
public:
virtual ~ConnectionHandler() = default;
/**
* Process incoming data from a connection.
*
* @param data Incoming data buffer (may be partial message)
* @param conn_ptr Unique pointer to connection - handler can take ownership
* by releasing it
* @return ProcessResult indicating how to handle the connection
*
* Implementation should:
* - Parse incoming data using arena allocator when needed
* - Use conn_ptr->appendMessage() to queue response data
* - Return appropriate ProcessResult for connection management
* - Handle partial messages and streaming protocols appropriately
* - Can take ownership by calling conn_ptr.release() to pass to other threads
* - If ownership is taken, handler must call conn->releaseBackToServer() when
* done
*/
virtual ProcessResult process_data(std::string_view data,
std::unique_ptr<Connection> &conn_ptr) = 0;
/**
* Called when a new connection is established.
*
* @param conn Newly established connection
*
* Use this for:
* - Connection-specific initialization
* - Sending greeting messages
* - Setting up connection state
*/
virtual void on_connection_established(Connection &) {}
/**
* Called when a connection is about to be closed.
*
* @param conn Connection being closed
*
* Use this for:
* - Cleanup of connection-specific resources
* - Logging connection statistics
* - Finalizing protocol state
*/
virtual void on_connection_closed(Connection &) {}
};