Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
proxy-types.h
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#ifndef MP_PROXY_TYPES_H
6#define MP_PROXY_TYPES_H
7
8#include <mp/proxy-io.h>
9
10#include <exception>
11#include <optional>
12#include <set>
13#include <typeindex>
14#include <vector>
15
16// KJ exception support is required, or exceptions thrown in serverInvoke below go uncaught
17// and crash the process instead of being returned to the client as errors.
18#if defined(KJ_NO_EXCEPTIONS) && KJ_NO_EXCEPTIONS
19#error "KJ_NO_EXCEPTIONS=1 is set but libmultiprocess requires support for exceptions. Please check build settings. On NetBSD you may also need to set -DKJ_NO_EXCEPTIONS=0 -DKJ_NO_RTTI=0 explicitly (https://github.com/capnproto/capnproto/pull/2756)"
20#endif
21
22namespace mp {
23
24template <typename Value>
26{
27public:
28 ValueField(Value& value) : m_value(value) {}
29 ValueField(Value&& value) : m_value(value) {}
30 Value& m_value;
31
32 const Value& get() const { return m_value; }
33 Value& get() { return m_value; }
34 Value& init() { return m_value; }
35 bool has() const { return true; }
36};
37
38template <typename Accessor, typename Struct>
40{
41 template <typename S>
46
47 decltype(auto) get() const { return Accessor::get(this->m_struct); }
48
49 bool has() const {
50 if constexpr (Accessor::optional) {
51 return Accessor::getHas(m_struct);
52 } else if constexpr (Accessor::boxed) {
53 return Accessor::has(m_struct);
54 } else {
55 return true;
56 }
57 }
58
59 bool want() const {
60 if constexpr (Accessor::requested) {
61 return Accessor::getWant(m_struct);
62 } else {
63 return true;
64 }
65 }
66
67 template <typename... Args> decltype(auto) set(Args &&...args) const {
68 return Accessor::set(this->m_struct, std::forward<Args>(args)...);
69 }
70
71 template <typename... Args> decltype(auto) init(Args &&...args) const {
72 return Accessor::init(this->m_struct, std::forward<Args>(args)...);
73 }
74
75 void setHas() const {
76 if constexpr (Accessor::optional) {
77 Accessor::setHas(m_struct);
78 }
79 }
80
81 void setWant() const {
82 if constexpr (Accessor::requested) {
83 Accessor::setWant(m_struct);
84 }
85 }
86};
87
88
89
90// Destination parameter type that can be passed to ReadField function as an
91// alternative to ReadDestUpdate. It allows the ReadField implementation to call
92// the provided emplace_fn function with constructor arguments, so it only needs
93// to determine the arguments, and can let the emplace function decide how to
94// actually construct the read destination object. For example, if a std::string
95// is being read, the ReadField call will call the custom emplace_fn with char*
96// and size_t arguments, and the emplace function can decide whether to call the
97// constructor via the operator, make_shared, emplace or just return a
98// temporary string that is moved from.
99template <typename LocalType, typename EmplaceFn>
101{
103
106 template <typename... Args>
107 decltype(auto) construct(Args&&... args)
108 {
109 return m_emplace_fn(std::forward<Args>(args)...);
110 }
111
116 template <typename UpdateFn>
117 decltype(auto) update(UpdateFn&& update_fn)
118 {
119 if constexpr (std::is_const_v<std::remove_reference_t<std::invoke_result_t<EmplaceFn>>>) {
120 // If destination type is const, default construct temporary
121 // to pass to update, then call move constructor via construct() to
122 // move from that temporary.
123 std::remove_cv_t<LocalType> temp;
125 return construct(std::move(temp));
126 } else {
127 // Default construct object and pass it to update_fn.
128 decltype(auto) temp = construct();
130 return temp;
131 }
132 }
134};
135
138template <typename LocalType>
140{
141 return ReadDestEmplace{TypeList<LocalType>(), [](auto&&... args) -> decltype(auto) {
142 return LocalType{std::forward<decltype(args)>(args)...};
143 }};
144}
145
150template <typename Value>
152{
153 ReadDestUpdate(Value& value) : m_value(value) {}
154
156 template <typename UpdateFn>
158 {
160 return m_value;
161 }
162
165 template <typename... Args>
166 Value& construct(Args&&... args)
167 {
168 m_value.~Value();
169 new (&m_value) Value(std::forward<Args>(args)...);
170 return m_value;
171 }
172
173 Value& m_value;
174};
175
212template <typename... LocalTypes, typename Input>
214{
215 return input.has();
216}
217
218template <typename... LocalTypes, typename Input, typename... Args>
220{
221 return CustomReadField(TypeList<RemoveCvRef<LocalTypes>...>(), Priority<2>(), invoke_context, std::forward<Input>(input), std::forward<Args>(args)...);
222}
223
224template <typename LocalType, typename Input>
226{
227 ReadField(
229 [] [[noreturn]] (auto&& ...args) -> const LocalType& { throw LocalType{std::forward<decltype(args)>(args)...}; }));
230}
231
235template <typename Input>
237{
238 auto data = input.get();
239 throw std::runtime_error(std::string(CharCast(data.begin()), data.size()));
240}
241
249template <typename... Values>
251{
252 return true;
253}
254
255template <typename... LocalTypes, typename Context, typename... Values, typename Output>
257{
258 if (CustomHasValue(context, values...)) {
259 CustomBuildField(TypeList<LocalTypes...>(), Priority<3>(), context, std::forward<Values>(values)...,
260 std::forward<Output>(output));
261 }
262}
263
264// Adapter that allows BuildField overloads to work with, set, and initialize list
265// elements as if they were fields of a struct. If BuildField is changed to use some
266// kind of accessor class instead of calling method pointers, then maybe this could
267// go away or be simplified, because there would no longer be a need to return
268// ListOutput method pointers emulating capnp struct method pointers.
269template <typename ListType>
271
272template <typename T, ::capnp::Kind kind>
273struct ListOutput<::capnp::List<T, kind>>
274{
275 using Builder = typename ::capnp::List<T, kind>::Builder;
276
277 ListOutput(Builder& builder, size_t index) : m_builder(builder), m_index(index) {}
279 size_t m_index;
280
281 // clang-format off
282 decltype(auto) get() const { return this->m_builder[this->m_index]; }
283 decltype(auto) init() const { return this->m_builder[this->m_index]; }
284 template<typename B = Builder, typename Arg> decltype(auto) set(Arg&& arg) const { return static_cast<B&>(this->m_builder).set(m_index, std::forward<Arg>(arg)); }
285 template<typename B = Builder, typename Arg> decltype(auto) init(Arg&& arg) const { return static_cast<B&>(this->m_builder).init(m_index, std::forward<Arg>(arg)); }
286 // clang-format on
287};
288
289template <typename LocalType, typename Value, typename Output>
291{
292 auto list = output.init(value.size());
293 size_t i = 0;
294 // Iterate with an explicit iterator rather than a range-for loop so the
295 // value category of `*it` is passed through to BuildField unchanged. This
296 // matters for two reasons:
297 //
298 // - Elements must be passed as non-const so that BuildField can move out of
299 // them, e.g. calling unique_ptr::release() to transfer ownership of an
300 // interface pointer to the capnp server.
301 //
302 // - For proxy containers like std::vector<bool>, `*it` is a prvalue proxy
303 // object rather than a reference. A range-for loop would bind it to a
304 // named variable and demote it to an lvalue; passing `*it` directly
305 // preserves the prvalue-ness.
306 //
307 // Only move out of elements when `value` itself is an rvalue container that
308 // is about to be destroyed. When it is an lvalue reference owned by the
309 // caller, pass elements as lvalues so BuildField does not move from them.
310 for (auto it = value.begin(); it != value.end(); ++it, ++i) {
311 if constexpr (std::is_lvalue_reference_v<Value&&>) {
312 BuildField(TypeList<LocalType>(), invoke_context, ListOutput<typename decltype(list)::Builds>(list, i), *it);
313 } else {
314 BuildField(TypeList<LocalType>(), invoke_context, ListOutput<typename decltype(list)::Builds>(list, i), std::move(*it));
315 }
316 }
317}
318
319template <typename LocalType, typename Input, typename ReadDest, typename InitFn, typename EmplaceFn>
321{
322 return read_dest.update([&](auto& value) {
323 auto data = input.get();
324 init(value, data.size());
325 for (auto item : data) {
327 ReadDestEmplace(TypeList<LocalType>(), [&emplace, &value](auto&&... args) -> decltype(auto) {
328 return emplace(value, std::forward<decltype(args)>(args)...);
329 }));
330 }
331 });
332}
333
334template <typename LocalType, typename Value, typename Output>
336{
337 output.set(BuildPrimitive(invoke_context, std::forward<Value>(value), TypeList<decltype(output.get())>()));
338}
339
341template <typename Accessor, typename LocalType, typename ServerContext, typename Fn, typename... Args>
343 -> Require<typename decltype(Accessor::get(server_context.call_context.getParams()))::Calls>
344{
345 // Just create a temporary ProxyClient if argument is a reference to an
346 // interface client. If argument needs to have a longer lifetime and not be
347 // destroyed after this call, a CustomPassField overload can be implemented
348 // to bypass this code, and a custom ProxyServerMethodTraits overload can be
349 // implemented in order to read the capability pointer out of params and
350 // construct a ProxyClient with a longer lifetime.
351 const auto& params = server_context.call_context.getParams();
352 const auto& input = Make<StructField, Accessor>(params);
353 using Interface = typename Decay<decltype(input.get())>::Calls;
354 auto param = std::make_unique<ProxyClient<Interface>>(input.get(), server_context.proxy_server.m_context.connection, false);
355 fn.invoke(server_context, std::forward<Args>(args)..., *param);
356}
357
358template <typename... Args>
359void MaybeBuildField(std::true_type, Args&&... args)
360{
361 BuildField(std::forward<Args>(args)...);
362}
363template <typename... Args>
364void MaybeBuildField(std::false_type, Args&&...)
365{
366}
367template <typename... Args>
368void MaybeReadField(std::true_type, Args&&... args)
369{
370 ReadField(std::forward<Args>(args)...);
371}
372template <typename... Args>
373void MaybeReadField(std::false_type, Args&&...)
374{
375}
376
377template <typename LocalType, typename Value, typename Output>
378void MaybeSetWant(TypeList<LocalType*>, Priority<1>, const Value& value, Output&& output)
379{
380 if (value) {
381 output.setWant();
382 }
383}
384
385template <typename LocalTypes, typename... Args>
386void MaybeSetWant(LocalTypes, Priority<0>, const Args&...)
387{
388}
389
391template <typename Accessor, typename LocalType, typename ServerContext, typename Fn, typename... Args>
393{
396 std::optional<ArgType> param;
397 const auto& params = server_context.call_context.getParams();
398 MaybeReadField(std::integral_constant<bool, Accessor::in>(), TypeList<ArgType>(), invoke_context,
399 Make<StructField, Accessor>(params), ReadDestEmplace(TypeList<ArgType>(), [&](auto&&... args) -> auto& {
400 param.emplace(std::forward<decltype(args)>(args)...);
401 return *param;
402 }));
403 if constexpr (Accessor::in) {
404 assert(param);
405 } else {
406 if (!param) param.emplace();
407 }
408 fn.invoke(server_context, std::forward<Args>(args)..., static_cast<LocalType&&>(*param));
409 auto&& results = server_context.call_context.getResults();
410 MaybeBuildField(std::integral_constant<bool, Accessor::out>(), TypeList<LocalType>(), invoke_context,
412}
413
415template <typename Accessor, typename ServerContext, typename Fn, typename... Args>
417{
418 const auto& params = server_context.call_context.getParams();
419 const auto& input = Make<StructField, Accessor>(params);
421 fn.invoke(server_context, std::forward<Args>(args)...);
422 auto&& results = server_context.call_context.getResults();
424}
425
426template <typename Derived, size_t N = 0>
428{
429 template <typename Arg1, typename Arg2, typename ParamList, typename NextFn, typename... NextFnArgs>
431 {
432 using S = Split<N, ParamList>;
433 handleChain(arg1, arg2, typename S::First());
434 next_fn.handleChain(arg1, arg2, typename S::Second(),
435 std::forward<NextFnArgs>(next_fn_args)...);
436 }
437
438 template <typename Arg1, typename Arg2, typename ParamList>
440 {
441 static_cast<Derived*>(this)->handleField(arg1, arg2, ParamList());
442 }
443private:
445 friend Derived;
446};
447
448struct IterateFields : IterateFieldsHelper<IterateFields, 0>
449{
450 template <typename Arg1, typename Arg2, typename ParamList>
452 {
453 }
454};
455
456template <typename Exception, typename Accessor>
458{
459 struct BuildParams : IterateFieldsHelper<BuildParams, 0>
460 {
461 template <typename Params, typename ParamList>
465
468 };
469
484};
485
486template <typename Accessor, typename... Types>
488{
489 ClientParam(Types&&... values) : m_values{std::forward<Types>(values)...} {}
490
491 struct BuildParams : IterateFieldsHelper<BuildParams, sizeof...(Types)>
492 {
493 template <typename Params, typename ParamList>
495 {
496 auto const fun = [&]<typename... Values>(Values&&... values) {
499 MaybeBuildField(std::integral_constant<bool, Accessor::in>(), ParamList(), invoke_context,
500 Make<StructField, Accessor>(params), std::forward<Values>(values)...);
501 };
502
503 // Note: The m_values tuple just consists of lvalue and rvalue
504 // references, so calling std::move doesn't change the tuple, it
505 // just causes std::apply to call the std::get overload that returns
506 // && instead of &, so rvalue references are preserved and not
507 // turned into lvalue references. This allows the BuildField call to
508 // move from the argument if it is an rvalue reference or was passed
509 // by value.
510 std::apply(fun, std::move(m_client_param->m_values));
511 }
512
515 };
516
517 struct ReadResults : IterateFieldsHelper<ReadResults, sizeof...(Types)>
518 {
519 template <typename Results, typename... Params>
521 {
522 auto const fun = [&]<typename... Values>(Values&&... values) {
523 MaybeReadField(std::integral_constant<bool, Accessor::out>(), TypeList<Decay<Params>...>(), invoke_context,
525 };
526
527 std::apply(fun, m_client_param->m_values);
528 }
529
532 };
533
534 std::tuple<Types&&...> m_values;
535};
536
537template <typename Accessor, typename... Types>
539{
540 return {std::forward<Types>(values)...};
541}
542
544{
545 // FIXME: maybe call call_context.releaseParams()
546 template <typename ServerContext, typename... Args>
547 decltype(auto) invoke(ServerContext& server_context, TypeList<>, Args&&... args) const
548 {
549 // If cancel_lock is set, release it while executing the method, and
550 // reacquire it afterwards. The lock is needed to prevent params and
551 // response structs from being deleted by the event loop thread if the
552 // request is canceled, so it is only needed before and after method
553 // execution. It is important to release the lock during execution
554 // because the method can take arbitrarily long to return and the event
555 // loop will need the lock itself in on_cancel if the call is canceled.
556 if (server_context.cancel_lock) server_context.cancel_lock->m_lock.unlock();
557 return TryFinally(
558 [&]() -> decltype(auto) {
560 typename decltype(server_context.call_context.getParams())::Reads
561 >::invoke(server_context, std::forward<Args>(args)...);
562 },
563 [&] {
564 if (server_context.cancel_lock) server_context.cancel_lock->m_lock.lock();
565 // If the IPC request was canceled, throw InterruptException
566 // because there is no point continuing and trying to fill the
567 // call_context.getResults() struct. It's also important to stop
568 // executing because the connection may have been destroyed as
569 // described in https://github.com/bitcoin/bitcoin/issues/34250
570 // and there could be invalid references to the destroyed
571 // Connection object if this continued.
572 // If the IPC method itself threw an exception, the
573 // InterruptException thrown below will take precedence over it.
574 // Since the call has been canceled that exception can't be
575 // returned to the caller, so it needs to be discarded like
576 // other result values.
577 if (server_context.request_canceled) throw InterruptException{"canceled"};
578 });
579 }
580};
581
583{
584 template <typename ServerContext, typename... Args>
586 {
587 server_context.proxy_server.invokeDestroy(std::forward<Args>(args)...);
588 }
589};
590
591template <typename Accessor, typename Parent>
592struct ServerRet : Parent
593{
594 ServerRet(Parent parent) : Parent(parent) {}
595
596 template <typename ServerContext, typename... Args>
598 {
599 auto&& result = Parent::invoke(server_context, TypeList<>(), std::forward<Args>(args)...);
600 auto&& results = server_context.call_context.getResults();
603 std::forward<decltype(result)>(result));
604 }
605};
606
607template <typename Exception, typename Accessor, typename Parent>
608struct ServerExcept : Parent
609{
610 ServerExcept(Parent parent) : Parent(parent) {}
611
612 template <typename ServerContext, typename... Args>
614 {
615 try {
616 return Parent::invoke(server_context, TypeList<>(), std::forward<Args>(args)...);
617 } catch (const Exception& exception) {
618 auto&& results = server_context.call_context.getResults();
620 }
621 }
622};
623
626template <typename Accessor, typename Message>
627decltype(auto) MaybeGet(Message&& message)
628 requires requires { Accessor::get(message); }
629{
630 return Accessor::get(message);
631}
632
633template <typename Accessor>
634::capnp::Void MaybeGet(...)
635{
636 return {};
637}
638
639template <class Accessor>
641
652template <typename Accessor, typename... Args>
653auto PassField(Priority<2>, Args&&... args) -> decltype(CustomPassField<Accessor>(std::forward<Args>(args)...))
654{
655 return CustomPassField<Accessor>(std::forward<Args>(args)...);
656}
657
658template <int argc, typename Accessor, typename Parent>
659struct ServerField : Parent
660{
661 ServerField(Parent parent) : Parent(parent) {}
662
663 const Parent& parent() const { return *this; }
664
665 template <typename ServerContext, typename ArgTypes, typename... Args>
666 decltype(auto) invoke(ServerContext& server_context, ArgTypes, Args&&... args) const
667 {
671 this->parent(),
673 std::forward<Args>(args)...);
674 }
675};
676
677template <int argc, typename Accessor, typename Parent>
679{
680 return {parent};
681}
682
683template <typename Request>
685
686template <typename _Params, typename _Results>
687struct CapRequestTraits<::capnp::Request<_Params, _Results>>
688{
691};
692
696template <typename Client>
698{
699 MP_LOG(*client.m_context.loop, Log::Debug) << "IPC client destroy " << CxxTypeName(client);
700}
701
702template <typename Server>
703void serverDestroy(Server& server)
704{
705 MP_LOG(*server.m_context.loop, Log::Debug) << "IPC server destroy " << CxxTypeName(server);
706}
707
717template <typename ProxyClient, typename GetRequest, typename... FieldObjs>
718void clientInvoke(ProxyClient& proxy_client, const GetRequest& get_request, FieldObjs&&... fields)
719{
720 if (!CurrentThread().waiter) {
721 assert(CurrentThread().thread_name.empty());
722 CurrentThread().thread_name = ThreadName(proxy_client.m_context.loop->m_exe_name);
723 // If next assert triggers, it means clientInvoke is being called from
724 // the capnp event loop thread. This can happen when a ProxyServer
725 // method implementation that runs synchronously on the event loop
726 // thread tries to make a blocking callback to the client. Any server
727 // method that makes a blocking callback or blocks in general needs to
728 // run asynchronously off the event loop thread. This is easy to fix by
729 // just adding a 'context :Proxy.Context' argument to the capnp method
730 // declaration so the server method runs in a dedicated thread.
731 assert(!CurrentThread().loop_thread);
732 CurrentThread().waiter = std::make_unique<Waiter>();
733 MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Info)
734 << "{" << CurrentThread().thread_name
735 << "} IPC client first request from current thread, constructing waiter";
736 }
737 ThreadContext& thread_context{CurrentThread()};
738 std::optional<ClientInvokeContext> invoke_context; // Must outlive waiter->wait() call below
739 std::exception_ptr exception;
740 std::string kj_exception;
741 bool done = false;
742 const char* disconnected = nullptr;
743 proxy_client.m_context.loop->sync([&]() {
744 if (!proxy_client.m_context.connection) {
745 const Lock lock(thread_context.waiter->m_mutex);
746 done = true;
747 disconnected = "IPC client method called after disconnect.";
748 thread_context.waiter->m_cv.notify_all();
749 return;
750 }
751
752 auto request = (proxy_client.m_client.*get_request)(nullptr);
753 using Request = CapRequestTraits<decltype(request)>;
755 invoke_context.emplace(*proxy_client.m_context.connection, thread_context);
756 IterateFields().handleChain(*invoke_context, request, FieldList(), typename FieldObjs::BuildParams{&fields}...);
757 MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Debug)
758 << "{" << thread_context.thread_name << "} IPC client send "
760 MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Trace)
761 << "send data: " << LogEscape(request.toString(), proxy_client.m_context.loop->m_log_opts.max_chars);
762
763 proxy_client.m_context.loop->m_task_set->add(request.send().then(
764 [&](::capnp::Response<typename Request::Results>&& response) {
765 MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Debug)
766 << "{" << thread_context.thread_name << "} IPC client recv "
767 << TypeName<typename Request::Results>();
768 MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Trace)
769 << "recv data: " << LogEscape(response.toString(), proxy_client.m_context.loop->m_log_opts.max_chars);
770 try {
771 IterateFields().handleChain(
772 *invoke_context, response, FieldList(), typename FieldObjs::ReadResults{&fields}...);
773 } catch (...) {
774 exception = std::current_exception();
775 }
776 const Lock lock(thread_context.waiter->m_mutex);
777 done = true;
778 thread_context.waiter->m_cv.notify_all();
779 },
780 [&](const ::kj::Exception& e) {
781 if (e.getType() == ::kj::Exception::Type::DISCONNECTED) {
782 disconnected = "IPC client method call interrupted by disconnect.";
783 } else {
784 kj_exception = kj::str("kj::Exception: ", e).cStr();
785 MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Info)
786 << "{" << thread_context.thread_name << "} IPC client exception " << kj_exception;
787 }
788 const Lock lock(thread_context.waiter->m_mutex);
789 done = true;
790 thread_context.waiter->m_cv.notify_all();
791 }));
792 });
793
794 Lock lock(thread_context.waiter->m_mutex);
795 thread_context.waiter->wait(lock, [&done]() { return done; });
796 if (exception) std::rethrow_exception(exception);
797 if (!kj_exception.empty()) MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Raise) << kj_exception;
798 if (disconnected) MP_LOGPLAIN(*proxy_client.m_context.loop, Log::Raise) << disconnected;
799}
800
804template <typename Fn, typename Ret>
805auto ReplaceVoid(Fn&& fn, Ret&& ret)
806{
807 if constexpr (std::is_same_v<decltype(fn()), void>) {
808 fn();
809 return ret();
810 } else {
811 return fn();
812 }
813}
814
815extern std::atomic<int> server_reqs;
816
824template <typename Server, typename CallContext, typename Fn>
825kj::Promise<void> serverInvoke(Server& server, CallContext& call_context, Fn fn)
826{
827 auto params = call_context.getParams();
828 using Params = decltype(params);
829 using Results = typename decltype(call_context.getResults())::Builds;
830
831 EventLoop& loop = *server.m_context.loop;
832 int req = ++server_reqs;
833 MP_LOG(loop, Log::Debug) << "IPC server recv request #" << req << " "
835 MP_LOG(loop, Log::Trace) << "request data: "
836 << LogEscape(params.toString(), server.m_context.loop->m_log_opts.max_chars);
837
838 try {
841 ServerContext server_context{server, call_context, req};
842 // ReplaceVoid is used to support fn.invoke implementations that
843 // execute asynchronously and return promises, as well as
844 // implementations that execute synchronously and return void. The
845 // invoke function will be synchronous by default, but asynchronous if
846 // an mp.Context argument is passed, and the mp.Context PassField
847 // overload returns a promise executing the request in a worker thread
848 // and waiting for it to complete.
849 return ReplaceVoid([&]() { return fn.invoke(server_context, ArgList()); },
850 [&]() { return kj::Promise<CallContext>(kj::mv(call_context)); })
851 .then([&loop, req](CallContext call_context) {
852 MP_LOG(loop, Log::Debug) << "IPC server send response #" << req << " " << TypeName<Results>();
853 MP_LOG(loop, Log::Trace) << "response data: "
854 << LogEscape(call_context.getResults().toString(), loop.m_log_opts.max_chars);
855 }).catch_([&loop, req](::kj::Exception&& e) -> kj::Promise<void> {
856 // Call failed for some reason. Cap'n Proto will try to send
857 // this error to the client as well, but it is good to log the
858 // failure early here and include the request number.
859 MP_LOG(loop, Log::Error) << "IPC server error request #" << req << " " << TypeName<Results>()
860 << " " << kj::str("kj::Exception: ", e.getDescription()).cStr();
861 return kj::mv(e);
862 });
863 } catch (const std::exception& e) {
864 MP_LOG(loop, Log::Error) << "IPC server unhandled exception: " << e.what();
865 throw;
866 } catch (...) {
867 MP_LOG(loop, Log::Error) << "IPC server unhandled exception";
868 throw;
869 }
870}
871
875 template<typename Interface>
877 types().emplace(typeid(Interface), [](void* iface) -> ProxyContext& { return static_cast<typename mp::ProxyType<Interface>::Client&>(*static_cast<Interface*>(iface)).m_context; });
878 }
879 using Types = std::map<std::type_index, ProxyContext&(*)(void*)>;
880 static Types& types() { static Types types; return types; }
881};
882
883} // namespace mp
884
885#endif // MP_PROXY_TYPES_H
int ret
catch(const std::exception &e)
ArgsManager & args
Definition bitcoind.cpp:280
const CChainParams & Params()
Return the currently selected parameters.
Event loop implementation.
Definition proxy-io.h:248
LogOptions m_log_opts
Logging options.
Definition proxy-io.h:350
void * m_context
External context pointer.
Definition proxy-io.h:353
Value & get()
Definition proxy-types.h:33
Value & init()
Definition proxy-types.h:34
const Value & get() const
Definition proxy-types.h:32
ValueField(Value &&value)
Definition proxy-types.h:29
ValueField(Value &value)
Definition proxy-types.h:28
Value & m_value
Definition proxy-types.h:30
bool has() const
Definition proxy-types.h:35
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
std::unique_ptr< ProxyClient< messages::FooInterface > > client
Definition basic.cpp:11
Functions to serialize / deserialize common bitcoin types.
void MaybeBuildField(std::true_type, Args &&... args)
void clientDestroy(Client &client)
Entry point called by all generated ProxyClient destructors.
std::string CxxTypeName(const T &)
Definition util.h:344
void clientInvoke(ProxyClient &proxy_client, const GetRequest &get_request, FieldObjs &&... fields)
Entry point called by generated client code that looks like:
void BuildList(TypeList< LocalType >, InvokeContext &invoke_context, Output &&output, Value &&value)
void CustomPassField()
ClientParam< Accessor, Types... > MakeClientParam(Types &&... values)
decltype(auto) MaybeGet(Message &&message)
Helper for CustomPassField below.
void MaybeReadField(std::true_type, Args &&... args)
decltype(auto) TryFinally(Fn &&fn, After &&after)
Invoke a function and run a follow-up action before returning the original result.
Definition util.h:260
kj::Promise< void > serverInvoke(Server &server, CallContext &call_context, Fn fn)
Entry point called by generated server code that looks like:
bool CustomHasValue(InvokeContext &, const Values &...)
Return whether to write a C++ value into a Cap'n Proto field.
ThreadContext & CurrentThread()
Return the current thread's ThreadContext.
Definition proxy.cpp:45
void BuildField(TypeList< LocalTypes... >, Context &context, Output &&output, Values &&... values)
auto PassField(Priority< 1 >, TypeList< LocalType & >, ServerContext &server_context, Fn &&fn, Args &&... args) -> Require< typename decltype(Accessor::get(server_context.call_context.getParams()))::Calls >
PassField override for callable interface reference arguments.
std::string ThreadName(const char *exe_name)
Format current thread name as "{exe_name}-{$pid}/{thread_name}-{$tid}".
Definition util.cpp:197
decltype(auto) CustomReadField(TypeList< LocalType >, Priority< 1 >, InvokeContext &invoke_context, Input &&input, ReadDest &&read_dest)
Overload multiprocess library's CustomReadField hook to allow any object with an Unserialize method t...
typename _Require< SfinaeExpr, Result >::Result Require
SFINAE helper, basically the same as to C++17's void_t, but allowing types other than void to be retu...
Definition util.h:131
std::atomic< int > server_reqs
Definition proxy.cpp:524
void ThrowField(TypeList< LocalType >, InvokeContext &invoke_context, Input &&input)
LocalType BuildPrimitive(InvokeContext &, const Value &value, TypeList< LocalType >)
Definition type-number.h:14
ServerInvokeContext< ProxyServer< Interface >, ::capnp::CallContext< Params, Results > > ServerContext
Definition proxy-io.h:78
void MaybeSetWant(TypeList< LocalType * >, Priority< 1 >, const Value &value, Output &&output)
void serverDestroy(Server &server)
std::decay_t< T > Decay
Type helper abbreviating std::decay.
Definition util.h:110
auto ReadDestTemp()
Helper function to create a ReadDestEmplace object that constructs a temporary, ReadField can return.
std::remove_cv_t< std::remove_reference_t< T > > RemoveCvRef
Substitutue for std::remove_cvref_t.
Definition util.h:106
decltype(auto) ReadField(TypeList< LocalTypes... >, InvokeContext &invoke_context, Input &&input, Args &&... args)
char * CharCast(char *c)
Definition util.h:326
auto ReplaceVoid(Fn &&fn, Ret &&ret)
Invoke callable fn() that may return void.
decltype(auto) ReadList(TypeList< LocalType >, InvokeContext &invoke_context, Input &&input, ReadDest &&read_dest, InitFn &&init, EmplaceFn &&emplace)
void CustomBuildField(TypeList< LocalType >, Priority< 1 >, InvokeContext &invoke_context, Value &&value, Output &&output)
Overload multiprocess library's CustomBuildField hook to allow any serializable object to be stored i...
ServerField< argc, Accessor, Parent > MakeServerField(Parent parent)
std::string LogEscape(const kj::StringTree &string, size_t max_size)
Escape binary string for use in log so it doesn't trigger unicode decode errors in python unit tests.
Definition util.cpp:228
bool CustomHasField(TypeList< CTransaction >, InvokeContext &invoke_context, const Input &input)
Interpret empty Data fields as null CTransactionRef values.
#define S(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
#define MP_LOG(loop,...)
Definition proxy-io.h:215
#define MP_LOGPLAIN(loop,...)
Definition proxy-io.h:213
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Accessor type holding flags that determine how to access a message field.
Definition proxy.h:318
static constexpr bool boxed
Field is a Cap'n Proto pointer type (struct, list, text, data, interface) as opposed to a primitive t...
Definition proxy.h:334
static constexpr bool in
Field is present from the Cap'n Proto Params struct (client -> server).
Definition proxy.h:320
static constexpr bool optional
Field has a companion has{Name} boolean field in the Cap'n Proto struct.
Definition proxy.h:327
static constexpr bool requested
Results field has a companion want{Name} boolean field in the Params struct.
Definition proxy.h:331
void handleField(InvokeContext &, Params &, ParamList)
ClientException * m_client_exception
BuildParams(ClientException *client_exception)
void handleField(InvokeContext &invoke_context, Results &results, ParamList)
ReadResults(ClientException *client_exception)
ClientException * m_client_exception
void handleField(ClientInvokeContext &invoke_context, Params &params, ParamList)
BuildParams(ClientParam *client_param)
ReadResults(ClientParam *client_param)
void handleField(ClientInvokeContext &invoke_context, Results &results, TypeList< Params... >)
ClientParam(Types &&... values)
std::tuple< Types &&... > m_values
Exception thrown from code executing an IPC call that is interrupted.
Definition util.h:354
void handleChain(Arg1 &arg1, Arg2 &arg2, ParamList)
void handleChain(Arg1 &arg1, Arg2 &arg2, ParamList, NextFn &&next_fn, NextFnArgs &&... next_fn_args)
void handleField(Arg1 &&, Arg2 &&, ParamList)
decltype(auto) set(Arg &&arg) const
decltype(auto) init(Arg &&arg) const
typename ::capnp::List< T, kind >::Builder Builder
ListOutput(Builder &builder, size_t index)
size_t max_chars
Maximum number of characters to use when representing request and response structs as strings.
Definition proxy-io.h:162
Function parameter type for prioritizing overloaded function calls that would otherwise be ambiguous.
Definition util.h:143
Mapping from capnp interface type to proxy client implementation (specializations are generated by pr...
Definition proxy.h:25
Context data associated with proxy client and server classes.
Definition proxy.h:71
Customizable (through template specialization) traits class used in generated ProxyServer implementat...
Definition proxy.h:306
Mapping from local c++ type to capnp type and traits (specializations are generated by proxy-codegen....
Definition proxy.h:34
Map to convert client interface pointers to ProxyContext struct references at runtime using typeids.
static Types & types()
ProxyTypeRegister(TypeList< Interface >)
std::map< std::type_index, ProxyContext &(*)(void *)> Types
decltype(auto) construct(Args &&... args)
Simple case.
ReadDestEmplace(TypeList< LocalType >, EmplaceFn emplace_fn)
decltype(auto) update(UpdateFn &&update_fn)
More complicated case.
Destination parameter type that can be passed to ReadField function as an alternative to ReadDestEmpl...
Value & update(UpdateFn &&update_fn)
Simple case. If ReadField works by calling update() just forward arguments to update_fn.
Value & construct(Args &&... args)
More complicated case.
ReadDestUpdate(Value &value)
decltype(auto) invoke(ServerContext &server_context, TypeList<>, Args &&... args) const
void invoke(ServerContext &server_context, TypeList<>, Args &&... args) const
ServerExcept(Parent parent)
void invoke(ServerContext &server_context, TypeList<>, Args &&... args) const
ServerField(Parent parent)
decltype(auto) invoke(ServerContext &server_context, ArgTypes, Args &&... args) const
const Parent & parent() const
void invoke(ServerContext &server_context, TypeList<>, Args &&... args) const
ServerRet(Parent parent)
Type helper splitting a TypeList into two halves at position index.
Definition util.h:81
StructField(S &struct_)
Definition proxy-types.h:42
void setWant() const
Definition proxy-types.h:81
decltype(auto) set(Args &&...args) const
Definition proxy-types.h:67
decltype(auto) init(Args &&...args) const
Definition proxy-types.h:71
bool want() const
Definition proxy-types.h:59
Struct & m_struct
Definition proxy-types.h:45
decltype(auto) get() const
Definition proxy-types.h:47
bool has() const
Definition proxy-types.h:49
void setHas() const
Definition proxy-types.h:75
The thread_local ThreadContext struct (see CurrentThread()) provides information about individual thr...
Definition proxy-io.h:737
std::unique_ptr< Waiter > waiter
Waiter object used to allow remote clients to execute code on this thread.
Definition proxy-io.h:756
std::string thread_name
Identifying string for debug.
Definition proxy-io.h:739
Type holding a list of types.
Definition util.h:57
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
#define B
assert(!tx.IsCoinBase())
WalletContext context