Clio develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
WithTimeout.hpp
1//------------------------------------------------------------------------------
2/*
3 This file is part of clio: https://github.com/XRPLF/clio
4 Copyright (c) 2024, the clio developers.
5
6 Permission to use, copy, modify, and distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
9
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*/
18//==============================================================================
19
20#pragma once
21
22#include <boost/asio/associated_executor.hpp>
23#include <boost/asio/bind_cancellation_slot.hpp>
24#include <boost/asio/cancellation_signal.hpp>
25#include <boost/asio/cancellation_type.hpp>
26#include <boost/asio/spawn.hpp>
27#include <boost/asio/steady_timer.hpp>
28#include <boost/system/detail/error_code.hpp>
29#include <boost/system/errc.hpp>
30
31#include <chrono>
32#include <ctime>
33#include <memory>
34
35namespace util {
36
47template <typename Operation>
48boost::system::error_code
49withTimeout(Operation&& operation, boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout)
50{
51 boost::system::error_code error;
52 auto operationCompleted = std::make_shared<bool>(false);
53 boost::asio::cancellation_signal cancellationSignal;
54 auto cyield = boost::asio::bind_cancellation_slot(cancellationSignal.slot(), yield[error]);
55
56 boost::asio::steady_timer timer{boost::asio::get_associated_executor(cyield), timeout};
57 timer.async_wait([&cancellationSignal, operationCompleted](boost::system::error_code errorCode) {
58 if (!errorCode and !*operationCompleted)
59 cancellationSignal.emit(boost::asio::cancellation_type::terminal);
60 });
61 operation(cyield);
62 *operationCompleted = true;
63
64 // Map error code to timeout
65 if (error == boost::system::errc::operation_canceled) {
66 return boost::system::errc::make_error_code(boost::system::errc::timed_out);
67 }
68 return error;
69}
70
71} // namespace util
This namespace contains various utilities.
Definition AccountUtils.hpp:30
boost::system::error_code withTimeout(Operation &&operation, boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout)
Perform a coroutine operation with a timeout.
Definition WithTimeout.hpp:49