5#include <portals/row_id.hpp>
6#include <portals/source_budget.hpp>
7#include <portals/widget.hpp>
39 std::array<std::uint64_t, 2>
token{};
111 template <
class... Args>
140std::expected<SourceStamp, SourceError> windowSourceStamp();
142template <
class T>
struct WindowPageData {
143 explicit WindowPageData(std::shared_ptr<SourceArena> storage) : arena(std::move(storage)) {
148 std::destroy_at(rows + --count);
152 std::shared_ptr<SourceArena> arena;
153 WindowRow<T> *rows{};
157 std::uint64_t revision{};
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>>{};
189 return data_ ? data_->revision : 0;
195 explicit WindowPage(std::shared_ptr<
const detail::WindowPageData<T>> data) : data_(std::move(data)) {
198 std::shared_ptr<const detail::WindowPageData<T>> data_;
224template <
class T>
class PageBuilder {
228 return data_->arena.get();
233 return workspace_.get();
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) {
251 auto used = data_->arena->used();
252 auto row = data_->rows + data_->count;
255 std::construct_at(row,
id, revision, std::forward<Args>(args)...);
256 }
catch (
const std::bad_alloc &) {
262 if (data_->arena->used() - used > maxRowBytes_ -
sizeof(
WindowRow<T>)) {
263 std::destroy_at(row);
279 if (sealed_ || before.
source != command_.source || after.
source != command_.source) {
283 data_->before = before;
284 data_->after = after;
285 data_->revision = command_.dataRevision;
299 std::size_t maxRowBytes)
300 : command_(command), workspace_(std::move(
workspace)), maxRowBytes_(maxRowBytes) {
301 static_assert(std::is_nothrow_destructible_v<T>);
303 data_ = std::make_shared<detail::WindowPageData<T>>(std::move(arena));
306 throw std::bad_alloc();
313 SourceReadCommand command_;
314 std::shared_ptr<detail::WindowPageData<T>> data_;
315 std::shared_ptr<SourceArena> workspace_;
316 std::size_t maxRowBytes_;
334 std::stop_token stop) = 0;
350template <
class T>
struct WindowState;
351template <
class T>
struct WindowConsumerState;
352template <
class T>
struct WindowWork;
353struct WindowRequestAccess;
355template <
class T>
struct WindowFrameData {
357 std::array<WindowPage<T>, 4> pages;
360 SourceCursor continuation;
361 SourceEdge edge{SourceEdge::MORE};
362 std::uint64_t revision{};
365template <
class T>
struct WindowCompletion {
366 std::shared_ptr<WindowWork<T>> work;
367 SourceReadReply<T> reply;
370struct WindowNotification {
373 std::uint64_t revision;
378struct WindowScopeMarker {};
380template <
class T>
struct WindowWork {
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{};
410 return data_ ? data_->count : 0;
414 std::size_t
size() const noexcept {
415 return data_ ? data_->rows : 0;
422 return data_ && index < data_->count ? data_->pages[index] :
WindowPage<T>{};
437 return data_ ? data_->revision : 0;
443 explicit WindowPin(std::shared_ptr<
const detail::WindowFrameData<T>> data) : data_(std::move(data)) {
446 std::shared_ptr<const detail::WindowFrameData<T>> data_;
465 return !work_ || !work_->alive->load() || work_->marker.expired() || work_->stop.stop_requested();
473 work_->stop.request_stop();
480 std::expected<SourceReadReply<T>,
SourceError>
load(std::stop_token external = {})
const {
483 return provider.
load(command, out, stop);
491 std::expected<PublishResult, SchedulerError>
499 bool expected =
false;
501 if (!work->submitted.compare_exchange_strong(expected,
true)) {
512 value.error = reply.error();
515 auto event = std::make_shared<const detail::WindowCompletion<T>>(work, std::move(value));
516 auto published = work->publisher.publish(std::move(event));
519 work->submitted.store(
false);
523 }
catch (
const std::bad_alloc &) {
524 work->submitted.store(
false);
531 friend struct detail::WindowRequestAccess;
534 template <
class Loader>
535 std::expected<SourceReadReply<T>,
SourceError> loadUsing(Loader &&loader, std::stop_token external)
const {
538 if (stopRequested()) {
542 if (work->uiThread == std::this_thread::get_id()) {
543 return std::unexpected(SourceError::WRONG_THREAD);
546 if (work->loaded.exchange(
true)) {
547 return std::unexpected(SourceError::ALREADY_COMPLETED);
550 std::stop_callback stop(external, [work] {
551 work->stop.request_stop();
555 auto arena = SourceArena::create(std::move(work->pageCredit));
558 return std::unexpected(arena.error());
561 auto temporary = work->credit.split({work->options.workspaceBytes, 0, 0, 0});
562 auto workspace = SourceArena::create(std::move(*temporary));
565 return std::unexpected(workspace.error());
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());
572 if (stopRequested()) {
573 return std::unexpected(SourceError::CANCELLED);
577 }
catch (
const std::bad_alloc &) {
578 return std::unexpected(SourceError::NO_MEMORY);
580 return std::unexpected(SourceError::CALLBACK_FAILED);
584 explicit WindowRequest(std::shared_ptr<detail::WindowWork<T>> work) : work_(std::move(work)) {
587 std::shared_ptr<detail::WindowWork<T>> work_;
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);
603template <
class T>
struct WindowConsumerState {
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;
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{};
623 std::optional<SourceError> error;
624 std::optional<SourceCursor> recovery;
629template <
class T>
struct WindowState {
630 WindowState(WidgetTree &value, Node<Widget> node, std::size_t consumers)
631 : tree(value), target(node), slots(consumers) {
634 std::expected<void, SourceError> allowed()
const {
635 if (owner != std::this_thread::get_id()) {
636 return std::unexpected(SourceError::WRONG_THREAD);
639 if (!alive->load() || marker.expired()) {
640 return std::unexpected(SourceError::CLOSED);
643 auto result = tree.withScope(target, [](
const UiScope &) {
647 return std::unexpected(sourceTreeError(result.error()));
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;
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};
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;
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);
684 total += options.workspaceBytes + options.envelopeBytes;
685 auto credit = source->budget->reserve({total, 1, 1, 0});
688 return std::unexpected(credit.error());
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>));
709 }
catch (
const std::bad_alloc &) {
710 return std::unexpected(SourceError::NO_MEMORY);
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();
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) {
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;
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);
743 failWindow(*consumer, work.error());
748 if (consumer->closed || !consumer->source->allowed()) {
752 consumer->active = *work;
753 consumer->pending = std::move(*work);
754 consumer->status = WindowStatus::LOADING;
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});
764 return std::unexpected(credit.error());
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];
774 next->count = consumer->pageCount;
775 next->rows = consumer->accumulated;
776 next->continuation = continuation;
778 next->revision = consumer->fillRevision;
779 auto allowed = source->allowed();
782 return std::unexpected(allowed.error());
785 auto invalidated = source->tree.invalidate(source->target, Invalidation::LAYOUT);
788 return std::unexpected(sourceTreeError(invalidated.error()));
791 auto previous = std::exchange(consumer->current, std::move(next));
794 }
catch (
const std::bad_alloc &) {
795 return std::unexpected(SourceError::NO_MEMORY);
800void applyWindowCompletion(
const std::shared_ptr<WindowState<T>> &source,
const WindowCompletion<T> &event) {
801 auto consumer =
event.work->consumer.lock();
803 if (!consumer || consumer->closed || consumer->generation != event.work->generation || !source->allowed()) {
808 auto invalidated = source->tree.invalidate(source->target, Invalidation::LAYOUT);
811 failWindow(*consumer, sourceTreeError(invalidated.error()));
816 consumer->active.reset();
818 if (event.work->stop.stop_requested()) {
819 consumer->retryNeeded =
false;
820 failWindow(*consumer, SourceError::CANCELLED);
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);
833 restartWindow(consumer);
838 const auto &reply =
event.reply;
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;
848 failWindow(*consumer, reply.state == SourceReadState::FAILED ? reply.error : SourceError::INVALID_REPLY);
851 restartWindow(consumer);
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;
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);
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);
880 bool duplicate = std::ranges::any_of(rows.first(i), [&](
const auto &row) {
881 return row.id == rows[i].id;
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;
891 failWindow(*consumer, SourceError::INVALID_REPLY);
897 if (!consumer->visitedCount) {
898 consumer->visited[consumer->visitedCount++] = input;
901 if (reply.edge == SourceEdge::MORE) {
902 if (continuation == input) {
903 failWindow(*consumer, SourceError::NO_PROGRESS);
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);
915 consumer->visited[consumer->visitedCount++] = continuation;
918 consumer->pages[consumer->pageCount++] = reply.page;
919 consumer->accumulated += rows.size();
921 bool fulfilled = consumer->accumulated >= consumer->target;
923 if (fulfilled || reply.edge != SourceEdge::MORE || consumer->loads == 4) {
924 auto committed = commitWindow(consumer, continuation, reply.edge);
927 failWindow(*consumer, committed.error());
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;
939 failWindow(*consumer, SourceError::CONTINUATION_LIMIT);
942 restartWindow(consumer);
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);
955 failWindow(*consumer, next.error());
960 if (consumer->closed || !source->allowed()) {
964 consumer->active = *next;
965 consumer->pending = std::move(*next);
984 if (state_ && state_->source->owner != std::this_thread::get_id()) {
993 state_.swap(other.state_);
1004 auto state = state_;
1006 if (!state || state->closed) {
1010 auto allowed = state->source->allowed();
1013 return std::unexpected(allowed.error());
1016 auto invalidated = state->source->tree.invalidate(state->source->target,
Invalidation::LAYOUT);
1019 return std::unexpected(detail::sourceTreeError(invalidated.error()));
1023 state->retryNeeded =
false;
1025 if (state->generation != std::numeric_limits<std::uint64_t>::max()) {
1026 ++state->generation;
1029 auto work = state->active.lock();
1033 work->stop.request_stop();
1041 auto state = std::move(state_);
1047 if (state->source->owner != std::this_thread::get_id()) {
1051 state->closed =
true;
1052 state->retryNeeded =
false;
1054 if (
auto work = state->active.lock()) {
1055 work->stop.request_stop();
1058 state->pending.reset();
1067 std::size_t viewportRows) {
1068 auto state = state_;
1070 if (!state || state->closed) {
1074 auto source = state->source;
1075 auto allowed = source->allowed();
1078 return std::unexpected(allowed.error());
1101 if (state->generation == std::numeric_limits<std::uint64_t>::max()) {
1106 auto previousGeneration = state->generation;
1108 std::min(source->options.maxPageRows, viewportRows)};
1109 auto work = detail::admitWindowWork(state, command, previousGeneration + 1);
1112 return std::unexpected(work.error());
1115 if (state->closed || !source->allowed()) {
1119 if (state->generation != previousGeneration) {
1126 return std::unexpected(detail::sourceTreeError(invalidated.error()));
1129 (*work)->consumer = state;
1131 auto previous = state->active.lock();
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;
1142 state->pageCount = 0;
1143 state->visitedCount = 0;
1145 state->accumulated = 0;
1146 state->error.reset();
1147 state->recovery.reset();
1148 state->pending.reset();
1149 state->active = *work;
1154 previous->stop.request_stop();
1162 if (!state_ || state_->closed) {
1166 auto allowed = state_->source->allowed();
1169 return std::unexpected(allowed.error());
1172 if (!state_->pending) {
1173 return std::optional<WindowRequest<T>>{};
1176 return std::optional<WindowRequest<T>>(
WindowRequest<T>(std::exchange(state_->pending, {})));
1185 if (state_->source->owner != std::this_thread::get_id()) {
1193 std::expected<WindowStatus, SourceError>
status()
const {
1198 if (state_->source->owner != std::this_thread::get_id()) {
1202 return state_->status;
1210 return std::unexpected(result.error());
1213 return state_->error;
1221 return std::unexpected(result.error());
1224 return state_->recovery;
1230 explicit WindowConsumer(std::shared_ptr<detail::WindowConsumerState<T>> state) : state_(std::move(state)) {
1233 std::shared_ptr<detail::WindowConsumerState<T>> state_;
1248 auto state = state_;
1249 auto publisher = publisher_;
1255 if (source != state->stamp) {
1263 if (!state || !state->alive->load() || state->marker.expired()) {
1269 std::lock_guard lock(state->notificationMutex);
1271 if (state->publishedRevision == std::numeric_limits<std::uint64_t>::max()) {
1275 if (revision <= state->publishedRevision) {
1282 return std::unexpected(credit.error());
1286 auto event = std::make_shared<const detail::WindowNotification>(std::move(*credit), source, revision);
1287 auto queued = publisher.publish(std::move(event));
1294 state->publishedRevision = revision;
1297 }
catch (
const std::bad_alloc &) {
1306 : state_(std::move(state)), publisher_(std::move(publisher)) {
1309 std::shared_ptr<detail::WindowState<T>> state_;
1310 Publisher<detail::WindowNotification> publisher_;
1316template <
class T>
class WindowSource {
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);
1335 if (
sizeof(WindowRow<T>) > options.maxRowBytes ||
1336 sizeof(WindowRow<T>) > options.pageBytes - SourceArena::METADATA_BYTES) {
1337 return std::unexpected(SourceError::ROW_TOO_LARGE);
1340 auto checked = tree.
withScope(context, [](
const UiScope &) {
1344 return std::unexpected(detail::sourceTreeError(checked.error()));
1348 auto created = SourceBudget::create();
1351 return std::unexpected(created.error());
1354 budget = std::move(*created);
1357 auto stamp = detail::windowSourceStamp();
1360 return std::unexpected(stamp.error());
1363 auto count = budget->options().maxConsumers;
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);
1370 auto credit = budget->reserve(
1371 {SourceArena::METADATA_BYTES + count *
sizeof(std::weak_ptr<detail::WindowConsumerState<T>>), 0, 0, 0});
1374 return std::unexpected(credit.error());
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);
1389 auto marker = std::make_shared<detail::WindowScopeMarker>();
1390 state->marker = marker;
1391 auto complete = tree.template connect<detail::WindowCompletion<T>>(
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);
1400 return std::unexpected(detail::sourceTreeError(complete.error()));
1403 state->publisher = complete->publisher;
1404 auto notifications = tree.template connect<detail::WindowNotification>(
1406 [weak = std::weak_ptr(state), marker](Widget &, std::shared_ptr<const detail::WindowNotification> event) {
1407 auto source = weak.lock();
1409 if (!source || !source->allowed() || event->source != source->stamp || event->revision <= source->revision) {
1413 source->revision =
event->revision;
1415 for (
const auto &slot : source->slots) {
1416 auto consumer = slot.lock();
1418 if (!consumer || consumer->closed) {
1422 consumer->desiredRevision =
event->revision;
1423 consumer->retryNeeded =
true;
1425 if (consumer->active.expired()) {
1426 detail::restartWindow(consumer);
1430 if (source->allowed()) {
1431 (void)source->tree.invalidate(source->target, Invalidation::LAYOUT);
1434 SchedulerLane::DATA, SchedulerOverflow::REPLACE_LATEST);
1436 if (!notifications) {
1437 return std::unexpected(detail::sourceTreeError(notifications.error()));
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);
1456 return state_->stamp;
1464 auto allowed = state_->allowed();
1466 return allowed ? std::expected<std::uint64_t, SourceError>(state_->revision) : std::unexpected(allowed.error());
1470 std::shared_ptr<SourceBudget>
budget() const noexcept {
1471 return state_->budget;
1476 return state_->capabilities;
1481 auto state = state_;
1482 auto allowed = state->allowed();
1485 return std::unexpected(allowed.error());
1488 auto slot = std::ranges::find_if(state->slots, [](
const auto &item) {
1489 return item.expired();
1492 if (slot == state->slots.end()) {
1500 return std::unexpected(credit.error());
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();
1511 return std::unexpected(checked.error());
1514 slot = std::ranges::find_if(state->slots, [](
const auto &item) {
1515 return item.expired();
1518 if (slot == state->slots.end()) {
1525 }
catch (
const std::bad_alloc &) {
1540 return notifier().notifyReady(source, revision);
1545 auto state = state_;
1547 if (state->owner != std::this_thread::get_id()) {
1551 if (!state->alive->exchange(
false)) {
1555 auto completion = std::move(completion_);
1556 auto notifications = std::move(notifications_);
1557 (void)completion.subscription.disconnect();
1558 (void)notifications.subscription.disconnect();
1560 for (
const auto &slot : state->slots) {
1561 if (
auto consumer = slot.lock()) {
1562 consumer->retryNeeded =
false;
1564 if (
auto work = consumer->active.lock()) {
1565 work->stop.request_stop();
1568 consumer->pending.reset();
1574 WindowSource(std::shared_ptr<detail::WindowState<T>> state,
1577 : state_(std::move(state)), completion_(std::move(completion)), notifications_(std::move(notifications)) {
1580 std::shared_ptr<detail::WindowState<T>> state_;
1581 SchedulerConnection<detail::WindowCompletion<T>> completion_;
1582 SchedulerConnection<detail::WindowNotification> notifications_;
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
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