muse_code_sdk/
handshake.rs1use 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
14pub const INITIALIZE_METHOD: &str = "initialize";
16pub const INITIALIZED_METHOD: &str = "initialized";
18
19pub type HandshakeFuture<'a, T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>;
21
22pub trait HandshakeConnection {
27 type Error: Error + Send + Sync + 'static;
29
30 fn request<'a>(
32 &'a mut self,
33 method: &'static str,
34 params: Value,
35 ) -> HandshakeFuture<'a, Value, Self::Error>;
36
37 fn notify<'a>(&'a mut self, method: &'static str) -> HandshakeFuture<'a, (), Self::Error>;
39}
40
41#[derive(Debug, Error)]
43#[non_exhaustive]
44pub enum HandshakeError<E: Error + 'static> {
45 #[error("could not encode initialize params: {0}")]
47 Encode(#[source] serde_json::Error),
48 #[error("initialize transport failed: {0}")]
52 Transport(#[source] E),
53 #[error("initialize result did not match the generated MSP shape: {0}")]
55 InvalidResult(#[source] serde_json::Error),
56}
57
58#[non_exhaustive]
60pub enum HandshakeRecoveryError<C, E: Error + 'static> {
61 Encode(serde_json::Error),
63 Transport(E),
67 InvalidResult(serde_json::Error),
69 InitializedNotify {
71 source: E,
73 connection: C,
75 },
76}
77
78impl<C, E: Error + 'static> HandshakeRecoveryError<C, E> {
79 #[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 #[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 #[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
155pub struct Handshake<C> {
158 connection: C,
159}
160
161impl<C> Handshake<C> {
162 #[must_use]
164 pub fn new(connection: C) -> Self {
165 Self { connection }
166 }
167}
168
169impl<C: HandshakeConnection> Handshake<C> {
170 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 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
217pub struct Initialized<C> {
219 connection: C,
220 pub initialize_result: InitializeResult,
222 pub fingerprint_warning: Option<FingerprintWarning>,
225}
226
227impl<C> Initialized<C> {
228 #[must_use]
230 pub fn connection(&self) -> &C {
231 &self.connection
232 }
233
234 #[must_use]
236 pub fn connection_mut(&mut self) -> &mut C {
237 &mut self.connection
238 }
239
240 #[must_use]
242 pub fn into_connection(self) -> C {
243 self.connection
244 }
245}