Aedis 1.3.1  
A redis client designed for performance and scalability
common.cpp
1/* Copyright (c) 2018-2022 Marcelo Zimbres Silva (mzimbres@gmail.com)
2 *
3 * Distributed under the Boost Software License, Version 1.0. (See
4 * accompanying file LICENSE.txt)
5 */
6
7#include "common.hpp"
8
9#include <boost/asio.hpp>
10#if defined(BOOST_ASIO_HAS_CO_AWAIT)
11#include <boost/asio/experimental/awaitable_operators.hpp>
12#include <iostream>
13
14namespace net = boost::asio;
15using namespace net::experimental::awaitable_operators;
16using resolver = net::use_awaitable_t<>::as_default_on_t<net::ip::tcp::resolver>;
17using timer_type = net::use_awaitable_t<>::as_default_on_t<net::steady_timer>;
19using aedis::adapt;
21
22namespace
23{
24auto redir(boost::system::error_code& ec)
25 { return net::redirect_error(net::use_awaitable, ec); }
26}
27
28auto healthy_checker(std::shared_ptr<connection> conn) -> net::awaitable<void>
29{
30 try {
31 request req;
32 req.get_config().cancel_on_connection_lost = true;
33 req.push("PING");
34
35 timer_type timer{co_await net::this_coro::executor};
36
37 for (boost::system::error_code ec;;) {
38 timer.expires_after(std::chrono::seconds{1});
39 co_await (conn->async_exec(req, adapt()) || timer.async_wait(redir(ec)));
40
41 if (!ec) {
42 co_return;
43 }
44
45 // Waits some time before trying the next ping.
46 timer.expires_after(std::chrono::seconds{1});
47 co_await timer.async_wait();
48 }
49 } catch (...) {
50 }
51}
52
53auto
54connect(
55 std::shared_ptr<connection> conn,
56 std::string const& host,
57 std::string const& port) -> net::awaitable<void>
58{
59 auto ex = co_await net::this_coro::executor;
60 resolver resv{ex};
61 timer_type timer{ex};
62
63 boost::system::error_code ec;
64 timer.expires_after(std::chrono::seconds{5});
65 auto const addrs = co_await (resv.async_resolve(host, port) || timer.async_wait(redir(ec)));
66 if (!ec)
67 throw std::runtime_error("Resolve timeout");
68
69 timer.expires_after(std::chrono::seconds{5});
70 co_await (net::async_connect(conn->next_layer(), std::get<0>(addrs)) || timer.async_wait(redir(ec)));
71 if (!ec)
72 throw std::runtime_error("Connect timeout");
73}
74
75#endif // defined(BOOST_ASIO_HAS_CO_AWAIT)
Creates Redis requests.
Definition: request.hpp:176
auto adapt(std::size_t max_read_size=(std::numeric_limits< std::size_t >::max)()) noexcept
Creates an adapter that ignores responses.
Definition: adapt.hpp:199
operation
Connection operations that can be cancelled.
Definition: operation.hpp:18