MayaFlux 0.1.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
Server.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <expected>
4#ifdef MAYAFLUX_PLATFORM_WINDOWS
5#include <winsock2.h>
6#include <ws2tcpip.h>
7#else
8#include <netinet/in.h>
9#endif // MAYAFLUX_PLATFORM_WINDOWS
10
11#include "EventBus.hpp"
12#include "ServerThread.hpp"
13
14namespace Lila {
15
16/**
17 * @class Server
18 * @brief TCP server for interactive live coding sessions in MayaFlux
19 *
20 * The Server class provides the underlying network infrastructure for Lila's live coding capabilities.
21 * It manages client connections, message handling, session management, and event broadcasting.
22 * While end users interact with MayaFlux through higher-level interfaces, Server enables
23 * real-time code evaluation and communication between clients and the interpreter.
24 *
25 * ## Core Responsibilities
26 * - Accepts TCP client connections and manages their lifecycle
27 * - Receives code snippets or control messages from clients
28 * - Dispatches messages to the interpreter and returns results
29 * - Tracks client sessions and broadcasts events (e.g., connection, evaluation, errors)
30 * - Provides hooks for connection, disconnection, and server lifecycle events
31 *
32 * ## Usage Flow
33 * 1. Construct a Server instance with a desired port (default: 9090)
34 * 2. Set message and connection handlers as needed
35 * 3. Call start() to begin listening for clients
36 * 4. Use stop() to gracefully shut down the server
37 * 5. Use event_bus() to subscribe to server events for monitoring or integration
38 *
39 * The Server is designed for internal use by Lila and is not intended for direct user interaction.
40 */
41class LILA_API Server {
42public:
43 /**
44 * @brief Handler for processing incoming client messages
45 * @param message The message received from the client
46 * @return Expected response string or error string
47 *
48 * The message handler is invoked for each message received from a client.
49 * It typically forwards code snippets to the interpreter and returns the result.
50 */
51 using MessageHandler = std::function<std::expected<std::string, std::string>(std::string_view)>;
52
53 /**
54 * @brief Handler for client connection/disconnection events
55 * @param info Information about the connected/disconnected client
56 */
57 using ConnectionHandler = std::function<void(const ClientInfo&)>;
58
59 /**
60 * @brief Handler for server start events
61 */
62 using StartHandler = std::function<void()>;
63
64 /**
65 * @brief Constructs a Server instance
66 * @param port TCP port to listen on (default: 9090)
67 */
68 Server(int port = 9090);
69
70 /**
71 * @brief Destructor; stops the server if running
72 */
73 ~Server();
74
75 /**
76 * @brief Starts the server and begins accepting clients
77 * @return True if server started successfully, false otherwise
78 */
79 [[nodiscard]] bool start() noexcept;
80
81 /**
82 * @brief Stops the server and disconnects all clients
83 */
84 void stop() noexcept;
85
86 /**
87 * @brief Checks if the server is currently running
88 * @return True if running, false otherwise
89 */
90 [[nodiscard]] bool is_running() const { return m_running; }
91
92 /**
93 * @brief Sets the handler for incoming client messages
94 * @param handler Function to process messages
95 */
96 void set_message_handler(MessageHandler handler) { m_message_handler = std::move(handler); }
97
98 /**
99 * @brief Registers a handler for client connection events
100 * @param handler Function to call when a client connects
101 */
102 void on_client_connected(ConnectionHandler handler) { m_connect_handler = std::move(handler); }
103
104 /**
105 * @brief Registers a handler for client disconnection events
106 * @param handler Function to call when a client disconnects
107 */
108 void on_client_disconnected(ConnectionHandler handler) { m_disconnect_handler = std::move(handler); }
109
110 /**
111 * @brief Registers a handler for server start events
112 * @param handler Function to call when the server starts
113 */
114 void on_server_started(StartHandler handler) { m_start_handler = std::move(handler); }
115
116 /**
117 * @brief Accesses the event bus for subscribing to server events
118 * @return Reference to the EventBus
119 */
120 EventBus& event_bus() { return m_event_bus; }
121
122 /**
123 * @brief Const access to the event bus
124 * @return Const reference to the EventBus
125 */
126 const EventBus& event_bus() const noexcept { return m_event_bus; }
127
128 /**
129 * @brief Broadcasts an event to connected clients
130 * @param event The event to broadcast
131 * @param target_session Optional session ID to target a specific client
132 */
133 void broadcast_event(const StreamEvent& event, std::optional<std::string_view> target_session = std::nullopt);
134
135 /**
136 * @brief Broadcasts a raw message to all connected clients
137 * @param message The message to send
138 */
139 void broadcast_to_all(std::string_view message);
140
141 /**
142 * @brief Sets the session ID for a client
143 * @param client_fd Client file descriptor
144 * @param session_id Session identifier string
145 */
146 void set_client_session(int client_fd, std::string session_id);
147
148 /**
149 * @brief Gets the session ID for a client
150 * @param client_fd Client file descriptor
151 * @return Optional session ID string
152 */
153 [[nodiscard]] std::optional<std::string> get_client_session(int client_fd) const;
154
155 /**
156 * @brief Gets a list of all currently connected clients
157 * @return Vector of ClientInfo structures
158 */
159 [[nodiscard]] std::vector<ClientInfo> get_connected_clients() const;
160
161private:
162 int m_port; ///< TCP port to listen on
163 int m_server_fd { -1 }; ///< Server socket file descriptor
164 std::atomic<bool> m_running { false }; ///< Server running state
165 ServerThread m_server_thread; ///< Server thread
166
167 MessageHandler m_message_handler; ///< Handler for client messages
168 ConnectionHandler m_connect_handler; ///< Handler for client connections
169 ConnectionHandler m_disconnect_handler; ///< Handler for client disconnections
170 StartHandler m_start_handler; ///< Handler for server start
171 EventBus m_event_bus; ///< Event bus for publishing server events
172
173 mutable std::shared_mutex m_clients_mutex; ///< Mutex for client map
174 std::unordered_map<int, ClientInfo> m_connected_clients; ///< Map of connected clients
175
176 /**
177 * @brief Main server loop; accepts and manages clients
178 * @param stop_token Token to signal server shutdown
179 */
180#ifndef MAYAFLUX_JTHREAD_BROKEN
181 void server_loop(const std::stop_token& stop_token);
182#else
183 void server_loop(const ServerThread::StopToken& stop_token);
184#endif
185
186 /**
187 * @brief Handles communication with a single client
188 * @param client_fd Client file descriptor
189 */
190 void handle_client(int client_fd);
191
192 /**
193 * @brief Reads a message from a client
194 * @param client_fd Client file descriptor
195 * @return Expected message string or error string
196 */
197 [[nodiscard]] std::expected<std::string, std::string> read_message(int client_fd);
198
199 /**
200 * @brief Sends a message to a client
201 * @param client_fd Client file descriptor
202 * @param message Message to send
203 * @return True if message sent successfully
204 */
205 [[nodiscard]] bool send_message(int client_fd, std::string_view message);
206
207 /**
208 * @brief Processes control messages (e.g., session, ping)
209 * @param client_fd Client file descriptor
210 * @param message Control message string
211 */
212 void process_control_message(int client_fd, std::string_view message);
213
214 /**
215 * @brief Cleans up resources for a disconnected client
216 * @param client_fd Client file descriptor
217 */
218 void cleanup_client(int client_fd);
219};
220
221} // namespace Lila
Platform-specific threading wrapper for Server class.
Thread-safe event subscription and publishing system for Lila.
Definition EventBus.hpp:180
API-compatible stop token for platforms without std::stop_token.
Fallback std::thread-based thread wrapper with manual stop signaling.
ServerThread m_server_thread
Server thread.
Definition Server.hpp:165
void broadcast_to_all(std::string_view message)
Broadcasts a raw message to all connected clients.
ConnectionHandler m_disconnect_handler
Handler for client disconnections.
Definition Server.hpp:169
std::shared_mutex m_clients_mutex
Mutex for client map.
Definition Server.hpp:173
std::optional< std::string > get_client_session(int client_fd) const
Gets the session ID for a client.
void set_message_handler(MessageHandler handler)
Sets the handler for incoming client messages.
Definition Server.hpp:96
std::function< void(const ClientInfo &)> ConnectionHandler
Handler for client connection/disconnection events.
Definition Server.hpp:57
void on_client_disconnected(ConnectionHandler handler)
Registers a handler for client disconnection events.
Definition Server.hpp:108
EventBus & event_bus()
Accesses the event bus for subscribing to server events.
Definition Server.hpp:120
std::unordered_map< int, ClientInfo > m_connected_clients
Map of connected clients.
Definition Server.hpp:174
int m_port
TCP port to listen on.
Definition Server.hpp:162
MessageHandler m_message_handler
Handler for client messages.
Definition Server.hpp:167
void on_client_connected(ConnectionHandler handler)
Registers a handler for client connection events.
Definition Server.hpp:102
StartHandler m_start_handler
Handler for server start.
Definition Server.hpp:170
EventBus m_event_bus
Event bus for publishing server events.
Definition Server.hpp:171
ConnectionHandler m_connect_handler
Handler for client connections.
Definition Server.hpp:168
std::function< void()> StartHandler
Handler for server start events.
Definition Server.hpp:62
void on_server_started(StartHandler handler)
Registers a handler for server start events.
Definition Server.hpp:114
std::function< std::expected< std::string, std::string >(std::string_view)> MessageHandler
Handler for processing incoming client messages.
Definition Server.hpp:51
const EventBus & event_bus() const noexcept
Const access to the event bus.
Definition Server.hpp:126
TCP server for interactive live coding sessions in MayaFlux.
Definition Server.hpp:41
Information about a connected client.
Definition EventBus.hpp:58
Represents a published event in the system.
Definition EventBus.hpp:121