CIRCT 24.0.0git
Loading...
Searching...
No Matches
RpcServer.cpp
Go to the documentation of this file.
1//===- RpcServer.cpp - Run a cosim server ---------------------------------===//
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// Implementation of the cosim RPC server over the WebSocket + JSON protocol.
10// The wire protocol is documented in cosim-protocol.md.
11//
12//===----------------------------------------------------------------------===//
13
15#include "esi/Context.h"
16#include "esi/Utils.h"
17#include "esi/backends/RpcClient.h" // for ChannelDirection
18
19#include "RpcWire.h"
20
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>
26
27#include <algorithm>
28#include <atomic>
29#include <cassert>
30#include <condition_variable>
31#include <cstdint>
32#include <cstdio>
33#include <cstring>
34#include <deque>
35#include <format>
36#include <map>
37#include <mutex>
38#include <optional>
39#include <string>
40#include <thread>
41#include <unordered_map>
42#include <unordered_set>
43#include <utility>
44#include <vector>
45
46#ifdef _WIN32
47#include <winsock2.h>
48#include <ws2tcpip.h>
49#else
50#include <arpa/inet.h>
51#include <netinet/in.h>
52#include <sys/socket.h>
53#include <unistd.h>
54#endif
55
56using namespace esi;
57using namespace esi::cosim;
58using json = nlohmann::json;
59
60namespace {
61
62//===----------------------------------------------------------------------===//
63// Helpers
64//===----------------------------------------------------------------------===//
65
66/// Write the bound port number to a file so callers (typically esi-cosim) can
67/// discover it. Necessary when the OS picks the port, since the simulator's
68/// stdout/stderr buffering is undefined.
69static void writePortFile(uint16_t port) {
70 FILE *fd = fopen("cosim.cfg", "w");
71 if (!fd)
72 return;
73 fprintf(fd, "port: %u\n", static_cast<unsigned int>(port));
74 fclose(fd);
75}
76
77/// Pre-bind a temporary loopback socket to port 0 to discover an OS-assigned
78/// ephemeral port. IXWebSocket exposes the port a user passed in but does not
79/// query `getsockname` after binding, so for the "let the OS pick" path we have
80/// to find a free port ourselves and hand it to IX. SO_REUSEADDR + immediate
81/// close keep the race window minimal in practice.
82static int pickEphemeralPort() {
83#ifdef _WIN32
84 SOCKET fd = socket(AF_INET, SOCK_STREAM, 0);
85 if (fd == INVALID_SOCKET)
86 return -1;
87#else
88 int fd = socket(AF_INET, SOCK_STREAM, 0);
89 if (fd < 0)
90 return -1;
91#endif
92 int enable = 1;
93 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
94 reinterpret_cast<const char *>(&enable), sizeof(enable));
95 sockaddr_in addr{};
96 addr.sin_family = AF_INET;
97 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
98 addr.sin_port = 0;
99 if (bind(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) < 0) {
100#ifdef _WIN32
101 closesocket(fd);
102#else
103 close(fd);
104#endif
105 return -1;
106 }
107 sockaddr_in bound{};
108 socklen_t len = sizeof(bound);
109 int rc = getsockname(fd, reinterpret_cast<sockaddr *>(&bound), &len);
110#ifdef _WIN32
111 closesocket(fd);
112#else
113 close(fd);
114#endif
115 if (rc < 0)
116 return -1;
117 return ntohs(bound.sin_port);
118}
119
120class RpcServerReadPort;
121class RpcServerWritePort;
122
123} // namespace
124
125//===----------------------------------------------------------------------===//
126// RpcServer::Impl - private implementation
127//===----------------------------------------------------------------------===//
128
130public:
131 Impl(Context &ctxt, int port);
132 ~Impl();
133
134 Context &getContext() { return ctxt; }
135
136 void setManifest(int esiVersion,
137 const std::vector<uint8_t> &compressedManifest);
138
139 ReadChannelPort &registerReadPort(const std::string &name,
140 const std::string &type);
141 WriteChannelPort &registerWritePort(const std::string &name,
142 const std::string &type);
144
145 void stop(uint32_t timeoutMS);
146 int getPort() const { return boundPort; }
147
148 // Dirty-set doorbell for the transport thread. Public so each port's
149 // TSQueue can pass `[&impl, id]{ impl.readyIds.markReady(id); }` as its
150 // push-notifier; also called directly from `handleSubscribe` to flush
151 // anything queued before the subscription arrived.
153
154 /// Log that a `size`-byte frame for channel `channelId` was dropped since
155 /// the simulator-side consumer refused it.
156 void logRefusedFrame(uint64_t channelId, size_t size);
157
158private:
159 // Reuse the public direction enum from the client side rather than
160 // duplicating it; both ends of the cosim transport agree on the same two
161 // values.
163 struct ChannelInfo {
164 uint64_t id;
165 std::string name;
166 std::string typeId;
168 RpcServerReadPort *readPort = nullptr;
169 RpcServerWritePort *writePort = nullptr;
170 };
171
172 // Locking rules. IXWebSocket may invoke the close callback (`onClose`)
173 // synchronously from inside a send on a dead socket, on whichever thread is
174 // sending. So:
175 // - Never send while holding `channelsMutex`, `sessionMutex` or a port's
176 // `connectMutex`; `onClose` takes the first two.
177 // - Sending while holding a session's `subscribedMutex` is allowed (it
178 // orders data frames against the unsubscribe-ack), so never wait for
179 // `subscribedMutex` while holding any other lock.
180 // - Senders hold a `shared_ptr` to the session, which owns the socket,
181 // so `onClose` never has to wait for them. Since `onClose` can't take
182 // `subscribedMutex` either, per-port client state is tagged with the
183 // session's generation, and `onClose` retires the generation so late
184 // updates from in-progress requests are ignored.
185 // - Within a port, only the write queue's and the doorbell's locks are
186 // taken while holding its `stateMutex`.
188 std::shared_ptr<ix::WebSocket> ws;
189 // The set of `to_client` channel ids the client subscribed to. Guarded by
190 // `subscribedMutex`.
191 std::mutex subscribedMutex;
192 std::unordered_set<uint64_t> subscribed;
193 // True once `hello` has been answered.
194 std::atomic<bool> helloDone = false;
195 // Set once the client has disconnected.
196 std::atomic<bool> closed = false;
197 // Distinguishes this session from earlier ones, so state belonging to an
198 // earlier client (e.g. credits for frames it sent) isn't given to this
199 // one.
200 uint64_t generation = 0;
201 };
202
204
205 // Manifest state. setManifest() flips manifestReady and broadcasts the CV;
206 // any in-flight `hello` handler blocks on this until it is set.
207 std::mutex manifestMutex;
208 std::condition_variable manifestReadyCV;
209 int esiVersion = -1;
210 std::vector<uint8_t> compressedManifest;
211 bool manifestReady = false;
212
213 // Channel table is keyed by name in the public API and by id on the wire.
214 // Ports are owned here; ChannelInfo holds non-owning pointers.
215 std::mutex channelsMutex;
216 std::map<std::string, std::unique_ptr<RpcServerReadPort>> readPorts;
217 std::map<std::string, std::unique_ptr<RpcServerWritePort>> writePorts;
218 std::unordered_map<uint64_t, ChannelInfo> channelById;
219 std::unordered_map<std::string, uint64_t> idByName;
220 uint64_t nextChannelId = 0;
221
222 // Session state. v4 of the protocol allows a single concurrent client.
223 std::mutex sessionMutex;
224 std::shared_ptr<ClientSession> session;
226
227 /// The active session, if any. The returned pointer stays valid after the
228 /// client disconnects; sends on it then just fail.
229 std::shared_ptr<ClientSession> getSession() {
230 std::lock_guard<std::mutex> lock(sessionMutex);
231 return session;
232 }
233 /// The active session if `ws` is its socket, else null. Requests are
234 /// handled through this, so one still being handled when its client
235 /// disconnects can't act on a replacement client's session.
236 std::shared_ptr<ClientSession> sessionFor(const ix::WebSocket &ws) {
237 std::shared_ptr<ClientSession> s = getSession();
238 if (s && s->ws.get() != &ws)
239 return nullptr;
240 return s;
241 }
242
243 // Transport thread; drains `readyIds` and dispatches per channel id.
244 std::thread transportThread;
245
246 // The IXWebSocket server.
247 std::unique_ptr<ix::WebSocketServer> server;
248 int boundPort = -1;
249
250 // Connection callbacks.
251 void onClientMessage(const std::weak_ptr<ix::WebSocket> &wsWeak,
252 ix::WebSocket &ws, const ix::WebSocketMessagePtr &msg);
253 void onOpen(const std::weak_ptr<ix::WebSocket> &wsWeak);
254 void onClose(ix::WebSocket &ws);
255 void handleBinaryFrame(uint64_t generation, const std::string &data);
256 void handleControlFrame(ix::WebSocket &ws, const std::string &text);
257 void handleEvent(uint64_t generation, const json &frame);
258 void handleHello(ix::WebSocket &ws, uint64_t requestId, const json &params);
259 void handleSubscribe(ix::WebSocket &ws, uint64_t requestId,
260 const json &params);
261 void handleUnsubscribe(ix::WebSocket &ws, uint64_t requestId,
262 const json &params);
263 /// Look up a channel. If it doesn't exist or doesn't have direction `dir`,
264 /// reply with an error and return nullopt.
265 std::optional<ChannelInfo> findChannel(ix::WebSocket &ws, uint64_t requestId,
266 uint64_t channelId,
267 ChannelDirection dir);
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);
271
272 void transportLoop();
273 /// Send a batched `consumed` event for any to-server messages the
274 /// simulation has consumed since the last call. Transport thread only.
275 void sendConsumedEvent(const std::unordered_set<uint64_t> &ids);
276 /// Forget all per-channel state belonging to client session `generation`,
277 /// which has disconnected.
278 void retireSession(uint64_t generation);
279
280 // Cross-thread fault propagation out of the IX network thread. See
281 // FaultStash docs in RpcWire.h.
283};
284
286
287//===----------------------------------------------------------------------===//
288// Port implementations
289//
290// Read and write ports are simple queues; the RPC server pushes/pops as
291// appropriate. These mirror the previous gRPC implementation: they are
292// transport-agnostic except that write port writes ring the sender doorbell.
293//===----------------------------------------------------------------------===//
294
295namespace {
296/// Read port for "to server" channels.
297///
298/// The cosim transport hands inbound frames synchronously from the IX
299/// network thread, which is shared across every channel on a connection.
300/// Any back-pressure on a per-port consumer would stall that thread and risk
301/// a cross-channel deadlock when an accelerator's flow control requires
302/// ordering across channels. So we *force* polling-mode `connect` to use an
303/// unbounded internal queue regardless of what the caller passes --
304/// `ReadChannelPort::pollingState` then acts as our buffer and
305/// `invokeCallback` is guaranteed non-blocking. The unbounded queue mirrors
306/// the existing `to_client` write queue and is acceptable for a cosim
307/// driver. The client bounds how many messages it sends ahead of the
308/// simulation using credits which this port returns via `markConsumed()`.
309///
310/// Frames which arrive while the port is not connected are parked here, in
311/// order, and handed over when it connects. They stay in flight until the
312/// simulation consumes them, so the client is backpressured rather than
313/// having its frames dropped.
314///
315/// Each frame's credit belongs to the client session which sent it. Frames
316/// outlive their session (in the base class's queue or parked here), so they
317/// are tracked by session, and credits for a session which has gone are
318/// dropped rather than handed to the next client: a new client starts with
319/// nothing in flight.
320class RpcServerReadPort : public ReadChannelPort {
321public:
322 RpcServerReadPort(Type *type, Impl &impl, uint64_t channelId)
323 : ReadChannelPort(type), impl(impl), channelId(channelId) {}
324
325 /// Polling-mode connect: force the internal queue to be unbounded
326 /// (`bufferSize == 0`) regardless of what the caller asked for.
327 void connect(const ConnectOptions &options = {}) override {
328 ConnectOptions forced = options;
329 forced.bufferSize = 0;
331 markConnected();
332 }
333 void connect(ReadCallback callback,
334 const ConnectOptions &options = {}) override {
335 ReadChannelPort::connect(std::move(callback), options);
336 markConnected();
337 }
339
340 /// Client session `generation` closed: its credits are dropped.
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)
345 unreported = 0;
346 }
347
348 void disconnect() override {
349 {
350 std::lock_guard<std::mutex> lock(connectMutex);
351 connected = false;
352 }
353 // Held across the base class's disconnect so no frame is handed over and
354 // counted in `held` after its queue is torn down (see `handOver()`).
355 std::lock_guard<std::recursive_mutex> lock(creditMutex);
356 accepting = false;
358 // The base class discarded whatever it had queued for the simulation.
359 // Return those frames' credits, like the server stops counting a client's
360 // unconsumed frames on `unsubscribe`.
361 for (auto [generation, count] : held)
362 credit(generation, count);
363 held.clear();
364 }
365
366 /// Hand one inbound frame from client session `generation` to the
367 /// simulation, or park it if the port isn't connected (or earlier frames
368 /// are still parked). Returns `false` only if a connected callback-mode
369 /// consumer refused the frame, in which case the caller should drop it and
370 /// call `dropped()`.
371 bool deliver(uint64_t generation, const MessageData &data) {
372 {
373 std::lock_guard<std::mutex> lock(connectMutex);
374 if (!connected || !parked.empty()) {
375 parked.emplace_back(generation, data);
376 return true;
377 }
378 }
379 switch (handOver(generation, data)) {
380 case HandOverResult::Accepted:
381 return true;
382 case HandOverResult::Refused:
383 return false;
384 case HandOverResult::NotConnected:
385 break;
386 }
387 // Lost a race with `disconnect()`: park it at the front, since it arrived
388 // before anything parked since.
389 std::lock_guard<std::mutex> lock(connectMutex);
390 if (connected)
391 return false;
392 parked.emplace_front(generation, data);
393 return true;
394 }
395
396 /// A frame from client session `generation` was dropped rather than handed
397 /// to the simulation. Return its credit.
398 void dropped(uint64_t generation) {
399 std::lock_guard<std::recursive_mutex> lock(creditMutex);
400 credit(generation, 1);
401 }
402
403 /// The simulation consumed the oldest frame handed to it. Return its credit
404 /// to the session which sent it.
405 void markConsumed() {
406 std::lock_guard<std::recursive_mutex> lock(creditMutex);
407 // Empty if its credit was already returned by `disconnect()`.
408 if (held.empty())
409 return;
410 auto &[generation, count] = held.front();
411 credit(generation, 1);
412 if (--count == 0)
413 held.pop_front();
414 }
415
416 /// Take (and zero) the credits not yet returned to client session
417 /// `generation`.
418 uint64_t takeConsumed(uint64_t generation) {
419 std::lock_guard<std::recursive_mutex> lock(creditMutex);
420 if (generation != unreportedGeneration)
421 return 0;
422 return std::exchange(unreported, 0);
423 }
424
425private:
426 enum class HandOverResult {
427 Accepted,
428 /// Refused by the connected callback-mode consumer.
429 Refused,
430 /// The port is disconnected (or being disconnected).
431 NotConnected,
432 };
433
434 /// Pass one frame from session `generation` to the base class's callback /
435 /// polling queue, counting it in `held` if that worked.
436 HandOverResult handOver(uint64_t generation, const MessageData &data) {
437 std::unique_ptr<SegmentedMessageData> msg =
438 std::make_unique<MessageData>(data);
439 // Held throughout, so `disconnect()` sees the frame either counted in
440 // `held` or not handed over at all. Counted first, since a callback-mode
441 // consumer may report it consumed from within the callback.
442 std::lock_guard<std::recursive_mutex> lock(creditMutex);
443 if (!accepting)
444 return HandOverResult::NotConnected;
445 if (!held.empty() && held.back().first == generation)
446 ++held.back().second;
447 else
448 held.emplace_back(generation, 1);
449 bool ok = false;
450 try {
451 ok = invokeCallback(msg);
452 } catch (...) {
453 unhold();
454 throw;
455 }
456 if (ok)
457 return HandOverResult::Accepted;
458 unhold();
459 // `accepting` can only have changed if the consumer disconnected the port
460 // from within the callback. Otherwise, the consumer refused the frame,
461 // even if a `disconnect()` is waiting for `creditMutex`.
462 return accepting ? HandOverResult::Refused : HandOverResult::NotConnected;
463 }
464
465 /// Undo the count of the frame `handOver()` failed to hand over.
466 void unhold() {
467 if (held.empty())
468 return;
469 if (--held.back().second == 0)
470 held.pop_back();
471 }
472
473 /// Return `count` credits to session `generation`, unless it has gone.
474 /// Caller holds `creditMutex`.
475 void credit(uint64_t generation, uint64_t count) {
476 if (generation <= retiredGeneration || generation < unreportedGeneration)
477 return;
478 if (generation != unreportedGeneration) {
479 unreportedGeneration = generation;
480 unreported = 0;
481 }
482 unreported += count;
483 impl.readyIds.markReady(channelId);
484 }
485
486 /// Called after the base class has finished connecting (so inbound frames
487 /// will be accepted). Flushes parked frames in order.
488 void markConnected() {
489 std::unique_lock<std::mutex> lock(connectMutex);
490 {
491 std::lock_guard<std::recursive_mutex> creditLock(creditMutex);
492 accepting = true;
493 }
494 connected = true;
495 // `deliver()` keeps appending to `parked` (rather than delivering
496 // directly) until it's empty, which preserves ordering while we flush
497 // without holding the lock across the callback.
498 while (!parked.empty()) {
499 auto [generation, front] = parked.front();
500 lock.unlock();
501 HandOverResult result = handOver(generation, front);
502 lock.lock();
503 if (result != HandOverResult::Accepted) {
504 if (result == HandOverResult::NotConnected && !connected)
505 break; // Disconnected again; leave it parked.
506 // Refused by a callback-mode consumer: drop it, like a frame which
507 // arrives while connected (see `deliver()`), rather than leave it
508 // blocking everything after it.
509 impl.logRefusedFrame(channelId, front.getSize());
510 dropped(generation);
511 }
512 parked.pop_front();
513 }
514 }
515
516 Impl &impl;
517 uint64_t channelId;
518
519 // Guards the credit state below. Also held while a frame is handed over
520 // (see `handOver()`), and recursive since a callback-mode consumer may
521 // report a frame consumed from within the callback.
522 std::recursive_mutex creditMutex;
523 // Whether frames may be handed to the base class: set once it has connected
524 // and cleared before it disconnects.
525 bool accepting = false;
526 // Frames handed to the base class and not yet consumed, oldest first, as
527 // runs of (client session generation, count).
528 std::deque<std::pair<uint64_t, uint64_t>> held;
529 // Credits not yet returned to session `unreportedGeneration`.
530 uint64_t unreported = 0;
531 uint64_t unreportedGeneration = 0;
532 // Sessions up to this one have closed; their credits are dropped.
533 uint64_t retiredGeneration = 0;
534
535 std::mutex connectMutex;
536 bool connected = false;
537 // Frames received while not connected, oldest first, with the generation
538 // of the session which sent them.
539 std::deque<std::pair<uint64_t, MessageData>> parked;
540};
541
542/// Write queue for "to client" channels. Writes go into the per-port TSQueue;
543/// the queue's notifier hook rings the transport doorbell so the transport
544/// thread wakes up and drains across the WebSocket. DPI threads must never
545/// block on I/O, so this path is strictly non-blocking.
546///
547/// Flow control: the port's in-flight count is the number of messages queued
548/// here plus the number sent to the client but not yet reported consumed.
549/// `tryWrite()` refuses new messages while that count is at the in-flight
550/// limit. The limit is set by the client on `subscribe` (0 means unbounded)
551/// and reverts to the default when there is no subscriber.
552class RpcServerWritePort : public WriteChannelPort {
553public:
555
556 RpcServerWritePort(Type *type, Impl &impl, uint64_t channelId)
557 : WriteChannelPort(type), channelId(channelId), impl(impl),
558 writeQueue([&impl, channelId] { impl.readyIds.markReady(channelId); }) {
559 }
560
561 uint64_t getChannelId() const { return channelId; }
562 uint64_t channelId;
564
565 /// Pop the next queued message for sending to client session
566 /// `generation`, accounting it as sent but unacknowledged. Returns nullopt
567 /// once that session is retired, so nothing is sent (and counted) for a
568 /// client which has gone away.
569 std::optional<MessageData> popForSend(uint64_t generation) {
570 std::lock_guard<std::mutex> lock(stateMutex);
571 if (generation <= retiredGeneration || generation != ownerGeneration)
572 return std::nullopt;
573 std::optional<MessageData> msg = writeQueue.pop();
574 if (!msg)
575 return std::nullopt;
576 // Increment `unacked` before decrementing `queued` so a concurrent
577 // `hasSpace()` never under-counts the in-flight total.
578 unacked.fetch_add(1);
579 queued.fetch_sub(1);
580 return msg;
581 }
582
583 /// Client session `generation` reported `count` messages consumed. Ignored
584 /// unless it owns the flow-control state (see `subscribed()`).
585 void ack(uint64_t count, uint64_t generation) {
586 std::lock_guard<std::mutex> lock(stateMutex);
587 if (generation <= retiredGeneration || generation != ownerGeneration)
588 return;
589 // Clamp at zero, just in case.
590 unacked.store(unacked.load() - (std::min)(unacked.load(), count));
591 spaceCv.notify_all();
592 }
593
594 /// Client session `generation` subscribed with in-flight limit `limit`. It
595 /// now owns the flow-control state; anything an earlier session had in
596 /// flight is gone. Ignored if that session is already retired.
597 void subscribed(uint64_t limit, uint64_t generation) {
598 std::lock_guard<std::mutex> lock(stateMutex);
599 if (generation <= retiredGeneration)
600 return;
601 if (generation != ownerGeneration) {
602 ownerGeneration = generation;
603 unacked.store(0);
604 }
605 maxInFlight.store(limit);
606 spaceCv.notify_all();
607 }
608
609 /// Client session `generation` unsubscribed: messages it had not
610 /// acknowledged are gone, so stop counting them.
611 void unsubscribed(uint64_t generation) {
612 std::lock_guard<std::mutex> lock(stateMutex);
613 if (generation == ownerGeneration)
614 resetFlowControlLocked();
615 }
616
617 /// Client session `generation` closed: forget its flow-control state (if a
618 /// later session hasn't already taken it over) and ignore anything else
619 /// which arrives on its behalf.
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();
625 }
626
627 /// Wakes any `write()` blocked at the in-flight limit, which then throws.
628 void disconnect() override {
629 {
630 std::lock_guard<std::mutex> lock(stateMutex);
631 disconnected = true;
632 }
633 spaceCv.notify_all();
635 }
636
637protected:
638 void connectImpl(const ConnectOptions &) override {
639 std::lock_guard<std::mutex> lock(stateMutex);
640 disconnected = false;
641 }
642
643 /// Blocks while the in-flight limit is reached. The simulation must not
644 /// call this, since the client may need it to make progress before it
645 /// consumes anything; it should use `tryWrite()`. Throws if the port is
646 /// disconnected meanwhile.
647 void writeImpl(const MessageData &data) override {
648 std::unique_lock<std::mutex> lock(stateMutex);
649 spaceCv.wait(lock, [&] { return disconnected || hasSpace(); });
650 if (disconnected)
651 throw std::runtime_error("Channel id " + std::to_string(channelId) +
652 " disconnected while writing");
653 pushLocked(data);
654 }
655 bool tryWriteImpl(const MessageData &data) override {
656 std::lock_guard<std::mutex> lock(stateMutex);
657 if (!hasSpace())
658 return false;
659 pushLocked(data);
660 return true;
661 }
662
663private:
664 void pushLocked(const MessageData &data) {
665 queued.fetch_add(1);
666 writeQueue.push(data);
667 }
668
669 void resetFlowControlLocked() {
670 unacked.store(0);
671 maxInFlight.store(RpcClient::DefaultToClientMaxInFlight);
672 spaceCv.notify_all();
673 }
674
675 bool hasSpace() const {
676 uint64_t limit = maxInFlight.load();
677 return limit == 0 || queued.load() + unacked.load() < limit;
678 }
679
680 Impl &impl;
681 std::atomic<uint64_t> queued{0};
682 std::atomic<uint64_t> unacked{0};
683 std::atomic<uint64_t> maxInFlight{RpcClient::DefaultToClientMaxInFlight};
684 // Guards the generations and `disconnected`, and orders flow-control
685 // updates against them. Only the write queue's and doorbell's locks are
686 // taken while holding it.
687 std::mutex stateMutex;
688 // Notified whenever room may have appeared, or the port disconnected.
689 std::condition_variable spaceCv;
690 bool disconnected = false;
691 uint64_t retiredGeneration = 0;
692 // The session which subscribed last, and so owns the flow-control state.
693 uint64_t ownerGeneration = 0;
694};
695} // namespace
696
697//===----------------------------------------------------------------------===//
698// Impl - server lifecycle
699//===----------------------------------------------------------------------===//
700
702 // On Windows, `ix::initNetSystem()` calls `WSAStartup` and returns false if
703 // that fails. On other platforms it's a no-op that always returns true.
704 if (!ix::initNetSystem())
705 throw std::runtime_error(
706 "RpcServer: ix::initNetSystem() failed (WSAStartup)");
707
708 // Resolve port 0 / negative request to an OS-assigned ephemeral port,
709 // since IXWebSocket does not expose the bound port after the fact.
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");
716 }
717
718 const std::string host = "127.0.0.1";
719 server = std::make_unique<ix::WebSocketServer>(requestedPort, host);
720 server->disablePerMessageDeflate();
721
722 // Use the connection callback (rather than the simpler client-message one)
723 // because it hands us an owning reference to the socket, which the session
724 // holds so senders on other threads can't outlive it.
725 server->setOnConnectionCallback(
726 [this](std::weak_ptr<ix::WebSocket> wsWeak,
727 std::shared_ptr<ix::ConnectionState> /*state*/) {
728 std::shared_ptr<ix::WebSocket> ws = wsWeak.lock();
729 if (!ws)
730 return;
731 ix::WebSocket *raw = ws.get();
732 ws->setOnMessageCallback(
733 [this, wsWeak, raw](const ix::WebSocketMessagePtr &msg) {
734 onClientMessage(wsWeak, *raw, msg);
735 });
736 });
737
738 auto res = server->listen();
739 if (!res.first)
740 throw std::runtime_error("RpcServer: listen failed: " + res.second);
741
742 server->start();
743 boundPort = requestedPort;
744 writePortFile(static_cast<uint16_t>(boundPort));
745 ctxt.getLogger().info("cosim", std::format("Server listening on {}:{}", host,
746 static_cast<unsigned>(boundPort)));
747
748 // Start the always-on transport thread that drains every port's queue. It
749 // lives the entire lifetime of the server and sleeps on `readyIds`'s
750 // internal CV when there is nothing to do regardless of whether a client
751 // is connected.
752 transportThread = std::thread([this] { transportLoop(); });
753}
754
756 if (server) {
757 // A pending fault from the network thread is interesting, but throwing
758 // out of a destructor is worse than swallowing it. The user can still
759 // observe the fault by calling stop() explicitly before letting the
760 // server destruct; if they didn't, log and continue.
761 try {
762 stop(0);
763 } catch (const std::exception &e) {
764 ctxt.getLogger().error(
765 "cosim",
766 std::string("Suppressed exception during ~RpcServer::Impl: ") +
767 e.what());
768 } catch (...) {
769 ctxt.getLogger().error(
770 "cosim", "Suppressed non-std::exception during ~RpcServer::Impl");
771 }
772 }
773}
774
776 const std::vector<uint8_t> &compressedManifest) {
777 faultStash.check();
778 {
779 std::lock_guard<std::mutex> lock(manifestMutex);
780 this->esiVersion = esiVersion;
781 this->compressedManifest = compressedManifest;
782 manifestReady = true;
783 }
784 manifestReadyCV.notify_all();
785}
786
788 const std::string &type) {
789 faultStash.check();
790 std::lock_guard<std::mutex> lock(channelsMutex);
791 uint64_t id = nextChannelId++;
792 auto port = std::make_unique<RpcServerReadPort>(new Type(type), *this, id);
793 RpcServerReadPort *raw = port.get();
794 readPorts.emplace(name, std::move(port));
795
796 ChannelInfo info{id, name, type, ChannelDirection::ToServer, raw, nullptr};
797 channelById.emplace(id, std::move(info));
798 idByName.emplace(name, id);
799 return *raw;
800}
801
803 // Only ports created by `registerReadPort` are handed out, so this cast is
804 // safe for any well-behaved caller.
805 static_cast<RpcServerReadPort &>(port).markConsumed();
806}
807
809 const std::string &type) {
810 faultStash.check();
811 std::lock_guard<std::mutex> lock(channelsMutex);
812 uint64_t id = nextChannelId++;
813 auto port = std::make_unique<RpcServerWritePort>(new Type(type), *this, id);
814 RpcServerWritePort *raw = port.get();
815 writePorts.emplace(name, std::move(port));
816
817 ChannelInfo info{id, name, type, ChannelDirection::ToClient, nullptr, raw};
818 channelById.emplace(id, std::move(info));
819 idByName.emplace(name, id);
820 return *raw;
821}
822
823void Impl::stop(uint32_t /*timeoutMS*/) {
824 // Disconnect ports first so any in-flight DPI writes see a closed channel.
825 {
826 std::lock_guard<std::mutex> lock(channelsMutex);
827 for (auto &[name, port] : readPorts)
828 port->disconnect();
829 for (auto &[name, port] : writePorts)
830 port->disconnect();
831 }
832
833 // Retire the transport thread.
834 if (transportThread.joinable()) {
835 readyIds.requestShutdown();
836 transportThread.join();
837 // NB: there's no explicit "clear readyIds" step: each port's queue
838 // contents and the corresponding dirty markers belong to the ports,
839 // not to the transport thread, and the server doesn't restart in-place.
840 }
841
842 if (server) {
843 server->stop();
844 server.reset();
845 }
846
847 std::shared_ptr<ClientSession> old;
848 {
849 std::lock_guard<std::mutex> lock(sessionMutex);
850 old.swap(session);
851 }
852
853 // Surface any fault the IX network thread caught while we were running.
854 // Done last so the rest of the shutdown sequence completes regardless.
855 faultStash.check();
856}
857
858//===----------------------------------------------------------------------===//
859// Impl - WebSocket message dispatch
860//===----------------------------------------------------------------------===//
861
862void Impl::onClientMessage(const std::weak_ptr<ix::WebSocket> &wsWeak,
863 ix::WebSocket &ws,
864 const ix::WebSocketMessagePtr &msg) {
865 switch (msg->type) {
866 case ix::WebSocketMessageType::Open:
867 onOpen(wsWeak);
868 return;
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));
876 onClose(ws);
877 return;
878 }
879 case ix::WebSocketMessageType::Message:
880 // An exception escaping this callback would kill IX's network thread.
881 // Stash the first one so the next public RpcServer method rethrows it
882 // on the user's thread.
883 try {
884 if (msg->binary) {
885 // Frames from a rejected additional client are ignored.
886 if (std::shared_ptr<ClientSession> s = sessionFor(ws))
887 handleBinaryFrame(s->generation, msg->str);
888 } else {
889 handleControlFrame(ws, msg->str);
890 }
891 } catch (...) {
892 faultStash.record(std::current_exception());
893 }
894 return;
895 default:
896 return;
897 }
898}
899
900void Impl::onOpen(const std::weak_ptr<ix::WebSocket> &wsWeak) {
901 std::shared_ptr<ix::WebSocket> ws = wsWeak.lock();
902 if (!ws)
903 return;
904 {
905 std::lock_guard<std::mutex> lock(sessionMutex);
906 if (!session) {
907 session = std::make_shared<ClientSession>();
908 session->ws = ws;
909 session->generation = nextSessionGeneration++;
910 ctxt.getLogger().debug("cosim", "Client connected");
911 return;
912 }
913 }
914 // Single-client model: a session is already active. Send an unsolicited
915 // JSON error frame so the new client gets an actionable, application-level
916 // reason, then close with 1013 ("Try Again Later") rather than 1011
917 // ("Internal Error") -- the latter falsely implies a server-side bug.
918 ctxt.getLogger().warning(
919 "cosim", "Rejecting additional client; one already connected");
920 json err;
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());
926 // 1013 = Try Again Later (RFC 6455 §7.4).
927 ws->close(1013, "cosim server busy: another client is already connected");
928}
929
930void Impl::onClose(ix::WebSocket &ws) {
931 std::shared_ptr<ClientSession> old;
932 {
933 std::lock_guard<std::mutex> lock(sessionMutex);
934 // A rejected second client closing must not tear down the active one.
935 if (!session || session->ws.get() != &ws)
936 return;
937 old.swap(session);
938 }
939 old->closed.store(true);
940 // Must not wait for in-progress sends: this may be running inside one (see
941 // the locking rules on ClientSession). Senders hold their own reference.
942 // Requests from this session still being handled are fenced off by
943 // generation instead.
944 retireSession(old->generation);
945}
946
947void Impl::retireSession(uint64_t generation) {
948 std::lock_guard<std::mutex> lock(channelsMutex);
949 for (auto &[name, port] : writePorts)
950 port->retireClient(generation);
951 for (auto &[name, port] : readPorts)
952 port->clientDisconnected(generation);
953}
954
955void Impl::handleBinaryFrame(uint64_t generation, const std::string &data) {
956 uint64_t channelId;
957 const uint8_t *payloadBytes;
958 size_t payloadSize;
959 if (!parseDataFrame(data, channelId, payloadBytes, payloadSize)) {
960 ctxt.getLogger().error("cosim",
961 "Received binary frame shorter than 8-byte header");
962 return;
963 }
964
965 RpcServerReadPort *port = nullptr;
966 {
967 std::lock_guard<std::mutex> lock(channelsMutex);
968 auto it = channelById.find(channelId);
969 if (it == channelById.end() ||
970 it->second.direction != ChannelDirection::ToServer)
971 port = nullptr;
972 else
973 port = it->second.readPort;
974 }
975 if (!port) {
976 ctxt.getLogger().error(
977 "cosim", std::format("Binary frame for unknown to-server channel id {}",
978 channelId));
979 return;
980 }
981
982 MessageData payload(payloadBytes, payloadSize);
983 // RpcServerReadPort always has an unbounded internal queue so `deliver` is
984 // non-blocking: it enqueues into `ReadChannelPort`'s internal polling buffer
985 // (or parks the frame until the port connects) and returns. A `false`
986 // return means a callback-mode consumer refused it; drop the frame but
987 // still return the credit so the client's in-flight count doesn't leak.
988 if (!port->deliver(generation, payload)) {
989 logRefusedFrame(channelId, payload.getSize());
990 port->dropped(generation);
991 }
992}
993
994void Impl::logRefusedFrame(uint64_t channelId, size_t size) {
995 ctxt.getLogger().warning(
996 "cosim", std::format("Dropped {} bytes for channel id {}: refused by "
997 "the simulator-side consumer",
998 size, channelId));
999}
1000
1001void Impl::handleControlFrame(ix::WebSocket &ws, const std::string &text) {
1002 json req;
1003 try {
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()));
1008 sendError(ws, 0, "protocol_error",
1009 std::string("Failed to parse JSON: ") + e.what());
1010 faultStash.record(std::current_exception());
1011 return;
1012 }
1013
1014 auto typeIt = req.find("type");
1015 if (typeIt != req.end() && typeIt->is_string() &&
1016 typeIt->get<std::string>() == "event") {
1017 // Events from a rejected additional client are ignored.
1018 if (std::shared_ptr<ClientSession> s = sessionFor(ws))
1019 handleEvent(s->generation, req);
1020 return;
1021 }
1022 if (typeIt == req.end() || !typeIt->is_string() ||
1023 typeIt->get<std::string>() != "request") {
1024 sendError(ws, 0, "protocol_error",
1025 "Control frame missing \"type\":\"request\"");
1026 return;
1027 }
1028 uint64_t requestId = 0;
1029 if (auto idIt = req.find("request_id"); idIt != req.end()) {
1030 // Accept only unsigned integers.
1031 if (!idIt->is_number_unsigned()) {
1032 sendError(ws, 0, "protocol_error",
1033 "\"request_id\" must be an unsigned integer");
1034 return;
1035 }
1036 try {
1037 requestId = idIt->get<uint64_t>();
1038 } catch (const std::exception &e) {
1039 sendError(ws, 0, "protocol_error",
1040 std::string("Invalid \"request_id\": ") + e.what());
1041 return;
1042 }
1043 }
1044 auto methodIt = req.find("method");
1045 if (methodIt == req.end() || !methodIt->is_string()) {
1046 sendError(ws, requestId, "protocol_error", "Missing \"method\"");
1047 return;
1048 }
1049 std::string method = methodIt->get<std::string>();
1050 json params = req.value("params", json::object());
1051
1052 if (method == "hello")
1053 handleHello(ws, requestId, params);
1054 else if (method == "subscribe")
1055 handleSubscribe(ws, requestId, params);
1056 else if (method == "unsubscribe")
1057 handleUnsubscribe(ws, requestId, params);
1058 else
1059 sendError(ws, requestId, "protocol_error", "Unknown method: " + method);
1060}
1061
1062//===----------------------------------------------------------------------===//
1063// Impl - control methods
1064//===----------------------------------------------------------------------===//
1065
1066/// Parse the `channels` list of a `consumed` event into (channel_id, count)
1067/// pairs. Returns false (with `err` set) on a malformed event.
1068static bool parseConsumedEvent(const json &frame,
1069 std::vector<std::pair<uint64_t, uint64_t>> &out,
1070 std::string &err) {
1071 auto paramsIt = frame.find("params");
1072 if (paramsIt == frame.end() || !paramsIt->is_object()) {
1073 err = "missing \"params\" object";
1074 return false;
1075 }
1076 auto chIt = paramsIt->find("channels");
1077 if (chIt == paramsIt->end() || !chIt->is_array()) {
1078 err = "missing \"channels\" array";
1079 return false;
1080 }
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\"";
1087 return false;
1088 }
1089 out.emplace_back(idIt->get<uint64_t>(), countIt->get<uint64_t>());
1090 }
1091 return true;
1092}
1093
1094void Impl::handleEvent(uint64_t generation, const json &frame) {
1095 std::string event = frame.value("event", std::string());
1096 if (event != "consumed") {
1097 // Events carry no request_id, so there's nobody to reply to. Ignore
1098 // unknown events per the protocol's additive-evolution rule.
1099 ctxt.getLogger().debug("cosim",
1100 "Ignoring unknown client event \"" + event + "\"");
1101 return;
1102 }
1103 std::vector<std::pair<uint64_t, uint64_t>> acks;
1104 std::string err;
1105 if (!parseConsumedEvent(frame, acks, err)) {
1106 ctxt.getLogger().warning("cosim", "Malformed consumed event: " + err);
1107 return;
1108 }
1109 std::lock_guard<std::mutex> lock(channelsMutex);
1110 for (auto [id, count] : acks) {
1111 auto it = channelById.find(id);
1112 if (it == channelById.end() || !it->second.writePort) {
1113 ctxt.getLogger().warning(
1114 "cosim",
1115 std::format("consumed event for unknown to-client channel id {}",
1116 id));
1117 continue;
1118 }
1119 it->second.writePort->ack(count, generation);
1120 }
1121}
1122
1123void Impl::handleHello(ix::WebSocket &ws, uint64_t requestId,
1124 const json &params) {
1125 auto verIt = params.find("client_protocol_version");
1126 if (verIt == params.end() || !verIt->is_number_unsigned() ||
1127 verIt->get<uint64_t>() != kProtocolVersion) {
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.",
1132 kProtocolVersion, got));
1133 return;
1134 }
1135
1136 // Block until the manifest has been set. This replaces the gRPC-era poll
1137 // loop on the client side.
1138 {
1139 std::unique_lock<std::mutex> lock(manifestMutex);
1140 manifestReadyCV.wait(lock, [&] { return manifestReady; });
1141 }
1142
1143 json result;
1144 result["protocol_version"] = kProtocolVersion;
1145 {
1146 std::lock_guard<std::mutex> lock(manifestMutex);
1147 result["esi_version"] = esiVersion;
1148 result["compressed_manifest_b64"] = macaron::Base64::Encode(
1149 std::string(reinterpret_cast<const char *>(compressedManifest.data()),
1150 compressedManifest.size()));
1151 }
1152
1153 json channelsJson = json::array();
1154 {
1155 std::lock_guard<std::mutex> lock(channelsMutex);
1156 // Emit in id order for deterministic output.
1157 for (uint64_t i = 0; i < nextChannelId; ++i) {
1158 auto it = channelById.find(i);
1159 if (it == channelById.end())
1160 continue;
1161 const ChannelInfo &info = it->second;
1162 json c;
1163 c["channel_id"] = info.id;
1164 c["name"] = info.name;
1165 c["type"] = info.typeId;
1166 c["direction"] = info.direction == ChannelDirection::ToServer
1167 ? "to_server"
1168 : "to_client";
1169 channelsJson.push_back(std::move(c));
1170 }
1171 }
1172 result["channels"] = std::move(channelsJson);
1173
1174 if (std::shared_ptr<ClientSession> s = sessionFor(ws))
1175 s->helloDone = true;
1176
1177 sendResult(ws, requestId, result);
1178}
1179
1180void Impl::handleSubscribe(ix::WebSocket &ws, uint64_t requestId,
1181 const json &params) {
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\"");
1186 return;
1187 }
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");
1194 return;
1195 }
1196 maxInFlight = limitIt->get<uint64_t>();
1197 }
1198
1199 std::optional<ChannelInfo> info =
1200 findChannel(ws, requestId, channelId, ChannelDirection::ToClient);
1201 if (!info)
1202 return;
1203 std::shared_ptr<ClientSession> s = sessionFor(ws);
1204 if (!s) {
1205 sendError(ws, requestId, "internal", "No active session");
1206 return;
1207 }
1208 {
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));
1213 return;
1214 }
1215 s->subscribed.insert(channelId);
1216 info->writePort->subscribed(maxInFlight, s->generation);
1217 // Send the subscribe-ack BEFORE waking the transport thread. IXWebSocket
1218 // queues sends in FIFO order on a given connection, so as long as the ack
1219 // is enqueued first, any data frames the transport thread emits next will
1220 // arrive after it. Holding `subscribedMutex` keeps the transport thread
1221 // from sending on this channel before the ack, too.
1222 sendResult(ws, requestId, json::object());
1223 }
1224 // Kick the transport thread: if the port already has queued data (typical
1225 // for accelerator-startup writes that landed before the client
1226 // subscribed), this is what flushes it.
1227 readyIds.markReady(channelId);
1228}
1229
1230void Impl::handleUnsubscribe(ix::WebSocket &ws, uint64_t requestId,
1231 const json &params) {
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\"");
1236 return;
1237 }
1238 uint64_t channelId = chIdIt->get<uint64_t>();
1239
1240 RpcServerWritePort *writePort = nullptr;
1241 {
1242 std::lock_guard<std::mutex> chLock(channelsMutex);
1243 auto it = channelById.find(channelId);
1244 if (it != channelById.end())
1245 writePort = it->second.writePort;
1246 }
1247
1248 std::shared_ptr<ClientSession> s = sessionFor(ws);
1249 if (!s) {
1250 sendError(ws, requestId, "internal", "No active session");
1251 return;
1252 }
1253 // Holding `subscribedMutex` across the ack keeps the transport thread from
1254 // sending another data frame on this channel before it.
1255 {
1256 std::lock_guard<std::mutex> subLock(s->subscribedMutex);
1257 auto removed = s->subscribed.erase(channelId);
1258 if (!removed) {
1259 sendError(ws, requestId, "not_subscribed",
1260 std::format("Channel id {} is not subscribed", channelId));
1261 return;
1262 }
1263 // The client drops anything it hasn't consumed once it unsubscribes.
1264 // Reset under the same lock so the transport thread can't send (and
1265 // count) another frame on this channel in between.
1266 if (writePort)
1267 writePort->unsubscribed(s->generation);
1268 sendResult(ws, requestId, json::object());
1269 }
1270}
1271
1272std::optional<Impl::ChannelInfo> Impl::findChannel(ix::WebSocket &ws,
1273 uint64_t requestId,
1274 uint64_t channelId,
1275 ChannelDirection dir) {
1276 std::optional<ChannelInfo> info;
1277 {
1278 std::lock_guard<std::mutex> chLock(channelsMutex);
1279 auto it = channelById.find(channelId);
1280 if (it != channelById.end())
1281 info = it->second;
1282 }
1283 if (!info) {
1284 sendError(ws, requestId, "unknown_channel",
1285 std::format("No channel with id {}", channelId));
1286 return std::nullopt;
1287 }
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"
1292 : "to-client"));
1293 return std::nullopt;
1294 }
1295 return info;
1296}
1297
1298void Impl::sendResult(ix::WebSocket &ws, uint64_t requestId,
1299 const json &result) {
1300 json resp;
1301 resp["type"] = "response";
1302 resp["request_id"] = requestId;
1303 resp["result"] = result;
1304 // IXWebSocket serializes concurrent send calls internally. Callers must
1305 // follow the locking rules on ClientSession.
1306 ws.sendUtf8Text(resp.dump());
1307}
1308
1309void Impl::sendError(ix::WebSocket &ws, uint64_t requestId,
1310 const std::string &code, const std::string &message) {
1311 json resp;
1312 resp["type"] = "response";
1313 resp["request_id"] = requestId;
1314 resp["error"] = {{"code", code}, {"message", message}};
1315 ws.sendUtf8Text(resp.dump());
1316}
1317
1318//===----------------------------------------------------------------------===//
1319// Impl - transport thread
1320//
1321// Drains `to_client` write queues onto the WebSocket and returns credits for
1322// consumed `to_server` messages.
1323//===----------------------------------------------------------------------===//
1324
1326 while (true) {
1327 std::unordered_set<uint64_t> ids;
1328 if (!readyIds.waitDrain(ids))
1329 return;
1330 sendConsumedEvent(ids);
1331 for (uint64_t id : ids) {
1332 RpcServerWritePort *writePort = nullptr;
1333 {
1334 std::lock_guard<std::mutex> chLock(channelsMutex);
1335 auto it = channelById.find(id);
1336 if (it == channelById.end() ||
1337 it->second.direction != ChannelDirection::ToClient)
1338 continue;
1339 writePort = it->second.writePort;
1340 }
1341 if (!writePort)
1342 continue;
1343
1344 // Only drain if a client is subscribed; otherwise data stays in the
1345 // queue until subscription (handleSubscribe fires markReady). We
1346 // re-acquire `subscribedMutex` on every iteration so
1347 // `handleUnsubscribe` can interpose between frames: once it erases the
1348 // subscription and sends the unsubscribe-ack, the next iteration here
1349 // sees the channel as not subscribed and breaks, guaranteeing the ack
1350 // is the last `to_client` frame on that channel (as the protocol spec
1351 // requires). Our reference to the session keeps its socket alive
1352 // against a concurrent `onClose()`.
1353 std::shared_ptr<ClientSession> s = getSession();
1354 if (!s)
1355 continue;
1356 while (true) {
1357 if (readyIds.isShutdown())
1358 return;
1359 if (s->closed.load())
1360 break;
1361 std::lock_guard<std::mutex> subLock(s->subscribedMutex);
1362 if (!s->subscribed.count(id))
1363 break;
1364 std::optional<MessageData> msg = writePort->popForSend(s->generation);
1365 if (!msg)
1366 break;
1367 std::string frame = buildDataFrame(id, msg->getBytes(), msg->getSize());
1368 // IXWebSocket serializes concurrent send calls internally and queues
1369 // them in FIFO order on the WS.
1370 s->ws->sendBinary(frame);
1371 }
1372 }
1373 }
1374}
1375
1376void Impl::sendConsumedEvent(const std::unordered_set<uint64_t> &ids) {
1377 // Credits belong to the session which sent the frames, so are only
1378 // returned to that one. With no client there's nobody holding any.
1379 std::shared_ptr<ClientSession> s = getSession();
1380 if (!s || !s->helloDone)
1381 return;
1382 std::vector<std::pair<uint64_t, RpcServerReadPort *>> ports;
1383 {
1384 std::lock_guard<std::mutex> chLock(channelsMutex);
1385 for (uint64_t id : ids) {
1386 auto it = channelById.find(id);
1387 if (it != channelById.end() && it->second.readPort)
1388 ports.emplace_back(id, it->second.readPort);
1389 }
1390 }
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())
1396 return;
1397
1398 json event;
1399 event["type"] = "event";
1400 event["event"] = "consumed";
1401 event["params"] = {{"channels", std::move(channels)}};
1402 s->ws->sendUtf8Text(event.dump());
1403}
1404
1405//===----------------------------------------------------------------------===//
1406// RpcServer pass-throughs
1407//===----------------------------------------------------------------------===//
1408
1410RpcServer::~RpcServer() = default;
1411
1412void RpcServer::setManifest(int esiVersion,
1413 const std::vector<uint8_t> &compressedManifest) {
1414 if (!impl)
1415 throw std::runtime_error("Server not running");
1416 impl->setManifest(esiVersion, compressedManifest);
1417}
1418
1420 const std::string &type) {
1421 if (!impl)
1422 throw std::runtime_error("Server not running");
1423 return impl->registerReadPort(name, type);
1424}
1425
1427 const std::string &type) {
1428 if (!impl)
1429 throw std::runtime_error("Server not running");
1430 return impl->registerWritePort(name, type);
1431}
1432
1434 if (!impl)
1435 throw std::runtime_error("Server not running");
1436 impl->messageConsumed(port);
1437}
1438
1439void RpcServer::run(int port) {
1440 if (impl)
1441 throw std::runtime_error("Server already running");
1442 impl = std::make_unique<Impl>(ctxt, port);
1443}
1444
1445void RpcServer::stop(uint32_t timeoutMS) {
1446 if (!impl)
1447 throw std::runtime_error("Server not running");
1448 impl->stop(timeoutMS);
1449}
1450
1452 if (!impl)
1453 throw std::runtime_error("Server not running");
1454 return impl->getPort();
1455}
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.
Definition RpcClient.h:34
static constexpr unsigned DefaultToClientMaxInFlight
Default maximum number of frames in flight (queued in the simulator or sent but not yet consumed by t...
Definition RpcClient.h:71
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Definition Context.h:34
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
size_t getSize() const
Get the size of the data in bytes.
Definition Common.h:230
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
Definition Ports.cpp:143
virtual void disconnect() override
Disconnect the channel.
Definition Ports.cpp:71
Root class of the ESI type system.
Definition Types.h:36
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
virtual void disconnect() override
Disconnect the port.
Definition Ports.cpp:902
A client for the cosim RPC server.
Definition RpcClient.h:34
ChannelDirection
Channel direction as reported by the server.
Definition RpcClient.h:50
static constexpr unsigned DefaultToClientMaxInFlight
Default maximum number of frames in flight (queued in the simulator or sent but not yet consumed by t...
Definition RpcClient.h:71
Cross-thread error channel for the IXWebSocket network thread.
Definition RpcWire.h:73
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 &params)
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
void sendResult(ix::WebSocket &ws, uint64_t requestId, const json &result)
void handleHello(ix::WebSocket &ws, uint64_t requestId, const json &params)
::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
backends::cosim::RpcClient::ChannelDirection ChannelDirection
void handleSubscribe(ix::WebSocket &ws, uint64_t requestId, const json &params)
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)
RpcServer(Context &ctxt)
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 run(int port=-1)
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
Definition RpcServer.h:79
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.
Definition Utils.h:177
Thread safe queue.
Definition Utils.h:48
void push(E... t)
Push onto the queue.
Definition Utils.h:86
std::optional< T > pop()
Pop something off the queue but return nullopt if the queue is empty.
Definition Utils.h:98
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
std::shared_ptr< ix::WebSocket > ws
std::unordered_set< uint64_t > subscribed