Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
SendingQueue.hpp
1#pragma once
2
3#include "web/ng/Error.hpp"
4
5#include <boost/asio/any_io_executor.hpp>
6#include <boost/asio/spawn.hpp>
7#include <boost/system/detail/error_code.hpp>
8
9#include <functional>
10#include <optional>
11#include <queue>
12
13namespace web::ng::impl {
14
15template <typename T>
16class SendingQueue {
17public:
18 using Sender = std::function<
19 void(T const&, boost::asio::basic_yield_context<boost::asio::any_io_executor>)>;
20
21private:
22 std::queue<T> queue_;
23 Sender sender_;
24 Error error_;
25 bool isSending_{false};
26
27public:
28 SendingQueue(Sender sender) : sender_{std::move(sender)}
29 {
30 }
31
32 std::expected<void, Error>
33 send(T message, boost::asio::yield_context yield)
34 {
35 if (error_)
36 return std::unexpected{error_};
37
38 queue_.push(std::move(message));
39 if (isSending_)
40 return {};
41
42 isSending_ = true;
43 while (not queue_.empty() and not error_) {
44 auto const responseToSend = std::move(queue_.front());
45 queue_.pop();
46 sender_(responseToSend, yield[error_]);
47 }
48 isSending_ = false;
49 if (error_)
50 return std::unexpected{error_};
51 return {};
52 }
53};
54
55} // namespace web::ng::impl