time_source.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. #pragma once
  2. /*
  3. * Copyright 2018-present Facebook, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #include <folly/experimental/pushmi/executor.h>
  18. #include <folly/experimental/pushmi/time_single_sender.h>
  19. #include <queue>
  20. //
  21. // time_source is used to build a time_single_executor from a single_executor.
  22. //
  23. namespace pushmi {
  24. template <class E, class TP>
  25. class time_source_shared;
  26. template <class E, class TP, class NF, class Executor>
  27. class time_source_executor;
  28. template <class E, class TP>
  29. class time_heap_item {
  30. public:
  31. using time_point = std::decay_t<TP>;
  32. time_heap_item(
  33. time_point at,
  34. any_receiver<E, any_time_executor_ref<E, TP>> out)
  35. : when(std::move(at)), what(std::move(out)) {}
  36. time_point when;
  37. any_receiver<E, any_time_executor_ref<E, TP>> what;
  38. };
  39. template <class E, class TP>
  40. bool operator<(const time_heap_item<E, TP>& l, const time_heap_item<E, TP>& r) {
  41. return l.when < r.when;
  42. }
  43. template <class E, class TP>
  44. bool operator>(const time_heap_item<E, TP>& l, const time_heap_item<E, TP>& r) {
  45. return l.when > r.when;
  46. }
  47. template <class E, class TP>
  48. bool operator==(
  49. const time_heap_item<E, TP>& l,
  50. const time_heap_item<E, TP>& r) {
  51. return l.when == r.when;
  52. }
  53. template <class E, class TP>
  54. bool operator!=(
  55. const time_heap_item<E, TP>& l,
  56. const time_heap_item<E, TP>& r) {
  57. return !(l == r);
  58. }
  59. template <class E, class TP>
  60. bool operator<=(
  61. const time_heap_item<E, TP>& l,
  62. const time_heap_item<E, TP>& r) {
  63. return !(l > r);
  64. }
  65. template <class E, class TP>
  66. bool operator>=(
  67. const time_heap_item<E, TP>& l,
  68. const time_heap_item<E, TP>& r) {
  69. return !(l < r);
  70. }
  71. template <class E, class TP>
  72. class time_source_queue_base
  73. : public std::enable_shared_from_this<time_source_queue_base<E, TP>> {
  74. public:
  75. using time_point = std::decay_t<TP>;
  76. bool dispatching_ = false;
  77. bool pending_ = false;
  78. std::priority_queue<
  79. time_heap_item<E, TP>,
  80. std::vector<time_heap_item<E, TP>>,
  81. std::greater<>>
  82. heap_;
  83. virtual ~time_source_queue_base() {}
  84. time_heap_item<E, TP>& top() {
  85. // :(
  86. return const_cast<time_heap_item<E, TP>&>(this->heap_.top());
  87. }
  88. virtual void dispatch() = 0;
  89. };
  90. template <class E, class TP, class NF, class Executor>
  91. class time_source_queue : public time_source_queue_base<E, TP> {
  92. public:
  93. using time_point = std::decay_t<TP>;
  94. ~time_source_queue() {}
  95. time_source_queue(
  96. std::weak_ptr<time_source_shared<E, time_point>> source,
  97. NF nf,
  98. Executor ex)
  99. : source_(std::move(source)), nf_(std::move(nf)), ex_(std::move(ex)) {}
  100. std::weak_ptr<time_source_shared<E, time_point>> source_;
  101. NF nf_;
  102. Executor ex_;
  103. void dispatch() override;
  104. auto shared_from_that() {
  105. return std::static_pointer_cast<time_source_queue<E, TP, NF, Executor>>(
  106. this->shared_from_this());
  107. }
  108. template <class Exec>
  109. void value(Exec&&) {
  110. auto s = source_.lock();
  111. if (s->t_.get_id() == std::this_thread::get_id()) {
  112. // Executor is not allowed to use the time_source thread
  113. std::abort();
  114. }
  115. //
  116. // pull ready items from the heap in order.
  117. // drain anything queued within the next 50ms before
  118. // going back to the pending queue.
  119. auto start = nf_() + std::chrono::milliseconds(50);
  120. std::unique_lock<std::mutex> guard{s->lock_};
  121. if (!this->dispatching_ || this->pending_) {
  122. std::abort();
  123. }
  124. if (this->heap_.empty()) {
  125. return;
  126. }
  127. auto that = shared_from_that();
  128. auto subEx = time_source_executor<E, TP, NF, Executor>{s, that};
  129. while (!this->heap_.empty() && this->heap_.top().when <= start) {
  130. auto item{std::move(this->top())};
  131. this->heap_.pop();
  132. guard.unlock();
  133. std::this_thread::sleep_until(item.when);
  134. ::pushmi::set_value(item.what, any_time_executor_ref<E, TP>{subEx});
  135. ::pushmi::set_done(item.what);
  136. guard.lock();
  137. // allows set_value to queue nested items
  138. --s->items_;
  139. }
  140. if (this->heap_.empty()) {
  141. // if this is empty, tell worker to check for the done condition.
  142. ++s->dirty_;
  143. s->wake_.notify_one();
  144. } else {
  145. if (!!s->error_) {
  146. while (!this->heap_.empty()) {
  147. try {
  148. auto what{std::move(this->top().what)};
  149. this->heap_.pop();
  150. --s->items_;
  151. guard.unlock();
  152. ::pushmi::set_error(what, *s->error_);
  153. guard.lock();
  154. } catch (...) {
  155. // we already have an error, ignore this one.
  156. }
  157. }
  158. }
  159. }
  160. }
  161. template <class AE>
  162. void error(AE e) noexcept {
  163. auto s = source_.lock();
  164. std::unique_lock<std::mutex> guard{s->lock_};
  165. if (!this->dispatching_ || this->pending_) {
  166. std::abort();
  167. }
  168. while (!this->heap_.empty()) {
  169. auto what{std::move(this->top().what)};
  170. this->heap_.pop();
  171. --s->items_;
  172. guard.unlock();
  173. ::pushmi::set_error(what, detail::as_const(e));
  174. guard.lock();
  175. }
  176. this->dispatching_ = false;
  177. }
  178. void done() {
  179. auto s = source_.lock();
  180. std::unique_lock<std::mutex> guard{s->lock_};
  181. if (!this->dispatching_ || this->pending_) {
  182. std::abort();
  183. }
  184. this->dispatching_ = false;
  185. // add back to pending_ to get the remaining items dispatched
  186. s->pending_.push_back(this->shared_from_this());
  187. this->pending_ = true;
  188. if (this->heap_.top().when <= s->earliest_) {
  189. // this is the earliest, tell worker to reset earliest_
  190. ++s->dirty_;
  191. s->wake_.notify_one();
  192. }
  193. }
  194. };
  195. template <class E, class TP, class NF, class Executor>
  196. struct time_source_queue_receiver
  197. : std::shared_ptr<time_source_queue<E, TP, NF, Executor>> {
  198. ~time_source_queue_receiver() {}
  199. explicit time_source_queue_receiver(
  200. std::shared_ptr<time_source_queue<E, TP, NF, Executor>> that)
  201. : std::shared_ptr<time_source_queue<E, TP, NF, Executor>>(that),
  202. source_(that->source_.lock()) {}
  203. using properties = property_set<is_receiver<>>;
  204. std::shared_ptr<time_source_shared<E, TP>> source_;
  205. };
  206. template <class E, class TP, class NF, class Executor>
  207. void time_source_queue<E, TP, NF, Executor>::dispatch() {
  208. ::pushmi::submit(
  209. ex_, time_source_queue_receiver<E, TP, NF, Executor>{shared_from_that()});
  210. }
  211. template <class E, class TP>
  212. class time_queue_dispatch_pred_fn {
  213. public:
  214. bool operator()(std::shared_ptr<time_source_queue_base<E, TP>>& q) {
  215. return !q->heap_.empty();
  216. }
  217. };
  218. template <class E, class TP>
  219. class time_item_process_pred_fn {
  220. public:
  221. using time_point = std::decay_t<TP>;
  222. const time_point* start_;
  223. time_point* earliest_;
  224. bool operator()(const std::shared_ptr<time_source_queue_base<E, TP>>& q) {
  225. // ready for dispatch if it has a ready item
  226. bool ready =
  227. !q->dispatching_ && !q->heap_.empty() && q->heap_.top().when <= *start_;
  228. q->dispatching_ = ready;
  229. q->pending_ = !ready && !q->heap_.empty();
  230. // ready queues are ignored, they will update earliest_ after they have
  231. // processed the ready items
  232. *earliest_ = !ready && !q->heap_.empty()
  233. ? min(*earliest_, q->heap_.top().when)
  234. : *earliest_;
  235. return q->pending_;
  236. }
  237. };
  238. template <class E, class TP>
  239. class time_source_shared_base
  240. : public std::enable_shared_from_this<time_source_shared_base<E, TP>> {
  241. public:
  242. using time_point = std::decay_t<TP>;
  243. std::mutex lock_;
  244. std::condition_variable wake_;
  245. std::thread t_;
  246. std::chrono::system_clock::time_point earliest_;
  247. bool done_;
  248. bool joined_;
  249. int dirty_;
  250. int items_;
  251. detail::opt<E> error_;
  252. std::deque<std::shared_ptr<time_source_queue_base<E, TP>>> pending_;
  253. time_source_shared_base()
  254. : earliest_(std::chrono::system_clock::now() + std::chrono::hours(24)),
  255. done_(false),
  256. joined_(false),
  257. dirty_(0),
  258. items_(0) {}
  259. };
  260. template <class E, class TP>
  261. class time_source_shared : public time_source_shared_base<E, TP> {
  262. public:
  263. std::thread t_;
  264. // this is safe to reuse as long as there is only one thread in the
  265. // time_source_shared
  266. std::vector<std::shared_ptr<time_source_queue_base<E, TP>>> ready_;
  267. ~time_source_shared() {
  268. // not allowed to be discarded without joining and completing all queued
  269. // items
  270. if (t_.joinable() || this->items_ != 0) {
  271. std::abort();
  272. }
  273. }
  274. time_source_shared() {}
  275. static void start(std::shared_ptr<time_source_shared<E, TP>> that) {
  276. that->t_ = std::thread{&time_source_shared<E, TP>::worker, that};
  277. }
  278. static void join(std::shared_ptr<time_source_shared<E, TP>> that) {
  279. std::unique_lock<std::mutex> guard{that->lock_};
  280. that->done_ = true;
  281. ++that->dirty_;
  282. that->wake_.notify_one();
  283. guard.unlock();
  284. that->t_.join();
  285. }
  286. static void worker(std::shared_ptr<time_source_shared<E, TP>> that) {
  287. try {
  288. std::unique_lock<std::mutex> guard{that->lock_};
  289. // once done_, keep going until empty
  290. while (!that->done_ || that->items_ > 0) {
  291. // wait for something to do
  292. that->wake_.wait_until(guard, that->earliest_, [&]() {
  293. return that->dirty_ != 0 ||
  294. std::chrono::system_clock::now() >= that->earliest_;
  295. });
  296. that->dirty_ = 0;
  297. //
  298. // select ready and empty queues and reset earliest_
  299. auto start = std::chrono::system_clock::now();
  300. auto earliest = start + std::chrono::hours(24);
  301. auto process = time_item_process_pred_fn<E, TP>{&start, &earliest};
  302. auto process_begin = std::partition(
  303. that->pending_.begin(), that->pending_.end(), process);
  304. that->earliest_ = earliest;
  305. // copy out the queues that have ready items so that the lock
  306. // is not held during dispatch
  307. std::copy_if(
  308. process_begin,
  309. that->pending_.end(),
  310. std::back_inserter(that->ready_),
  311. time_queue_dispatch_pred_fn<E, TP>{});
  312. // remove processed queues from pending queue.
  313. that->pending_.erase(process_begin, that->pending_.end());
  314. // printf("d %lu, %lu, %d, %ld\n", that->pending_.size(),
  315. // that->ready_.size(), that->items_,
  316. // std::chrono::duration_cast<std::chrono::milliseconds>(earliest -
  317. // start).count());
  318. // dispatch to queues with ready items
  319. guard.unlock();
  320. for (auto& q : that->ready_) {
  321. q->dispatch();
  322. }
  323. guard.lock();
  324. that->ready_.clear();
  325. }
  326. that->joined_ = true;
  327. } catch (...) {
  328. //
  329. // block any more items from being enqueued, all new items will be sent
  330. // this error on the same context that calls submit
  331. //
  332. // also dispatch errors to all items already in the queues from the
  333. // time thread
  334. std::unique_lock<std::mutex> guard{that->lock_};
  335. // creates a dependency that std::exception_ptr must be ConvertibleTo E
  336. // TODO: break this dependency rather than enforce it with concepts
  337. that->error_ = std::current_exception();
  338. for (auto& q : that->pending_) {
  339. while (!q->heap_.empty()) {
  340. try {
  341. auto what{std::move(q->top().what)};
  342. q->heap_.pop();
  343. --that->items_;
  344. guard.unlock();
  345. ::pushmi::set_error(what, *that->error_);
  346. guard.lock();
  347. } catch (...) {
  348. // we already have an error, ignore this one.
  349. }
  350. }
  351. }
  352. }
  353. }
  354. void insert(
  355. std::shared_ptr<time_source_queue_base<E, TP>> queue,
  356. time_heap_item<E, TP> item) {
  357. std::unique_lock<std::mutex> guard{this->lock_};
  358. // deliver error_ and return
  359. if (!!this->error_) {
  360. ::pushmi::set_error(item.what, *this->error_);
  361. return;
  362. }
  363. // once join() is called, new work queued to the executor is not safe unless
  364. // it is nested in an existing item.
  365. if (!!this->joined_) {
  366. std::abort();
  367. };
  368. queue->heap_.push(std::move(item));
  369. ++this->items_;
  370. if (!queue->dispatching_ && !queue->pending_) {
  371. // add queue to pending pending_ list if it is not already there
  372. this->pending_.push_back(queue);
  373. queue->pending_ = true;
  374. }
  375. if (queue->heap_.top().when < this->earliest_) {
  376. // this is the earliest, tell worker to reset earliest_
  377. ++this->dirty_;
  378. this->wake_.notify_one();
  379. }
  380. }
  381. };
  382. //
  383. // the time executor will queue the work to the time ordered heap.
  384. //
  385. template <class E, class TP, class NF, class Executor>
  386. class time_source_executor {
  387. using time_point = std::decay_t<TP>;
  388. std::shared_ptr<time_source_shared<E, time_point>> source_;
  389. std::shared_ptr<time_source_queue<E, time_point, NF, Executor>> queue_;
  390. public:
  391. using properties = property_set<
  392. is_time<>,
  393. is_executor<>,
  394. is_maybe_blocking<>,
  395. is_fifo_sequence<>,
  396. is_single<>>;
  397. time_source_executor(
  398. std::shared_ptr<time_source_shared<E, time_point>> source,
  399. std::shared_ptr<time_source_queue<E, time_point, NF, Executor>> queue)
  400. : source_(std::move(source)), queue_(std::move(queue)) {}
  401. auto top() {
  402. return queue_->nf_();
  403. }
  404. auto executor() {
  405. return *this;
  406. }
  407. PUSHMI_TEMPLATE(class TPA, class Out)
  408. (requires Regular<TPA>&& ReceiveValue<Out, any_time_executor_ref<E, TP>>&&
  409. ReceiveError<Out, E>)
  410. void submit(TPA tp, Out out) {
  411. // queue for later
  412. source_->insert(
  413. queue_,
  414. time_heap_item<E, TP>{
  415. tp, any_receiver<E, any_time_executor_ref<E, TP>>{std::move(out)}});
  416. }
  417. };
  418. //
  419. // the time executor factory produces a new time ordered queue each time that it
  420. // is called.
  421. //
  422. template <class E, class TP, class NF, class ExecutorFactory>
  423. class time_source_executor_factory_fn {
  424. using time_point = std::decay_t<TP>;
  425. std::shared_ptr<time_source_shared<E, time_point>> source_;
  426. NF nf_;
  427. ExecutorFactory ef_;
  428. public:
  429. time_source_executor_factory_fn(
  430. std::shared_ptr<time_source_shared<E, time_point>> source,
  431. NF nf,
  432. ExecutorFactory ef)
  433. : source_(std::move(source)), nf_(std::move(nf)), ef_(std::move(ef)) {}
  434. auto operator()() {
  435. auto ex = ef_();
  436. auto queue =
  437. std::make_shared<time_source_queue<E, time_point, NF, decltype(ex)>>(
  438. source_, nf_, std::move(ex));
  439. return time_source_executor<E, time_point, NF, decltype(ex)>{source_,
  440. queue};
  441. }
  442. };
  443. //
  444. // each time_source is an independent source of timed events
  445. //
  446. // a time_source is a time_single_executor factory, it is not an executor
  447. // itself.
  448. //
  449. // each time_source has a single thread that is shared across all the
  450. // time executors it produces. the thread is used to wait for the next time
  451. // event. when a time event is ready the thread will use the executor passed
  452. // into make() to callback on the receiver passed to the time executor submit()
  453. //
  454. // passing an executor to time_source.make() will create a time executor
  455. // factory. the time executor factory is a function that will return a time
  456. // executor when called with no arguments.
  457. //
  458. //
  459. //
  460. template <
  461. class E = std::exception_ptr,
  462. class TP = std::chrono::system_clock::time_point>
  463. class time_source {
  464. public:
  465. using time_point = std::decay_t<TP>;
  466. private:
  467. std::shared_ptr<time_source_shared<E, time_point>> source_;
  468. public:
  469. time_source()
  470. : source_(std::make_shared<time_source_shared<E, time_point>>()) {
  471. source_->start(source_);
  472. }
  473. PUSHMI_TEMPLATE(class NF, class ExecutorFactory)
  474. (requires Invocable<ExecutorFactory&>&&
  475. Executor<invoke_result_t<ExecutorFactory&>>&&
  476. NeverBlocking<invoke_result_t<
  477. ExecutorFactory&>>)
  478. auto make(NF nf, ExecutorFactory ef) {
  479. return time_source_executor_factory_fn<E, time_point, NF, ExecutorFactory>{
  480. source_, std::move(nf), std::move(ef)};
  481. }
  482. void join() {
  483. source_->join(source_);
  484. }
  485. };
  486. } // namespace pushmi