muse_code_sdk/session/reconnect.rs
1//! Same-command retry across a reconnect.
2//!
3//! A transport end makes a session unusable, so a reconnect is a new
4//! `MuseClient` plus `resume_session`, or `resume_session_with_approval_handler`
5//! for a caller that answers approvals still waiting at the drop.
6//! The old session's unobserved
7//! submissions cross to the resumed one and are resent under their original
8//! command ids, which a server that can still read their earlier admission
9//! answers with its first decision.
10
11use std::sync::Mutex;
12
13use super::state::SessionState;
14use super::{PendingCommandGuard, SendUserTurnOptions, Session, SessionOpening};
15use crate::client::{FacadeResult, lock};
16use crate::errors::{MuseError, ProtocolError};
17use crate::msp::{LastTurn, TurnStartResult};
18use crate::turn::Turn;
19
20/// A `send_user_turn` submission whose outcome its session never observed.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct PendingTurn {
23 pub(super) session_id: String,
24 pub(super) command_id: String,
25 pub(super) options: SendUserTurnOptions,
26 pub(super) turn_id: Option<String>,
27}
28
29impl PendingTurn {
30 /// The session the submission was sent to.
31 pub fn session_id(&self) -> &str {
32 &self.session_id
33 }
34
35 /// The submission's command id; [`Session::resolve_reconnect`] resends
36 /// under it, so the server answers the same submission again.
37 pub fn command_id(&self) -> &str {
38 &self.command_id
39 }
40
41 /// The options the submission was sent with; a resend sends them
42 /// unchanged.
43 pub fn options(&self) -> &SendUserTurnOptions {
44 &self.options
45 }
46
47 /// The turn an answer named, or `None` when no answer arrived.
48 ///
49 /// A resend's answer can name another turn: a host that cannot read the
50 /// earlier admission takes the resend as a new submission, which names a
51 /// different turn when it or the earlier one joined a turn already
52 /// running. The resend's input then runs in the turn its answer names, which
53 /// [`Reconnected::Live`] follows, and may already have run once in the
54 /// earlier turn, so it may have run twice, tools included. A
55 /// [`Turn::turn_id`](crate::turn::Turn::turn_id) that differs from this
56 /// shows the host took the resend as new; the same id, or no earlier id,
57 /// does not rule that out.
58 pub fn turn_id(&self) -> Option<&str> {
59 self.turn_id.as_deref()
60 }
61}
62
63/// What the server's answer to one resent submission settled.
64// One answer per resent submission, moved once; boxing a field would change
65// the public match pattern for no measurable gain.
66#[allow(clippy::large_enum_variant)]
67#[non_exhaustive]
68pub enum Reconnected {
69 /// The answer names a turn this session follows to its terminal. It can
70 /// differ from the carried [`PendingTurn::turn_id`] when the host took the
71 /// resend as a new submission (see that method); the resend's input runs
72 /// in this turn and may have run once before.
73 Live(Turn),
74 /// The answer names the turn the resume restated as `lastTurn`: that turn
75 /// already ended, so this carries the restated terminal instead of a
76 /// [`Turn`]. Events a cursor resume replays for it are not delivered here.
77 Ended {
78 /// The server's answer to the resend.
79 ack: TurnStartResult,
80 /// The ended turn as the resume restated it.
81 last_turn: LastTurn,
82 },
83}
84
85/// One carried submission after [`Session::resolve_reconnect`] resent it.
86pub struct ReconnectResolution {
87 /// The carried submission's command id.
88 pub command_id: String,
89 /// What the resend settled, or its error. On a durable client, of its
90 /// errors only a server refusal drops this entry; any other keeps it in
91 /// [`Session::pending`], and after a transport end every later entry
92 /// stays there too.
93 pub result: Result<Reconnected, MuseError>,
94}
95
96impl Session {
97 /// Lists, in submission order, every `send_user_turn` submission whose
98 /// outcome this session has not observed: no answer arrived, or the
99 /// answered turn's terminal never did. Carry it to
100 /// [`Session::resolve_reconnect`] on the resumed session.
101 ///
102 /// Unlike [`PendingCommandSet`](crate::pending::PendingCommandSet), which
103 /// settles an entry on its acknowledgement, this keeps an answered
104 /// submission until its turn's terminal: an answer alone is not the outcome.
105 pub fn pending(&self) -> Vec<PendingTurn> {
106 lock(&self.inner.state).pending_turns(&self.inner.session_id)
107 }
108
109 /// Resends carried submissions in order under their original command ids.
110 ///
111 /// A written intake the host can still read replays its first decision
112 /// instead of running twice; a host that cannot read it takes the resend
113 /// as new and may run it again (see [`PendingTurn::turn_id`]).
114 /// On a durable client, a server refusal fails only its own entry; after a
115 /// transport end, that entry and every later one stay in this session's
116 /// [`Session::pending`].
117 /// An entry from another session refuses the whole call before any write.
118 ///
119 /// Once past those refusals, the call releases a resumed session's hold on
120 /// settled turns when it ends, whether it succeeds or is cancelled. A call
121 /// refused for a foreign entry keeps the hold for the corrected call; a
122 /// discarded session refuses every call and has already dropped its settled
123 /// turns. After a resume with nothing to carry, call it with an empty list
124 /// to release that hold.
125 pub async fn resolve_reconnect(
126 &self,
127 carried: Vec<PendingTurn>,
128 ) -> FacadeResult<Vec<ReconnectResolution>> {
129 self.inner.ensure_available()?;
130 if let Some(foreign) = carried
131 .iter()
132 .find(|entry| entry.session_id != self.inner.session_id)
133 {
134 return Err(ProtocolError::new(
135 format!(
136 "pending turn {} belongs to session {}, not {}",
137 foreign.command_id, foreign.session_id, self.inner.session_id
138 ),
139 None,
140 )
141 .into());
142 }
143 // After the refusals, which must leave the hold for a corrected call;
144 // before the guards, so it drops after them on success or cancellation.
145 let _release = ReleaseSettledAliasHold(&self.inner.state);
146 let last_turn = match &self.inner.opening {
147 SessionOpening::Resume(result) => result.last_turn.clone(),
148 SessionOpening::Start(_) => None,
149 };
150 // Every guard lives until the last claim, so a terminal that lands
151 // between two resends stays claimable as a settled alias.
152 let mut guards: Vec<PendingCommandGuard> = carried
153 .iter()
154 .map(|entry| {
155 PendingCommandGuard::begin(
156 &self.inner,
157 entry.command_id.clone(),
158 entry.options.clone(),
159 )
160 })
161 .collect();
162 let mut resolutions = Vec::with_capacity(carried.len());
163 for (entry, guard) in carried.into_iter().zip(guards.iter_mut()) {
164 let answer = self
165 .inner
166 .submit_turn(&entry.command_id, entry.options, guard)
167 .await;
168 let result = answer.map(|ack| match &last_turn {
169 Some(last_turn) if last_turn.turn_id == ack.turn_id => {
170 lock(&self.inner.state).forget_submission(&entry.command_id);
171 Reconnected::Ended {
172 ack,
173 last_turn: last_turn.clone(),
174 }
175 }
176 _ => Reconnected::Live(self.inner.follow_submitted_turn(
177 &entry.command_id,
178 &ack,
179 None,
180 )),
181 });
182 resolutions.push(ReconnectResolution {
183 command_id: entry.command_id,
184 result,
185 });
186 }
187 drop(guards);
188 Ok(resolutions)
189 }
190}
191
192struct ReleaseSettledAliasHold<'a>(&'a Mutex<SessionState>);
193
194impl Drop for ReleaseSettledAliasHold<'_> {
195 fn drop(&mut self) {
196 lock(self.0).release_settled_alias_hold();
197 }
198}