-
Notifications
You must be signed in to change notification settings - Fork 62
/
websocket_server.hpp
1584 lines (1392 loc) · 61.2 KB
/
websocket_server.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include <nlohmann/json.hpp>
#include <websocketpp/config/asio.hpp>
#include <websocketpp/server.hpp>
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <shared_mutex>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "callback_queue.hpp"
#include "common.hpp"
#include "parameter.hpp"
#include "regex_utils.hpp"
#include "serialization.hpp"
#include "server_interface.hpp"
#include "websocket_logging.hpp"
// Debounce a function call (tied to the line number)
// This macro takes in a function and the debounce time in milliseconds
#define FOXGLOVE_DEBOUNCE(f, ms) \
{ \
static auto last_call = std::chrono::system_clock::now(); \
const auto now = std::chrono::system_clock::now(); \
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_call).count() > ms) { \
last_call = now; \
f(); \
} \
}
namespace {
constexpr uint32_t StringHash(const std::string_view str) {
uint32_t result = 0x811C9DC5; // FNV-1a 32-bit algorithm
for (char c : str) {
result = (static_cast<uint32_t>(c) ^ result) * 0x01000193;
}
return result;
}
constexpr auto SUBSCRIBE = StringHash("subscribe");
constexpr auto UNSUBSCRIBE = StringHash("unsubscribe");
constexpr auto ADVERTISE = StringHash("advertise");
constexpr auto UNADVERTISE = StringHash("unadvertise");
constexpr auto GET_PARAMETERS = StringHash("getParameters");
constexpr auto SET_PARAMETERS = StringHash("setParameters");
constexpr auto SUBSCRIBE_PARAMETER_UPDATES = StringHash("subscribeParameterUpdates");
constexpr auto UNSUBSCRIBE_PARAMETER_UPDATES = StringHash("unsubscribeParameterUpdates");
constexpr auto SUBSCRIBE_CONNECTION_GRAPH = StringHash("subscribeConnectionGraph");
constexpr auto UNSUBSCRIBE_CONNECTION_GRAPH = StringHash("unsubscribeConnectionGraph");
constexpr auto FETCH_ASSET = StringHash("fetchAsset");
} // namespace
namespace foxglove {
using json = nlohmann::json;
using ConnHandle = websocketpp::connection_hdl;
using OpCode = websocketpp::frame::opcode::value;
static const websocketpp::log::level APP = websocketpp::log::alevel::app;
static const websocketpp::log::level WARNING = websocketpp::log::elevel::warn;
static const websocketpp::log::level RECOVERABLE = websocketpp::log::elevel::rerror;
/// Map of required capability by client operation (text).
const std::unordered_map<std::string, std::string> CAPABILITY_BY_CLIENT_OPERATION = {
// {"subscribe", }, // No required capability.
// {"unsubscribe", }, // No required capability.
{"advertise", CAPABILITY_CLIENT_PUBLISH},
{"unadvertise", CAPABILITY_CLIENT_PUBLISH},
{"getParameters", CAPABILITY_PARAMETERS},
{"setParameters", CAPABILITY_PARAMETERS},
{"subscribeParameterUpdates", CAPABILITY_PARAMETERS_SUBSCRIBE},
{"unsubscribeParameterUpdates", CAPABILITY_PARAMETERS_SUBSCRIBE},
{"subscribeConnectionGraph", CAPABILITY_CONNECTION_GRAPH},
{"unsubscribeConnectionGraph", CAPABILITY_CONNECTION_GRAPH},
{"fetchAsset", CAPABILITY_ASSETS},
};
/// Map of required capability by client operation (binary).
const std::unordered_map<ClientBinaryOpcode, std::string> CAPABILITY_BY_CLIENT_BINARY_OPERATION = {
{ClientBinaryOpcode::MESSAGE_DATA, CAPABILITY_CLIENT_PUBLISH},
{ClientBinaryOpcode::SERVICE_CALL_REQUEST, CAPABILITY_SERVICES},
};
constexpr websocketpp::log::level StatusLevelToLogLevel(StatusLevel level) {
switch (level) {
case StatusLevel::Info:
return APP;
case StatusLevel::Warning:
return WARNING;
case StatusLevel::Error:
return RECOVERABLE;
default:
return RECOVERABLE;
}
}
template <typename ServerConfiguration>
class Server final : public ServerInterface<ConnHandle> {
public:
using ServerType = websocketpp::server<ServerConfiguration>;
using ConnectionType = websocketpp::connection<ServerConfiguration>;
using MessagePtr = typename ServerType::message_ptr;
using Tcp = websocketpp::lib::asio::ip::tcp;
explicit Server(std::string name, LogCallback logger, const ServerOptions& options);
virtual ~Server() override;
Server(const Server&) = delete;
Server(Server&&) = delete;
Server& operator=(const Server&) = delete;
Server& operator=(Server&&) = delete;
void start(const std::string& host, uint16_t port) override;
void stop() override;
std::vector<ChannelId> addChannels(const std::vector<ChannelWithoutId>& channels) override;
void removeChannels(const std::vector<ChannelId>& channelIds) override;
void publishParameterValues(ConnHandle clientHandle, const std::vector<Parameter>& parameters,
const std::optional<std::string>& requestId = std::nullopt) override;
void updateParameterValues(const std::vector<Parameter>& parameters) override;
std::vector<ServiceId> addServices(const std::vector<ServiceWithoutId>& services) override;
void removeServices(const std::vector<ServiceId>& serviceIds) override;
void setHandlers(ServerHandlers<ConnHandle>&& handlers) override;
void broadcastMessage(ChannelId chanId, uint64_t timestamp, const uint8_t* payload,
size_t payloadSize) override;
void sendMessage(ConnHandle clientHandle, ChannelId chanId, uint64_t timestamp,
const uint8_t* payload, size_t payloadSize) override;
void sendStatusAndLogMsg(ConnHandle clientHandle, const StatusLevel level,
const std::string& message,
const std::optional<std::string>& id = std::nullopt);
void broadcastTime(uint64_t timestamp) override;
void sendServiceResponse(ConnHandle clientHandle, const ServiceResponse& response) override;
void sendServiceFailure(ConnHandle clientHandle, ServiceId serviceId, uint32_t callId,
const std::string& message) override;
void updateConnectionGraph(const MapOfSets& publishedTopics, const MapOfSets& subscribedTopics,
const MapOfSets& advertisedServices) override;
void sendFetchAssetResponse(ConnHandle clientHandle, const FetchAssetResponse& response) override;
void sendStatus(ConnHandle clientHandle, const Status& status);
void sendStatus(const Status& status) override;
void removeStatus(const std::vector<std::string>& statusIds) override;
uint16_t getPort() override;
std::string remoteEndpointString(ConnHandle clientHandle) override;
private:
struct ClientInfo {
std::string name;
ConnHandle handle;
std::unordered_map<ChannelId, SubscriptionId> subscriptionsByChannel;
std::unordered_set<ClientChannelId> advertisedChannels;
bool subscribedToConnectionGraph = false;
explicit ClientInfo(const std::string& name, ConnHandle handle)
: name(name)
, handle(handle) {}
ClientInfo(const ClientInfo&) = delete;
ClientInfo& operator=(const ClientInfo&) = delete;
ClientInfo(ClientInfo&&) = default;
ClientInfo& operator=(ClientInfo&&) = default;
};
std::string _name;
LogCallback _logger;
ServerOptions _options;
ServerType _server;
std::unique_ptr<std::thread> _serverThread;
std::unique_ptr<CallbackQueue> _handlerCallbackQueue;
uint32_t _nextChannelId = 0;
std::map<ConnHandle, ClientInfo, std::owner_less<>> _clients;
std::unordered_map<ChannelId, Channel> _channels;
std::map<ConnHandle, std::unordered_map<ClientChannelId, ClientAdvertisement>, std::owner_less<>>
_clientChannels;
std::map<ConnHandle, std::unordered_set<std::string>, std::owner_less<>>
_clientParamSubscriptions;
ServiceId _nextServiceId = 0;
std::unordered_map<ServiceId, ServiceWithoutId> _services;
ServerHandlers<ConnHandle> _handlers;
std::shared_mutex _clientsMutex;
std::shared_mutex _channelsMutex;
std::shared_mutex _clientChannelsMutex;
std::shared_mutex _servicesMutex;
std::mutex _clientParamSubscriptionsMutex;
struct {
int subscriptionCount = 0;
MapOfSets publishedTopics;
MapOfSets subscribedTopics;
MapOfSets advertisedServices;
} _connectionGraph;
std::shared_mutex _connectionGraphMutex;
void setupTlsHandler();
void socketInit(ConnHandle hdl);
bool validateConnection(ConnHandle hdl);
void handleConnectionOpened(ConnHandle hdl);
void handleConnectionClosed(ConnHandle hdl);
void handleMessage(ConnHandle hdl, MessagePtr msg);
void handleTextMessage(ConnHandle hdl, MessagePtr msg);
void handleBinaryMessage(ConnHandle hdl, MessagePtr msg);
void sendJson(ConnHandle hdl, json&& payload);
void sendJsonRaw(ConnHandle hdl, const std::string& payload);
void sendBinary(ConnHandle hdl, const uint8_t* payload, size_t payloadSize);
void unsubscribeParamsWithoutSubscriptions(ConnHandle hdl,
const std::unordered_set<std::string>& paramNames);
bool isParameterSubscribed(const std::string& paramName) const;
bool hasCapability(const std::string& capability) const;
bool hasHandler(uint32_t op) const;
void handleSubscribe(const nlohmann::json& payload, ConnHandle hdl);
void handleUnsubscribe(const nlohmann::json& payload, ConnHandle hdl);
void handleAdvertise(const nlohmann::json& payload, ConnHandle hdl);
void handleUnadvertise(const nlohmann::json& payload, ConnHandle hdl);
void handleGetParameters(const nlohmann::json& payload, ConnHandle hdl);
void handleSetParameters(const nlohmann::json& payload, ConnHandle hdl);
void handleSubscribeParameterUpdates(const nlohmann::json& payload, ConnHandle hdl);
void handleUnsubscribeParameterUpdates(const nlohmann::json& payload, ConnHandle hdl);
void handleSubscribeConnectionGraph(ConnHandle hdl);
void handleUnsubscribeConnectionGraph(ConnHandle hdl);
void handleFetchAsset(const nlohmann::json& payload, ConnHandle hdl);
};
template <typename ServerConfiguration>
inline Server<ServerConfiguration>::Server(std::string name, LogCallback logger,
const ServerOptions& options)
: _name(std::move(name))
, _logger(logger)
, _options(options) {
// Redirect logging
_server.get_alog().set_callback(_logger);
_server.get_elog().set_callback(_logger);
websocketpp::lib::error_code ec;
_server.init_asio(ec);
if (ec) {
throw std::runtime_error("Failed to initialize websocket server: " + ec.message());
}
_server.clear_access_channels(websocketpp::log::alevel::all);
_server.set_access_channels(APP);
_server.set_tcp_pre_init_handler(std::bind(&Server::socketInit, this, std::placeholders::_1));
this->setupTlsHandler();
_server.set_validate_handler(std::bind(&Server::validateConnection, this, std::placeholders::_1));
_server.set_open_handler(std::bind(&Server::handleConnectionOpened, this, std::placeholders::_1));
_server.set_close_handler(
std::bind(&Server::handleConnectionClosed, this, std::placeholders::_1));
_server.set_message_handler(
std::bind(&Server::handleMessage, this, std::placeholders::_1, std::placeholders::_2));
_server.set_reuse_addr(true);
_server.set_listen_backlog(128);
// Callback queue for handling client requests.
_handlerCallbackQueue = std::make_unique<CallbackQueue>(_logger, /*numThreads=*/1ul);
}
template <typename ServerConfiguration>
inline Server<ServerConfiguration>::~Server() {}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::socketInit(ConnHandle hdl) {
websocketpp::lib::asio::error_code ec;
_server.get_con_from_hdl(hdl)->get_raw_socket().set_option(Tcp::no_delay(true), ec);
if (ec) {
_server.get_elog().write(RECOVERABLE, "Failed to set TCP_NODELAY: " + ec.message());
}
}
template <typename ServerConfiguration>
inline bool Server<ServerConfiguration>::validateConnection(ConnHandle hdl) {
auto con = _server.get_con_from_hdl(hdl);
const auto& subprotocols = con->get_requested_subprotocols();
if (std::find(subprotocols.begin(), subprotocols.end(), SUPPORTED_SUBPROTOCOL) !=
subprotocols.end()) {
con->select_subprotocol(SUPPORTED_SUBPROTOCOL);
return true;
}
_server.get_alog().write(APP, "Rejecting client " + remoteEndpointString(hdl) +
" which did not declare support for subprotocol " +
SUPPORTED_SUBPROTOCOL);
return false;
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::handleConnectionOpened(ConnHandle hdl) {
auto con = _server.get_con_from_hdl(hdl);
const auto endpoint = remoteEndpointString(hdl);
_server.get_alog().write(APP, "Client " + endpoint + " connected via " + con->get_resource());
{
std::unique_lock<std::shared_mutex> lock(_clientsMutex);
_clients.emplace(hdl, ClientInfo(endpoint, hdl));
}
con->send(json({
{"op", "serverInfo"},
{"name", _name},
{"capabilities", _options.capabilities},
{"supportedEncodings", _options.supportedEncodings},
{"metadata", _options.metadata},
{"sessionId", _options.sessionId},
})
.dump());
std::vector<Channel> channels;
{
std::shared_lock<std::shared_mutex> lock(_channelsMutex);
for (const auto& [id, channel] : _channels) {
(void)id;
channels.push_back(channel);
}
}
sendJson(hdl, {
{"op", "advertise"},
{"channels", std::move(channels)},
});
std::vector<Service> services;
{
std::shared_lock<std::shared_mutex> lock(_servicesMutex);
for (const auto& [id, service] : _services) {
services.push_back(Service(service, id));
}
}
sendJson(hdl, {
{"op", "advertiseServices"},
{"services", std::move(services)},
});
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::handleConnectionClosed(ConnHandle hdl) {
std::unordered_map<ChannelId, SubscriptionId> oldSubscriptionsByChannel;
std::unordered_set<ClientChannelId> oldAdvertisedChannels;
std::string clientName;
bool wasSubscribedToConnectionGraph;
{
std::unique_lock<std::shared_mutex> lock(_clientsMutex);
const auto clientIt = _clients.find(hdl);
if (clientIt == _clients.end()) {
_server.get_elog().write(RECOVERABLE, "Client " + remoteEndpointString(hdl) +
" disconnected but not found in _clients");
return;
}
const auto& client = clientIt->second;
clientName = client.name;
_server.get_alog().write(APP, "Client " + clientName + " disconnected");
oldSubscriptionsByChannel = std::move(client.subscriptionsByChannel);
oldAdvertisedChannels = std::move(client.advertisedChannels);
wasSubscribedToConnectionGraph = client.subscribedToConnectionGraph;
_clients.erase(clientIt);
}
// Unadvertise all channels this client advertised
for (const auto clientChannelId : oldAdvertisedChannels) {
_server.get_alog().write(APP, "Client " + clientName + " unadvertising channel " +
std::to_string(clientChannelId) + " due to disconnect");
if (_handlers.clientUnadvertiseHandler) {
try {
_handlers.clientUnadvertiseHandler(clientChannelId, hdl);
} catch (const std::exception& ex) {
_server.get_elog().write(
RECOVERABLE, "Exception caught when closing connection: " + std::string(ex.what()));
} catch (...) {
_server.get_elog().write(RECOVERABLE, "Exception caught when closing connection");
}
}
}
{
std::unique_lock<std::shared_mutex> lock(_clientChannelsMutex);
_clientChannels.erase(hdl);
}
// Unsubscribe all channels this client subscribed to
if (_handlers.unsubscribeHandler) {
for (const auto& [chanId, subs] : oldSubscriptionsByChannel) {
(void)subs;
try {
_handlers.unsubscribeHandler(chanId, hdl);
} catch (const std::exception& ex) {
_server.get_elog().write(
RECOVERABLE, "Exception caught when closing connection: " + std::string(ex.what()));
} catch (...) {
_server.get_elog().write(RECOVERABLE, "Exception caught when closing connection");
}
}
}
// Unsubscribe from parameters this client subscribed to
std::unordered_set<std::string> clientSubscribedParameters;
{
std::lock_guard<std::mutex> lock(_clientParamSubscriptionsMutex);
clientSubscribedParameters = _clientParamSubscriptions[hdl];
_clientParamSubscriptions.erase(hdl);
}
unsubscribeParamsWithoutSubscriptions(hdl, clientSubscribedParameters);
if (wasSubscribedToConnectionGraph) {
std::unique_lock<std::shared_mutex> lock(_connectionGraphMutex);
_connectionGraph.subscriptionCount--;
if (_connectionGraph.subscriptionCount == 0 && _handlers.subscribeConnectionGraphHandler) {
_server.get_alog().write(APP, "Unsubscribing from connection graph updates.");
try {
_handlers.subscribeConnectionGraphHandler(false);
} catch (const std::exception& ex) {
_server.get_elog().write(
RECOVERABLE, "Exception caught when closing connection: " + std::string(ex.what()));
} catch (...) {
_server.get_elog().write(RECOVERABLE, "Exception caught when closing connection");
}
}
}
} // namespace foxglove
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::setHandlers(ServerHandlers<ConnHandle>&& handlers) {
_handlers = handlers;
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::stop() {
if (_server.stopped()) {
return;
}
_server.get_alog().write(APP, "Stopping WebSocket server");
websocketpp::lib::error_code ec;
_server.stop_perpetual();
if (_server.is_listening()) {
_server.stop_listening(ec);
if (ec) {
_server.get_elog().write(RECOVERABLE, "Failed to stop listening: " + ec.message());
}
}
std::vector<std::shared_ptr<ConnectionType>> connections;
{
std::shared_lock<std::shared_mutex> lock(_clientsMutex);
connections.reserve(_clients.size());
for (const auto& [hdl, client] : _clients) {
(void)client;
if (auto connection = _server.get_con_from_hdl(hdl, ec)) {
connections.push_back(connection);
}
}
}
if (!connections.empty()) {
_server.get_alog().write(
APP, "Closing " + std::to_string(connections.size()) + " client connection(s)");
// Iterate over all client connections and start the close connection handshake
for (const auto& connection : connections) {
connection->close(websocketpp::close::status::going_away, "server shutdown", ec);
if (ec) {
_server.get_elog().write(RECOVERABLE, "Failed to close connection: " + ec.message());
}
}
// Wait for all connections to close
constexpr size_t MAX_SHUTDOWN_MS = 1000;
constexpr size_t SLEEP_MS = 10;
size_t durationMs = 0;
while (!_server.stopped() && durationMs < MAX_SHUTDOWN_MS) {
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_MS));
_server.poll_one();
durationMs += SLEEP_MS;
}
if (!_server.stopped()) {
_server.get_elog().write(RECOVERABLE, "Failed to close all connections, forcefully stopping");
for (const auto& hdl : connections) {
if (auto con = _server.get_con_from_hdl(hdl, ec)) {
_server.get_elog().write(RECOVERABLE,
"Terminating connection to " + remoteEndpointString(hdl));
con->terminate(ec);
}
}
_server.stop();
}
}
_server.get_alog().write(APP, "All WebSocket connections closed");
if (_serverThread) {
_server.get_alog().write(APP, "Waiting for WebSocket server run loop to terminate");
_serverThread->join();
_serverThread.reset();
_server.get_alog().write(APP, "WebSocket server run loop terminated");
}
std::unique_lock<std::shared_mutex> lock(_clientsMutex);
_clients.clear();
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::start(const std::string& host, uint16_t port) {
if (_serverThread) {
throw std::runtime_error("Server already started");
}
websocketpp::lib::error_code ec;
_server.listen(host, std::to_string(port), ec);
if (ec) {
throw std::runtime_error("Failed to listen on port " + std::to_string(port) + ": " +
ec.message());
}
_server.start_accept(ec);
if (ec) {
throw std::runtime_error("Failed to start accepting connections: " + ec.message());
}
_serverThread = std::make_unique<std::thread>([this]() {
_server.get_alog().write(APP, "WebSocket server run loop started");
_server.run();
_server.get_alog().write(APP, "WebSocket server run loop stopped");
});
if (!_server.is_listening()) {
throw std::runtime_error("WebSocket server failed to listen on port " + std::to_string(port));
}
websocketpp::lib::asio::error_code asioEc;
auto endpoint = _server.get_local_endpoint(asioEc);
if (asioEc) {
throw std::runtime_error("Failed to resolve the local endpoint: " + ec.message());
}
const std::string protocol = _options.useTls ? "wss" : "ws";
auto address = endpoint.address();
_server.get_alog().write(APP, "WebSocket server listening at " + protocol + "://" +
IPAddressToString(address) + ":" +
std::to_string(endpoint.port()));
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::sendJson(ConnHandle hdl, json&& payload) {
try {
_server.send(hdl, std::move(payload).dump(), OpCode::TEXT);
} catch (std::exception const& e) {
_server.get_elog().write(RECOVERABLE, e.what());
}
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::sendJsonRaw(ConnHandle hdl, const std::string& payload) {
try {
_server.send(hdl, payload, OpCode::TEXT);
} catch (std::exception const& e) {
_server.get_elog().write(RECOVERABLE, e.what());
}
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::sendBinary(ConnHandle hdl, const uint8_t* payload,
size_t payloadSize) {
try {
_server.send(hdl, payload, payloadSize, OpCode::BINARY);
} catch (std::exception const& e) {
_server.get_elog().write(RECOVERABLE, e.what());
}
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::sendStatus(ConnHandle clientHandle, const Status& status) {
json statusPayload = {
{"op", "status"},
{"level", static_cast<uint8_t>(status.level)},
{"message", status.message},
};
if (status.id) {
statusPayload["id"] = status.id.value();
}
sendJson(clientHandle, std::move(statusPayload));
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::sendStatusAndLogMsg(ConnHandle clientHandle,
const StatusLevel level,
const std::string& message,
const std::optional<std::string>& id) {
const std::string endpoint = remoteEndpointString(clientHandle);
const std::string logMessage = endpoint + ": " + message;
const auto logLevel = StatusLevelToLogLevel(level);
auto logger = level == StatusLevel::Info ? _server.get_alog() : _server.get_elog();
logger.write(logLevel, logMessage);
sendStatus(clientHandle, {level, message, id});
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::handleMessage(ConnHandle hdl, MessagePtr msg) {
const OpCode op = msg->get_opcode();
_handlerCallbackQueue->addCallback([this, hdl, msg, op]() {
try {
if (op == OpCode::TEXT) {
handleTextMessage(hdl, msg);
} else if (op == OpCode::BINARY) {
handleBinaryMessage(hdl, msg);
}
} catch (const std::exception& e) {
sendStatusAndLogMsg(hdl, StatusLevel::Error, e.what());
} catch (...) {
sendStatusAndLogMsg(hdl, StatusLevel::Error,
"Exception occurred when executing message handler");
}
});
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::handleTextMessage(ConnHandle hdl, MessagePtr msg) {
const json payload = json::parse(msg->get_payload());
const std::string& op = payload.at("op").get<std::string>();
const auto requiredCapabilityIt = CAPABILITY_BY_CLIENT_OPERATION.find(op);
if (requiredCapabilityIt != CAPABILITY_BY_CLIENT_OPERATION.end() &&
!hasCapability(requiredCapabilityIt->second)) {
sendStatusAndLogMsg(hdl, StatusLevel::Error,
"Operation '" + op + "' not supported as server capability '" +
requiredCapabilityIt->second + "' is missing");
return;
}
if (!hasHandler(StringHash(op))) {
sendStatusAndLogMsg(
hdl, StatusLevel::Error,
"Operation '" + op + "' not supported as server handler function is missing");
return;
}
try {
switch (StringHash(op)) {
case SUBSCRIBE:
handleSubscribe(payload, hdl);
break;
case UNSUBSCRIBE:
handleUnsubscribe(payload, hdl);
break;
case ADVERTISE:
handleAdvertise(payload, hdl);
break;
case UNADVERTISE:
handleUnadvertise(payload, hdl);
break;
case GET_PARAMETERS:
handleGetParameters(payload, hdl);
break;
case SET_PARAMETERS:
handleSetParameters(payload, hdl);
break;
case SUBSCRIBE_PARAMETER_UPDATES:
handleSubscribeParameterUpdates(payload, hdl);
break;
case UNSUBSCRIBE_PARAMETER_UPDATES:
handleUnsubscribeParameterUpdates(payload, hdl);
break;
case SUBSCRIBE_CONNECTION_GRAPH:
handleSubscribeConnectionGraph(hdl);
break;
case UNSUBSCRIBE_CONNECTION_GRAPH:
handleUnsubscribeConnectionGraph(hdl);
break;
case FETCH_ASSET:
handleFetchAsset(payload, hdl);
break;
default:
sendStatusAndLogMsg(hdl, StatusLevel::Error, "Unrecognized client opcode \"" + op + "\"");
break;
}
} catch (const ExeptionWithId<uint32_t>& e) {
const std::string postfix = " (op: " + op + ", id: " + std::to_string(e.id()) + ")";
sendStatusAndLogMsg(hdl, StatusLevel::Error, e.what() + postfix);
} catch (const std::exception& e) {
const std::string postfix = " (op: " + op + ")";
sendStatusAndLogMsg(hdl, StatusLevel::Error, e.what() + postfix);
} catch (...) {
const std::string postfix = " (op: " + op + ")";
sendStatusAndLogMsg(hdl, StatusLevel::Error, "Failed to execute handler" + postfix);
}
} // namespace foxglove
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::handleBinaryMessage(ConnHandle hdl, MessagePtr msg) {
const auto& payload = msg->get_payload();
const uint8_t* data = reinterpret_cast<const uint8_t*>(payload.data());
const size_t length = payload.size();
if (length < 1) {
sendStatusAndLogMsg(hdl, StatusLevel::Error, "Received an empty binary message");
return;
}
const auto op = static_cast<ClientBinaryOpcode>(data[0]);
const auto requiredCapabilityIt = CAPABILITY_BY_CLIENT_BINARY_OPERATION.find(op);
if (requiredCapabilityIt != CAPABILITY_BY_CLIENT_BINARY_OPERATION.end() &&
!hasCapability(requiredCapabilityIt->second)) {
sendStatusAndLogMsg(hdl, StatusLevel::Error,
"Binary operation '" + std::to_string(static_cast<int>(op)) +
"' not supported as server capability '" + requiredCapabilityIt->second +
"' is missing");
return;
}
switch (op) {
case ClientBinaryOpcode::MESSAGE_DATA: {
if (!_handlers.clientMessageHandler) {
return;
}
if (length < 5) {
sendStatusAndLogMsg(hdl, StatusLevel::Error,
"Invalid message length " + std::to_string(length));
return;
}
const auto timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
const ClientChannelId channelId = *reinterpret_cast<const ClientChannelId*>(data + 1);
std::shared_lock<std::shared_mutex> lock(_clientChannelsMutex);
auto clientPublicationsIt = _clientChannels.find(hdl);
if (clientPublicationsIt == _clientChannels.end()) {
sendStatusAndLogMsg(hdl, StatusLevel::Error, "Client has no advertised channels");
return;
}
auto& clientPublications = clientPublicationsIt->second;
const auto& channelIt = clientPublications.find(channelId);
if (channelIt == clientPublications.end()) {
sendStatusAndLogMsg(hdl, StatusLevel::Error,
"Channel " + std::to_string(channelId) + " is not advertised");
return;
}
try {
const auto& advertisement = channelIt->second;
const uint32_t sequence = 0;
const ClientMessage clientMessage{static_cast<uint64_t>(timestamp),
static_cast<uint64_t>(timestamp),
sequence,
advertisement,
length,
data};
_handlers.clientMessageHandler(clientMessage, hdl);
} catch (const ClientChannelError& e) {
sendStatusAndLogMsg(hdl, StatusLevel::Error, e.what());
} catch (...) {
sendStatusAndLogMsg(hdl, StatusLevel::Error, "clientPublish: Failed to execute handler");
}
} break;
case ClientBinaryOpcode::SERVICE_CALL_REQUEST: {
ServiceRequest request;
if (length < request.size()) {
const std::string errMessage =
"Invalid service call request length " + std::to_string(length);
sendServiceFailure(hdl, request.serviceId, request.callId, errMessage);
_server.get_elog().write(RECOVERABLE, errMessage);
return;
}
request.read(data + 1, length - 1);
{
std::shared_lock<std::shared_mutex> lock(_servicesMutex);
if (_services.find(request.serviceId) == _services.end()) {
const std::string errMessage =
"Service " + std::to_string(request.serviceId) + " is not advertised";
sendServiceFailure(hdl, request.serviceId, request.callId, errMessage);
_server.get_elog().write(RECOVERABLE, errMessage);
return;
}
}
try {
if (!_handlers.serviceRequestHandler) {
throw foxglove::ServiceError(request.serviceId, "No service handler");
}
_handlers.serviceRequestHandler(request, hdl);
} catch (const std::exception& e) {
sendServiceFailure(hdl, request.serviceId, request.callId, e.what());
_server.get_elog().write(RECOVERABLE, e.what());
}
} break;
default: {
sendStatusAndLogMsg(hdl, StatusLevel::Error,
"Unrecognized client opcode " + std::to_string(uint8_t(op)));
} break;
}
}
template <typename ServerConfiguration>
inline std::vector<ChannelId> Server<ServerConfiguration>::addChannels(
const std::vector<ChannelWithoutId>& channels) {
if (channels.empty()) {
return {};
}
std::vector<ChannelId> channelIds;
channelIds.reserve(channels.size());
json::array_t channelsJson;
{
std::unique_lock<std::shared_mutex> lock(_channelsMutex);
for (const auto& channelWithoutId : channels) {
const auto newId = ++_nextChannelId;
channelIds.push_back(newId);
Channel newChannel{newId, channelWithoutId};
channelsJson.push_back(newChannel);
_channels.emplace(newId, std::move(newChannel));
}
}
const auto msg = json{{"op", "advertise"}, {"channels", channelsJson}}.dump();
std::shared_lock<std::shared_mutex> clientsLock(_clientsMutex);
for (const auto& [hdl, clientInfo] : _clients) {
(void)clientInfo;
sendJsonRaw(hdl, msg);
}
return channelIds;
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::removeChannels(const std::vector<ChannelId>& channelIds) {
if (channelIds.empty()) {
return;
}
{
std::unique_lock<std::shared_mutex> channelsLock(_channelsMutex);
for (auto channelId : channelIds) {
_channels.erase(channelId);
}
}
const auto msg = json{{"op", "unadvertise"}, {"channelIds", channelIds}}.dump();
std::unique_lock<std::shared_mutex> clientsLock(_clientsMutex);
for (auto& [hdl, clientInfo] : _clients) {
for (auto channelId : channelIds) {
if (const auto it = clientInfo.subscriptionsByChannel.find(channelId);
it != clientInfo.subscriptionsByChannel.end()) {
clientInfo.subscriptionsByChannel.erase(it);
}
}
sendJsonRaw(hdl, msg);
}
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::publishParameterValues(
ConnHandle hdl, const std::vector<Parameter>& parameters,
const std::optional<std::string>& requestId) {
// Filter out parameters which are not set.
std::vector<Parameter> nonEmptyParameters;
std::copy_if(parameters.begin(), parameters.end(), std::back_inserter(nonEmptyParameters),
[](const auto& p) {
return p.getType() != ParameterType::PARAMETER_NOT_SET;
});
nlohmann::json jsonPayload{{"op", "parameterValues"}, {"parameters", nonEmptyParameters}};
if (requestId) {
jsonPayload["id"] = requestId.value();
}
sendJsonRaw(hdl, jsonPayload.dump());
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::updateParameterValues(
const std::vector<Parameter>& parameters) {
std::lock_guard<std::mutex> lock(_clientParamSubscriptionsMutex);
for (const auto& clientParamSubscriptions : _clientParamSubscriptions) {
std::vector<Parameter> paramsToSendToClient;
// Only consider parameters that are subscribed by the client
std::copy_if(parameters.begin(), parameters.end(), std::back_inserter(paramsToSendToClient),
[clientParamSubscriptions](const Parameter& param) {
return clientParamSubscriptions.second.find(param.getName()) !=
clientParamSubscriptions.second.end();
});
if (!paramsToSendToClient.empty()) {
publishParameterValues(clientParamSubscriptions.first, paramsToSendToClient);
}
}
}
template <typename ServerConfiguration>
inline std::vector<ServiceId> Server<ServerConfiguration>::addServices(
const std::vector<ServiceWithoutId>& services) {
if (services.empty()) {
return {};
}
std::unique_lock<std::shared_mutex> lock(_servicesMutex);
std::vector<ServiceId> serviceIds;
json newServices;
for (const auto& service : services) {
if (!service.request.has_value() && !service.requestSchema.has_value()) {
throw std::runtime_error(
"Invalid service definition: Either `request` or `requestSchema` must be defined");
}
if (!service.response.has_value() && !service.responseSchema.has_value()) {
throw std::runtime_error(
"Invalid service definition: Either `response` or `responseSchema` must be defined");
}
const ServiceId serviceId = ++_nextServiceId;
_services.emplace(serviceId, service);
serviceIds.push_back(serviceId);
newServices.push_back(Service(service, serviceId));
}
const auto msg = json{{"op", "advertiseServices"}, {"services", std::move(newServices)}}.dump();
std::shared_lock<std::shared_mutex> clientsLock(_clientsMutex);
for (const auto& [hdl, clientInfo] : _clients) {
(void)clientInfo;
sendJsonRaw(hdl, msg);
}
return serviceIds;
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::removeServices(const std::vector<ServiceId>& serviceIds) {
std::unique_lock<std::shared_mutex> lock(_servicesMutex);
std::vector<ServiceId> removedServices;
for (const auto& serviceId : serviceIds) {
if (const auto it = _services.find(serviceId); it != _services.end()) {
_services.erase(it);
removedServices.push_back(serviceId);
}
}
if (!removedServices.empty()) {
const auto msg =
json{{"op", "unadvertiseServices"}, {"serviceIds", std::move(removedServices)}}.dump();
std::shared_lock<std::shared_mutex> clientsLock(_clientsMutex);
for (const auto& [hdl, clientInfo] : _clients) {
(void)clientInfo;
sendJsonRaw(hdl, msg);
}
}
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::broadcastMessage(ChannelId chanId, uint64_t timestamp,
const uint8_t* payload,
size_t payloadSize) {
std::shared_lock<std::shared_mutex> lock(_clientsMutex);
for (const auto& [hdl, clientInfo] : _clients) {
(void)clientInfo;
sendMessage(hdl, chanId, timestamp, payload, payloadSize);
}
}
template <typename ServerConfiguration>
inline void Server<ServerConfiguration>::sendMessage(ConnHandle clientHandle, ChannelId chanId,
uint64_t timestamp, const uint8_t* payload,
size_t payloadSize) {
websocketpp::lib::error_code ec;
const auto con = _server.get_con_from_hdl(clientHandle, ec);
if (ec || !con) {
return;
}
const auto bufferSizeinBytes = con->get_buffered_amount();
if (bufferSizeinBytes + payloadSize >= _options.sendBufferLimitBytes) {
const auto logFn = [this, clientHandle]() {
sendStatusAndLogMsg(clientHandle, StatusLevel::Warning, "Send buffer limit reached");
};
FOXGLOVE_DEBOUNCE(logFn, 2500)