supervisor.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. #pragma once
  2. //
  3. // Copyright (c) 2019-2020 Ivan Baidakou (basiliscos) (the dot dmol at gmail dot com)
  4. //
  5. // Distributed under the MIT Software License
  6. //
  7. #include "actor_base.h"
  8. #include "handler.hpp"
  9. #include "message.h"
  10. #include "messages.hpp"
  11. #include "subscription.h"
  12. #include "system_context.h"
  13. #include "supervisor_config.h"
  14. #include "address_mapping.h"
  15. #include <functional>
  16. #include <unordered_map>
  17. namespace rotor {
  18. /** \struct supervisor_t
  19. * \brief supervisor is responsible for managing actors (workers) lifetime
  20. *
  21. * Supervisor starts, stops actors (children/workers) and process messages.
  22. * The message processing is basically sorting messages by their destination
  23. * {@link address_t}: if an address belongs to the supervisor, then message
  24. * is dispatched locally, otherwise the message is forwarded to supervisor,
  25. * which owns address.
  26. *
  27. * During message dispatching phase, supervisor examines handlers
  28. * ({@link handler_base_t}), if they are local, then a message in immediately
  29. * delivered to it (i.e. a local actor is invoked immediately), otherwise
  30. * is is forwarded for delivery to the supervisor, which owns the handler.
  31. *
  32. * Supervisor is responsible for managing it's local actors lifetime, i.e.
  33. * sending initialization, start, shutdown requests etc.
  34. *
  35. * Supervisor is locality-aware: i.e. if two supervisors have the same
  36. * locality (i.e. executed in the same thread/event loop), it takes advantage
  37. * of this and immediately delivers message to the target supervisor
  38. * without involving any synchronization mechanisms. In other words,
  39. * a message is delivered to any actor of the locality, even if the
  40. * actor is not child of the current supervisor.
  41. *
  42. * As supervisor is special kind of actor, it should be possible to spawn
  43. * other supervisors constructing tree-like organization of responsibilities.
  44. *
  45. * Unlike Erlang's supervisor, rotor's supervisor does not spawn actors
  46. * if they terminated. It should be possible, hovewer, to implement it in derived
  47. * classes with application-specific logic.
  48. *
  49. * This supervisor class is abstract, and the concrete implementation is
  50. * is event-loop specific, i.e. it should know how to start/stop shutdown
  51. * timers, how to trigger messages processing in thread-safe way, how
  52. * to deliver message to a supervisor in a thread-safe way etc.
  53. *
  54. */
  55. struct supervisor_t : public actor_base_t {
  56. // clang-format off
  57. /** \brief the default list of plugins for an supervisor
  58. *
  59. * The order of plugins is very important, as they are initialized in the direct order
  60. * and deinitilized in the reverse order.
  61. *
  62. */
  63. using plugins_list_t = std::tuple<
  64. plugin::address_maker_plugin_t,
  65. plugin::locality_plugin_t,
  66. plugin::delivery_plugin_t<plugin::default_local_delivery_t>,
  67. plugin::lifetime_plugin_t,
  68. plugin::init_shutdown_plugin_t,
  69. plugin::foreigners_support_plugin_t,
  70. plugin::child_manager_plugin_t,
  71. plugin::link_server_plugin_t,
  72. plugin::link_client_plugin_t,
  73. plugin::registry_plugin_t,
  74. plugin::starter_plugin_t>;
  75. // clang-format on
  76. /** \brief injects an alias for supervisor_config_t */
  77. using config_t = supervisor_config_t;
  78. /** \brief injects templated supervisor_config_builder_t */
  79. template <typename Supervisor> using config_builder_t = supervisor_config_builder_t<Supervisor>;
  80. /** \brief constructs new supervisor with optional parent supervisor */
  81. supervisor_t(supervisor_config_t &config);
  82. supervisor_t(const supervisor_t &) = delete;
  83. supervisor_t(supervisor_t &&) = delete;
  84. virtual void do_initialize(system_context_t *ctx) noexcept override;
  85. /** \brief process queue of messages of locality leader
  86. *
  87. * The locality leaders queue `queue` of messages is processed.
  88. *
  89. * -# It takes message from the queue
  90. * -# If the message destination address belongs to the foreing the supervisor,
  91. * then it is forwarded to it immediately.
  92. * -# Otherwise, the message is local, i.e. either for the supervisor or one
  93. * of its non-supervisor children (internal), or to other supervisor within
  94. * the same locality.
  95. * -# in the former case the message is immediately delivered locally in
  96. * the context of current supervisor; in the latter case in the context
  97. * of other supervsior. In the both cases `deliver_local` method is used.
  98. *
  99. * It is expected, that derived classes should invoke `do_process` message,
  100. * whenever it is known that there are messages for processing. The invocation
  101. * should be performed in safe thread/loop context.
  102. *
  103. * The method should be invoked in event-loop context only.
  104. *
  105. */
  106. inline void do_process() noexcept { delivery->process(); }
  107. /** \brief creates new {@link address_t} linked with the supervisor */
  108. virtual address_ptr_t make_address() noexcept;
  109. /** \brief removes the subscription point: local address and (foreign-or-local)
  110. * handler pair
  111. */
  112. virtual void commit_unsubscription(const subscription_info_ptr_t &info) noexcept;
  113. /** \brief thread-safe version of `do_process`
  114. *
  115. * Starts supervisor to processing messages queue in safe thread/loop
  116. * context. Once it becomes empty, the method returns
  117. */
  118. virtual void start() noexcept = 0;
  119. /** \brief thread-safe version of `do_shutdown`, i.e. send shutdown request
  120. * let it be processed by the supervisor */
  121. virtual void shutdown() noexcept = 0;
  122. void do_shutdown() noexcept override;
  123. /** \brief supervisor hook for reaction on child actor init */
  124. virtual void on_child_init(actor_base_t *actor, const std::error_code &ec) noexcept;
  125. /** \brief supervisor hook for reaction on child actor shutdown */
  126. virtual void on_child_shutdown(actor_base_t *actor, const std::error_code &ec) noexcept;
  127. /** \brief enqueues messages thread safe way and triggers processing
  128. *
  129. * This is the only method for deliver message outside of `rotor` context.
  130. * Basically it is `put` and `process` in the event loop context.
  131. *
  132. * The thread-safety should be guaranteed by derived class and/or used event-loop.
  133. *
  134. * This method is used for messaging between supervisors with different
  135. * localities, event loops or threads.
  136. *
  137. */
  138. virtual void enqueue(message_ptr_t message) noexcept = 0;
  139. /** \brief puts a message into internal supevisor queue for further processing
  140. *
  141. * This is thread-unsafe method. The `enqueue` method should be used to put
  142. * a new message from external context in thread-safe way.
  143. *
  144. */
  145. inline void put(message_ptr_t message) { locality_leader->queue.emplace_back(std::move(message)); }
  146. /** \brief templated version of `subscribe_actor` */
  147. template <typename Handler> void subscribe(actor_base_t &actor, Handler &&handler) {
  148. supervisor->subscribe(actor.address, wrap_handler(actor, std::move(handler)));
  149. }
  150. /** \brief convenient templated version of `unsubscribe_actor */
  151. template <typename Handler> inline void unsubscribe_actor(const address_ptr_t &addr, Handler &&handler) noexcept {
  152. handler_ptr_t wrapped_handler(std::forward<Handler>(handler));
  153. lifetime->unsubscribe(wrapped_handler, addr);
  154. }
  155. /** \brief creates child-actor builder */
  156. template <typename Actor> auto create_actor() {
  157. using builder_t = typename Actor::template config_builder_t<Actor>;
  158. assert(manager && "child_manager_plugin_t should be already initialized");
  159. return builder_t([this](auto &actor) { manager->create_child(actor); }, this);
  160. }
  161. /** \brief convenient method for request building
  162. *
  163. * The built request isn't sent immediately, but only after invoking `send(timeout)`
  164. *
  165. */
  166. template <typename T, typename... Args>
  167. request_builder_t<T> do_request(actor_base_t &actor, const address_ptr_t &dest_addr, const address_ptr_t &reply_to,
  168. Args &&... args) noexcept {
  169. return request_builder_t<T>(*this, actor, dest_addr, reply_to, std::forward<Args>(args)...);
  170. }
  171. /**
  172. * \brief main subscription implementation
  173. *
  174. * The subscription point is materialized inot subscription info. If address is
  175. * internal/local, then it is immediately confirmed to the source actor as
  176. * {@link payload::subscription_confirmation_t}.
  177. *
  178. * Otherwise, if the address is external (foreign), then subscription request
  179. * is forwarded to approriate supervisor as {@link payload::external_subscription_t}
  180. * request.
  181. *
  182. * The materialized subscription info is returned.
  183. *
  184. */
  185. subscription_info_ptr_t subscribe(const handler_ptr_t &handler, const address_ptr_t &addr,
  186. const actor_base_t *owner_ptr, owner_tag_t owner_tag) noexcept;
  187. using actor_base_t::subscribe;
  188. /** \brief returns registry actor address (if it was defined or registry actor was created) */
  189. inline const address_ptr_t &get_registry_address() const noexcept { return registry_address; }
  190. /** \brief generic non-public fields accessor */
  191. template <typename T> auto &access() noexcept;
  192. /** \brief generic non-public methods accessor */
  193. template <typename T, typename... Args> auto access(Args... args) noexcept;
  194. protected:
  195. /** \brief creates new address with respect to supervisor locality mark */
  196. virtual address_ptr_t instantiate_address(const void *locality) noexcept;
  197. /** \brief timer to response with timeout procuder type */
  198. using request_map_t = std::unordered_map<request_id_t, request_curry_t>;
  199. /** \brief invoked as timer callback; creates response or just clean up for previously set request */
  200. void on_request_trigger(request_id_t timer_id, bool cancelled) noexcept;
  201. /** \brief starts non-recurring timer (to be implemented in descendants) */
  202. virtual void do_start_timer(const pt::time_duration &interval, timer_handler_base_t &handler) noexcept = 0;
  203. /** \brief cancels timer (to be implemented in descendants) */
  204. virtual void do_cancel_timer(request_id_t timer_id) noexcept = 0;
  205. /** \brief non-owning pointer to system context. */
  206. system_context_t *context;
  207. /** \brief queue of unprocessed messages */
  208. messages_queue_t queue;
  209. /** \brief counter for request/timer ids */
  210. request_id_t last_req_id;
  211. /** \brief timer to response with timeout procuder */
  212. request_map_t request_map;
  213. /** \brief main subscription support class */
  214. subscription_t subscription_map;
  215. /** \brief non-owning pointer to parent supervisor, `NULL` for root supervisor */
  216. supervisor_t *parent;
  217. /** \brief delivery plugin pointer */
  218. plugin::delivery_plugin_base_t *delivery = nullptr;
  219. /** \brief child manager plugin pointer */
  220. plugin::child_manager_plugin_t *manager = nullptr;
  221. /** \brief root supervisor for the locality */
  222. supervisor_t *locality_leader;
  223. private:
  224. bool create_registry;
  225. bool synchronize_start;
  226. address_ptr_t registry_address;
  227. supervisor_policy_t policy;
  228. /** \brief per-actor and per-message request tracking support */
  229. address_mapping_t address_mapping;
  230. template <typename T> friend struct request_builder_t;
  231. template <typename Supervisor> friend struct actor_config_builder_t;
  232. friend struct plugin::delivery_plugin_base_t;
  233. friend struct actor_base_t;
  234. template <typename T> friend struct plugin::delivery_plugin_t;
  235. inline request_id_t next_request_id() noexcept {
  236. request_map_t::iterator it;
  237. do {
  238. it = request_map.find(++last_req_id);
  239. } while (it != request_map.end());
  240. return last_req_id;
  241. }
  242. };
  243. using supervisor_ptr_t = intrusive_ptr_t<supervisor_t>;
  244. /* third-party classes implementations */
  245. template <typename Supervisor> auto system_context_t::create_supervisor() {
  246. using builder_t = typename Supervisor::template config_builder_t<Supervisor>;
  247. return builder_t(
  248. [this](auto &actor) {
  249. if (supervisor) {
  250. on_error(make_error_code(error_code_t::supervisor_defined));
  251. actor.reset();
  252. } else {
  253. this->supervisor = actor;
  254. actor->do_initialize(this);
  255. }
  256. },
  257. *this);
  258. }
  259. template <typename M, typename... Args> void actor_base_t::send(const address_ptr_t &addr, Args &&... args) {
  260. supervisor->put(make_message<M>(addr, std::forward<Args>(args)...));
  261. }
  262. template <typename Delegate, typename Method>
  263. void actor_base_t::start_timer(request_id_t request_id, const pt::time_duration &interval, Delegate &delegate,
  264. Method method) noexcept {
  265. using final_handler_t = timer_handler_t<Delegate, Method>;
  266. auto handler = std::make_unique<final_handler_t>(this, request_id, &delegate, std::forward<Method>(method));
  267. supervisor->do_start_timer(interval, *handler);
  268. timers_map.emplace(request_id, std::move(handler));
  269. }
  270. template <typename Delegate, typename Method>
  271. request_id_t actor_base_t::start_timer(const pt::time_duration &interval, Delegate &delegate, Method method) noexcept {
  272. auto request_id = supervisor->next_request_id();
  273. start_timer(request_id, interval, delegate, std::forward<Method>(method));
  274. return request_id;
  275. }
  276. /** \brief wraps handler (pointer to member function) and actor address into intrusive pointer */
  277. template <typename Handler> handler_ptr_t wrap_handler(actor_base_t &actor, Handler &&handler) {
  278. using final_handler_t = handler_t<Handler>;
  279. auto handler_raw = new final_handler_t(actor, std::move(handler));
  280. return handler_ptr_t{handler_raw};
  281. }
  282. template <typename Handler> subscription_info_ptr_t actor_base_t::subscribe(Handler &&h) noexcept {
  283. auto wrapped_handler = wrap_handler(*this, std::move(h));
  284. return supervisor->subscribe(wrapped_handler, address, this, owner_tag_t::ANONYMOUS);
  285. }
  286. template <typename Handler>
  287. subscription_info_ptr_t actor_base_t::subscribe(Handler &&h, const address_ptr_t &addr) noexcept {
  288. auto wrapped_handler = wrap_handler(*this, std::move(h));
  289. return supervisor->subscribe(wrapped_handler, addr, this, owner_tag_t::ANONYMOUS);
  290. }
  291. namespace plugin {
  292. template <typename Handler>
  293. subscription_info_ptr_t plugin_base_t::subscribe(Handler &&h, const address_ptr_t &addr) noexcept {
  294. using final_handler_t = handler_t<Handler>;
  295. handler_ptr_t wrapped_handler(new final_handler_t(*this, std::move(h)));
  296. auto info = actor->supervisor->subscribe(wrapped_handler, addr, actor, owner_tag_t::PLUGIN);
  297. own_subscriptions.emplace_back(info);
  298. return info;
  299. }
  300. template <typename Handler> subscription_info_ptr_t plugin_base_t::subscribe(Handler &&h) noexcept {
  301. return subscribe(std::forward<Handler>(h), actor->address);
  302. }
  303. template <> inline auto &plugin_base_t::access<plugin::starter_plugin_t>() noexcept { return own_subscriptions; }
  304. template <typename Handler> handler_ptr_t starter_plugin_t::subscribe_actor(Handler &&handler) noexcept {
  305. auto &address = actor->get_address();
  306. return subscribe_actor(std::forward<Handler>(handler), address);
  307. }
  308. template <typename Handler>
  309. handler_ptr_t starter_plugin_t::subscribe_actor(Handler &&handler, const address_ptr_t &addr) noexcept {
  310. auto wrapped_handler = wrap_handler(*actor, std::move(handler));
  311. auto info = actor->get_supervisor().subscribe(wrapped_handler, addr, actor, owner_tag_t::PLUGIN);
  312. assert(std::count_if(tracked.begin(), tracked.end(), [&](auto &it) { return *it == *info; }) == 0 &&
  313. "already subscribed");
  314. tracked.emplace_back(info);
  315. access<starter_plugin_t>().emplace_back(std::move(info));
  316. return wrapped_handler;
  317. }
  318. template <typename LocalDelivery> void delivery_plugin_t<LocalDelivery>::process() noexcept {
  319. while (queue->size()) {
  320. auto message = queue->front();
  321. auto &dest = message->address;
  322. queue->pop_front();
  323. auto &dest_sup = dest->supervisor;
  324. auto internal = &dest_sup == actor;
  325. if (internal) { /* subscriptions are handled by me */
  326. auto *local_recipients = subscription_map->get_recipients(*message);
  327. if (local_recipients) {
  328. LocalDelivery::delivery(message, *local_recipients);
  329. }
  330. } else if (dest_sup.address->same_locality(*address)) {
  331. auto *local_recipients = dest_sup.subscription_map.get_recipients(*message);
  332. if (local_recipients) {
  333. LocalDelivery::delivery(message, *local_recipients);
  334. }
  335. } else {
  336. dest_sup.enqueue(std::move(message));
  337. }
  338. }
  339. }
  340. } // namespace plugin
  341. template <typename Handler, typename Enabled> void actor_base_t::unsubscribe(Handler &&h) noexcept {
  342. supervisor->unsubscribe_actor(address, wrap_handler(*this, std::move(h)));
  343. }
  344. template <typename Handler, typename Enabled>
  345. void actor_base_t::unsubscribe(Handler &&h, address_ptr_t &addr) noexcept {
  346. supervisor->unsubscribe_actor(addr, wrap_handler(*this, std::move(h)));
  347. }
  348. template <typename T>
  349. template <typename... Args>
  350. request_builder_t<T>::request_builder_t(supervisor_t &sup_, actor_base_t &actor_, const address_ptr_t &destination_,
  351. const address_ptr_t &reply_to_, Args &&... args)
  352. : sup{sup_}, actor{actor_}, request_id{sup.next_request_id()}, destination{destination_}, reply_to{reply_to_},
  353. do_install_handler{false} {
  354. auto addr = sup.address_mapping.get_mapped_address(actor_, response_message_t::message_type);
  355. if (addr) {
  356. imaginary_address = addr;
  357. } else {
  358. // subscribe to imaginary address instead of real one because of
  359. // 1. faster dispatching
  360. // 2. need to distinguish between "timeout guarded responses" and "responses to own requests"
  361. imaginary_address = sup.make_address();
  362. do_install_handler = true;
  363. }
  364. req.reset(
  365. new request_message_t{destination, request_id, imaginary_address, reply_to_, std::forward<Args>(args)...});
  366. }
  367. template <typename T> request_id_t request_builder_t<T>::send(pt::time_duration timeout) noexcept {
  368. if (do_install_handler) {
  369. install_handler();
  370. }
  371. auto fn = &request_traits_t<T>::make_error_response;
  372. sup.request_map.emplace(request_id, request_curry_t{fn, reply_to, req});
  373. sup.put(req);
  374. sup.start_timer(request_id, timeout, sup, &supervisor_t::on_request_trigger);
  375. return request_id;
  376. }
  377. template <typename T> void request_builder_t<T>::install_handler() noexcept {
  378. auto handler = lambda<response_message_t>([supervisor = &sup](response_message_t &msg) {
  379. auto request_id = msg.payload.request_id();
  380. auto it = supervisor->request_map.find(request_id);
  381. if (it != supervisor->request_map.end()) {
  382. auto &orig_addr = it->second.origin;
  383. supervisor->template send<wrapped_res_t>(orig_addr, msg.payload);
  384. supervisor->request_map.erase(it);
  385. supervisor->cancel_timer(request_id);
  386. }
  387. // if a response to request has arrived and no timer can be found
  388. // that means that either timeout timer already triggered
  389. // and error-message already delivered or response is not expected.
  390. // just silently drop it anyway
  391. });
  392. auto wrapped_handler = wrap_handler(sup, std::move(handler));
  393. auto info = sup.subscribe(wrapped_handler, imaginary_address, &actor, owner_tag_t::SUPERVISOR);
  394. sup.address_mapping.set(actor, info);
  395. }
  396. /** \brief makes an reqest to the destination address with the message constructed from `args`
  397. *
  398. * The `reply_to` address is defaulted to actor's main address.1
  399. *
  400. */
  401. template <typename Request, typename... Args>
  402. request_builder_t<typename request_wrapper_t<Request>::request_t> actor_base_t::request(const address_ptr_t &dest_addr,
  403. Args &&... args) {
  404. using request_t = typename request_wrapper_t<Request>::request_t;
  405. return supervisor->do_request<request_t>(*this, dest_addr, address, std::forward<Args>(args)...);
  406. }
  407. /** \brief makes an reqest to the destination address with the message constructed from `args`
  408. *
  409. * The `reply_addr` is used to specify the exact destinatiion address, where reply should be
  410. * delivered.
  411. *
  412. */
  413. template <typename Request, typename... Args>
  414. request_builder_t<typename request_wrapper_t<Request>::request_t>
  415. actor_base_t::request_via(const address_ptr_t &dest_addr, const address_ptr_t &reply_addr, Args &&... args) {
  416. using request_t = typename request_wrapper_t<Request>::request_t;
  417. return supervisor->do_request<request_t>(*this, dest_addr, reply_addr, std::forward<Args>(args)...);
  418. }
  419. template <typename Request> auto actor_base_t::make_response(Request &message, const std::error_code &ec) {
  420. using payload_t = typename Request::payload_t::request_t;
  421. using traits_t = request_traits_t<payload_t>;
  422. return traits_t::make_error_response(message.payload.reply_to, message, ec);
  423. }
  424. template <typename Request, typename... Args> auto actor_base_t::make_response(Request &message, Args &&... args) {
  425. using payload_t = typename Request::payload_t::request_t;
  426. using traits_t = request_traits_t<payload_t>;
  427. using response_t = typename traits_t::response::wrapped_t;
  428. using request_ptr_t = typename traits_t::request::message_ptr_t;
  429. return make_message<response_t>(message.payload.reply_to, request_ptr_t{&message}, std::forward<Args>(args)...);
  430. }
  431. template <typename Request, typename... Args> void actor_base_t::reply_to(Request &message, Args &&... args) {
  432. supervisor->put(make_response<Request>(message, std::forward<Args>(args)...));
  433. }
  434. template <typename Request> void actor_base_t::reply_with_error(Request &message, const std::error_code &ec) {
  435. supervisor->put(make_response<Request>(message, ec));
  436. }
  437. template <typename Actor>
  438. actor_config_builder_t<Actor>::actor_config_builder_t(install_action_t &&action_, supervisor_t *supervisor_)
  439. : install_action{std::move(action_)}, supervisor{supervisor_},
  440. system_context{*supervisor_->context}, config{supervisor_} {
  441. init_ctor();
  442. }
  443. template <typename Actor> intrusive_ptr_t<Actor> actor_config_builder_t<Actor>::finish() && {
  444. intrusive_ptr_t<Actor> actor_ptr;
  445. if (!validate()) {
  446. auto ec = make_error_code(error_code_t::actor_misconfigured);
  447. system_context.on_error(ec);
  448. } else {
  449. auto &cfg = static_cast<typename builder_t::config_t &>(config);
  450. auto actor = new Actor(cfg);
  451. actor_ptr.reset(actor);
  452. install_action(actor_ptr);
  453. }
  454. return actor_ptr;
  455. }
  456. } // namespace rotor