aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/cppcoro/task.h
blob: f02ec22008984958725733724d30d847257d3239 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#pragma once
#include "task_result.h"
#include <util/system/yassert.h>
#include <coroutine>

namespace NActors {

    template<class T>
    class TTask;

    /**
     * This exception is commonly thrown when task is cancelled
     */
    class TTaskCancelled : public std::exception {
    public:
        const char* what() const noexcept {
            return "Task cancelled";
        }
    };

    namespace NDetail {

        template<class T>
        class TTaskPromise;

        template<class T>
        using TTaskHandle = std::coroutine_handle<TTaskPromise<T>>;

        template<class T>
        class TTaskAwaiter {
        public:
            explicit TTaskAwaiter(TTaskHandle<T> handle)
                : Handle(handle)
            {
                Y_VERIFY_DEBUG(Handle);
            }

            TTaskAwaiter(TTaskAwaiter&& rhs)
                : Handle(std::exchange(rhs.Handle, {}))
            {}

            TTaskAwaiter& operator=(const TTaskAwaiter&) = delete;
            TTaskAwaiter& operator=(TTaskAwaiter&&) = delete;

            ~TTaskAwaiter() noexcept {
                if (Handle) {
                    Handle.destroy();
                }
            }

            // We can only await a task that has not started yet
            static bool await_ready() noexcept { return false; }

            // Some arbitrary continuation c suspended and awaits the task
            TTaskHandle<T> await_suspend(std::coroutine_handle<> c) noexcept {
                Y_VERIFY_DEBUG(Handle);
                Handle.promise().SetContinuation(c);
                return Handle;
            }

            TTaskResult<T>&& await_resume() noexcept {
                Y_VERIFY_DEBUG(Handle);
                return std::move(Handle.promise().Result);
            }

        private:
            TTaskHandle<T> Handle;
        };

        template<class T>
        class TTaskResultAwaiter final : public TTaskAwaiter<T> {
        public:
            using TTaskAwaiter<T>::TTaskAwaiter;

            T&& await_resume() {
                return TTaskAwaiter<T>::await_resume().Value();
            }
        };

        template<>
        class TTaskResultAwaiter<void> final : public TTaskAwaiter<void> {
        public:
            using TTaskAwaiter<void>::TTaskAwaiter;

            void await_resume() {
                TTaskAwaiter<void>::await_resume().Value();
            }
        };

        template<class T>
        class TTaskResultHandlerBase {
        public:
            void unhandled_exception() noexcept {
                Result.SetException(std::current_exception());
            }

        protected:
            TTaskResult<T> Result;
        };

        template<class T>
        class TTaskResultHandler : public TTaskResultHandlerBase<T> {
        public:
            template<class TResult>
            void return_value(TResult&& value) {
                this->Result.SetValue(std::forward<TResult>(value));
            }
        };

        template<>
        class TTaskResultHandler<void> : public TTaskResultHandlerBase<void> {
        public:
            void return_void() noexcept {
                this->Result.SetValue();
            }
        };

        template<class T>
        class TTaskPromise final
            : public TTaskResultHandler<T>
        {
            friend class TTaskAwaiter<T>;

        public:
            TTask<T> get_return_object() noexcept;

            static auto initial_suspend() noexcept { return std::suspend_always{}; }

            struct TFinalSuspend {
                static bool await_ready() noexcept { return false; }
                static void await_resume() noexcept { Y_FAIL("unexpected coroutine resume"); }

                static std::coroutine_handle<> await_suspend(std::coroutine_handle<TTaskPromise<T>> h) noexcept {
                    auto next = std::exchange(h.promise().Continuation, std::noop_coroutine());
                    Y_VERIFY_DEBUG(next, "Task finished without a continuation");
                    return next;
                }
            };

            static auto final_suspend() noexcept { return TFinalSuspend{}; }

        private:
            void SetContinuation(std::coroutine_handle<> continuation) noexcept {
                Y_VERIFY_DEBUG(!Continuation, "Task can only be awaited once");
                Continuation = continuation;
            }

        private:
            std::coroutine_handle<> Continuation;
        };

    } // namespace NDetail

    /**
     * Represents a task that has not been started yet
     */
    template<class T>
    class TTask final {
    public:
        using promise_type = NDetail::TTaskPromise<T>;
        using value_type = T;

    public:
        TTask() noexcept = default;

        explicit TTask(NDetail::TTaskHandle<T> handle) noexcept
            : Handle(handle)
        {}

        TTask(TTask&& rhs) noexcept
            : Handle(std::exchange(rhs.Handle, {}))
        {}

        ~TTask() {
            if (Handle) {
                Handle.destroy();
            }
        }

        TTask& operator=(TTask&& rhs) noexcept {
            if (Y_LIKELY(this != &rhs)) {
                auto handle = std::exchange(Handle, {});
                Handle = std::exchange(rhs.Handle, {});
                if (handle) {
                    handle.destroy();
                }
            }
            return *this;
        }

        /**
         * Returns true for a valid task object
         */
        explicit operator bool() const noexcept {
            return bool(Handle);
        }

        /**
         * Starts task and returns TTaskResult<T> when it completes
         */
        auto WhenDone() && noexcept {
            Y_VERIFY_DEBUG(Handle, "Cannot await an empty task");
            return NDetail::TTaskAwaiter<T>(std::exchange(Handle, {}));
        }

        /**
         * Starts task and returns its result when it completes
         */
        auto operator co_await() && noexcept {
            Y_VERIFY_DEBUG(Handle, "Cannot await an empty task");
            return NDetail::TTaskResultAwaiter<T>(std::exchange(Handle, {}));
        }

    private:
        NDetail::TTaskHandle<T> Handle;
    };

    namespace NDetail {

        template<class T>
        inline TTask<T> TTaskPromise<T>::get_return_object() noexcept {
            return TTask<T>(TTaskHandle<T>::from_promise(*this));
        }

    } // namespace NDetail

} // namespace NActors