Skip to main content

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