Seastar
High performance C++ framework for concurrent servers
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
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/format.hh>
24#include <seastar/core/function_traits.hh>
25#include <seastar/core/shared_ptr.hh>
26#include <seastar/core/sstring.hh>
27#include <seastar/core/when_all.hh>
28#include <seastar/util/is_smart_ptr.hh>
29#include <seastar/core/simple-stream.hh>
30#include <seastar/net/packet-data-source.hh>
31
32#include <boost/type.hpp> // for compatibility
33
34namespace seastar {
35
36namespace rpc {
37
38enum class exception_type : uint32_t {
39 USER = 0,
40 UNKNOWN_VERB = 1,
41};
42
43template<typename T>
45 using type = T;
46};
47
48template<typename T>
50 using type = T;
51};
52
53struct 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
64template <typename Ret, typename... In>
65struct 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
74template <typename Ret, typename... In>
75struct 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
83template <typename Ret, typename... In>
84struct 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
93template <typename Ret, typename... In>
94struct 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
102template <typename Ret, typename... In>
103struct 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
112template <typename Ret, typename... In>
113struct 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
121template <typename T>
123 using type = wait_type;
124 using cleaned_type = T;
125};
126
127template <typename... T>
128struct wait_signature<future<T...>> {
129 using type = wait_type;
130 using cleaned_type = future<T...>;
131};
132
133template <>
135 using type = no_wait_type;
136 using cleaned_type = void;
137};
138
139template <>
141 using type = no_wait_type;
142 using cleaned_type = future<>;
143};
144
145template <typename T>
146using wait_signature_t = typename wait_signature<T>::type;
147
148template <typename... In>
149inline
150std::tuple<In...>
151maybe_add_client_info(dont_want_client_info, client_info&, std::tuple<In...>&& args) {
152 return std::move(args);
153}
154
155template <typename... In>
156inline
157std::tuple<std::reference_wrapper<client_info>, In...>
158maybe_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
162template <typename... In>
163inline
164std::tuple<In...>
165maybe_add_time_point(dont_want_time_point, opt_time_point&, std::tuple<In...>&& args) {
166 return std::move(args);
167}
168
169template <typename... In>
170inline
171std::tuple<opt_time_point, In...>
172maybe_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
176inline 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
183inline 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
190template <bool IsSmartPtr>
192
193template <>
194struct 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
201template <>
202struct 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
209template <typename Serializer, typename Output, typename... T>
210inline void do_marshall(Serializer& serializer, Output& out, const T&... args);
211
212template <typename Serializer, typename Output>
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 // since C++23, std::apply() only accepts tuple-like types, while
245 // rpc::tuple is not a tuple-like type from the tuple-like C++
246 // concept's perspective. so we have to cast it to std::tuple to
247 // appease std::apply()
248 std::apply(do_do_marshall, static_cast<const std::tuple<T...>&>(arg));
249 }
250 };
251};
252
253template <typename Serializer, typename Output, typename... T>
254inline void do_marshall(Serializer& serializer, Output& out, const T&... args) {
255 // C++ guarantees that brace-initialization expressions are evaluted in order
256 (void)std::initializer_list<int>{(marshall_one<Serializer, Output>::template helper<T>::doit(serializer, out, args), 1)...};
257}
258
259static inline memory_output_stream<snd_buf::iterator> make_serializer_stream(snd_buf& output) {
260 auto* b = std::get_if<temporary_buffer<char>>(&output.bufs);
261 if (b) {
262 return memory_output_stream<snd_buf::iterator>(memory_output_stream<snd_buf::iterator>::simple(b->get_write(), b->size()));
263 } else {
264 auto& ar = std::get<std::vector<temporary_buffer<char>>>(output.bufs);
265 return memory_output_stream<snd_buf::iterator>(memory_output_stream<snd_buf::iterator>::fragmented(ar.begin(), output.size));
266 }
267}
268
269template <typename Serializer, typename... T>
270inline snd_buf marshall(Serializer& serializer, size_t head_space, const T&... args) {
271 measuring_output_stream measure;
272 do_marshall(serializer, measure, args...);
273 snd_buf ret(measure.size() + head_space);
274 auto out = make_serializer_stream(ret);
275 out.skip(head_space);
276 do_marshall(serializer, out, args...);
277 return ret;
278}
279
280template <typename Serializer, typename Input, typename... T>
281std::tuple<T...> do_unmarshall(connection& c, Input& in);
282
283// The protocol to call the serializer is read(serializer, stream, rpc::type<T>).
284// However, some users (ahem) used boost::type instead of rpc::type when the two
285// types were aliased, preventing us from moving to the newer std::type_identity.
286// To preserve compatibility, calls to read() are routed through
287// read_via_type_marker(), of which there are two variants, one for
288// boost::type (marked as deprecated) and one for std::type_identity.
289
290template <typename T, typename... Args>
291requires requires (Args... args, type<T> t) { read(std::forward<Args>(args)..., t); }
292auto
293read_via_type_marker(Args&&... args) {
294 return read(std::forward<Args>(args)..., type<T>());
295}
296
297template <typename T, typename... Args>
298requires requires (Args... args, boost::type<T> t) { read(std::forward<Args>(args)..., t); }
299[[deprecated("Use rpc::type<> instead of boost::type<>")]]
300auto
301read_via_type_marker(Args&&... args) {
302 return read(std::forward<Args>(args)..., boost::type<T>());
303}
304
305template<typename Serializer, typename Input>
307 template<typename T> struct helper {
308 static T doit(connection& c, Input& in) {
309 return read_via_type_marker<T>(c.serializer<Serializer>(), in);
310 }
311 };
312 template<typename T> struct helper<optional<T>> {
313 static optional<T> doit(connection& c, Input& in) {
314 if (in.size()) {
315 return optional<T>(read_via_type_marker<typename remove_optional<T>::type>(c.serializer<Serializer>(), in));
316 } else {
317 return optional<T>();
318 }
319 }
320 };
321 template<typename T> struct helper<std::reference_wrapper<const T>> {
322 static T doit(connection& c, Input& in) {
323 return helper<T>::doit(c, in);
324 }
325 };
326 static connection_id get_connection_id(Input& in) {
327 sstring id = uninitialized_string(sizeof(connection_id));
328 in.read(id.data(), sizeof(connection_id));
329 return deserialize_connection_id(id);
330 }
331 template<typename... T> struct helper<sink<T...>> {
332 static sink<T...> doit(connection& c, Input& in) {
333 return sink<T...>(make_shared<sink_impl<Serializer, T...>>(c.get_stream(get_connection_id(in))));
334 }
335 };
336 template<typename... T> struct helper<source<T...>> {
337 static source<T...> doit(connection& c, Input& in) {
338 return source<T...>(make_shared<source_impl<Serializer, T...>>(c.get_stream(get_connection_id(in))));
339 }
340 };
341 template <typename... T> struct helper<tuple<T...>> {
342 static tuple<T...> doit(connection& c, Input& in) {
343 return do_unmarshall<Serializer, Input, T...>(c, in);
344 }
345 };
346};
347
348template <typename... T>
350
351template <>
353 using type = std::tuple<>;
354};
355
356template <typename T0, typename... T>
358 using type = std::tuple<
359 T0,
360 std::conditional_t<
361 std::is_default_constructible_v<T>,
362 T,
363 std::optional<T>
364 >...
365 >;
366};
367
368template <typename... T>
369using default_constructible_tuple_except_first_t = typename default_constructible_tuple_except_first<T...>::type;
370
371// Where Tin != Tout, apply std:optional::value()
372template <typename... Tout, typename... Tin>
373auto
374unwrap_optional_if_needed(std::tuple<Tin...>&& tuple_in) {
375 using tuple_in_t = std::tuple<Tin...>;
376 using tuple_out_t = std::tuple<Tout...>;
377 return std::invoke([&] <size_t... Idx> (std::index_sequence<Idx...>) {
378 return tuple_out_t(
379 std::invoke([&] () {
380 if constexpr (std::same_as<std::tuple_element_t<Idx, tuple_in_t>, std::tuple_element_t<Idx, tuple_out_t>>) {
381 return std::move(std::get<Idx>(tuple_in));
382 } else {
383 return std::move(std::get<Idx>(tuple_in).value());
384 }
385 })...);
386 }, std::make_index_sequence<sizeof...(Tout)>());
387}
388
389template <typename Serializer, typename Input, typename... T>
390inline std::tuple<T...> do_unmarshall(connection& c, Input& in) {
391 // Argument order processing is unspecified, but we need to deserialize
392 // left-to-right. So we deserialize into something that can be lazily
393 // constructed (and can conditionally destroy itself if we only constructed some
394 // of the arguments).
395 //
396 // The first element of the tuple has no ordering
397 // problem, and we can deserialize directly into a std::tuple<T...>.
398 //
399 // For the rest of the elements, if they are default-constructible, we leave
400 // them as is, and if not, we deserialize into std::optional<T>, and later
401 // unwrap them. If we're lucky and nothing was wrapped, we can return without
402 // any data movement.
403 using ret_type = std::tuple<T...>;
404 using temporary_type = default_constructible_tuple_except_first_t<T...>;
405 return std::invoke([&] <size_t... Idx> (std::index_sequence<Idx...>) {
406 auto tmp = temporary_type(
407 std::invoke([&] () -> std::tuple_element_t<Idx, temporary_type> {
408 if constexpr (Idx == 0) {
409 // The first T has no ordering problem, so we can deserialize it directly into the tuple
410 return unmarshal_one<Serializer, Input>::template helper<std::tuple_element_t<Idx, ret_type>>::doit(c, in);
411 } else {
412 // Use default constructor for the rest of the Ts
413 return {};
414 }
415 })...
416 );
417 // Deserialize the other Ts, comma-expression preserves left-to-right order.
418 (void)(..., ((Idx == 0
419 ? 0
420 : ((std::get<Idx>(tmp) = unmarshal_one<Serializer, Input>::template helper<std::tuple_element_t<Idx, ret_type>>::doit(c, in), 0)))));
421 if constexpr (std::same_as<ret_type, temporary_type>) {
422 // Use Named Return Vale Optimization (NVRO) if we didn't have to wrap anything
423 return tmp;
424 } else {
425 return unwrap_optional_if_needed<T...>(std::move(tmp));
426 }
427 }, std::index_sequence_for<T...>());
428}
429
430template <typename Serializer, typename... T>
431inline std::tuple<T...> unmarshall(connection& c, rcv_buf input) {
432 auto in = make_deserializer_stream(input);
433 return do_unmarshall<Serializer, decltype(in), T...>(c, in);
434}
435
436inline std::exception_ptr unmarshal_exception(rcv_buf& d) {
437 std::exception_ptr ex;
438 auto data = make_deserializer_stream(d);
439
440 uint32_t v32;
441 data.read(reinterpret_cast<char*>(&v32), 4);
442 exception_type ex_type = exception_type(le_to_cpu(v32));
443 data.read(reinterpret_cast<char*>(&v32), 4);
444 uint32_t ex_len = le_to_cpu(v32);
445
446 switch (ex_type) {
447 case exception_type::USER: {
448 std::string s(ex_len, '\0');
449 data.read(&*s.begin(), ex_len);
450 ex = std::make_exception_ptr(remote_verb_error(std::move(s)));
451 break;
452 }
453 case exception_type::UNKNOWN_VERB: {
454 uint64_t v64;
455 data.read(reinterpret_cast<char*>(&v64), 8);
456 ex = std::make_exception_ptr(unknown_verb_error(le_to_cpu(v64)));
457 break;
458 }
459 default:
460 ex = std::make_exception_ptr(unknown_exception_error());
461 break;
462 }
463 return ex;
464}
465
466template <typename Payload, typename... T>
468 bool done = false;
469 promise<T...> p;
470 template<typename... V>
471 void set_value(V&&... v) {
472 done = true;
473 p.set_value(internal::untuple(std::forward<V>(v))...);
474 }
476 if (!done) {
477 p.set_exception(closed_error());
478 }
479 }
480};
481
482template<typename Serializer, typename T>
483struct rcv_reply : rcv_reply_base<T, T> {
484 inline void get_reply(rpc::client& dst, rcv_buf input) {
485 this->set_value(unmarshall<Serializer, T>(dst, std::move(input)));
486 }
487};
488
489template<typename Serializer, typename... T>
490struct rcv_reply<Serializer, future<T...>> : rcv_reply_base<std::tuple<T...>, T...> {
491 inline void get_reply(rpc::client& dst, rcv_buf input) {
492 this->set_value(unmarshall<Serializer, T...>(dst, std::move(input)));
493 }
494};
495
496template<typename Serializer>
497struct rcv_reply<Serializer, void> : rcv_reply_base<void, void> {
498 inline void get_reply(rpc::client&, rcv_buf) {
499 this->set_value();
500 }
501};
502
503template<typename Serializer>
504struct rcv_reply<Serializer, future<>> : rcv_reply<Serializer, void> {};
505
506template <typename Serializer, typename Ret, typename... InArgs>
507inline auto wait_for_reply(wait_type, std::optional<rpc_clock_type::time_point> timeout, rpc_clock_type::time_point start, cancellable* cancel, rpc::client& dst, id_type msg_id,
508 signature<Ret (InArgs...)>) {
509 using reply_type = rcv_reply<Serializer, Ret>;
510 auto lambda = [] (reply_type& r, rpc::client& dst, id_type msg_id, rcv_buf data) mutable {
511 if (msg_id >= 0) {
512 dst.get_stats_internal().replied++;
513 return r.get_reply(dst, std::move(data));
514 } else {
515 dst.get_stats_internal().exception_received++;
516 r.done = true;
517 r.p.set_exception(unmarshal_exception(data));
518 }
519 };
520 using handler_type = typename rpc::client::template reply_handler<reply_type, decltype(lambda)>;
521 auto r = std::make_unique<handler_type>(std::move(lambda));
522 r->start = start;
523 auto fut = r->reply.p.get_future();
524 dst.wait_for_reply(msg_id, std::move(r), timeout, cancel);
525 return fut;
526}
527
528template<typename Serializer, typename... InArgs>
529inline auto wait_for_reply(no_wait_type, std::optional<rpc_clock_type::time_point>, rpc_clock_type::time_point start, cancellable*, rpc::client&, id_type,
530 signature<no_wait_type (InArgs...)>) { // no_wait overload
531 return make_ready_future<>();
532}
533
534template<typename Serializer, typename... InArgs>
535inline auto wait_for_reply(no_wait_type, std::optional<rpc_clock_type::time_point>, rpc_clock_type::time_point, cancellable*, rpc::client&, id_type,
536 signature<future<no_wait_type> (InArgs...)>) { // future<no_wait> overload
537 return make_ready_future<>();
538}
539
540// Convert a relative timeout (a duration) to an absolute one (time_point).
541// Do the calculation safely so that a very large duration will be capped by
542// time_point::max, instead of wrapping around to ancient history.
543inline rpc_clock_type::time_point
544relative_timeout_to_absolute(rpc_clock_type::duration relative) {
545 rpc_clock_type::time_point now = rpc_clock_type::now();
546 return now + std::min(relative, rpc_clock_type::time_point::max() - now);
547}
548
549// Refer to struct request_frame for more details
550static constexpr size_t request_frame_headroom = 28;
551
552// Returns lambda that can be used to send rpc messages.
553// The lambda gets client connection and rpc parameters as arguments, marshalls them sends
554// to a server and waits for a reply. After receiving reply it unmarshalls it and signal completion
555// to a caller.
556template<typename Serializer, typename MsgType, typename Ret, typename... InArgs>
557auto send_helper(MsgType xt, signature<Ret (InArgs...)> xsig) {
558 struct shelper {
559 MsgType t;
560 signature<Ret (InArgs...)> sig;
561 auto send(rpc::client& dst, std::optional<rpc_clock_type::time_point> timeout, cancellable* cancel, const InArgs&... args) {
562 if (dst.error()) {
563 using cleaned_ret_type = typename wait_signature<Ret>::cleaned_type;
564 return futurize<cleaned_ret_type>::make_exception_future(closed_error());
565 }
566
567 auto start = rpc_clock_type::now();
568 // send message
569 auto msg_id = dst.next_message_id();
570 snd_buf data = marshall(dst.template serializer<Serializer>(), request_frame_headroom, args...);
571
572 // prepare reply handler, if return type is now_wait_type this does nothing, since no reply will be sent
573 using wait = wait_signature_t<Ret>;
574 return when_all(dst.request(uint64_t(t), msg_id, std::move(data), timeout, cancel), wait_for_reply<Serializer>(wait(), timeout, start, cancel, dst, msg_id, sig)).then([] (auto r) {
575 std::get<0>(r).ignore_ready_future();
576 return std::move(std::get<1>(r)); // return future of wait_for_reply
577 });
578 }
579 auto operator()(rpc::client& dst, const InArgs&... args) {
580 return send(dst, {}, nullptr, args...);
581 }
582 auto operator()(rpc::client& dst, rpc_clock_type::time_point timeout, const InArgs&... args) {
583 return send(dst, timeout, nullptr, args...);
584 }
585 auto operator()(rpc::client& dst, rpc_clock_type::duration timeout, const InArgs&... args) {
586 return send(dst, relative_timeout_to_absolute(timeout), nullptr, args...);
587 }
588 auto operator()(rpc::client& dst, cancellable& cancel, const InArgs&... args) {
589 return send(dst, {}, &cancel, args...);
590 }
591
592 };
593 return shelper{xt, xsig};
594}
595
596// Refer to struct response_frame for more details
597static constexpr size_t response_frame_headroom = 16;
598
599template<typename Serializer, typename RetTypes>
600inline future<> reply(wait_type, future<RetTypes>&& ret, int64_t msg_id, shared_ptr<server::connection> client,
601 std::optional<rpc_clock_type::time_point> timeout, std::optional<rpc_clock_type::duration> handler_duration) {
602 if (!client->error()) {
603 snd_buf data;
604 try {
605 if constexpr (std::is_void_v<RetTypes>) {
606 ret.get();
607 data = std::invoke(marshall<Serializer>, std::ref(client->template serializer<Serializer>()), response_frame_headroom);
608 } else {
609 data = std::invoke(marshall<Serializer, const RetTypes&>, std::ref(client->template serializer<Serializer>()), response_frame_headroom, std::move(ret.get()));
610 }
611 } catch (std::exception& ex) {
612 uint32_t len = std::strlen(ex.what());
613 data = snd_buf(response_frame_headroom + 2 * sizeof(uint32_t) + len);
614 auto os = make_serializer_stream(data);
615 os.skip(response_frame_headroom);
616 uint32_t v32 = cpu_to_le(uint32_t(exception_type::USER));
617 os.write(reinterpret_cast<char*>(&v32), sizeof(v32));
618 v32 = cpu_to_le(len);
619 os.write(reinterpret_cast<char*>(&v32), sizeof(v32));
620 os.write(ex.what(), len);
621 msg_id = -msg_id;
622 }
623
624 return client->respond(msg_id, std::move(data), timeout, handler_duration);
625 } else {
626 ret.ignore_ready_future();
627 return make_ready_future<>();
628 }
629}
630
631// specialization for no_wait_type which does not send a reply
632template<typename Serializer>
633inline future<> reply(no_wait_type, future<no_wait_type>&& r, int64_t msgid, shared_ptr<server::connection> client,
634 std::optional<rpc_clock_type::time_point>, std::optional<rpc_clock_type::duration>) {
635 try {
636 r.get();
637 } catch (std::exception& ex) {
638 client->get_logger()(client->info(), msgid, to_sstring("exception \"") + ex.what() + "\" in no_wait handler ignored");
639 }
640 return make_ready_future<>();
641}
642
643template<typename Ret, typename... InArgs, typename WantClientInfo, typename WantTimePoint, typename Func, typename ArgsTuple>
644inline futurize_t<Ret> apply(Func& func, client_info& info, opt_time_point time_point, WantClientInfo wci, WantTimePoint wtp, signature<Ret (InArgs...)>, ArgsTuple&& args) {
645 using futurator = futurize<Ret>;
646 return futurator::apply(func, maybe_add_client_info(wci, info, maybe_add_time_point(wtp, time_point, std::forward<ArgsTuple>(args))));
647}
648
649// lref_to_cref is a helper that encapsulates lvalue reference in std::ref() or does nothing otherwise
650template<typename T>
651auto lref_to_cref(T&& x) {
652 return std::move(x);
653}
654
655template<typename T>
656auto lref_to_cref(T& x) {
657 return std::ref(x);
658}
659
660// Creates lambda to handle RPC message on a server.
661// The lambda unmarshalls all parameters, calls a handler, marshall return values and sends them back to a client
662template <typename Serializer, typename Func, typename Ret, typename... InArgs, typename WantClientInfo, typename WantTimePoint>
663auto recv_helper(signature<Ret (InArgs...)> sig, Func&& func, WantClientInfo, WantTimePoint) {
664 using signature = decltype(sig);
665 using wait_style = wait_signature_t<Ret>;
666 return [func = lref_to_cref(std::forward<Func>(func))](shared_ptr<server::connection> client,
667 std::optional<rpc_clock_type::time_point> timeout,
668 int64_t msg_id,
669 rcv_buf data,
670 gate::holder guard) mutable {
671 auto memory_consumed = client->estimate_request_size(data.size);
672 if (memory_consumed > client->max_request_size()) {
673 auto err = format("request size {:d} large than memory limit {:d}", memory_consumed, client->max_request_size());
674 client->get_logger()(client->peer_address(), err);
675 // FIXME: future is discarded
676 (void)try_with_gate(client->get_server().reply_gate(), [client, timeout, msg_id, err = std::move(err)] {
677 return reply<Serializer>(wait_style(), futurize<Ret>::make_exception_future(std::runtime_error(err.c_str())), msg_id, client, timeout, std::nullopt).handle_exception([client, msg_id] (std::exception_ptr eptr) {
678 client->get_logger()(client->info(), msg_id, format("got exception while processing an oversized message: {}", eptr));
679 });
680 }).handle_exception_type([] (gate_closed_exception&) {/* ignore */});
681 return make_ready_future();
682 }
683 // note: apply is executed asynchronously with regards to networking so we cannot chain futures here by doing "return apply()"
684 auto f = client->wait_for_resources(memory_consumed, timeout).then([client, timeout, msg_id, data = std::move(data), &func, g = std::move(guard)] (auto permit) mutable {
685 // FIXME: future is discarded
686 (void)try_with_gate(client->get_server().reply_gate(), [client, timeout, msg_id, data = std::move(data), permit = std::move(permit), &func] () mutable {
687 try {
688 auto args = unmarshall<Serializer, InArgs...>(*client, std::move(data));
689 auto start = rpc_clock_type::now();
690 return apply(func, client->info(), timeout, WantClientInfo(), WantTimePoint(), signature(), std::move(args)).then_wrapped([client, timeout, msg_id, permit = std::move(permit), start] (futurize_t<Ret> ret) mutable {
691 return reply<Serializer>(wait_style(), std::move(ret), msg_id, client, timeout, rpc_clock_type::now() - start).handle_exception([permit = std::move(permit), client, msg_id] (std::exception_ptr eptr) {
692 client->get_logger()(client->info(), msg_id, format("got exception while processing a message: {}", eptr));
693 });
694 });
695 } catch (...) {
696 client->get_logger()(client->info(), msg_id, format("caught exception while processing a message: {}", std::current_exception()));
697 return make_ready_future();
698 }
699 }).handle_exception_type([g = std::move(g)] (gate_closed_exception&) {/* ignore */});
700 });
701
702 if (timeout) {
703 f = f.handle_exception_type([] (semaphore_timed_out&) { /* ignore */ });
704 }
705
706 return f;
707 };
708}
709
710// helper to create copy constructible lambda from non copy constructible one. std::function<> works only with former kind.
711template<typename Func>
712auto make_copyable_function(Func&& func, std::enable_if_t<!std::is_copy_constructible_v<std::decay_t<Func>>, void*> = nullptr) {
713 auto p = make_lw_shared<typename std::decay_t<Func>>(std::forward<Func>(func));
714 return [p] (auto&&... args) { return (*p)( std::forward<decltype(args)>(args)... ); };
715}
716
717template<typename Func>
718auto make_copyable_function(Func&& func, std::enable_if_t<std::is_copy_constructible_v<std::decay_t<Func>>, void*> = nullptr) {
719 return std::forward<Func>(func);
720}
721
722// This class is used to calculate client side rpc function signature.
723// Return type is converted from a smart pointer to a type it points to.
724// rpc::optional are converted to non optional type.
725//
726// Examples:
727// std::unique_ptr<int>(int, rpc::optional<long>) -> int(int, long)
728// double(float) -> double(float)
729template<typename Ret, typename... In>
731 template<typename T, bool IsSmartPtr>
732 struct drop_smart_ptr_impl;
733 template<typename T>
734 struct drop_smart_ptr_impl<T, true> {
735 using type = typename T::element_type;
736 };
737 template<typename T>
738 struct drop_smart_ptr_impl<T, false> {
739 using type = T;
740 };
741 template<typename T>
742 using drop_smart_ptr = drop_smart_ptr_impl<T, is_smart_ptr<T>::value>;
743
744 // if return type is smart ptr take a type it points to instead
745 using return_type = typename drop_smart_ptr<Ret>::type;
746public:
747 using type = return_type(typename remove_optional<In>::type...);
748};
749
750template<typename Serializer, typename MsgType>
751template<typename Ret, typename... In>
752auto protocol<Serializer, MsgType>::make_client(signature<Ret(In...)>, MsgType t) {
753 using sig_type = signature<typename client_function_type<Ret, In...>::type>;
754 return send_helper<Serializer>(t, sig_type());
755}
756
757template<typename Serializer, typename MsgType>
758template<typename Func>
760 return make_client(typename signature<typename function_traits<Func>::signature>::clean(), t);
761}
762
763template<typename Serializer, typename MsgType>
764template<typename Func>
767 using clean_sig_type = typename sig_type::clean;
768 using want_client_info = typename sig_type::want_client_info;
769 using want_time_point = typename sig_type::want_time_point;
770 auto recv = recv_helper<Serializer>(clean_sig_type(), std::forward<Func>(func),
771 want_client_info(), want_time_point());
772 register_receiver(t, rpc_handler{sg, make_copyable_function(std::move(recv)), {}});
773 return make_client(clean_sig_type(), t);
774}
775
776template<typename Serializer, typename MsgType>
777template<typename Func>
779 return register_handler(t, scheduling_group(), std::forward<Func>(func));
780}
781
782template<typename Serializer, typename MsgType>
784 auto it = _handlers.find(t);
785 if (it != _handlers.end()) {
786 return it->second.use_gate.close().finally([this, t] {
787 _handlers.erase(t);
788 });
789 }
790 return make_ready_future<>();
791}
792
793template<typename Serializer, typename MsgType>
795 auto it = _handlers.find(msg_id);
796 if (it == _handlers.end()) {
797 return false;
798 }
799 return !it->second.use_gate.is_closed();
800}
801
802template<typename Serializer, typename MsgType>
803std::optional<protocol_base::handler_with_holder> protocol<Serializer, MsgType>::get_handler(uint64_t msg_id) {
804 const auto it = _handlers.find(MsgType(msg_id));
805 if (it != _handlers.end()) {
806 try {
807 return handler_with_holder{it->second, it->second.use_gate.hold()};
808 } catch (gate_closed_exception&) {
809 // unregistered, just ignore
810 }
811 }
812 return std::nullopt;
813}
814
815template<typename T> T make_shard_local_buffer_copy(foreign_ptr<std::unique_ptr<T>> org);
816
817template<typename Serializer, typename... Out>
818future<> sink_impl<Serializer, Out...>::operator()(const Out&... args) {
819 // note that we use remote serializer pointer, so if serailizer needs a state
820 // it should have per-cpu one
821 snd_buf data = marshall(this->_con->get()->template serializer<Serializer>(), 4, args...);
822 static_assert(snd_buf::chunk_size >= 4, "send buffer chunk size is too small");
823 auto p = data.front().get_write();
824 write_le<uint32_t>(p, data.size - 4);
825 // we do not want to dead lock on huge packets, so let them in
826 // but only one at a time
827 auto size = std::min(size_t(data.size), max_stream_buffers_memory);
828 const auto seq_num = _next_seq_num++;
829 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 {
830 if (this->_ex) {
831 return make_exception_future(this->_ex);
832 }
833 // It is OK to discard this future. The user is required to
834 // wait for it when closing.
835 (void)smp::submit_to(this->_con->get_owner_shard(), [this, data = std::move(data), seq_num] () mutable {
836 connection* con = this->_con->get();
837 if (con->error()) {
838 return make_exception_future(closed_error());
839 }
840 if(con->sink_closed()) {
841 return make_exception_future(stream_closed());
842 }
843
844 auto& last_seq_num = _remote_state.last_seq_num;
845 auto& out_of_order_bufs = _remote_state.out_of_order_bufs;
846
847 auto local_data = make_shard_local_buffer_copy(std::move(data));
848 const auto seq_num_diff = seq_num - last_seq_num;
849 if (seq_num_diff > 1) {
850 auto [it, _] = out_of_order_bufs.emplace(seq_num, deferred_snd_buf{promise<>{}, std::move(local_data)});
851 return it->second.pr.get_future();
852 }
853
854 last_seq_num = seq_num;
855 auto ret_fut = con->send(std::move(local_data), {}, nullptr);
856 while (!out_of_order_bufs.empty() && out_of_order_bufs.begin()->first == (last_seq_num + 1)) {
857 auto it = out_of_order_bufs.begin();
858 last_seq_num = it->first;
859 auto fut = con->send(std::move(it->second.data), {}, nullptr);
860 fut.forward_to(std::move(it->second.pr));
861 out_of_order_bufs.erase(it);
862 }
863 return ret_fut;
864 }).then_wrapped([su = std::move(su), this] (future<> f) {
865 if (f.failed() && !this->_ex) { // first error is the interesting one
866 this->_ex = f.get_exception();
867 } else {
868 f.ignore_ready_future();
869 }
870 });
871 return make_ready_future<>();
872 });
873}
874
875template<typename Serializer, typename... Out>
876future<> sink_impl<Serializer, Out...>::flush() {
877 // wait until everything is sent out before returning.
878 return with_semaphore(this->_sem, max_stream_buffers_memory, [this] {
879 if (this->_ex) {
880 return make_exception_future(this->_ex);
881 }
882 return make_ready_future();
883 });
884}
885
886template<typename Serializer, typename... Out>
887future<> sink_impl<Serializer, Out...>::close() {
888 return with_semaphore(this->_sem, max_stream_buffers_memory, [this] {
889 return smp::submit_to(this->_con->get_owner_shard(), [this] {
890 connection* con = this->_con->get();
891 if (con->sink_closed()) { // double close, should not happen!
892 return make_exception_future(stream_closed());
893 }
894 future<> f = make_ready_future<>();
895 if (!con->error() && !this->_ex) {
896 snd_buf data = marshall(con->template serializer<Serializer>(), 4);
897 static_assert(snd_buf::chunk_size >= 4, "send buffer chunk size is too small");
898 auto p = data.front().get_write();
899 write_le<uint32_t>(p, -1U); // max len fragment marks an end of a stream
900 f = con->send(std::move(data), {}, nullptr);
901 } else {
902 f = this->_ex ? make_exception_future(this->_ex) : make_exception_future(closed_error());
903 }
904 return f.finally([con] { return con->close_sink(); });
905 });
906 });
907}
908
909template<typename Serializer, typename... Out>
910sink_impl<Serializer, Out...>::~sink_impl() {
911 // A failure to close might leave some continuations running after
912 // this is destroyed, leading to use-after-free bugs.
913 assert(this->_con->get()->sink_closed());
914}
915
916template<typename Serializer, typename... In>
917future<std::optional<std::tuple<In...>>> source_impl<Serializer, In...>::operator()() {
918 auto process_one_buffer = [this] {
919 foreign_ptr<std::unique_ptr<rcv_buf>> buf = std::move(this->_bufs.front());
920 this->_bufs.pop_front();
921 return std::apply([] (In&&... args) {
922 auto ret = std::make_optional(std::make_tuple(std::move(args)...));
923 return make_ready_future<std::optional<std::tuple<In...>>>(std::move(ret));
924 }, unmarshall<Serializer, In...>(*this->_con->get(), make_shard_local_buffer_copy(std::move(buf))));
925 };
926
927 if (!this->_bufs.empty()) {
928 return process_one_buffer();
929 }
930
931 // refill buffers from remote cpu
932 return smp::submit_to(this->_con->get_owner_shard(), [this] () -> future<> {
933 connection* con = this->_con->get();
934 if (con->_source_closed) {
935 return make_exception_future<>(stream_closed());
936 }
937 return con->stream_receive(this->_bufs).then_wrapped([this, con] (future<>&& f) {
938 if (f.failed()) {
939 return con->close_source().then_wrapped([ex = f.get_exception()] (future<> f){
940 f.ignore_ready_future();
941 return make_exception_future<>(ex);
942 });
943 }
944 if (this->_bufs.empty()) { // nothing to read -> eof
945 return con->close_source().then_wrapped([] (future<> f) {
946 f.ignore_ready_future();
947 return make_ready_future<>();
948 });
949 }
950 return make_ready_future<>();
951 });
952 }).then([this, process_one_buffer] () {
953 if (this->_bufs.empty()) {
954 return make_ready_future<std::optional<std::tuple<In...>>>(std::nullopt);
955 } else {
956 return process_one_buffer();
957 }
958 });
959}
960
961template<typename... Out>
962connection_id sink<Out...>::get_id() const {
963 return _impl->_con->get()->get_connection_id();
964}
965
966template<typename... In>
967connection_id source<In...>::get_id() const {
968 return _impl->_con->get()->get_connection_id();
969}
970
971template<typename... In>
972template<typename Serializer, typename... Out>
973sink<Out...> source<In...>::make_sink() {
974 return sink<Out...>(make_shared<sink_impl<Serializer, Out...>>(_impl->_con));
975}
976
977}
978
979}
980
981namespace std {
982template<>
983struct hash<seastar::rpc::streaming_domain_type> {
984 size_t operator()(const seastar::rpc::streaming_domain_type& domain) const {
985 size_t h = 0;
986 boost::hash_combine(h, std::hash<uint64_t>{}(domain._id));
987 return h;
988 }
989};
990}
991
992
A representation of a possibly not-yet-computed value.
Definition: future.hh:1240
static time_point now() noexcept
Definition: lowres_clock.hh:74
promise - allows a future value to be made available at a later time.
Definition: future.hh:934
void set_value(A &&... a) noexcept
Sets the promises value.
Definition: future.hh:990
Definition: reference_wrapper.hh:43
Definition: rpc_impl.hh:730
Definition: rpc.hh:433
Definition: rpc_types.hh:139
Definition: rpc_types.hh:66
Definition: rpc.hh:249
Definition: rpc_types.hh:193
Definition: rpc_types.hh:188
Definition: rpc.hh:817
Definition: rpc.hh:408
Definition: rpc_types.hh:317
Definition: rpc.hh:427
Definition: rpc_types.hh:356
Definition: rpc_types.hh:397
Identifies function calls that are accounted as a group.
Definition: scheduling.hh:285
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:1943
future< T > make_exception_future(std::exception_ptr &&value) noexcept
Creates a future in an available, failed state.
Definition: future.hh:1949
auto when_all(FutOrFuncs &&... fut_or_funcs) noexcept
Definition: when_all.hh:252
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:204
Seastar API namespace.
Definition: abort_on_ebadf.hh:26
sstring format(fmt::format_string< A... > fmt, A &&... a)
Definition: format.hh:42
Definition: function_traits.hh:62
STL namespace.
Definition: rpc_types.hh:203
Definition: rpc_types.hh:97
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:179
Definition: rpc_types.hh:239
Definition: rpc_impl.hh:467
Definition: rpc_impl.hh:483
Definition: rpc_impl.hh:44
Definition: rpc.hh:704
Definition: rpc_impl.hh:191
Definition: rpc_impl.hh:65
Definition: rpc.hh:191
Definition: rpc_impl.hh:307
Definition: rpc_impl.hh:306
Definition: rpc_impl.hh:122
Definition: rpc_impl.hh:53