Kurlyk
Loading...
Searching...
No Matches
WebSocketClient.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _KURLYK_WEBSOCKET_CLIENT_HPP_INCLUDED
3#define _KURLYK_WEBSOCKET_CLIENT_HPP_INCLUDED
4
7
9#include <mutex>
10
11namespace kurlyk {
12
17 public:
18
27
31 WebSocketClient(std::unique_ptr<WebSocketConfig> config, std::function<void(bool)> callback = nullptr) {
34 m_client->notify_handler() = []() {
36 };
37 m_client->set_config(std::move(config), std::move(callback));
38 }
39
52 const std::string& url,
53 const Headers& headers = Headers(),
54 const std::string& proxy_server = std::string(),
55 const std::string& proxy_auth = std::string(),
57 long request_timeout = 20,
58 bool reconnect = true,
59 bool verify_cert = true,
60 const std::string& ca_file = std::string(),
61 int rpm = 200) {
64 m_client->notify_handler() = []() {
66 };
68
69 m_config->url = url;
70 m_config->headers = headers;
71 m_config->proxy_server = proxy_server;
72 m_config->proxy_auth = proxy_auth;
73 m_config->proxy_type = proxy_type;
74 m_config->request_timeout = request_timeout;
75 m_config->reconnect = reconnect;
76 m_config->verify_cert = verify_cert;
77 m_config->ca_file = ca_file;
78 m_config->add_rate_limit(rpm, 60000);
79 }
80
83
85 virtual ~WebSocketClient() {
86 auto client = m_client;
88 client->shutdown();
89 });
90 }
91
94 void on_event(std::function<void(std::unique_ptr<WebSocketEventData>)> callback) {
95 m_client->event_handler() = std::move(callback);
96 }
97
100 std::function<void(std::unique_ptr<WebSocketEventData>)>& event_handler() {
101 return m_client->event_handler();
102 }
103
107 std::future<bool> set_config(std::unique_ptr<WebSocketConfig> config) {
108 auto promise = std::make_shared<std::promise<bool>>();
109 auto future = promise->get_future();
110 m_client->set_config(std::move(config), [promise](bool success) {
111 promise->set_value(success);
112 });
114 return future;
115 }
116
120 void set_config(std::unique_ptr<WebSocketConfig> config, std::function<void(bool)> callback) {
121 m_client->set_config(std::move(config), std::move(callback));
123 }
124
127 std::future<bool> connect() {
128 if (m_config) {
129# if __cplusplus >= 201402L
130 auto config = std::make_unique<WebSocketConfig>(*m_config.get());
131# else
132 auto config = std::unique_ptr<WebSocketConfig>(new WebSocketConfig(*m_config.get()));
133# endif
134 m_client->set_config(std::move(config), nullptr);
135 }
136 auto promise = std::make_shared<std::promise<bool>>();
137 auto future = promise->get_future();
138 m_client->connect([promise](bool success) {
139 promise->set_value(success);
140 });
142 return future;
143 }
144
147 void connect(std::function<void(bool)> callback) {
148 if (m_config) {
149# if __cplusplus >= 201402L
150 auto config = std::make_unique<WebSocketConfig>(*m_config.get());
151# else
152 auto config = std::unique_ptr<WebSocketConfig>(new WebSocketConfig(*m_config.get()));
153# endif
154 m_client->set_config(std::move(config), nullptr);
155 }
156 m_client->connect(std::move(callback));
158 }
159
163 auto connect_future = connect();
164 return connect_future.get();
165 }
166
169 std::future<bool> disconnect() {
170 auto promise = std::make_shared<std::promise<bool>>();
171 auto future = promise->get_future();
172 m_client->disconnect([promise](bool success) {
173 promise->set_value(success);
174 });
176 return future;
177 }
178
182 auto disconnect_future = disconnect();
183 return disconnect_future.get();
184 }
185
188 void disconnect(std::function<void(bool success)> callback) {
189 m_client->disconnect(std::move(callback));
191 }
192
195 const bool is_connected() const {
196 return m_client->is_connected();
197 }
198
205 const std::string &message,
206 long rate_limit_id = 0,
207 std::function<void(const std::error_code&)> callback = nullptr) {
208 return m_client->submit_message(message, rate_limit_id, std::move(callback));
209 }
210
217 const std::string &message,
218 long rate_limit_id = 0,
219 std::function<void(const std::error_code&)> callback = nullptr) {
220 return submit_message(message, rate_limit_id, std::move(callback)).accepted;
221 }
222
229 const int status = 1000,
230 const std::string &reason = std::string(),
231 std::function<void(const std::error_code&)> callback = nullptr) {
232 return m_client->submit_close(status, reason, std::move(callback));
233 }
234
241 const int status = 1000,
242 const std::string &reason = std::string(),
243 std::function<void(const std::error_code&)> callback = nullptr) {
244 return submit_close(status, reason, std::move(callback)).accepted;
245 }
246
249 std::list<std::unique_ptr<WebSocketEventData>> receive_events() {
250 return m_client->receive_events();
251 }
252
255 std::unique_ptr<WebSocketEventData> receive_event() {
256 return m_client->receive_event();
257 }
258
261 std::string get_http_version() const {
262 return m_client->get_http_version();
263 }
264
268 return m_client->get_headers();
269 }
270
273 std::string get_remote_endpoint() const {
274 return m_client->get_remote_endpoint();
275 }
276
281 void set_url(const std::string& host, const std::string& path, const std::string& query = "") {
282 init_config();
283 return m_config->set_url(host, path, query);
284 }
285
289 void set_url(const std::string& url, const QueryParams& query) {
290 init_config();
291 return m_config->set_url(url, query);
292 }
293
299 void set_accept_encoding(bool identity = false, bool deflate = false, bool gzip = false, bool brotli = false) {
300 init_config();
301 return m_config->set_accept_encoding(identity, deflate, gzip, brotli);
302 }
303
309 const std::string& ip,
310 int port,
312 init_config();
313 return m_config->set_proxy(ip, port, type);
314 }
315
323 const std::string& ip,
324 int port,
325 const std::string& username,
326 const std::string& password,
328 init_config();
329 return m_config->set_proxy(ip, port, username, password, type);
330 }
331
334 void set_proxy_server(const std::string& server) {
335 init_config();
336 return m_config->set_proxy_server(server);
337 }
338
341 void set_proxy_auth(const std::string& auth) {
342 init_config();
343 return m_config->set_proxy_auth(auth);
344 }
345
349 init_config();
350 return m_config->set_proxy_type(type);
351 }
352
356 void set_proxy_auth(const std::string& username, const std::string& password) {
357 init_config();
358 return m_config->set_proxy_auth(username, password);
359 }
360
365 void set_reconnect(bool reconnect, long reconnect_attempts = 0, long reconnect_delay = 0) {
366 init_config();
367 return m_config->set_reconnect(reconnect, reconnect_attempts, reconnect_delay);
368 }
369
372 void set_user_agent(const std::string& user_agent) {
373 init_config();
374 return m_config->set_user_agent(user_agent);
375 }
376
379 void set_accept_language(const std::string& accept_language) {
380 init_config();
381 return m_config->set_accept_language(accept_language);
382 }
383
386 void set_cookie(const std::string& cookie) {
387 init_config();
388 return m_config->set_cookie(cookie);
389 }
390
393 void set_idle_timeout(long idle_timeout) {
394 init_config();
395 return m_config->set_idle_timeout(idle_timeout);
396 }
397
400 void set_request_timeout(long request_timeout) {
401 init_config();
402 return m_config->set_request_timeout(request_timeout);
403 }
404
407 void set_max_send_queue_size(std::size_t max_send_queue_size) {
408 init_config();
409 return m_config->set_max_send_queue_size(max_send_queue_size);
410 }
411
414 void set_ca_file(const std::string& ca_file) {
415 init_config();
416 return m_config->set_ca_file(ca_file);
417 }
418
422 void set_ca_file(bool verify_cert, const std::string& ca_file) {
423 init_config();
424 return m_config->set_ca_file(verify_cert, ca_file);
425 }
426
429 void set_verify_cert(bool verify_cert) {
430 init_config();
431 return m_config->set_verify_cert(verify_cert);
432 }
433
443 long add_rate_limit(long requests_per_period, long period_ms) {
444 init_config();
445 return m_config->add_rate_limit(requests_per_period, period_ms);
446 }
447
451 long add_rate_limit_rpm(long requests_per_minute) {
452 long period_ms = 60000; // 1 minute in milliseconds
453 return add_rate_limit(requests_per_minute, period_ms);
454 }
455
459 long add_rate_limit_rps(long requests_per_second) {
460 long period_ms = 1000; // 1 second in milliseconds
461 return add_rate_limit(requests_per_second, period_ms);
462 }
463
464 private:
466 std::unique_ptr<WebSocketConfig> m_config;
467
469 void init_config() {
470 if (!m_config) {
471# if __cplusplus >= 201402L
472 m_config = std::make_unique<WebSocketConfig>();
473# else
474 m_config = std::unique_ptr<WebSocketConfig>(new WebSocketConfig());
475# endif
476 }
477 }
478
481 static void ensure_initialized() {
482 static std::once_flag once;
483 std::call_once(once, []() {
487 });
488 }
489
490 }; // WebSocketClient
491
492} // namespace kurlyk
493
494#endif // _KURLYK_WEBSOCKET_CLIENT_HPP_INCLUDED
Defines the WebSocketManager singleton responsible for backend-specific WebSocket client instances.
static HttpRequestManager & get_instance()
Get the singleton instance of HttpRequestManager.
std::function< void(std::unique_ptr< WebSocketEventData >)> & event_handler()
Accessor for the event handler function.
std::list< std::unique_ptr< WebSocketEventData > > receive_events()
Retrieves all pending WebSocket events in a batch.
void set_proxy_type(ProxyType type)
Sets the proxy type.
void set_proxy_auth(const std::string &username, const std::string &password)
Configures proxy authentication credentials.
static void ensure_initialized()
Ensures the WebSocket and network components are initialized.
void set_accept_language(const std::string &accept_language)
Sets the Accept-Language header.
void set_verify_cert(bool verify_cert)
Sets whether to verify the server’s certificate.
void set_cookie(const std::string &cookie)
Sets the cookie data.
void set_max_send_queue_size(std::size_t max_send_queue_size)
Sets the maximum number of outbound send operations queued for this client.
void set_proxy(const std::string &ip, int port, ProxyType type=ProxyType::PROXY_HTTP)
Sets the proxy server address.
void on_event(std::function< void(std::unique_ptr< WebSocketEventData >)> callback)
Sets a callback for WebSocket events.
std::string get_http_version() const
Retrieves the HTTP version used in the WebSocket connection.
void set_user_agent(const std::string &user_agent)
Sets the User-Agent header.
void set_idle_timeout(long idle_timeout)
Configures the idle timeout for the WebSocket connection.
std::unique_ptr< WebSocketEventData > receive_event()
Retrieves a single WebSocket event, if available.
WebSocketClient(const std::string &url, const Headers &headers=Headers(), const std::string &proxy_server=std::string(), const std::string &proxy_auth=std::string(), ProxyType proxy_type=ProxyType::PROXY_HTTP, long request_timeout=20, bool reconnect=true, bool verify_cert=true, const std::string &ca_file=std::string(), int rpm=200)
Initializes the facade with URL-based configuration values.
void set_url(const std::string &url, const QueryParams &query)
Sets the WebSocket server URL with specified query parameters.
void set_proxy_auth(const std::string &auth)
Sets the proxy authentication credentials.
WebSocketClient & operator=(const WebSocketClient &)=delete
const bool is_connected() const
Checks if the WebSocket is connected.
std::unique_ptr< WebSocketConfig > m_config
Deferred WebSocket configuration copied into the backend before connect().
void set_accept_encoding(bool identity=false, bool deflate=false, bool gzip=false, bool brotli=false)
Sets the Accept-Encoding header with specified encodings.
SubmitResult submit_close(const int status=1000, const std::string &reason=std::string(), std::function< void(const std::error_code &)> callback=nullptr)
Attempts to submit a close request to the WebSocket server.
bool send_close(const int status=1000, const std::string &reason=std::string(), std::function< void(const std::error_code &)> callback=nullptr)
Sends a close request to the WebSocket server.
SubmitResult submit_message(const std::string &message, long rate_limit_id=0, std::function< void(const std::error_code &)> callback=nullptr)
Attempts to submit a message through the WebSocket.
bool disconnect_and_wait()
Disconnects from the WebSocket server, blocking until the disconnection completes.
void set_reconnect(bool reconnect, long reconnect_attempts=0, long reconnect_delay=0)
Configures reconnection behavior.
std::string get_remote_endpoint() const
Retrieves the remote endpoint information.
void init_config()
Initializes the WebSocket configuration if it is not already set.
long add_rate_limit(long requests_per_period, long period_ms)
Adds a rate limit configuration to control the frequency of WebSocket messages.
void disconnect(std::function< void(bool success)> callback)
Disconnects from the WebSocket server and invokes a callback upon completion.
void set_ca_file(bool verify_cert, const std::string &ca_file)
Sets certificate verification and sets the CA certificate file.
void set_ca_file(const std::string &ca_file)
Sets the path to the CA certificate file.
long add_rate_limit_rpm(long requests_per_minute)
Adds a rate limit based on Requests Per Minute (RPM).
WebSocketClient(const WebSocketClient &)=delete
void set_proxy_server(const std::string &server)
Sets the proxy server address.
long add_rate_limit_rps(long requests_per_second)
Adds a rate limit based on Requests Per Second (RPS).
WebSocketClient(std::unique_ptr< WebSocketConfig > config, std::function< void(bool)> callback=nullptr)
Initializes the facade with a WebSocket configuration object.
void set_config(std::unique_ptr< WebSocketConfig > config, std::function< void(bool)> callback)
Sets the WebSocket configuration and executes a callback upon completion.
selected_backend_client_ptr m_client
Backend-specific WebSocket client selected by compile-time platform macros.
void set_url(const std::string &host, const std::string &path, const std::string &query="")
Sets the WebSocket server URL with optional query parameters.
bool connect_and_wait()
Connects to the WebSocket server, blocking until the connection completes.
virtual ~WebSocketClient()
Schedules backend shutdown through NetworkWorker before the facade is destroyed.
std::future< bool > set_config(std::unique_ptr< WebSocketConfig > config)
Asynchronously sets the WebSocket configuration.
void connect(std::function< void(bool)> callback)
Connects to the WebSocket server and executes a callback upon completion.
void set_proxy(const std::string &ip, int port, const std::string &username, const std::string &password, ProxyType type=ProxyType::PROXY_HTTP)
Sets the proxy server address with authentication.
WebSocketClient()
Initializes the WebSocket client facade and its backend-specific implementation.
void set_request_timeout(long request_timeout)
Sets the timeout for WebSocket requests.
std::future< bool > connect()
Asynchronously connects to the WebSocket server.
bool send_message(const std::string &message, long rate_limit_id=0, std::function< void(const std::error_code &)> callback=nullptr)
Sends a message through the WebSocket.
std::future< bool > disconnect()
Asynchronously disconnects from the WebSocket server.
Headers get_headers() const
Retrieves the headers associated with the WebSocket connection.
Configuration parameters for establishing and managing WebSocket connections.
static WebSocketManager & get_instance()
Get the singleton instance of WebSocketManager.
selected_backend_client_ptr create_client()
Creates and returns a new backend-specific WebSocket client selected by compilation flags.
void notify()
Notifies the worker to begin processing requests or tasks.
static NetworkWorker & get_instance()
Get the singleton instance of NetworkWorker.
void add_task(std::function< void()> task)
Adds a task to the queue and notifies the worker thread.
void start(const bool use_async)
Starts the worker thread for asynchronous task processing.
#define KURLYK_AUTO_INIT_USE_ASYNC
Determines whether the NetworkWorker runs in a background thread during automatic initialization.
Definition kurlyk.hpp:20
Primary namespace for the Kurlyk library, encompassing initialization, request management,...
std::shared_ptr< selected_backend_client_t > selected_backend_client_ptr
Shared pointer to the compile-time selected backend client type.
ProxyType
Enumeration of supported proxy types compatible with libcurl.
Definition enums.hpp:12
@ PROXY_HTTP
HTTP proxy.
Definition enums.hpp:13
utils::CaseInsensitiveMultimap Headers
Alias for HTTP headers, providing a case-insensitive unordered multimap.
utils::CaseInsensitiveMultimap QueryParams
Alias for query parameters in HTTP requests, stored case-insensitively.
Represents the synchronous result of trying to enqueue or submit work.
bool accepted
Indicates whether the work item was accepted for processing.