Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
scheduler.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/diagnostics.hpp>
6
7#include <chrono>
8#include <cstddef>
9#include <cstdint>
10#include <expected>
11#include <functional>
12#include <memory>
13#include <new>
14#include <utility>
15
16namespace portals {
18using SchedulerTime = std::uint64_t;
31
32enum class SchedulerLane {
35};
36
41
46
52
59 using Reader = SchedulerTime (*)(void *) noexcept;
61 void *context{};
62};
63
66 std::size_t data_capacity{256};
67 std::size_t control_capacity{32};
68 std::size_t data_budget{32};
69 std::size_t control_budget{32};
70 std::size_t timer_budget{32};
71 std::size_t subscription_capacity{256};
72 std::shared_ptr<Diagnostics> diagnostics{};
73};
74
77 std::size_t pending{};
78 std::size_t high_water{};
79 std::uint64_t accepted{};
80 std::uint64_t rejected{};
81 std::uint64_t replaced{};
82 std::uint64_t delivered{};
83 std::uint64_t cancelled{};
87};
88
97
100 std::size_t control{};
101 std::size_t timers{};
102 std::size_t data{};
103 std::size_t callback_failures{};
104 bool stopped{};
105};
106
107namespace detail {
108struct SchedulerState;
109std::expected<PublishResult, SchedulerError> schedulerPublish(const std::shared_ptr<SchedulerState> &, std::uint64_t,
110 std::shared_ptr<const void>);
111void schedulerWake(const std::shared_ptr<SchedulerState> &) noexcept;
112void schedulerRequestStop(const std::shared_ptr<SchedulerState> &) noexcept;
113} // namespace detail
114
115class Scheduler;
116
122public:
124 Subscription() = default;
130 Subscription(Subscription &&other) noexcept;
136 Subscription(const Subscription &) = delete;
137 Subscription &operator=(const Subscription &) = delete;
141 std::expected<void, SchedulerError> disconnect();
142
143private:
144 friend class Scheduler;
145 Subscription(std::shared_ptr<detail::SchedulerState> state, std::uint64_t id);
146 std::shared_ptr<detail::SchedulerState> state_;
147 std::uint64_t id_{};
148};
149
154class UiScope {
155public:
157 UiScope() = default;
163 UiScope(UiScope &&other) noexcept;
168 UiScope &operator=(UiScope &&other) noexcept;
169 UiScope(const UiScope &) = delete;
170 UiScope &operator=(const UiScope &) = delete;
174 std::expected<void, SchedulerError> close();
175
176private:
177 friend class Scheduler;
178 UiScope(std::shared_ptr<detail::SchedulerState> state, std::uint64_t id);
179 std::shared_ptr<detail::SchedulerState> state_;
180 std::uint64_t id_{};
181};
182
189template <class T> class Publisher {
190public:
192 Publisher() = default;
193
200 std::expected<PublishResult, SchedulerError> publish(std::shared_ptr<const T> value) const {
201 return detail::schedulerPublish(state_, id_, std::move(value));
202 }
203
205 void wake() const noexcept {
206 detail::schedulerWake(state_);
207 }
208
210 void requestStop() const noexcept {
211 detail::schedulerRequestStop(state_);
212 }
213
214private:
215 friend class Scheduler;
216
217 Publisher(std::shared_ptr<detail::SchedulerState> state, std::uint64_t id) : state_(std::move(state)), id_(id) {
218 }
219
220 std::shared_ptr<detail::SchedulerState> state_;
221 std::uint64_t id_{};
222};
223
231
238class Scheduler {
239public:
241 using ErrorSink = void (*)(void *, SchedulerError) noexcept;
250 static std::expected<std::unique_ptr<Scheduler>, SchedulerError> create(SchedulerOptions options = {},
251 SchedulerClock clock = {},
252 ErrorSink sink = nullptr,
253 void *sink_context = nullptr);
256 Scheduler(const Scheduler &) = delete;
257 Scheduler &operator=(const Scheduler &) = delete;
261 std::expected<UiScope, SchedulerError> makeScope();
262
278 template <class T, class Callback>
279 std::expected<SchedulerConnection<T>, SchedulerError>
280 connect(const UiScope &scope, Callback &&callback, SchedulerLane lane = SchedulerLane::DATA,
282 try {
283 auto id = add(
284 scope,
285 [function = std::forward<Callback>(callback)](std::shared_ptr<const void> value) mutable {
286 std::invoke(function, std::static_pointer_cast<const T>(std::move(value)));
287 },
288 lane, overflow, false, 0);
289
290 if (!id) {
291 return std::unexpected(id.error());
292 }
293
294 return SchedulerConnection<T>{Subscription(state_, *id), Publisher<T>(state_, *id)};
295 } catch (const std::bad_alloc &) {
296 return std::unexpected(SchedulerError::NO_MEMORY);
297 }
298 }
299
311 template <class Callback>
312 std::expected<Subscription, SchedulerError> at(const UiScope &scope, SchedulerTime deadline, Callback &&callback) {
313 try {
314 auto id = add(
315 scope,
316 [function = std::forward<Callback>(callback)](std::shared_ptr<const void>) mutable {
317 std::invoke(function);
318 },
320
321 if (!id) {
322 return std::unexpected(id.error());
323 }
324
325 return Subscription(state_, *id);
326 } catch (const std::bad_alloc &) {
327 return std::unexpected(SchedulerError::NO_MEMORY);
328 }
329 }
330
335 std::expected<SchedulerDispatch, SchedulerError> dispatch();
342 std::expected<SchedulerWake, SchedulerError> waitFor(std::chrono::milliseconds timeout);
344 void requestStop() noexcept;
348 std::expected<void, SchedulerError> stop();
356 Diagnostics *diagnostics() const noexcept;
357
358private:
359 explicit Scheduler(std::shared_ptr<detail::SchedulerState> state);
360 std::expected<std::uint64_t, SchedulerError> add(const UiScope &, std::function<void(std::shared_ptr<const void>)>,
361 SchedulerLane, SchedulerOverflow, bool timer,
362 SchedulerTime deadline);
363 std::shared_ptr<detail::SchedulerState> state_;
364};
365} // namespace portals
Explicit, thread-safe metadata recorder. Disabled by default; no clocks or I/O. enable/disable/snapsh...
Definition diagnostics.hpp:141
Copyable, worker-safe endpoint. It owns the closed channel state, never UI captures....
Definition scheduler.hpp:189
Publisher()=default
Empty closed endpoint.
void requestStop() const noexcept
Close all publications; UI reclaims callbacks.
Definition scheduler.hpp:210
std::expected< PublishResult, SchedulerError > publish(std::shared_ptr< const T > value) const
Transfer a strong immutable owner; null is INVALID_ARGUMENT, full is WOULD_BLOCK. No allocation occur...
Definition scheduler.hpp:200
void wake() const noexcept
Wake a waiter without queueing work.
Definition scheduler.hpp:205
One UI executor; call dispatch only between frames, never during layout/paint. create captures its ca...
Definition scheduler.hpp:238
std::expected< Subscription, SchedulerError > at(const UiScope &scope, SchedulerTime deadline, Callback &&callback)
Register a cancellable one-shot timer at an absolute clock millisecond. Due timers run in deadline/re...
Definition scheduler.hpp:312
void requestStop() noexcept
Worker-safe while this object lives; sender variant can outlive it.
std::expected< SchedulerDispatch, SchedulerError > dispatch()
UI-only; nested dispatch rejected, callback exceptions contained.
void(*)(void *, SchedulerError) noexcept ErrorSink
UI error sink; borrowed context must outlive Scheduler, sink must not throw.
Definition scheduler.hpp:241
Diagnostics * diagnostics() const noexcept
Borrow the configured recorder; its lifetime is retained by this scheduler.
std::expected< SchedulerWake, SchedulerError > waitFor(std::chrono::milliseconds timeout)
UI-only bounded blocking wait; negative timeout invalid, dispatch reentry rejected....
std::expected< void, SchedulerError > stop()
UI-only close and reclamation, including self-stop.
SchedulerMetrics metrics() const
Thread-safe copy, usable after stop.
std::expected< UiScope, SchedulerError > makeScope()
UI-only; closed/identity exhaustion are explicit.
~Scheduler()
Stop/reclaim on owner; no joins; destroying from a callback is prohibited.
std::expected< SchedulerConnection< T >, SchedulerError > connect(const UiScope &scope, Callback &&callback, SchedulerLane lane=SchedulerLane::DATA, SchedulerOverflow overflow=SchedulerOverflow::REJECT)
UI-only typed registration; copies/moves and owns callback, translating bad_alloc....
Definition scheduler.hpp:280
static std::expected< std::unique_ptr< Scheduler >, SchedulerError > create(SchedulerOptions options={}, SchedulerClock clock={}, ErrorSink sink=nullptr, void *sink_context=nullptr)
Allocate bounded storage; invalid limits/no memory return errors without partial state....
UI-owned move-only cancellation token. Release before Scheduler. Disconnect is immediate logically; a...
Definition scheduler.hpp:121
Subscription(Subscription &&other) noexcept
Transfer ownership on UI.
Subscription & operator=(Subscription &&other) noexcept
Disconnect old token, then transfer.
Subscription()=default
Empty disconnected token.
~Subscription()
Disconnect on UI; never joins a worker.
std::expected< void, SchedulerError > disconnect()
UI-only, idempotent; WRONG_THREAD leaves unchanged.
UI-owned scope disconnecting all its subscriptions and timers, in any token order....
Definition scheduler.hpp:154
UiScope & operator=(UiScope &&other) noexcept
Close old scope, then transfer.
UiScope(UiScope &&other) noexcept
Transfer scope on UI.
~UiScope()
Close on UI; wrong-thread destruction terminates.
std::expected< void, SchedulerError > close()
UI-only, idempotent; no worker join.
UiScope()=default
Empty closed scope.
Public Portals API.
Definition action.hpp:8
SchedulerError
Observable operation failures; no callback is started on rejection.
Definition scheduler.hpp:20
@ WRONG_SCHEDULER
The supplied scope belongs to another scheduler.
Definition scheduler.hpp:23
@ REENTRANT_DISPATCH
Dispatch or blocking wait was called from active dispatch.
Definition scheduler.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition scheduler.hpp:26
SchedulerOverflow
Replace only this sender's pending display snapshot; never raw domain events.
Definition scheduler.hpp:37
@ REPLACE_LATEST
Replace only this sender's pending data snapshot, preserving its FIFO position.
Definition scheduler.hpp:39
@ REJECT
Reject publication when the lane has no free queue slot.
Definition scheduler.hpp:38
@ READY
Successful nonempty content; the reserved status strip is blank.
Definition data_presentation.hpp:12
PublishResult
Whether a publication appended a value or replaced its sender's pending value.
Definition scheduler.hpp:42
@ QUEUED
A new queue entry was accepted.
Definition scheduler.hpp:43
SchedulerLane
Independent finite queues; control is serviced before data each cycle.
Definition scheduler.hpp:32
@ DATA
Ordinary immutable data publications.
Definition scheduler.hpp:33
@ REPLACED
A later snapshot displaced this publication.
Definition diagnostics.hpp:42
@ CALLBACK_FAILED
A non-allocation exception escaped into a runner callback boundary.
Definition application.hpp:34
@ NO_MEMORY
Allocation failed at a runner exception boundary.
Definition application.hpp:33
@ CLOSED
Owner, node scope, scheduler or completion endpoint is closed.
Definition async.hpp:28
@ WRONG_THREAD
The operation or coroutine frame belongs to another thread.
Definition async.hpp:27
@ WOULD_BLOCK
Active resume, invocation, registration or queue capacity rejects the operation.
Definition async.hpp:30
@ IDENTITY_EXHAUSTED
Invocation identity cannot advance without reuse.
Definition async.hpp:33
@ INVALID_ARGUMENT
Empty task, callback or immutable data owner, or invalid policy.
Definition async.hpp:26
@ CONTROL
Nonzero ASCII control byte, including DEL.
Definition document_hex.hpp:21
@ TIMEOUT
Control sequence, control string or paste reached its deadline; reset is required.
Definition input.hpp:359
std::uint64_t SchedulerTime
Monotonic milliseconds; the clock must not move backwards.
Definition scheduler.hpp:18
SchedulerWake
A finite wait ended by work, explicit wake, stop or timeout.
Definition scheduler.hpp:47
@ STOPPED
Stop was requested; no further publications are accepted.
Definition scheduler.hpp:49
Borrowed clock service, invoked under the scheduler mutex on UI or producer threads....
Definition scheduler.hpp:57
SchedulerTime(*)(void *) noexcept Reader
Read monotonic milliseconds from the borrowed context; cannot throw or reenter the scheduler.
Definition scheduler.hpp:59
void * context
Borrowed reader context.
Definition scheduler.hpp:61
Reader read
Monotonic millisecond reader.
Definition scheduler.hpp:60
UI owns the subscription; workers receive copies of only the publisher.
Definition scheduler.hpp:227
Publisher< T > publisher
Worker-safe publication endpoint.
Definition scheduler.hpp:229
Subscription subscription
Scoped callback owner.
Definition scheduler.hpp:228
One bounded dispatch result; stop can interrupt the cycle after the current callback.
Definition scheduler.hpp:99
std::size_t data
Data callbacks started.
Definition scheduler.hpp:102
std::size_t callback_failures
Exceptions reported to the error sink.
Definition scheduler.hpp:103
bool stopped
Stop was requested; resources were reclaimed on UI.
Definition scheduler.hpp:104
std::size_t timers
Timer callbacks started.
Definition scheduler.hpp:101
std::size_t control
Control callbacks started.
Definition scheduler.hpp:100
Thread-safe, copied metrics; no retained samples or unbounded history.
Definition scheduler.hpp:90
std::uint64_t cycles
Complete or stop-interrupted dispatch calls.
Definition scheduler.hpp:95
std::uint64_t callback_failures
Exceptions caught at dispatch.
Definition scheduler.hpp:94
SchedulerQueueMetrics data
Data queue evidence.
Definition scheduler.hpp:91
std::uint64_t timer_callbacks
Invoked one-shot timers.
Definition scheduler.hpp:93
SchedulerQueueMetrics control
Control queue evidence.
Definition scheduler.hpp:92
Finite resource limits and maximum work per dispatch; all fields must be positive.
Definition scheduler.hpp:65
std::size_t control_budget
Maximum control deliveries per cycle.
Definition scheduler.hpp:69
std::size_t timer_budget
Maximum due one-shot timers per cycle.
Definition scheduler.hpp:70
std::shared_ptr< Diagnostics > diagnostics
Optional shared recorder; disabled by default.
Definition scheduler.hpp:72
std::size_t control_capacity
Maximum queued keyboard/resize/quit owners.
Definition scheduler.hpp:67
std::size_t data_budget
Maximum data deliveries per cycle.
Definition scheduler.hpp:68
std::size_t subscription_capacity
Maximum live subscriptions and timers together.
Definition scheduler.hpp:71
std::size_t data_capacity
Maximum queued data owners.
Definition scheduler.hpp:66
Queue counters saturate at UINT64_MAX; latency is measured in clock milliseconds.
Definition scheduler.hpp:76
std::uint64_t cancelled
Queued values discarded by disconnect/stop.
Definition scheduler.hpp:83
std::uint64_t replaced
Pending display values replaced.
Definition scheduler.hpp:81
SchedulerTime last_latency
Delay from most recent accepted value to invocation.
Definition scheduler.hpp:84
std::size_t high_water
Largest occupancy.
Definition scheduler.hpp:78
std::uint64_t rejected
Publications rejected for capacity.
Definition scheduler.hpp:80
SchedulerTime total_latency
Saturating sum of delivered queue delays.
Definition scheduler.hpp:86
std::size_t pending
Current occupancy.
Definition scheduler.hpp:77
std::uint64_t accepted
Successful publications, including replacements.
Definition scheduler.hpp:79
SchedulerTime max_latency
Maximum observed queue delay.
Definition scheduler.hpp:85
std::uint64_t delivered
Callback invocations, including throwing callbacks.
Definition scheduler.hpp:82