srs-control 0.2.2
Loading...
Searching...
No Matches
FecSwitchSocket.cpp
Go to the documentation of this file.
1#include "FecSwitchSocket.hpp"
2#include "srs/connections/ConnectionBase.hpp" // IWYU pragma: keep
7#include "srs/utils/UDPFormatters.hpp" // IWYU pragma: keep
8#include <algorithm>
9#include <asio/awaitable.hpp>
10#include <asio/deferred.hpp>
11#include <asio/detached.hpp>
12#include <asio/experimental/cancellation_condition.hpp>
13#include <asio/experimental/parallel_group.hpp>
14#include <asio/impl/co_spawn.hpp>
15#include <asio/strand.hpp>
16#include <asio/use_future.hpp>
17#include <chrono>
18#include <cstddef>
19#include <fmt/base.h>
20#include <fmt/format.h>
21#include <fmt/ranges.h>
22#include <memory>
23#include <mutex>
24#include <ranges>
25#include <span>
26#include <spdlog/spdlog.h>
27#include <string>
28#include <utility>
29
30namespace srs::connection
31{
32 namespace
33 {
34 auto remove_once_if(auto& connections, auto unitary_opt) -> bool
35 {
36 auto iter = std::ranges::find_if(
37 connections, [unitary_opt](const auto& connection) -> bool { return not unitary_opt(connection); });
38 if (iter == connections.end())
39 {
40 return false;
41 }
42 std::iter_swap(iter, connections.end() - 1);
43 connections.pop_back();
44 return true;
45 }
46
47 auto print_connections(const auto& connections) -> std::string
48 {
49 auto join_connection = [](const auto& connection)
50 { return fmt::format("{:02x}", fmt::join(connection->get_response_msg(), " ")); };
51 return fmt::format("{}", fmt::join(connections | std::views::transform(join_connection), "\n\t"));
52 }
53 } // namespace
54
56 : SpecialSocket{ port_number, io_context }
57 , strand_{ asio::make_strand(io_context.get_executor()) }
58
59 {
61 }
62
63 void FecCommandSocket::register_send_action_imp(asio::awaitable<void> action,
64 const std::shared_ptr<SmallConnection>& connection)
65 {
66 auto co_action = asio::co_spawn(strand_, std::move(action), asio::deferred);
67 action_queue_.push_back(std::move(co_action));
68
69 auto lock = std::lock_guard{ mut_ };
70 const auto& remote_endpoint = connection->get_remote_endpoint();
71 auto& connections = all_connections_.try_emplace(remote_endpoint, SmallConnections{}).first->second;
72 connections.push_back(connection);
73 }
74
76 {
77 start_time_ = std::chrono::steady_clock::now();
78
79 // NOTE: Use the make_parallel_group causes the thread sanitizer reporting a possible data racing, but has the
80 // fastest sending sequence. Use detached or use_future inside a for loop prevents the reporting, but has slower
81 // sending sequence. Possible a false positive from the thread sanitizer.
82
83 asio::experimental::make_parallel_group(std::move(action_queue_))
84 .async_wait(asio::experimental::wait_for_all(), asio::detached);
85 // [[maybe_unused]] auto res = asio::experimental::make_parallel_group(std::move(action_queue_))
86 // .async_wait(asio::experimental::wait_for_all(), asio::use_future)
87 // .get();
88
89 // for (auto& action : action_queue_)
90 // {
91 // std::move(action)(asio::detached);
92 // }
93 }
94
96 std::span<char> response,
97 SmallConnections& connections)
98 {
99 if (connections.empty())
100 {
101 spdlog::debug("Response from the remote endpoint {} to the local endpoint {} is received. But no further "
102 "message from the endpoint is not required anymore!",
103 endpoint,
104 get_socket().local_endpoint());
105 return;
106 }
107 auto res = remove_once_if(connections,
108 [response](const std::shared_ptr<SmallConnection>& connection) -> bool
109 {
110 auto is_same = connection->check_response(response);
111 return not is_same;
112 });
113 if (res)
114 {
115 spdlog::debug("Response from the remote endpoint {} is recognized by the local endpoint {}",
116 endpoint,
117 get_socket().local_endpoint());
118 // print_available_responses();
119 }
120 else
121 {
122 spdlog::warn("From remote endpoint {}, socket with local endpoint {} received an unrecognized msg: {:02x}",
123 endpoint,
124 get_socket().local_endpoint(),
125 fmt::join(response, " "));
127 }
128 }
129
131 {
132 spdlog::info(
133 "Available responses are:\n\t{}",
134 fmt::join(all_connections_ | std::views::values |
135 std::views::filter([](const auto& connections) -> bool { return not connections.empty(); }) |
136 std::views::transform([](const auto& connections) { return print_connections(connections); }),
137 "\n\t"));
138 }
139
141 {
142 fmt::println("");
143 spdlog::error("TIMEOUT from local port {} waiting for the response(s):\n\t{}",
144 get_port(),
145 fmt::join(all_connections_ |
146 std::views::filter([](const auto& key_value) -> bool
147 { return not key_value.second.empty(); }) |
148 std::views::transform(
149 [](const auto& key_value)
150 {
151 return fmt::format("Remote endpoint:\t{}\n\tExpected Response:\t{}",
152 key_value.first,
153 print_connections(key_value.second));
154 }),
155 "\n\t"));
156 }
157
158 void FecCommandSocket::response_handler(const UDPEndpoint& endpoint, std::size_t read_size)
159 {
160 auto lock = std::lock_guard{ mut_ };
161 auto response = std::span{ read_msg_buffer_.data(), read_size };
162 spdlog::trace("Local port {} received a response from a remote endpoint {}: \n\t{:02x}",
163 get_port(),
164 endpoint,
165 fmt::join(response, " "));
166 auto connections_iter = all_connections_.find(endpoint);
167 if (connections_iter == all_connections_.end())
168 {
169 spdlog::error("Local socket with port {} received an unknown remote endpoint: {}", get_port(), endpoint);
170 return;
171 }
172 deregister_connection(endpoint, response, connections_iter->second);
173 }
174
176 {
177
178 return std::ranges::all_of(all_connections_ | std::views::values,
179 [](const auto& connections) -> bool { return connections.empty(); });
180 }
181
183 {
184 if (auto* report = get_report(); report != nullptr)
185 {
186 report->register_switch_socket_result(fmt::format("{}", get_socket().local_endpoint()),
187 std::move(time_stamps_));
188 }
189 }
190} // namespace srs::connection
FecCommandSocket(int port_number, io_context_type &io_context)
void deregister_connection(const UDPEndpoint &endpoint, std::span< char > response, SmallConnections &connections)
std::map< UDPEndpoint, SmallConnections > all_connections_
std::vector< ActionType > action_queue_
void response_handler(const UDPEndpoint &endpoint, std::size_t read_size)
void register_send_action_imp(asio::awaitable< void > action, const std::shared_ptr< SmallConnection > &connection)
asio::strand< io_context_type::executor_type > strand_
std::chrono::time_point< std::chrono::steady_clock > start_time_
std::vector< std::pair< std::string, AppReport::FecSwitchStat > > time_stamps_
std::vector< std::shared_ptr< SmallConnection > > SmallConnections
auto get_port() const -> int
Getter for the port number.
auto get_socket() const -> udp::socket &
Getter for the asio udp socket object.
constexpr auto SMALL_READ_MSG_BUFFER_SIZE
asio::ip::basic_endpoint< asio::ip::udp > UDPEndpoint
asio::thread_pool io_context_type