CIRCT 24.0.0git
Loading...
Searching...
No Matches
ESIRuntimeCosimRpcTest.cpp
Go to the documentation of this file.
1//===- ESIRuntimeCosimRpcTest.cpp - Cosim RPC protocol tests --------------===//
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// Runs the cosim RpcServer and RpcClient in-process (no simulator) to check
10// the protocol's behavior.
11//
12//===----------------------------------------------------------------------===//
13
14#include "esi/Context.h"
15#include "esi/Logging.h"
16#include "esi/Ports.h"
19#include "gtest/gtest.h"
20
21#include <atomic>
22#include <chrono>
23#include <cstdint>
24#include <filesystem>
25#include <functional>
26#include <future>
27#include <memory>
28#include <mutex>
29#include <optional>
30#include <thread>
31#include <utility>
32#include <vector>
33
34using namespace esi;
37using namespace std::chrono_literals;
38
39namespace {
40
41MessageData msg(uint32_t v) { return MessageData::from(v); }
42
43/// Poll `cond` until it holds or a generous deadline passes.
44bool waitFor(const std::function<bool()> &cond,
45 std::chrono::milliseconds timeout = 10s) {
46 auto deadline = std::chrono::steady_clock::now() + timeout;
47 while (!cond()) {
48 if (std::chrono::steady_clock::now() > deadline)
49 return false;
50 std::this_thread::sleep_for(1ms);
51 }
52 return true;
53}
54
55class CosimRpcTest : public ::testing::Test {
56protected:
57 void SetUp() override {
58 // RpcServer writes `cosim.cfg` into the working directory.
59 oldCwd = std::filesystem::current_path();
60 tmpDir = std::filesystem::temp_directory_path() /
61 ("esi_cosim_rpc_test_" +
62 std::to_string(
63 std::chrono::steady_clock::now().time_since_epoch().count()));
64 std::filesystem::create_directories(tmpDir);
65 std::filesystem::current_path(tmpDir);
66
67 ctxt = Context::withLogger<NullLogger>();
68 server = std::make_unique<RpcServer>(*ctxt);
69 // The server picks a free port by probing, then binds it; another process
70 // can take it in between. Retry, since tests run in parallel.
71 for (int attempt = 0;; ++attempt) {
72 try {
73 server->run(0);
74 break;
75 } catch (const std::runtime_error &) {
76 if (attempt == 4)
77 throw;
78 }
79 }
80 toServer = &server->registerReadPort("in", "i32");
81 // Registered, but left for each test to connect (or not).
82 lateToServer = &server->registerReadPort("late", "i32");
83 toClient = &server->registerWritePort("out", "i32");
84 toServer->connect();
85 toClient->connect();
86 // Non-empty: IXWebSocket's base64 encoder crashes on empty input.
87 server->setManifest(0, {1, 2, 3, 4});
88 }
89
90 void TearDown() override {
91 client.reset();
92 if (server)
93 server->stop();
94 server.reset();
95 std::filesystem::current_path(oldCwd);
96 std::error_code ec;
97 std::filesystem::remove_all(tmpDir, ec);
98 }
99
100 void connectClient() {
101 client = std::make_unique<RpcClient>(ctxt->getLogger(), "127.0.0.1",
102 server->getPort());
103 }
104
105 /// Read one message from the to-server port as the simulator would, and
106 /// return its credit.
107 uint32_t consumeOne() { return consumeFrom(*toServer); }
108
109 std::filesystem::path oldCwd, tmpDir;
110 std::unique_ptr<Context> ctxt;
111 std::unique_ptr<RpcServer> server;
112 ReadChannelPort *toServer = nullptr;
113 ReadChannelPort *lateToServer = nullptr;
114 WriteChannelPort *toClient = nullptr;
115 std::unique_ptr<RpcClient> client;
116
117 /// Read one message from `port` as the simulator would, and return its
118 /// credit. Fails the test (and returns an arbitrary value) rather than
119 /// hanging if none arrives.
120 uint32_t consumeFrom(ReadChannelPort &port) {
121 std::future<MessageData> f = port.readAsync();
122 if (f.wait_for(10s) != std::future_status::ready) {
123 ADD_FAILURE() << "timed out waiting for a message";
124 return ~0u;
125 }
126 MessageData m = f.get();
127 server->messageConsumed(port);
128 return *m.as<uint32_t>();
129 }
130};
131
132TEST_F(CosimRpcTest, ToServerTryWriteBackpressure) {
133 connectClient();
134 client->setToServerMaxInFlight("in", 4);
135
136 for (uint32_t i = 0; i < 4; ++i)
137 EXPECT_TRUE(client->tryWriteToServer("in", {msg(i)}));
138 // At the in-flight limit: nothing consumed yet.
139 EXPECT_FALSE(client->tryWriteToServer("in", {msg(4)}));
140
141 // Consuming one returns one credit.
142 EXPECT_EQ(consumeOne(), 0u);
143 ASSERT_TRUE(
144 waitFor([&] { return client->tryWriteToServer("in", {msg(4)}); }));
145 EXPECT_FALSE(client->tryWriteToServer("in", {msg(5)}));
146
147 for (uint32_t i = 1; i <= 4; ++i)
148 EXPECT_EQ(consumeOne(), i);
149
150 // A multi-frame message is admitted on a single credit.
151 ASSERT_TRUE(waitFor([&] {
152 return client->tryWriteToServer(
153 "in", {msg(10), msg(11), msg(12), msg(13), msg(14)});
154 }));
155 EXPECT_FALSE(client->tryWriteToServer("in", {msg(15)}));
156 for (uint32_t i = 10; i <= 14; ++i)
157 EXPECT_EQ(consumeOne(), i);
158
159 // With no in-flight limit, writes are never refused.
160 client->setToServerMaxInFlight("in", 0);
161 for (uint32_t i = 0; i < 100; ++i)
162 EXPECT_TRUE(client->tryWriteToServer("in", {msg(i)}));
163 for (uint32_t i = 0; i < 100; ++i)
164 EXPECT_EQ(consumeOne(), i);
165}
166
167TEST_F(CosimRpcTest, ToServerForcedWriteIgnoresLimit) {
168 connectClient();
169 client->setToServerMaxInFlight("in", 1);
170 EXPECT_TRUE(client->tryWriteToServer("in", {msg(0)}));
171 EXPECT_FALSE(client->tryWriteToServer("in", {msg(1)}));
172 // The rest of an admitted message is sent regardless of the limit, and
173 // counts as in flight.
174 EXPECT_TRUE(client->tryWriteToServer("in", {msg(1)}, /*force=*/true));
175 EXPECT_EQ(consumeOne(), 0u);
176 std::this_thread::sleep_for(50ms);
177 EXPECT_FALSE(client->tryWriteToServer("in", {msg(2)}));
178 EXPECT_EQ(consumeOne(), 1u);
179 ASSERT_TRUE(
180 waitFor([&] { return client->tryWriteToServer("in", {msg(2)}); }));
181 EXPECT_EQ(consumeOne(), 2u);
182}
183
184TEST_F(CosimRpcTest, ToServerBlockingWrite) {
185 connectClient();
186 client->setToServerMaxInFlight("in", 2);
187 client->writeToServer("in", msg(0));
188 client->writeToServer("in", msg(1));
189
190 std::atomic<bool> done = false;
191 std::thread writer([&] {
192 client->writeToServer("in", msg(2));
193 done = true;
194 });
195 std::this_thread::sleep_for(100ms);
196 EXPECT_FALSE(done.load()) << "write() should block at the in-flight limit";
197
198 EXPECT_EQ(consumeOne(), 0u);
199 EXPECT_TRUE(waitFor([&] { return done.load(); }));
200 writer.join();
201 EXPECT_EQ(consumeOne(), 1u);
202 EXPECT_EQ(consumeOne(), 2u);
203}
204
205TEST_F(CosimRpcTest, ToServerBlockedWriterThrowsOnDisconnect) {
206 connectClient();
207 // Use a port the simulator side never connects: frames held for it stay in
208 // flight even when the server stops. (Stopping disconnects connected ports,
209 // which hands back the in-flight count of frames they held, legitimately
210 // unblocking the writer.)
211 client->setToServerMaxInFlight("late", 1);
212 client->writeToServer("late", msg(0));
213
214 std::promise<bool> threw;
215 std::thread writer([&] {
216 try {
217 client->writeToServer("late", msg(1));
218 threw.set_value(false);
219 } catch (const std::exception &) {
220 threw.set_value(true);
221 }
222 });
223 std::this_thread::sleep_for(50ms);
224 server->stop();
225 server.reset();
226 auto f = threw.get_future();
227 ASSERT_EQ(f.wait_for(10s), std::future_status::ready);
228 EXPECT_TRUE(f.get());
229 writer.join();
230}
231
232TEST_F(CosimRpcTest, ToClientBackpressure) {
233 // Without a subscriber, the default in-flight limit bounds the server-side
234 // queue.
235 uint32_t next = 0;
236 while (toClient->tryWrite(msg(next)))
237 ASSERT_LT(++next, 1000u) << "server never applied backpressure";
239
240 connectClient();
241 std::atomic<bool> accepting = true;
242 std::mutex receivedMutex;
243 std::vector<uint32_t> received;
244 auto conn = client->connectClientReceiver(
245 "out",
246 [&](std::unique_ptr<SegmentedMessageData> &data) {
247 if (!accepting)
248 return false;
249 std::lock_guard<std::mutex> lock(receivedMutex);
250 received.push_back(*data->toMessageData().as<uint32_t>());
251 return true;
252 },
253 /*maxInFlight=*/4);
254 auto numReceived = [&] {
255 std::lock_guard<std::mutex> lock(receivedMutex);
256 return received.size();
257 };
258
259 // The backlog drains to the client, whose acks make room again.
260 ASSERT_TRUE(waitFor([&] { return numReceived() == next; }));
261 ASSERT_TRUE(waitFor([&] { return toClient->tryWrite(msg(next)); }));
262 ++next;
263 ASSERT_TRUE(waitFor([&] { return numReceived() == next; }));
264
265 // While the client refuses messages, at most `maxInFlight` can be in
266 // flight.
267 accepting = false;
268 uint32_t admitted = 0;
269 while (toClient->tryWrite(msg(next))) {
270 ++next;
271 ASSERT_LE(++admitted, 4u);
272 }
273 std::this_thread::sleep_for(100ms);
274 EXPECT_FALSE(toClient->tryWrite(msg(next)));
275
276 // Once the client consumes again, credits flow back.
277 accepting = true;
278 ASSERT_TRUE(waitFor([&] { return toClient->tryWrite(msg(next)); }));
279 ++next;
280 ASSERT_TRUE(waitFor([&] { return numReceived() == next; }));
281 std::lock_guard<std::mutex> lock(receivedMutex);
282 for (uint32_t i = 0; i < next; ++i)
283 EXPECT_EQ(received[i], i);
284}
285
286TEST_F(CosimRpcTest, ToClientUnsubscribeResetsInFlight) {
287 connectClient();
288 {
289 std::atomic<bool> seen = false;
290 auto conn = client->connectClientReceiver(
291 "out",
292 [&](std::unique_ptr<SegmentedMessageData> &) {
293 seen = true;
294 return false;
295 },
296 /*maxInFlight=*/1);
297 EXPECT_TRUE(toClient->tryWrite(msg(0)));
298 EXPECT_FALSE(toClient->tryWrite(msg(1)));
299 // Make sure it was sent (not merely queued, which the server would keep
300 // for the next subscriber) before unsubscribing.
301 ASSERT_TRUE(waitFor([&] { return seen.load(); }));
302 }
303 // Unsubscribing drops the unacknowledged message and restores the default
304 // in-flight limit for the (now empty) queue.
305 uint32_t admitted = 0;
306 ASSERT_TRUE(waitFor([&] { return toClient->tryWrite(msg(0)); }));
307 ++admitted;
308 while (toClient->tryWrite(msg(admitted)))
309 ASSERT_LE(++admitted, RpcClient::DefaultToClientMaxInFlight);
310 EXPECT_EQ(admitted, RpcClient::DefaultToClientMaxInFlight);
311}
312
313TEST_F(CosimRpcTest, UnconnectedServerPortBackpressures) {
314 connectClient();
315 // Frames for the unconnected port must be parked and count as in flight,
316 // so the client stalls rather than losing data.
317 client->setToServerMaxInFlight("late", 4);
318 for (uint32_t i = 0; i < 4; ++i)
319 EXPECT_TRUE(client->tryWriteToServer("late", {msg(i)}));
320 std::this_thread::sleep_for(50ms);
321 EXPECT_FALSE(client->tryWriteToServer("late", {msg(4)}));
322
323 // Connecting hands the parked frames over in order.
324 lateToServer->connect();
325 for (uint32_t i = 0; i < 4; ++i)
326 EXPECT_EQ(consumeFrom(*lateToServer), i);
327 ASSERT_TRUE(
328 waitFor([&] { return client->tryWriteToServer("late", {msg(4)}); }));
329 EXPECT_EQ(consumeFrom(*lateToServer), 4u);
330}
331
332TEST_F(CosimRpcTest, ServerPortDisconnectReturnsInFlight) {
333 connectClient();
334 lateToServer->connect();
335 client->setToServerMaxInFlight("late", 3);
336 for (uint32_t i = 0; i < 3; ++i)
337 EXPECT_TRUE(client->tryWriteToServer("late", {msg(i)}));
338 // Make sure they reached the port's queue before disconnecting: the server
339 // handles frames in arrival order, so once a later frame on another
340 // channel has been delivered, these have too.
341 client->writeToServer("in", msg(99));
342 EXPECT_EQ(consumeOne(), 99u);
343
344 // Disconnecting discards the unconsumed frames; their count comes back.
345 lateToServer->disconnect();
346 ASSERT_TRUE(
347 waitFor([&] { return client->tryWriteToServer("late", {msg(10)}); }));
348
349 // And frames sent while disconnected are parked until reconnect.
350 lateToServer->connect();
351 EXPECT_EQ(consumeFrom(*lateToServer), 10u);
352}
353
354TEST_F(CosimRpcTest, RefusedFramesDontSkewDisconnectCredits) {
355 connectClient();
356 client->setToServerMaxInFlight("late", 1);
357 // A callback-mode consumer which refuses everything: frames are dropped
358 // and their credits returned.
359 std::atomic<int> offered{0};
360 lateToServer->connect([&](MessageData) -> bool {
361 ++offered;
362 return false;
363 });
364 EXPECT_TRUE(client->tryWriteToServer("late", {msg(1)}));
365 ASSERT_TRUE(
366 waitFor([&] { return client->tryWriteToServer("late", {msg(2)}); }));
367 ASSERT_TRUE(waitFor([&] { return offered.load() == 2; }));
368 lateToServer->disconnect();
369
370 // Reconnect in polling mode and leave one frame unread.
371 lateToServer->connect();
372 ASSERT_TRUE(
373 waitFor([&] { return client->tryWriteToServer("late", {msg(3)}); }));
374 client->writeToServer("in", msg(99));
375 EXPECT_EQ(consumeOne(), 99u);
376 EXPECT_FALSE(client->tryWriteToServer("late", {msg(4)}));
377
378 // Disconnecting discards it, which must return its credit.
379 lateToServer->disconnect();
380 ASSERT_TRUE(
381 waitFor([&] { return client->tryWriteToServer("late", {msg(5)}); }));
382}
383
384TEST_F(CosimRpcTest, FrameRefusedDuringDisconnectIsDropped) {
385 connectClient();
386 client->setToServerMaxInFlight("late", 1);
387 // The consumer refuses a frame while a disconnect is in progress on another
388 // thread. It must still be dropped (returning its credit) rather than held
389 // for the next connection.
390 std::thread disconnector;
391 std::atomic<bool> refused{false};
392 lateToServer->connect([&](MessageData) -> bool {
393 disconnector = std::thread([&] { lateToServer->disconnect(); });
394 // Give the disconnect time to start and block waiting for this frame.
395 std::this_thread::sleep_for(100ms);
396 refused = true;
397 return false;
398 });
399 EXPECT_TRUE(client->tryWriteToServer("late", {msg(1)}));
400 ASSERT_TRUE(waitFor([&] { return refused.load(); }));
401 disconnector.join();
402
403 lateToServer->connect();
404 ASSERT_TRUE(
405 waitFor([&] { return client->tryWriteToServer("late", {msg(2)}); }));
406 EXPECT_EQ(consumeFrom(*lateToServer), 2u);
407}
408
409TEST_F(CosimRpcTest, DepartedClientsCreditsNotGivenToNext) {
410 // A client leaves a frame parked on "late" and goes away.
411 connectClient();
412 client->writeToServer("late", msg(1));
413 client->writeToServer("in", msg(99));
414 EXPECT_EQ(consumeOne(), 99u);
415 client.reset();
416
417 // The next client reaches its in-flight limit on "late".
418 connectClient();
419 client->setToServerMaxInFlight("late", 1);
420 EXPECT_TRUE(client->tryWriteToServer("late", {msg(2)}));
421 client->writeToServer("in", msg(98));
422 EXPECT_EQ(consumeOne(), 98u);
423
424 // Consuming the departed client's frame returns nothing to this one.
425 lateToServer->connect();
426 EXPECT_EQ(consumeFrom(*lateToServer), 1u);
427 std::this_thread::sleep_for(100ms);
428 EXPECT_FALSE(client->tryWriteToServer("late", {msg(3)}));
429
430 // Consuming its own frame does.
431 EXPECT_EQ(consumeFrom(*lateToServer), 2u);
432 ASSERT_TRUE(
433 waitFor([&] { return client->tryWriteToServer("late", {msg(3)}); }));
434 EXPECT_EQ(consumeFrom(*lateToServer), 3u);
435}
436
437TEST_F(CosimRpcTest, UnconnectedServerPortHoldsFrames) {
438 connectClient();
439 // Frames for a port the simulator hasn't connected yet are held, not
440 // dropped, and handed over in order once it connects.
441 for (uint32_t i = 0; i < 4; ++i)
442 client->writeToServer("late", msg(i));
443 // Make sure they've arrived: the server handles frames in order, so once a
444 // later frame on another channel has been delivered, these have too.
445 client->writeToServer("in", msg(99));
446 EXPECT_EQ(consumeOne(), 99u);
447
448 lateToServer->connect();
449 for (uint32_t i = 0; i < 4; ++i)
450 EXPECT_EQ(consumeFrom(*lateToServer), i);
451
452 // And again after a disconnect.
453 lateToServer->disconnect();
454 client->writeToServer("late", msg(10));
455 client->writeToServer("in", msg(98));
456 EXPECT_EQ(consumeOne(), 98u);
457 lateToServer->connect();
458 EXPECT_EQ(consumeFrom(*lateToServer), 10u);
459}
460
461TEST_F(CosimRpcTest, RejectedClientLeavesActiveOneConnected) {
462 connectClient();
463 // Shared, since the callback may still be running in `set_value()` once
464 // the test has seen the result and is returning.
465 auto received = std::make_shared<std::promise<uint32_t>>();
466 std::future<uint32_t> f = received->get_future();
467 auto conn = client->connectClientReceiver(
468 "out", [received](std::unique_ptr<SegmentedMessageData> &data) {
469 received->set_value(*data->toMessageData().as<uint32_t>());
470 return true;
471 });
472
473 // Only one client at a time: a second is turned away...
474 EXPECT_ANY_THROW(
475 RpcClient(ctxt->getLogger(), "127.0.0.1", server->getPort()));
476 // (Let the server see it close.)
477 std::this_thread::sleep_for(100ms);
478
479 // ...without disturbing the first.
480 toClient->write(msg(7));
481 ASSERT_EQ(f.wait_for(10s), std::future_status::ready);
482 EXPECT_EQ(f.get(), 7u);
483}
484
485TEST_F(CosimRpcTest, RefusedParkedFrameDoesNotBlockTheRest) {
486 connectClient();
487 for (uint32_t i = 0; i < 3; ++i)
488 client->writeToServer("late", msg(i));
489 client->writeToServer("in", msg(99));
490 EXPECT_EQ(consumeOne(), 99u);
491
492 // A callback-mode consumer which refuses the first frame it's offered.
493 std::mutex receivedMutex;
494 std::vector<uint32_t> received;
495 bool refused = false;
496 lateToServer->connect([&](MessageData data) -> bool {
497 std::lock_guard<std::mutex> lock(receivedMutex);
498 if (!refused) {
499 refused = true;
500 return false;
501 }
502 received.push_back(*data.as<uint32_t>());
503 return true;
504 });
505 // The refused frame is dropped, as one arriving while connected would be;
506 // the ones behind it still get through.
507 {
508 std::lock_guard<std::mutex> lock(receivedMutex);
509 EXPECT_EQ(received, (std::vector<uint32_t>{1, 2}));
510 }
511 // The callback refers to locals.
512 lateToServer->disconnect();
513}
514
515TEST_F(CosimRpcTest, SecondReceiverRejected) {
516 connectClient();
517 // Shared, since the callback may still be running in `set_value()` once
518 // the test has seen the result and is returning.
519 auto received = std::make_shared<std::promise<uint32_t>>();
520 std::future<uint32_t> f = received->get_future();
521 auto conn = client->connectClientReceiver(
522 "out", [received](std::unique_ptr<SegmentedMessageData> &data) {
523 received->set_value(*data->toMessageData().as<uint32_t>());
524 return true;
525 });
526 EXPECT_THROW(
527 client->connectClientReceiver(
528 "out", [](std::unique_ptr<SegmentedMessageData> &) { return true; }),
529 std::runtime_error);
530
531 // The first receiver is undisturbed.
532 toClient->write(msg(5));
533 ASSERT_EQ(f.wait_for(10s), std::future_status::ready);
534 EXPECT_EQ(f.get(), 5u);
535}
536
537TEST_F(CosimRpcTest, ToClientBlockingWrite) {
538 connectClient();
539 std::atomic<bool> accepting = false;
540 std::atomic<int> received = 0;
541 auto conn = client->connectClientReceiver(
542 "out",
543 [&](std::unique_ptr<SegmentedMessageData> &) {
544 if (!accepting)
545 return false;
546 ++received;
547 return true;
548 },
549 /*maxInFlight=*/2);
550 toClient->write(msg(0));
551 toClient->write(msg(1));
552
553 // At the limit: `write()` blocks until the client consumes something.
554 std::atomic<bool> written = false;
555 std::thread writer([&] {
556 toClient->write(msg(2));
557 written = true;
558 });
559 std::this_thread::sleep_for(100ms);
560 EXPECT_FALSE(written);
561 accepting = true;
562 ASSERT_TRUE(waitFor([&] { return written.load(); }));
563 writer.join();
564 ASSERT_TRUE(waitFor([&] { return received == 3; }));
565}
566
567TEST_F(CosimRpcTest, ToClientBlockedWriteThrowsOnDisconnect) {
568 // Without a subscriber, the default in-flight limit applies.
569 uint32_t next = 0;
570 while (toClient->tryWrite(msg(next)))
571 ++next;
572 std::promise<bool> threw;
573 std::thread writer([&] {
574 try {
575 toClient->write(msg(next));
576 threw.set_value(false);
577 } catch (const std::exception &) {
578 threw.set_value(true);
579 }
580 });
581 std::this_thread::sleep_for(50ms);
582 toClient->disconnect();
583 auto f = threw.get_future();
584 ASSERT_EQ(f.wait_for(10s), std::future_status::ready);
585 EXPECT_TRUE(f.get());
586 writer.join();
587}
588
589using Frames = std::optional<std::vector<MessageData>>;
590
591TEST_F(CosimRpcTest, ServerSenderDrivenByCredits) {
592 connectClient();
593 client->setToServerMaxInFlight("in", 2);
594 constexpr uint32_t numMsgs = 10;
595 std::atomic<uint32_t> fetches = 0, next = 0;
596 auto conn = client->connectServerSender(
597 "in",
598 [&]() -> Frames {
599 ++fetches;
600 if (next == numMsgs)
601 return std::nullopt;
602 return std::vector<MessageData>{msg(next++)};
603 },
604 [](std::exception_ptr) { ADD_FAILURE(); });
605 // Fetches as many messages as the in-flight limit allows.
606 conn->notify();
607 ASSERT_TRUE(waitFor([&] { return next == 2; }));
608 std::this_thread::sleep_for(50ms);
609 EXPECT_EQ(fetches, 2u);
610
611 // Each frame the simulation consumes returns a credit, which fetches
612 // another message without a notification.
613 for (uint32_t i = 0; i < numMsgs; ++i)
614 EXPECT_EQ(consumeOne(), i);
615 // Plus the fetch which found no more data.
616 ASSERT_TRUE(waitFor([&] { return fetches == numMsgs + 1; }));
617}
618
619TEST_F(CosimRpcTest, ServerSenderFetchesAgainOnlyWhenNotified) {
620 connectClient();
621 std::atomic<int> fetches = 0, errors = 0;
622 std::atomic<bool> fail = false;
623 auto conn = client->connectServerSender(
624 "in",
625 [&]() -> Frames {
626 ++fetches;
627 if (fail)
628 throw std::runtime_error("fetch failure");
629 return std::nullopt;
630 },
631 [&](std::exception_ptr) { ++errors; });
632 // One sender per channel, and only to-server channels.
633 auto noFetch = []() -> Frames { return std::nullopt; };
634 auto noError = [](std::exception_ptr) {};
635 EXPECT_THROW(client->connectServerSender("in", noFetch, noError),
636 std::runtime_error);
637 EXPECT_THROW(client->connectServerSender("out", noFetch, noError),
638 std::runtime_error);
639
640 // After returning nullopt, not called again until notified, even when
641 // credits change.
642 conn->notify();
643 ASSERT_TRUE(waitFor([&] { return fetches == 1; }));
644 client->setToServerMaxInFlight("in", 3);
645 std::this_thread::sleep_for(50ms);
646 EXPECT_EQ(fetches, 1);
647
648 // Likewise after throwing, which is reported.
649 fail = true;
650 conn->notify();
651 ASSERT_TRUE(waitFor([&] { return errors == 1; }));
652 std::this_thread::sleep_for(50ms);
653 EXPECT_EQ(fetches, 2);
654
655 // Once disconnected, it isn't called, and the channel can have another.
656 conn->disconnect();
657 conn->notify();
658 std::this_thread::sleep_for(50ms);
659 EXPECT_EQ(fetches, 2);
660 auto conn2 = client->connectServerSender("in", noFetch, noError);
661}
662
663TEST_F(CosimRpcTest, ServerSenderTakesTurns) {
664 connectClient();
665 client->setToServerMaxInFlight("in", 0);
666 // A sender which always has data doesn't stop other channels being
667 // serviced.
668 std::atomic<bool> stop = false;
669 std::atomic<uint32_t> sent = 0;
670 auto conn = client->connectServerSender(
671 "in",
672 [&]() -> Frames {
673 if (stop)
674 return std::nullopt;
675 return std::vector<MessageData>{msg(sent++)};
676 },
677 [](std::exception_ptr) { ADD_FAILURE(); });
678 auto received = std::make_shared<std::promise<uint32_t>>();
679 auto reader = client->connectClientReceiver(
680 "out", [received](std::unique_ptr<SegmentedMessageData> &data) {
681 received->set_value(*data->toMessageData().as<uint32_t>());
682 return true;
683 });
684 conn->notify();
685 ASSERT_TRUE(waitFor([&] { return sent > 0; }));
686 toClient->write(msg(7));
687 std::future<uint32_t> f = received->get_future();
688 EXPECT_EQ(f.wait_for(10s), std::future_status::ready);
689 stop = true;
690 conn->disconnect();
691 EXPECT_EQ(f.get(), 7u);
692 EXPECT_GE(sent, RpcClient::MaxSendsPerTurn);
693}
694
695TEST_F(CosimRpcTest, ServerSenderZeroFrameMessagesTakeTurns) {
696 connectClient();
697 // Messages without frames send nothing, but don't stop more being fetched.
698 // A source which only has those then doesn't stop other channels being
699 // serviced, since they count towards the sender's turn.
700 std::atomic<uint32_t> fetches = 0;
701 auto conn = client->connectServerSender(
702 "in",
703 [&]() -> Frames {
704 uint32_t n = ++fetches;
705 if (n == 2 || n == 4)
706 return std::vector<MessageData>{msg(n / 2)};
707 return std::vector<MessageData>{};
708 },
709 [](std::exception_ptr) { ADD_FAILURE(); });
710 auto received = std::make_shared<std::promise<uint32_t>>();
711 auto reader = client->connectClientReceiver(
712 "out", [received](std::unique_ptr<SegmentedMessageData> &data) {
713 received->set_value(*data->toMessageData().as<uint32_t>());
714 return true;
715 });
716 conn->notify();
717 EXPECT_EQ(consumeOne(), 1u);
718 EXPECT_EQ(consumeOne(), 2u);
719 toClient->write(msg(7));
720 std::future<uint32_t> f = received->get_future();
721 EXPECT_EQ(f.wait_for(10s), std::future_status::ready);
722 conn->disconnect();
723 EXPECT_EQ(f.get(), 7u);
724}
725
726TEST_F(CosimRpcTest, ServerSenderDisconnectWaitsForCall) {
727 connectClient();
728 std::atomic<bool> inCall = false, release = false;
729 auto conn = client->connectServerSender(
730 "in",
731 [&]() -> Frames {
732 inCall = true;
733 while (!release)
734 std::this_thread::yield();
735 return std::nullopt;
736 },
737 [](std::exception_ptr) {});
738 conn->notify();
739 ASSERT_TRUE(waitFor([&] { return inCall.load(); }));
740
741 // Disconnecting on another thread blocks until the call returns.
742 std::atomic<bool> disconnected = false;
743 std::thread disconnecter([&] {
744 conn->disconnect();
745 disconnected = true;
746 });
747 std::this_thread::sleep_for(50ms);
748 EXPECT_FALSE(disconnected);
749 release = true;
750 disconnecter.join();
751 EXPECT_TRUE(disconnected);
752}
753
754TEST_F(CosimRpcTest, ServerSenderCanDisconnectItself) {
755 connectClient();
756 std::unique_ptr<RpcClient::WriteChannelConnection> conn;
757 std::atomic<int> fetches = 0, errors = 0;
758 std::promise<void> done;
759 conn = client->connectServerSender(
760 "in",
761 [&]() -> Frames {
762 ++fetches;
763 conn->disconnect();
764 done.set_value();
765 // Dropped, since it's disconnected.
766 return std::vector<MessageData>{msg(1)};
767 },
768 [&](std::exception_ptr) { ++errors; });
769 conn->notify();
770 ASSERT_EQ(done.get_future().wait_for(10s), std::future_status::ready);
771 std::future<MessageData> f = toServer->readAsync();
772 EXPECT_EQ(f.wait_for(100ms), std::future_status::timeout);
773 EXPECT_EQ(fetches, 1);
774 EXPECT_EQ(errors, 0);
775}
776
777TEST_F(CosimRpcTest, ServerSenderReportsConnectionLoss) {
778 connectClient();
779 auto lost = std::make_shared<std::promise<void>>();
780 std::atomic<bool> reported = false;
781 auto conn = client->connectServerSender(
782 "in", []() -> Frames { return std::nullopt; },
783 [lost, &reported](std::exception_ptr) {
784 if (!reported.exchange(true))
785 lost->set_value();
786 });
787 // Woken by the connection closing.
788 server->stop();
789 server.reset();
790 ASSERT_EQ(lost->get_future().wait_for(10s), std::future_status::ready);
791 conn.reset();
792}
793
794} // namespace
static std::unique_ptr< RpcServer > server
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:73
static constexpr size_t MaxSendsPerTurn
The most messages a sender sends before other channels are serviced.
Definition RpcClient.h:120
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
const T * as() const
Cast to a type.
Definition Common.h:240
static MessageData from(T &t)
Cast from a type to its raw bytes.
Definition Common.h:250
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
Definition Ports.cpp:143
virtual std::future< MessageData > readAsync()
Asynchronous polling read.
Definition Ports.cpp:228
virtual void disconnect() override
Disconnect the channel.
Definition Ports.cpp:71
virtual void disconnect() override
Disconnect the port.
Definition Ports.cpp:902
void write(const MessageData &data)
A very basic blocking write API.
Definition Ports.h:356
bool tryWrite(const MessageData &data)
A basic non-blocking write API.
Definition Ports.h:379
A client for the cosim RPC server.
Definition RpcClient.h:36
TODO: make this a proper backend (as much as possible).
Definition RpcServer.h:26
Definition esi.py:1