Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
background.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/async.hpp>
6#include <portals/background_options.hpp>
7
8#include <stop_token>
9#include <type_traits>
10
11namespace portals {
13
19public:
20 virtual ~BackgroundJob() = default;
24 virtual void run(std::stop_token stop) noexcept = 0;
28 virtual std::expected<void, AsyncError> publish() = 0;
30 void requestStop() noexcept;
32 std::stop_token stopToken() const noexcept;
33
34private:
35 std::stop_source stop_;
36};
37
40public:
41 BackgroundTicket() = default;
49 BackgroundTicket(const BackgroundTicket &) = delete;
51
55 explicit BackgroundTicket(std::weak_ptr<BackgroundJob> job) : job_(std::move(job)) {
56 }
57
61 void cancel() noexcept;
62
63private:
64 std::weak_ptr<BackgroundJob> job_;
65};
66
73public:
74 virtual ~BackgroundExecutor() = default;
78 virtual std::expected<BackgroundTicket, BackgroundError> submit(std::unique_ptr<BackgroundJob> &job) = 0;
80 virtual void service() noexcept = 0;
82 virtual std::uint64_t capacityEpoch() const noexcept = 0;
86 virtual BackgroundWorkerStorage *workerStorage() noexcept { return nullptr; }
87};
88
96class BackgroundPool final : public BackgroundExecutor {
97public:
102 static std::expected<std::unique_ptr<BackgroundPool>, BackgroundError> create(BackgroundOptions options = {},
103 Publisher<int> wake = {});
104 ~BackgroundPool() override;
105 BackgroundPool(const BackgroundPool &) = delete;
106 BackgroundPool &operator=(const BackgroundPool &) = delete;
107 std::expected<BackgroundTicket, BackgroundError> submit(std::unique_ptr<BackgroundJob> &job) override;
108 void service() noexcept override;
109 std::uint64_t capacityEpoch() const noexcept override;
115 void requestStop() noexcept;
119 void join() noexcept;
120
121private:
122 struct State;
123 explicit BackgroundPool(std::unique_ptr<State> state);
124 std::unique_ptr<State> state_;
125};
126
132
139public:
141 explicit BackgroundLatest(BackgroundExecutor &executor) : executor_(executor) {
142 }
143
145 BackgroundLatest(const BackgroundLatest &) = delete;
146 BackgroundLatest &operator=(const BackgroundLatest &) = delete;
150 std::expected<BackgroundAdmission, BackgroundError> replace(std::unique_ptr<BackgroundJob> job);
152 std::expected<BackgroundAdmission, BackgroundError> service();
154 void cancel() noexcept;
155
156private:
157 std::expected<BackgroundAdmission, BackgroundError> admit();
158 BackgroundExecutor &executor_;
159 BackgroundTicket ticket_;
160 std::unique_ptr<BackgroundJob> pending_;
161 std::uint64_t observed_{};
162};
163
164namespace detail {
166template <class Input, class Output, class Work> class BackgroundTransform final : public BackgroundJob {
167public:
168 BackgroundTransform(std::shared_ptr<const Input> input, AsyncReply<Output> reply, Work work)
169 : input_(std::move(input)), reply_(std::move(reply)), work_(std::move(work)) {
170 }
171
172 void run(std::stop_token stop) noexcept override {
173 try {
174 result_ = std::invoke(work_, *input_, stop);
175
176 if (stop.stop_requested()) {
177 result_ = std::unexpected(AsyncError::CANCELLED);
178 } else if (result_ && !*result_) {
179 result_ = std::unexpected(AsyncError::INVALID_ARGUMENT);
180 }
181 } catch (const std::bad_alloc &) {
182 result_ = std::unexpected(AsyncError::NO_MEMORY);
183 } catch (...) {
184 result_ = std::unexpected(AsyncError::CALLBACK_FAILED);
185 }
186 }
187
188 std::expected<void, AsyncError> publish() override {
189 auto sent = result_ ? reply_.complete(*result_) : reply_.fail(result_.error());
190
191 if (!sent) {
192 return std::unexpected(sent.error());
193 }
194
195 return {};
196 }
197
198private:
199 std::shared_ptr<const Input> input_;
200 AsyncReply<Output> reply_;
201 Work work_;
202 std::expected<std::shared_ptr<const Output>, AsyncError> result_{std::unexpected(AsyncError::CANCELLED)};
203};
205} // namespace detail
206
218template <class Input, class Output, class Work>
219 requires std::is_nothrow_move_constructible_v<Work>
220std::expected<std::unique_ptr<BackgroundJob>, BackgroundError> makeBackgroundJob(std::shared_ptr<const Input> input,
221 AsyncReply<Output> reply, Work work) {
222 if (!input) {
223 return std::unexpected(BackgroundError::INVALID_ARGUMENT);
224 }
225
226 try {
227 return std::make_unique<detail::BackgroundTransform<Input, Output, Work>>(std::move(input), std::move(reply),
228 std::move(work));
229 } catch (const std::bad_alloc &) {
230 return std::unexpected(BackgroundError::NO_MEMORY);
231 }
232}
233} // namespace portals
Copyable producer endpoint owning no UI state, callbacks or coroutine frame. T and its deleter must s...
Definition async.hpp:213
Borrowed host service. A scene never owns, stops or joins this executor. UI integration calls service...
Definition background.hpp:72
virtual void service() noexcept=0
Permit one publication retry per blocked worker; does not wait or invoke UI callbacks.
virtual ~BackgroundExecutor()=default
Concrete owning executors define their final join boundary.
virtual BackgroundWorkerStorage * workerStorage() noexcept
Definition background.hpp:86
virtual std::uint64_t capacityEpoch() const noexcept=0
virtual std::expected< BackgroundTicket, BackgroundError > submit(std::unique_ptr< BackgroundJob > &job)=0
Worker-safe work item; never retain Application, UI references, callbacks or coroutine frames....
Definition background.hpp:18
std::stop_token stopToken() const noexcept
void requestStop() noexcept
Request cancellation without joining. Registered stop callbacks run synchronously and must be short.
virtual ~BackgroundJob()=default
Release worker-safe owning input and prepared result.
virtual void run(std::stop_token stop) noexcept=0
virtual std::expected< void, AsyncError > publish()=0
void cancel() noexcept
Cancel admitted work and release the latest unadmitted intent; no worker join.
std::expected< BackgroundAdmission, BackgroundError > replace(std::unique_ptr< BackgroundJob > job)
BackgroundLatest(BackgroundExecutor &executor)
Definition background.hpp:141
~BackgroundLatest()
Cancel this source's admitted work without stopping the borrowed executor.
std::expected< BackgroundAdmission, BackgroundError > service()
static std::expected< std::unique_ptr< BackgroundPool >, BackgroundError > create(BackgroundOptions options={}, Publisher< int > wake={})
void join() noexcept
Stop and join owned workers; may wait for cooperative user code, never services UI....
std::expected< BackgroundTicket, BackgroundError > submit(std::unique_ptr< BackgroundJob > &job) override
std::uint64_t capacityEpoch() const noexcept override
void service() noexcept override
Permit one publication retry per blocked worker; does not wait or invoke UI callbacks.
BackgroundWorkerStorage * workerStorage() noexcept override
void requestStop() noexcept
Close admission, cancel owned jobs and wake workers independently of scheduler progress.
Move-only cancellation ownership; destruction requests cancellation but never joins.
Definition background.hpp:39
BackgroundTicket(BackgroundTicket &&other) noexcept
void cancel() noexcept
Request cooperative cancellation; stop callbacks must return promptly. This retires work without publ...
~BackgroundTicket()
Request cancellation; never wait for a worker.
BackgroundTicket(std::weak_ptr< BackgroundJob > job)
Definition background.hpp:55
BackgroundTicket & operator=(BackgroundTicket &&other) noexcept
BackgroundTicket()=default
Empty inactive ticket.
Optional executor capability for bounded opaque worker-owned caches. Direct operations borrow the liv...
Definition worker_storage.hpp:94
Copyable, worker-safe endpoint. It owns the closed channel state, never UI captures....
Definition scheduler.hpp:189
Public Portals API.
Definition action.hpp:8
BackgroundAdmission
Whether the newest source intent was admitted or retained for a future capacity change.
Definition background.hpp:128
@ STARTED
No unadmitted intent remains; an accepted job may still be running.
Definition background.hpp:129
@ RETAINED
Exactly one latest unadmitted owning intent remains.
Definition background.hpp:130
AsyncError
Failures of the optional single-frame UI coroutine adapter.
Definition async.hpp:25
BackgroundError
Executor admission and startup failures; domain errors stay in the result value.
Definition background_options.hpp:11
@ INVALID_ARGUMENT
Null job or zero worker/pending capacity.
Definition background_options.hpp:12
@ NO_MEMORY
An executor allocation failed.
Definition background_options.hpp:16
std::expected< std::unique_ptr< BackgroundJob >, BackgroundError > makeBackgroundJob(std::shared_ptr< const Input > input, AsyncReply< Output > reply, Work work)
Prepare owning immutable work without running it on the caller's UI thread.
Definition background.hpp:220
Count bounds, independent of the transitive byte size of inputs and results.
Definition background_options.hpp:24