srs-control 0.2.2
Loading...
Searching...
No Matches
SpecialSocketBase.hpp
Go to the documentation of this file.
1#pragma once
2
7#include <asio/as_tuple.hpp>
8#include <asio/awaitable.hpp>
9#include <asio/buffer.hpp>
10#include <asio/experimental/awaitable_operators.hpp>
11#include <asio/system_timer.hpp>
12#include <asio/this_coro.hpp>
13#include <asio/use_awaitable.hpp>
14#include <asio/use_future.hpp>
15#include <chrono>
16#include <concepts>
17#include <cstddef>
18#include <cstdint>
19#include <expected>
20#include <fmt/ranges.h>
21#include <future>
22#include <memory>
23#include <optional>
24#include <spdlog/spdlog.h>
25#include <system_error>
26#include <type_traits>
27#include <utility>
28#include <variant>
29
30namespace srs
31{
32 class AppReport;
33}
34
35namespace srs::connection
36{
37 class SpecialSocket;
38
39 template <typename SocketType>
41 requires(SocketType socket, std::shared_ptr<typename SocketType::ConnectionType> connection) {
42 requires std::derived_from<SocketType, SpecialSocket>;
43 requires not std::is_same_v<SocketType, SpecialSocket>;
44
45 asio::mutable_buffer{ socket.get_response_msg_buffer() };
46
48
49 { socket.response_handler(UDPEndpoint{}, std::size_t{}) } -> std::same_as<void>;
50 { socket.is_finished() } -> std::same_as<bool>;
51 { socket.print_error() } -> std::same_as<void>;
52 { socket.register_send_action_imp(asio::awaitable<void>{}, connection) } -> std::same_as<void>;
53 };
54
58 class SpecialSocket : public std::enable_shared_from_this<SpecialSocket>
59 {
60 public:
61 template <SpecialSocketDerived SocketType, typename... Args>
62 static auto create(int port_number, io_context_type& io_context, Args&&... args)
63 -> std::expected<std::shared_ptr<SocketType>, std::error_code>;
64
75 this auto&& self,
76 asio::awaitable<void> action,
77 const std::shared_ptr<typename std::remove_cvref_t<decltype(self)>::ConnectionType>& connection);
78
85 void listen(this auto& self, io_context_type& io_context);
86
95 auto cancel_listen_after(this auto&& self,
96 io_context_type& io_context,
97 std::chrono::seconds waiting_time = std::chrono::seconds(2)) -> std::future<void>;
98
105 auto wait_for_listen_finish(std::chrono::seconds time) -> std::optional<std::future_status>;
106
107 void set_report(AppReport* report) { report_ = report; }
109
110 // getters:
111
117 [[nodiscard]] auto get_socket() const -> udp::socket& { return *socket_; }
118
124 [[nodiscard]] auto get_port() const -> int { return port_number_; }
125
131 auto get_future() -> auto& { return listen_future_; }
132
138 auto get_n_records() const -> std::size_t { return n_records_; }
139
145 auto get_n_bytes() const -> std::size_t { return n_bytes; }
146
152 auto get_total_time_ns() const -> std::uint64_t { return total_time_ns_; }
153
154 auto get_report() -> auto* { return report_; }
155
156 protected:
163 explicit SpecialSocket(int port_number, io_context_type& io_context);
164 auto get_cancel_timer() -> auto& { return cancel_timer_; };
165
166 private:
168 AppReport* report_ = nullptr;
169 std::unique_ptr<udp::socket> socket_;
170 std::shared_future<std::variant<std::monostate, std::monostate>> listen_future_;
171 asio::system_timer cancel_timer_;
172
173 // for the time measurement
174 [[maybe_unused]] std::chrono::steady_clock clock_;
175 std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> time_point_;
176 std::size_t n_records_ = 0;
177 std::size_t n_bytes = 0;
178 std::uint64_t total_time_ns_ = 0;
179
180 auto cancel_coroutine() -> asio::awaitable<void>;
181 auto bind_socket() -> std::error_code;
182 auto close_socket() -> std::error_code;
183
184 // NOTE: Coroutine should always be static to avoid lifetime issue.
185 template <SpecialSocketDerived SocketType>
186 static auto async_listen_all_connections(std::shared_ptr<SocketType> socket) -> asio::awaitable<void>;
187 };
188
189 template <SpecialSocketDerived SocketType, typename... Args>
190 auto SpecialSocket::create(int port_number, io_context_type& io_context, Args&&... args)
191 -> std::expected<std::shared_ptr<SocketType>, std::error_code>
192 {
193 auto socket =
194 std::shared_ptr<SocketType>(new SocketType{ port_number, io_context, std::forward<Args>(args)... });
195 auto error_code = socket->bind_socket();
196 if (error_code)
197 {
198 spdlog::critical("Local socket failed to bind to the port {} due to the error: {}",
199 socket->get_port(),
200 error_code.message());
201 return std::unexpected{ error_code };
202 }
203 socket->listen(io_context);
204 return socket;
205 }
206
207 template <SpecialSocketDerived SocketType>
208 auto SpecialSocket::async_listen_all_connections(std::shared_ptr<SocketType> socket) -> asio::awaitable<void>
209 {
210 const auto port_str = fmt::format("{}", socket->get_port());
211 const auto _ = ExitLogger{ port_str };
212 auto remote_endpoint = udp::endpoint{};
213 spdlog::debug("Local socket with endpoint {} starts to listen ...", socket->get_socket().local_endpoint());
214 while (true)
215 {
216 const auto [err_code, receive_size] = co_await socket->get_socket().async_receive_from(
217 asio::mutable_buffer{ socket->get_response_msg_buffer() },
218 remote_endpoint,
219 asio::as_tuple(asio::use_awaitable));
220
221 socket->time_point_ = socket->clock_.now();
222
223 if (not err_code)
224 {
225 socket->response_handler(remote_endpoint, receive_size);
226 }
227 else
228 {
229 break;
230 }
231
232 ++socket->n_records_;
233 socket->n_bytes += receive_size;
234 socket->total_time_ns_ += static_cast<uint64_t>((socket->clock_.now() - socket->time_point_).count());
235 }
236
237 socket->before_socket_close();
238 if (auto err = socket->close_socket(); err)
239 {
240 spdlog::error("Error occurred when closing the socket with local endpoint {}: {}",
241 socket->get_socket().local_endpoint(),
242 err.message());
243 }
244 // TODO: close the socket here
245 spdlog::trace("Coroutine for the local socket with port {} has existed.", socket->get_port());
246 co_return;
247 }
248
250 this auto&& self,
251 asio::awaitable<void> action,
252 const std::shared_ptr<typename std::remove_cvref_t<decltype(self)>::ConnectionType>& connection)
253 {
254 spdlog::trace("Registering send action from connection {} with remote endpoint {}.",
255 connection->get_name(),
256 connection->get_remote_endpoint());
257 self.register_send_action_imp(std::move(action), connection);
258 spdlog::trace("Send action to the remote endpoint {} has been registered.",
259 connection->get_name(),
260 connection->get_remote_endpoint());
261 }
262
263 void SpecialSocket::listen(this auto& self, io_context_type& io_context)
264 {
265 using asio::experimental::awaitable_operators::operator||;
266 self.listen_future_ =
267 asio::co_spawn(io_context,
268 async_listen_all_connections(common::get_shared_from_this(self)) || self.cancel_coroutine(),
269 asio::use_future)
270 .share();
271 }
272
274 io_context_type& io_context,
275 std::chrono::seconds waiting_time) -> std::future<void>
276 {
277 auto waiting_action = [](auto socket, std::chrono::seconds waiting_time) -> asio::awaitable<void>
278 {
279 auto is_finished = false;
280 spdlog::trace("Waiting local socket with port {} to finish listening ...", socket->get_port());
281 auto timer = asio::system_timer{ co_await asio::this_coro::executor };
282 if (socket->is_finished())
283 {
284 spdlog::trace("Local socket with port {} finished listening and is cancelled immediately.",
285 socket->get_port());
286 timer.expires_after(std::chrono::seconds(0));
287 is_finished = true;
288 }
289 else
290 {
291 timer.expires_after(waiting_time);
292 }
293 [[maybe_unused]] auto err_code = co_await timer.async_wait(asio::as_tuple(asio::use_awaitable));
294 socket->cancel_timer_.cancel();
295 if (not is_finished and not socket->is_finished())
296 {
297 socket->print_error();
298 }
299 };
300 return asio::co_spawn(
301 io_context, waiting_action(common::get_shared_from_this(self), waiting_time), asio::use_future);
302 }
303} // namespace srs::connection
Base socket class for sending and listening messages.
auto cancel_listen_after(this auto &&self, io_context_type &io_context, std::chrono::seconds waiting_time=std::chrono::seconds(2)) -> std::future< void >
Cancelling the listening action after a certain time.
asio::system_timer cancel_timer_
Used for cancel the unfinished coroutine.
auto cancel_coroutine() -> asio::awaitable< void >
auto get_total_time_ns() const -> std::uint64_t
Getter for the total listening time in nano seconds.
auto get_n_records() const -> std::size_t
Getter for the number of frames read.
static auto create(int port_number, io_context_type &io_context, Args &&... args) -> std::expected< std::shared_ptr< SocketType >, std::error_code >
std::chrono::steady_clock clock_
auto wait_for_listen_finish(std::chrono::seconds time) -> std::optional< std::future_status >
Blocking the current thread by waiting the listen action to finish until a certain time duration.
auto close_socket() -> std::error_code
std::chrono::time_point< std::chrono::steady_clock, std::chrono::nanoseconds > time_point_
auto bind_socket() -> std::error_code
std::unique_ptr< udp::socket > socket_
void set_report(AppReport *report)
auto get_future() -> auto &
Getter for the status of the listen action.
void listen(this auto &self, io_context_type &io_context)
Listen to any UDP data.
static auto async_listen_all_connections(std::shared_ptr< SocketType > socket) -> asio::awaitable< void >
auto get_n_bytes() const -> std::size_t
Getter for the number of bytes read.
SpecialSocket(int port_number, io_context_type &io_context)
Projected constructor, which can only be called from the derived classes.
auto get_port() const -> int
Getter for the port number.
void register_send_action(this auto &&self, asio::awaitable< void > action, const std::shared_ptr< typename std::remove_cvref_t< decltype(self)>::ConnectionType > &connection)
Registering the send action.
std::shared_future< std::variant< std::monostate, std::monostate > > listen_future_
auto get_socket() const -> udp::socket &
Getter for the asio udp socket object.
constexpr auto get_shared_from_this(auto &&obj)
asio::ip::basic_endpoint< asio::ip::udp > UDPEndpoint
asio::thread_pool io_context_type