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