Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
window_source.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/row_id.hpp>
6#include <portals/source_budget.hpp>
7#include <portals/widget.hpp>
8
9#include <algorithm>
10#include <array>
11#include <atomic>
12#include <cstddef>
13#include <cstdint>
14#include <expected>
15#include <limits>
16#include <memory>
17#include <optional>
18#include <span>
19#include <stop_token>
20#include <thread>
21#include <type_traits>
22#include <utility>
23#include <vector>
24
25namespace portals {
28 std::uint64_t instance{};
29 std::uint64_t epoch{};
33 bool operator==(const SourceStamp &other) const noexcept = default;
34};
35
39 std::array<std::uint64_t, 2> token{};
43 bool operator==(const SourceCursor &other) const noexcept = default;
44};
45
51
58
64
71
74 bool backward{};
75 bool seekRow{};
76 bool tail{};
77};
78
81 std::uint64_t initialRevision{1};
82 std::size_t pageBytes{256 * 1024};
83 std::size_t maxRowBytes{64 * 1024};
84 std::size_t maxPageRows{1024};
85 std::size_t workspaceBytes{128 * 1024};
86 std::size_t envelopeBytes{4096};
87};
88
97
101template <class T> struct WindowRow {
103 std::uint64_t valueRevision;
105
111 template <class... Args>
112 WindowRow(RowId identity, std::uint64_t revision, Args &&...args)
113 : id(identity), valueRevision(revision), value(std::forward<Args>(args)...) {
114 }
115};
116
118namespace detail {
119inline SourceError sourceTreeError(TreeError error) {
120 switch (error) {
126 return SourceError::CLOSED;
135 default:
137 }
138}
139
140std::expected<SourceStamp, SourceError> windowSourceStamp();
141
142template <class T> struct WindowPageData {
143 explicit WindowPageData(std::shared_ptr<SourceArena> storage) : arena(std::move(storage)) {
144 }
145
146 ~WindowPageData() {
147 while (count) {
148 std::destroy_at(rows + --count);
149 }
150 }
151
152 std::shared_ptr<SourceArena> arena;
153 WindowRow<T> *rows{};
154 std::size_t count{};
155 SourceCursor before;
156 SourceCursor after;
157 std::uint64_t revision{};
158};
159} // namespace detail
160
162
163template <class T> class PageBuilder;
164
168template <class T> class WindowPage {
169public:
170 WindowPage() = default;
171
173 std::span<const WindowRow<T>> rows() const noexcept {
174 return data_ ? std::span<const WindowRow<T>>(data_->rows, data_->count) : std::span<const WindowRow<T>>{};
175 }
176
178 SourceCursor before() const noexcept {
179 return data_ ? data_->before : SourceCursor{};
180 }
181
183 SourceCursor after() const noexcept {
184 return data_ ? data_->after : SourceCursor{};
185 }
186
188 std::uint64_t dataRevision() const noexcept {
189 return data_ ? data_->revision : 0;
190 }
191
192private:
193 friend class PageBuilder<T>;
194
195 explicit WindowPage(std::shared_ptr<const detail::WindowPageData<T>> data) : data_(std::move(data)) {
196 }
197
198 std::shared_ptr<const detail::WindowPageData<T>> data_;
199};
200
208
220
224template <class T> class PageBuilder {
225public:
227 std::pmr::memory_resource *resource() noexcept {
228 return data_->arena.get();
229 }
230
232 std::pmr::memory_resource *workspace() noexcept {
233 return workspace_.get();
234 }
235
242 template <class... Args> std::expected<void, SourceError> emplace(RowId id, std::uint64_t revision, Args &&...args) {
243 if (sealed_ || !id.value || !id.generation || !revision || data_->count >= command_.maxRows) {
244 return std::unexpected(SourceError::INVALID_ARGUMENT);
245 }
246
247 if (sizeof(WindowRow<T>) > maxRowBytes_) {
248 return std::unexpected(SourceError::ROW_TOO_LARGE);
249 }
250
251 auto used = data_->arena->used();
252 auto row = data_->rows + data_->count;
253
254 try {
255 std::construct_at(row, id, revision, std::forward<Args>(args)...);
256 } catch (const std::bad_alloc &) {
257 return std::unexpected(SourceError::PAGE_TOO_LARGE);
258 } catch (...) {
259 return std::unexpected(SourceError::CALLBACK_FAILED);
260 }
261
262 if (data_->arena->used() - used > maxRowBytes_ - sizeof(WindowRow<T>)) {
263 std::destroy_at(row);
264
265 return std::unexpected(SourceError::ROW_TOO_LARGE);
266 }
267
268 ++data_->count;
269
270 return {};
271 }
272
278 std::expected<SourceReadReply<T>, SourceError> ready(SourceCursor before, SourceCursor after, SourceEdge edge) {
279 if (sealed_ || before.source != command_.source || after.source != command_.source) {
280 return std::unexpected(SourceError::INVALID_REPLY);
281 }
282
283 data_->before = before;
284 data_->after = after;
285 data_->revision = command_.dataRevision;
286 sealed_ = true;
287 SourceReadReply<T> result;
289 result.page = WindowPage<T>(data_);
290 result.edge = edge;
291
292 return result;
293 }
294
295private:
296 template <class> friend class WindowRequest;
297
298 PageBuilder(SourceReadCommand command, std::shared_ptr<SourceArena> arena, std::shared_ptr<SourceArena> workspace,
299 std::size_t maxRowBytes)
300 : command_(command), workspace_(std::move(workspace)), maxRowBytes_(maxRowBytes) {
301 static_assert(std::is_nothrow_destructible_v<T>);
302 static_assert(sizeof(detail::WindowPageData<T>) < SourceArena::METADATA_BYTES / 2);
303 data_ = std::make_shared<detail::WindowPageData<T>>(std::move(arena));
304
305 if (command.maxRows > data_->arena->capacity() / sizeof(WindowRow<T>)) {
306 throw std::bad_alloc();
307 }
308
309 data_->rows = static_cast<WindowRow<T> *>(
310 data_->arena->allocate(command.maxRows * sizeof(WindowRow<T>), alignof(WindowRow<T>)));
311 }
312
313 SourceReadCommand command_;
314 std::shared_ptr<detail::WindowPageData<T>> data_;
315 std::shared_ptr<SourceArena> workspace_;
316 std::size_t maxRowBytes_;
317 bool sealed_{};
318};
319
323template <class T> class WindowProvider {
324public:
325 virtual ~WindowProvider() = default;
327 virtual SourceCapabilities capabilities() const noexcept = 0;
333 virtual std::expected<SourceReadReply<T>, SourceError> load(const SourceReadCommand &command, PageBuilder<T> &out,
334 std::stop_token stop) = 0;
335};
336
347
349namespace detail {
350template <class T> struct WindowState;
351template <class T> struct WindowConsumerState;
352template <class T> struct WindowWork;
353struct WindowRequestAccess;
354
355template <class T> struct WindowFrameData {
356 SourceCredit credit;
357 std::array<WindowPage<T>, 4> pages;
358 std::size_t count{};
359 std::size_t rows{};
360 SourceCursor continuation;
361 SourceEdge edge{SourceEdge::MORE};
362 std::uint64_t revision{};
363};
364
365template <class T> struct WindowCompletion {
366 std::shared_ptr<WindowWork<T>> work;
367 SourceReadReply<T> reply;
368};
369
370struct WindowNotification {
371 SourceCredit credit;
372 SourceStamp source;
373 std::uint64_t revision;
374};
375
376// Only scheduler callback captures own this marker. Node/scope retirement releases it
377// before WidgetTree destruction, so weak-marker validation precedes every raw-tree access.
378struct WindowScopeMarker {};
379
380template <class T> struct WindowWork {
381 SourceCredit credit;
382 SourceCredit pageCredit;
383 std::shared_ptr<SourceArena> workspace;
384 std::shared_ptr<WindowProvider<T>> provider;
385 std::shared_ptr<std::atomic<bool>> alive;
386 std::weak_ptr<WindowScopeMarker> marker;
387 std::weak_ptr<WindowConsumerState<T>> consumer;
388 Publisher<WindowCompletion<T>> publisher;
389 SourceReadCommand command;
390 WindowSourceOptions options;
391 std::thread::id uiThread;
392 std::uint64_t generation{};
393 std::stop_source stop;
394 std::atomic<bool> loaded{};
395 std::atomic<bool> submitted{};
396};
397} // namespace detail
398
400
404template <class T> class WindowPin {
405public:
406 WindowPin() = default;
407
409 std::size_t pageCount() const noexcept {
410 return data_ ? data_->count : 0;
411 }
412
414 std::size_t size() const noexcept {
415 return data_ ? data_->rows : 0;
416 }
417
421 WindowPage<T> page(std::size_t index) const noexcept {
422 return data_ && index < data_->count ? data_->pages[index] : WindowPage<T>{};
423 }
424
426 SourceCursor continuation() const noexcept {
427 return data_ ? data_->continuation : SourceCursor{};
428 }
429
431 SourceEdge edge() const noexcept {
432 return data_ ? data_->edge : SourceEdge::MORE;
433 }
434
436 std::uint64_t dataRevision() const noexcept {
437 return data_ ? data_->revision : 0;
438 }
439
440private:
441 template <class> friend class WindowConsumer;
442
443 explicit WindowPin(std::shared_ptr<const detail::WindowFrameData<T>> data) : data_(std::move(data)) {
444 }
445
446 std::shared_ptr<const detail::WindowFrameData<T>> data_;
447};
448
454template <class T> class WindowRequest {
455public:
456 WindowRequest() = default;
457
459 SourceReadCommand command() const noexcept {
460 return work_ ? work_->command : SourceReadCommand{};
461 }
462
464 bool stopRequested() const noexcept {
465 return !work_ || !work_->alive->load() || work_->marker.expired() || work_->stop.stop_requested();
466 }
467
471 void cancel() const noexcept {
472 if (work_) {
473 work_->stop.request_stop();
474 }
475 }
476
480 std::expected<SourceReadReply<T>, SourceError> load(std::stop_token external = {}) const {
481 return loadUsing(
482 [](WindowProvider<T> &provider, const SourceReadCommand &command, PageBuilder<T> &out, std::stop_token stop) {
483 return provider.load(command, out, stop);
484 },
485 external);
486 }
487
491 std::expected<PublishResult, SchedulerError>
492 complete(const std::expected<SourceReadReply<T>, SourceError> &reply) const {
493 auto work = work_;
494
495 if (stopRequested()) {
496 return std::unexpected(SchedulerError::CLOSED);
497 }
498
499 bool expected = false;
500
501 if (!work->submitted.compare_exchange_strong(expected, true)) {
502 return std::unexpected(SchedulerError::CLOSED);
503 }
504
505 try {
506 SourceReadReply<T> value;
507
508 if (reply) {
509 value = *reply;
510 } else {
511 value.state = SourceReadState::FAILED;
512 value.error = reply.error();
513 }
514
515 auto event = std::make_shared<const detail::WindowCompletion<T>>(work, std::move(value));
516 auto published = work->publisher.publish(std::move(event));
517
518 if (!published) {
519 work->submitted.store(false);
520 }
521
522 return published;
523 } catch (const std::bad_alloc &) {
524 work->submitted.store(false);
525
526 return std::unexpected(SchedulerError::NO_MEMORY);
527 }
528 }
529
530private:
531 friend struct detail::WindowRequestAccess;
532 template <class> friend class WindowConsumer;
533
534 template <class Loader>
535 std::expected<SourceReadReply<T>, SourceError> loadUsing(Loader &&loader, std::stop_token external) const {
536 auto work = work_;
537
538 if (stopRequested()) {
539 return std::unexpected(SourceError::CANCELLED);
540 }
541
542 if (work->uiThread == std::this_thread::get_id()) {
543 return std::unexpected(SourceError::WRONG_THREAD);
544 }
545
546 if (work->loaded.exchange(true)) {
547 return std::unexpected(SourceError::ALREADY_COMPLETED);
548 }
549
550 std::stop_callback stop(external, [work] {
551 work->stop.request_stop();
552 });
553
554 try {
555 auto arena = SourceArena::create(std::move(work->pageCredit));
556
557 if (!arena) {
558 return std::unexpected(arena.error());
559 }
560
561 auto temporary = work->credit.split({work->options.workspaceBytes, 0, 0, 0});
562 auto workspace = SourceArena::create(std::move(*temporary));
563
564 if (!workspace) {
565 return std::unexpected(workspace.error());
566 }
567
568 work->workspace = *workspace;
569 PageBuilder<T> out(work->command, std::move(*arena), *workspace, work->options.maxRowBytes);
570 auto reply = std::forward<Loader>(loader)(*work->provider, work->command, out, work->stop.get_token());
571
572 if (stopRequested()) {
573 return std::unexpected(SourceError::CANCELLED);
574 }
575
576 return reply;
577 } catch (const std::bad_alloc &) {
578 return std::unexpected(SourceError::NO_MEMORY);
579 } catch (...) {
580 return std::unexpected(SourceError::CALLBACK_FAILED);
581 }
582 }
583
584 explicit WindowRequest(std::shared_ptr<detail::WindowWork<T>> work) : work_(std::move(work)) {
585 }
586
587 std::shared_ptr<detail::WindowWork<T>> work_;
588};
589
591namespace detail {
592// Trusted adapters preserve richer per-call failures on their owning worker job.
593// The loader receives the actual captured provider and shares public load()'s
594// affinity, single-load, cancellation and reservation gates without a side channel.
595struct WindowRequestAccess {
596 template <class T, class Loader>
597 static std::expected<SourceReadReply<T>, SourceError> load(const WindowRequest<T> &request, Loader &&loader,
598 std::stop_token external = {}) {
599 return request.loadUsing(std::forward<Loader>(loader), external);
600 }
601};
602
603template <class T> struct WindowConsumerState {
604 SourceCredit credit;
605 std::shared_ptr<WindowState<T>> source;
606 std::shared_ptr<const WindowFrameData<T>> current;
607 std::shared_ptr<WindowWork<T>> pending;
608 std::weak_ptr<WindowWork<T>> active;
609 std::array<WindowPage<T>, 4> pages;
610 std::array<SourceCursor, 5> visited;
611 SourceAnchor intent;
612 SourceDirection direction{SourceDirection::FORWARD};
613 std::uint64_t generation{};
614 std::uint64_t desiredRevision{1};
615 std::uint64_t attemptedRevision{};
616 std::uint64_t fillRevision{};
617 std::size_t target{};
618 std::size_t accumulated{};
619 std::size_t pageCount{};
620 std::size_t visitedCount{};
621 std::size_t loads{};
622 WindowStatus status{WindowStatus::EMPTY};
623 std::optional<SourceError> error;
624 std::optional<SourceCursor> recovery;
625 bool retryNeeded{};
626 bool closed{};
627};
628
629template <class T> struct WindowState {
630 WindowState(WidgetTree &value, Node<Widget> node, std::size_t consumers)
631 : tree(value), target(node), slots(consumers) {
632 }
633
634 std::expected<void, SourceError> allowed() const {
635 if (owner != std::this_thread::get_id()) {
636 return std::unexpected(SourceError::WRONG_THREAD);
637 }
638
639 if (!alive->load() || marker.expired()) {
640 return std::unexpected(SourceError::CLOSED);
641 }
642
643 auto result = tree.withScope(target, [](const UiScope &) {
644 });
645
646 if (!result) {
647 return std::unexpected(sourceTreeError(result.error()));
648 }
649
650 return {};
651 }
652
653 SourceCredit credit;
654 WidgetTree &tree;
655 Node<Widget> target;
656 const std::thread::id owner{std::this_thread::get_id()};
657 std::shared_ptr<SourceBudget> budget;
658 std::shared_ptr<WindowProvider<T>> provider;
659 std::shared_ptr<std::atomic<bool>> alive;
660 std::weak_ptr<WindowScopeMarker> marker;
661 std::vector<std::weak_ptr<WindowConsumerState<T>>> slots;
662 SourceStamp stamp;
663 SourceCapabilities capabilities;
664 WindowSourceOptions options;
665 Publisher<WindowCompletion<T>> publisher;
666 std::mutex notificationMutex;
667 std::uint64_t publishedRevision{1};
668 std::uint64_t revision{1};
669};
670
671template <class T>
672std::expected<std::shared_ptr<WindowWork<T>>, SourceError>
673admitWindowWork(const std::shared_ptr<WindowConsumerState<T>> &consumer, SourceReadCommand command,
674 std::uint64_t generation) {
675 auto source = consumer->source;
676 const auto &options = source->options;
677 auto total = options.pageBytes;
678
679 if (options.workspaceBytes > std::numeric_limits<std::size_t>::max() - total ||
680 options.envelopeBytes > std::numeric_limits<std::size_t>::max() - total - options.workspaceBytes) {
681 return std::unexpected(SourceError::INVALID_ARGUMENT);
682 }
683
684 total += options.workspaceBytes + options.envelopeBytes;
685 auto credit = source->budget->reserve({total, 1, 1, 0});
686
687 if (!credit) {
688 return std::unexpected(credit.error());
689 }
690
691 try {
692 auto work = std::make_shared<WindowWork<T>>();
693 auto page = credit->split({options.pageBytes, 1, 0, 0});
694 work->credit = std::move(*credit);
695 work->pageCredit = std::move(*page);
696 work->provider = source->provider;
697 work->alive = source->alive;
698 work->marker = source->marker;
699 work->consumer = consumer;
700 work->publisher = source->publisher;
701 work->options = options;
702 work->uiThread = source->owner;
703 work->generation = generation;
704 work->command = command;
705 work->command.maxRows =
706 std::min(command.maxRows, (options.pageBytes - SourceArena::METADATA_BYTES) / sizeof(WindowRow<T>));
707
708 return work;
709 } catch (const std::bad_alloc &) {
710 return std::unexpected(SourceError::NO_MEMORY);
711 }
712}
713
714template <class T> void failWindow(WindowConsumerState<T> &consumer, SourceError error) {
715 consumer.status = WindowStatus::FAILED;
716 consumer.error = error;
717 consumer.pageCount = 0;
718 consumer.visitedCount = 0;
719 consumer.accumulated = 0;
720 consumer.pending.reset();
721 consumer.pages = {};
722}
723
724template <class T> void restartWindow(const std::shared_ptr<WindowConsumerState<T>> &consumer) {
725 if (consumer->closed || !consumer->target || !consumer->retryNeeded ||
726 consumer->desiredRevision <= consumer->attemptedRevision) {
727 return;
728 }
729
730 consumer->attemptedRevision = consumer->desiredRevision;
731 consumer->fillRevision = consumer->desiredRevision;
732 consumer->retryNeeded = false;
733 consumer->pages = {};
734 consumer->pageCount = 0;
735 consumer->visitedCount = 0;
736 consumer->accumulated = 0;
737 consumer->loads = 0;
738 SourceReadCommand command{consumer->source->stamp, consumer->fillRevision, consumer->intent, consumer->direction,
739 std::min(consumer->source->options.maxPageRows, consumer->target)};
740 auto work = admitWindowWork(consumer, command, consumer->generation);
741
742 if (!work) {
743 failWindow(*consumer, work.error());
744
745 return;
746 }
747
748 if (consumer->closed || !consumer->source->allowed()) {
749 return;
750 }
751
752 consumer->active = *work;
753 consumer->pending = std::move(*work);
754 consumer->status = WindowStatus::LOADING;
755}
756
757template <class T>
758std::expected<void, SourceError> commitWindow(const std::shared_ptr<WindowConsumerState<T>> &consumer,
759 SourceCursor continuation, SourceEdge edge) {
760 auto source = consumer->source;
761 auto credit = source->budget->reserve({SourceArena::METADATA_BYTES, 0, 0, 0});
762
763 if (!credit) {
764 return std::unexpected(credit.error());
765 }
766
767 try {
768 auto next = std::make_shared<WindowFrameData<T>>();
769 next->credit = std::move(*credit);
770 for (std::size_t i = 0; i < consumer->pageCount; ++i) {
771 auto index = consumer->direction == SourceDirection::BACKWARD ? consumer->pageCount - i - 1 : i;
772 next->pages[i] = consumer->pages[index];
773 }
774 next->count = consumer->pageCount;
775 next->rows = consumer->accumulated;
776 next->continuation = continuation;
777 next->edge = edge;
778 next->revision = consumer->fillRevision;
779 auto allowed = source->allowed();
780
781 if (!allowed) {
782 return std::unexpected(allowed.error());
783 }
784
785 auto invalidated = source->tree.invalidate(source->target, Invalidation::LAYOUT);
786
787 if (!invalidated) {
788 return std::unexpected(sourceTreeError(invalidated.error()));
789 }
790
791 auto previous = std::exchange(consumer->current, std::move(next));
792
793 return {};
794 } catch (const std::bad_alloc &) {
795 return std::unexpected(SourceError::NO_MEMORY);
796 }
797}
798
799template <class T>
800void applyWindowCompletion(const std::shared_ptr<WindowState<T>> &source, const WindowCompletion<T> &event) {
801 auto consumer = event.work->consumer.lock();
802
803 if (!consumer || consumer->closed || consumer->generation != event.work->generation || !source->allowed()) {
804 return;
805 }
806
807 // Pending/error transitions and a newly admitted continuation also need an application cycle.
808 auto invalidated = source->tree.invalidate(source->target, Invalidation::LAYOUT);
809
810 if (!invalidated) {
811 failWindow(*consumer, sourceTreeError(invalidated.error()));
812
813 return;
814 }
815
816 consumer->active.reset();
817
818 if (event.work->stop.stop_requested()) {
819 consumer->retryNeeded = false;
820 failWindow(*consumer, SourceError::CANCELLED);
821
822 return;
823 }
824
825 if (event.work->command.dataRevision != consumer->desiredRevision ||
826 (event.reply.state == SourceReadState::FAILED && event.reply.error == SourceError::REVISION_CHANGED)) {
827 if (consumer->desiredRevision <= consumer->attemptedRevision) {
828 failWindow(*consumer, SourceError::REVISION_CHANGED);
829
830 return;
831 }
832
833 restartWindow(consumer);
834
835 return;
836 }
837
838 const auto &reply = event.reply;
839
840 if (reply.state != SourceReadState::READY) {
841 if (reply.state == SourceReadState::PENDING && reply.observedRevision == consumer->fillRevision) {
842 consumer->status = WindowStatus::PENDING;
843 } else if (reply.state == SourceReadState::HISTORY_UNAVAILABLE &&
844 (!reply.recovery || reply.recovery->source == source->stamp)) {
845 consumer->status = WindowStatus::HISTORY_UNAVAILABLE;
846 consumer->recovery = reply.recovery;
847 } else {
848 failWindow(*consumer, reply.state == SourceReadState::FAILED ? reply.error : SourceError::INVALID_REPLY);
849 }
850
851 restartWindow(consumer);
852
853 return;
854 }
855
856 const auto rows = reply.page.rows();
857 auto before = reply.page.before();
858 auto after = reply.page.after();
859 auto input = consumer->direction == SourceDirection::FORWARD ? before : after;
860 auto continuation = consumer->direction == SourceDirection::FORWARD ? after : before;
861
862 if (before.source != source->stamp || after.source != source->stamp ||
863 reply.page.dataRevision() != consumer->fillRevision || rows.size() > event.work->command.maxRows ||
864 (event.work->command.anchor.kind == SourceAnchorKind::CURSOR && input != event.work->command.anchor.cursor) ||
865 (reply.edge != SourceEdge::MORE && reply.edge != SourceEdge::TEMPORARY_TAIL &&
866 reply.edge != SourceEdge::FINAL_END) ||
867 (reply.edge == SourceEdge::TEMPORARY_TAIL && consumer->direction != SourceDirection::FORWARD)) {
868 failWindow(*consumer, SourceError::INVALID_REPLY);
869
870 return;
871 }
872
873 for (std::size_t i = 0; i < rows.size(); ++i) {
874 if (!rows[i].id.value || !rows[i].id.generation || !rows[i].valueRevision) {
875 failWindow(*consumer, SourceError::INVALID_REPLY);
876
877 return;
878 }
879
880 bool duplicate = std::ranges::any_of(rows.first(i), [&](const auto &row) {
881 return row.id == rows[i].id;
882 });
883
884 for (std::size_t page = 0; !duplicate && page < consumer->pageCount; ++page) {
885 duplicate = std::ranges::any_of(consumer->pages[page].rows(), [&](const auto &row) {
886 return row.id == rows[i].id;
887 });
888 }
889
890 if (duplicate) {
891 failWindow(*consumer, SourceError::INVALID_REPLY);
892
893 return;
894 }
895 }
896
897 if (!consumer->visitedCount) {
898 consumer->visited[consumer->visitedCount++] = input;
899 }
900
901 if (reply.edge == SourceEdge::MORE) {
902 if (continuation == input) {
903 failWindow(*consumer, SourceError::NO_PROGRESS);
904
905 return;
906 }
907
908 if (std::ranges::find(std::span(consumer->visited).first(consumer->visitedCount), continuation) !=
909 std::span(consumer->visited).first(consumer->visitedCount).end()) {
910 failWindow(*consumer, SourceError::CURSOR_CYCLE);
911
912 return;
913 }
914
915 consumer->visited[consumer->visitedCount++] = continuation;
916 }
917
918 consumer->pages[consumer->pageCount++] = reply.page;
919 consumer->accumulated += rows.size();
920 ++consumer->loads;
921 bool fulfilled = consumer->accumulated >= consumer->target;
922
923 if (fulfilled || reply.edge != SourceEdge::MORE || consumer->loads == 4) {
924 auto committed = commitWindow(consumer, continuation, reply.edge);
925
926 if (!committed) {
927 failWindow(*consumer, committed.error());
928
929 return;
930 }
931
932 if (fulfilled) {
933 consumer->status = WindowStatus::READY;
934 } else if (reply.edge == SourceEdge::FINAL_END) {
935 consumer->status = WindowStatus::FINAL_END;
936 } else if (reply.edge == SourceEdge::TEMPORARY_TAIL) {
937 consumer->status = WindowStatus::TEMPORARY_TAIL;
938 } else {
939 failWindow(*consumer, SourceError::CONTINUATION_LIMIT);
940 }
941
942 restartWindow(consumer);
943
944 return;
945 }
946
947 SourceAnchor anchor;
948 anchor.kind = SourceAnchorKind::CURSOR;
949 anchor.cursor = continuation;
950 SourceReadCommand command{source->stamp, consumer->fillRevision, anchor, consumer->direction,
951 std::min(source->options.maxPageRows, consumer->target - consumer->accumulated)};
952 auto next = admitWindowWork(consumer, command, consumer->generation);
953
954 if (!next) {
955 failWindow(*consumer, next.error());
956
957 return;
958 }
959
960 if (consumer->closed || !source->allowed()) {
961 return;
962 }
963
964 consumer->active = *next;
965 consumer->pending = std::move(*next);
966}
967} // namespace detail
968
970
974template <class T> class WindowConsumer {
975public:
976 WindowConsumer() = default;
977
979 close();
980 }
981
983 WindowConsumer(WindowConsumer &&other) noexcept : state_(std::move(other.state_)) {
984 if (state_ && state_->source->owner != std::this_thread::get_id()) {
985 std::terminate();
986 }
987 }
988
993 state_.swap(other.state_);
994
995 return *this;
996 }
997
998 WindowConsumer(const WindowConsumer &) = delete;
999
1003 std::expected<void, SourceError> cancel() {
1004 auto state = state_;
1005
1006 if (!state || state->closed) {
1007 return std::unexpected(SourceError::CLOSED);
1008 }
1009
1010 auto allowed = state->source->allowed();
1011
1012 if (!allowed) {
1013 return std::unexpected(allowed.error());
1014 }
1015
1016 auto invalidated = state->source->tree.invalidate(state->source->target, Invalidation::LAYOUT);
1017
1018 if (!invalidated) {
1019 return std::unexpected(detail::sourceTreeError(invalidated.error()));
1020 }
1021
1022 state->target = 0;
1023 state->retryNeeded = false;
1024
1025 if (state->generation != std::numeric_limits<std::uint64_t>::max()) {
1026 ++state->generation;
1027 }
1028
1029 auto work = state->active.lock();
1030 detail::failWindow(*state, SourceError::CANCELLED);
1031
1032 if (work) {
1033 work->stop.request_stop();
1034 }
1035
1036 return {};
1037 }
1038
1040 void close() noexcept {
1041 auto state = std::move(state_);
1042
1043 if (!state) {
1044 return;
1045 }
1046
1047 if (state->source->owner != std::this_thread::get_id()) {
1048 std::terminate();
1049 }
1050
1051 state->closed = true;
1052 state->retryNeeded = false;
1053
1054 if (auto work = state->active.lock()) {
1055 work->stop.request_stop();
1056 }
1057
1058 state->pending.reset();
1059 }
1060
1066 std::expected<WindowRequest<T>, SourceError> request(SourceAnchor anchor, SourceDirection direction,
1067 std::size_t viewportRows) {
1068 auto state = state_;
1069
1070 if (!state || state->closed) {
1071 return std::unexpected(SourceError::CLOSED);
1072 }
1073
1074 auto source = state->source;
1075 auto allowed = source->allowed();
1076
1077 if (!allowed) {
1078 return std::unexpected(allowed.error());
1079 }
1080
1081 if (!viewportRows || (direction != SourceDirection::FORWARD && direction != SourceDirection::BACKWARD) ||
1083 anchor.kind != SourceAnchorKind::TAIL && anchor.kind != SourceAnchorKind::ROW)) {
1084 return std::unexpected(SourceError::INVALID_ARGUMENT);
1085 }
1086
1087 if ((direction == SourceDirection::BACKWARD && !source->capabilities.backward) ||
1088 (anchor.kind == SourceAnchorKind::TAIL && !source->capabilities.tail) ||
1089 (anchor.kind == SourceAnchorKind::ROW && !source->capabilities.seekRow)) {
1090 return std::unexpected(SourceError::UNSUPPORTED);
1091 }
1092
1093 if (anchor.kind == SourceAnchorKind::CURSOR && anchor.cursor.source != source->stamp) {
1094 return std::unexpected(SourceError::STALE_SOURCE);
1095 }
1096
1097 if (anchor.kind == SourceAnchorKind::ROW && (!anchor.row.value || !anchor.row.generation)) {
1098 return std::unexpected(SourceError::INVALID_ARGUMENT);
1099 }
1100
1101 if (state->generation == std::numeric_limits<std::uint64_t>::max()) {
1102 return std::unexpected(SourceError::IDENTITY_EXHAUSTED);
1103 }
1104
1105 // Reserve the replacement before changing intent or cancelling the old generation.
1106 auto previousGeneration = state->generation;
1107 SourceReadCommand command{source->stamp, source->revision, anchor, direction,
1108 std::min(source->options.maxPageRows, viewportRows)};
1109 auto work = detail::admitWindowWork(state, command, previousGeneration + 1);
1110
1111 if (!work) {
1112 return std::unexpected(work.error());
1113 }
1114
1115 if (state->closed || !source->allowed()) {
1116 return std::unexpected(SourceError::CLOSED);
1117 }
1118
1119 if (state->generation != previousGeneration) {
1120 return std::unexpected(SourceError::WOULD_BLOCK);
1121 }
1122
1123 auto invalidated = source->tree.invalidate(source->target, Invalidation::LAYOUT);
1124
1125 if (!invalidated) {
1126 return std::unexpected(detail::sourceTreeError(invalidated.error()));
1127 }
1128
1129 (*work)->consumer = state;
1130
1131 auto previous = state->active.lock();
1132
1133 state->intent = anchor;
1134 state->direction = direction;
1135 state->target = viewportRows;
1136 ++state->generation;
1137 state->fillRevision = source->revision;
1138 state->attemptedRevision = source->revision;
1139 state->desiredRevision = source->revision;
1140 state->retryNeeded = false;
1141 state->pages = {};
1142 state->pageCount = 0;
1143 state->visitedCount = 0;
1144 state->loads = 0;
1145 state->accumulated = 0;
1146 state->error.reset();
1147 state->recovery.reset();
1148 state->pending.reset();
1149 state->active = *work;
1150 state->status = WindowStatus::LOADING;
1151
1152 if (previous) {
1153 // A stop callback may destroy the public consumer/source; no member access follows it.
1154 previous->stop.request_stop();
1155 }
1156
1157 return WindowRequest<T>(std::move(*work));
1158 }
1159
1161 std::expected<std::optional<WindowRequest<T>>, SourceError> takeRequest() {
1162 if (!state_ || state_->closed) {
1163 return std::unexpected(SourceError::CLOSED);
1164 }
1165
1166 auto allowed = state_->source->allowed();
1167
1168 if (!allowed) {
1169 return std::unexpected(allowed.error());
1170 }
1171
1172 if (!state_->pending) {
1173 return std::optional<WindowRequest<T>>{};
1174 }
1175
1176 return std::optional<WindowRequest<T>>(WindowRequest<T>(std::exchange(state_->pending, {})));
1177 }
1178
1180 std::expected<WindowPin<T>, SourceError> pin() const {
1181 if (!state_) {
1182 return std::unexpected(SourceError::CLOSED);
1183 }
1184
1185 if (state_->source->owner != std::this_thread::get_id()) {
1186 return std::unexpected(SourceError::WRONG_THREAD);
1187 }
1188
1189 return WindowPin<T>(state_->current);
1190 }
1191
1193 std::expected<WindowStatus, SourceError> status() const {
1194 if (!state_) {
1195 return std::unexpected(SourceError::CLOSED);
1196 }
1197
1198 if (state_->source->owner != std::this_thread::get_id()) {
1199 return std::unexpected(SourceError::WRONG_THREAD);
1200 }
1201
1202 return state_->status;
1203 }
1204
1206 std::expected<std::optional<SourceError>, SourceError> lastError() const {
1207 auto result = status();
1208
1209 if (!result) {
1210 return std::unexpected(result.error());
1211 }
1212
1213 return state_->error;
1214 }
1215
1217 std::expected<std::optional<SourceCursor>, SourceError> recovery() const {
1218 auto result = status();
1219
1220 if (!result) {
1221 return std::unexpected(result.error());
1222 }
1223
1224 return state_->recovery;
1225 }
1226
1227private:
1228 template <class> friend class WindowSource;
1229
1230 explicit WindowConsumer(std::shared_ptr<detail::WindowConsumerState<T>> state) : state_(std::move(state)) {
1231 }
1232
1233 std::shared_ptr<detail::WindowConsumerState<T>> state_;
1234};
1235
1239template <class T> class WindowNotifier {
1240public:
1241 WindowNotifier() = default;
1242
1247 std::expected<PublishResult, SourceError> notifyReady(SourceStamp source, std::uint64_t revision) const {
1248 auto state = state_;
1249 auto publisher = publisher_;
1250
1251 if (!state) {
1252 return std::unexpected(SourceError::CLOSED);
1253 }
1254
1255 if (source != state->stamp) {
1256 return std::unexpected(SourceError::STALE_SOURCE);
1257 }
1258
1259 if (!revision) {
1260 return std::unexpected(SourceError::INVALID_ARGUMENT);
1261 }
1262
1263 if (!state || !state->alive->load() || state->marker.expired()) {
1264 return std::unexpected(SourceError::CLOSED);
1265 }
1266
1267 // Serial admission prevents an older producer from replacing a newer queued revision.
1268 // Only successfully admitted notifications advance this producer-side watermark.
1269 std::lock_guard lock(state->notificationMutex);
1270
1271 if (state->publishedRevision == std::numeric_limits<std::uint64_t>::max()) {
1272 return std::unexpected(SourceError::IDENTITY_EXHAUSTED);
1273 }
1274
1275 if (revision <= state->publishedRevision) {
1276 return std::unexpected(SourceError::REVISION_CHANGED);
1277 }
1278
1279 auto credit = state->budget->reserve({SourceArena::METADATA_BYTES, 0, 0, 0});
1280
1281 if (!credit) {
1282 return std::unexpected(credit.error());
1283 }
1284
1285 try {
1286 auto event = std::make_shared<const detail::WindowNotification>(std::move(*credit), source, revision);
1287 auto queued = publisher.publish(std::move(event));
1288
1289 if (!queued) {
1290 return std::unexpected(queued.error() == SchedulerError::WOULD_BLOCK ? SourceError::WOULD_BLOCK
1292 }
1293
1294 state->publishedRevision = revision;
1295
1296 return *queued;
1297 } catch (const std::bad_alloc &) {
1298 return std::unexpected(SourceError::NO_MEMORY);
1299 }
1300 }
1301
1302private:
1303 template <class> friend class WindowSource;
1304
1305 WindowNotifier(std::shared_ptr<detail::WindowState<T>> state, Publisher<detail::WindowNotification> publisher)
1306 : state_(std::move(state)), publisher_(std::move(publisher)) {
1307 }
1308
1309 std::shared_ptr<detail::WindowState<T>> state_;
1310 Publisher<detail::WindowNotification> publisher_;
1311};
1312
1316template <class T> class WindowSource {
1317public:
1325 static std::expected<std::unique_ptr<WindowSource>, SourceError> create(WidgetTree &tree, Node<Widget> context,
1326 std::shared_ptr<WindowProvider<T>> provider,
1327 WindowSourceOptions options = {},
1328 std::shared_ptr<SourceBudget> budget = {}) {
1329 if (!provider || !options.initialRevision || options.pageBytes <= SourceArena::METADATA_BYTES ||
1330 !options.maxPageRows || !options.maxRowBytes || options.workspaceBytes <= SourceArena::METADATA_BYTES ||
1331 options.envelopeBytes < SourceArena::METADATA_BYTES) {
1332 return std::unexpected(SourceError::INVALID_ARGUMENT);
1333 }
1334
1335 if (sizeof(WindowRow<T>) > options.maxRowBytes ||
1336 sizeof(WindowRow<T>) > options.pageBytes - SourceArena::METADATA_BYTES) {
1337 return std::unexpected(SourceError::ROW_TOO_LARGE);
1338 }
1339
1340 auto checked = tree.withScope(context, [](const UiScope &) {
1341 });
1342
1343 if (!checked) {
1344 return std::unexpected(detail::sourceTreeError(checked.error()));
1345 }
1346
1347 if (!budget) {
1348 auto created = SourceBudget::create();
1349
1350 if (!created) {
1351 return std::unexpected(created.error());
1352 }
1353
1354 budget = std::move(*created);
1355 }
1356
1357 auto stamp = detail::windowSourceStamp();
1358
1359 if (!stamp) {
1360 return std::unexpected(stamp.error());
1361 }
1362
1363 auto count = budget->options().maxConsumers;
1364
1365 if (count > (std::numeric_limits<std::size_t>::max() - SourceArena::METADATA_BYTES) /
1366 sizeof(std::weak_ptr<detail::WindowConsumerState<T>>)) {
1367 return std::unexpected(SourceError::INVALID_ARGUMENT);
1368 }
1369
1370 auto credit = budget->reserve(
1371 {SourceArena::METADATA_BYTES + count * sizeof(std::weak_ptr<detail::WindowConsumerState<T>>), 0, 0, 0});
1372
1373 if (!credit) {
1374 return std::unexpected(credit.error());
1375 }
1376
1377 try {
1378 auto state = std::make_shared<detail::WindowState<T>>(tree, context, count);
1379 state->credit = std::move(*credit);
1380 state->budget = budget;
1381 state->stamp = *stamp;
1382 state->options = options;
1383 state->revision = options.initialRevision;
1384 state->publishedRevision = options.initialRevision;
1385 state->provider = std::move(provider);
1386 state->capabilities = state->provider->capabilities();
1387 state->alive = std::make_shared<std::atomic<bool>>(true);
1388
1389 auto marker = std::make_shared<detail::WindowScopeMarker>();
1390 state->marker = marker;
1391 auto complete = tree.template connect<detail::WindowCompletion<T>>(
1392 context,
1393 [weak = std::weak_ptr(state), marker](Widget &, std::shared_ptr<const detail::WindowCompletion<T>> event) {
1394 if (auto source = weak.lock()) {
1395 detail::applyWindowCompletion(source, *event);
1396 }
1397 });
1398
1399 if (!complete) {
1400 return std::unexpected(detail::sourceTreeError(complete.error()));
1401 }
1402
1403 state->publisher = complete->publisher;
1404 auto notifications = tree.template connect<detail::WindowNotification>(
1405 context,
1406 [weak = std::weak_ptr(state), marker](Widget &, std::shared_ptr<const detail::WindowNotification> event) {
1407 auto source = weak.lock();
1408
1409 if (!source || !source->allowed() || event->source != source->stamp || event->revision <= source->revision) {
1410 return;
1411 }
1412
1413 source->revision = event->revision;
1414
1415 for (const auto &slot : source->slots) {
1416 auto consumer = slot.lock();
1417
1418 if (!consumer || consumer->closed) {
1419 continue;
1420 }
1421
1422 consumer->desiredRevision = event->revision;
1423 consumer->retryNeeded = true;
1424
1425 if (consumer->active.expired()) {
1426 detail::restartWindow(consumer);
1427 }
1428 }
1429
1430 if (source->allowed()) {
1431 (void)source->tree.invalidate(source->target, Invalidation::LAYOUT);
1432 }
1433 },
1434 SchedulerLane::DATA, SchedulerOverflow::REPLACE_LATEST);
1435
1436 if (!notifications) {
1437 return std::unexpected(detail::sourceTreeError(notifications.error()));
1438 }
1439
1440 return std::unique_ptr<WindowSource>(
1441 new WindowSource(std::move(state), std::move(*complete), std::move(*notifications)));
1442 } catch (const std::bad_alloc &) {
1443 return std::unexpected(SourceError::NO_MEMORY);
1444 }
1445 }
1446
1448 close();
1449 }
1450
1451 WindowSource(const WindowSource &) = delete;
1452 WindowSource &operator=(const WindowSource &) = delete;
1453
1455 SourceStamp stamp() const noexcept {
1456 return state_->stamp;
1457 }
1458
1463 std::expected<std::uint64_t, SourceError> dataRevision() const {
1464 auto allowed = state_->allowed();
1465
1466 return allowed ? std::expected<std::uint64_t, SourceError>(state_->revision) : std::unexpected(allowed.error());
1467 }
1468
1470 std::shared_ptr<SourceBudget> budget() const noexcept {
1471 return state_->budget;
1472 }
1473
1476 return state_->capabilities;
1477 }
1478
1480 std::expected<WindowConsumer<T>, SourceError> openConsumer() {
1481 auto state = state_;
1482 auto allowed = state->allowed();
1483
1484 if (!allowed) {
1485 return std::unexpected(allowed.error());
1486 }
1487
1488 auto slot = std::ranges::find_if(state->slots, [](const auto &item) {
1489 return item.expired();
1490 });
1491
1492 if (slot == state->slots.end()) {
1493 return std::unexpected(SourceError::WOULD_BLOCK);
1494 }
1495
1496 auto credit =
1497 state->budget->reserve({sizeof(detail::WindowConsumerState<T>) + SourceArena::METADATA_BYTES, 0, 0, 1});
1498
1499 if (!credit) {
1500 return std::unexpected(credit.error());
1501 }
1502
1503 try {
1504 auto consumer = std::make_shared<detail::WindowConsumerState<T>>();
1505 consumer->credit = std::move(*credit);
1506 consumer->source = state;
1507 consumer->desiredRevision = state->revision;
1508 auto checked = state->allowed();
1509
1510 if (!checked) {
1511 return std::unexpected(checked.error());
1512 }
1513
1514 slot = std::ranges::find_if(state->slots, [](const auto &item) {
1515 return item.expired();
1516 });
1517
1518 if (slot == state->slots.end()) {
1519 return std::unexpected(SourceError::WOULD_BLOCK);
1520 }
1521
1522 *slot = consumer;
1523
1524 return WindowConsumer<T>(std::move(consumer));
1525 } catch (const std::bad_alloc &) {
1526 return std::unexpected(SourceError::NO_MEMORY);
1527 }
1528 }
1529
1531 WindowNotifier<T> notifier() const noexcept {
1532 return WindowNotifier<T>(state_, notifications_.publisher);
1533 }
1534
1539 std::expected<PublishResult, SourceError> notifyReady(SourceStamp source, std::uint64_t revision) const {
1540 return notifier().notifyReady(source, revision);
1541 }
1542
1544 void close() noexcept {
1545 auto state = state_;
1546
1547 if (state->owner != std::this_thread::get_id()) {
1548 std::terminate();
1549 }
1550
1551 if (!state->alive->exchange(false)) {
1552 return;
1553 }
1554
1555 auto completion = std::move(completion_);
1556 auto notifications = std::move(notifications_);
1557 (void)completion.subscription.disconnect();
1558 (void)notifications.subscription.disconnect();
1559
1560 for (const auto &slot : state->slots) {
1561 if (auto consumer = slot.lock()) {
1562 consumer->retryNeeded = false;
1563
1564 if (auto work = consumer->active.lock()) {
1565 work->stop.request_stop();
1566 }
1567
1568 consumer->pending.reset();
1569 }
1570 }
1571 }
1572
1573private:
1574 WindowSource(std::shared_ptr<detail::WindowState<T>> state,
1575 SchedulerConnection<detail::WindowCompletion<T>> completion,
1577 : state_(std::move(state)), completion_(std::move(completion)), notifications_(std::move(notifications)) {
1578 }
1579
1580 std::shared_ptr<detail::WindowState<T>> state_;
1581 SchedulerConnection<detail::WindowCompletion<T>> completion_;
1582 SchedulerConnection<detail::WindowNotification> notifications_;
1583};
1584} // namespace portals
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
One reserved worker-only builder. Never expose its writable resource after publication.
Definition window_source.hpp:224
std::pmr::memory_resource * resource() noexcept
Definition window_source.hpp:227
std::expected< void, SourceError > emplace(RowId id, std::uint64_t revision, Args &&...args)
Definition window_source.hpp:242
std::pmr::memory_resource * workspace() noexcept
Definition window_source.hpp:232
std::expected< SourceReadReply< T >, SourceError > ready(SourceCursor before, SourceCursor after, SourceEdge edge)
Definition window_source.hpp:278
Copyable, worker-safe endpoint. It owns the closed channel state, never UI captures....
Definition scheduler.hpp:189
static constexpr std::size_t METADATA_BYTES
Conservative per-allocation envelope for arena/control-block metadata.
Definition source_budget.hpp:180
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
std::expected< void, TreeError > withScope(Node< Widget > node, Callback &&callback)
Borrow the node-owned scope for registration with the existing Scheduler. Registrations borrowing wid...
Definition widget.hpp:340
Move-only UI consumer. Fetch continuation/retry tokens with takeRequest(), then dispatch on a worker.
Definition window_source.hpp:974
std::expected< std::optional< SourceCursor >, SourceError > recovery() const
Definition window_source.hpp:1217
std::expected< void, SourceError > cancel()
Definition window_source.hpp:1003
std::expected< std::optional< WindowRequest< T > >, SourceError > takeRequest()
Definition window_source.hpp:1161
std::expected< WindowRequest< T >, SourceError > request(SourceAnchor anchor, SourceDirection direction, std::size_t viewportRows)
Definition window_source.hpp:1066
WindowConsumer & operator=(WindowConsumer other) noexcept
Definition window_source.hpp:992
void close() noexcept
Close on UI; no implicit restart follows explicit cancellation.
Definition window_source.hpp:1040
std::expected< WindowStatus, SourceError > status() const
Definition window_source.hpp:1193
std::expected< std::optional< SourceError >, SourceError > lastError() const
Definition window_source.hpp:1206
WindowConsumer(WindowConsumer &&other) noexcept
Transfer on UI.
Definition window_source.hpp:983
WindowConsumer()=default
Empty closed consumer.
~WindowConsumer()
Cancel without waiting; outstanding owners retain credit.
Definition window_source.hpp:978
std::expected< WindowPin< T >, SourceError > pin() const
Definition window_source.hpp:1180
Copyable worker endpoint; retains only worker-safe state, never a UI source owner.
Definition window_source.hpp:1239
WindowNotifier()=default
Empty closed endpoint.
std::expected< PublishResult, SourceError > notifyReady(SourceStamp source, std::uint64_t revision) const
Definition window_source.hpp:1247
Cheap owning page; copying never copies T or allocates.
Definition window_source.hpp:168
std::uint64_t dataRevision() const noexcept
Definition window_source.hpp:188
SourceCursor before() const noexcept
Definition window_source.hpp:178
WindowPage()=default
Empty owning page.
SourceCursor after() const noexcept
Definition window_source.hpp:183
std::span< const WindowRow< T > > rows() const noexcept
Definition window_source.hpp:173
Owning immutable committed window, containing at most four bounded pages.
Definition window_source.hpp:404
std::size_t pageCount() const noexcept
Definition window_source.hpp:409
std::uint64_t dataRevision() const noexcept
Definition window_source.hpp:436
SourceEdge edge() const noexcept
Definition window_source.hpp:431
SourceCursor continuation() const noexcept
Definition window_source.hpp:426
WindowPage< T > page(std::size_t index) const noexcept
Definition window_source.hpp:421
std::size_t size() const noexcept
Definition window_source.hpp:414
WindowPin()=default
Empty pin.
Worker provider; the source captures capabilities once and never calls load on UI.
Definition window_source.hpp:323
virtual std::expected< SourceReadReply< T >, SourceError > load(const SourceReadCommand &command, PageBuilder< T > &out, std::stop_token stop)=0
virtual ~WindowProvider()=default
Safe final destruction on any releasing worker.
virtual SourceCapabilities capabilities() const noexcept=0
Copyable worker token. Dispatch load() through the existing background executor. The library owns no ...
Definition window_source.hpp:454
SourceReadCommand command() const noexcept
Definition window_source.hpp:459
std::expected< SourceReadReply< T >, SourceError > load(std::stop_token external={}) const
Definition window_source.hpp:480
bool stopRequested() const noexcept
Definition window_source.hpp:464
std::expected< PublishResult, SchedulerError > complete(const std::expected< SourceReadReply< T >, SourceError > &reply) const
Definition window_source.hpp:492
WindowRequest()=default
Empty cancelled request.
void cancel() const noexcept
Cooperative cancellation only; does not release shared capacity or join. Registered stop callbacks ex...
Definition window_source.hpp:471
Tree-scoped source using only existing scheduler queues; no total/origin/runtime is required.
Definition window_source.hpp:1316
WindowNotifier< T > notifier() const noexcept
Definition window_source.hpp:1531
std::shared_ptr< SourceBudget > budget() const noexcept
Definition window_source.hpp:1470
std::expected< std::uint64_t, SourceError > dataRevision() const
Definition window_source.hpp:1463
~WindowSource()
Close on UI without joining workers.
Definition window_source.hpp:1447
void close() noexcept
Retire admission/delivery on UI; old immutable owners remain charged until final release.
Definition window_source.hpp:1544
static std::expected< std::unique_ptr< WindowSource >, SourceError > create(WidgetTree &tree, Node< Widget > context, std::shared_ptr< WindowProvider< T > > provider, WindowSourceOptions options={}, std::shared_ptr< SourceBudget > budget={})
Definition window_source.hpp:1325
std::expected< PublishResult, SourceError > notifyReady(SourceStamp source, std::uint64_t revision) const
Definition window_source.hpp:1539
SourceCapabilities capabilities() const noexcept
Definition window_source.hpp:1475
std::expected< WindowConsumer< T >, SourceError > openConsumer()
Definition window_source.hpp:1480
SourceStamp stamp() const noexcept
Definition window_source.hpp:1455
Public Portals API.
Definition action.hpp:8
SourceReadState
Distinct provider states; a short ready page never implies end.
Definition window_source.hpp:202
@ READY
Owning page and explicit edge are available.
Definition window_source.hpp:203
@ FAILED
Typed failure, without replacement rows.
Definition window_source.hpp:206
@ PENDING
Data is not ready; no row count or EOF is inferred.
Definition window_source.hpp:204
@ PENDING
Complete or abandon the owning session before submitting another frame.
Definition diff.hpp:108
@ BACKWARD
Prefer the preceding item; an entry boundary falls back to the following item.
Definition model_position.hpp:44
@ FORWARD
Prefer the following item; an end boundary falls back to the preceding item.
Definition model_position.hpp:43
@ CLOSED
Scheduler, scope, registration or endpoint is closed.
Definition scheduler.hpp:24
@ WOULD_BLOCK
A bounded queue or registration budget has no available slot.
Definition scheduler.hpp:25
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition scheduler.hpp:26
@ READY
Successful nonempty content; the reserved status strip is blank.
Definition data_presentation.hpp:12
@ EMPTY
Successful content has zero logical rows.
Definition data_presentation.hpp:14
@ LOADING
Initial or viewport request is pending.
Definition data_presentation.hpp:13
SourceAnchorKind
Entry operation; ENTRY does not promise a global origin.
Definition window_source.hpp:52
@ TAIL
Capability-gated available-tail window.
Definition window_source.hpp:55
@ ROW
Capability-gated stable-identity lookup.
Definition window_source.hpp:56
@ ENTRY
Provider entry, without a global-origin promise.
Definition window_source.hpp:53
@ CURSOR
Valid gap token in this immutable session.
Definition window_source.hpp:54
@ FAILED
The coroutine returned an error or threw.
Definition async.hpp:46
@ HISTORY_UNAVAILABLE
Supported historical data cannot be recovered.
Definition log_navigation.hpp:75
SourceError
Source protocol and admission failures, independent of a provider's storage format.
Definition source_budget.hpp:14
@ CLOSED
Source, consumer or node delivery scope has retired.
Definition source_budget.hpp:17
@ CALLBACK_FAILED
Provider construction/preparation threw an unexpected exception.
Definition source_budget.hpp:21
@ STALE_SOURCE
The supplied immutable source namespace does not match.
Definition source_budget.hpp:24
@ ROW_TOO_LARGE
One materialized row exceeds its inline/transitive byte limit.
Definition source_budget.hpp:29
@ UNSUPPORTED
A required optional capability is unavailable.
Definition source_budget.hpp:23
@ INVALID_REPLY
Result shape, identities, revision or boundaries violate the protocol.
Definition source_budget.hpp:31
@ CONTEXT_ERROR
The tree rejected a stale/foreign context or invalidation.
Definition source_budget.hpp:22
@ REVISION_CHANGED
Requested provider revision is unavailable or a notification is stale.
Definition source_budget.hpp:26
@ WRONG_THREAD
UI ownership or worker-only load affinity was violated.
Definition source_budget.hpp:16
@ CANCELLED
Explicit navigation cancellation or cooperative worker cancellation.
Definition source_budget.hpp:35
@ WOULD_BLOCK
Root, work, frame or consumer capacity rejected admission.
Definition source_budget.hpp:18
@ PAGE_TOO_LARGE
The fixed page/workspace cannot hold the requested allocation.
Definition source_budget.hpp:30
@ IDENTITY_EXHAUSTED
An identity or readiness revision cannot advance without reuse.
Definition source_budget.hpp:20
@ INVALID_ARGUMENT
Invalid options, enum, identity or command shape.
Definition source_budget.hpp:15
@ NO_MEMORY
Allocation failed inside a fallible operation.
Definition source_budget.hpp:19
SourceDirection
Requested traversal; returned rows remain in display order.
Definition window_source.hpp:47
@ BACKWARD
Read before the requested gap.
Definition window_source.hpp:49
@ FORWARD
Read after the requested gap.
Definition window_source.hpp:48
SourceEdge
State beyond a ready page in the requested direction.
Definition window_source.hpp:59
@ TEMPORARY_TAIL
Current forward tail; wait for readiness or user demand.
Definition window_source.hpp:61
@ FINAL_END
Definitive boundary in this direction for this session.
Definition window_source.hpp:62
@ MORE
Continuation exists; short/empty pages do not imply end.
Definition window_source.hpp:60
@ LAYOUT
Layout and painting are required; old arranged geometry becomes invalid.
Definition widget_types.hpp:44
WindowStatus
Current consumer outcome; ready pins remain valid through every transition.
Definition window_source.hpp:337
@ LOADING
Admitted work needs worker dispatch or delivery.
Definition window_source.hpp:339
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ CLOSED
The owning tree or source is closed.
Definition widget_types.hpp:31
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ WRONG_THREAD
Operation requires the tree's UI thread.
Definition widget_types.hpp:28
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ IDENTITY_EXHAUSTED
A session, generation or revision cannot advance without reuse.
Definition widget_types.hpp:34
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
Provider-assigned row identity, independent of position; increment generation on reuse.
Definition row_id.hpp:9
std::uint64_t generation
Nonzero generation; never wrap or reuse an exhausted pair.
Definition row_id.hpp:11
std::uint64_t value
Nonzero identity within one model.
Definition row_id.hpp:10
UI owns the subscription; workers receive copies of only the publisher.
Definition scheduler.hpp:227
Owning navigation intent, including optional capability-gated operations.
Definition window_source.hpp:66
RowId row
Used for ROW only.
Definition window_source.hpp:69
SourceCursor cursor
Used for CURSOR only.
Definition window_source.hpp:68
SourceAnchorKind kind
Operation to resolve on a worker.
Definition window_source.hpp:67
Immutable navigation capabilities of the delivery channel, not of the complete model.
Definition window_source.hpp:73
bool backward
Read before a gap without an unbounded UI scan.
Definition window_source.hpp:74
bool seekRow
Resolve stable row identity using a bounded worker operation.
Definition window_source.hpp:75
bool tail
Locate available tail on a worker.
Definition window_source.hpp:76
Owning opaque gap token; no arithmetic, row count or pointer semantics.
Definition window_source.hpp:37
bool operator==(const SourceCursor &other) const noexcept=default
SourceStamp source
Issuing immutable namespace.
Definition window_source.hpp:38
std::array< std::uint64_t, 2 > token
Provider-validated gap representation.
Definition window_source.hpp:39
Immutable worker command; maxRows is an upper bound, never an extent.
Definition window_source.hpp:90
SourceAnchor anchor
Latest bounded navigation intent.
Definition window_source.hpp:93
SourceStamp source
Expected session namespace.
Definition window_source.hpp:91
std::uint64_t dataRevision
Exact requested readiness/data revision.
Definition window_source.hpp:92
SourceDirection direction
Traversal direction.
Definition window_source.hpp:94
std::size_t maxRows
Positive remaining demand, capped per page.
Definition window_source.hpp:95
Owning result with fixed metadata; no optional/variant deep copies.
Definition window_source.hpp:212
WindowPage< T > page
Valid for READY only.
Definition window_source.hpp:214
std::optional< SourceCursor > recovery
Optional explicit HISTORY_UNAVAILABLE alternative.
Definition window_source.hpp:217
SourceEdge edge
Boundary for READY only.
Definition window_source.hpp:215
std::uint64_t observedRevision
PENDING must match the command revision.
Definition window_source.hpp:216
SourceError error
FAILED diagnostic.
Definition window_source.hpp:218
SourceReadState state
Explicit readiness/end-independent result.
Definition window_source.hpp:213
Immutable source namespace; replacement sessions must share their old budget root.
Definition window_source.hpp:27
std::uint64_t instance
Nonzero process-unique session identity.
Definition window_source.hpp:28
std::uint64_t epoch
Nonzero namespace fixed at creation.
Definition window_source.hpp:29
bool operator==(const SourceStamp &other) const noexcept=default
Immutable typed row; use arena storage for all dynamically owned payload.
Definition window_source.hpp:101
WindowRow(RowId identity, std::uint64_t revision, Args &&...args)
Definition window_source.hpp:112
std::uint64_t valueRevision
Positive conditional-write identity.
Definition window_source.hpp:103
T value
Transitively immutable inline or arena-accounted payload.
Definition window_source.hpp:104
RowId id
Stable provider identity, independent of position.
Definition window_source.hpp:102
Positive bounded storage/work defaults, independent of logical source length.
Definition window_source.hpp:80
std::size_t maxRowBytes
Inline row plus newly allocated transitive payload.
Definition window_source.hpp:83
std::size_t workspaceBytes
Reserved worker workspace.
Definition window_source.hpp:85
std::size_t maxPageRows
Largest provider command.
Definition window_source.hpp:84
std::size_t envelopeBytes
Work/queue/control-block metadata allowance.
Definition window_source.hpp:86
std::size_t pageBytes
Entire page reservation, including metadata allowance.
Definition window_source.hpp:82
std::uint64_t initialRevision
Positive initial provider readiness/data revision.
Definition window_source.hpp:81