Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
async.hh
Go to the documentation of this file.
1#pragma once
3
5#include "nix/util/ref.hh"
6#include "nix/util/signals.hh"
7
8#include <boost/asio/co_spawn.hpp>
9#include <boost/asio/io_context.hpp>
10#include <boost/asio/post.hpp>
11#include <boost/asio/awaitable.hpp>
12#include <boost/asio/use_awaitable.hpp>
13#include <boost/asio/associated_cancellation_slot.hpp>
14
15#include <concepts>
16
17namespace nix {
18
19namespace asio = boost::asio;
20
21template<typename T, std::invocable<Callback<T>> F, typename CompletionToken>
22auto callbackToAwaitable(F && initiate, CompletionToken && token)
23{
24 return asio::async_initiate<CompletionToken, void(std::future<T>)>(
25 [initiate = std::forward<F>(initiate)](auto handler) mutable {
26 auto executor = asio::get_associated_executor(handler);
27 auto done = std::make_shared<std::atomic<bool>>(false);
28 auto h = std::make_shared<decltype(handler)>(std::move(handler));
29
30 if (auto slot = asio::get_associated_cancellation_slot(*h); slot.is_connected()) {
31 std::weak_ptr wh = h; /* To handle the cyclic ownership. */
32 std::weak_ptr wdone = done;
33 slot.assign([executor, wh, wdone](asio::cancellation_type /*don't care*/) {
34 auto h = wh.lock();
35 auto done = wdone.lock();
36 if (!h || !done || done->exchange(true))
37 return; /* Gracefully die. */
38 /* Doesn't need to be kept alive for get_future() since it shares the ownership. */
39 std::promise<T> p;
40 p.set_exception(std::make_exception_ptr(Interrupted("interrupted by user")));
41 asio::post(executor, [h, fut = p.get_future()]() mutable { std::move (*h)(std::move(fut)); });
42 });
43 }
44
45 initiate(
46 Callback<T>([executor,
47 done,
48 h,
49 /* Ugly, but we need a work guard for the actual executor to ensure that the io_context
50 stays alive until the callback has finished on possibly another thread. */
51 guard = asio::make_work_guard(
52 static_cast<asio::io_context &>(asio::query(executor, asio::execution::context)))](
53 std::future<T> fut) mutable {
54 auto releaseOwnership = [&]() {
55 /* Release our ownership. If the callback is owned by another thread, we don't want to be
56 responsible for tearing down the last reference to any of the captured objects. */
57 executor = {};
58 h.reset();
59 done.reset();
60 guard.reset();
61 };
62
63 if (done->exchange(true)) {
64 releaseOwnership();
65 /* Early return for cooperative cancellation. The callback has been called
66 later than we've been cancelled. In practice we'll get an error, the handler
67 has already been posted by the cancellation handler. */
68 return;
69 }
70
71 asio::post(executor, [h, fut = std::move(fut)]() mutable { std::move (*h)(std::move(fut)); });
72 releaseOwnership();
73 }));
74 },
75 std::forward<CompletionToken>(token));
76}
77
83template<typename T, std::invocable<Callback<T>> F>
84asio::awaitable<T> callbackToAwaitable(F && initiate)
85{
86 auto fut = co_await callbackToAwaitable<T>(std::forward<F>(initiate), asio::use_awaitable);
87 co_return fut.get();
88}
89
90template<typename Range, typename F>
91asio::awaitable<void> forEachAsync(Range && range, const F & f)
92{
93 /* This code only runs on a strand - we don't do multithreaded executors, so
94 no need for synchronisation. */
95 auto pending = std::ranges::size(range);
96 if (pending == 0)
97 co_return;
98 else if (pending == 1)
99 co_return co_await f(*range.begin());
100
101 auto executor = co_await asio::this_coro::executor;
102 std::exception_ptr err;
103
104 /* TODO: Handle cancellation on first error. Not very useful for now since we
105 do all-or-nothing cancellation typically. */
106 co_await asio::async_initiate<decltype(asio::use_awaitable), void(std::exception_ptr)>(
107 [&](auto handler) {
108 auto h = std::make_shared<decltype(handler)>(std::move(handler));
109 for (auto && elt : std::forward<Range>(range)) {
110 asio::co_spawn(executor, f(elt), [executor, h, &err, &pending](std::exception_ptr ex) {
111 if (ex && !err)
112 err = ex;
113 if (--pending == 0)
114 /* Post the coroutine resumption to the executor. */
115 asio::post(executor, [h = std::move(h), &err]() mutable { std::move (*h)(err); });
116 });
117 }
118 },
119 asio::use_awaitable);
120}
121
122} // namespace nix
Definition callback.hh:19