hmbdc
simplify-high-performance-messaging-programming
NetContext.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 #include "hmbdc/app/utils/NetContextUtil.hpp"
4 #include "hmbdc/app/Config.hpp"
5 #include "hmbdc/app/tcpcast/Messages.hpp"
6 #include "hmbdc/app/tcpcast/Sender.hpp"
7 #include "hmbdc/app/tcpcast/SendTransportEngine.hpp"
8 #include "hmbdc/app/tcpcast/RecvTransportEngine.hpp"
9 #include "hmbdc/app/tcpcast/DefaultUserConfig.hpp"
10 
11 #include "hmbdc/comm/Topic.hpp"
12 #include "hmbdc/pattern/GuardedSingleton.hpp"
13 
14 #include <boost/regex.hpp>
15 
16 #include <vector>
17 #include <mutex>
18 #include <memory>
19 
20 
21 /**
22  * @namespace hmbdc::app::tcpcast
23  * reliable tcpcast (based on TCP) transport
24  */
25 
26 namespace hmbdc { namespace app { namespace tcpcast {
27 
28 
29 /**
30 * @example chat.cpp
31 * @example perf-tcpcast.cpp
32 * @example rmcast-cp.cpp
33 * @example ping-pong-tcpcast.cpp
34 */
35 
36 /**
37  * @class NetContext
38  * @brief a singleton that holding tcpcast resources
39  * @details it manages transport engines
40  *
41  * see perf-tcpcast.cpp chat.cpp for usage.
42  *
43  */
44 struct NetContext
47 
48  friend struct hmbdc::pattern::SingletonGuardian<NetContext>;
50 
51 /**
52  * @brief construct a send transport enngine (and remember it)
53  * @details After this, user is responsible to get it started within a hmbdc Context,
54  * if running in Context pool, it needs to be pinned on a single pool thread, CANNOT span
55  * more than one thread, otherwise the transport is not functioing/running.
56  * Don't create the same thing twice.
57  *
58  * @param cfgIn jason specifing the transport - see perf-tcpcast.cpp and hmbdc/app/tcpcast/DefaultUserConfig.hpp
59  * @param maxMessageSize max messafe size in bytes to be sent
60  * hold the message in buffer
61  * @return a pointer to the Engine
62  */
64  Config const& cfgIn
65  , size_t maxMessageSize) {
66  Config dft(DefaultUserConfig, "tx");
67  Config cfg(cfgIn);
68  cfg.setDefaultUserConfig(dft);
69 
70  std::lock_guard<std::mutex> tlock(sendTransportEnginesLock_);
71  auto res = new SendTransportEngine(cfg, maxMessageSize);
72  sendTransports_.emplace_back(res);
73  return res;
74  }
75 
76 /**
77  * @brief same as above but provide an unified interface - not preferred
78  * @return a pointer to the Engine - don't delete it
79  */
81  , size_t maxMessageSize
82  , std::tuple<size_t> args) {
83  return createSendTransportEngine(cfg, maxMessageSize);
84  }
85 
86 /**
87  * @brief construct a send transport and remember it
88  * @details After this, user is respoonsible to get it started within a hmbdc Context,
89  * if running in Context pool, it needs to pin at a single pool thread, CANNOT span
90  * more than one thread
91  * otherwise the transport is not functioing/running. Don't create the same thing twice
92  *
93  * @param cfgIn jason specifing the transport - see perf-tcpcast.cpp and hmbdc/app/tcpcast/DefaultUserConfig.hpp
94  * @param buffer buffer that recv messages go, normally the one returned by app::Context::buffer()
95  * @param arb optonally an arbitrator to decide which messages to keep and drop
96  * if arb is an rvalue, it is passed in value, if an lvalue, passed in as reference;
97  * it supports ONLY hmbdc message level (AFTER topic filtering) arbitration if
98  * int operator()(TransportMessageHeader const* header) presents in the arb passed in.
99  * (NO packet level since it is tcp)
100  * @return a pointer to the Engine
101  */
102  template <typename Buffer, typename MsgArbitrator = RecvTransport::NoOpArb>
104  , Buffer& buffer
105  , MsgArbitrator&& arb = RecvTransport::NoOpArb()) {
106  Config dft(DefaultUserConfig, "rx");
107  Config cfg(cfgIn);
108  cfg.setDefaultUserConfig(dft);
109 
110  std::lock_guard<std::mutex> tlock(recvTransportsLock_);
112  cfg, buffer, std::forward<MsgArbitrator>(arb));
113  recvTransports_.emplace_back(res);
114  return res;
115  }
116 
117 /**
118  * @brief same as above but to provide a unified interface - not preferred
119  * @details use forward_as_tuple to make the tuple passed in
120  * @return a pointer to the Engine
121  */
122  template <typename Buffer, typename ArgsTuple>
124  Config const& cfg
125  , Buffer& buffer
126  , ArgsTuple&& args) {
127  return createRecvTransportEngine(cfg
128  , buffer
129  , std::get<0>(args)
130  );
131  }
132 
133 /**
134  * @brief get (or create for the first time) a Sender - whose function is to send messages on
135  * its associated Topic
136  * @details this operation typically might be slow, so caching the return value is recommended.
137  *
138  * @param t - the Topic that the Sender is for
139  */
140  Sender* getSender(comm::Topic const& t) {
141  std::lock_guard<std::mutex> lock(sendersLock_);
142  auto sender = senders_.find(t);
143  if ( sender != senders_.end()) {
144  return sender->second.get();
145  } else {
146  std::lock_guard<std::mutex> slock(sendTransportEnginesLock_);
147  for (auto i = 0u;
148  i < sendTransports_.size();
149  ++i) {
150  auto st = sendTransports_[i];
151  if (st->match(t)) {
152  auto newSender = new Sender(st, t);
153  senders_[t].reset(newSender);
154  return newSender;
155  }
156  }
157  }
158 
159  return nullptr;
160  }
161 
162 /**
163  * @brief This process is interested in a Topic
164  * @details Normally the receiving transport covering this topic
165  * needs to be created - not necessarily running - before calling this
166  *
167  * @param t Topic interested
168  */
169  void listenTo(comm::Topic const& t) {
170  std::lock_guard<std::mutex> tlock(recvTransportsLock_);
171  for (auto ptr : recvTransports_) {
172  ptr->listenTo(t);
173  }
174  }
175 
176 /**
177  * @brief undo the subscription
178  *
179  * @param t Topic
180  */
181  void stopListenTo(comm::Topic const& t) {
182  std::lock_guard<std::mutex> tlock(recvTransportsLock_);
183  for (auto ptr : recvTransports_) {
184  ptr->stopListenTo(t);
185  }
186  }
187 
188 private:
189 /**
190  * @brief this ctor is to create some commonly used basic engine setup to start with.
191  * This is private and only meant to be used through SingletonGuardian,
192  * see in example chat.cpp
193  * @snippet chat.cpp create NetContext with initial tx/rx capabilities
194  * @details It creates one send transport engine and/or one recv transport engine based on cfgIn.
195  * and run them using a single OS thread indicated by runningUsingThreadIndex
196  * If recv engine is created, this method also automaticallly makes the NetContext listen to
197  * a default topic (listenToTopic).
198  *
199  * @param ctx a Context that manages the send / recv transport engines, and hold the received messages
200  * @param cfgIn optional Config for the send AND recv transport engines
201  * @param sendSec the section name for send transport engine in above cfgIn, special values:
202  * nullptr - create send engine using no section config values
203  * "" - do not create send engine
204  * @param recvSec the section name for recv transport engine in above cfgIn
205  * nullptr - create recv engine using no section config values
206  * "" - do not create recv engine
207  * @param maxMessageSize max message size in bytes to be sent, if 0, uses ctx's maxMessageSize()
208  * @param runningUsingThreadIndex see details above
209  * @tparam CcContext ctx Context type
210  */
211  template <typename CcContext>
212  NetContext(CcContext& ctx
213  , Config::Base const* cfgIn = nullptr
214  , char const* sendSec = nullptr
215  , char const* recvSec = nullptr
216  , size_t maxMessageSize = 0
217  , uint8_t runningUsingThreadIndex = 0
218  , char const* listenToTopic = "_")
219  : runningCtx(0u, 2ul) {
220  createMinimumNetContext(
221  *this, runningCtx, ctx, cfgIn, sendSec, recvSec, maxMessageSize, runningUsingThreadIndex, listenToTopic);
222  }
223 
224 /**
225  * @brief this is for users that want finer control of engine creation - from a blank NetContext.
226  * @details it does not do anything that the previous ctor does
227  */
229  }
230 
231  ~NetContext() {
232  }
233 
234 
235  std::vector<SendTransport::ptr> sendTransports_;
236  std::mutex sendTransportEnginesLock_;
237 
238  std::vector<RecvTransport::ptr> recvTransports_;
239  std::mutex recvTransportsLock_;
240 
241  std::map<comm::Topic, Sender::ptr> senders_;
242  std::mutex sendersLock_;
243  Context<> runningCtx;
244 };
245 
246 } //tcpcast
247 
248 }}
249 
void setDefaultUserConfig(Config const &c)
internal use
Definition: Config.hpp:139
class to hold an hmbdc configuration
Definition: Config.hpp:44
NetContext()
this is for users that want finer control of engine creation - from a blank NetContext.
Definition: NetContext.hpp:228
fascade class for sending network messages
Definition: Sender.hpp:11
topic as in the publish / subscribe communication paradigm
Definition: Topic.hpp:14
Definition: NetContextUtil.hpp:7
SendTransportEngine * createSendTransportEngine(Config const &cfgIn, size_t maxMessageSize)
construct a send transport enngine (and remember it)
Definition: NetContext.hpp:63
base for the Singleton that works with SingletonGuardian
Definition: GuardedSingleton.hpp:35
RAII representing the lifespan of the underlying Singleton which also ganrantees the singularity of u...
Definition: GuardedSingleton.hpp:20
auto createRecvTransportEngine(Config const &cfgIn, Buffer &buffer, MsgArbitrator &&arb=RecvTransport::NoOpArb())
construct a send transport and remember it
Definition: NetContext.hpp:103
NetContext(CcContext &ctx, Config::Base const *cfgIn=nullptr, char const *sendSec=nullptr, char const *recvSec=nullptr, size_t maxMessageSize=0, uint8_t runningUsingThreadIndex=0, char const *listenToTopic="_")
this ctor is to create some commonly used basic engine setup to start with. This is private and only ...
Definition: NetContext.hpp:212
void listenTo(comm::Topic const &t)
This process is interested in a Topic.
Definition: NetContext.hpp:169
Definition: SendTransportEngine.hpp:190
SendTransportEngine * createSendTransportEngineTuply(Config const &cfg, size_t maxMessageSize, std::tuple< size_t > args)
same as above but provide an unified interface - not preferred
Definition: NetContext.hpp:80
a singleton that holding tcpcast resources
Definition: NetContext.hpp:44
void stopListenTo(comm::Topic const &t)
undo the subscription
Definition: NetContext.hpp:181
A Context is like a media object that facilitates the communications for the Clients that it is holdi...
Definition: Context.hpp:408
a take all arbitrator (no arbitration at all)
Definition: RecvTransportEngine.hpp:36
auto createRecvTransportEngineTuply(Config const &cfg, Buffer &buffer, ArgsTuple &&args)
same as above but to provide a unified interface - not preferred
Definition: NetContext.hpp:123
Sender * getSender(comm::Topic const &t)
get (or create for the first time) a Sender - whose function is to send messages on its associated To...
Definition: NetContext.hpp:140
impl class
Definition: RecvTransportEngine.hpp:61
Definition: Base.hpp:12