Seastar
High performance C++ framework for concurrent servers
rpc_impl.hh
1 /*
2  * This file is open source software, licensed to you under the terms
3  * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4  * distributed with this work for additional information regarding copyright
5  * ownership. You may not use this file except in compliance with the License.
6  *
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing,
12  * software distributed under the License is distributed on an
13  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14  * KIND, either express or implied. See the License for the
15  * specific language governing permissions and limitations
16  * under the License.
17  */
18 /*
19  * Copyright (C) 2015 Cloudius Systems, Ltd.
20  */
21 #pragma once
22 
23 #include <seastar/core/function_traits.hh>
24 #include <seastar/core/shared_ptr.hh>
25 #include <seastar/core/sstring.hh>
26 #include <seastar/core/when_all.hh>
27 #include <seastar/util/is_smart_ptr.hh>
28 #include <seastar/core/simple-stream.hh>
29 #include <boost/range/numeric.hpp>
30 #include <boost/range/adaptor/transformed.hpp>
31 #include <seastar/net/packet-data-source.hh>
32 #include <seastar/core/print.hh>
33 
34 namespace seastar {
35 
36 namespace rpc {
37 
38 enum class exception_type : uint32_t {
39  USER = 0,
40  UNKNOWN_VERB = 1,
41 };
42 
43 template<typename T>
45  using type = T;
46 };
47 
48 template<typename T>
50  using type = T;
51 };
52 
53 struct wait_type {}; // opposite of no_wait_type
54 
55 // tags to tell whether we want a const client_info& parameter
58 
59 // tags to tell whether we want a opt_time_point parameter
62 
63 // General case
64 template <typename Ret, typename... In>
65 struct signature<Ret (In...)> {
66  using ret_type = Ret;
67  using arg_types = std::tuple<In...>;
68  using clean = signature;
71 };
72 
73 // Specialize 'clean' for handlers that receive client_info
74 template <typename Ret, typename... In>
75 struct signature<Ret (const client_info&, In...)> {
76  using ret_type = Ret;
77  using arg_types = std::tuple<In...>;
78  using clean = signature<Ret (In...)>;
81 };
82 
83 template <typename Ret, typename... In>
84 struct signature<Ret (client_info&, In...)> {
85  using ret_type = Ret;
86  using arg_types = std::tuple<In...>;
87  using clean = signature<Ret (In...)>;
90 };
91 
92 // Specialize 'clean' for handlers that receive client_info and opt_time_point
93 template <typename Ret, typename... In>
94 struct signature<Ret (const client_info&, opt_time_point, In...)> {
95  using ret_type = Ret;
96  using arg_types = std::tuple<In...>;
97  using clean = signature<Ret (In...)>;
100 };
101 
102 template <typename Ret, typename... In>
103 struct signature<Ret (client_info&, opt_time_point, In...)> {
104  using ret_type = Ret;
105  using arg_types = std::tuple<In...>;
106  using clean = signature<Ret (In...)>;
109 };
110 
111 // Specialize 'clean' for handlers that receive opt_time_point
112 template <typename Ret, typename... In>
113 struct signature<Ret (opt_time_point, In...)> {
114  using ret_type = Ret;
115  using arg_types = std::tuple<In...>;
116  using clean = signature<Ret (In...)>;
119 };
120 
121 template <typename T>
123  using type = wait_type;
124  using cleaned_type = T;
125 };
126 
127 template <typename... T>
128 struct wait_signature<future<T...>> {
129  using type = wait_type;
130  using cleaned_type = future<T...>;
131 };
132 
133 template <>
135  using type = no_wait_type;
136  using cleaned_type = void;
137 };
138 
139 template <>
141  using type = no_wait_type;
142  using cleaned_type = future<>;
143 };
144 
145 template <typename T>
146 using wait_signature_t = typename wait_signature<T>::type;
147 
148 template <typename... In>
149 inline
150 std::tuple<In...>
151 maybe_add_client_info(dont_want_client_info, client_info&, std::tuple<In...>&& args) {
152  return std::move(args);
153 }
154 
155 template <typename... In>
156 inline
157 std::tuple<std::reference_wrapper<client_info>, In...>
158 maybe_add_client_info(do_want_client_info, client_info& ci, std::tuple<In...>&& args) {
159  return std::tuple_cat(std::make_tuple(std::ref(ci)), std::move(args));
160 }
161 
162 template <typename... In>
163 inline
164 std::tuple<In...>
165 maybe_add_time_point(dont_want_time_point, opt_time_point&, std::tuple<In...>&& args) {
166  return std::move(args);
167 }
168 
169 template <typename... In>
170 inline
171 std::tuple<opt_time_point, In...>
172 maybe_add_time_point(do_want_time_point, opt_time_point& otp, std::tuple<In...>&& args) {
173  return std::tuple_cat(std::make_tuple(otp), std::move(args));
174 }
175 
176 inline sstring serialize_connection_id(const connection_id& id) {
177  sstring p = uninitialized_string(sizeof(id));
178  auto c = p.data();
179  write_le(c, id.id());
180  return p;
181 }
182 
183 inline connection_id deserialize_connection_id(const sstring& s) {
184  using id_type = decltype(connection_id{0}.id());
185  auto p = s.c_str();
186  auto id = read_le<id_type>(p);
187  return connection_id{id};
188 }
189 
190 template <bool IsSmartPtr>
192 
193 template <>
194 struct serialize_helper<false> {
195  template <typename Serializer, typename Output, typename T>
196  static inline void serialize(Serializer& serializer, Output& out, const T& t) {
197  return write(serializer, out, t);
198  }
199 };
200 
201 template <>
202 struct serialize_helper<true> {
203  template <typename Serializer, typename Output, typename T>
204  static inline void serialize(Serializer& serializer, Output& out, const T& t) {
205  return write(serializer, out, *t);
206  }
207 };
208 
209 template <typename Serializer, typename Output, typename... T>
210 inline void do_marshall(Serializer& serializer, Output& out, const T&... args);
211 
212 template <typename Serializer, typename Output>
213 struct marshall_one {
214  template <typename T> struct helper {
215  static void doit(Serializer& serializer, Output& out, const T& arg) {
216  using serialize_helper_type = serialize_helper<is_smart_ptr<typename std::remove_reference_t<T>>::value>;
217  serialize_helper_type::serialize(serializer, out, arg);
218  }
219  };
220  template<typename T> struct helper<std::reference_wrapper<const T>> {
221  static void doit(Serializer& serializer, Output& out, const std::reference_wrapper<const T>& arg) {
222  helper<T>::doit(serializer, out, arg.get());
223  }
224  };
225  static void put_connection_id(const connection_id& cid, Output& out) {
226  sstring id = serialize_connection_id(cid);
227  out.write(id.c_str(), id.size());
228  }
229  template <typename... T> struct helper<sink<T...>> {
230  static void doit(Serializer&, Output& out, const sink<T...>& arg) {
231  put_connection_id(arg.get_id(), out);
232  }
233  };
234  template <typename... T> struct helper<source<T...>> {
235  static void doit(Serializer&, Output& out, const source<T...>& arg) {
236  put_connection_id(arg.get_id(), out);
237  }
238  };
239  template <typename... T> struct helper<tuple<T...>> {
240  static void doit(Serializer& serializer, Output& out, const tuple<T...>& arg) {
241  auto do_do_marshall = [&serializer, &out] (const auto&... args) {
242  do_marshall(serializer, out, args...);
243  };
244  std::apply(do_do_marshall, arg);
245  }
246  };
247 };
248 
249 template <typename Serializer, typename Output, typename... T>
250 inline void do_marshall(Serializer& serializer, Output& out, const T&... args) {
251  // C++ guarantees that brace-initialization expressions are evaluted in order
252  (void)std::initializer_list<int>{(marshall_one<Serializer, Output>::template helper<T>::doit(serializer, out, args), 1)...};
253 }
254 
255 static inline memory_output_stream<snd_buf::iterator> make_serializer_stream(snd_buf& output) {
256  auto* b = std::get_if<temporary_buffer<char>>(&output.bufs);
257  if (b) {
258  return memory_output_stream<snd_buf::iterator>(memory_output_stream<snd_buf::iterator>::simple(b->get_write(), b->size()));
259  } else {
260  auto& ar = std::get<std::vector<temporary_buffer<char>>>(output.bufs);
261  return memory_output_stream<snd_buf::iterator>(memory_output_stream<snd_buf::iterator>::fragmented(ar.begin(), output.size));
262  }
263 }
264 
265 template <typename Serializer, typename... T>
266 inline snd_buf marshall(Serializer& serializer, size_t head_space, const T&... args) {
267  measuring_output_stream measure;
268  do_marshall(serializer, measure, args...);
269  snd_buf ret(measure.size() + head_space);
270  auto out = make_serializer_stream(ret);
271  out.skip(head_space);
272  do_marshall(serializer, out, args...);
273  return ret;
274 }
275 
276 template <typename Serializer, typename Input, typename... T>
277 std::tuple<T...> do_unmarshall(connection& c, Input& in);
278 
279 template<typename Serializer, typename Input>
281  template<typename T> struct helper {
282  static T doit(connection& c, Input& in) {
283  return read(c.serializer<Serializer>(), in, type<T>());
284  }
285  };
286  template<typename T> struct helper<optional<T>> {
287  static optional<T> doit(connection& c, Input& in) {
288  if (in.size()) {
289  return optional<T>(read(c.serializer<Serializer>(), in, type<typename remove_optional<T>::type>()));
290  } else {
291  return optional<T>();
292  }
293  }
294  };
295  template<typename T> struct helper<std::reference_wrapper<const T>> {
296  static T doit(connection& c, Input& in) {
297  return helper<T>::doit(c, in);
298  }
299  };
300  static connection_id get_connection_id(Input& in) {
301  sstring id = uninitialized_string(sizeof(connection_id));
302  in.read(id.data(), sizeof(connection_id));
303  return deserialize_connection_id(id);
304  }
305  template<typename... T> struct helper<sink<T...>> {
306  static sink<T...> doit(connection& c, Input& in) {
307  return sink<T...>(make_shared<sink_impl<Serializer, T...>>(c.get_stream(get_connection_id(in))));
308  }
309  };
310  template<typename... T> struct helper<source<T...>> {
311  static source<T...> doit(connection& c, Input& in) {
312  return source<T...>(make_shared<source_impl<Serializer, T...>>(c.get_stream(get_connection_id(in))));
313  }
314  };
315  template <typename... T> struct helper<tuple<T...>> {
316  static tuple<T...> doit(connection& c, Input& in) {
317  return do_unmarshall<Serializer, Input, T...>(c, in);
318  }
319  };
320 };
321 
322 template <typename Serializer, typename Input, typename... T>
323 inline std::tuple<T...> do_unmarshall(connection& c, Input& in) {
324  // Argument order processing is unspecified, but we need to deserialize
325  // left-to-right. So we deserialize into something that can be lazily
326  // constructed (and can conditionally destroy itself if we only constructed some
327  // of the arguments).
328  std::tuple<std::optional<T>...> temporary;
329  return std::apply([&] (auto&... args) {
330  // Comma-expression preserves left-to-right order
331  (..., (args = unmarshal_one<Serializer, Input>::template helper<typename std::remove_reference_t<decltype(args)>::value_type>::doit(c, in)));
332  return std::tuple(std::move(*args)...);
333  }, temporary);
334 }
335 
336 template <typename Serializer, typename... T>
337 inline std::tuple<T...> unmarshall(connection& c, rcv_buf input) {
338  auto in = make_deserializer_stream(input);
339  return do_unmarshall<Serializer, decltype(in), T...>(c, in);
340 }
341 
342 inline std::exception_ptr unmarshal_exception(rcv_buf& d) {
343  std::exception_ptr ex;
344  auto data = make_deserializer_stream(d);
345 
346  uint32_t v32;
347  data.read(reinterpret_cast<char*>(&v32), 4);
348  exception_type ex_type = exception_type(le_to_cpu(v32));
349  data.read(reinterpret_cast<char*>(&v32), 4);
350  uint32_t ex_len = le_to_cpu(v32);
351 
352  switch (ex_type) {
353  case exception_type::USER: {
354  std::string s(ex_len, '\0');
355  data.read(&*s.begin(), ex_len);
356  ex = std::make_exception_ptr(remote_verb_error(std::move(s)));
357  break;
358  }
359  case exception_type::UNKNOWN_VERB: {
360  uint64_t v64;
361  data.read(reinterpret_cast<char*>(&v64), 8);
362  ex = std::make_exception_ptr(unknown_verb_error(le_to_cpu(v64)));
363  break;
364  }
365  default:
366  ex = std::make_exception_ptr(unknown_exception_error());
367  break;
368  }
369  return ex;
370 }
371 
372 template <typename Payload, typename... T>
374  bool done = false;
375  promise<T...> p;
376  template<typename... V>
377  void set_value(V&&... v) {
378  done = true;
379  p.set_value(internal::untuple(std::forward<V>(v))...);
380  }
381  ~rcv_reply_base() {
382  if (!done) {
383  p.set_exception(closed_error());
384  }
385  }
386 };
387 
388 template<typename Serializer, typename T>
389 struct rcv_reply : rcv_reply_base<T, T> {
390  inline void get_reply(rpc::client& dst, rcv_buf input) {
391  this->set_value(unmarshall<Serializer, T>(dst, std::move(input)));
392  }
393 };
394 
395 template<typename Serializer, typename... T>
396 struct rcv_reply<Serializer, future<T...>> : rcv_reply_base<std::tuple<T...>, T...> {
397  inline void get_reply(rpc::client& dst, rcv_buf input) {
398  this->set_value(unmarshall<Serializer, T...>(dst, std::move(input)));
399  }
400 };
401 
402 template<typename Serializer>
403 struct rcv_reply<Serializer, void> : rcv_reply_base<void, void> {
404  inline void get_reply(rpc::client&, rcv_buf) {
405  this->set_value();
406  }
407 };
408 
409 template<typename Serializer>
410 struct rcv_reply<Serializer, future<>> : rcv_reply<Serializer, void> {};
411 
412 template <typename Serializer, typename Ret, typename... InArgs>
413 inline auto wait_for_reply(wait_type, std::optional<rpc_clock_type::time_point> timeout, cancellable* cancel, rpc::client& dst, id_type msg_id,
414  signature<Ret (InArgs...)>) {
415  using reply_type = rcv_reply<Serializer, Ret>;
416  auto lambda = [] (reply_type& r, rpc::client& dst, id_type msg_id, rcv_buf data) mutable {
417  if (msg_id >= 0) {
418  dst.get_stats_internal().replied++;
419  return r.get_reply(dst, std::move(data));
420  } else {
421  dst.get_stats_internal().exception_received++;
422  r.done = true;
423  r.p.set_exception(unmarshal_exception(data));
424  }
425  };
426  using handler_type = typename rpc::client::template reply_handler<reply_type, decltype(lambda)>;
427  auto r = std::make_unique<handler_type>(std::move(lambda));
428  auto fut = r->reply.p.get_future();
429  dst.wait_for_reply(msg_id, std::move(r), timeout, cancel);
430  return fut;
431 }
432 
433 template<typename Serializer, typename... InArgs>
434 inline auto wait_for_reply(no_wait_type, std::optional<rpc_clock_type::time_point>, cancellable*, rpc::client&, id_type,
435  signature<no_wait_type (InArgs...)>) { // no_wait overload
436  return make_ready_future<>();
437 }
438 
439 template<typename Serializer, typename... InArgs>
440 inline auto wait_for_reply(no_wait_type, std::optional<rpc_clock_type::time_point>, cancellable*, rpc::client&, id_type,
441  signature<future<no_wait_type> (InArgs...)>) { // future<no_wait> overload
442  return make_ready_future<>();
443 }
444 
445 // Convert a relative timeout (a duration) to an absolute one (time_point).
446 // Do the calculation safely so that a very large duration will be capped by
447 // time_point::max, instead of wrapping around to ancient history.
448 inline rpc_clock_type::time_point
449 relative_timeout_to_absolute(rpc_clock_type::duration relative) {
450  rpc_clock_type::time_point now = rpc_clock_type::now();
451  return now + std::min(relative, rpc_clock_type::time_point::max() - now);
452 }
453 
454 // Refer to struct request_frame for more details
455 static constexpr size_t request_frame_headroom = 28;
456 
457 // Returns lambda that can be used to send rpc messages.
458 // The lambda gets client connection and rpc parameters as arguments, marshalls them sends
459 // to a server and waits for a reply. After receiving reply it unmarshalls it and signal completion
460 // to a caller.
461 template<typename Serializer, typename MsgType, typename Ret, typename... InArgs>
462 auto send_helper(MsgType xt, signature<Ret (InArgs...)> xsig) {
463  struct shelper {
464  MsgType t;
465  signature<Ret (InArgs...)> sig;
466  auto send(rpc::client& dst, std::optional<rpc_clock_type::time_point> timeout, cancellable* cancel, const InArgs&... args) {
467  if (dst.error()) {
468  using cleaned_ret_type = typename wait_signature<Ret>::cleaned_type;
469  return futurize<cleaned_ret_type>::make_exception_future(closed_error());
470  }
471 
472  // send message
473  auto msg_id = dst.next_message_id();
474  snd_buf data = marshall(dst.template serializer<Serializer>(), request_frame_headroom, args...);
475 
476  // prepare reply handler, if return type is now_wait_type this does nothing, since no reply will be sent
477  using wait = wait_signature_t<Ret>;
478  return when_all(dst.request(uint64_t(t), msg_id, std::move(data), timeout, cancel), wait_for_reply<Serializer>(wait(), timeout, cancel, dst, msg_id, sig)).then([] (auto r) {
479  std::get<0>(r).ignore_ready_future();
480  return std::move(std::get<1>(r)); // return future of wait_for_reply
481  });
482  }
483  auto operator()(rpc::client& dst, const InArgs&... args) {
484  return send(dst, {}, nullptr, args...);
485  }
486  auto operator()(rpc::client& dst, rpc_clock_type::time_point timeout, const InArgs&... args) {
487  return send(dst, timeout, nullptr, args...);
488  }
489  auto operator()(rpc::client& dst, rpc_clock_type::duration timeout, const InArgs&... args) {
490  return send(dst, relative_timeout_to_absolute(timeout), nullptr, args...);
491  }
492  auto operator()(rpc::client& dst, cancellable& cancel, const InArgs&... args) {
493  return send(dst, {}, &cancel, args...);
494  }
495 
496  };
497  return shelper{xt, xsig};
498 }
499 
500 // Refer to struct response_frame for more details
501 static constexpr size_t response_frame_headroom = 12;
502 
503 template<typename Serializer, typename RetTypes>
504 inline future<> reply(wait_type, future<RetTypes>&& ret, int64_t msg_id, shared_ptr<server::connection> client,
505  std::optional<rpc_clock_type::time_point> timeout) {
506  if (!client->error()) {
507  snd_buf data;
508  try {
509  if constexpr (std::is_void_v<RetTypes>) {
510  ret.get();
511  data = std::invoke(marshall<Serializer>, std::ref(client->template serializer<Serializer>()), response_frame_headroom);
512  } else {
513  data = std::invoke(marshall<Serializer, const RetTypes&>, std::ref(client->template serializer<Serializer>()), response_frame_headroom, std::move(ret.get0()));
514  }
515  } catch (std::exception& ex) {
516  uint32_t len = std::strlen(ex.what());
517  data = snd_buf(response_frame_headroom + 2 * sizeof(uint32_t) + len);
518  auto os = make_serializer_stream(data);
519  os.skip(response_frame_headroom);
520  uint32_t v32 = cpu_to_le(uint32_t(exception_type::USER));
521  os.write(reinterpret_cast<char*>(&v32), sizeof(v32));
522  v32 = cpu_to_le(len);
523  os.write(reinterpret_cast<char*>(&v32), sizeof(v32));
524  os.write(ex.what(), len);
525  msg_id = -msg_id;
526  }
527 
528  return client->respond(msg_id, std::move(data), timeout);
529  } else {
530  ret.ignore_ready_future();
531  return make_ready_future<>();
532  }
533 }
534 
535 // specialization for no_wait_type which does not send a reply
536 template<typename Serializer>
537 inline future<> reply(no_wait_type, future<no_wait_type>&& r, int64_t msgid, shared_ptr<server::connection> client, std::optional<rpc_clock_type::time_point>) {
538  try {
539  r.get();
540  } catch (std::exception& ex) {
541  client->get_logger()(client->info(), msgid, to_sstring("exception \"") + ex.what() + "\" in no_wait handler ignored");
542  }
543  return make_ready_future<>();
544 }
545 
546 template<typename Ret, typename... InArgs, typename WantClientInfo, typename WantTimePoint, typename Func, typename ArgsTuple>
547 inline futurize_t<Ret> apply(Func& func, client_info& info, opt_time_point time_point, WantClientInfo wci, WantTimePoint wtp, signature<Ret (InArgs...)>, ArgsTuple&& args) {
548  using futurator = futurize<Ret>;
549  return futurator::apply(func, maybe_add_client_info(wci, info, maybe_add_time_point(wtp, time_point, std::forward<ArgsTuple>(args))));
550 }
551 
552 // lref_to_cref is a helper that encapsulates lvalue reference in std::ref() or does nothing otherwise
553 template<typename T>
554 auto lref_to_cref(T&& x) {
555  return std::move(x);
556 }
557 
558 template<typename T>
559 auto lref_to_cref(T& x) {
560  return std::ref(x);
561 }
562 
563 // Creates lambda to handle RPC message on a server.
564 // The lambda unmarshalls all parameters, calls a handler, marshall return values and sends them back to a client
565 template <typename Serializer, typename Func, typename Ret, typename... InArgs, typename WantClientInfo, typename WantTimePoint>
566 auto recv_helper(signature<Ret (InArgs...)> sig, Func&& func, WantClientInfo, WantTimePoint) {
567  using signature = decltype(sig);
568  using wait_style = wait_signature_t<Ret>;
569  return [func = lref_to_cref(std::forward<Func>(func))](shared_ptr<server::connection> client,
570  std::optional<rpc_clock_type::time_point> timeout,
571  int64_t msg_id,
572  rcv_buf data) mutable {
573  auto memory_consumed = client->estimate_request_size(data.size);
574  if (memory_consumed > client->max_request_size()) {
575  auto err = format("request size {:d} large than memory limit {:d}", memory_consumed, client->max_request_size());
576  client->get_logger()(client->peer_address(), err);
577  // FIXME: future is discarded
578  (void)try_with_gate(client->get_server().reply_gate(), [client, timeout, msg_id, err = std::move(err)] {
579  return reply<Serializer>(wait_style(), futurize<Ret>::make_exception_future(std::runtime_error(err.c_str())), msg_id, client, timeout).handle_exception([client, msg_id] (std::exception_ptr eptr) {
580  client->get_logger()(client->info(), msg_id, format("got exception while processing an oversized message: {}", eptr));
581  });
582  }).handle_exception_type([] (gate_closed_exception&) {/* ignore */});
583  return make_ready_future();
584  }
585  // note: apply is executed asynchronously with regards to networking so we cannot chain futures here by doing "return apply()"
586  auto f = client->wait_for_resources(memory_consumed, timeout).then([client, timeout, msg_id, data = std::move(data), &func] (auto permit) mutable {
587  // FIXME: future is discarded
588  (void)try_with_gate(client->get_server().reply_gate(), [client, timeout, msg_id, data = std::move(data), permit = std::move(permit), &func] () mutable {
589  try {
590  auto args = unmarshall<Serializer, InArgs...>(*client, std::move(data));
591  return apply(func, client->info(), timeout, WantClientInfo(), WantTimePoint(), signature(), std::move(args)).then_wrapped([client, timeout, msg_id, permit = std::move(permit)] (futurize_t<Ret> ret) mutable {
592  return reply<Serializer>(wait_style(), std::move(ret), msg_id, client, timeout).handle_exception([permit = std::move(permit), client, msg_id] (std::exception_ptr eptr) {
593  client->get_logger()(client->info(), msg_id, format("got exception while processing a message: {}", eptr));
594  });
595  });
596  } catch (...) {
597  client->get_logger()(client->info(), msg_id, format("caught exception while processing a message: {}", std::current_exception()));
598  return make_ready_future();
599  }
600  }).handle_exception_type([] (gate_closed_exception&) {/* ignore */});
601  });
602 
603  if (timeout) {
604  f = f.handle_exception_type([] (semaphore_timed_out&) { /* ignore */ });
605  }
606 
607  return f;
608  };
609 }
610 
611 // helper to create copy constructible lambda from non copy constructible one. std::function<> works only with former kind.
612 template<typename Func>
613 auto make_copyable_function(Func&& func, std::enable_if_t<!std::is_copy_constructible_v<std::decay_t<Func>>, void*> = nullptr) {
614  auto p = make_lw_shared<typename std::decay_t<Func>>(std::forward<Func>(func));
615  return [p] (auto&&... args) { return (*p)( std::forward<decltype(args)>(args)... ); };
616 }
617 
618 template<typename Func>
619 auto make_copyable_function(Func&& func, std::enable_if_t<std::is_copy_constructible_v<std::decay_t<Func>>, void*> = nullptr) {
620  return std::forward<Func>(func);
621 }
622 
623 // This class is used to calculate client side rpc function signature.
624 // Return type is converted from a smart pointer to a type it points to.
625 // rpc::optional are converted to non optional type.
626 //
627 // Examples:
628 // std::unique_ptr<int>(int, rpc::optional<long>) -> int(int, long)
629 // double(float) -> double(float)
630 template<typename Ret, typename... In>
632  template<typename T, bool IsSmartPtr>
633  struct drop_smart_ptr_impl;
634  template<typename T>
635  struct drop_smart_ptr_impl<T, true> {
636  using type = typename T::element_type;
637  };
638  template<typename T>
639  struct drop_smart_ptr_impl<T, false> {
640  using type = T;
641  };
642  template<typename T>
643  using drop_smart_ptr = drop_smart_ptr_impl<T, is_smart_ptr<T>::value>;
644 
645  // if return type is smart ptr take a type it points to instead
646  using return_type = typename drop_smart_ptr<Ret>::type;
647 public:
648  using type = return_type(typename remove_optional<In>::type...);
649 };
650 
651 template<typename Serializer, typename MsgType>
652 template<typename Ret, typename... In>
653 auto protocol<Serializer, MsgType>::make_client(signature<Ret(In...)>, MsgType t) {
654  using sig_type = signature<typename client_function_type<Ret, In...>::type>;
655  return send_helper<Serializer>(t, sig_type());
656 }
657 
658 template<typename Serializer, typename MsgType>
659 template<typename Func>
661  return make_client(typename signature<typename function_traits<Func>::signature>::clean(), t);
662 }
663 
664 template<typename Serializer, typename MsgType>
665 template<typename Func>
668  using clean_sig_type = typename sig_type::clean;
669  using want_client_info = typename sig_type::want_client_info;
670  using want_time_point = typename sig_type::want_time_point;
671  auto recv = recv_helper<Serializer>(clean_sig_type(), std::forward<Func>(func),
672  want_client_info(), want_time_point());
673  register_receiver(t, rpc_handler{sg, make_copyable_function(std::move(recv)), {}});
674  return make_client(clean_sig_type(), t);
675 }
676 
677 template<typename Serializer, typename MsgType>
678 template<typename Func>
680  return register_handler(t, scheduling_group(), std::forward<Func>(func));
681 }
682 
683 template<typename Serializer, typename MsgType>
685  auto it = _handlers.find(t);
686  if (it != _handlers.end()) {
687  return it->second.use_gate.close().finally([this, t] {
688  _handlers.erase(t);
689  });
690  }
691  return make_ready_future<>();
692 }
693 
694 template<typename Serializer, typename MsgType>
695 bool protocol<Serializer, MsgType>::has_handler(MsgType msg_id) {
696  auto it = _handlers.find(msg_id);
697  if (it == _handlers.end()) {
698  return false;
699  }
700  return !it->second.use_gate.is_closed();
701 }
702 
703 template<typename Serializer, typename MsgType>
704 rpc_handler* protocol<Serializer, MsgType>::get_handler(uint64_t msg_id) {
705  rpc_handler* h = nullptr;
706  auto it = _handlers.find(MsgType(msg_id));
707  if (it != _handlers.end()) {
708  try {
709  it->second.use_gate.enter();
710  h = &it->second;
711  } catch (gate_closed_exception&) {
712  // unregistered, just ignore
713  }
714  }
715  return h;
716 }
717 
718 template<typename Serializer, typename MsgType>
719 void protocol<Serializer, MsgType>::put_handler(rpc_handler* h) {
720  h->use_gate.leave();
721 }
722 
723 template<typename T> T make_shard_local_buffer_copy(foreign_ptr<std::unique_ptr<T>> org);
724 
725 template<typename Serializer, typename... Out>
726 future<> sink_impl<Serializer, Out...>::operator()(const Out&... args) {
727  // note that we use remote serializer pointer, so if serailizer needs a state
728  // it should have per-cpu one
729  snd_buf data = marshall(this->_con->get()->template serializer<Serializer>(), 4, args...);
730  static_assert(snd_buf::chunk_size >= 4, "send buffer chunk size is too small");
731  auto p = data.front().get_write();
732  write_le<uint32_t>(p, data.size - 4);
733  // we do not want to dead lock on huge packets, so let them in
734  // but only one at a time
735  auto size = std::min(size_t(data.size), max_stream_buffers_memory);
736  const auto seq_num = _next_seq_num++;
737  return get_units(this->_sem, size).then([this, data = make_foreign(std::make_unique<snd_buf>(std::move(data))), seq_num] (semaphore_units<> su) mutable {
738  if (this->_ex) {
739  return make_exception_future(this->_ex);
740  }
741  // It is OK to discard this future. The user is required to
742  // wait for it when closing.
743  (void)smp::submit_to(this->_con->get_owner_shard(), [this, data = std::move(data), seq_num] () mutable {
744  connection* con = this->_con->get();
745  if (con->error()) {
746  return make_exception_future(closed_error());
747  }
748  if(con->sink_closed()) {
749  return make_exception_future(stream_closed());
750  }
751 
752  auto& last_seq_num = _remote_state.last_seq_num;
753  auto& out_of_order_bufs = _remote_state.out_of_order_bufs;
754 
755  auto local_data = make_shard_local_buffer_copy(std::move(data));
756  const auto seq_num_diff = seq_num - last_seq_num;
757  if (seq_num_diff > 1) {
758  auto [it, _] = out_of_order_bufs.emplace(seq_num, deferred_snd_buf{promise<>{}, std::move(local_data)});
759  return it->second.pr.get_future();
760  }
761 
762  last_seq_num = seq_num;
763  auto ret_fut = con->send(std::move(local_data), {}, nullptr);
764  while (!out_of_order_bufs.empty() && out_of_order_bufs.begin()->first == (last_seq_num + 1)) {
765  auto it = out_of_order_bufs.begin();
766  last_seq_num = it->first;
767  auto fut = con->send(std::move(it->second.data), {}, nullptr);
768  fut.forward_to(std::move(it->second.pr));
769  out_of_order_bufs.erase(it);
770  }
771  return ret_fut;
772  }).then_wrapped([su = std::move(su), this] (future<> f) {
773  if (f.failed() && !this->_ex) { // first error is the interesting one
774  this->_ex = f.get_exception();
775  } else {
776  f.ignore_ready_future();
777  }
778  });
779  return make_ready_future<>();
780  });
781 }
782 
783 template<typename Serializer, typename... Out>
784 future<> sink_impl<Serializer, Out...>::flush() {
785  // wait until everything is sent out before returning.
786  return with_semaphore(this->_sem, max_stream_buffers_memory, [this] {
787  if (this->_ex) {
788  return make_exception_future(this->_ex);
789  }
790  return make_ready_future();
791  });
792 }
793 
794 template<typename Serializer, typename... Out>
795 future<> sink_impl<Serializer, Out...>::close() {
796  return with_semaphore(this->_sem, max_stream_buffers_memory, [this] {
797  return smp::submit_to(this->_con->get_owner_shard(), [this] {
798  connection* con = this->_con->get();
799  if (con->sink_closed()) { // double close, should not happen!
800  return make_exception_future(stream_closed());
801  }
802  future<> f = make_ready_future<>();
803  if (!con->error() && !this->_ex) {
804  snd_buf data = marshall(con->template serializer<Serializer>(), 4);
805  static_assert(snd_buf::chunk_size >= 4, "send buffer chunk size is too small");
806  auto p = data.front().get_write();
807  write_le<uint32_t>(p, -1U); // max len fragment marks an end of a stream
808  f = con->send(std::move(data), {}, nullptr);
809  } else {
810  f = this->_ex ? make_exception_future(this->_ex) : make_exception_future(closed_error());
811  }
812  return f.finally([con] { return con->close_sink(); });
813  });
814  });
815 }
816 
817 template<typename Serializer, typename... Out>
818 sink_impl<Serializer, Out...>::~sink_impl() {
819  // A failure to close might leave some continuations running after
820  // this is destroyed, leading to use-after-free bugs.
821  assert(this->_con->get()->sink_closed());
822 }
823 
824 template<typename Serializer, typename... In>
825 future<std::optional<std::tuple<In...>>> source_impl<Serializer, In...>::operator()() {
826  auto process_one_buffer = [this] {
827  foreign_ptr<std::unique_ptr<rcv_buf>> buf = std::move(this->_bufs.front());
828  this->_bufs.pop_front();
829  return std::apply([] (In&&... args) {
830  auto ret = std::make_optional(std::make_tuple(std::move(args)...));
831  return make_ready_future<std::optional<std::tuple<In...>>>(std::move(ret));
832  }, unmarshall<Serializer, In...>(*this->_con->get(), make_shard_local_buffer_copy(std::move(buf))));
833  };
834 
835  if (!this->_bufs.empty()) {
836  return process_one_buffer();
837  }
838 
839  // refill buffers from remote cpu
840  return smp::submit_to(this->_con->get_owner_shard(), [this] () -> future<> {
841  connection* con = this->_con->get();
842  if (con->_source_closed) {
843  return make_exception_future<>(stream_closed());
844  }
845  return con->stream_receive(this->_bufs).then_wrapped([this, con] (future<>&& f) {
846  if (f.failed()) {
847  return con->close_source().then_wrapped([ex = f.get_exception()] (future<> f){
848  f.ignore_ready_future();
849  return make_exception_future<>(ex);
850  });
851  }
852  if (this->_bufs.empty()) { // nothing to read -> eof
853  return con->close_source().then_wrapped([] (future<> f) {
854  f.ignore_ready_future();
855  return make_ready_future<>();
856  });
857  }
858  return make_ready_future<>();
859  });
860  }).then([this, process_one_buffer] () {
861  if (this->_bufs.empty()) {
862  return make_ready_future<std::optional<std::tuple<In...>>>(std::nullopt);
863  } else {
864  return process_one_buffer();
865  }
866  });
867 }
868 
869 template<typename... Out>
870 connection_id sink<Out...>::get_id() const {
871  return _impl->_con->get()->get_connection_id();
872 }
873 
874 template<typename... In>
875 connection_id source<In...>::get_id() const {
876  return _impl->_con->get()->get_connection_id();
877 }
878 
879 template<typename... In>
880 template<typename Serializer, typename... Out>
881 sink<Out...> source<In...>::make_sink() {
882  return sink<Out...>(make_shared<sink_impl<Serializer, Out...>>(_impl->_con));
883 }
884 
885 }
886 
887 }
888 
889 namespace std {
890 template<>
891 struct hash<seastar::rpc::streaming_domain_type> {
892  size_t operator()(const seastar::rpc::streaming_domain_type& domain) const {
893  size_t h = 0;
894  boost::hash_combine(h, std::hash<uint64_t>{}(domain._id));
895  return h;
896  }
897 };
898 }
899 
900 
A representation of a possibly not-yet-computed value.
Definition: future.hh:1238
futurize_t< FuncResult > then_wrapped(Func &&func) &noexcept
Schedule a block of code to run when the future is ready, allowing for exception handling.
Definition: future.hh:1511
static time_point now() noexcept
Definition: lowres_clock.hh:77
promise - allows a future value to be made available at a later time.
Definition: future.hh:926
void set_value(A &&... a) noexcept
Sets the promises value.
Definition: future.hh:982
Definition: reference_wrapper.hh:43
Definition: rpc_impl.hh:631
Definition: rpc.hh:420
Definition: rpc_types.hh:138
Definition: rpc_types.hh:65
Definition: rpc.hh:237
Definition: rpc_types.hh:192
Definition: rpc_types.hh:187
Definition: rpc.hh:796
Definition: rpc.hh:395
Definition: rpc_types.hh:309
Definition: rpc.hh:414
Definition: rpc_types.hh:348
Definition: rpc_types.hh:389
Identifies function calls that are accounted as a group.
Definition: scheduling.hh:286
static futurize_t< std::invoke_result_t< Func > > submit_to(unsigned t, smp_submit_to_options options, Func &&func) noexcept
Definition: smp.hh:354
future< T > make_ready_future(A &&... value) noexcept
Creates a future in an available, value state.
Definition: future.hh:1934
future< T > make_exception_future(std::exception_ptr &&value) noexcept
Creates a future in an available, failed state.
Definition: future.hh:1940
auto when_all(FutOrFuncs &&... fut_or_funcs) noexcept
Definition: when_all.hh:255
future now()
Returns a ready future.
Definition: later.hh:35
reference_wrapper< T > ref(T &object) noexcept
Wraps reference in a reference_wrapper.
Definition: reference_wrapper.hh:62
std::future< T > submit_to(instance &instance, unsigned shard, Func func)
Definition: alien.hh:206
Seastar API namespace.
Definition: abort_on_ebadf.hh:26
sstring format(const char *fmt, A &&... a)
Definition: print.hh:142
Definition: function_traits.hh:62
Definition: rpc_types.hh:202
Definition: rpc_types.hh:96
Definition: rpc_impl.hh:56
Definition: rpc_impl.hh:60
Definition: rpc_impl.hh:57
Definition: rpc_impl.hh:61
Definition: rpc_impl.hh:214
Definition: rpc_impl.hh:213
Definition: rpc_types.hh:178
Definition: rpc_types.hh:238
Definition: rpc_impl.hh:373
Definition: rpc_impl.hh:389
Definition: rpc_impl.hh:44
Definition: rpc.hh:686
Definition: rpc_impl.hh:191
Definition: rpc_impl.hh:65
Definition: rpc.hh:189
Definition: rpc_impl.hh:281
Definition: rpc_impl.hh:280
Definition: rpc_impl.hh:122
Definition: rpc_impl.hh:53