Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
model_position_finite.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/model.hpp>
6#include <portals/model_position.hpp>
7
8namespace portals {
9namespace detail {
11template <class T>
12std::expected<PositionHistoryReply, SourceError> modelPositionHistory(const ModelSnapshot<T> &snapshot,
13 std::uint64_t revision) noexcept {
14 try {
15 auto owner = snapshot.positionHistory();
16 if (!owner) {
17 return PositionHistoryReply{};
18 }
19 auto reply = owner->changesFrom(revision);
20 if (!reply) {
21 return std::unexpected(reply.error());
22 }
23 if ((reply->state != PositionResolution::EXACT && reply->state != PositionResolution::UNSUPPORTED &&
24 reply->state != PositionResolution::UNAVAILABLE) ||
25 (reply->state == PositionResolution::EXACT && revision < snapshot.revision() && !reply->changes) ||
26 (reply->state != PositionResolution::EXACT && reply->changes)) {
27 return std::unexpected(SourceError::INVALID_REPLY);
28 }
29 if (reply->changes &&
30 (reply->changes.fromRevision() != revision || reply->changes.toRevision() != snapshot.revision() ||
31 reply->changes.afterCount() != snapshot.rowCount())) {
32 return std::unexpected(SourceError::INVALID_REPLY);
33 }
34 return reply;
35 } catch (const std::bad_alloc &) {
36 return std::unexpected(SourceError::NO_MEMORY);
37 } catch (...) {
38 return std::unexpected(SourceError::CALLBACK_FAILED);
39 }
40}
41
43} // namespace detail
44
54template <class T> class FinitePositionResolver final : public PositionResolver {
55public:
62 static std::expected<FinitePositionResolver, SourceError> create(ModelResource resource, SourceStamp session,
63 std::shared_ptr<const ModelSnapshot<T>> snapshot,
64 PositionChangeMap changes = {}) {
65 if (!snapshot || resource.identity.instance == 0 || resource.identity.epoch == 0 || resource.lineage == 0 ||
66 session.instance == 0 || session.epoch == 0 || snapshot->revision() == 0 ||
67 (changes && (changes.toRevision() != snapshot->revision() || changes.afterCount() != snapshot->rowCount()))) {
68 return std::unexpected(SourceError::INVALID_ARGUMENT);
69 }
70
71 return FinitePositionResolver(resource, session, snapshot, std::move(changes));
72 }
73
79 std::expected<ModelBookmark, SourceError> capture(std::uint64_t index,
81 BookmarkOptions options = {}) const {
82 auto snapshot = snapshot_.lock();
83 const auto resource = resource_;
84
85 if (!snapshot) {
86 return std::unexpected(SourceError::CLOSED);
87 }
88
89 auto row = readRow(snapshot, index);
90
91 if (!row) {
92 return std::unexpected(row.error());
93 }
94
95 if (!*row) {
96 return std::unexpected(SourceError::WOULD_BLOCK);
97 }
98
99 return ModelBookmark::create(resource, {PositionKind::ITEM, **row, index, snapshot->revision(), affinity}, {},
100 options);
101 }
102
108 std::expected<PositionReply, SourceError> resolve(const PositionRequest &request,
109 std::stop_token stop = {}) const override {
110 if (request.sequence == 0 || request.revision == 0 || request.bookmark.position().revision == 0) {
111 return std::unexpected(SourceError::INVALID_ARGUMENT);
112 }
113
114 if (request.session != session_) {
115 return std::unexpected(SourceError::STALE_SOURCE);
116 }
117
118 if (stop.stop_requested()) {
119 return std::unexpected(SourceError::CANCELLED);
120 }
121
122 auto snapshot = snapshot_.lock();
123
124 if (!snapshot) {
125 return std::unexpected(SourceError::CLOSED);
126 }
127
128 if (request.revision != snapshot->revision()) {
129 return std::unexpected(SourceError::REVISION_CHANGED);
130 }
131
132 auto reply = receipt(request);
133 const auto position = request.bookmark.position();
134
135 if (request.bookmark.resource() != resource_ || position.revision > snapshot->revision()) {
137
138 return reply;
139 }
140
141 if (position.kind == PositionKind::TEXT || !request.bookmark.metadata().empty()) {
143
144 return reply;
145 }
146
147 if (position.kind == PositionKind::GAP) {
148 return resolveGap(reply, position, *snapshot, stop);
149 }
150
151 // Provider calls may release external owners. Retain the complete remaining
152 // resolution state on the stack before invoking either provider operation.
153 const auto changes = changes_;
154
155 try {
156 return resolveItem(reply, position, snapshot, changes, stop);
157 } catch (const std::bad_alloc &) {
158 return std::unexpected(SourceError::NO_MEMORY);
159 } catch (...) {
160 return std::unexpected(SourceError::CALLBACK_FAILED);
161 }
162 }
163
164private:
165 FinitePositionResolver(ModelResource resource, SourceStamp session,
166 const std::shared_ptr<const ModelSnapshot<T>> &snapshot, PositionChangeMap changes)
167 : resource_(resource), session_(session), snapshot_(snapshot), changes_(std::move(changes)) {
168 }
169
170 PositionReply receipt(const PositionRequest &request) const noexcept {
171 return {resource_, session_, request.revision, request.sequence, PositionResolution::INCOMPATIBLE, {}};
172 }
173
174 static std::expected<std::optional<RowId>, SourceError>
175 readRow(const std::shared_ptr<const ModelSnapshot<T>> &snapshot, std::uint64_t index) {
176 if (index >= snapshot->rowCount()) {
177 return std::unexpected(SourceError::INVALID_ARGUMENT);
178 }
179
180 auto range = ModelRange<T>::read(snapshot, {index, 1}, 1);
181
182 if (!range) {
183 return std::unexpected(detail::sourceTreeError(range.error()));
184 }
185
186 if (range->state() == RangeState::PENDING) {
187 return std::optional<RowId>{};
188 }
189
190 if (range->state() != RangeState::READY) {
191 return std::unexpected(SourceError::CALLBACK_FAILED);
192 }
193
194 const auto id = range->rows().front().id;
195
196 if (id.value == 0 || id.generation == 0) {
197 return std::unexpected(SourceError::INVALID_REPLY);
198 }
199
200 return std::optional<RowId>{id};
201 }
202
203 std::expected<PositionReply, SourceError> resolveGap(PositionReply reply, ModelPosition position,
204 const ModelSnapshot<T> &snapshot,
205 std::stop_token stop) const noexcept {
206 auto changes = changes_;
207 if (position.revision != snapshot.revision()) {
208 if (!changes || changes.fromRevision() != position.revision) {
209 auto history = detail::modelPositionHistory(snapshot, position.revision);
210 if (stop.stop_requested()) {
211 return std::unexpected(SourceError::CANCELLED);
212 }
213 if (!history) {
214 return std::unexpected(history.error());
215 }
216 if (history->state == PositionResolution::UNAVAILABLE) {
218 return reply;
219 }
220 changes = std::move(history->changes);
221 if (!changes) {
222 return reply;
223 }
224 }
225
226 auto mapped = changes.map(position);
227
228 if (!mapped) {
229 return std::unexpected(mapped.error());
230 }
231
232 position.offset = mapped->offset;
233 }
234
235 if (position.offset > snapshot.rowCount()) {
236 return std::unexpected(SourceError::INVALID_ARGUMENT);
237 }
238
239 position.revision = snapshot.revision();
240 reply.state = PositionResolution::EXACT;
241 reply.position = position;
242
243 return reply;
244 }
245
246 static std::expected<PositionReply, SourceError> resolveItem(PositionReply reply, ModelPosition position,
247 const std::shared_ptr<const ModelSnapshot<T>> &snapshot,
248 const PositionChangeMap &provided,
249 std::stop_token stop) {
250 const auto found = snapshot->locateRow(position.row);
251
252 if (stop.stop_requested()) {
253 return std::unexpected(SourceError::CANCELLED);
254 }
255
256 if (found.state == RowLookupState::UNSUPPORTED) {
258
259 return reply;
260 }
261
262 auto offset = found.index;
263 auto outcome = PositionResolution::EXACT;
264
265 if (found.state == RowLookupState::NOT_FOUND) {
266 auto changes = provided;
267 if (!changes || changes.fromRevision() != position.revision) {
268 auto history = detail::modelPositionHistory(*snapshot, position.revision);
269 if (stop.stop_requested()) {
270 return std::unexpected(SourceError::CANCELLED);
271 }
272 if (!history) {
273 return std::unexpected(history.error());
274 }
275 if (history->state == PositionResolution::UNAVAILABLE) {
277 return reply;
278 }
279 changes = std::move(history->changes);
280 if (!changes) {
281 return reply;
282 }
283 }
284
285 auto mapped = changes.map(position);
286
287 if (!mapped) {
288 return std::unexpected(mapped.error());
289 }
290
291 if (!mapped->removed) {
292 return reply;
293 }
294
295 if (snapshot->rowCount() == 0) {
296 reply.state = PositionResolution::EMPTY;
297
298 return reply;
299 }
300
301 offset = mapped->offset;
302
303 if (position.affinity == PositionAffinity::BACKWARD && offset != 0) {
304 --offset;
305 }
306
307 offset = std::min(offset, snapshot->rowCount() - 1);
309 } else if (found.state != RowLookupState::FOUND || offset >= snapshot->rowCount()) {
310 return std::unexpected(SourceError::INVALID_REPLY);
311 }
312
313 auto row = readRow(snapshot, offset);
314
315 if (!row) {
316 return std::unexpected(row.error());
317 }
318
319 if (stop.stop_requested()) {
320 return std::unexpected(SourceError::CANCELLED);
321 }
322
323 if (!*row) {
324 reply.state = PositionResolution::PENDING;
325
326 return reply;
327 }
328
329 if (outcome == PositionResolution::EXACT && **row != position.row) {
330 return std::unexpected(SourceError::INVALID_REPLY);
331 }
332
333 position.row = **row;
334 position.offset = offset;
335 position.revision = snapshot->revision();
336 reply.state = outcome;
337 reply.position = position;
338
339 return reply;
340 }
341
342 ModelResource resource_;
343 SourceStamp session_;
344 std::weak_ptr<const ModelSnapshot<T>> snapshot_;
345 PositionChangeMap changes_;
346};
347} // namespace portals
static std::expected< FinitePositionResolver, SourceError > create(ModelResource resource, SourceStamp session, std::shared_ptr< const ModelSnapshot< T > > snapshot, PositionChangeMap changes={})
Definition model_position_finite.hpp:62
std::expected< PositionReply, SourceError > resolve(const PositionRequest &request, std::stop_token stop={}) const override
Definition model_position_finite.hpp:108
std::expected< ModelBookmark, SourceError > capture(std::uint64_t index, PositionAffinity affinity=PositionAffinity::FORWARD, BookmarkOptions options={}) const
Definition model_position_finite.hpp:79
static std::expected< ModelBookmark, SourceError > create(ModelResource resource, ModelPosition position, std::span< const std::byte > metadata={}, BookmarkOptions options={})
std::span< const std::byte > metadata() const noexcept
ModelPosition position() const noexcept
ModelResource resource() const noexcept
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
Immutable list/table provider storage, independent of view/source lifetime. Implement read as bounded...
Definition model.hpp:94
Immutable bounded provider proof between two revisions of a finite order. The provider must report al...
Definition model_position.hpp:224
Bounded provider extension independent of views, schedulers, and total extent. Implementations must n...
Definition model_position.hpp:163
Public Portals API.
Definition action.hpp:8
PositionAffinity
Preferred surviving side when a position is deleted or text is inserted beside a mark.
Definition model_position.hpp:42
@ 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
@ ITEM
Full RowId with a version-qualified ordinal hint.
Definition model_position.hpp:36
@ TEXT
Provider-defined text mark; providers must preserve grapheme boundaries.
Definition model_position.hpp:38
@ GAP
Boundary between rows, including the entry and end gaps.
Definition model_position.hpp:37
@ READY
Exactly the requested immutable rows are available.
Definition model.hpp:47
@ PENDING
Data is not ready; reading must not block or start work.
Definition model.hpp:46
@ UNAVAILABLE
Supported position history or storage is no longer available.
Definition model_position.hpp:130
@ UNSUPPORTED
The provider does not implement the requested kind or identity capability.
Definition model_position.hpp:128
@ INCOMPATIBLE
Resource, lineage or change proof cannot identify this position safely.
Definition model_position.hpp:129
@ NEAREST
The original item was removed; a declared surviving neighbor was selected.
Definition model_position.hpp:125
@ EMPTY
Compatible source is empty and has no current item.
Definition model_position.hpp:126
@ EXACT
The same item or a proven mapped gap/mark is present.
Definition model_position.hpp:124
@ PENDING
Provider has not materialized the required bounded data yet.
Definition model_position.hpp:127
@ 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
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
@ INVALID_REPLY
Result shape, identities, revision or boundaries violate the protocol.
Definition source_budget.hpp:31
@ REVISION_CHANGED
Requested provider revision is unavailable or a notification is stale.
Definition source_budget.hpp:26
@ 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
@ 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
Checked bookmark capacity, independent of logical source length.
Definition model_position.hpp:57
std::uint64_t revision
Positive revision in which the hint was captured.
Definition model_position.hpp:52
Logical resource namespace, distinct from its current delivery session. Reuse an existing SourceStamp...
Definition model_position.hpp:21
Immutable qualified navigation request; does not start work by itself.
Definition model_position.hpp:134
std::uint64_t sequence
Positive request generation assigned by the existing caller.
Definition model_position.hpp:137
std::uint64_t revision
Exact target data revision.
Definition model_position.hpp:136
ModelBookmark bookmark
Owning source position, independent of the originating view.
Definition model_position.hpp:138
SourceStamp session
Current delivery session, not the bookmark origin.
Definition model_position.hpp:135
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