5#ifndef MP_PROXY_TYPES_H
6#define MP_PROXY_TYPES_H
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)"
24template <
typename Value>
35 bool has()
const {
return true; }
38template <
typename Accessor,
typename Struct>
47 decltype(
auto)
get()
const {
return Accessor::get(this->m_struct); }
67 template <
typename... Args>
decltype(
auto)
set(Args &&...
args)
const {
68 return Accessor::set(this->m_struct, std::forward<Args>(
args)...);
71 template <
typename... Args>
decltype(
auto)
init(Args &&...
args)
const {
72 return Accessor::init(this->m_struct, std::forward<Args>(
args)...);
99template <
typename LocalType,
typename EmplaceFn>
106 template <
typename... Args>
116 template <
typename UpdateFn>
119 if constexpr (std::is_const_v<std::remove_reference_t<std::invoke_result_t<EmplaceFn>>>) {
123 std::remove_cv_t<LocalType>
temp;
138template <
typename LocalType>
150template <
typename Value>
156 template <
typename UpdateFn>
165 template <
typename... Args>
224template <
typename LocalType,
typename Input>
235template <
typename Input>
238 auto data = input.get();
249template <
typename...
Values>
260 std::forward<Output>(output));
269template <
typename ListType>
272template <
typename T, ::capnp::Kind kind>
275 using Builder = typename ::capnp::List<T, kind>::Builder;
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)); }
289template <
typename LocalType,
typename Value,
typename Output>
292 auto list = output.init(value.size());
310 for (
auto it = value.begin(); it != value.end(); ++it, ++i) {
311 if constexpr (std::is_lvalue_reference_v<Value&&>) {
319template <
typename LocalType,
typename Input,
typename ReadDest,
typename InitFn,
typename EmplaceFn>
322 return read_dest.update([&](
auto& value) {
323 auto data = input.get();
328 return emplace(value, std::forward<
decltype(
args)>(
args)...);
334template <
typename LocalType,
typename Value,
typename Output>
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);
358template <
typename... Args>
363template <
typename... Args>
367template <
typename... Args>
372template <
typename... Args>
377template <
typename LocalType,
typename Value,
typename Output>
385template <
typename LocalTypes,
typename... Args>
396 std::optional<ArgType> param;
400 param.emplace(std::forward<
decltype(
args)>(
args)...);
406 if (!param) param.emplace();
415template <
typename Accessor,
typename ServerContext,
typename Fn,
typename... Args>
426template <
typename Derived,
size_t N = 0>
438 template <
typename Arg1,
typename Arg2,
typename ParamList>
450 template <
typename Arg1,
typename Arg2,
typename ParamList>
456template <
typename Exception,
typename Accessor>
461 template <
typename Params,
typename ParamList>
472 template <
typename Results,
typename ParamList>
486template <
typename Accessor,
typename... Types>
493 template <
typename Params,
typename ParamList>
519 template <
typename Results,
typename...
Params>
537template <
typename Accessor,
typename... Types>
540 return {std::forward<Types>(
values)...};
558 [&]() ->
decltype(
auto) {
591template <
typename Accessor,
typename Parent>
603 std::forward<
decltype(result)>(result));
607template <
typename Exception,
typename Accessor,
typename Parent>
617 }
catch (
const Exception& exception) {
626template <
typename Accessor,
typename Message>
628 requires requires { Accessor::get(message); }
630 return Accessor::get(message);
633template <
typename Accessor>
639template <
class Accessor>
652template <
typename Accessor,
typename... Args>
658template <
int argc,
typename Accessor,
typename Parent>
663 const Parent&
parent()
const {
return *
this; }
673 std::forward<Args>(
args)...);
677template <
int argc,
typename Accessor,
typename Parent>
683template <
typename Request>
686template <
typename _Params,
typename _Results>
696template <
typename Client>
702template <
typename Server>
717template <
typename ProxyClient,
typename GetRequest,
typename...
FieldObjs>
735 <<
"} IPC client first request from current thread, constructing waiter";
739 std::exception_ptr exception;
742 const char* disconnected =
nullptr;
745 const Lock lock(thread_context.waiter->m_mutex);
747 disconnected =
"IPC client method called after disconnect.";
748 thread_context.waiter->m_cv.notify_all();
758 <<
"{" << thread_context.thread_name <<
"} IPC client send "
761 <<
"send data: " <<
LogEscape(request.toString(),
proxy_client.m_context.loop->m_log_opts.max_chars);
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);
771 IterateFields().handleChain(
772 *invoke_context, response, FieldList(), typename FieldObjs::ReadResults{&fields}...);
774 exception = std::current_exception();
776 const Lock lock(thread_context.waiter->m_mutex);
778 thread_context.waiter->m_cv.notify_all();
780 [&](const ::kj::Exception&
e) {
781 if (
e.getType() == ::kj::Exception::Type::DISCONNECTED) {
782 disconnected =
"IPC client method call interrupted by disconnect.";
786 <<
"{" << thread_context.thread_name <<
"} IPC client exception " <<
kj_exception;
788 const Lock lock(thread_context.waiter->m_mutex);
790 thread_context.waiter->m_cv.notify_all();
794 Lock lock(thread_context.waiter->m_mutex);
795 thread_context.waiter->wait(lock, [&done]() {
return done; });
796 if (exception) std::rethrow_exception(exception);
804template <
typename Fn,
typename Ret>
807 if constexpr (std::is_same_v<
decltype(fn()),
void>) {
815extern std::atomic<int> server_reqs;
824template <
typename Server,
typename CallContext,
typename Fn>
825kj::Promise<void>
serverInvoke(Server& server, CallContext& call_context, Fn fn)
827 auto params = call_context.getParams();
828 using Params =
decltype(params);
829 using Results =
typename decltype(call_context.getResults())
::Builds;
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);
850 [&]() {
return kj::Promise<CallContext>(kj::mv(call_context)); })
851 .
then([&loop, req](CallContext call_context) {
853 MP_LOG(loop, Log::Trace) <<
"response data: "
855 }).
catch_([&loop, req](::kj::Exception&&
e) -> kj::Promise<void> {
860 <<
" " << kj::str(
"kj::Exception: ",
e.getDescription()).cStr();
863 }
catch (
const std::exception&
e) {
864 MP_LOG(loop, Log::Error) <<
"IPC server unhandled exception: " <<
e.what();
867 MP_LOG(loop, Log::Error) <<
"IPC server unhandled exception";
875 template<
typename Interface>
catch(const std::exception &e)
const CChainParams & Params()
Return the currently selected parameters.
Event loop implementation.
LogOptions m_log_opts
Logging options.
void * m_context
External context pointer.
const Value & get() const
ValueField(Value &&value)
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
std::unique_ptr< ProxyClient< messages::FooInterface > > client
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 &)
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)
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.
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.
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}".
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...
std::atomic< int > server_reqs
void ThrowField(TypeList< LocalType >, InvokeContext &invoke_context, Input &&input)
LocalType BuildPrimitive(InvokeContext &, const Value &value, TypeList< LocalType >)
ServerInvokeContext< ProxyServer< Interface >, ::capnp::CallContext< Params, Results > > ServerContext
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.
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.
decltype(auto) ReadField(TypeList< LocalTypes... >, InvokeContext &invoke_context, Input &&input, Args &&... args)
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.
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_LOGPLAIN(loop,...)
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.
static constexpr bool boxed
Field is a Cap'n Proto pointer type (struct, list, text, data, interface) as opposed to a primitive t...
static constexpr bool in
Field is present from the Cap'n Proto Params struct (client -> server).
static constexpr bool optional
Field has a companion has{Name} boolean field in the Cap'n Proto struct.
static constexpr bool requested
Results field has a companion want{Name} boolean field in the Params struct.
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 ¶ms, ParamList)
BuildParams(ClientParam *client_param)
ClientParam * m_client_param
ClientParam * m_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.
void handleChain(Arg1 &arg1, Arg2 &arg2, ParamList)
void handleChain(Arg1 &arg1, Arg2 &arg2, ParamList, NextFn &&next_fn, NextFnArgs &&... next_fn_args)
IterateFieldsHelper()=default
void handleField(Arg1 &&, Arg2 &&, ParamList)
decltype(auto) set(Arg &&arg) const
decltype(auto) init(Arg &&arg) const
decltype(auto) get() const
decltype(auto) init() 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.
Function parameter type for prioritizing overloaded function calls that would otherwise be ambiguous.
Mapping from capnp interface type to proxy client implementation (specializations are generated by pr...
Context data associated with proxy client and server classes.
Customizable (through template specialization) traits class used in generated ProxyServer implementat...
Mapping from local c++ type to capnp type and traits (specializations are generated by proxy-codegen....
Map to convert client interface pointers to ProxyContext struct references at runtime using typeids.
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
Type helper splitting a TypeList into two halves at position index.
decltype(auto) set(Args &&...args) const
decltype(auto) init(Args &&...args) const
decltype(auto) get() const
The thread_local ThreadContext struct (see CurrentThread()) provides information about individual thr...
std::unique_ptr< Waiter > waiter
Waiter object used to allow remote clients to execute code on this thread.
std::string thread_name
Identifying string for debug.
Type holding a list of types.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.