1mod host;
4mod open;
5mod shared;
6
7use std::collections::HashSet;
8use std::io;
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex, MutexGuard};
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use tokio::sync::watch;
14
15use crate::DuplexTransport;
16use crate::connection::{Connection, ConnectionError, StdioTransport};
17use crate::errors::ProtocolError;
18use crate::fingerprint::FingerprintWarning;
19use crate::handshake::{Handshake, HandshakeError};
20use crate::host_death::{SessionDurabilityProfile, durability_profile};
21use crate::msp::{ClientInfo, InitializeParams, InitializeResult, SessionDurability};
22use crate::spawn::{ExitClassification, MuseChild, SpawnOptions, spawn_muse};
23
24use host::HostExit;
25use shared::NotificationRouter;
26
27static NEXT_CLIENT_NONCE: AtomicU64 = AtomicU64::new(0);
28
29pub use crate::errors::MuseError as FacadeError;
30
31pub type FacadeResult<T> = Result<T, FacadeError>;
33
34pub use open::{ResumeSessionOptions, StartSessionOptions};
35
36pub struct MuseClient {
43 shared: Arc<ClientShared>,
44}
45
46pub struct MuseClientConnection {
48 pub client: MuseClient,
50 pub fingerprint_warning: Option<FingerprintWarning>,
53}
54
55impl MuseClient {
56 pub async fn spawn(options: SpawnOptions) -> FacadeResult<MuseClientConnection> {
58 let mut host = spawn_muse(options)?;
59 let stdin = host
60 .take_stdin()
61 .ok_or_else(|| missing_host_pipe("stdin"))?;
62 let stdout = host
63 .take_stdout()
64 .ok_or_else(|| missing_host_pipe("stdout"))?;
65 Self::attach_transport(StdioTransport::new(stdin, stdout), Some(host)).await
66 }
67
68 pub async fn attach<T>(transport: T) -> FacadeResult<MuseClientConnection>
70 where
71 T: DuplexTransport + 'static,
72 {
73 Self::attach_transport(transport, None).await
74 }
75
76 async fn attach_transport<T>(
77 transport: T,
78 mut host: Option<MuseChild>,
79 ) -> FacadeResult<MuseClientConnection>
80 where
81 T: DuplexTransport + 'static,
82 {
83 let router = Arc::new(NotificationRouter::default());
84 let route = Arc::clone(&router);
85 let overflow = Arc::clone(&router);
86 let (connection, driver, notifications) = Connection::with_notification_handler(
87 transport,
88 move |notification| {
89 route.route(notification);
90 },
91 move |notification| {
92 overflow.overflow(notification);
93 },
94 );
95 tokio::spawn(notifications.run());
96 tokio::spawn(driver.run());
97 let initialized = match Handshake::new(connection)
98 .initialize(initialize_params())
99 .await
100 {
101 Ok(initialized) => initialized,
102 Err(error) => {
103 if let Some(host) = host.as_mut() {
104 let _ = host.close().await;
105 }
106 return Err(handshake_error(error));
107 }
108 };
109 let durability = initialized
110 .initialize_result
111 .session_durability
112 .clone()
113 .unwrap_or(SessionDurability::Durable);
114 let fingerprint_warning = initialized.fingerprint_warning.clone();
115 let initialize_result = initialized.initialize_result.clone();
116 let client = Self::from_connection(
117 initialized.into_connection(),
118 router,
119 durability,
120 command_id_minter(),
121 Some(initialize_result),
122 host,
123 );
124 Ok(MuseClientConnection {
125 client,
126 fingerprint_warning,
127 })
128 }
129
130 pub fn new<T>(transport: T, durability: SessionDurability) -> Self
137 where
138 T: DuplexTransport + 'static,
139 {
140 Self::with_command_id_minter(transport, durability, command_id_minter())
141 }
142
143 pub fn with_command_id_minter<T, F>(
150 transport: T,
151 durability: SessionDurability,
152 minter: F,
153 ) -> Self
154 where
155 T: DuplexTransport + 'static,
156 F: Fn() -> String + Send + Sync + 'static,
157 {
158 let router = Arc::new(NotificationRouter::default());
159 let route = Arc::clone(&router);
160 let overflow = Arc::clone(&router);
161 let (connection, driver, notifications) = Connection::with_notification_handler(
162 transport,
163 move |notification| {
164 route.route(notification);
165 },
166 move |notification| {
167 overflow.overflow(notification);
168 },
169 );
170 tokio::spawn(notifications.run());
171 tokio::spawn(driver.run());
172 Self::from_connection(connection, router, durability, minter, None, None)
173 }
174
175 fn from_connection<F>(
176 connection: Connection,
177 router: Arc<NotificationRouter>,
178 durability: SessionDurability,
179 minter: F,
180 initialize_result: Option<InitializeResult>,
181 host: Option<MuseChild>,
182 ) -> Self
183 where
184 F: Fn() -> String + Send + Sync + 'static,
185 {
186 let (close_tx, _) = watch::channel(false);
187 let (close_finished, _) = watch::channel(false);
188 let mut driver_closed = connection.subscribe_closed();
189 router.set_durability(durability.clone());
190 let shared = Arc::new(ClientShared {
191 connection,
192 host: host.map(HostExit::spawn),
193 initialize_result,
194 minter: Arc::new(minter),
195 durability,
196 router,
197 discarded_session_ids: Mutex::new(HashSet::new()),
198 closed: AtomicBool::new(false),
199 transport_ended: AtomicBool::new(false),
200 close_tx,
201 close_finished,
202 runtime: tokio::runtime::Handle::current(),
203 });
204 let weak = Arc::downgrade(&shared);
205 tokio::spawn(async move {
206 let already_closed = *driver_closed.borrow();
207 if !already_closed {
208 let _ = driver_closed.changed().await;
209 }
210 if let Some(shared) = weak.upgrade() {
211 shared.mark_transport_ended();
212 }
213 });
214 Self { shared }
215 }
216
217 pub async fn close(&self) {
225 let mut finished = self.shared.close_finished.subscribe();
226 if !self.shared.closed.swap(true, Ordering::AcqRel) {
227 self.shared.close_tx.send_replace(true);
228 let workers = self.shared.begin_close();
229 let finish = FinishOnDrop(Arc::clone(&self.shared));
230 self.shared.runtime.spawn(async move {
234 let shared = &finish.0;
235 for worker in workers {
236 let _ = worker.await;
237 }
238 shared.connection.close().await;
239 if let Some(host) = &shared.host {
240 let _ = host.close().await;
242 }
243 });
244 }
245 let _ = finished.wait_for(|finished| *finished).await;
246 }
247
248 pub fn initialize_result(&self) -> Option<&InitializeResult> {
252 self.shared.initialize_result.as_ref()
253 }
254
255 pub fn durability(&self) -> SessionDurabilityProfile {
257 durability_profile(Some(&self.shared.durability))
258 }
259
260 pub async fn exit(&self) -> Option<io::Result<ExitClassification>> {
269 Some(self.shared.host.as_ref()?.exit().await)
270 }
271
272 pub fn is_closed(&self) -> bool {
274 self.shared.closed.load(Ordering::Acquire)
275 }
276
277 pub fn is_session_discarded(&self, session_id: &str) -> bool {
281 lock(&self.shared.discarded_session_ids).contains(session_id)
282 }
283
284 pub fn is_command_discarded(&self, command_id: &str) -> bool {
286 self.shared
287 .router
288 .sessions()
289 .iter()
290 .any(|session| session.is_command_discarded(command_id))
291 }
292}
293
294struct FinishOnDrop(Arc<ClientShared>);
297
298impl Drop for FinishOnDrop {
299 fn drop(&mut self) {
300 self.0.close_finished.send_replace(true);
301 }
302}
303
304pub(crate) struct ClientShared {
305 connection: Connection,
306 host: Option<HostExit>,
307 initialize_result: Option<InitializeResult>,
308 minter: Arc<dyn Fn() -> String + Send + Sync>,
309 durability: SessionDurability,
310 router: Arc<NotificationRouter>,
311 discarded_session_ids: Mutex<HashSet<String>>,
312 closed: AtomicBool,
313 transport_ended: AtomicBool,
314 close_tx: watch::Sender<bool>,
315 close_finished: watch::Sender<bool>,
316 pub(crate) runtime: tokio::runtime::Handle,
321}
322
323pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
324 match mutex.lock() {
325 Ok(guard) => guard,
326 Err(poisoned) => poisoned.into_inner(),
327 }
328}
329
330fn invalid_frame(error: serde_json::Error) -> FacadeError {
331 protocol_error(error.to_string())
332}
333
334fn protocol_error(message: impl Into<String>) -> FacadeError {
335 FacadeError::Protocol(ProtocolError::new(message, None))
336}
337
338fn initialize_params() -> InitializeParams {
339 InitializeParams {
340 client_info: ClientInfo {
341 name: "muse_code_sdk".to_owned(),
342 version: env!("CARGO_PKG_VERSION").to_owned(),
343 title: Some("Muse Code Rust SDK".to_owned()),
344 },
345 capabilities: None,
346 }
347}
348
349fn command_id_minter() -> impl Fn() -> String + Send + Sync + 'static {
350 let client_nonce = NEXT_CLIENT_NONCE.fetch_add(1, Ordering::Relaxed);
351 let sequence = AtomicU64::new(0);
352 move || mint_command_id(client_nonce, sequence.fetch_add(1, Ordering::Relaxed))
353}
354
355fn missing_host_pipe(name: &str) -> FacadeError {
356 FacadeError::Transport(io::Error::new(
357 io::ErrorKind::BrokenPipe,
358 format!("spawned host has no {name} pipe"),
359 ))
360}
361
362fn handshake_error(error: HandshakeError<ConnectionError>) -> FacadeError {
363 match error {
364 HandshakeError::Encode(error) | HandshakeError::InvalidResult(error) => {
365 invalid_frame(error)
366 }
367 HandshakeError::Transport(error) => connection_error(error),
368 }
369}
370
371fn connection_error(error: ConnectionError) -> FacadeError {
372 match error {
373 ConnectionError::Closed => FacadeError::TransportEnded,
374 ConnectionError::Transport(error) => FacadeError::Transport(error),
375 ConnectionError::Msp(error) => FacadeError::Msp(error),
376 ConnectionError::Protocol(error) => FacadeError::Protocol(error),
377 }
378}
379
380fn mint_command_id(client_nonce: u64, sequence: u64) -> String {
381 let millis = SystemTime::now()
382 .duration_since(UNIX_EPOCH)
383 .map_or(0, |duration| duration.as_millis() as u64)
384 & 0x0000_ffff_ffff_ffff;
385 let process = u64::from(std::process::id());
386 let mixed = sequence ^ client_nonce.rotate_left(31) ^ process.rotate_left(17);
387 format!(
388 "{:08x}-{:04x}-7{:03x}-8{:03x}-{:012x}",
389 millis >> 16,
390 millis & 0xffff,
391 (mixed >> 60) & 0x0fff,
392 (mixed >> 48) & 0x0fff,
393 mixed & 0x0000_ffff_ffff_ffff
394 )
395}
396
397#[cfg(test)]
398mod tests {
399 use super::mint_command_id;
400
401 #[test]
402 fn minted_command_ids_pin_the_uuid_v7_and_variant_shape() {
403 let id = mint_command_id(0x1234, 0x5678);
404 let bytes = id.as_bytes();
405
406 assert_eq!(id.len(), 36);
407 assert_eq!(&id[8..9], "-");
408 assert_eq!(&id[13..14], "-");
409 assert_eq!(&id[18..19], "-");
410 assert_eq!(&id[23..24], "-");
411 assert_eq!(bytes[14], b'7');
412 assert!(matches!(bytes[19], b'8' | b'9' | b'a' | b'b'));
413 assert!(id.chars().all(|ch| ch == '-' || ch.is_ascii_hexdigit()));
414 }
415}