muse_code_sdk/session/fold_view.rs
1//! The session-owned fold: its read
2//! view, its resume-history seed, and the loss marker that ends its currency.
3
4use serde_json::Value;
5
6use super::{Session, SessionInner};
7use crate::client::lock;
8use crate::fold::{DeliveryGap, PendingApproval, SessionFold, Turn};
9use crate::msp::{Notification, ViewGapParams};
10
11impl Session {
12 /// A read view of this session's fold.
13 ///
14 /// The fold holds every event this session applied, in order, plus the
15 /// items its resume history served. A resume seeds
16 /// items only: turns, approvals, user inputs and session state show the
17 /// events that arrive after it, and the turn still running at resume is
18 /// named by [`Session::opening`]. The fold is complete only while
19 /// [`SessionFoldView::is_current`] holds: after a lost event, or once this
20 /// session id is opened again on the same client, it stops applying and
21 /// stays not current, which [`SessionFoldView::is_stopped`] reports. A
22 /// re-opened fold still lists its questions until its event source fails.
23 pub fn fold(&self) -> SessionFoldView<'_> {
24 SessionFoldView { inner: &self.inner }
25 }
26
27 pub(crate) fn mark_fold_reopened(&self) {
28 self.inner.mark_fold_reopened();
29 }
30}
31
32/// One `Session`'s fold, read one value at a time.
33///
34/// Each getter takes the fold's lock briefly and returns an owned copy of one
35/// value, so an event waits at most for one getter's copy, never for caller
36/// code, and no event copies the whole fold. No read spans several values
37/// atomically: an event can land between two calls.
38pub struct SessionFoldView<'a> {
39 inner: &'a SessionInner,
40}
41
42impl SessionFoldView<'_> {
43 fn read<R>(&self, read: impl FnOnce(&SessionFold) -> R) -> R {
44 read(&lock(&self.inner.fold))
45 }
46
47 /// Item `id` at its latest revision, with the deltas since that revision
48 /// appended, or `None` when the fold holds no such item.
49 pub fn item(&self, id: &str) -> Option<Value> {
50 self.read(|fold| fold.items().get(id).cloned())
51 }
52
53 /// How many items the fold holds; items are never removed.
54 pub fn item_count(&self) -> usize {
55 self.read(|fold| fold.items().len())
56 }
57
58 /// Item ids in first-seen order (resume history first, in served order).
59 pub fn item_ids(&self) -> Vec<String> {
60 self.read(|fold| fold.items().ids().to_vec())
61 }
62
63 /// The `item/delta` text appended to item `id`'s `field` since its latest
64 /// revision arrived, or `None` when none has.
65 pub fn accumulated(&self, id: &str, field: &str) -> Option<String> {
66 self.read(|fold| fold.items().accumulated(id, field).map(str::to_owned))
67 }
68
69 /// The latest params of the session-state notification `family` (for
70 /// example `session/modelChanged`), or `None` when the fold applied none.
71 pub fn session_state(&self, family: &str) -> Option<Value> {
72 self.read(|fold| fold.session_state().get(family).cloned())
73 }
74
75 /// The turn whose `turn/started` the fold applied last, until that turn
76 /// completes, is retracted or is unqueued. On a resumed session the turn
77 /// running at resume shows here only if the resume's streamed events
78 /// replay its `turn/started`; [`Session::opening`] names that turn.
79 pub fn active_turn_id(&self) -> Option<String> {
80 self.read(|fold| fold.active_turn_id().map(str::to_owned))
81 }
82
83 /// The fold's record of turn `id`, or `None` when no turn event the fold
84 /// applied named it (a declined `turn/retracted` for a turn it has not
85 /// seen adds none).
86 pub fn turn(&self, id: &str) -> Option<Turn> {
87 self.read(|fold| fold.turn(id).cloned())
88 }
89
90 /// Turn ids in first-seen order.
91 pub fn turn_ids(&self) -> Vec<String> {
92 self.read(|fold| fold.turn_ids().to_vec())
93 }
94
95 /// The delivery gap the fold has pending, or `None`. A stopped fold keeps
96 /// its last gap, which nothing fills (see [`Self::is_stopped`]).
97 pub fn pending_gap(&self) -> Option<DeliveryGap> {
98 self.read(|fold| fold.pending_gap().cloned())
99 }
100
101 /// False while a delivery gap is pending, and for good once the session
102 /// lost an event or its id was opened again on the same client.
103 pub fn is_current(&self) -> bool {
104 self.read(SessionFold::is_current)
105 }
106
107 /// True for good once the fold stopped applying events: the session lost
108 /// an event (nothing applies after), or its id was opened again on the
109 /// same client (only question events still apply, until its event source
110 /// fails). A stopped fold can keep the gap it had
111 /// pending, so this, not [`Self::is_current`], tells it apart from a fill
112 /// still running.
113 pub fn is_stopped(&self) -> bool {
114 self.read(SessionFold::is_stopped)
115 }
116
117 /// The params of the latest `approval/requested` or `approval/updated`
118 /// for approval `id`, while it awaits its first terminal.
119 pub fn pending_approval(&self, id: &str) -> Option<Value> {
120 self.read(|fold| fold.pending_approval(id).cloned())
121 }
122
123 /// The first `approval/resolved` params of approval `id`; a later
124 /// terminal never replaces it.
125 pub fn resolved_approval(&self, id: &str) -> Option<Value> {
126 self.read(|fold| fold.resolved_approval(id).cloned())
127 }
128
129 /// Pending approvals in first-request order, each with its latest request
130 /// and latest update.
131 pub fn pending_approvals(&self) -> Vec<PendingApproval> {
132 self.read(|fold| fold.pending_approvals().into_iter().cloned().collect())
133 }
134
135 /// The first durable terminal per approval, in first-resolution order.
136 pub fn resolved_approvals(&self) -> Vec<Value> {
137 self.read(|fold| fold.resolved_approvals().into_iter().cloned().collect())
138 }
139
140 /// The latest `userInput/requested` params of question `id` while it
141 /// awaits its first settlement.
142 pub fn pending_user_input(&self, id: &str) -> Option<Value> {
143 self.read(|fold| fold.pending_user_input(id).cloned())
144 }
145
146 /// The first `userInput/settled` params of question `id`; a later
147 /// settlement never replaces it.
148 pub fn settled_user_input(&self, id: &str) -> Option<Value> {
149 self.read(|fold| fold.settled_user_input(id).cloned())
150 }
151
152 /// Pending user-input requests in first-request order.
153 pub fn pending_user_inputs(&self) -> Vec<Value> {
154 self.read(|fold| fold.pending_user_inputs().into_iter().cloned().collect())
155 }
156
157 /// Settled user-input requests in first-settlement order.
158 pub fn settled_user_inputs(&self) -> Vec<Value> {
159 self.read(|fold| fold.settled_user_inputs().into_iter().cloned().collect())
160 }
161}
162
163impl SessionInner {
164 /// Folds one event ahead of its turn route, so while the fold applies
165 /// events a turn never yields one it lacks.
166 pub(super) fn fold_event(&self, notification: &Notification) {
167 // A routed `userInput/request` folds as its `userInput/requested` twin:
168 // they share their params.
169 if notification.method == "userInput/request" {
170 let mut twin = notification.clone();
171 twin.method = "userInput/requested".to_owned();
172 lock(&self.fold).apply(&twin);
173 return;
174 }
175 lock(&self.fold).apply(notification);
176 }
177
178 /// Mirrors the gap route's pending hole into the fold.
179 pub(super) fn mirror_gap(&self, gap: Option<&ViewGapParams>) {
180 lock(&self.fold).track_gap(gap);
181 }
182
183 pub(crate) fn mark_fold_lost(&self) {
184 lock(&self.fold).mark_lost();
185 }
186
187 pub(crate) fn mark_fold_reopened(&self) {
188 lock(&self.fold).mark_reopened();
189 }
190
191 /// A gap fill cut off by client close or transport end can never finish,
192 /// so it stops the fold like a failed fill, whichever runs first.
193 /// `fail_event_source` and `transport_ended` themselves
194 /// stop a cut fill, before they wake the failed turns.
195 pub(super) fn stop_fold_on_cut_fill(&self) {
196 lock(&self.fold).stop_if_gap_pending();
197 }
198}
199
200/// A fold seeded with every history item a resume served, finished turns
201/// included.
202pub(super) fn seeded_fold(session_id: &str, history: &[Value]) -> SessionFold {
203 let mut fold = SessionFold::new(session_id);
204 for item in history.iter().filter_map(Value::as_object) {
205 fold.seed_history_item(item);
206 }
207 fold
208}
209
210/// The snapshot schema version, the view fold's version, that this SDK's fold
211/// understands.
212pub(crate) const SNAPSHOT_SCHEMA_VERSION: u64 = 1;
213
214/// Drops a resume snapshot newer than this SDK's fold before the result is
215/// decoded, so a changed snapshot shape cannot fail the resume and nothing
216/// reads it as the old shape. The resume then uses none of the snapshot's
217/// state; events after its cursor still stream and apply, and `history.mode`
218/// still names what the host served.
219/// Returns the dropped snapshot's `schemaVersion`.
220pub(crate) fn drop_unreadable_snapshot(result: &mut Value) -> Option<u64> {
221 let version = result
222 .pointer("/history/snapshot/schemaVersion")
223 .and_then(Value::as_u64)
224 .filter(|version| *version > SNAPSHOT_SCHEMA_VERSION)?;
225 *result.pointer_mut("/history/snapshot")? = Value::Null;
226 Some(version)
227}
228
229/// The raw items a resume served, inline or in its snapshot. Seeding from
230/// the raw objects keeps members this SDK does not know.
231pub(crate) fn resume_history_items(result: &Value) -> &[Value] {
232 ["/history/items", "/history/snapshot/state/items"]
233 .iter()
234 .find_map(|pointer| result.pointer(pointer).and_then(Value::as_array))
235 .map_or(&[], Vec::as_slice)
236}