Skip to main content

muse_code_sdk/
handshake.rs

1//! MSP initialization handshake.
2
3use std::error::Error;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7
8use serde_json::Value;
9use thiserror::Error;
10
11use crate::fingerprint::FingerprintWarning;
12use crate::msp::{InitializeParams, InitializeResult};
13
14/// The only request legal before initialization.
15pub const INITIALIZE_METHOD: &str = "initialize";
16/// Notification that completes the initialization sequence.
17pub const INITIALIZED_METHOD: &str = "initialized";
18
19/// Caller-runtime-owned future returned by the connection seam.
20pub type HandshakeFuture<'a, T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>;
21
22/// The request/notification subset the initialization state machine needs.
23///
24/// The full connection implements this seam; tests can use a scripted fake
25/// without a real process, network, clock, or runtime.
26pub trait HandshakeConnection {
27    /// The transport failure type.
28    type Error: Error + Send + Sync + 'static;
29
30    /// Sends one request and resolves to its raw JSON result.
31    fn request<'a>(
32        &'a mut self,
33        method: &'static str,
34        params: Value,
35    ) -> HandshakeFuture<'a, Value, Self::Error>;
36
37    /// Sends one notification, which has no params and gets no answer.
38    fn notify<'a>(&'a mut self, method: &'static str) -> HandshakeFuture<'a, (), Self::Error>;
39}
40
41/// Failure before the connection reaches the `initialized` state.
42#[derive(Debug, Error)]
43#[non_exhaustive]
44pub enum HandshakeError<E: Error + 'static> {
45    /// The `initialize` params could not be encoded as JSON.
46    #[error("could not encode initialize params: {0}")]
47    Encode(#[source] serde_json::Error),
48    /// The connection failed the `initialize` request or the `initialized`
49    /// notification. `E` is the connection's own error type, so this can also
50    /// carry a server refusal the connection reports.
51    #[error("initialize transport failed: {0}")]
52    Transport(#[source] E),
53    /// The `initialize` result did not match the MSP shape this SDK expects.
54    #[error("initialize result did not match the generated MSP shape: {0}")]
55    InvalidResult(#[source] serde_json::Error),
56}
57
58/// Notify-phase failure that preserves the accepted connection for retry/close.
59#[non_exhaustive]
60pub enum HandshakeRecoveryError<C, E: Error + 'static> {
61    /// The `initialize` params could not be encoded as JSON.
62    Encode(serde_json::Error),
63    /// The connection failed the `initialize` request. `E` is the
64    /// connection's own error type, so this can also carry a server refusal
65    /// the connection reports.
66    Transport(E),
67    /// The `initialize` result did not match the MSP shape this SDK expects.
68    InvalidResult(serde_json::Error),
69    /// The server accepted `initialize`, but sending `initialized` failed.
70    InitializedNotify {
71        /// The transport failure.
72        source: E,
73        /// The connection the server accepted, kept for a retry or a close.
74        connection: C,
75    },
76}
77
78impl<C, E: Error + 'static> HandshakeRecoveryError<C, E> {
79    /// Returns the accepted connection when failure happened after initialize.
80    #[must_use]
81    pub fn connection(&self) -> Option<&C> {
82        match self {
83            Self::InitializedNotify { connection, .. } => Some(connection),
84            Self::Encode(_) | Self::Transport(_) | Self::InvalidResult(_) => None,
85        }
86    }
87
88    /// Consumes the error and returns the accepted connection, if one exists.
89    #[must_use]
90    pub fn into_connection(self) -> Option<C> {
91        match self {
92            Self::InitializedNotify { connection, .. } => Some(connection),
93            Self::Encode(_) | Self::Transport(_) | Self::InvalidResult(_) => None,
94        }
95    }
96
97    /// Converts to the connection-agnostic handshake error shape.
98    #[must_use]
99    pub fn into_handshake_error(self) -> HandshakeError<E> {
100        match self {
101            Self::Encode(error) => HandshakeError::Encode(error),
102            Self::Transport(error) | Self::InitializedNotify { source: error, .. } => {
103                HandshakeError::Transport(error)
104            }
105            Self::InvalidResult(error) => HandshakeError::InvalidResult(error),
106        }
107    }
108}
109
110impl<C, E: Error + 'static> fmt::Debug for HandshakeRecoveryError<C, E> {
111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::Encode(error) => formatter.debug_tuple("Encode").field(error).finish(),
114            Self::Transport(source) => formatter.debug_tuple("Transport").field(source).finish(),
115            Self::InvalidResult(error) => {
116                formatter.debug_tuple("InvalidResult").field(error).finish()
117            }
118            Self::InitializedNotify { source, .. } => formatter
119                .debug_struct("InitializedNotify")
120                .field("source", source)
121                .field("connection", &"<preserved>")
122                .finish(),
123        }
124    }
125}
126
127impl<C, E: Error + 'static> fmt::Display for HandshakeRecoveryError<C, E> {
128    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
129        match self {
130            Self::Encode(error) => {
131                write!(formatter, "could not encode initialize params: {error}")
132            }
133            Self::Transport(source) => write!(formatter, "initialize transport failed: {source}"),
134            Self::InvalidResult(error) => write!(
135                formatter,
136                "initialize result did not match the generated MSP shape: {error}"
137            ),
138            Self::InitializedNotify { source, .. } => write!(
139                formatter,
140                "initialized notification transport failed: {source}"
141            ),
142        }
143    }
144}
145
146impl<C, E: Error + 'static> Error for HandshakeRecoveryError<C, E> {
147    fn source(&self) -> Option<&(dyn Error + 'static)> {
148        match self {
149            Self::Encode(error) | Self::InvalidResult(error) => Some(error),
150            Self::Transport(source) | Self::InitializedNotify { source, .. } => Some(source),
151        }
152    }
153}
154
155/// The pre-initialized connection state. Consuming `initialize` makes sending
156/// it twice unrepresentable through this API.
157pub struct Handshake<C> {
158    connection: C,
159}
160
161impl<C> Handshake<C> {
162    /// Wraps a connection that has not sent `initialize` yet.
163    #[must_use]
164    pub fn new(connection: C) -> Self {
165        Self { connection }
166    }
167}
168
169impl<C: HandshakeConnection> Handshake<C> {
170    /// Run `initialize` exactly once and complete the `initialized` sequence.
171    ///
172    /// A served fingerprint mismatch is attached to the returned ready state;
173    /// it never prevents the final notification or discards the connection.
174    /// To keep the accepted connection after an `initialized` notify failure,
175    /// call [`Self::initialize_preserving_connection`].
176    pub async fn initialize(
177        self,
178        params: InitializeParams,
179    ) -> Result<Initialized<C>, HandshakeError<C::Error>> {
180        self.initialize_preserving_connection(params)
181            .await
182            .map_err(HandshakeRecoveryError::into_handshake_error)
183    }
184
185    /// Run `initialize` and preserve the accepted connection if `initialized`
186    /// fails after the server accepted the request.
187    pub async fn initialize_preserving_connection(
188        mut self,
189        params: InitializeParams,
190    ) -> Result<Initialized<C>, HandshakeRecoveryError<C, C::Error>> {
191        let params = serde_json::to_value(params).map_err(HandshakeRecoveryError::Encode)?;
192        let raw = self
193            .connection
194            .request(INITIALIZE_METHOD, params)
195            .await
196            .map_err(HandshakeRecoveryError::Transport)?;
197        let initialize_result: InitializeResult =
198            serde_json::from_value(raw).map_err(HandshakeRecoveryError::InvalidResult)?;
199        let fingerprint_warning =
200            FingerprintWarning::for_server(initialize_result.schema.fingerprint.clone());
201
202        if let Err(source) = self.connection.notify(INITIALIZED_METHOD).await {
203            return Err(HandshakeRecoveryError::InitializedNotify {
204                source,
205                connection: self.connection,
206            });
207        }
208
209        Ok(Initialized {
210            connection: self.connection,
211            initialize_result,
212            fingerprint_warning,
213        })
214    }
215}
216
217/// A connection that completed the MSP initialization sequence.
218pub struct Initialized<C> {
219    connection: C,
220    /// The server's `initialize` result.
221    pub initialize_result: InitializeResult,
222    /// Set when the server's schema fingerprint differs from the one this SDK
223    /// was generated from.
224    pub fingerprint_warning: Option<FingerprintWarning>,
225}
226
227impl<C> Initialized<C> {
228    /// The initialized connection.
229    #[must_use]
230    pub fn connection(&self) -> &C {
231        &self.connection
232    }
233
234    /// The initialized connection, mutably.
235    #[must_use]
236    pub fn connection_mut(&mut self) -> &mut C {
237        &mut self.connection
238    }
239
240    /// Consumes the ready state and returns the connection.
241    #[must_use]
242    pub fn into_connection(self) -> C {
243        self.connection
244    }
245}