Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
model.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/widget.hpp>
7
8#include <algorithm>
9#include <atomic>
10#include <limits>
11#include <optional>
12#include <stdexcept>
13#include <string_view>
14#include <thread>
15
16namespace portals {
18
19namespace ui::detail {
20struct EditAccess;
21}
22
24struct ColumnId {
25 std::uint64_t value{};
26 std::uint64_t generation{};
31 bool operator==(const ColumnId &other) const noexcept = default;
32};
33
35struct RowRange {
36 std::uint64_t first{};
37 std::size_t count{};
42 bool operator==(const RowRange &other) const noexcept = default;
43};
44
50
55template <class T> struct ModelRow {
58};
59
64template <class T> struct ModelRows {
66 std::span<const ModelRow<T>> rows;
67 std::string_view error;
68};
69
76
82
94template <class T> class ModelSnapshot {
95public:
100 ModelSnapshot(std::uint64_t revision, std::uint64_t rows) : revision_(revision), rows_(rows) {
101 }
102
104 virtual ~ModelSnapshot() = default;
105
109 std::uint64_t revision() const noexcept {
110 return revision_;
111 }
112
116 std::uint64_t rowCount() const noexcept {
117 return rows_;
118 }
119
125 virtual ModelRows<T> read(RowRange range) const = 0;
126
134 virtual RowLookup locateRow(RowId id) const {
135 (void)id;
136
137 return {};
138 }
139
144 virtual std::shared_ptr<const PositionChangeHistory> positionHistory() const {
145 return {};
146 }
147
148private:
149 const std::uint64_t revision_;
150 const std::uint64_t rows_;
151};
152
155 std::uint64_t session{};
156 std::uint64_t value{};
161 bool operator==(const ModelRangeId &other) const noexcept = default;
162};
163
166 std::size_t max_range_rows{4096};
167 std::size_t max_consumers{32};
168 std::size_t max_in_flight{64};
169};
170
175template <class T> class ModelRange {
176public:
178 ModelRange() = default;
179
183 ModelRange(const ModelRange &other) = default;
187 ModelRange(ModelRange &&other) noexcept = default;
188
193 ModelRange &operator=(ModelRange other) noexcept {
194 std::swap(owner_, other.owner_);
195 std::swap(range_, other.range_);
196 std::swap(data_, other.data_);
197
198 return *this;
199 }
200
204 RangeState state() const noexcept {
205 return data_.state;
206 }
207
211 std::span<const ModelRow<T>> rows() const noexcept {
212 return data_.rows;
213 }
214
218 std::string_view error() const noexcept {
219 return data_.error;
220 }
221
225 RowRange range() const noexcept {
226 return range_;
227 }
228
232 std::uint64_t dataRevision() const noexcept {
233 return owner_ ? owner_->revision() : 0;
234 }
235
244 static std::expected<ModelRange, TreeError> read(std::shared_ptr<const ModelSnapshot<T>> owner, RowRange range,
245 std::size_t max_rows) {
246 if (!owner || range.count > max_rows || range.first > owner->rowCount() ||
247 range.count > owner->rowCount() - range.first) {
248 return std::unexpected(TreeError::INVALID_ARGUMENT);
249 }
250
251 try {
252 auto rows = owner->read(range);
253
254 if ((rows.state == RangeState::READY && (rows.rows.size() != range.count || !rows.error.empty())) ||
255 (rows.state != RangeState::READY && !rows.rows.empty()) ||
256 (rows.state == RangeState::PENDING && !rows.error.empty()) ||
257 (rows.state != RangeState::READY && rows.state != RangeState::PENDING && rows.state != RangeState::FAILED)) {
258 return std::unexpected(TreeError::INVALID_ARGUMENT);
259 }
260
261 return ModelRange(std::move(owner), range, rows);
262 } catch (const std::bad_alloc &) {
263 return std::unexpected(TreeError::NO_MEMORY);
264 } catch (...) {
265 return std::unexpected(TreeError::CALLBACK_FAILED);
266 }
267 }
268
269private:
270 template <class> friend class ModelConsumer;
271 template <class> friend class Model;
272 template <class> friend class ModelFrame;
273
274 ModelRange(std::shared_ptr<const ModelSnapshot<T>> owner, RowRange range, ModelRows<T> data)
275 : owner_(std::move(owner)), range_(range), data_(data) {
276 }
277
278 std::shared_ptr<const ModelSnapshot<T>> owner_;
279 RowRange range_;
280 ModelRows<T> data_;
281};
282
284namespace detail {
285std::expected<std::uint64_t, TreeError> modelSession();
286
287struct ModelLifetime {
288 std::atomic<bool> alive{true};
289 std::atomic<std::size_t> outstanding{};
290};
291
292struct ModelLease {
293 ModelLease(std::shared_ptr<ModelLifetime> life, std::shared_ptr<const void> storage)
294 : lifetime(std::move(life)), storage(std::move(storage)) {
295 lifetime->outstanding.fetch_add(1);
296 }
297
298 ~ModelLease() {
299 // Reentrant storage destruction must still see the outstanding reservation.
300 storage.reset();
301 lifetime->outstanding.fetch_sub(1);
302 }
303
304 std::shared_ptr<ModelLifetime> lifetime;
305 std::shared_ptr<const void> storage;
306 std::atomic<bool> cancelled{};
307 std::atomic<bool> submitted{};
308};
309
310template <class T> struct ModelEntry {
311 ModelRangeId id;
312 std::uint64_t generation{};
313 ModelRange<T> result;
314 std::weak_ptr<ModelLease> work;
315};
316
317template <class T> struct ModelFrameData {
318 explicit ModelFrameData(std::shared_ptr<const ModelSnapshot<T>> initial) : snapshot(std::move(initial)) {
319 }
320
321 std::shared_ptr<const ModelSnapshot<T>> snapshot;
322 std::vector<ModelEntry<T>> entries = std::vector<ModelEntry<T>>(0);
323 std::uint64_t revision{};
324};
325
326template <class T> struct ModelCompletion {
327 ModelRangeId id;
328 std::uint64_t generation{};
329 std::shared_ptr<ModelLease> lease;
330 ModelRange<T> result;
331};
332
333template <class T> struct ModelState {
334 ModelState(WidgetTree &value, Node<Widget> node) : tree(value), target(node) {
335 }
336
337 std::expected<void, TreeError> allowed() const {
338 if (owner != std::this_thread::get_id()) {
339 return std::unexpected(TreeError::WRONG_THREAD);
340 }
341
342 if (!lifetime->alive.load()) {
343 return std::unexpected(TreeError::CLOSED);
344 }
345
346 return tree.withScope(target, [](const UiScope &) {
347 });
348 }
349
350 std::expected<std::shared_ptr<ModelFrameData<T>>, TreeError> next() const {
351 if (current->revision == std::numeric_limits<std::uint64_t>::max()) {
352 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
353 }
354
355 try {
356 auto result = std::make_shared<ModelFrameData<T>>(*current);
357
358 ++result->revision;
359
360 return result;
361 } catch (const std::bad_alloc &) {
362 return std::unexpected(TreeError::NO_MEMORY);
363 }
364 }
365
366 std::expected<void, TreeError> commit(std::shared_ptr<ModelFrameData<T>> next) {
367 auto invalidated = tree.invalidate(target, Invalidation::LAYOUT);
368
369 if (!invalidated) {
370 return std::unexpected(invalidated.error());
371 }
372
373 // Keep old storage until the new state and all bookkeeping are committed.
374 auto previous = std::exchange(current, std::move(next));
375
376 return {};
377 }
378
379 WidgetTree &tree;
380 Node<Widget> target;
381 const std::thread::id owner{std::this_thread::get_id()};
382 ModelOptions options;
383 std::uint64_t session{};
384 std::uint64_t identity{};
385 std::vector<ModelRangeId> retired = std::vector<ModelRangeId>(0);
386 std::shared_ptr<ModelLifetime> lifetime = std::make_shared<ModelLifetime>();
387 std::shared_ptr<const ModelFrameData<T>> current;
388 Publisher<ModelCompletion<T>> publisher;
389 std::optional<TreeError> application_error;
390};
391} // namespace detail
392
394
400template <class T> class ModelFrame {
401public:
405 ModelFrame(const ModelFrame &other) = default;
409 ModelFrame(ModelFrame &&other) noexcept = default;
410
415 ModelFrame &operator=(ModelFrame other) noexcept {
416 std::swap(data_, other.data_);
417 std::swap(max_rows_, other.max_rows_);
418
419 return *this;
420 }
421
425 std::uint64_t revision() const noexcept {
426 return data_->revision;
427 }
428
432 std::uint64_t dataRevision() const noexcept {
433 return data_->snapshot->revision();
434 }
435
441 std::shared_ptr<const ModelSnapshot<T>> snapshot() const noexcept {
442 return data_->snapshot;
443 }
444
448 std::uint64_t rowCount() const noexcept {
449 return data_->snapshot->rowCount();
450 }
451
456 std::expected<ModelRange<T>, TreeError> range(ModelRangeId id) const {
457 auto entry = std::ranges::find_if(data_->entries, [id](const auto &value) {
458 return value.id == id;
459 });
460
461 if (entry == data_->entries.end()) {
462 return std::unexpected(TreeError::STALE_NODE);
463 }
464
465 return entry->result;
466 }
467
472 std::expected<ModelRange<T>, TreeError> read(RowRange range) const {
473 return ModelRange<T>::read(data_->snapshot, range, max_rows_);
474 }
475
482 std::expected<RowLookup, TreeError> locateRow(RowId id) const {
483 if (id.value == 0 || id.generation == 0) {
484 return std::unexpected(TreeError::INVALID_ARGUMENT);
485 }
486
487 try {
488 const auto result = data_->snapshot->locateRow(id);
489
490 switch (result.state) {
493 return result;
495 if (result.index < rowCount()) {
496 return result;
497 }
498
499 break;
500 }
501
502 return std::unexpected(TreeError::INVALID_ARGUMENT);
503 } catch (const std::bad_alloc &) {
504 return std::unexpected(TreeError::NO_MEMORY);
505 } catch (...) {
506 return std::unexpected(TreeError::CALLBACK_FAILED);
507 }
508 }
509
510private:
511 template <class> friend class Model;
512 template <class> friend class VirtualList;
513 template <class> friend class VirtualTable;
514 template <class> friend class Chart;
515
516 // A view may reuse its own immutable completion snapshot, without merging consumer results.
517 // The current pin still supplies the domain revision, row count and synchronous read budget.
518 std::expected<ModelRange<T>, TreeError> readCached(const ModelRange<T> &completed, const ModelRange<T> *retained,
519 RowRange range) const {
520 const auto readOwner = [&](const ModelRange<T> &cached) -> std::expected<ModelRange<T>, TreeError> {
521 if (!cached.owner_ || cached.owner_ == data_->snapshot || cached.dataRevision() != dataRevision() ||
522 cached.owner_->rowCount() != rowCount()) {
523 return ModelRange<T>{};
524 }
525
526 return ModelRange<T>::read(cached.owner_, range, max_rows_);
527 };
528
529 auto cached = readOwner(completed);
530
531 if (!cached || cached->state() != RangeState::PENDING || !retained) {
532 return cached;
533 }
534
535 auto previous = readOwner(*retained);
536
537 if (!previous) {
538 return std::unexpected(previous.error());
539 }
540
541 // A completion for another viewport can arrive just before a direction change.
542 // Preserve the ready retained page; never turn provider failure into cached success.
543 if (cached->dataRevision() == 0 || previous->state() != RangeState::PENDING) {
544 return previous;
545 }
546
547 return cached;
548 }
549
550 ModelFrame(std::shared_ptr<const detail::ModelFrameData<T>> data, std::size_t max_rows)
551 : data_(std::move(data)), max_rows_(max_rows) {
552 }
553
554 std::shared_ptr<const detail::ModelFrameData<T>> data_;
555 std::size_t max_rows_;
556};
557
564template <class T> class ModelRequest {
565public:
567 ModelRequest() = default;
568
572 ModelRequest(const ModelRequest &other) = default;
576 ModelRequest(ModelRequest &&other) noexcept = default;
577
583 std::swap(id_, other.id_);
584 std::swap(generation_, other.generation_);
585 std::swap(revision_, other.revision_);
586 std::swap(row_count_, other.row_count_);
587 std::swap(range_, other.range_);
588 std::swap(lease_, other.lease_);
589 std::swap(publisher_, other.publisher_);
590
591 return *this;
592 }
593
597 RowRange range() const noexcept {
598 return range_;
599 }
600
604 std::uint64_t dataRevision() const noexcept {
605 return revision_;
606 }
607
612 bool stopRequested() const noexcept {
613 return !lease_ || lease_->cancelled.load() || !lease_->lifetime->alive.load();
614 }
615
617 void cancel() const noexcept {
618 if (lease_) {
619 lease_->cancelled.store(true);
620 }
621 }
622
631 std::expected<PublishResult, SchedulerError> complete(std::shared_ptr<const ModelSnapshot<T>> snapshot) const {
632 auto request = *this;
633
634 if (request.stopRequested()) {
635 return std::unexpected(SchedulerError::CLOSED);
636 }
637
638 if (!snapshot || snapshot->revision() != request.revision_ || snapshot->rowCount() != request.row_count_) {
639 return std::unexpected(SchedulerError::INVALID_ARGUMENT);
640 }
641
642 auto result = ModelRange<T>::read(std::move(snapshot), request.range_, request.range_.count);
643
644 if (!result || result->state() == RangeState::PENDING) {
645 if (!result && result.error() == TreeError::NO_MEMORY) {
646 return std::unexpected(SchedulerError::NO_MEMORY);
647 }
648
649 if (!result && result.error() == TreeError::CALLBACK_FAILED) {
650 return std::unexpected(SchedulerError::CALLBACK_FAILED);
651 }
652
653 return std::unexpected(SchedulerError::INVALID_ARGUMENT);
654 }
655
656 // Admission is shared by all token copies. A failed enqueue releases the claim so the same
657 // generation can retry; successful enqueue retains the lease until UI delivery releases it.
658 bool expected = false;
659
660 if (!request.lease_->submitted.compare_exchange_strong(expected, true)) {
661 return std::unexpected(SchedulerError::CLOSED);
662 }
663
664 try {
665 auto event = std::make_shared<const detail::ModelCompletion<T>>(request.id_, request.generation_, request.lease_,
666 std::move(*result));
667 auto published = request.publisher_.publish(std::move(event));
668
669 if (!published) {
670 request.lease_->submitted.store(false);
671 }
672
673 return published;
674 } catch (const std::bad_alloc &) {
675 request.lease_->submitted.store(false);
676
677 return std::unexpected(SchedulerError::NO_MEMORY);
678 }
679 }
680
681private:
682 template <class> friend class ModelConsumer;
683 ModelRangeId id_;
684 std::uint64_t generation_{};
685 std::uint64_t revision_{};
686 std::uint64_t row_count_{};
687 RowRange range_;
688 std::shared_ptr<detail::ModelLease> lease_;
689 Publisher<detail::ModelCompletion<T>> publisher_;
690};
691
698template <class T> class ModelConsumer {
699public:
701 ModelConsumer() = default;
702
705 retire();
706 }
707
711 ModelConsumer(ModelConsumer &&other) noexcept : state_(std::move(other.state_)), id_(std::exchange(other.id_, {})) {
712 if (state_ && state_->owner != std::this_thread::get_id()) {
713 std::terminate();
714 }
715 }
716
722 if (state_ && state_->owner != std::this_thread::get_id()) {
723 std::terminate();
724 }
725
726 std::swap(state_, other.state_);
727 std::swap(id_, other.id_);
728
729 return *this;
730 }
731
732 ModelConsumer(const ModelConsumer &) = delete;
733
737 ModelRangeId id() const noexcept {
738 return id_;
739 }
740
750 std::expected<ModelRequest<T>, TreeError> request(RowRange range, std::shared_ptr<const void> work_owner = {}) {
751 auto state = state_;
752
753 if (!state || id_.value == 0) {
754 return std::unexpected(TreeError::CLOSED);
755 }
756
757 auto allowed = state->allowed();
758
759 if (!allowed) {
760 return std::unexpected(allowed.error());
761 }
762
763 auto current = state->current;
764 auto entry = find(*current);
765
766 if (entry == current->entries.end()) {
767 return std::unexpected(TreeError::CLOSED);
768 }
769
770 if (range.count > state->options.max_range_rows || range.first > current->snapshot->rowCount() ||
771 range.count > current->snapshot->rowCount() - range.first) {
772 return std::unexpected(TreeError::INVALID_ARGUMENT);
773 }
774
775 if (state->lifetime->outstanding.load() >= state->options.max_in_flight) {
776 return std::unexpected(TreeError::WOULD_BLOCK);
777 }
778
779 if (entry->generation == std::numeric_limits<std::uint64_t>::max()) {
780 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
781 }
782
783 // Prepare a complete replacement table before changing this consumer or cancelling its old work.
784 auto next = state->next();
785
786 if (!next) {
787 return std::unexpected(next.error());
788 }
789
790 try {
791 auto lease =
792 std::make_shared<detail::ModelLease>(state->lifetime, work_owner ? std::move(work_owner) : current->snapshot);
793 auto &updated = *std::ranges::find_if((*next)->entries, [this](auto &value) {
794 return value.id == id_;
795 });
796
797 ++updated.generation;
798 updated.work = lease;
799 updated.result = ModelRange<T>(current->snapshot, range, {});
800
801 ModelRequest<T> result;
802
803 result.id_ = id_;
804 result.generation_ = updated.generation;
805 result.revision_ = current->snapshot->revision();
806 result.row_count_ = current->snapshot->rowCount();
807 result.range_ = range;
808 result.lease_ = std::move(lease);
809 result.publisher_ = state->publisher;
810
811 auto committed = state->commit(std::move(*next));
812
813 if (!committed) {
814 return std::unexpected(committed.error());
815 }
816
817 if (auto old = entry->work.lock()) {
818 old->cancelled.store(true);
819 }
820
821 return result;
822 } catch (const std::bad_alloc &) {
823 return std::unexpected(TreeError::NO_MEMORY);
824 }
825 }
826
831 std::expected<void, TreeError> close() {
832 if (state_ && state_->owner != std::this_thread::get_id()) {
833 return std::unexpected(TreeError::WRONG_THREAD);
834 }
835
836 retire();
837
838 return {};
839 }
840
841private:
842 template <class> friend class Model;
843
844 ModelConsumer(std::shared_ptr<detail::ModelState<T>> state, ModelRangeId id) : state_(std::move(state)), id_(id) {
845 }
846
847 auto find(const detail::ModelFrameData<T> &data) const {
848 return std::ranges::find_if(data.entries, [this](const auto &value) {
849 return value.id == id_;
850 });
851 }
852
853 void retire() noexcept {
854 auto state = std::move(state_);
855 auto id = std::exchange(id_, {});
856
857 if (!state) {
858 return;
859 }
860
861 if (state->owner != std::this_thread::get_id()) {
862 std::terminate();
863 }
864
865 // Retire identity before a temporary strong lease can release reentrant user storage.
866 state->retired.push_back(id);
867
868 auto entry = std::ranges::find_if(state->current->entries, [id](const auto &value) {
869 return value.id == id;
870 });
871
872 if (entry != state->current->entries.end()) {
873 if (auto work = entry->work.lock()) {
874 work->cancelled.store(true);
875 }
876 }
877 }
878
879 std::shared_ptr<detail::ModelState<T>> state_;
880 ModelRangeId id_;
881};
882
890template <class T> class Model {
891public:
900 static std::expected<std::unique_ptr<Model>, TreeError> create(WidgetTree &tree, Node<Widget> context,
901 std::shared_ptr<const ModelSnapshot<T>> initial,
902 ModelOptions options = {}) {
903 if (!initial || options.max_range_rows == 0 || options.max_consumers == 0 || options.max_in_flight == 0) {
904 return std::unexpected(TreeError::INVALID_ARGUMENT);
905 }
906
907 auto allowed = tree.withScope(context, [](const UiScope &) {
908 });
909
910 if (!allowed) {
911 return std::unexpected(allowed.error());
912 }
913
914 auto session = detail::modelSession();
915
916 if (!session) {
917 return std::unexpected(session.error());
918 }
919
920 try {
921 auto state = std::make_shared<detail::ModelState<T>>(tree, context);
922
923 state->session = *session;
924 state->options = options;
925 state->retired.reserve(options.max_consumers);
926 state->current = std::make_shared<const detail::ModelFrameData<T>>(std::move(initial));
927
928 auto completed = tree.template connect<detail::ModelCompletion<T>>(
929 context, [weak = std::weak_ptr(state)](Widget &, std::shared_ptr<const detail::ModelCompletion<T>> value) {
930 auto state = weak.lock();
931
932 if (!state || !state->lifetime->alive.load() || value->lease->cancelled.load()) {
933 return;
934 }
935
936 auto previous = state->current;
937 auto entry = std::ranges::find_if(previous->entries, [&](const auto &item) {
938 return item.id == value->id;
939 });
940
941 // Identity, generation and provider revision are independent stale-result barriers:
942 // closing a consumer, replacing its request, or publishing new data invalidates different work.
943 if (entry == previous->entries.end() || entry->generation != value->generation ||
944 value->result.dataRevision() != previous->snapshot->revision() || retired(*state, value->id)) {
945 return;
946 }
947
948 auto next = state->next();
949
950 if (!next) {
951 state->application_error = next.error();
952
953 return;
954 }
955
956 (*next)->entries[static_cast<std::size_t>(entry - previous->entries.begin())].result = value->result;
957
958 auto result = state->commit(std::move(*next));
959
960 if (!result) {
961 state->application_error = result.error();
962 }
963 });
964
965 if (!completed) {
966 return std::unexpected(completed.error());
967 }
968
969 state->publisher = completed->publisher;
970
971 auto snapshots = tree.template connect<ModelSnapshot<T>>(
972 context, [weak = std::weak_ptr(state)](Widget &, std::shared_ptr<const ModelSnapshot<T>> value) {
973 auto state = weak.lock();
974
975 if (!state || !state->lifetime->alive.load() || value->revision() <= state->current->snapshot->revision()) {
976 return;
977 }
978
979 auto applied = applySnapshot(*state, std::move(value));
980 if (!applied) {
981 state->application_error = applied.error();
982 }
983 });
984
985 if (!snapshots) {
986 return std::unexpected(snapshots.error());
987 }
988
989 return std::unique_ptr<Model>(new Model(std::move(state), std::move(*completed), std::move(*snapshots)));
990 } catch (const std::length_error &) {
991 return std::unexpected(TreeError::INVALID_ARGUMENT);
992 } catch (const std::bad_alloc &) {
993 return std::unexpected(TreeError::NO_MEMORY);
994 }
995 }
996
999 if (state_->owner != std::this_thread::get_id()) {
1000 std::terminate();
1001 }
1002
1003 state_->lifetime->alive.store(false);
1004 }
1005
1006 Model(const Model &) = delete;
1007 Model &operator=(const Model &) = delete;
1008
1013 return snapshots_.publisher;
1014 }
1015
1019 std::expected<ModelFrame<T>, TreeError> pin() const {
1020 if (state_->owner != std::this_thread::get_id()) {
1021 return std::unexpected(TreeError::WRONG_THREAD);
1022 }
1023
1024 return ModelFrame<T>(state_->current, state_->options.max_range_rows);
1025 }
1026
1030 std::expected<ModelConsumer<T>, TreeError> openRange() {
1031 auto state = state_;
1032 auto allowed = state->allowed();
1033
1034 if (!allowed) {
1035 return std::unexpected(allowed.error());
1036 }
1037
1038 if (state->current->entries.size() - state->retired.size() >= state->options.max_consumers) {
1039 return std::unexpected(TreeError::NODE_LIMIT);
1040 }
1041
1042 if (state->identity == std::numeric_limits<std::uint64_t>::max()) {
1043 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
1044 }
1045
1046 auto previous = state->current;
1047 auto next = state->next();
1048
1049 if (!next) {
1050 return std::unexpected(next.error());
1051 }
1052
1053 try {
1054 std::erase_if((*next)->entries, [&](const auto &entry) {
1055 return retired(*state, entry.id);
1056 });
1057
1058 ModelRangeId id{state->session, state->identity + 1};
1059
1060 (*next)->entries.push_back({id, 0, ModelRange<T>((*next)->snapshot, {}, {}), {}});
1061
1062 auto committed = state->commit(std::move(*next));
1063
1064 if (!committed) {
1065 return std::unexpected(committed.error());
1066 }
1067
1068 state->identity = id.value;
1069 state->retired.clear();
1070
1071 return ModelConsumer<T>(std::move(state), id);
1072 } catch (const std::bad_alloc &) {
1073 return std::unexpected(TreeError::NO_MEMORY);
1074 }
1075 }
1076
1080 std::expected<std::optional<TreeError>, TreeError> lastError() const {
1081 if (state_->owner != std::this_thread::get_id()) {
1082 return std::unexpected(TreeError::WRONG_THREAD);
1083 }
1084
1085 return state_->application_error;
1086 }
1087
1088private:
1089 friend class ManagedScene;
1090 friend struct ui::detail::EditAccess;
1091
1092 // Both queued provider delivery and managed UI collection adapters use this same transaction.
1093 static std::expected<void, TreeError> applySnapshot(detail::ModelState<T> &state,
1094 std::shared_ptr<const ModelSnapshot<T>> value) {
1095 auto allowed = state.allowed();
1096 if (!allowed) {
1097 return allowed;
1098 }
1099 if (!value || value->revision() <= state.current->snapshot->revision()) {
1100 return std::unexpected(TreeError::WOULD_BLOCK);
1101 }
1102 auto previous = state.current;
1103 auto next = state.next();
1104
1105 if (!next) {
1106 return std::unexpected(next.error());
1107 }
1108
1109 (*next)->snapshot = std::move(value);
1110
1111 // A new provider revision invalidates every old range as one table publication.
1112 // Cancel old leases only after commit succeeds, preserving old work on rejection.
1113 for (auto &entry : (*next)->entries) {
1114 entry.result = ModelRange<T>((*next)->snapshot, {}, {});
1115 entry.work.reset();
1116 }
1117
1118 auto result = state.commit(std::move(*next));
1119
1120 if (!result) {
1121 return result;
1122 }
1123
1124 for (const auto &entry : previous->entries) {
1125 if (auto work = entry.work.lock()) {
1126 work->cancelled.store(true);
1127 }
1128 }
1129 return {};
1130 }
1131
1132 static bool retired(const detail::ModelState<T> &state, ModelRangeId id) {
1133 return std::ranges::contains(state.retired, id);
1134 }
1135
1136 Model(std::shared_ptr<detail::ModelState<T>> state, SchedulerConnection<detail::ModelCompletion<T>> completion,
1137 SchedulerConnection<ModelSnapshot<T>> snapshots)
1138 : state_(std::move(state)), completion_(std::move(completion)), snapshots_(std::move(snapshots)) {
1139 }
1140
1141 std::shared_ptr<detail::ModelState<T>> state_;
1142 SchedulerConnection<detail::ModelCompletion<T>> completion_;
1143 SchedulerConnection<ModelSnapshot<T>> snapshots_;
1144};
1145} // namespace portals
UI-owned retained plot of a bounded immutable model range. Accessors run only in prepareChart,...
Definition chart.hpp:117
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
Move-only UI-owned range slot. Equal/overlapping consumers are independent. Close/destruction retires...
Definition model.hpp:698
ModelConsumer(ModelConsumer &&other) noexcept
Transfer on UI.
Definition model.hpp:711
std::expected< ModelRequest< T >, TreeError > request(RowRange range, std::shared_ptr< const void > work_owner={})
UI-only request or replace this slot's work; never starts a worker or reads provider data....
Definition model.hpp:750
~ModelConsumer()
Logically retire without waiting for workers.
Definition model.hpp:704
ModelRangeId id() const noexcept
Stable handle for ModelFrame::range.
Definition model.hpp:737
std::expected< void, TreeError > close()
Retire this consumer on UI. Idempotent; no allocation, cancellation never joins. Retained tables keep...
Definition model.hpp:831
ModelConsumer & operator=(ModelConsumer other) noexcept
Transfer on UI; retire old ownership only after the full replacement is complete.
Definition model.hpp:721
ModelConsumer()=default
Empty consumer.
One immutable model revision retained by the frame owner for all its views. Obtain once before Widget...
Definition model.hpp:400
std::expected< ModelRange< T >, TreeError > read(RowRange range) const
Direct bounded read from the base snapshot, without asynchronous requests or overlays.
Definition model.hpp:472
std::uint64_t rowCount() const noexcept
Logical rows.
Definition model.hpp:448
std::shared_ptr< const ModelSnapshot< T > > snapshot() const noexcept
Retain the immutable base source without reading rows or transferring this UI frame.
Definition model.hpp:441
std::uint64_t dataRevision() const noexcept
Provider data revision.
Definition model.hpp:432
ModelFrame(const ModelFrame &other)=default
Retain the same immutable ownership.
ModelFrame & operator=(ModelFrame other) noexcept
Replace all fields before releasing old storage, whose destructor may reenter.
Definition model.hpp:415
std::expected< ModelRange< T >, TreeError > range(ModelRangeId id) const
Read a consumer's exact result; stale/foreign consumer returns STALE_NODE. No spatial merge.
Definition model.hpp:456
std::uint64_t revision() const noexcept
UI publication revision, including range readiness.
Definition model.hpp:425
std::expected< RowLookup, TreeError > locateRow(RowId id) const
Resolve identity against the same retained snapshot as this frame's base rows.
Definition model.hpp:482
ModelFrame(ModelFrame &&other) noexcept=default
Transfer ownership without releasing old storage.
Independent owner for borrowed rows and provider error text.
Definition model.hpp:175
ModelRange & operator=(ModelRange other) noexcept
Replace all fields before releasing old storage, whose destructor may reenter.
Definition model.hpp:193
std::span< const ModelRow< T > > rows() const noexcept
Borrow until this owner is released.
Definition model.hpp:211
static std::expected< ModelRange, TreeError > read(std::shared_ptr< const ModelSnapshot< T > > owner, RowRange range, std::size_t max_rows)
Read only memory and retain its snapshot. Bounds/provider contract failures are explicit....
Definition model.hpp:244
ModelRange(const ModelRange &other)=default
Retain the same immutable ownership.
RowRange range() const noexcept
Logical interval of this result.
Definition model.hpp:225
std::string_view error() const noexcept
Borrow error text for this owner's lifetime.
Definition model.hpp:218
ModelRange(ModelRange &&other) noexcept=default
Transfer ownership without releasing old storage.
RangeState state() const noexcept
Read readiness without loading.
Definition model.hpp:204
ModelRange()=default
Empty pending result.
std::uint64_t dataRevision() const noexcept
Provider revision.
Definition model.hpp:232
ModelRequest()=default
Empty cancelled token.
RowRange range() const noexcept
Requested rows.
Definition model.hpp:597
ModelRequest & operator=(ModelRequest other) noexcept
Replace all fields before releasing old storage, whose destructor may reenter.
Definition model.hpp:582
ModelRequest(ModelRequest &&other) noexcept=default
Transfer ownership without releasing old storage.
bool stopRequested() const noexcept
Worker-safe cooperative stop query.
Definition model.hpp:612
void cancel() const noexcept
Cancel only this generation; does not release its work budget.
Definition model.hpp:617
std::uint64_t dataRevision() const noexcept
Required provider revision.
Definition model.hpp:604
std::expected< PublishResult, SchedulerError > complete(std::shared_ptr< const ModelSnapshot< T > > snapshot) const
Queue ready/error storage from the requested data revision; pending is invalid. Exactly one successfu...
Definition model.hpp:631
ModelRequest(const ModelRequest &other)=default
Retain the same immutable ownership.
Immutable list/table provider storage, independent of view/source lifetime. Implement read as bounded...
Definition model.hpp:94
virtual ~ModelSnapshot()=default
Reclaim storage after all ranges, frames and workers release it.
virtual std::shared_ptr< const PositionChangeHistory > positionHistory() const
Optional immutable ordering proof owner; default sources add no storage.
Definition model.hpp:144
std::uint64_t rowCount() const noexcept
Logical count, without materializing rows.
Definition model.hpp:116
ModelSnapshot(std::uint64_t revision, std::uint64_t rows)
Define immutable metadata.
Definition model.hpp:100
virtual ModelRows< T > read(RowRange range) const =0
Borrow a checked interval; may return pending/error.
std::uint64_t revision() const noexcept
Provider data revision; strictly increasing on replacement.
Definition model.hpp:109
virtual RowLookup locateRow(RowId id) const
Resolve stable identity without materializing rows or blocking the UI.
Definition model.hpp:134
UI-owned source connecting immutable providers and scoped ranges to a real WidgetTree....
Definition model.hpp:890
Publisher< ModelSnapshot< T > > publisher() const
Copy worker-safe full snapshot endpoint on UI.
Definition model.hpp:1012
std::expected< std::optional< TreeError >, TreeError > lastError() const
Last UI application failure; queue acceptance alone is not proof of application.
Definition model.hpp:1080
~Model()
Close publication delivery on UI, without waiting for worker ownership.
Definition model.hpp:998
std::expected< ModelConsumer< T >, TreeError > openRange()
Register one independent consumer; NODE_LIMIT reports its finite capacity.
Definition model.hpp:1030
std::expected< ModelFrame< T >, TreeError > pin() const
Capture one immutable frame owner on UI; never reads provider ranges or copies rows.
Definition model.hpp:1019
static std::expected< std::unique_ptr< Model >, TreeError > create(WidgetTree &tree, Node< Widget > context, std::shared_ptr< const ModelSnapshot< T > > initial, ModelOptions options={})
Create two bounded Scheduler endpoints in the context's scope; initial snapshot is required.
Definition model.hpp:900
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Optional immutable bounded ordering history owned only by supporting providers. No rows,...
Definition model_position.hpp:267
Copyable, worker-safe endpoint. It owns the closed channel state, never UI captures....
Definition scheduler.hpp:189
One UI-owned view with bounded owning row text and one independent model consumer....
Definition virtual_list.hpp:133
One UI-owned table with bounded owning cell text and one independent model consumer....
Definition virtual_table.hpp:154
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
consteval auto id(StyleState state=StyleState::ANY, bool readOnly=false)
Definition style_static.hpp:865
Public Portals API.
Definition action.hpp:8
@ PENDING
Complete or abandon the owning session before submitting another frame.
Definition diff.hpp:108
@ CLOSED
Scheduler, scope, registration or endpoint is closed.
Definition scheduler.hpp:24
@ CALLBACK_FAILED
A user callback threw; dispatch disconnects its registration.
Definition scheduler.hpp:29
@ INVALID_ARGUMENT
Invalid option, null snapshot or unsupported lane/overflow combination.
Definition scheduler.hpp:21
@ 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
@ FAILED
The coroutine returned an error or threw.
Definition async.hpp:46
RangeState
Observable asynchronous range readiness.
Definition model.hpp:45
@ READY
Exactly the requested immutable rows are available.
Definition model.hpp:47
@ FAILED
Provider failure is represented by snapshot-owned text and no rows.
Definition model.hpp:48
@ PENDING
Data is not ready; reading must not block or start work.
Definition model.hpp:46
@ FOUND
A selected owning match is available.
Definition document_search.hpp:18
@ UNSUPPORTED
The application explicitly excludes this annotated phase.
Definition key_binding.hpp:44
RowLookupState
Identity lookup capability and outcome for a pinned provider snapshot.
Definition model.hpp:71
@ FOUND
The index identifies this RowId in the same snapshot.
Definition model.hpp:74
@ UNSUPPORTED
Provider does not implement an identity index; ordinal scrolling remains available.
Definition model.hpp:72
@ NOT_FOUND
Provider supports lookup, but this full RowId is absent.
Definition model.hpp:73
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
@ NODE_LIMIT
The configured live node, observer or consumer limit was reached.
Definition widget_types.hpp:35
@ WRONG_THREAD
Operation requires the tree's UI thread.
Definition widget_types.hpp:28
@ STALE_NODE
The observed node or model consumer is absent or retired.
Definition widget_types.hpp:30
@ 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 column identity; typed row accessors define column values.
Definition model.hpp:24
std::uint64_t generation
Nonzero generation, independent of visual order.
Definition model.hpp:26
std::uint64_t value
Nonzero identity within one model.
Definition model.hpp:25
bool operator==(const ColumnId &other) const noexcept=default
Compare identity.
Finite per-model storage and work budgets; all fields must be positive.
Definition model.hpp:165
std::size_t max_in_flight
Request owners, including cancelled and queued work not yet released.
Definition model.hpp:168
std::size_t max_range_rows
Largest single read/request.
Definition model.hpp:166
std::size_t max_consumers
Live scoped range slots, regardless of readiness.
Definition model.hpp:167
Stable identity of a scoped range consumer, distinct even for equal row intervals.
Definition model.hpp:154
std::uint64_t value
Never-reused consumer identity.
Definition model.hpp:156
std::uint64_t session
Process-unique model session.
Definition model.hpp:155
bool operator==(const ModelRangeId &other) const noexcept=default
Compare source and consumer.
A typed domain row and its stable identity; a table uses a typed record as T.
Definition model.hpp:55
T value
Typed value; all reachable data must be immutable while published.
Definition model.hpp:57
RowId id
Stable provider identity, never the row index.
Definition model.hpp:56
Provider result borrowing from its immutable snapshot.
Definition model.hpp:64
RangeState state
Pending never blocks or initiates I/O.
Definition model.hpp:65
std::string_view error
Snapshot-owned description when error; otherwise empty.
Definition model.hpp:67
std::span< const ModelRow< T > > rows
Exactly the requested count when ready; otherwise empty.
Definition model.hpp:66
Provider-assigned row identity, independent of position; increment generation on reuse.
Definition row_id.hpp:9
Owning lookup result; no row storage is borrowed.
Definition model.hpp:78
RowLookupState state
Explicit capability/result, never inferred from an index.
Definition model.hpp:79
std::uint64_t index
Logical index, meaningful only for FOUND.
Definition model.hpp:80
Half-open logical row interval; arithmetic is checked before provider access.
Definition model.hpp:35
std::uint64_t first
First logical row.
Definition model.hpp:36
bool operator==(const RowRange &other) const noexcept=default
Compare interval.
std::size_t count
Number of rows, bounded independently of logical model size.
Definition model.hpp:37