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::{HistoryMode, 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 in
79 /// `session.activeTurnId`, but if its `lastTurn` names the same turn, that
80 /// turn has ended.
81 pub fn active_turn_id(&self) -> Option<String> {
82 self.read(|fold| fold.active_turn_id().map(str::to_owned))
83 }
84
85 /// The fold's record of turn `id`, or `None` when no turn event the fold
86 /// applied named it (a declined `turn/retracted` for a turn it has not
87 /// seen adds none).
88 pub fn turn(&self, id: &str) -> Option<Turn> {
89 self.read(|fold| fold.turn(id).cloned())
90 }
91
92 /// Turn ids in first-seen order.
93 pub fn turn_ids(&self) -> Vec<String> {
94 self.read(|fold| fold.turn_ids().to_vec())
95 }
96
97 /// The delivery gap the fold has pending, or `None`. A stopped fold keeps
98 /// its last gap, which nothing fills (see [`Self::is_stopped`]).
99 pub fn pending_gap(&self) -> Option<DeliveryGap> {
100 self.read(|fold| fold.pending_gap().cloned())
101 }
102
103 /// False while a delivery gap is pending, and for good once the session
104 /// lost an event or its id was opened again on the same client.
105 pub fn is_current(&self) -> bool {
106 self.read(SessionFold::is_current)
107 }
108
109 /// True for good once the fold stopped applying events: the session lost
110 /// an event (nothing applies after), or its id was opened again on the
111 /// same client (only question events still apply, until its event source
112 /// fails). A stopped fold can keep the gap it had
113 /// pending, so this, not [`Self::is_current`], tells it apart from a fill
114 /// still running.
115 pub fn is_stopped(&self) -> bool {
116 self.read(SessionFold::is_stopped)
117 }
118
119 /// The params of the latest `approval/requested` or `approval/updated`
120 /// for approval `id`, while it awaits its first terminal.
121 pub fn pending_approval(&self, id: &str) -> Option<Value> {
122 self.read(|fold| fold.pending_approval(id).cloned())
123 }
124
125 /// The first `approval/resolved` params of approval `id`; a later
126 /// terminal never replaces it.
127 pub fn resolved_approval(&self, id: &str) -> Option<Value> {
128 self.read(|fold| fold.resolved_approval(id).cloned())
129 }
130
131 /// Pending approvals in first-request order, each with its latest request
132 /// and latest update.
133 pub fn pending_approvals(&self) -> Vec<PendingApproval> {
134 self.read(|fold| fold.pending_approvals().into_iter().cloned().collect())
135 }
136
137 /// The first durable terminal per approval, in first-resolution order.
138 pub fn resolved_approvals(&self) -> Vec<Value> {
139 self.read(|fold| fold.resolved_approvals().into_iter().cloned().collect())
140 }
141
142 /// The latest `userInput/requested` params of question `id` while it
143 /// awaits its first settlement.
144 pub fn pending_user_input(&self, id: &str) -> Option<Value> {
145 self.read(|fold| fold.pending_user_input(id).cloned())
146 }
147
148 /// The first `userInput/settled` params of question `id`; a later
149 /// settlement never replaces it.
150 pub fn settled_user_input(&self, id: &str) -> Option<Value> {
151 self.read(|fold| fold.settled_user_input(id).cloned())
152 }
153
154 /// Pending user-input requests in first-request order.
155 pub fn pending_user_inputs(&self) -> Vec<Value> {
156 self.read(|fold| fold.pending_user_inputs().into_iter().cloned().collect())
157 }
158
159 /// Settled user-input requests in first-settlement order.
160 pub fn settled_user_inputs(&self) -> Vec<Value> {
161 self.read(|fold| fold.settled_user_inputs().into_iter().cloned().collect())
162 }
163}
164
165impl SessionInner {
166 /// Folds one event ahead of its turn route, so while the fold applies
167 /// events a turn never yields one it lacks.
168 pub(super) fn fold_event(&self, notification: &Notification) {
169 // A routed `userInput/request` folds as its `userInput/requested` twin:
170 // they share their params.
171 if notification.method == "userInput/request" {
172 let mut twin = notification.clone();
173 twin.method = "userInput/requested".to_owned();
174 lock(&self.fold).apply(&twin);
175 return;
176 }
177 lock(&self.fold).apply(notification);
178 }
179
180 /// Mirrors the gap route's pending hole into the fold.
181 pub(super) fn mirror_gap(&self, gap: Option<&ViewGapParams>) {
182 lock(&self.fold).track_gap(gap);
183 }
184
185 pub(crate) fn mark_fold_lost(&self) {
186 lock(&self.fold).mark_lost();
187 }
188
189 pub(crate) fn mark_fold_reopened(&self) {
190 lock(&self.fold).mark_reopened();
191 }
192
193 /// A gap fill cut off by client close or transport end can never finish,
194 /// so it stops the fold like a failed fill, whichever runs first.
195 /// `fail_event_source` and `transport_ended` themselves
196 /// stop a cut fill, before they wake the failed turns.
197 pub(super) fn stop_fold_on_cut_fill(&self) {
198 lock(&self.fold).stop_if_gap_pending();
199 }
200}
201
202/// A fold seeded with every history item a resume served, finished turns
203/// included.
204pub(super) fn seeded_fold(session_id: &str, history: &[Value]) -> SessionFold {
205 let mut fold = SessionFold::new(session_id);
206 for item in history.iter().filter_map(Value::as_object) {
207 fold.seed_history_item(item);
208 }
209 fold
210}
211
212/// The snapshot schema version, the view fold's version, that this SDK's fold
213/// understands.
214pub(crate) const SNAPSHOT_SCHEMA_VERSION: u64 = 1;
215
216/// Drops a resume snapshot newer than this SDK's fold before the result is
217/// decoded, so a changed snapshot shape cannot fail the resume and nothing
218/// reads it as the old shape. The resume then uses none of the snapshot's
219/// state; events after its cursor still stream and apply, and `history.mode`
220/// still names what the host served.
221/// Returns the dropped snapshot's `schemaVersion`.
222pub(crate) fn drop_unreadable_snapshot(result: &mut Value) -> Option<u64> {
223 let version = result
224 .pointer("/history/snapshot/schemaVersion")
225 .and_then(Value::as_u64)
226 .filter(|version| *version > SNAPSHOT_SCHEMA_VERSION)?;
227 *result.pointer_mut("/history/snapshot")? = Value::Null;
228 Some(version)
229}
230
231/// The raw items a resume served, inline or in its snapshot, under the
232/// result's decoded `mode`. Seeding from the raw objects keeps members this
233/// SDK does not know. A history mode this SDK does not know seeds nothing:
234/// its reading is "page it yourself", so no member it carries is read as
235/// history.
236pub(crate) fn resume_history_items<'a>(result: &'a Value, mode: &HistoryMode) -> &'a [Value] {
237 if matches!(mode, HistoryMode::Unknown(_)) {
238 return &[];
239 }
240 ["/history/items", "/history/snapshot/state/items"]
241 .iter()
242 .find_map(|pointer| result.pointer(pointer).and_then(Value::as_array))
243 .map_or(&[], Vec::as_slice)
244}