Boost.Redis: include/boost/redis/detail/connector.hpp Source File

Boost.Redis 1.84.0 A redis client library

Loading...
Searching...
No Matches
connector.hpp
1/* Copyright (c) 2018-2024 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#ifndef BOOST_REDIS_CONNECTOR_HPP
8#define BOOST_REDIS_CONNECTOR_HPP
9
10#include <boost/redis/detail/helper.hpp>
11#include <boost/redis/error.hpp>
12#include <boost/asio/compose.hpp>
13#include <boost/asio/connect.hpp>
14#include <boost/asio/coroutine.hpp>
15#include <boost/asio/ip/tcp.hpp>
16#include <boost/asio/cancel_after.hpp>
17#include <string>
18#include <chrono>
19
20namespace boost::redis::detail
21{
22
23template <class Connector, class Stream>
24struct connect_op {
25 Connector* ctor_ = nullptr;
26 Stream* stream = nullptr;
27 asio::ip::tcp::resolver::results_type const* res_ = nullptr;
28 asio::coroutine coro{};
29
30 template <class Self>
31 void operator()( Self& self
32 , system::error_code const& ec = {}
33 , asio::ip::tcp::endpoint const& ep= {})
34 {
35 BOOST_ASIO_CORO_REENTER (coro)
36 {
37 BOOST_ASIO_CORO_YIELD
38 asio::async_connect(*stream, *res_,
39 [](system::error_code const&, auto const&) { return true; },
40 asio::cancel_after(ctor_->timeout_, std::move(self)));
41
42 ctor_->endpoint_ = ep;
43
44 if (ec == asio::error::operation_aborted) {
45 self.complete(redis::error::connect_timeout);
46 } else {
47 self.complete(ec);
48 }
49 }
50 }
51};
52
53class connector {
54public:
55 void set_config(config const& cfg)
56 { timeout_ = cfg.connect_timeout; }
57
58 template <class Stream, class CompletionToken>
59 auto
60 async_connect(
61 Stream& stream,
62 asio::ip::tcp::resolver::results_type const& res,
63 CompletionToken&& token)
64 {
65 return asio::async_compose
66 < CompletionToken
67 , void(system::error_code)
68 >(connect_op<connector, Stream>{this, &stream, &res}, token);
69 }
70
71 auto const& endpoint() const noexcept { return endpoint_;}
72
73private:
74 template <class, class> friend struct connect_op;
75
76 std::chrono::steady_clock::duration timeout_ = std::chrono::seconds{2};
77 asio::ip::tcp::endpoint endpoint_;
78};
79
80} // boost::redis::detail
81
82#endif // BOOST_REDIS_CONNECTOR_HPP
boost::redis::error::connect_timeout
@ connect_timeout
Connect timeout.