SNode.C
Loading...
Searching...
No Matches
SocketClient.h
Go to the documentation of this file.
1/*
2 * SNode.C - A Slim Toolkit for Network Communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#ifndef CORE_SOCKET_STREAM_SOCKETCLIENT_H
43#define CORE_SOCKET_STREAM_SOCKETCLIENT_H
44
45#include "core/SNodeC.h"
46#include "core/socket/Socket.h" // IWYU pragma: export
47#include "core/socket/State.h" // IWYU pragma: export
48#include "core/socket/stream/SocketContextFactory.h"
49#include "core/timer/Timer.h"
50
51#ifndef DOXYGEN_SHOULD_SKIP_THIS
52
53#include "log/Logger.h"
54#include "utils/Random.h"
55
56#include <algorithm>
57#include <functional> // IWYU pragma: export
58
59#endif /* DOXYGEN_SHOULD_SKIP_THIS */
60
61namespace core::socket::stream {
62
63 /** Sequence diagram showing how a connect to a peer is performed.
64 @startuml
65 !include core/socket/stream/pu/SocketClient.pu
66 @enduml
67 */
68 template <typename SocketConnectorT, typename SocketContextFactoryT, typename... Args>
69 requires std::is_base_of_v<core::socket::stream::SocketContextFactory, SocketContextFactoryT>
70 class SocketClient : public core::socket::Socket<typename SocketConnectorT::Config> {
71 private:
72 using SocketConnector = SocketConnectorT;
73 using SocketContextFactory = SocketContextFactoryT;
74
75 using Super = core::socket::Socket<typename SocketConnector::Config>;
76
77 public:
78 using SocketConnection = typename SocketConnector::SocketConnection;
79 using SocketAddress = typename SocketConnector::SocketAddress;
80
81 SocketClient(const std::string& name,
82 const std::function<void(SocketConnection*)>& onConnect,
83 const std::function<void(SocketConnection*)>& onConnected,
84 const std::function<void(SocketConnection*)>& onDisconnect,
85 Args&&... args)
86 : Super(name)
87 , socketContextFactory(std::make_shared<SocketContextFactory>(std::forward<Args>(args)...))
88 , onConnect(onConnect)
89 , onConnected(onConnected)
90 , onDisconnect(onDisconnect) {
91 }
92
93 SocketClient(const std::function<void(SocketConnection*)>& onConnect,
94 const std::function<void(SocketConnection*)>& onConnected,
95 const std::function<void(SocketConnection*)>& onDisconnect,
96 Args&&... args)
97 : SocketClient("", onConnect, onConnected, onDisconnect, std::forward<Args>(args)...) {
98 }
99
100 // VLOG() is used hire as this are log messages for the application
101 SocketClient(const std::string& name, Args&&... args)
102 : SocketClient(
103 name,
104 [name](SocketConnection* socketConnection) { // onConnect
105 VLOG(2) << name << ": OnConnect";
106
107 VLOG(2) << " Local: " << socketConnection->getLocalAddress().toString();
108 VLOG(2) << " Peer: " << socketConnection->getRemoteAddress().toString();
109 },
110 [name](SocketConnection* socketConnection) { // onConnected
111 VLOG(2) << name << ": OnConnected ";
112
113 VLOG(2) << " Local: " << socketConnection->getLocalAddress().toString();
114 VLOG(2) << " Peer: " << socketConnection->getRemoteAddress().toString();
115 },
116 [name](SocketConnection* socketConnection) { // onDisconnect
117 VLOG(2) << name << ": OnDisconnect ";
118
119 VLOG(2) << " Local: " << socketConnection->getLocalAddress().toString();
120 VLOG(2) << " Peer: " << socketConnection->getRemoteAddress().toString();
121 },
122 std::forward<Args>(args)...) {
123 }
124
125 explicit SocketClient(Args&&... args)
126 : SocketClient("", std::forward<Args>(args)...) {
127 }
128
129 private:
130 void realConnect(const std::function<void(const SocketAddress&, core::socket::State)>& onStatus,
131 unsigned int tries,
132 double retryTimeoutScale) const {
134 new SocketConnector(
136 onConnect,
138 [client = *this, onStatus](SocketConnection* socketConnection) {
139 client.onDisconnect(socketConnection);
140
141 if (client.getConfig().getReconnect() && core::eventLoopState() == core::State::RUNNING) {
142 double relativeReconnectTimeout = client.getConfig().getReconnectTime();
143
144 LOG(INFO) << client.getConfig().getInstanceName() << ": OnStatus";
145 LOG(INFO) << " reconnecting in " << relativeReconnectTimeout << " seconds";
146
148 [client, onStatus]() {
149 client.getConfig().Local::renew();
150 client.getConfig().Remote::renew();
151
152 client.realConnect(onStatus, 0, 1);
153 },
154 relativeReconnectTimeout);
155 }
156 },
157 [client = *this, onStatus, tries, retryTimeoutScale](const SocketAddress& socketAddress, core::socket::State state) {
158 bool retry = (state & core::socket::State::NO_RETRY) == 0 &&
159 (client.getConfig().getRetryTries() == 0 || tries < client.getConfig().getRetryTries());
160 state &= ~core::socket::State::NO_RETRY;
161
162 onStatus(socketAddress, state);
163
164 switch (state) {
165 case core::socket::State::OK:
166 [[fallthrough]];
167 case core::socket::State::DISABLED:
168 retry = false;
169 break;
170 case core::socket::State::ERROR:
171 retry = retry && client.getConfig().getRetry();
172 break;
173 case core::socket::State::FATAL:
174 retry = retry && client.getConfig().getRetry() && client.getConfig().getRetryOnFatal();
175 break;
176 }
177
178 if (retry) {
179 double relativeRetryTimeout = client.getConfig().getRetryLimit() > 0
180 ? std::min<double>(client.getConfig().getRetryTimeout() * retryTimeoutScale,
181 client.getConfig().getRetryLimit())
182 : client.getConfig().getRetryTimeout() * retryTimeoutScale;
183 relativeRetryTimeout -=
184 utils::Random::getInRange(-client.getConfig().getRetryJitter(), client.getConfig().getRetryJitter()) *
185 relativeRetryTimeout / 100.;
186
187 LOG(INFO) << client.getConfig().getInstanceName() << ": OnStatus";
188 LOG(INFO) << " retrying in " << relativeRetryTimeout << " seconds";
189
191 [client, onStatus, tries, retryTimeoutScale]() mutable {
192 client.getConfig().Local::renew();
193 client.getConfig().Remote::renew();
194
195 client.realConnect(onStatus, tries + 1, retryTimeoutScale * client.getConfig().getRetryBase());
196 },
197 relativeRetryTimeout);
198 }
199 },
200 Super::config);
201 }
202 }
203
204 public:
205 void connect(const std::function<void(const SocketAddress&, core::socket::State)>& onStatus) const {
206 realConnect(onStatus, 0, 1);
207 }
208
209 void connect(const SocketAddress& remoteAddress,
210 const std::function<void(const SocketAddress&, core::socket::State)>& onStatus) const {
211 Super::config->Remote::setSocketAddress(remoteAddress);
212
213 connect(onStatus);
214 }
215
216 void connect(const SocketAddress& remoteAddress,
217 const SocketAddress& localAddress,
218 const std::function<void(const SocketAddress&, core::socket::State)>& onStatus) const {
219 Super::config->Local::setSocketAddress(localAddress);
220
221 connect(remoteAddress, onStatus);
222 }
223
224 std::function<void(SocketConnection*)> setOnConnect(const std::function<void(SocketConnection*)>& onConnect) {
225 std::function<void(SocketConnection*)> oldOnConnect = this->onConnect;
226
227 this->onConnect = onConnect;
228
229 return oldOnConnect;
230 }
231
232 std::function<void(SocketConnection*)> setOnConnected(const std::function<void(SocketConnection*)>& onConnected) {
233 std::function<void(SocketConnection*)> oldOnConnected = this->onConnected;
234
235 this->onConnected = onConnected;
236
237 return oldOnConnected;
238 }
239
240 std::function<void(SocketConnection*)> setOnDisconnect(const std::function<void(SocketConnection*)>& onDisconnect) {
241 std::function<void(SocketConnection*)> oldOnDisconnect = this->onDisconnect;
242
243 this->onDisconnect = onDisconnect;
244
245 return oldOnDisconnect;
246 }
247
248 std::shared_ptr<SocketContextFactory> getSocketContextFactory() const {
250 }
251
252 private:
253 const std::shared_ptr<SocketContextFactory> socketContextFactory;
254
255 std::function<void(SocketConnection*)> onConnect;
256 std::function<void(SocketConnection*)> onConnected;
257 std::function<void(SocketConnection*)> onDisconnect;
258 };
259
260} // namespace core::socket::stream
261
262#endif // CORE_SOCKET_STREAM_SOCKETCLIENT_H
core::socket::stream::SocketContext * create(core::socket::stream::SocketConnection *socketConnection) override
web::http::client::ResponseParser * responseParser
SimpleSocketProtocol(core::socket::stream::SocketConnection *socketConnection)
void onReadError(int errnum) override
void onWriteError(int errnum) override
std::size_t onReceivedFromPeer() override
virtual void timeoutEvent()=0
DescriptorEventReceiver(const std::string &name, DescriptorEventPublisher &descriptorEventPublisher, const utils::Timeval &timeout=TIMEOUT::DISABLE)
void triggered(const utils::Timeval &currentTime)
virtual void dispatchEvent()=0
DescriptorEventPublisher & descriptorEventPublisher
void setEnabled(const utils::Timeval &currentTime)
void onEvent(const utils::Timeval &currentTime) final
void setTimeout(const utils::Timeval &timeout)
virtual void signalEvent(int signum)=0
void checkTimeout(const utils::Timeval &currentTime)
utils::Timeval getTimeout(const utils::Timeval &currentTime) const
const std::string & getName() const
virtual void destruct()
static void atNextTick(const std::function< void(void)> &callBack)
virtual void onEvent(const utils::Timeval &currentTime)=0
EventReceiver & operator=(EventReceiver &&)=delete
virtual ~EventReceiver()=default
EventReceiver(EventReceiver &)=delete
EventReceiver(const std::string &name)
EventReceiver(EventReceiver &&)=delete
EventReceiver & operator=(EventReceiver &)=delete
bool published
Definition Event.h:83
void span()
Definition Event.cpp:64
const std::string & getName() const
Definition Event.cpp:78
void dispatch(const utils::Timeval &currentTime)
Definition Event.cpp:82
EventMultiplexer & eventMultiplexer
Definition Event.h:81
EventReceiver * eventReceiver
Definition Event.h:80
std::string name
Definition Event.h:78
Event(EventReceiver *eventReceiver, const std::string &name)
Definition Event.cpp:54
EventReceiver * getEventReceiver() const
Definition Event.cpp:87
void relax()
Definition Event.cpp:71
Observer(Observer &&)=delete
Observer()=default
Observer(Observer &)=delete
virtual void unobservedEvent()=0
static void init(int argc, char *argv[])
Definition SNodeC.cpp:54
static State state()
Definition SNodeC.cpp:76
static int start(const utils::Timeval &timeOut={LONG_MAX, 0})
Definition SNodeC.cpp:60
ConnectEventReceiver(const std::string &name, const utils::Timeval &timeout)
ReadEventReceiver(const std::string &name, const utils::Timeval &timeout)
WriteEventReceiver(const std::string &name, const utils::Timeval &timeout)
Config & getConfig() const
Definition Socket.hpp:60
State & operator^=(int state)
Definition State.cpp:96
State & operator&=(int state)
Definition State.cpp:90
operator int() const
Definition State.cpp:70
static constexpr int DISABLED
Definition State.h:56
bool operator==(const int &state) const
Definition State.cpp:74
State operator&(int state)
Definition State.cpp:106
State & operator=(int state)
Definition State.cpp:78
static constexpr int ERROR
Definition State.h:57
std::string what() const
Definition State.cpp:114
static constexpr int FATAL
Definition State.h:58
static constexpr int OK
Definition State.h:55
State(const int &state, const std::string &file, const int &line)
Definition State.cpp:54
std::string errstr
Definition State.h:95
State operator^(int state)
Definition State.cpp:110
State(const int &state, const std::string &file, const int &line, int errnum, const std::string &errstr)
Definition State.cpp:62
std::string where() const
Definition State.cpp:134
static constexpr int NO_RETRY
Definition State.h:59
State operator|(int state)
Definition State.cpp:102
std::string file
Definition State.h:91
State & operator|=(int state)
Definition State.cpp:84
SocketClient(const std::string &name, const std::function< void(SocketConnection *)> &onConnect, const std::function< void(SocketConnection *)> &onConnected, const std::function< void(SocketConnection *)> &onDisconnect, Args &&... args)
void connect(const SocketAddress &remoteAddress, const SocketAddress &localAddress, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
const std::shared_ptr< SocketContextFactory > socketContextFactory
std::function< void(SocketConnection *)> setOnConnect(const std::function< void(SocketConnection *)> &onConnect)
std::function< void(SocketConnection *)> setOnDisconnect(const std::function< void(SocketConnection *)> &onDisconnect)
SocketClient(const std::string &name, Args &&... args)
void connect(const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
std::function< void(SocketConnection *)> onConnect
std::shared_ptr< SocketContextFactory > getSocketContextFactory() const
SocketClient(const std::function< void(SocketConnection *)> &onConnect, const std::function< void(SocketConnection *)> &onConnected, const std::function< void(SocketConnection *)> &onDisconnect, Args &&... args)
std::function< void(SocketConnection *)> onDisconnect
void connect(const SocketAddress &remoteAddress, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
std::function< void(SocketConnection *)> setOnConnected(const std::function< void(SocketConnection *)> &onConnected)
std::function< void(SocketConnection *)> onConnected
void realConnect(const std::function< void(const SocketAddress &, core::socket::State)> &onStatus, unsigned int tries, double retryTimeoutScale) const
void onReceivedFromPeer(std::size_t available) final
void setTimeout(const utils::Timeval &timeout) final
std::size_t readFromPeer(char *chunk, std::size_t chunkLen) final
const SocketAddress & getRemoteAddress() const final
SocketConnectionT(const std::string &instanceName, PhysicalSocket &&physicalSocket, const std::function< void()> &onDisconnect, const std::string &configuredServer, const SocketAddress &localAddress, const SocketAddress &remoteAddress, const utils::Timeval &readTimeout, const utils::Timeval &writeTimeout, std::size_t readBlockSize, std::size_t writeBlockSize, const utils::Timeval &terminateTimeout)
void doWriteShutdown(const std::function< void()> &onShutdown) override
bool streamToPeer(core::pipe::Source *source) final
void shutdownWrite(bool forceClose) final
void sendToPeer(const char *chunk, std::size_t chunkLen) final
const SocketAddress & getLocalAddress() const final
const std::string & getConfiguredServer() const
virtual void sendToPeer(const char *chunk, std::size_t chunkLen)=0
core::socket::stream::SocketContext * newSocketContext
core::socket::stream::SocketContext * socketContext
void connectSocketContext(const std::shared_ptr< SocketContextFactory > &socketContextFactory)
void switchSocketContext(SocketContext *newSocketContext)
virtual const core::socket::SocketAddress & getLocalAddress() const =0
virtual void setTimeout(const utils::Timeval &timeout)=0
void sentToPeer(const std::vector< char > &data)
void sentToPeer(const std::vector< uint8_t > &data)
const std::string & getConnectionName() const
void setSocketContext(SocketContext *socketContext)
virtual const core::socket::SocketAddress & getRemoteAddress() const =0
void sendToPeer(const std::string &data)
virtual void shutdownWrite(bool forceClose)=0
virtual std::size_t readFromPeer(char *chunk, std::size_t chunkLen)=0
SocketConnection(const std::string &instanceName, int fd, const std::string &configuredServer)
virtual bool streamToPeer(core::pipe::Source *source)=0
const std::string & getInstanceName() const
SocketConnector(const SocketConnector &socketConnector)
std::function< void(const SocketAddress &, core::socket::State)> onStatus
std::function< void(SocketConnection *)> onConnected
std::shared_ptr< core::socket::stream::SocketContextFactory > socketContextFactory
std::function< void(SocketConnection *)> onDisconnect
std::function< void(SocketConnection *)> onConnect
SocketConnector(const std::shared_ptr< core::socket::stream::SocketContextFactory > &socketContextFactory, const std::function< void(SocketConnection *)> &onConnect, const std::function< void(SocketConnection *)> &onConnected, const std::function< void(SocketConnection *)> &onDisconnect, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus, const std::shared_ptr< Config > &config)
SocketContext(core::socket::stream::SocketConnection *socketConnection)
void onReadError(int errnum) override
void shutdownWrite(bool forceClose=false)
void onWriteError(int errnum) override
void signalEvent(int sigNum) final
SocketReader(const std::string &instanceName, const std::function< void(int)> &onStatus, const utils::Timeval &timeout, std::size_t blockSize, const utils::Timeval &terminateTimeout)
std::size_t readFromPeer(char *chunk, std::size_t chunkLen)
void setBlockSize(std::size_t readBlockSize)
virtual void onReceivedFromPeer(std::size_t available)=0
virtual ssize_t read(char *chunk, std::size_t chunkLen)
std::function< void(int)> onStatus
virtual void doWriteShutdown(const std::function< void()> &onShutdown)=0
std::function< void(int)> onStatus
void setBlockSize(std::size_t writeBlockSize)
void sendToPeer(const char *chunk, std::size_t chunkLen)
void signalEvent(int sigNum) final
std::function< void()> onShutdown
virtual bool onSignal(int sigNum)=0
void shutdownWrite(const std::function< void()> &onShutdown)
bool streamToPeer(core::pipe::Source *source)
virtual ssize_t write(const char *chunk, std::size_t chunkLen)
SocketWriter(const std::string &instanceName, const std::function< void(int)> &onStatus, const utils::Timeval &timeout, std::size_t blockSize, const utils::Timeval &terminateTimeout)
SocketConnection(const std::string &instanceName, PhysicalSocket &&physicalSocket, const std::function< void(SocketConnection *)> &onDisconnect, const std::string &configuredServer, const SocketAddress &localAddress, const SocketAddress &remoteAddress, const utils::Timeval &readTimeout, const utils::Timeval &writeTimeout, std::size_t readBlockSize, std::size_t writeBlockSize, const utils::Timeval &terminateTimeout)
SocketConnector(const std::shared_ptr< core::socket::stream::SocketContextFactory > &socketContextFactory, const std::function< void(SocketConnection *)> &onConnect, const std::function< void(SocketConnection *)> &onConnected, const std::function< void(SocketConnection *)> &onDisconnect, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus, const std::shared_ptr< Config > &config)
SocketConnector(const SocketConnector &socketConnector)
static Timer singleshotTimer(const std::function< void()> &dispatcher, const utils::Timeval &timeout)
Definition Timer.cpp:57
const std::string & getInstanceName() const
SocketAddress(const std::string &ipOrHostname, uint16_t port)
std::string getCanonName() const
std::string toString(bool expanded=true) const override
void init(const Hints &hints={.aiFlags=0,.aiSockType=0,.aiProtocol=0})
void connect(const std::string &ipOrHostname, uint16_t port, const std::string &bindHost, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
void connect(const std::string &ipOrHostname, uint16_t port, const std::string &bindHost, uint16_t bindPort, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
void connect(const std::string &ipOrHostname, uint16_t port, uint16_t bindPort, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
void connect(const std::string &ipOrHostname, uint16_t port, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
static double getInRange(double ll, double ul)
Definition Random.cpp:52
std::size_t parse()
Definition Parser.cpp:92
ResponseParser(core::socket::stream::SocketContext *socketContext, const std::function< void()> &onResponseStart, const std::function< void(Response &&)> &onResponseParsed, const std::function< void(int, const std::string &)> &onResponseParseError)
int main(int argc, char *argv[])
static web::http::client::ResponseParser * getResponseParser(core::socket::stream::SocketContext *socketContext)
Definition Timer.h:59
State
Definition State.h:51
State eventLoopState()
Definition State.cpp:52
SocketClient getLegacyClient()
SocketClient getClient()