21#include <ixwebsocket/IXBase64.h>
22#include <ixwebsocket/IXNetSystem.h>
23#include <ixwebsocket/IXWebSocket.h>
24#include <ixwebsocket/IXWebSocketServer.h>
25#include <nlohmann/json.hpp>
30#include <condition_variable>
41#include <unordered_map>
42#include <unordered_set>
51#include <netinet/in.h>
52#include <sys/socket.h>
58using json = nlohmann::json;
69static void writePortFile(uint16_t port) {
70 FILE *fd = fopen(
"cosim.cfg",
"w");
73 fprintf(fd,
"port: %u\n",
static_cast<unsigned int>(port));
82static int pickEphemeralPort() {
84 SOCKET fd = socket(AF_INET, SOCK_STREAM, 0);
85 if (fd == INVALID_SOCKET)
88 int fd = socket(AF_INET, SOCK_STREAM, 0);
93 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
94 reinterpret_cast<const char *
>(&enable),
sizeof(enable));
96 addr.sin_family = AF_INET;
97 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
99 if (bind(fd,
reinterpret_cast<sockaddr *
>(&addr),
sizeof(addr)) < 0) {
108 socklen_t len =
sizeof(bound);
109 int rc = getsockname(fd,
reinterpret_cast<sockaddr *
>(&bound), &len);
117 return ntohs(bound.sin_port);
120class RpcServerReadPort;
121class RpcServerWritePort;
140 const std::string &type);
142 const std::string &type);
145 void stop(uint32_t timeoutMS);
188 std::shared_ptr<ix::WebSocket>
ws;
216 std::map<std::string, std::unique_ptr<RpcServerReadPort>>
readPorts;
217 std::map<std::string, std::unique_ptr<RpcServerWritePort>>
writePorts;
219 std::unordered_map<std::string, uint64_t>
idByName;
236 std::shared_ptr<ClientSession>
sessionFor(
const ix::WebSocket &ws) {
237 std::shared_ptr<ClientSession> s =
getSession();
238 if (s && s->ws.get() != &ws)
247 std::unique_ptr<ix::WebSocketServer>
server;
252 ix::WebSocket &ws,
const ix::WebSocketMessagePtr &msg);
253 void onOpen(
const std::weak_ptr<ix::WebSocket> &wsWeak);
254 void onClose(ix::WebSocket &ws);
258 void handleHello(ix::WebSocket &ws, uint64_t requestId,
const json ¶ms);
265 std::optional<ChannelInfo>
findChannel(ix::WebSocket &ws, uint64_t requestId,
268 void sendResult(ix::WebSocket &ws, uint64_t requestId,
const json &result);
269 void sendError(ix::WebSocket &ws, uint64_t requestId,
const std::string &code,
270 const std::string &message);
322 RpcServerReadPort(
Type *type,
Impl &impl, uint64_t channelId)
327 void connect(
const ConnectOptions &options = {})
override {
328 ConnectOptions forced = options;
329 forced.bufferSize = 0;
333 void connect(ReadCallback callback,
334 const ConnectOptions &options = {})
override {
341 void clientDisconnected(uint64_t generation) {
342 std::lock_guard<std::recursive_mutex> lock(creditMutex);
343 retiredGeneration = (std::max)(retiredGeneration, generation);
344 if (unreportedGeneration <= generation)
348 void disconnect()
override {
350 std::lock_guard<std::mutex> lock(connectMutex);
355 std::lock_guard<std::recursive_mutex> lock(creditMutex);
361 for (
auto [generation, count] : held)
362 credit(generation, count);
371 bool deliver(uint64_t generation,
const MessageData &data) {
373 std::lock_guard<std::mutex> lock(connectMutex);
374 if (!connected || !parked.empty()) {
375 parked.emplace_back(generation, data);
379 switch (handOver(generation, data)) {
380 case HandOverResult::Accepted:
382 case HandOverResult::Refused:
384 case HandOverResult::NotConnected:
389 std::lock_guard<std::mutex> lock(connectMutex);
392 parked.emplace_front(generation, data);
398 void dropped(uint64_t generation) {
399 std::lock_guard<std::recursive_mutex> lock(creditMutex);
400 credit(generation, 1);
405 void markConsumed() {
406 std::lock_guard<std::recursive_mutex> lock(creditMutex);
410 auto &[generation, count] = held.front();
411 credit(generation, 1);
418 uint64_t takeConsumed(uint64_t generation) {
419 std::lock_guard<std::recursive_mutex> lock(creditMutex);
420 if (generation != unreportedGeneration)
422 return std::exchange(unreported, 0);
426 enum class HandOverResult {
436 HandOverResult handOver(uint64_t generation,
const MessageData &data) {
437 std::unique_ptr<SegmentedMessageData> msg =
438 std::make_unique<MessageData>(data);
442 std::lock_guard<std::recursive_mutex> lock(creditMutex);
444 return HandOverResult::NotConnected;
445 if (!held.empty() && held.back().first == generation)
446 ++held.back().second;
448 held.emplace_back(generation, 1);
451 ok = invokeCallback(msg);
457 return HandOverResult::Accepted;
462 return accepting ? HandOverResult::Refused : HandOverResult::NotConnected;
469 if (--held.back().second == 0)
475 void credit(uint64_t generation, uint64_t count) {
476 if (generation <= retiredGeneration || generation < unreportedGeneration)
478 if (generation != unreportedGeneration) {
479 unreportedGeneration = generation;
483 impl.readyIds.markReady(channelId);
488 void markConnected() {
489 std::unique_lock<std::mutex> lock(connectMutex);
491 std::lock_guard<std::recursive_mutex> creditLock(creditMutex);
498 while (!parked.empty()) {
499 auto [generation, front] = parked.front();
501 HandOverResult result = handOver(generation, front);
503 if (result != HandOverResult::Accepted) {
504 if (result == HandOverResult::NotConnected && !connected)
509 impl.logRefusedFrame(channelId, front.getSize());
522 std::recursive_mutex creditMutex;
525 bool accepting =
false;
528 std::deque<std::pair<uint64_t, uint64_t>> held;
530 uint64_t unreported = 0;
531 uint64_t unreportedGeneration = 0;
533 uint64_t retiredGeneration = 0;
535 std::mutex connectMutex;
536 bool connected =
false;
539 std::deque<std::pair<uint64_t, MessageData>> parked;
556 RpcServerWritePort(
Type *type,
Impl &impl, uint64_t channelId)
558 writeQueue([&impl, channelId] { impl.readyIds.markReady(channelId); }) {
561 uint64_t getChannelId()
const {
return channelId; }
569 std::optional<MessageData> popForSend(uint64_t generation) {
570 std::lock_guard<std::mutex> lock(stateMutex);
571 if (generation <= retiredGeneration || generation != ownerGeneration)
573 std::optional<MessageData> msg = writeQueue.
pop();
578 unacked.fetch_add(1);
585 void ack(uint64_t count, uint64_t generation) {
586 std::lock_guard<std::mutex> lock(stateMutex);
587 if (generation <= retiredGeneration || generation != ownerGeneration)
590 unacked.store(unacked.load() - (std::min)(unacked.load(), count));
591 spaceCv.notify_all();
597 void subscribed(uint64_t limit, uint64_t generation) {
598 std::lock_guard<std::mutex> lock(stateMutex);
599 if (generation <= retiredGeneration)
601 if (generation != ownerGeneration) {
602 ownerGeneration = generation;
605 maxInFlight.store(limit);
606 spaceCv.notify_all();
611 void unsubscribed(uint64_t generation) {
612 std::lock_guard<std::mutex> lock(stateMutex);
613 if (generation == ownerGeneration)
614 resetFlowControlLocked();
620 void retireClient(uint64_t generation) {
621 std::lock_guard<std::mutex> lock(stateMutex);
622 retiredGeneration = (std::max)(retiredGeneration, generation);
623 if (ownerGeneration <= generation)
624 resetFlowControlLocked();
628 void disconnect()
override {
630 std::lock_guard<std::mutex> lock(stateMutex);
633 spaceCv.notify_all();
638 void connectImpl(
const ConnectOptions &)
override {
639 std::lock_guard<std::mutex> lock(stateMutex);
640 disconnected =
false;
648 std::unique_lock<std::mutex> lock(stateMutex);
649 spaceCv.wait(lock, [&] {
return disconnected || hasSpace(); });
651 throw std::runtime_error(
"Channel id " + std::to_string(channelId) +
652 " disconnected while writing");
655 bool tryWriteImpl(
const MessageData &data)
override {
656 std::lock_guard<std::mutex> lock(stateMutex);
666 writeQueue.
push(data);
669 void resetFlowControlLocked() {
672 spaceCv.notify_all();
675 bool hasSpace()
const {
676 uint64_t limit = maxInFlight.load();
677 return limit == 0 || queued.load() + unacked.load() < limit;
681 std::atomic<uint64_t> queued{0};
682 std::atomic<uint64_t> unacked{0};
687 std::mutex stateMutex;
689 std::condition_variable spaceCv;
690 bool disconnected =
false;
691 uint64_t retiredGeneration = 0;
693 uint64_t ownerGeneration = 0;
704 if (!ix::initNetSystem())
705 throw std::runtime_error(
706 "RpcServer: ix::initNetSystem() failed (WSAStartup)");
710 int requestedPort = port;
711 if (requestedPort <= 0) {
712 requestedPort = pickEphemeralPort();
713 if (requestedPort <= 0)
714 throw std::runtime_error(
715 "RpcServer: failed to obtain an ephemeral TCP port");
718 const std::string host =
"127.0.0.1";
719 server = std::make_unique<ix::WebSocketServer>(requestedPort, host);
720 server->disablePerMessageDeflate();
725 server->setOnConnectionCallback(
726 [
this](std::weak_ptr<ix::WebSocket> wsWeak,
727 std::shared_ptr<ix::ConnectionState> ) {
728 std::shared_ptr<ix::WebSocket> ws = wsWeak.lock();
731 ix::WebSocket *raw = ws.get();
732 ws->setOnMessageCallback(
733 [
this, wsWeak, raw](
const ix::WebSocketMessagePtr &msg) {
738 auto res =
server->listen();
740 throw std::runtime_error(
"RpcServer: listen failed: " + res.second);
744 writePortFile(
static_cast<uint16_t
>(
boundPort));
745 ctxt.getLogger().info(
"cosim", std::format(
"Server listening on {}:{}", host,
763 }
catch (
const std::exception &e) {
764 ctxt.getLogger().error(
766 std::string(
"Suppressed exception during ~RpcServer::Impl: ") +
769 ctxt.getLogger().error(
770 "cosim",
"Suppressed non-std::exception during ~RpcServer::Impl");
788 const std::string &type) {
792 auto port = std::make_unique<RpcServerReadPort>(
new Type(type), *
this,
id);
793 RpcServerReadPort *raw = port.get();
794 readPorts.emplace(name, std::move(port));
796 ChannelInfo info{id, name, type, ChannelDirection::ToServer, raw,
nullptr};
805 static_cast<RpcServerReadPort &
>(port).markConsumed();
809 const std::string &type) {
813 auto port = std::make_unique<RpcServerWritePort>(
new Type(type), *
this,
id);
814 RpcServerWritePort *raw = port.get();
817 ChannelInfo info{id, name, type, ChannelDirection::ToClient,
nullptr, raw};
847 std::shared_ptr<ClientSession> old;
864 const ix::WebSocketMessagePtr &msg) {
866 case ix::WebSocketMessageType::Open:
869 case ix::WebSocketMessageType::Close:
870 case ix::WebSocketMessageType::Error: {
871 ctxt.getLogger().debug(
872 "cosim", std::format(
"Client disconnected: {}",
873 msg->type == ix::WebSocketMessageType::Error
874 ? msg->errorInfo.reason
875 : msg->closeInfo.reason));
879 case ix::WebSocketMessageType::Message:
886 if (std::shared_ptr<ClientSession> s =
sessionFor(ws))
901 std::shared_ptr<ix::WebSocket> ws = wsWeak.lock();
907 session = std::make_shared<ClientSession>();
910 ctxt.getLogger().debug(
"cosim",
"Client connected");
918 ctxt.getLogger().warning(
919 "cosim",
"Rejecting additional client; one already connected");
921 err[
"type"] =
"error";
922 err[
"error"] = {{
"code",
"server_busy"},
923 {
"message",
"cosim server allows only one client at a "
924 "time; another client is already connected"}};
925 ws->sendUtf8Text(err.dump());
927 ws->close(1013,
"cosim server busy: another client is already connected");
931 std::shared_ptr<ClientSession> old;
939 old->closed.store(
true);
950 port->retireClient(generation);
952 port->clientDisconnected(generation);
957 const uint8_t *payloadBytes;
959 if (!
parseDataFrame(data, channelId, payloadBytes, payloadSize)) {
960 ctxt.getLogger().error(
"cosim",
961 "Received binary frame shorter than 8-byte header");
965 RpcServerReadPort *port =
nullptr;
970 it->second.direction != ChannelDirection::ToServer)
973 port = it->second.readPort;
976 ctxt.getLogger().error(
977 "cosim", std::format(
"Binary frame for unknown to-server channel id {}",
988 if (!port->deliver(generation, payload)) {
990 port->dropped(generation);
995 ctxt.getLogger().warning(
996 "cosim", std::format(
"Dropped {} bytes for channel id {}: refused by "
997 "the simulator-side consumer",
1004 req = json::parse(text);
1005 }
catch (
const std::exception &e) {
1006 ctxt.getLogger().error(
1007 "cosim", std::format(
"Failed to parse control frame: {}", e.what()));
1009 std::string(
"Failed to parse JSON: ") + e.what());
1014 auto typeIt = req.find(
"type");
1015 if (typeIt != req.end() && typeIt->is_string() &&
1016 typeIt->get<std::string>() ==
"event") {
1018 if (std::shared_ptr<ClientSession> s =
sessionFor(ws))
1022 if (typeIt == req.end() || !typeIt->is_string() ||
1023 typeIt->get<std::string>() !=
"request") {
1025 "Control frame missing \"type\":\"request\"");
1028 uint64_t requestId = 0;
1029 if (
auto idIt = req.find(
"request_id"); idIt != req.end()) {
1031 if (!idIt->is_number_unsigned()) {
1033 "\"request_id\" must be an unsigned integer");
1037 requestId = idIt->get<uint64_t>();
1038 }
catch (
const std::exception &e) {
1040 std::string(
"Invalid \"request_id\": ") + e.what());
1044 auto methodIt = req.find(
"method");
1045 if (methodIt == req.end() || !methodIt->is_string()) {
1046 sendError(ws, requestId,
"protocol_error",
"Missing \"method\"");
1049 std::string method = methodIt->get<std::string>();
1050 json params = req.value(
"params", json::object());
1052 if (method ==
"hello")
1054 else if (method ==
"subscribe")
1056 else if (method ==
"unsubscribe")
1059 sendError(ws, requestId,
"protocol_error",
"Unknown method: " + method);
1069 std::vector<std::pair<uint64_t, uint64_t>> &out,
1071 auto paramsIt = frame.find(
"params");
1072 if (paramsIt == frame.end() || !paramsIt->is_object()) {
1073 err =
"missing \"params\" object";
1076 auto chIt = paramsIt->find(
"channels");
1077 if (chIt == paramsIt->end() || !chIt->is_array()) {
1078 err =
"missing \"channels\" array";
1081 for (
const json &c : *chIt) {
1082 auto idIt = c.find(
"channel_id");
1083 auto countIt = c.find(
"count");
1084 if (idIt == c.end() || !idIt->is_number_unsigned() || countIt == c.end() ||
1085 !countIt->is_number_unsigned()) {
1086 err =
"entries need unsigned \"channel_id\" and \"count\"";
1089 out.emplace_back(idIt->get<uint64_t>(), countIt->get<uint64_t>());
1095 std::string
event = frame.value(
"event", std::string());
1096 if (event !=
"consumed") {
1099 ctxt.getLogger().debug(
"cosim",
1100 "Ignoring unknown client event \"" + event +
"\"");
1103 std::vector<std::pair<uint64_t, uint64_t>> acks;
1106 ctxt.getLogger().warning(
"cosim",
"Malformed consumed event: " + err);
1110 for (
auto [
id, count] : acks) {
1112 if (it ==
channelById.end() || !it->second.writePort) {
1113 ctxt.getLogger().warning(
1115 std::format(
"consumed event for unknown to-client channel id {}",
1119 it->second.writePort->ack(count, generation);
1124 const json ¶ms) {
1125 auto verIt = params.find(
"client_protocol_version");
1126 if (verIt == params.end() || !verIt->is_number_unsigned() ||
1128 std::string got = verIt == params.end() ?
"none" : verIt->dump();
1129 sendError(ws, requestId,
"unsupported_version",
1130 std::format(
"Server speaks cosim protocol v{}; client requested "
1131 "{}. Update the ESI runtime on both sides.",
1148 result[
"compressed_manifest_b64"] = macaron::Base64::Encode(
1153 json channelsJson = json::array();
1163 c[
"channel_id"] = info.id;
1164 c[
"name"] = info.name;
1165 c[
"type"] = info.typeId;
1166 c[
"direction"] = info.direction == ChannelDirection::ToServer
1169 channelsJson.push_back(std::move(c));
1172 result[
"channels"] = std::move(channelsJson);
1174 if (std::shared_ptr<ClientSession> s =
sessionFor(ws))
1175 s->helloDone =
true;
1181 const json ¶ms) {
1182 auto chIdIt = params.find(
"channel_id");
1183 if (chIdIt == params.end() || !chIdIt->is_number_unsigned()) {
1184 sendError(ws, requestId,
"protocol_error",
1185 "subscribe requires unsigned \"channel_id\"");
1188 uint64_t channelId = chIdIt->get<uint64_t>();
1190 if (
auto limitIt = params.find(
"max_in_flight"); limitIt != params.end()) {
1191 if (!limitIt->is_number_unsigned()) {
1192 sendError(ws, requestId,
"protocol_error",
1193 "\"max_in_flight\" must be an unsigned integer");
1196 maxInFlight = limitIt->get<uint64_t>();
1199 std::optional<ChannelInfo> info =
1200 findChannel(ws, requestId, channelId, ChannelDirection::ToClient);
1203 std::shared_ptr<ClientSession> s =
sessionFor(ws);
1205 sendError(ws, requestId,
"internal",
"No active session");
1209 std::lock_guard<std::mutex> subLock(s->subscribedMutex);
1210 if (s->subscribed.count(channelId)) {
1211 sendError(ws, requestId,
"protocol_error",
1212 std::format(
"Channel id {} is already subscribed", channelId));
1215 s->subscribed.insert(channelId);
1216 info->writePort->subscribed(maxInFlight, s->generation);
1231 const json ¶ms) {
1232 auto chIdIt = params.find(
"channel_id");
1233 if (chIdIt == params.end() || !chIdIt->is_number_unsigned()) {
1234 sendError(ws, requestId,
"protocol_error",
1235 "unsubscribe requires unsigned \"channel_id\"");
1238 uint64_t channelId = chIdIt->get<uint64_t>();
1240 RpcServerWritePort *writePort =
nullptr;
1245 writePort = it->second.writePort;
1248 std::shared_ptr<ClientSession> s =
sessionFor(ws);
1250 sendError(ws, requestId,
"internal",
"No active session");
1256 std::lock_guard<std::mutex> subLock(s->subscribedMutex);
1257 auto removed = s->subscribed.erase(channelId);
1259 sendError(ws, requestId,
"not_subscribed",
1260 std::format(
"Channel id {} is not subscribed", channelId));
1267 writePort->unsubscribed(s->generation);
1276 std::optional<ChannelInfo> info;
1284 sendError(ws, requestId,
"unknown_channel",
1285 std::format(
"No channel with id {}", channelId));
1286 return std::nullopt;
1288 if (info->direction != dir) {
1289 sendError(ws, requestId,
"wrong_direction",
1290 std::format(
"Channel id {} is not a {} channel", channelId,
1291 dir == ChannelDirection::ToServer ?
"to-server"
1293 return std::nullopt;
1299 const json &result) {
1301 resp[
"type"] =
"response";
1302 resp[
"request_id"] = requestId;
1303 resp[
"result"] = result;
1306 ws.sendUtf8Text(resp.dump());
1310 const std::string &code,
const std::string &message) {
1312 resp[
"type"] =
"response";
1313 resp[
"request_id"] = requestId;
1314 resp[
"error"] = {{
"code", code}, {
"message", message}};
1315 ws.sendUtf8Text(resp.dump());
1327 std::unordered_set<uint64_t> ids;
1331 for (uint64_t
id : ids) {
1332 RpcServerWritePort *writePort =
nullptr;
1337 it->second.direction != ChannelDirection::ToClient)
1339 writePort = it->second.writePort;
1353 std::shared_ptr<ClientSession> s =
getSession();
1359 if (s->closed.load())
1361 std::lock_guard<std::mutex> subLock(s->subscribedMutex);
1362 if (!s->subscribed.count(
id))
1364 std::optional<MessageData> msg = writePort->popForSend(s->generation);
1367 std::string frame =
buildDataFrame(
id, msg->getBytes(), msg->getSize());
1370 s->ws->sendBinary(frame);
1379 std::shared_ptr<ClientSession> s =
getSession();
1380 if (!s || !s->helloDone)
1382 std::vector<std::pair<uint64_t, RpcServerReadPort *>> ports;
1385 for (uint64_t
id : ids) {
1387 if (it !=
channelById.end() && it->second.readPort)
1388 ports.emplace_back(
id, it->second.readPort);
1391 json channels = json::array();
1392 for (
auto [
id, port] : ports)
1393 if (uint64_t count = port->takeConsumed(s->generation))
1394 channels.push_back({{
"channel_id",
id}, {
"count", count}});
1395 if (channels.empty())
1399 event[
"type"] =
"event";
1400 event[
"event"] =
"consumed";
1401 event[
"params"] = {{
"channels", std::move(channels)}};
1402 s->ws->sendUtf8Text(event.dump());
1413 const std::vector<uint8_t> &compressedManifest) {
1415 throw std::runtime_error(
"Server not running");
1416 impl->setManifest(esiVersion, compressedManifest);
1420 const std::string &type) {
1422 throw std::runtime_error(
"Server not running");
1423 return impl->registerReadPort(name, type);
1427 const std::string &type) {
1429 throw std::runtime_error(
"Server not running");
1430 return impl->registerWritePort(name, type);
1435 throw std::runtime_error(
"Server not running");
1436 impl->messageConsumed(port);
1441 throw std::runtime_error(
"Server already running");
1442 impl = std::make_unique<Impl>(
ctxt, port);
1447 throw std::runtime_error(
"Server not running");
1448 impl->stop(timeoutMS);
1453 throw std::runtime_error(
"Server not running");
1454 return impl->getPort();
esi::cosim::RpcServer::Impl Impl
static bool parseConsumedEvent(const json &frame, std::vector< std::pair< uint64_t, uint64_t > > &out, std::string &err)
Parse the channels list of a consumed event into (channel_id, count) pairs.
A client for the cosim RPC server.
static constexpr unsigned DefaultToClientMaxInFlight
Default maximum number of frames in flight (queued in the simulator or sent but not yet consumed by t...
AcceleratorConnections, Accelerators, and Manifests must all share a context.
A concrete flat message backed by a single vector of bytes.
size_t getSize() const
Get the size of the data in bytes.
A ChannelPort which reads data from the accelerator.
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
virtual void disconnect() override
Disconnect the channel.
Root class of the ESI type system.
A ChannelPort which sends data to the accelerator.
virtual void disconnect() override
Disconnect the port.
A client for the cosim RPC server.
ChannelDirection
Channel direction as reported by the server.
static constexpr unsigned DefaultToClientMaxInFlight
Default maximum number of frames in flight (queued in the simulator or sent but not yet consumed by t...
Cross-thread error channel for the IXWebSocket network thread.
ReadChannelPort & registerReadPort(const std::string &name, const std::string &type)
std::unique_ptr< ix::WebSocketServer > server
void onClose(ix::WebSocket &ws)
void logRefusedFrame(uint64_t channelId, size_t size)
Log that a size-byte frame for channel channelId was dropped since the simulator-side consumer refuse...
void handleBinaryFrame(uint64_t generation, const std::string &data)
std::vector< uint8_t > compressedManifest
void handleUnsubscribe(ix::WebSocket &ws, uint64_t requestId, const json ¶ms)
std::optional< ChannelInfo > findChannel(ix::WebSocket &ws, uint64_t requestId, uint64_t channelId, ChannelDirection dir)
Look up a channel.
std::unordered_map< std::string, uint64_t > idByName
uint64_t nextSessionGeneration
void sendResult(ix::WebSocket &ws, uint64_t requestId, const json &result)
void handleHello(ix::WebSocket &ws, uint64_t requestId, const json ¶ms)
::esi::cosim::FaultStash faultStash
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)
std::shared_ptr< ClientSession > session
void sendError(ix::WebSocket &ws, uint64_t requestId, const std::string &code, const std::string &message)
Impl(Context &ctxt, int port)
void stop(uint32_t timeoutMS)
std::condition_variable manifestReadyCV
std::map< std::string, std::unique_ptr< RpcServerWritePort > > writePorts
std::shared_ptr< ClientSession > sessionFor(const ix::WebSocket &ws)
The active session if ws is its socket, else null.
void handleEvent(uint64_t generation, const json &frame)
WriteChannelPort & registerWritePort(const std::string &name, const std::string &type)
std::unordered_map< uint64_t, ChannelInfo > channelById
std::map< std::string, std::unique_ptr< RpcServerReadPort > > readPorts
std::thread transportThread
backends::cosim::RpcClient::ChannelDirection ChannelDirection
void handleSubscribe(ix::WebSocket &ws, uint64_t requestId, const json ¶ms)
void onOpen(const std::weak_ptr< ix::WebSocket > &wsWeak)
void onClientMessage(const std::weak_ptr< ix::WebSocket > &wsWeak, ix::WebSocket &ws, const ix::WebSocketMessagePtr &msg)
utils::ReadyIdSet< uint64_t > readyIds
void retireSession(uint64_t generation)
Forget all per-channel state belonging to client session generation, which has disconnected.
std::shared_ptr< ClientSession > getSession()
The active session, if any.
void messageConsumed(ReadChannelPort &port)
void setManifest(int esiVersion, const std::vector< uint8_t > &compressedManifest)
void messageConsumed(ReadChannelPort &port)
Report that the simulation has consumed one message read from port (which must have been returned by ...
ReadChannelPort & registerReadPort(const std::string &name, const std::string &type)
Register a read or write port which communicates over RPC.
void stop(uint32_t timeoutMS=0)
void setManifest(int esiVersion, const std::vector< uint8_t > &compressedManifest)
Set the manifest and version.
std::unique_ptr< Impl > impl
WriteChannelPort & registerWritePort(const std::string &name, const std::string &type)
Multi-producer / single-consumer dirty-set of channel ids, with CV-style blocking drain semantics.
void push(E... t)
Push onto the queue.
std::optional< T > pop()
Pop something off the queue but return nullopt if the queue is empty.
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.
RpcServerReadPort * readPort
ChannelDirection direction
RpcServerWritePort * writePort
std::shared_ptr< ix::WebSocket > ws
std::atomic< bool > closed
std::mutex subscribedMutex
std::unordered_set< uint64_t > subscribed
std::atomic< bool > helloDone