diff options
Diffstat (limited to 'whiteboard.cpp')
-rw-r--r-- | whiteboard.cpp | 49 |
1 files changed, 42 insertions, 7 deletions
diff --git a/whiteboard.cpp b/whiteboard.cpp index 922bd37..2c8a47b 100644 --- a/whiteboard.cpp +++ b/whiteboard.cpp @@ -251,6 +251,45 @@ public: }); } + std::string stats_xml() + { + return make_xml({ + {"type", "stats" }, + {"dbsizegross", std::to_string(m_storage.dbsize_gross()) }, + {"dbsizenet", std::to_string(m_storage.dbsize_net()) }, + {"numberofdocuments", std::to_string(m_storage.getNumberOfDocuments()) }, + {"numberofconnections", std::to_string(m_registry.number_of_connections()) }, + }); + } + + void on_write_stats(std::shared_ptr<std::string> data, std::shared_ptr<boost::asio::const_buffer> buffer, boost::beast::error_code ec, std::size_t bytes_transferred) + { + boost::ignore_unused(bytes_transferred); + + if (ec) { + std::cerr << "Error on session write stats: " << ec.message() << std::endl; + } + } + + void stats_callback(const boost::system::error_code&) + { + auto data{std::make_shared<std::string>(stats_xml())}; + auto buffer{std::make_shared<boost::asio::const_buffer>(data->data(), data->size())}; + m_ws->async_write(*buffer, boost::asio::bind_executor(m_ws->next_layer().get_executor(), + boost::beast::bind_front_handler(&session::on_write_stats, shared_from_this(), data, buffer))); + + m_stats_timer->expires_at(m_stats_timer->expires_at() + boost::asio::chrono::seconds(5)); + m_stats_timer->async_wait(boost::beast::bind_front_handler(&session::stats_callback, this)); + } + + void setup_stats_timer() + { + if (!m_stats_timer) { + m_stats_timer = std::make_shared<boost::asio::steady_timer>(m_ws->next_layer().get_executor(), boost::asio::chrono::seconds(5)); + m_stats_timer->async_wait(boost::beast::bind_front_handler(&session::stats_callback, this)); + } + } + std::string handle_request(const std::string& request) { try { @@ -339,13 +378,8 @@ public: {"version", WHITEBOARD_VERSION } }); } else if (command == "getstats") { - return make_xml({ - {"type", "stats" }, - {"dbsizegross", std::to_string(m_storage.dbsize_gross()) }, - {"dbsizenet", std::to_string(m_storage.dbsize_net()) }, - {"numberofdocuments", std::to_string(m_storage.getNumberOfDocuments()) }, - {"numberofconnections", std::to_string(m_registry.number_of_connections()) }, - }); + setup_stats_timer(); + return stats_xml(); } else { throw std::runtime_error("Bad command: "s + command); } @@ -365,6 +399,7 @@ private: boost::beast::http::request<boost::beast::http::string_body> m_req; boost::beast::flat_buffer m_buffer; + std::shared_ptr<boost::asio::steady_timer> m_stats_timer{}; }; void Whiteboard::do_accept() |