CIRCT 24.0.0git
Loading...
Searching...
No Matches
RpcClient.cpp
Go to the documentation of this file.
1//===- RpcClient.cpp - ESI Cosim RPC client implementation ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Client implementation of the cosim WebSocket + JSON protocol. The wire
10// protocol is documented in cosim-protocol.md.
11//
12//===----------------------------------------------------------------------===//
13
15#include "esi/Logging.h"
16#include "esi/Utils.h"
17
18#include "RpcWire.h"
19
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>
25
26#include <atomic>
27#include <chrono>
28#include <condition_variable>
29#include <cstdint>
30#include <cstring>
31#include <future>
32#include <map>
33#include <memory>
34#include <mutex>
35#include <optional>
36#include <stdexcept>
37#include <string>
38#include <thread>
39#include <unordered_map>
40#include <vector>
41
42using namespace esi;
43using namespace esi::backends::cosim;
44using json = nlohmann::json;
45
46//===----------------------------------------------------------------------===//
47// RpcClient::Impl - hides IXWebSocket + JSON behind the public header
48//===----------------------------------------------------------------------===//
49
50namespace {
51class ReadChannelConnectionImpl;
52} // namespace
53
55public:
56 Impl(Logger &logger, const std::string &hostname, uint16_t port);
58
59 Logger &getLogger() { return logger; }
60
61 uint32_t getEsiVersion() const { return esiVersion; }
62 std::vector<uint8_t> getCompressedManifest() const { return manifest; }
63
64 bool getChannelDesc(const std::string &name,
65 RpcClient::ChannelDesc &desc) const;
66 std::vector<RpcClient::ChannelDesc> listChannels() const;
67
68 void writeToServer(const std::string &channelName, const MessageData &data);
69 bool tryWriteToServer(const std::string &channelName,
70 const std::vector<MessageData> &frames, bool force);
71 void setToServerMaxInFlight(const std::string &channelName,
72 unsigned maxInFlight);
73
74 std::unique_ptr<RpcClient::WriteChannelConnection>
75 connectServerSender(const std::string &channelName,
78
79 std::unique_ptr<RpcClient::ReadChannelConnection>
80 connectClientReceiver(const std::string &channelName,
81 RpcClient::ReadCallback callback, unsigned maxInFlight);
82
83 // Helpers used by ReadChannelConnectionImpl.
84 void unsubscribe(uint64_t channelId);
85 void unregisterCallback(uint64_t channelId);
86
87 // Per-channel write sender state; see `connectServerSender()`. Held by
88 // `shared_ptr` so the transport thread can copy the entry under the lock and
89 // call it while a concurrent `unregisterSender()` erases the map entry.
93 std::atomic<bool> canceled{false};
94 // False once `fetch` returns nullopt (or throws), until notified.
95 std::atomic<bool> dataAvailable{true};
96 // Held while calling the callbacks, so `unregisterSender()` can wait for a
97 // call in progress. Recursive since they may unregister the sender.
98 std::recursive_mutex mutex;
99 };
100
101 // Helpers used by WriteChannelConnectionImpl.
102 void notifySender(uint64_t channelId, WriteSenderEntry &entry) {
103 entry.dataAvailable.store(true);
104 readyIds.markReady(channelId);
105 }
106 void unregisterSender(uint64_t channelId,
107 const std::shared_ptr<WriteSenderEntry> &entry);
108
109private:
110 /// Fetch and send messages for a sender while its channel has room and it
111 /// has data, for up to `MaxSendsPerTurn` messages. Returns true if it should
112 /// be called again. Called on the transport thread, holding `entry.mutex`.
113 bool runSender(uint64_t channelId, WriteSenderEntry &entry);
114
115public:
116private:
117 struct ChannelMeta {
118 uint64_t id;
119 std::string name;
120 std::string type;
122 };
123
124 // ---- websocket lifecycle ----
125 void onMessage(const ix::WebSocketMessagePtr &msg);
126 void handleControlFrame(const std::string &text);
127 void handleEvent(const json &frame);
128 void handleBinaryFrame(const std::string &data);
129 void failAllPending(const std::string &reason);
130 /// Wake every writer blocked on credits so it can observe the lost
131 /// connection and throw.
133
134 // ---- request/response plumbing ----
135
136 /// Issue a JSON-RPC style request and synchronously await the response.
137 /// Throws on error (transport or server-reported).
138 json call(const std::string &method, json params);
139
140 /// Look up a to-server channel by name, throwing if it isn't one.
141 const ChannelMeta &getToServerChannel(const std::string &channelName) const;
142 /// Send one data frame. Throws on a transport failure.
143 void sendFrame(const ChannelMeta &meta, const MessageData &data);
144
145 std::string host;
147
148 // Manifest + channel table cached from the `hello` response.
149 uint32_t esiVersion = 0;
150 std::vector<uint8_t> manifest;
151 std::unordered_map<std::string, ChannelMeta> channelsByName;
152 std::unordered_map<uint64_t, ChannelMeta> channelsById;
153
154 // Per to-server channel credit state. `outstanding` counts frames sent but
155 // not yet reported consumed by the server. Writers block on `cv` while
156 // `outstanding >= maxInFlight` (unless it is 0, i.e. unbounded). The map
157 // is populated once in the constructor and never mutated afterwards, so
158 // lookups need no lock.
159 struct WriteCredit {
160 std::mutex mutex;
161 std::condition_variable cv;
162 uint64_t outstanding = 0;
164 };
165 std::unordered_map<uint64_t, std::unique_ptr<WriteCredit>> writeCredits;
166 /// Schedule a call to channel `channelId`'s sender, if it has one.
167 void markSenderReady(uint64_t channelId);
168 std::atomic<bool> connectionLost{false};
169 // Set once the constructor has populated the channel tables. Events from
170 // the server which arrive earlier (e.g. stale credits for a previous
171 // client's frames) are ignored.
172 std::atomic<bool> channelTablesReady{false};
173
174 // Pending control-plane requests, keyed by id.
175 std::mutex pendingMutex;
176 std::atomic<uint64_t> nextRequestId{1};
177 std::unordered_map<uint64_t, std::shared_ptr<std::promise<json>>> pending;
178
179 // Per-channel read state. Connection-time `subscribe` registers; the
180 // ReadChannelConnection destructor unregisters and sends `unsubscribe`.
181 //
182 // Each entry owns its own non-blocking TSQueue: `handleBinaryFrame` only
183 // pushes into the queue (on IX's single per-connection network thread),
184 // and a dedicated transport thread is what actually invokes the
185 // user-supplied callback. That decoupling is what makes the client
186 // cross-channel-deadlock-safe regardless of what the user's callback
187 // does: a callback that returns `false` (rejects the message) only
188 // delays its own channel -- the IX thread is free to keep delivering on
189 // other channels.
190 //
191 // The queue's `notifier` rings the server-wide doorbell
192 // (`Impl::markReady`) so the transport thread wakes up only when there's
193 // work for a specific channel.
194 //
195 // Held by `shared_ptr` so the transport thread can copy the entry under
196 // the lock and outlive a concurrent `unregisterCallback` that erases the
197 // map entry: the cancel flag flips, the transport thread sees it on its
198 // next iteration, and drops anything still in the queue.
201 std::atomic<bool> canceled{false};
202 uint64_t channelId;
204
205 ReadCallbackEntry(uint64_t channelId, std::function<void()> notifier)
206 : channelId(channelId), queue(std::move(notifier)) {}
207 };
209 std::unordered_map<uint64_t, std::shared_ptr<ReadCallbackEntry>>
211 // Write senders, by channel id. Their ids share `readyIds` with
212 // `readCallbacks`, since channel ids are unique across both directions.
214 std::unordered_map<uint64_t, std::shared_ptr<WriteSenderEntry>> writeSenders;
215 // Orders sending acknowledgements against canceling a subscription:
216 // `consumed` events are sent under it and leave out canceled entries, and
217 // entries are canceled under it before `unsubscribe` is sent. So an
218 // acknowledgement never follows its subscription's `unsubscribe` (and
219 // perhaps a new `subscribe`) and gets counted against the next one.
220 std::mutex ackMutex;
221
222 // Dirty-set doorbell for the transport thread. Each entry's TSQueue
223 // notifier inserts the channel id into `readyIds` and wakes the consumer.
225 std::thread transportThread;
226
228 /// Report `acks` (subscription -> count) of client-bound frames as
229 /// consumed, leaving out canceled subscriptions.
231 const std::unordered_map<std::shared_ptr<ReadCallbackEntry>, uint64_t>
232 &acks);
233
234 // Connection-open synchronization. The WS callback fires on IX's background
235 // thread, so the constructor blocks here until either Open or Error fires.
236 std::mutex openMutex;
237 std::condition_variable openCV;
238 enum class OpenState { Pending, Open, Failed } openState{OpenState::Pending};
239 std::string openError;
240
241 // Most recent unsolicited server-initiated error (`type="error"`), if any.
242 // The server sends one of these before closing the WS to explain why (e.g.
243 // `server_busy`). Recorded so a subsequent Close/Error path can surface it
244 // instead of the much-less-actionable raw WebSocket close reason.
246 std::string lastServerError;
247
248 std::atomic<bool> disconnecting{false};
249
250 // Cross-thread fault propagation out of the IX network thread. See
251 // FaultStash docs in RpcWire.h.
253
254 // Declared last so it's destroyed first: its destructor stops IX's threads,
255 // whose callbacks use the members above. That matters when the constructor
256 // throws after starting it, since then `~Impl()` doesn't run.
257 ix::WebSocket ws;
258};
259
260//===----------------------------------------------------------------------===//
261// ReadChannelConnectionImpl
262//
263// Held by the consumer of `connectClientReceiver`. Destructor unregisters the
264// callback and sends `unsubscribe`. The actual incoming bytes are delivered
265// by the shared websocket callback in RpcClient::Impl.
266//===----------------------------------------------------------------------===//
267
268namespace {
269class ReadChannelConnectionImpl : public RpcClient::ReadChannelConnection {
270public:
271 ReadChannelConnectionImpl(RpcClient::Impl *impl, uint64_t channelId)
272 : impl(impl), channelId(channelId) {}
273 ~ReadChannelConnectionImpl() override { disconnect(); }
274
275 void disconnect() override {
276 if (disconnected.exchange(true))
277 return;
278 impl->unregisterCallback(channelId);
279 try {
280 impl->unsubscribe(channelId);
281 } catch (const std::exception &e) {
282 // We're tearing down a per-channel reader and can't propagate the
283 // exception (this runs in a destructor). Log it so the failure isn't
284 // silently lost.
285 impl->getLogger().warning(
286 "cosim",
287 std::string("unsubscribe during disconnect failed: ") + e.what());
288 }
289 }
290
291private:
293 uint64_t channelId;
294 std::atomic<bool> disconnected{false};
295};
296
297class WriteChannelConnectionImpl : public RpcClient::WriteChannelConnection {
298public:
299 WriteChannelConnectionImpl(
300 RpcClient::Impl *impl, uint64_t channelId,
301 std::shared_ptr<RpcClient::Impl::WriteSenderEntry> entry)
302 : impl(impl), channelId(channelId), entry(std::move(entry)) {}
303 ~WriteChannelConnectionImpl() override { disconnect(); }
304
305 void notify() override {
306 if (!entry->canceled.load())
307 impl->notifySender(channelId, *entry);
308 }
309 void disconnect() override { impl->unregisterSender(channelId, entry); }
310
311private:
312 RpcClient::Impl *impl;
313 uint64_t channelId;
314 std::shared_ptr<RpcClient::Impl::WriteSenderEntry> entry;
315};
316} // namespace
317
318//===----------------------------------------------------------------------===//
319// RpcClient::Impl - construction / `hello` handshake
320//===----------------------------------------------------------------------===//
321
322RpcClient::Impl::Impl(Logger &logger, const std::string &hostname,
323 uint16_t port)
324 : host(hostname), logger(logger) {
325 // On Windows, `ix::initNetSystem()` calls `WSAStartup`; bail out cleanly if
326 // it fails rather than letting the WS start path fail with a less
327 // actionable `WSANOTINITIALISED`. No-op on other platforms.
328 if (!ix::initNetSystem())
329 throw std::runtime_error(
330 "RpcClient: ix::initNetSystem() failed (WSAStartup)");
331
332 ws.setUrl("ws://" + host + ":" + std::to_string(port) + "/esi/cosim/v" +
333 std::to_string(::esi::cosim::kProtocolVersion));
334 ws.disablePerMessageDeflate();
335 ws.disableAutomaticReconnection();
336
337 ws.setOnMessageCallback(
338 [this](const ix::WebSocketMessagePtr &msg) { onMessage(msg); });
339
340 ws.start();
341
342 // Wait for the WS to reach Open (or fail).
343 {
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);
349 }
350
351 // Send `hello`; the server blocks the response until its manifest is ready.
352 json result = call(
353 "hello", {{"client_protocol_version", ::esi::cosim::kProtocolVersion}});
354 auto verIt = result.find("protocol_version");
355 if (verIt == result.end() || !verIt->is_number_unsigned() ||
356 verIt->get<uint64_t>() != ::esi::cosim::kProtocolVersion)
357 throw std::runtime_error(
358 "RpcClient: server speaks an unsupported cosim protocol version (" +
359 (verIt == result.end() ? std::string("none") : verIt->dump()) +
360 "); expected " + std::to_string(::esi::cosim::kProtocolVersion));
361
362 // Cache manifest blob.
363 if (auto it = result.find("esi_version"); it != result.end())
364 esiVersion = it->get<uint32_t>();
365 if (auto it = result.find("compressed_manifest_b64"); it != result.end()) {
366 // macaron::Base64::Decode returns an empty error string on success and
367 // writes raw bytes into the out string; reinterpret as a byte vector.
368 std::string raw;
369 std::string err = macaron::Base64::Decode(it->get<std::string>(), raw);
370 if (!err.empty())
371 throw std::runtime_error("RpcClient: invalid base64 in manifest blob: " +
372 err);
373 manifest.assign(raw.begin(), raw.end());
374 }
375
376 // Cache channel table.
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) {
381 ChannelMeta meta;
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));
392 }
393 // Publish the channel tables to the IX network thread (see handleEvent).
394 channelTablesReady.store(true, std::memory_order_release);
395
396 // Start the transport thread now that initialisation is complete. It
397 // sleeps on `readyIds`'s internal CV until a per-channel TSQueue push
398 // wakes it.
399 transportThread = std::thread([this] { transportLoop(); });
400}
401
403 disconnecting = true;
404 failAllPending("client shutdown");
405 markConnectionLost();
406 // Mark every per-channel entry canceled so the transport loop drops any
407 // remaining queued frames promptly instead of spinning on the user
408 // callback.
409 {
410 std::lock_guard<std::mutex> lock(readCallbacksMutex);
411 for (auto &[id, entry] : readCallbacks)
412 entry->canceled.store(true);
413 }
414 {
415 std::lock_guard<std::mutex> lock(writeSendersMutex);
416 for (auto &[id, entry] : writeSenders)
417 entry->canceled.store(true);
418 }
419 // Stop IX *first* so no more `handleBinaryFrame` calls can fire and push
420 // into the per-channel queues. ws.stop() joins IX's internal threads
421 // synchronously.
422 ws.stop();
423 // Now retire the transport thread; nothing else is producing for it.
424 if (transportThread.joinable()) {
425 readyIds.requestShutdown();
426 transportThread.join();
427 }
428}
429
430//===----------------------------------------------------------------------===//
431// RpcClient::Impl - WebSocket message dispatch
432//===----------------------------------------------------------------------===//
433
434void RpcClient::Impl::onMessage(const ix::WebSocketMessagePtr &msg) {
435 switch (msg->type) {
436 case ix::WebSocketMessageType::Open: {
437 std::lock_guard<std::mutex> lock(openMutex);
438 openState = OpenState::Open;
439 openCV.notify_all();
440 return;
441 }
442 case ix::WebSocketMessageType::Error: {
443 std::string reason = msg->errorInfo.reason;
444 {
445 std::lock_guard<std::mutex> lock(lastServerErrorMutex);
446 if (!lastServerError.empty())
447 reason = lastServerError;
448 }
449 {
450 std::lock_guard<std::mutex> lock(openMutex);
451 if (openState == OpenState::Pending) {
452 openState = OpenState::Failed;
453 openError = reason;
454 openCV.notify_all();
455 }
456 }
457 failAllPending("websocket error: " + reason);
458 markConnectionLost();
459 return;
460 }
461 case ix::WebSocketMessageType::Close: {
462 std::string reason = msg->closeInfo.reason;
463 {
464 std::lock_guard<std::mutex> lock(lastServerErrorMutex);
465 if (!lastServerError.empty())
466 reason = lastServerError;
467 }
468 // If the server closed us before `Open` settled (e.g. immediate
469 // `server_busy` reject), surface that as an Open failure so the
470 // constructor's wait unblocks with a useful error.
471 {
472 std::lock_guard<std::mutex> lock(openMutex);
473 if (openState == OpenState::Pending) {
474 openState = OpenState::Failed;
475 openError = reason;
476 openCV.notify_all();
477 }
478 }
479 failAllPending("websocket closed: " + reason);
480 markConnectionLost();
481 return;
482 }
483 case ix::WebSocketMessageType::Message:
484 // An exception escaping this callback would kill IX's network thread.
485 // Stash the first one so the next public RpcClient method rethrows it
486 // on the user's thread.
487 try {
488 if (msg->binary)
489 handleBinaryFrame(msg->str);
490 else
491 handleControlFrame(msg->str);
492 } catch (...) {
493 faultStash.record(std::current_exception());
494 }
495 return;
496 default:
497 return;
498 }
499}
500
501void RpcClient::Impl::handleControlFrame(const std::string &text) {
502 json resp;
503 try {
504 resp = json::parse(text);
505 } catch (const std::exception &e) {
506 // Unparseable text frame: nothing useful we can do.
507 return;
508 }
509 auto typeIt = resp.find("type");
510 if (typeIt == resp.end() || !typeIt->is_string())
511 return;
512 std::string type = typeIt->get<std::string>();
513
514 // Unsolicited server-initiated error. The server sends one of these before
515 // closing the WS (e.g. `server_busy`). Stash the message so the imminent
516 // Close event surfaces this human-readable reason instead of just the raw
517 // WebSocket close reason.
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;
524 }
525 return;
526 }
527
528 if (type == "event") {
529 handleEvent(resp);
530 return;
531 }
532
533 if (type != "response") {
534 // Unknown control-frame type. Per the protocol, receivers MUST ignore
535 // unrecognised fields/types so the wire format can evolve additively
536 // under the same `protocol_version`, but warn so genuine misbehavior
537 // doesn't go silently dropped.
538 logger.debug("cosim",
539 "Ignoring control frame with unknown type \"" + type + "\"");
540 return;
541 }
542 auto idIt = resp.find("request_id");
543 if (idIt == resp.end())
544 return;
545 uint64_t requestId = idIt->get<uint64_t>();
546
547 std::shared_ptr<std::promise<json>> promise;
548 {
549 std::lock_guard<std::mutex> lock(pendingMutex);
550 auto it = pending.find(requestId);
551 if (it == pending.end())
552 return;
553 promise = it->second;
554 // Erase under the lock so a concurrent `failAllPending` won't also
555 // try to fulfill the same promise.
556 pending.erase(it);
557 }
558
559 try {
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);
567 } else {
568 // Per the wire spec, a `type=response` frame MUST carry either
569 // `result` (success) or `error` (failure). Surface the protocol
570 // violation to the caller instead of pretending it succeeded.
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))));
575 }
576 } catch (const std::exception &e) {
577 // Promise might be already satisfied if we raced with a shutdown that
578 // already fulfilled it via failAllPending. Benign, but log so unexpected
579 // duplicate responses from the server don't go entirely unnoticed.
580 logger.debug("cosim",
581 std::string("failed to fulfill promise for request_id=") +
582 std::to_string(requestId) + ": " + e.what());
583 }
584}
585
586void RpcClient::Impl::handleEvent(const json &frame) {
587 std::string event = frame.value("event", std::string());
588 if (event != "consumed") {
589 logger.debug("cosim", "Ignoring unknown server event \"" + event + "\"");
590 return;
591 }
592 if (!channelTablesReady.load(std::memory_order_acquire))
593 return;
594 auto paramsIt = frame.find("params");
595 if (paramsIt == frame.end() || !paramsIt->is_object())
596 return;
597 auto chIt = paramsIt->find("channels");
598 if (chIt == paramsIt->end() || !chIt->is_array())
599 return;
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());
606 continue;
607 }
608 auto credIt = writeCredits.find(idIt->get<uint64_t>());
609 if (credIt == writeCredits.end())
610 continue;
611 WriteCredit &cred = *credIt->second;
612 uint64_t count = countIt->get<uint64_t>();
613 {
614 std::lock_guard<std::mutex> lock(cred.mutex);
615 // Clamp: credits for frames sent by a previous client are possible.
616 cred.outstanding -= (std::min)(cred.outstanding, count);
617 }
618 cred.cv.notify_all();
619 markSenderReady(credIt->first);
620 }
621}
622
623void RpcClient::Impl::markSenderReady(uint64_t channelId) {
624 std::lock_guard<std::mutex> lock(writeSendersMutex);
625 if (writeSenders.count(channelId))
626 readyIds.markReady(channelId);
627}
628
630 connectionLost.store(true);
631 if (!channelTablesReady.load(std::memory_order_acquire))
632 return;
633 for (auto &[id, cred] : writeCredits) {
634 // Take the lock so a writer can't miss the wakeup between checking its
635 // predicate and blocking.
636 { std::lock_guard<std::mutex> lock(cred->mutex); }
637 cred->cv.notify_all();
638 // So they find out, e.g. to report it.
639 markSenderReady(id);
640 }
641}
642
643void RpcClient::Impl::handleBinaryFrame(const std::string &data) {
644 uint64_t channelId;
645 const uint8_t *payloadBytes;
646 size_t payloadSize;
647 if (!::esi::cosim::parseDataFrame(data, channelId, payloadBytes, payloadSize))
648 return;
649
650 std::shared_ptr<ReadCallbackEntry> entry;
651 {
652 std::lock_guard<std::mutex> lock(readCallbacksMutex);
653 auto it = readCallbacks.find(channelId);
654 if (it == readCallbacks.end()) {
655 // Per the protocol, the server MUST stop sending frames for a channel
656 // after the unsubscribe-ack. A frame for an unknown channel is
657 // therefore either a server bug or a misrouted message: warn rather
658 // than silently dropping so the issue is visible.
659 logger.warning("cosim", "Dropping inbound frame for channel id " +
660 std::to_string(channelId) +
661 ": no active subscriber");
662 return;
663 }
664 entry = it->second;
665 }
666
667 // Push the payload into the per-channel queue and return immediately;
668 // never block IX's network thread on the user-supplied callback. The
669 // queue's notifier rings the transport doorbell, and the dedicated
670 // transport thread is what actually invokes the callback.
671 entry->queue.push(MessageData(payloadBytes, payloadSize));
672}
673
674void RpcClient::Impl::failAllPending(const std::string &reason) {
675 std::lock_guard<std::mutex> lock(pendingMutex);
676 for (auto &[id, pr] : pending) {
677 try {
678 pr->set_exception(std::make_exception_ptr(std::runtime_error(reason)));
679 } catch (const std::exception &e) {
680 // Already-satisfied promise; benign but log it in case a real bug is
681 // racing with shutdown.
682 logger.debug("cosim", std::string("failAllPending: request_id=") +
683 std::to_string(id) +
684 " already satisfied: " + e.what());
685 }
686 }
687 pending.clear();
688}
689
690//===----------------------------------------------------------------------===//
691// RpcClient::Impl - request/response, sends
692//===----------------------------------------------------------------------===//
693
694json RpcClient::Impl::call(const std::string &method, json params) {
695 faultStash.check();
696 uint64_t requestId = nextRequestId.fetch_add(1);
697 std::future<json> future;
698 {
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));
703 }
704
705 json req;
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();
711
712 // No send-side mutex needed: IXWebSocket's `sendUtf8Text` is internally
713 // serialized with `sendBinary`, and every cosim frame is a single send
714 // call (no header+body splits).
715 auto info = ws.sendUtf8Text(text);
716 if (!info.success) {
717 std::lock_guard<std::mutex> plock(pendingMutex);
718 pending.erase(requestId);
719 throw std::runtime_error("RpcClient: failed to send " + method);
720 }
721
722 // Bounded wait so callers cannot hang forever on a missing/lost response.
723 // On WS close or error, `failAllPending()` fires and the future becomes
724 // ready immediately. The timeout only matters if the server stays
725 // connected but never replies (server bug, lost control frame).
726 constexpr auto kCallTimeout = std::chrono::seconds(30);
727 if (future.wait_for(kCallTimeout) != std::future_status::ready) {
728 // Drop the pending entry so a late response doesn't fulfill a
729 // destroyed promise (with shared_ptr it's still safe, but it would
730 // otherwise leak the slot forever).
731 std::lock_guard<std::mutex> plock(pendingMutex);
732 pending.erase(requestId);
733 throw std::runtime_error("RpcClient: timed out waiting for response to " +
734 method);
735 }
736 return future.get();
737}
738
739const RpcClient::Impl::ChannelMeta &
740RpcClient::Impl::getToServerChannel(const std::string &channelName) const {
741 auto it = channelsByName.find(channelName);
742 if (it == channelsByName.end())
743 throw std::runtime_error("Unknown channel '" + channelName + "'");
744 if (it->second.direction != RpcClient::ChannelDirection::ToServer)
745 throw std::runtime_error("Channel '" + channelName +
746 "' is not a to-server channel");
747 return it->second;
748}
749
750void RpcClient::Impl::sendFrame(const ChannelMeta &meta,
751 const MessageData &data) {
752 std::string frame =
753 esi::cosim::buildDataFrame(meta.id, data.getBytes(), data.getSize());
754 // IXWebSocket serializes sends internally; no extra mutex needed.
755 auto info = ws.sendBinary(frame);
756 if (!info.success)
757 throw std::runtime_error("Failed to send data on channel '" + meta.name +
758 "'");
759}
760
761void RpcClient::Impl::writeToServer(const std::string &channelName,
762 const MessageData &data) {
763 faultStash.check();
764 const ChannelMeta &meta = getToServerChannel(channelName);
765 WriteCredit &cred = *writeCredits.at(meta.id);
766 {
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;
771 });
772 if (connectionLost.load())
773 throw std::runtime_error("Connection to cosim server lost while "
774 "writing to channel '" +
775 channelName + "'");
776 ++cred.outstanding;
777 }
778 sendFrame(meta, data);
779}
780
781bool RpcClient::Impl::tryWriteToServer(const std::string &channelName,
782 const std::vector<MessageData> &frames,
783 bool force) {
784 faultStash.check();
785 const ChannelMeta &meta = getToServerChannel(channelName);
786 WriteCredit &cred = *writeCredits.at(meta.id);
787 {
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 '" +
792 channelName + "'");
793 if (!force && cred.maxInFlight != 0 && cred.outstanding >= cred.maxInFlight)
794 return false;
795 cred.outstanding += frames.size();
796 }
797 for (const MessageData &frame : frames)
798 sendFrame(meta, frame);
799 return true;
800}
801
802void RpcClient::Impl::setToServerMaxInFlight(const std::string &channelName,
803 unsigned maxInFlight) {
804 const ChannelMeta &meta = getToServerChannel(channelName);
805 WriteCredit &cred = *writeCredits.at(meta.id);
806 {
807 std::lock_guard<std::mutex> lock(cred.mutex);
808 cred.maxInFlight = maxInFlight;
809 }
810 cred.cv.notify_all();
811 markSenderReady(meta.id);
812}
813
814std::unique_ptr<RpcClient::WriteChannelConnection>
815RpcClient::Impl::connectServerSender(const std::string &channelName,
818 faultStash.check();
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);
825 {
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");
830 }
831 return std::make_unique<WriteChannelConnectionImpl>(this, channelId,
832 std::move(entry));
833}
834
835bool RpcClient::Impl::runSender(uint64_t channelId, WriteSenderEntry &entry) {
836 const ChannelMeta &meta = channelsById.at(channelId);
837 WriteCredit &cred = *writeCredits.at(channelId);
838 for (size_t i = 0; i < RpcClient::MaxSendsPerTurn; ++i) {
839 if (entry.canceled.load())
840 return false;
841 bool lost;
842 {
843 std::lock_guard<std::mutex> lock(cred.mutex);
844 lost = connectionLost.load();
845 if (!lost && cred.maxInFlight != 0 &&
846 cred.outstanding >= cred.maxInFlight)
847 return false;
848 }
849 if (lost) {
850 entry.onError(std::make_exception_ptr(std::runtime_error(
851 "Connection to cosim server lost while writing to channel '" +
852 meta.name + "'")));
853 return false;
854 }
855 // Cleared before fetching, so a notification which arrives while fetching
856 // (and which would be missed if this returns nullopt) isn't lost.
857 if (!entry.dataAvailable.exchange(false))
858 return false;
859 std::optional<std::vector<MessageData>> frames;
860 std::exception_ptr error;
861 try {
862 frames = entry.fetch();
863 } catch (...) {
864 error = std::current_exception();
865 }
866 // If the callback disconnected the sender, drop the message (or error).
867 if (entry.canceled.load())
868 return false;
869 if (error) {
870 entry.onError(error);
871 continue;
872 }
873 if (!frames)
874 continue;
875 // The callback had data, so it may have more.
876 entry.dataAvailable.store(true);
877 {
878 std::lock_guard<std::mutex> lock(cred.mutex);
879 cred.outstanding += frames->size();
880 }
881 try {
882 for (const MessageData &frame : *frames)
883 sendFrame(meta, frame);
884 } catch (...) {
885 entry.onError(std::current_exception());
886 }
887 }
888 // Out of turns, not data: continue after servicing other channels.
889 return !entry.canceled.load();
890}
891
893 uint64_t channelId, const std::shared_ptr<WriteSenderEntry> &entry) {
894 {
895 std::lock_guard<std::mutex> lock(writeSendersMutex);
896 auto it = writeSenders.find(channelId);
897 // Unless a replacement has already been registered.
898 if (it != writeSenders.end() && it->second == entry)
899 writeSenders.erase(it);
900 }
901 entry->canceled.store(true);
902 // Wait for a call in progress on the transport thread to return, unless this
903 // is it.
904 std::lock_guard<std::recursive_mutex> lock(entry->mutex);
905}
906
907//===----------------------------------------------------------------------===//
908// RpcClient::Impl - channel descriptor lookup
909//===----------------------------------------------------------------------===//
910
911bool RpcClient::Impl::getChannelDesc(const std::string &name,
912 RpcClient::ChannelDesc &desc) const {
913 auto it = channelsByName.find(name);
914 if (it == channelsByName.end())
915 return false;
916 desc.name = it->second.name;
917 desc.type = it->second.type;
918 desc.dir = it->second.direction;
919 return true;
920}
921
922std::vector<RpcClient::ChannelDesc> RpcClient::Impl::listChannels() const {
923 std::vector<RpcClient::ChannelDesc> out;
924 out.reserve(channelsByName.size());
925 for (const auto &[name, meta] : channelsByName) {
926 RpcClient::ChannelDesc d;
927 d.name = meta.name;
928 d.type = meta.type;
929 d.dir = meta.direction;
930 out.push_back(std::move(d));
931 }
932 return out;
933}
934
935//===----------------------------------------------------------------------===//
936// RpcClient::Impl - subscribe / unsubscribe
937//===----------------------------------------------------------------------===//
938
939std::unique_ptr<RpcClient::ReadChannelConnection>
940RpcClient::Impl::connectClientReceiver(const std::string &channelName,
942 unsigned maxInFlight) {
943 faultStash.check();
944 auto it = channelsByName.find(channelName);
945 if (it == channelsByName.end())
946 throw std::runtime_error("Unknown channel '" + channelName + "'");
947 if (it->second.direction != RpcClient::ChannelDirection::ToClient)
948 throw std::runtime_error("Channel '" + channelName +
949 "' is not a to-client channel");
950 uint64_t channelId = it->second.id;
951
952 // Register the callback first so any racing inbound binary frame after the
953 // server's subscribe-ack has somewhere to land. Refuse a second receiver
954 // here rather than letting it replace the first one's callback.
955 auto entry = std::make_shared<ReadCallbackEntry>(
956 channelId, [this, channelId] { readyIds.markReady(channelId); });
957 entry->callback = std::move(callback);
958 {
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");
963 }
964
965 try {
966 call("subscribe",
967 {{"channel_id", channelId}, {"max_in_flight", maxInFlight}});
968 } catch (...) {
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);
973 throw;
974 }
975
976 return std::make_unique<ReadChannelConnectionImpl>(this, channelId);
977}
978
979void RpcClient::Impl::unsubscribe(uint64_t channelId) {
980 if (disconnecting)
981 return;
982 // Skip the RPC if the WS is already closed (server tore down first, network
983 // drop, etc.). The unsubscribe is moot anyway, and otherwise every
984 // per-channel cleanup during teardown would generate a noisy "failed to
985 // send unsubscribe" warning from ReadChannelConnectionImpl::disconnect.
986 if (ws.getReadyState() != ix::ReadyState::Open)
987 return;
988 call("unsubscribe", {{"channel_id", channelId}});
989}
990
991void RpcClient::Impl::unregisterCallback(uint64_t channelId) {
992 std::shared_ptr<ReadCallbackEntry> entry;
993 {
994 std::lock_guard<std::mutex> lock(readCallbacksMutex);
995 auto it = readCallbacks.find(channelId);
996 if (it == readCallbacks.end())
997 return;
998 entry = it->second;
999 readCallbacks.erase(it);
1000 }
1001 // Flip the cancel flag on the entry that any in-flight transport-loop
1002 // iteration already copied out, so it bails out promptly and drops any
1003 // remaining queued frames (and their acknowledgements; see `ackMutex`).
1004 {
1005 std::lock_guard<std::mutex> lock(ackMutex);
1006 entry->canceled.store(true);
1007 }
1008 // Nudge the transport thread so it observes the cancelation promptly and
1009 // drains+drops whatever's still queued.
1010 readyIds.markReady(channelId);
1011}
1012
1013//===----------------------------------------------------------------------===//
1014// RpcClient::Impl - transport thread (per-channel deadlock isolation)
1015//===----------------------------------------------------------------------===//
1016
1018 // Channels whose last delivery attempt left a message at the head of the
1019 // queue (user callback returned `false`). We retry them after a short
1020 // backoff so other channels still get a chance every wake, and so a
1021 // permanently-busy channel doesn't pin the CPU.
1022 std::unordered_set<uint64_t> retry;
1023
1024 while (true) {
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)))
1029 return;
1030 ids.insert(retry.begin(), retry.end());
1031 retry.clear();
1032
1033 // Frames consumed this pass, per subscription. Reported to the server in
1034 // one batched event at the end of the pass to return their credits.
1035 std::unordered_map<std::shared_ptr<ReadCallbackEntry>, uint64_t> acks;
1036 for (uint64_t id : ids) {
1037 std::shared_ptr<WriteSenderEntry> sender;
1038 {
1039 std::lock_guard<std::mutex> lock(writeSendersMutex);
1040 auto it = writeSenders.find(id);
1041 if (it != writeSenders.end())
1042 sender = it->second;
1043 }
1044 if (sender) {
1045 std::lock_guard<std::recursive_mutex> lock(sender->mutex);
1046 if (sender->canceled.load() || disconnecting)
1047 continue;
1048 try {
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());
1054 } catch (...) {
1055 logger.error("cosim",
1056 "Write error callback threw an unknown exception");
1057 }
1058 continue;
1059 }
1060
1061 std::shared_ptr<ReadCallbackEntry> entry;
1062 {
1063 std::lock_guard<std::mutex> lock(readCallbacksMutex);
1064 auto it = readCallbacks.find(id);
1065 if (it == readCallbacks.end())
1066 continue;
1067 entry = it->second;
1068 }
1069
1070 if (entry->canceled.load() || disconnecting)
1071 continue;
1072
1073 // Best-effort drain. `TSQueue::pop(callback)` peeks at the front and
1074 // only pops if our callback returns true; on `false` we leave the
1075 // message at the head and mark the channel for retry.
1076 bool stuck = false;
1077 while (!stuck && !entry->canceled.load() && !disconnecting) {
1078 bool gotOne = false;
1079 entry->queue.pop([&](const MessageData &data) {
1080 gotOne = true;
1081 std::unique_ptr<SegmentedMessageData> msg =
1082 std::make_unique<MessageData>(data);
1083 if (entry->callback(msg)) {
1084 ++acks[entry];
1085 return true;
1086 }
1087 stuck = true;
1088 return false;
1089 });
1090 if (!gotOne)
1091 break; // queue empty
1092 if (stuck)
1093 retry.insert(id);
1094 }
1095 }
1096 if (!acks.empty())
1097 sendConsumedEvent(acks);
1098 }
1099}
1100
1102 const std::unordered_map<std::shared_ptr<ReadCallbackEntry>, uint64_t>
1103 &acks) {
1104 // Held while sending; see `ackMutex`.
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())
1111 return;
1112 json event;
1113 event["type"] = "event";
1114 event["event"] = "consumed";
1115 event["params"] = {{"channels", std::move(channels)}};
1116 // A failed send means the connection is going away, and with it the
1117 // server's flow-control state; nothing to recover.
1118 ws.sendUtf8Text(event.dump());
1119}
1120
1121//===----------------------------------------------------------------------===//
1122// RpcClient - public pass-throughs (unchanged API)
1123//===----------------------------------------------------------------------===//
1124
1125RpcClient::RpcClient(Logger &logger, const std::string &hostname, uint16_t port)
1126 : impl(std::make_unique<Impl>(logger, hostname, port)) {}
1127
1128RpcClient::~RpcClient() = default;
1129
1130uint32_t RpcClient::getEsiVersion() const { return impl->getEsiVersion(); }
1131
1132std::vector<uint8_t> RpcClient::getCompressedManifest() const {
1133 return impl->getCompressedManifest();
1134}
1135
1136bool RpcClient::getChannelDesc(const std::string &channelName,
1137 ChannelDesc &desc) const {
1138 return impl->getChannelDesc(channelName, desc);
1139}
1140
1141std::vector<RpcClient::ChannelDesc> RpcClient::listChannels() const {
1142 return impl->listChannels();
1143}
1144
1145void RpcClient::writeToServer(const std::string &channelName,
1146 const MessageData &data) {
1147 impl->writeToServer(channelName, data);
1148}
1149
1150bool RpcClient::tryWriteToServer(const std::string &channelName,
1151 const std::vector<MessageData> &frames,
1152 bool force) {
1153 return impl->tryWriteToServer(channelName, frames, force);
1154}
1155
1156void RpcClient::setToServerMaxInFlight(const std::string &channelName,
1157 unsigned maxInFlight) {
1158 impl->setToServerMaxInFlight(channelName, maxInFlight);
1159}
1160
1161std::unique_ptr<RpcClient::WriteChannelConnection>
1162RpcClient::connectServerSender(const std::string &channelName,
1163 SendFetchCallback fetch,
1164 SendErrorCallback onError) {
1165 return impl->connectServerSender(channelName, std::move(fetch),
1166 std::move(onError));
1167}
1168
1169std::unique_ptr<RpcClient::ReadChannelConnection>
1170RpcClient::connectClientReceiver(const std::string &channelName,
1171 ReadCallback callback, unsigned maxInFlight) {
1172 return impl->connectClientReceiver(channelName, std::move(callback),
1173 maxInFlight);
1174}
nlohmann::json json
Get a JSON representation of a type.
Definition RpcClient.cpp:44
std::vector< uint8_t > getCompressedManifest() const
Definition RpcClient.cpp:62
void markConnectionLost()
Wake every writer blocked on credits so it can observe the lost connection and throw.
void handleControlFrame(const std::string &text)
void unsubscribe(uint64_t channelId)
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::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::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::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
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
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.
::esi::cosim::FaultStash faultStash
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)
virtual void error(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an error.
Definition Logging.h:64
virtual void warning(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a warning.
Definition Logging.h:70
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
Definition Logging.h:83
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
Abstract handle for a read channel connection.
Definition RpcClient.h:141
Handle for a sender registered with connectServerSender().
Definition RpcClient.h:109
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.
Definition RpcClient.h:52
std::function< bool(std::unique_ptr< SegmentedMessageData > &)> ReadCallback
Callback type for receiving messages from a client-bound channel.
Definition RpcClient.h:136
static constexpr unsigned DefaultToServerMaxInFlight
Default maximum number of frames sent to a server-bound channel which the simulation has not yet cons...
Definition RpcClient.h:70
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.
Definition RpcClient.h:120
std::function< std::optional< std::vector< MessageData > >()> SendFetchCallback
Data source for a server-bound channel (see connectServerSender()): returns the frames of the next me...
Definition RpcClient.h:101
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.
Definition RpcClient.h:105
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
Definition RpcClient.h:160
Cross-thread error channel for the IXWebSocket network thread.
Definition RpcWire.h:73
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)
Multi-producer / single-consumer dirty-set of channel ids, with CV-style blocking drain semantics.
Definition Utils.h:177
Thread safe queue.
Definition Utils.h:48
void info(Twine message)
Definition LSPUtils.cpp:20
void error(Twine message)
Definition LSPUtils.cpp:16
std::string buildDataFrame(uint64_t channelId, const uint8_t *bytes, size_t size)
Pack a cosim binary data frame: [u64 LE channel_id][payload].
Definition RpcWire.h:33
constexpr uint64_t kProtocolVersion
Wire protocol version.
Definition RpcWire.h:30
bool parseDataFrame(const std::string &data, uint64_t &channelId, const uint8_t *&payload, size_t &payloadSize)
Parse a cosim binary data frame.
Definition RpcWire.h:52
Definition esi.py:1
ChannelDirection dir
Definition RpcClient.h:58
ReadCallbackEntry(uint64_t channelId, std::function< void()> notifier)
Description of a channel from the server.
Definition RpcClient.h:55