20#include <ixwebsocket/IXBase64.h>
21#include <ixwebsocket/IXNetSystem.h>
22#include <ixwebsocket/IXWebSocket.h>
23#include <ixwebsocket/IXWebSocketCloseConstants.h>
24#include <nlohmann/json.hpp>
28#include <condition_variable>
39#include <unordered_map>
44using json = nlohmann::json;
51class ReadChannelConnectionImpl;
70 const std::vector<MessageData> &frames,
bool force);
72 unsigned maxInFlight);
74 std::unique_ptr<RpcClient::WriteChannelConnection>
79 std::unique_ptr<RpcClient::ReadChannelConnection>
103 entry.dataAvailable.store(
true);
107 const std::shared_ptr<WriteSenderEntry> &entry);
113 bool runSender(uint64_t channelId, WriteSenderEntry &entry);
161 std::condition_variable
cv;
165 std::unordered_map<uint64_t, std::unique_ptr<WriteCredit>>
writeCredits;
177 std::unordered_map<uint64_t, std::shared_ptr<std::promise<json>>>
pending;
209 std::unordered_map<uint64_t, std::shared_ptr<ReadCallbackEntry>>
214 std::unordered_map<uint64_t, std::shared_ptr<WriteSenderEntry>>
writeSenders;
231 const std::unordered_map<std::shared_ptr<ReadCallbackEntry>, uint64_t>
272 :
impl(
impl), channelId(channelId) {}
273 ~ReadChannelConnectionImpl()
override { disconnect(); }
275 void disconnect()
override {
276 if (disconnected.exchange(
true))
278 impl->unregisterCallback(channelId);
280 impl->unsubscribe(channelId);
281 }
catch (
const std::exception &e) {
285 impl->getLogger().warning(
287 std::string(
"unsubscribe during disconnect failed: ") + e.what());
294 std::atomic<bool> disconnected{
false};
299 WriteChannelConnectionImpl(
301 std::shared_ptr<RpcClient::Impl::WriteSenderEntry> entry)
302 : impl(impl), channelId(channelId), entry(std::move(entry)) {}
303 ~WriteChannelConnectionImpl()
override { disconnect(); }
305 void notify()
override {
306 if (!entry->canceled.load())
307 impl->notifySender(channelId, *entry);
309 void disconnect()
override { impl->unregisterSender(channelId, entry); }
312 RpcClient::Impl *impl;
314 std::shared_ptr<RpcClient::Impl::WriteSenderEntry> entry;
324 : host(hostname), logger(logger) {
328 if (!ix::initNetSystem())
329 throw std::runtime_error(
330 "RpcClient: ix::initNetSystem() failed (WSAStartup)");
332 ws.setUrl(
"ws://" + host +
":" + std::to_string(port) +
"/esi/cosim/v" +
334 ws.disablePerMessageDeflate();
335 ws.disableAutomaticReconnection();
337 ws.setOnMessageCallback(
338 [
this](
const ix::WebSocketMessagePtr &msg) {
onMessage(msg); });
344 std::unique_lock<std::mutex> lock(openMutex);
345 openCV.wait(lock, [&] {
return openState != OpenState::Pending; });
346 if (openState == OpenState::Failed)
347 throw std::runtime_error(
"RpcClient: failed to connect to " +
348 ws.getUrl() +
": " + openError);
354 auto verIt = result.find(
"protocol_version");
355 if (verIt == result.end() || !verIt->is_number_unsigned() ||
357 throw std::runtime_error(
358 "RpcClient: server speaks an unsupported cosim protocol version (" +
359 (verIt == result.end() ? std::string(
"none") : verIt->dump()) +
363 if (
auto it = result.find(
"esi_version"); it != result.end())
365 if (
auto it = result.find(
"compressed_manifest_b64"); it != result.end()) {
369 std::string err = macaron::Base64::Decode(it->get<std::string>(), raw);
371 throw std::runtime_error(
"RpcClient: invalid base64 in manifest blob: " +
373 manifest.assign(raw.begin(), raw.end());
377 auto channelsIt = result.find(
"channels");
378 if (channelsIt == result.end() || !channelsIt->is_array())
379 throw std::runtime_error(
"RpcClient: hello response missing channels");
380 for (
const json &c : *channelsIt) {
382 meta.id = c.at(
"channel_id").get<uint64_t>();
383 meta.name = c.at(
"name").get<std::string>();
384 meta.type = c.at(
"type").get<std::string>();
385 std::string dir = c.at(
"direction").get<std::string>();
386 meta.direction = dir ==
"to_server" ? RpcClient::ChannelDirection::ToServer
387 : RpcClient::ChannelDirection::ToClient;
388 if (meta.direction == RpcClient::ChannelDirection::ToServer)
389 writeCredits.emplace(meta.id, std::make_unique<WriteCredit>());
390 channelsByName.emplace(meta.name, meta);
391 channelsById.emplace(meta.id, std::move(meta));
394 channelTablesReady.store(
true, std::memory_order_release);
403 disconnecting =
true;
404 failAllPending(
"client shutdown");
405 markConnectionLost();
410 std::lock_guard<std::mutex> lock(readCallbacksMutex);
411 for (
auto &[
id, entry] : readCallbacks)
412 entry->canceled.store(
true);
415 std::lock_guard<std::mutex> lock(writeSendersMutex);
416 for (
auto &[
id, entry] : writeSenders)
417 entry->canceled.store(
true);
424 if (transportThread.joinable()) {
425 readyIds.requestShutdown();
426 transportThread.join();
436 case ix::WebSocketMessageType::Open: {
437 std::lock_guard<std::mutex> lock(openMutex);
438 openState = OpenState::Open;
442 case ix::WebSocketMessageType::Error: {
443 std::string reason = msg->errorInfo.reason;
445 std::lock_guard<std::mutex> lock(lastServerErrorMutex);
446 if (!lastServerError.empty())
447 reason = lastServerError;
450 std::lock_guard<std::mutex> lock(openMutex);
451 if (openState == OpenState::Pending) {
452 openState = OpenState::Failed;
457 failAllPending(
"websocket error: " + reason);
458 markConnectionLost();
461 case ix::WebSocketMessageType::Close: {
462 std::string reason = msg->closeInfo.reason;
464 std::lock_guard<std::mutex> lock(lastServerErrorMutex);
465 if (!lastServerError.empty())
466 reason = lastServerError;
472 std::lock_guard<std::mutex> lock(openMutex);
473 if (openState == OpenState::Pending) {
474 openState = OpenState::Failed;
479 failAllPending(
"websocket closed: " + reason);
480 markConnectionLost();
483 case ix::WebSocketMessageType::Message:
489 handleBinaryFrame(msg->str);
491 handleControlFrame(msg->str);
493 faultStash.record(std::current_exception());
504 resp = json::parse(text);
505 }
catch (
const std::exception &e) {
509 auto typeIt = resp.find(
"type");
510 if (typeIt == resp.end() || !typeIt->is_string())
512 std::string type = typeIt->get<std::string>();
518 if (type ==
"error") {
519 if (
auto errIt = resp.find(
"error"); errIt != resp.end()) {
520 std::string code = errIt->value(
"code", std::string(
"internal"));
521 std::string message = errIt->value(
"message", std::string());
522 std::lock_guard<std::mutex> lock(lastServerErrorMutex);
523 lastServerError =
"server error [" + code +
"]: " + message;
528 if (type ==
"event") {
533 if (type !=
"response") {
538 logger.
debug(
"cosim",
539 "Ignoring control frame with unknown type \"" + type +
"\"");
542 auto idIt = resp.find(
"request_id");
543 if (idIt == resp.end())
545 uint64_t requestId = idIt->get<uint64_t>();
547 std::shared_ptr<std::promise<json>> promise;
549 std::lock_guard<std::mutex> lock(pendingMutex);
550 auto it = pending.find(requestId);
551 if (it == pending.end())
553 promise = it->second;
560 if (
auto errIt = resp.find(
"error"); errIt != resp.end()) {
561 std::string code = errIt->value(
"code", std::string(
"internal"));
562 std::string message = errIt->value(
"message", std::string());
563 promise->set_exception(std::make_exception_ptr(
564 std::runtime_error(
"Server error [" + code +
"]: " + message)));
565 }
else if (
auto resultIt = resp.find(
"result"); resultIt != resp.end()) {
566 promise->set_value(*resultIt);
571 promise->set_exception(std::make_exception_ptr(std::runtime_error(
572 "Server response missing both \"result\" and \"error\" fields "
573 "(protocol violation) for request_id=" +
574 std::to_string(requestId))));
576 }
catch (
const std::exception &e) {
580 logger.
debug(
"cosim",
581 std::string(
"failed to fulfill promise for request_id=") +
582 std::to_string(requestId) +
": " + e.what());
587 std::string
event = frame.value(
"event", std::string());
588 if (event !=
"consumed") {
589 logger.
debug(
"cosim",
"Ignoring unknown server event \"" + event +
"\"");
592 if (!channelTablesReady.load(std::memory_order_acquire))
594 auto paramsIt = frame.find(
"params");
595 if (paramsIt == frame.end() || !paramsIt->is_object())
597 auto chIt = paramsIt->find(
"channels");
598 if (chIt == paramsIt->end() || !chIt->is_array())
600 for (
const json &c : *chIt) {
601 auto idIt = c.find(
"channel_id");
602 auto countIt = c.find(
"count");
603 if (idIt == c.end() || !idIt->is_number_unsigned() || countIt == c.end() ||
604 !countIt->is_number_unsigned()) {
605 logger.
warning(
"cosim",
"Malformed consumed event entry: " + c.dump());
608 auto credIt = writeCredits.find(idIt->get<uint64_t>());
609 if (credIt == writeCredits.end())
611 WriteCredit &cred = *credIt->second;
612 uint64_t count = countIt->get<uint64_t>();
614 std::lock_guard<std::mutex> lock(cred.mutex);
616 cred.outstanding -= (std::min)(cred.outstanding, count);
618 cred.cv.notify_all();
619 markSenderReady(credIt->first);
624 std::lock_guard<std::mutex> lock(writeSendersMutex);
625 if (writeSenders.count(channelId))
626 readyIds.markReady(channelId);
630 connectionLost.store(
true);
631 if (!channelTablesReady.load(std::memory_order_acquire))
633 for (
auto &[
id, cred] : writeCredits) {
636 { std::lock_guard<std::mutex> lock(cred->mutex); }
637 cred->cv.notify_all();
645 const uint8_t *payloadBytes;
650 std::shared_ptr<ReadCallbackEntry> entry;
652 std::lock_guard<std::mutex> lock(readCallbacksMutex);
653 auto it = readCallbacks.find(channelId);
654 if (it == readCallbacks.end()) {
659 logger.
warning(
"cosim",
"Dropping inbound frame for channel id " +
660 std::to_string(channelId) +
661 ": no active subscriber");
671 entry->queue.push(MessageData(payloadBytes, payloadSize));
675 std::lock_guard<std::mutex> lock(pendingMutex);
676 for (
auto &[
id, pr] : pending) {
678 pr->set_exception(std::make_exception_ptr(std::runtime_error(reason)));
679 }
catch (
const std::exception &e) {
682 logger.
debug(
"cosim", std::string(
"failAllPending: request_id=") +
684 " already satisfied: " + e.what());
696 uint64_t requestId = nextRequestId.fetch_add(1);
697 std::future<json> future;
699 std::lock_guard<std::mutex> lock(pendingMutex);
700 auto promise = std::make_shared<std::promise<json>>();
701 future = promise->get_future();
702 pending.emplace(requestId, std::move(promise));
706 req[
"type"] =
"request";
707 req[
"request_id"] = requestId;
708 req[
"method"] = method;
709 req[
"params"] = std::move(params);
710 std::string text = req.dump();
715 auto info = ws.sendUtf8Text(text);
717 std::lock_guard<std::mutex> plock(pendingMutex);
718 pending.erase(requestId);
719 throw std::runtime_error(
"RpcClient: failed to send " + method);
726 constexpr auto kCallTimeout = std::chrono::seconds(30);
727 if (future.wait_for(kCallTimeout) != std::future_status::ready) {
731 std::lock_guard<std::mutex> plock(pendingMutex);
732 pending.erase(requestId);
733 throw std::runtime_error(
"RpcClient: timed out waiting for response to " +
739const RpcClient::Impl::ChannelMeta &
741 auto it = channelsByName.find(channelName);
742 if (it == channelsByName.end())
743 throw std::runtime_error(
"Unknown channel '" + channelName +
"'");
745 throw std::runtime_error(
"Channel '" + channelName +
746 "' is not a to-server channel");
751 const MessageData &data) {
755 auto info = ws.sendBinary(frame);
757 throw std::runtime_error(
"Failed to send data on channel '" + meta.name +
762 const MessageData &data) {
764 const ChannelMeta &meta = getToServerChannel(channelName);
765 WriteCredit &cred = *writeCredits.at(meta.id);
767 std::unique_lock<std::mutex> lock(cred.mutex);
768 cred.cv.wait(lock, [&] {
769 return connectionLost.load() || cred.maxInFlight == 0 ||
770 cred.outstanding < cred.maxInFlight;
772 if (connectionLost.load())
773 throw std::runtime_error(
"Connection to cosim server lost while "
774 "writing to channel '" +
778 sendFrame(meta, data);
782 const std::vector<MessageData> &frames,
785 const ChannelMeta &meta = getToServerChannel(channelName);
786 WriteCredit &cred = *writeCredits.at(meta.id);
788 std::lock_guard<std::mutex> lock(cred.mutex);
789 if (connectionLost.load())
790 throw std::runtime_error(
"Connection to cosim server lost while "
791 "writing to channel '" +
793 if (!force && cred.maxInFlight != 0 && cred.outstanding >= cred.maxInFlight)
795 cred.outstanding += frames.size();
797 for (
const MessageData &frame : frames)
798 sendFrame(meta, frame);
803 unsigned maxInFlight) {
804 const ChannelMeta &meta = getToServerChannel(channelName);
805 WriteCredit &cred = *writeCredits.at(meta.id);
807 std::lock_guard<std::mutex> lock(cred.mutex);
808 cred.maxInFlight = maxInFlight;
810 cred.cv.notify_all();
811 markSenderReady(meta.id);
814std::unique_ptr<RpcClient::WriteChannelConnection>
819 if (!fetch || !onError)
820 throw std::invalid_argument(
"connectServerSender: null callback");
821 uint64_t channelId = getToServerChannel(channelName).id;
822 auto entry = std::make_shared<WriteSenderEntry>();
823 entry->fetch = std::move(fetch);
824 entry->onError = std::move(onError);
826 std::lock_guard<std::mutex> lock(writeSendersMutex);
827 if (!writeSenders.emplace(channelId, entry).second)
828 throw std::runtime_error(
"Channel '" + channelName +
829 "' already has a sender");
831 return std::make_unique<WriteChannelConnectionImpl>(
this, channelId,
836 const ChannelMeta &meta = channelsById.at(channelId);
837 WriteCredit &cred = *writeCredits.at(channelId);
839 if (entry.canceled.load())
843 std::lock_guard<std::mutex> lock(cred.mutex);
844 lost = connectionLost.load();
845 if (!lost && cred.maxInFlight != 0 &&
846 cred.outstanding >= cred.maxInFlight)
850 entry.onError(std::make_exception_ptr(std::runtime_error(
851 "Connection to cosim server lost while writing to channel '" +
857 if (!entry.dataAvailable.exchange(
false))
859 std::optional<std::vector<MessageData>> frames;
860 std::exception_ptr
error;
862 frames = entry.fetch();
864 error = std::current_exception();
867 if (entry.canceled.load())
870 entry.onError(error);
876 entry.dataAvailable.store(
true);
878 std::lock_guard<std::mutex> lock(cred.mutex);
879 cred.outstanding += frames->size();
882 for (
const MessageData &frame : *frames)
883 sendFrame(meta, frame);
885 entry.onError(std::current_exception());
889 return !entry.canceled.load();
893 uint64_t channelId,
const std::shared_ptr<WriteSenderEntry> &entry) {
895 std::lock_guard<std::mutex> lock(writeSendersMutex);
896 auto it = writeSenders.find(channelId);
898 if (it != writeSenders.end() && it->second == entry)
899 writeSenders.erase(it);
901 entry->canceled.store(
true);
904 std::lock_guard<std::recursive_mutex> lock(entry->mutex);
912 RpcClient::ChannelDesc &desc)
const {
913 auto it = channelsByName.find(name);
914 if (it == channelsByName.end())
916 desc.
name = it->second.name;
917 desc.
type = it->second.type;
918 desc.
dir = it->second.direction;
923 std::vector<RpcClient::ChannelDesc> out;
924 out.reserve(channelsByName.size());
925 for (
const auto &[name, meta] : channelsByName) {
926 RpcClient::ChannelDesc
d;
929 d.dir = meta.direction;
930 out.push_back(std::move(d));
939std::unique_ptr<RpcClient::ReadChannelConnection>
942 unsigned maxInFlight) {
944 auto it = channelsByName.find(channelName);
945 if (it == channelsByName.end())
946 throw std::runtime_error(
"Unknown channel '" + channelName +
"'");
948 throw std::runtime_error(
"Channel '" + channelName +
949 "' is not a to-client channel");
950 uint64_t channelId = it->second.id;
955 auto entry = std::make_shared<ReadCallbackEntry>(
956 channelId, [
this, channelId] { readyIds.markReady(channelId); });
957 entry->callback = std::move(callback);
959 std::lock_guard<std::mutex> lock(readCallbacksMutex);
960 if (!readCallbacks.emplace(channelId, entry).second)
961 throw std::runtime_error(
"Channel '" + channelName +
962 "' already has a receiver");
967 {{
"channel_id", channelId}, {
"max_in_flight", maxInFlight}});
969 std::lock_guard<std::mutex> lock(readCallbacksMutex);
970 auto it = readCallbacks.find(channelId);
971 if (it != readCallbacks.end() && it->second == entry)
972 readCallbacks.erase(it);
976 return std::make_unique<ReadChannelConnectionImpl>(
this, channelId);
986 if (ws.getReadyState() != ix::ReadyState::Open)
988 call(
"unsubscribe", {{
"channel_id", channelId}});
992 std::shared_ptr<ReadCallbackEntry> entry;
994 std::lock_guard<std::mutex> lock(readCallbacksMutex);
995 auto it = readCallbacks.find(channelId);
996 if (it == readCallbacks.end())
999 readCallbacks.erase(it);
1005 std::lock_guard<std::mutex> lock(ackMutex);
1006 entry->canceled.store(
true);
1010 readyIds.markReady(channelId);
1022 std::unordered_set<uint64_t> retry;
1025 std::unordered_set<uint64_t> ids;
1026 if (!readyIds.waitDrain(
1027 ids, retry.empty() ? std::optional<std::chrono::milliseconds>{}
1028 : std::chrono::milliseconds(1)))
1030 ids.insert(retry.begin(), retry.end());
1035 std::unordered_map<std::shared_ptr<ReadCallbackEntry>, uint64_t> acks;
1036 for (uint64_t
id : ids) {
1037 std::shared_ptr<WriteSenderEntry> sender;
1039 std::lock_guard<std::mutex> lock(writeSendersMutex);
1040 auto it = writeSenders.find(
id);
1041 if (it != writeSenders.end())
1042 sender = it->second;
1045 std::lock_guard<std::recursive_mutex> lock(sender->mutex);
1046 if (sender->canceled.load() || disconnecting)
1049 if (runSender(
id, *sender))
1050 readyIds.markReady(
id);
1051 }
catch (
const std::exception &e) {
1052 logger.
error(
"cosim",
1053 std::string(
"Write error callback threw: ") + e.what());
1055 logger.
error(
"cosim",
1056 "Write error callback threw an unknown exception");
1061 std::shared_ptr<ReadCallbackEntry> entry;
1063 std::lock_guard<std::mutex> lock(readCallbacksMutex);
1064 auto it = readCallbacks.find(
id);
1065 if (it == readCallbacks.end())
1070 if (entry->canceled.load() || disconnecting)
1077 while (!stuck && !entry->canceled.load() && !disconnecting) {
1078 bool gotOne =
false;
1079 entry->queue.pop([&](
const MessageData &data) {
1081 std::unique_ptr<SegmentedMessageData> msg =
1082 std::make_unique<MessageData>(data);
1083 if (entry->callback(msg)) {
1097 sendConsumedEvent(acks);
1102 const std::unordered_map<std::shared_ptr<ReadCallbackEntry>, uint64_t>
1105 std::lock_guard<std::mutex> lock(ackMutex);
1106 json channels = json::array();
1107 for (
const auto &[entry, count] : acks)
1108 if (!entry->canceled.load())
1109 channels.push_back({{
"channel_id", entry->channelId}, {
"count", count}});
1110 if (channels.empty())
1113 event[
"type"] =
"event";
1114 event[
"event"] =
"consumed";
1115 event[
"params"] = {{
"channels", std::move(channels)}};
1118 ws.sendUtf8Text(event.dump());
1126 :
impl(std::make_unique<
Impl>(logger, hostname, port)) {}
1133 return impl->getCompressedManifest();
1138 return impl->getChannelDesc(channelName, desc);
1142 return impl->listChannels();
1147 impl->writeToServer(channelName, data);
1151 const std::vector<MessageData> &frames,
1153 return impl->tryWriteToServer(channelName, frames, force);
1157 unsigned maxInFlight) {
1158 impl->setToServerMaxInFlight(channelName, maxInFlight);
1161std::unique_ptr<RpcClient::WriteChannelConnection>
1165 return impl->connectServerSender(channelName, std::move(fetch),
1166 std::move(onError));
1169std::unique_ptr<RpcClient::ReadChannelConnection>
1172 return impl->connectClientReceiver(channelName, std::move(callback),
nlohmann::json json
Get a JSON representation of a type.
std::vector< uint8_t > getCompressedManifest() const
void markConnectionLost()
Wake every writer blocked on credits so it can observe the lost connection and throw.
void handleControlFrame(const std::string &text)
std::atomic< bool > disconnecting
void unsubscribe(uint64_t channelId)
uint32_t getEsiVersion() const
bool tryWriteToServer(const std::string &channelName, const std::vector< MessageData > &frames, bool force)
void failAllPending(const std::string &reason)
enum RpcClient::Impl::OpenState Pending
void unregisterCallback(uint64_t channelId)
std::unordered_map< uint64_t, std::shared_ptr< std::promise< json > > > pending
std::unordered_map< uint64_t, std::shared_ptr< ReadCallbackEntry > > readCallbacks
void onMessage(const ix::WebSocketMessagePtr &msg)
std::unordered_map< uint64_t, std::shared_ptr< WriteSenderEntry > > writeSenders
std::unordered_map< uint64_t, ChannelMeta > channelsById
void handleBinaryFrame(const std::string &data)
std::string lastServerError
std::unordered_map< uint64_t, std::unique_ptr< WriteCredit > > writeCredits
bool runSender(uint64_t channelId, WriteSenderEntry &entry)
Fetch and send messages for a sender while its channel has room and it has data, for up to MaxSendsPe...
std::condition_variable openCV
std::atomic< uint64_t > nextRequestId
std::unordered_map< std::string, ChannelMeta > channelsByName
std::unique_ptr< RpcClient::WriteChannelConnection > connectServerSender(const std::string &channelName, RpcClient::SendFetchCallback fetch, RpcClient::SendErrorCallback onError)
Impl(Logger &logger, const std::string &hostname, uint16_t port)
std::thread transportThread
std::unique_ptr< RpcClient::ReadChannelConnection > connectClientReceiver(const std::string &channelName, RpcClient::ReadCallback callback, unsigned maxInFlight)
void setToServerMaxInFlight(const std::string &channelName, unsigned maxInFlight)
void sendConsumedEvent(const std::unordered_map< std::shared_ptr< ReadCallbackEntry >, uint64_t > &acks)
Report acks (subscription -> count) of client-bound frames as consumed, leaving out canceled subscrip...
bool getChannelDesc(const std::string &name, RpcClient::ChannelDesc &desc) const
std::mutex writeSendersMutex
void unregisterSender(uint64_t channelId, const std::shared_ptr< WriteSenderEntry > &entry)
void notifySender(uint64_t channelId, WriteSenderEntry &entry)
const ChannelMeta & getToServerChannel(const std::string &channelName) const
Look up a to-server channel by name, throwing if it isn't one.
utils::ReadyIdSet< uint64_t > readyIds
std::mutex readCallbacksMutex
void writeToServer(const std::string &channelName, const MessageData &data)
std::vector< RpcClient::ChannelDesc > listChannels() const
void markSenderReady(uint64_t channelId)
Schedule a call to channel channelId's sender, if it has one.
std::atomic< bool > channelTablesReady
::esi::cosim::FaultStash faultStash
std::mutex lastServerErrorMutex
std::atomic< bool > connectionLost
json call(const std::string &method, json params)
Issue a JSON-RPC style request and synchronously await the response.
void sendFrame(const ChannelMeta &meta, const MessageData &data)
Send one data frame. Throws on a transport failure.
void handleEvent(const json &frame)
std::vector< uint8_t > manifest
virtual void error(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an error.
virtual void warning(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a warning.
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
A concrete flat message backed by a single vector of bytes.
Abstract handle for a read channel connection.
Handle for a sender registered with connectServerSender().
void setToServerMaxInFlight(const std::string &channelName, unsigned maxInFlight)
Set the maximum number of unconsumed frames on a server-bound channel.
ChannelDirection
Channel direction as reported by the server.
std::function< bool(std::unique_ptr< SegmentedMessageData > &)> ReadCallback
Callback type for receiving messages from a client-bound channel.
static constexpr unsigned DefaultToServerMaxInFlight
Default maximum number of frames sent to a server-bound channel which the simulation has not yet cons...
std::unique_ptr< ReadChannelConnection > connectClientReceiver(const std::string &channelName, ReadCallback callback, unsigned maxInFlight=DefaultToClientMaxInFlight)
Connect to a client-bound channel and receive messages via callback.
RpcClient(Logger &logger, const std::string &hostname, uint16_t port)
bool tryWriteToServer(const std::string &channelName, const std::vector< MessageData > &frames, bool force=false)
Non-blocking send of one message, split into frames, to a server-bound channel.
std::vector< uint8_t > getCompressedManifest() const
Get the compressed manifest from the server.
uint32_t getEsiVersion() const
Get the ESI version from the manifest.
static constexpr size_t MaxSendsPerTurn
The most messages a sender sends before other channels are serviced.
std::function< std::optional< std::vector< MessageData > >()> SendFetchCallback
Data source for a server-bound channel (see connectServerSender()): returns the frames of the next me...
void writeToServer(const std::string &channelName, const MessageData &data)
Send a message to a server-bound channel.
std::function< void(std::exception_ptr)> SendErrorCallback
Called with an exception thrown by a SendFetchCallback or while sending, e.g.
bool getChannelDesc(const std::string &channelName, ChannelDesc &desc) const
Get the channel description for a channel name.
std::vector< ChannelDesc > listChannels() const
List all channels available on the server.
std::unique_ptr< WriteChannelConnection > connectServerSender(const std::string &channelName, SendFetchCallback fetch, SendErrorCallback onError)
Send to a server-bound channel in callback (pull) mode, like WriteChannelPort's callback mode.
std::unique_ptr< Impl > impl
Cross-thread error channel for the IXWebSocket network thread.
void handleBinaryFrame(uint64_t generation, const std::string &data)
void sendConsumedEvent(const std::unordered_set< uint64_t > &ids)
Send a batched consumed event for any to-server messages the simulation has consumed since the last c...
void handleControlFrame(ix::WebSocket &ws, const std::string &text)
Impl(Context &ctxt, int port)
void handleEvent(uint64_t generation, const json &frame)
std::thread transportThread
Multi-producer / single-consumer dirty-set of channel ids, with CV-style blocking drain semantics.
void error(Twine message)
std::string buildDataFrame(uint64_t channelId, const uint8_t *bytes, size_t size)
Pack a cosim binary data frame: [u64 LE channel_id][payload].
constexpr uint64_t kProtocolVersion
Wire protocol version.
bool parseDataFrame(const std::string &data, uint64_t &channelId, const uint8_t *&payload, size_t &payloadSize)
Parse a cosim binary data frame.
ReadCallbackEntry(uint64_t channelId, std::function< void()> notifier)
RpcClient::ReadCallback callback
std::atomic< bool > canceled
utils::TSQueue< MessageData > queue
std::condition_variable cv
RpcClient::SendErrorCallback onError
std::recursive_mutex mutex
RpcClient::SendFetchCallback fetch
std::atomic< bool > dataAvailable
std::atomic< bool > canceled
Description of a channel from the server.