Bitcoin Core 30.99.0
P2P Digital Currency
test.cpp
Go to the documentation of this file.
1// Copyright (c) The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <mp/test/foo.capnp.h>
6#include <mp/test/foo.capnp.proxy.h>
7
8#include <atomic>
9#include <capnp/capability.h>
10#include <capnp/rpc.h>
11#include <condition_variable>
12#include <cstring>
13#include <functional>
14#include <future>
15#include <kj/async.h>
16#include <kj/async-io.h>
17#include <kj/common.h>
18#include <kj/debug.h>
19#include <kj/exception.h>
20#include <kj/memory.h>
21#include <kj/string.h>
22#include <kj/test.h>
23#include <memory>
24#include <mp/proxy.h>
25#include <mp/proxy.capnp.h>
26#include <mp/proxy-io.h>
27#include <mp/util.h>
28#include <mp/version.h>
29#include <optional>
30#include <set>
31#include <stdexcept>
32#include <string>
33#include <string_view>
34#include <system_error>
35#include <thread>
36#include <type_traits>
37#include <utility>
38#include <vector>
39
40namespace mp {
41namespace test {
42
46static_assert(std::is_integral_v<decltype(kMP_MAJOR_VERSION)>, "MP_MAJOR_VERSION must be an integral constant");
47static_assert(std::is_integral_v<decltype(kMP_MINOR_VERSION)>, "MP_MINOR_VERSION must be an integral constant");
48
64{
65public:
66 std::function<void()> server_disconnect;
67 std::function<void()> client_disconnect;
68 std::promise<std::unique_ptr<ProxyClient<messages::FooInterface>>> client_promise;
69 std::unique_ptr<ProxyClient<messages::FooInterface>> client;
73 std::thread thread;
74
75 TestSetup(bool client_owns_connection = true)
76 : thread{[&] {
77 EventLoop loop("mptest", [](mp::LogMessage log) {
78 // Info logs are not printed by default, but will be shown with `mptest --verbose`
79 KJ_LOG(INFO, log.level, log.message);
80 if (log.level == mp::Log::Raise) throw std::runtime_error(log.message);
81 });
82 auto pipe = loop.m_io_context.provider->newTwoWayPipe();
83
84 auto server_connection =
85 std::make_unique<Connection>(loop, kj::mv(pipe.ends[0]), [&](Connection& connection) {
86 auto server_proxy = kj::heap<ProxyServer<messages::FooInterface>>(
87 std::make_shared<FooImplementation>(), connection);
88 server = server_proxy;
89 return capnp::Capability::Client(kj::mv(server_proxy));
90 });
91 server_disconnect = [&] { loop.sync([&] { server_connection.reset(); }); };
92 // Set handler to destroy the server when the client disconnects. This
93 // is ignored if server_disconnect() is called instead.
94 server_connection->onDisconnect([&] { server_connection.reset(); });
95
96 auto client_connection = std::make_unique<Connection>(loop, kj::mv(pipe.ends[1]));
97 auto client_proxy = std::make_unique<ProxyClient<messages::FooInterface>>(
98 client_connection->m_rpc_system->bootstrap(ServerVatId().vat_id).castAs<messages::FooInterface>(),
99 client_connection.get(), /* destroy_connection= */ client_owns_connection);
100 if (client_owns_connection) {
101 client_connection.release();
102 } else {
103 client_disconnect = [&] { loop.sync([&] { client_connection.reset(); }); };
104 }
105
106 client_promise.set_value(std::move(client_proxy));
107 loop.loop();
108 }}
109 {
110 client = client_promise.get_future().get();
111 }
112
114 {
115 // Test that client cleanup_fns are executed.
116 bool destroyed = false;
117 client->m_context.cleanup_fns.emplace_front([&destroyed] { destroyed = true; });
118 client.reset();
119 KJ_EXPECT(destroyed);
120
121 thread.join();
122 }
123};
124
125KJ_TEST("Call FooInterface methods")
126{
128 ProxyClient<messages::FooInterface>* foo = setup.client.get();
129
130 KJ_EXPECT(foo->add(1, 2) == 3);
131 int ret;
132 foo->addOut(3, 4, ret);
133 KJ_EXPECT(ret == 7);
134 foo->addInOut(3, ret);
135 KJ_EXPECT(ret == 10);
136
137 FooStruct in;
138 in.name = "name";
139 in.setint.insert(2);
140 in.setint.insert(1);
141 in.vbool.push_back(false);
142 in.vbool.push_back(true);
143 in.vbool.push_back(false);
144 FooStruct out = foo->pass(in);
145 KJ_EXPECT(in.name == out.name);
146 KJ_EXPECT(in.setint.size() == out.setint.size());
147 for (auto init{in.setint.begin()}, outit{out.setint.begin()}; init != in.setint.end() && outit != out.setint.end(); ++init, ++outit) {
148 KJ_EXPECT(*init == *outit);
149 }
150 KJ_EXPECT(in.vbool.size() == out.vbool.size());
151 for (size_t i = 0; i < in.vbool.size(); ++i) {
152 KJ_EXPECT(in.vbool[i] == out.vbool[i]);
153 }
154
155 FooStruct err;
156 try {
157 foo->raise(in);
158 } catch (const FooStruct& e) {
159 err = e;
160 }
161 KJ_EXPECT(in.name == err.name);
162
163 class Callback : public ExtendedCallback
164 {
165 public:
166 Callback(int expect, int ret) : m_expect(expect), m_ret(ret) {}
167 int call(int arg) override
168 {
169 KJ_EXPECT(arg == m_expect);
170 return m_ret;
171 }
172 int callExtended(int arg) override
173 {
174 KJ_EXPECT(arg == m_expect + 10);
175 return m_ret + 10;
176 }
177 int m_expect, m_ret;
178 };
179
180 foo->initThreadMap();
181 Callback callback(1, 2);
182 KJ_EXPECT(foo->callback(callback, 1) == 2);
183 KJ_EXPECT(foo->callbackUnique(std::make_unique<Callback>(3, 4), 3) == 4);
184 KJ_EXPECT(foo->callbackShared(std::make_shared<Callback>(5, 6), 5) == 6);
185 auto saved = std::make_shared<Callback>(7, 8);
186 KJ_EXPECT(saved.use_count() == 1);
187 foo->saveCallback(saved);
188 KJ_EXPECT(saved.use_count() == 2);
189 foo->callbackSaved(7);
190 KJ_EXPECT(foo->callbackSaved(7) == 8);
191 foo->saveCallback(nullptr);
192 KJ_EXPECT(saved.use_count() == 1);
193 KJ_EXPECT(foo->callbackExtended(callback, 11) == 12);
194
195 FooCustom custom_in;
196 custom_in.v1 = "v1";
197 custom_in.v2 = 5;
198 FooCustom custom_out = foo->passCustom(custom_in);
199 KJ_EXPECT(custom_in.v1 == custom_out.v1);
200 KJ_EXPECT(custom_in.v2 == custom_out.v2);
201
202 foo->passEmpty(FooEmpty{});
203
204 FooMessage message1;
205 message1.message = "init";
206 FooMessage message2{foo->passMessage(message1)};
207 KJ_EXPECT(message2.message == "init build read call build read");
208
209 FooMutable mut;
210 mut.message = "init";
211 foo->passMutable(mut);
212 KJ_EXPECT(mut.message == "init build pass call return read");
213
214 KJ_EXPECT(foo->passFn([]{ return 10; }) == 10);
215}
216
217KJ_TEST("Call IPC method after client connection is closed")
218{
219 TestSetup setup{/*client_owns_connection=*/false};
220 ProxyClient<messages::FooInterface>* foo = setup.client.get();
221 KJ_EXPECT(foo->add(1, 2) == 3);
222 setup.client_disconnect();
223
224 bool disconnected{false};
225 try {
226 foo->add(1, 2);
227 } catch (const std::runtime_error& e) {
228 KJ_EXPECT(std::string_view{e.what()} == "IPC client method called after disconnect.");
229 disconnected = true;
230 }
231 KJ_EXPECT(disconnected);
232}
233
234KJ_TEST("Calling IPC method after server connection is closed")
235{
237 ProxyClient<messages::FooInterface>* foo = setup.client.get();
238 KJ_EXPECT(foo->add(1, 2) == 3);
239 setup.server_disconnect();
240
241 bool disconnected{false};
242 try {
243 foo->add(1, 2);
244 } catch (const std::runtime_error& e) {
245 KJ_EXPECT(std::string_view{e.what()} == "IPC client method call interrupted by disconnect.");
246 disconnected = true;
247 }
248 KJ_EXPECT(disconnected);
249}
250
251KJ_TEST("Calling IPC method and disconnecting during the call")
252{
253 TestSetup setup{/*client_owns_connection=*/false};
254 ProxyClient<messages::FooInterface>* foo = setup.client.get();
255 KJ_EXPECT(foo->add(1, 2) == 3);
256
257 // Set m_fn to initiate client disconnect when server is in the middle of
258 // handling the callFn call to make sure this case is handled cleanly.
259 setup.server->m_impl->m_fn = setup.client_disconnect;
260
261 bool disconnected{false};
262 try {
263 foo->callFn();
264 } catch (const std::runtime_error& e) {
265 KJ_EXPECT(std::string_view{e.what()} == "IPC client method call interrupted by disconnect.");
266 disconnected = true;
267 }
268 KJ_EXPECT(disconnected);
269}
270
271KJ_TEST("Calling IPC method, disconnecting and blocking during the call")
272{
273 // This test is similar to last test, except that instead of letting the IPC
274 // call return immediately after triggering a disconnect, make it disconnect
275 // & wait so server is forced to deal with having a disconnection and call
276 // in flight at the same time.
277 //
278 // Test uses callFnAsync() instead of callFn() to implement this. Both of
279 // these methods have the same implementation, but the callFnAsync() capnp
280 // method declaration takes an mp.Context argument so the method executes on
281 // an asynchronous thread instead of executing in the event loop thread, so
282 // it is able to block without deadlocking the event lock thread.
283 //
284 // This test adds important coverage because it causes the server Connection
285 // object to be destroyed before ProxyServer object, which is not a
286 // condition that usually happens because the m_rpc_system.reset() call in
287 // the ~Connection destructor usually would immediately free all remaining
288 // ProxyServer objects associated with the connection. Having an in-progress
289 // RPC call requires keeping the ProxyServer longer.
290
291 std::promise<void> signal;
292 TestSetup setup{/*client_owns_connection=*/false};
293 ProxyClient<messages::FooInterface>* foo = setup.client.get();
294 KJ_EXPECT(foo->add(1, 2) == 3);
295
296 foo->initThreadMap();
297 setup.server->m_impl->m_fn = [&] {
298 EventLoopRef loop{*setup.server->m_context.loop};
299 setup.client_disconnect();
300 signal.get_future().get();
301 };
302
303 bool disconnected{false};
304 try {
305 foo->callFnAsync();
306 } catch (const std::runtime_error& e) {
307 KJ_EXPECT(std::string_view{e.what()} == "IPC client method call interrupted by disconnect.");
308 disconnected = true;
309 }
310 KJ_EXPECT(disconnected);
311
312 // Now that the disconnect has been detected, set signal allowing the
313 // callFnAsync() IPC call to return. Since signalling may not wake up the
314 // thread right away, it is important for the signal variable to be declared
315 // *before* the TestSetup variable so is not destroyed while
316 // signal.get_future().get() is called.
317 signal.set_value();
318}
319
320KJ_TEST("Make simultaneous IPC calls to trigger 'thread busy' error")
321{
323 ProxyClient<messages::FooInterface>* foo = setup.client.get();
324 std::promise<void> signal;
325
326 foo->initThreadMap();
327 // Use callFnAsync() to get the client to set up the request_thread
328 // that will be used for the test.
329 setup.server->m_impl->m_fn = [&] {};
330 foo->callFnAsync();
332 Thread::Client *callback_thread, *request_thread;
333 foo->m_context.loop->sync([&] {
334 Lock lock(tc.waiter->m_mutex);
335 callback_thread = &tc.callback_threads.at(foo->m_context.connection)->m_client;
336 request_thread = &tc.request_threads.at(foo->m_context.connection)->m_client;
337 });
338
339 setup.server->m_impl->m_fn = [&] {
340 try
341 {
342 signal.get_future().get();
343 }
344 catch (const std::future_error& e)
345 {
346 KJ_EXPECT(e.code() == std::make_error_code(std::future_errc::future_already_retrieved));
347 }
348 };
349
350 auto client{foo->m_client};
351 bool caught_thread_busy = false;
352 // NOTE: '3' was chosen because it was the lowest number
353 // of simultaneous calls required to reliably catch a "thread busy" error
354 std::atomic<size_t> running{3};
355 foo->m_context.loop->sync([&]
356 {
357 for (size_t i = 0; i < running; i++)
358 {
359 auto request{client.callFnAsyncRequest()};
360 auto context{request.initContext()};
361 context.setCallbackThread(*callback_thread);
362 context.setThread(*request_thread);
363 foo->m_context.loop->m_task_set->add(request.send().then(
364 [&](auto&& results) {
365 running -= 1;
366 tc.waiter->m_cv.notify_all();
367 },
368 [&](kj::Exception&& e) {
369 KJ_EXPECT(std::string_view{e.getDescription().cStr()} ==
370 "remote exception: std::exception: thread busy");
371 caught_thread_busy = true;
372 running -= 1;
373 signal.set_value();
374 tc.waiter->m_cv.notify_all();
375 }
376 ));
377 }
378 });
379 {
380 Lock lock(tc.waiter->m_mutex);
381 tc.waiter->wait(lock, [&running] { return running == 0; });
382 }
383 KJ_EXPECT(caught_thread_busy);
384}
385
386} // namespace test
387} // namespace mp
int ret
Object holding network & rpc state associated with either an incoming server connection,...
Definition: proxy-io.h:377
Event loop implementation.
Definition: proxy-io.h:214
kj::AsyncIoContext m_io_context
Capnp IO context.
Definition: proxy-io.h:302
Event loop smart pointer automatically managing m_num_clients.
Definition: proxy.h:51
Definition: util.h:170
Test setup class creating a two way connection between a ProxyServer<FooInterface> object and a Proxy...
Definition: test.cpp:64
std::promise< std::unique_ptr< ProxyClient< messages::FooInterface > > > client_promise
Definition: test.cpp:68
TestSetup(bool client_owns_connection=true)
Definition: test.cpp:75
std::function< void()> server_disconnect
Definition: test.cpp:66
std::function< void()> client_disconnect
Definition: test.cpp:67
std::thread thread
Thread variable should be after other struct members so the thread does not start until the other mem...
Definition: test.cpp:73
ProxyServer< messages::FooInterface > * server
Definition: test.cpp:70
std::unique_ptr< ProxyClient< messages::FooInterface > > client
Definition: test.cpp:69
constexpr auto kMP_MAJOR_VERSION
Check version.h header values.
Definition: test.cpp:44
constexpr auto kMP_MINOR_VERSION
Definition: test.cpp:45
Functions to serialize / deserialize common bitcoin types.
Definition: common-types.h:57
thread_local ThreadContext g_thread_context
Definition: proxy.cpp:41
KJ_TEST("SpawnProcess does not run callback in child")
Definition: spawn_tests.cpp:44
Log level
The severity level of this message.
Definition: proxy-io.h:119
std::string message
Message to be logged.
Definition: proxy-io.h:116
Mapping from capnp interface type to proxy client implementation (specializations are generated by pr...
Definition: proxy.h:25
Vat id for server side of connection.
Definition: proxy-io.h:446
The thread_local ThreadContext g_thread_context struct provides information about individual threads ...
Definition: proxy-io.h:621
std::string v1
Definition: foo.h:30
std::string message
Definition: foo.h:40
std::string message
Definition: foo.h:45
std::string name
Definition: foo.h:21
std::set< int > setint
Definition: foo.h:22
std::vector< bool > vbool
Definition: foo.h:23
static int setup(void)
Definition: tests.c:7808
#define expect(bit)
#define MP_MAJOR_VERSION
Major version number.
Definition: version.h:19
#define MP_MINOR_VERSION
Minor version number.
Definition: version.h:24