Seastar
High performance C++ framework for concurrent servers
with_timeout.hh
1/*
2 * This file is open source software, licensed to you under the terms
3 * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4 * distributed with this work for additional information regarding copyright
5 * ownership. You may not use this file except in compliance with the License.
6 *
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,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied. See the License for the
15 * specific language governing permissions and limitations
16 * under the License.
17 */
18
19/*
20 * Copyright (C) 2020 ScyllaDB.
21 */
22
23
24#pragma once
25
26#ifndef SEASTAR_MODULE
27#include <chrono>
28
29#include <seastar/core/future.hh>
30#include <seastar/core/timed_out_error.hh>
31#include <seastar/core/timer.hh>
32#include <seastar/util/modules.hh>
33#endif
34
35namespace seastar {
36
39
52SEASTAR_MODULE_EXPORT
53template<typename ExceptionFactory = default_timeout_exception_factory, typename Clock, typename Duration, typename... T>
54future<T...> with_timeout(std::chrono::time_point<Clock, Duration> timeout, future<T...> f) {
55 if (f.available()) {
56 return f;
57 }
58 auto pr = std::make_unique<promise<T...>>();
59 auto result = pr->get_future();
60 timer<Clock> timer([&pr = *pr] {
61 pr.set_exception(std::make_exception_ptr(ExceptionFactory::timeout()));
62 });
63 timer.arm(timeout);
64 // Future is returned indirectly.
65 (void)f.then_wrapped([pr = std::move(pr), timer = std::move(timer)] (auto&& f) mutable {
66 if (timer.cancel()) {
67 f.forward_to(std::move(*pr));
68 } else {
70 }
71 });
72 return result;
73}
74
76
77} // namespace seastar
A representation of a possibly not-yet-computed value.
Definition: future.hh:1240
futurize_t< FuncResult > then_wrapped(Func &&func) &noexcept
Schedule a block of code to run when the future is ready, allowing for exception handling.
Definition: future.hh:1525
bool available() const noexcept
Checks whether the future is available.
Definition: future.hh:1394
void ignore_ready_future() noexcept
Ignore any result hold by this future.
Definition: future.hh:1766
promise - allows a future value to be made available at a later time.
Definition: future.hh:934
void arm(time_point until, std::optional< duration > period={}) noexcept
bool cancel() noexcept
future< T > get_future() noexcept
Gets the promise's associated future.
Definition: future.hh:1926
future< T... > with_timeout(std::chrono::time_point< Clock, Duration > timeout, future< T... > f)
Wait for either a future, or a timeout, whichever comes first.
Definition: with_timeout.hh:54
Seastar API namespace.
Definition: abort_on_ebadf.hh:26