mod host;
mod list;
mod open;
mod shared;
use std::collections::HashSet;
use std::io;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::watch;
use crate::DuplexTransport;
use crate::connection::{Connection, ConnectionError, StdioTransport};
use crate::errors::ProtocolError;
use crate::fingerprint::FingerprintWarning;
use crate::handshake::{Handshake, HandshakeError};
use crate::host_death::{SessionDurabilityProfile, durability_profile};
use crate::msp::{ClientInfo, InitializeParams, InitializeResult, SessionDurability};
use crate::spawn::{ExitClassification, MuseChild, SpawnOptions, spawn_muse};
use host::HostExit;
use shared::NotificationRouter;
static NEXT_CLIENT_NONCE: AtomicU64 = AtomicU64::new(0);
pub use crate::errors::MuseError as FacadeError;
pub type FacadeResult<T> = Result<T, FacadeError>;
pub use list::ListSessionsOptions;
pub use open::{ResumeSessionOptions, StartSessionOptions};
pub struct MuseClient {
shared: Arc<ClientShared>,
}
pub struct MuseClientConnection {
pub client: MuseClient,
pub fingerprint_warning: Option<FingerprintWarning>,
}
impl MuseClient {
pub async fn spawn(options: SpawnOptions) -> FacadeResult<MuseClientConnection> {
let mut host = spawn_muse(options)?;
let stdin = host
.take_stdin()
.ok_or_else(|| missing_host_pipe("stdin"))?;
let stdout = host
.take_stdout()
.ok_or_else(|| missing_host_pipe("stdout"))?;
Self::attach_transport(StdioTransport::new(stdin, stdout), Some(host)).await
}
pub async fn attach<T>(transport: T) -> FacadeResult<MuseClientConnection>
where
T: DuplexTransport + 'static,
{
Self::attach_transport(transport, None).await
}
async fn attach_transport<T>(
transport: T,
mut host: Option<MuseChild>,
) -> FacadeResult<MuseClientConnection>
where
T: DuplexTransport + 'static,
{
let router = Arc::new(NotificationRouter::default());
let route = Arc::clone(&router);
let overflow = Arc::clone(&router);
let (connection, driver, notifications) = Connection::with_notification_handler(
transport,
move |notification| {
route.route(notification);
},
move |notification| {
overflow.overflow(notification);
},
);
tokio::spawn(notifications.run());
tokio::spawn(driver.run());
let initialized = match Handshake::new(connection)
.initialize(initialize_params())
.await
{
Ok(initialized) => initialized,
Err(error) => {
if let Some(host) = host.as_mut() {
let _ = host.close().await;
}
return Err(handshake_error(error));
}
};
let durability = initialized
.initialize_result
.session_durability
.clone()
.unwrap_or(SessionDurability::Durable);
let fingerprint_warning = initialized.fingerprint_warning.clone();
let initialize_result = initialized.initialize_result.clone();
let client = Self::from_connection(
initialized.into_connection(),
router,
durability,
command_id_minter(),
Some(initialize_result),
host,
);
Ok(MuseClientConnection {
client,
fingerprint_warning,
})
}
pub fn new<T>(transport: T, durability: SessionDurability) -> Self
where
T: DuplexTransport + 'static,
{
Self::with_command_id_minter(transport, durability, command_id_minter())
}
pub fn with_command_id_minter<T, F>(
transport: T,
durability: SessionDurability,
minter: F,
) -> Self
where
T: DuplexTransport + 'static,
F: Fn() -> String + Send + Sync + 'static,
{
let router = Arc::new(NotificationRouter::default());
let route = Arc::clone(&router);
let overflow = Arc::clone(&router);
let (connection, driver, notifications) = Connection::with_notification_handler(
transport,
move |notification| {
route.route(notification);
},
move |notification| {
overflow.overflow(notification);
},
);
tokio::spawn(notifications.run());
tokio::spawn(driver.run());
Self::from_connection(connection, router, durability, minter, None, None)
}
fn from_connection<F>(
connection: Connection,
router: Arc<NotificationRouter>,
durability: SessionDurability,
minter: F,
initialize_result: Option<InitializeResult>,
host: Option<MuseChild>,
) -> Self
where
F: Fn() -> String + Send + Sync + 'static,
{
let (close_tx, _) = watch::channel(false);
let (close_finished, _) = watch::channel(false);
let mut driver_closed = connection.subscribe_closed();
router.set_durability(durability.clone());
let shared = Arc::new(ClientShared {
connection,
host: host.map(HostExit::spawn),
initialize_result,
minter: Arc::new(minter),
durability,
router,
discarded_session_ids: Mutex::new(HashSet::new()),
closed: AtomicBool::new(false),
transport_ended: AtomicBool::new(false),
close_tx,
close_finished,
runtime: tokio::runtime::Handle::current(),
});
let weak = Arc::downgrade(&shared);
tokio::spawn(async move {
let already_closed = *driver_closed.borrow();
if !already_closed {
let _ = driver_closed.changed().await;
}
if let Some(shared) = weak.upgrade() {
shared.mark_transport_ended();
}
});
Self { shared }
}
pub async fn close(&self) {
let mut finished = self.shared.close_finished.subscribe();
if !self.shared.closed.swap(true, Ordering::AcqRel) {
self.shared.close_tx.send_replace(true);
let workers = self.shared.begin_close();
let finish = FinishOnDrop(Arc::clone(&self.shared));
self.shared.runtime.spawn(async move {
let shared = &finish.0;
for worker in workers {
let _ = worker.await;
}
shared.connection.close().await;
if let Some(host) = &shared.host {
let _ = host.close().await;
}
});
}
let _ = finished.wait_for(|finished| *finished).await;
}
pub fn initialize_result(&self) -> Option<&InitializeResult> {
self.shared.initialize_result.as_ref()
}
pub fn durability(&self) -> SessionDurabilityProfile {
durability_profile(Some(&self.shared.durability))
}
pub async fn exit(&self) -> Option<io::Result<ExitClassification>> {
Some(self.shared.host.as_ref()?.exit().await)
}
pub fn is_closed(&self) -> bool {
self.shared.closed.load(Ordering::Acquire)
}
pub fn is_session_discarded(&self, session_id: &str) -> bool {
lock(&self.shared.discarded_session_ids).contains(session_id)
}
pub fn is_command_discarded(&self, command_id: &str) -> bool {
self.shared
.router
.sessions()
.iter()
.any(|session| session.is_command_discarded(command_id))
}
}
struct FinishOnDrop(Arc<ClientShared>);
impl Drop for FinishOnDrop {
fn drop(&mut self) {
self.0.close_finished.send_replace(true);
}
}
pub(crate) struct ClientShared {
connection: Connection,
host: Option<HostExit>,
initialize_result: Option<InitializeResult>,
minter: Arc<dyn Fn() -> String + Send + Sync>,
durability: SessionDurability,
router: Arc<NotificationRouter>,
discarded_session_ids: Mutex<HashSet<String>>,
closed: AtomicBool,
transport_ended: AtomicBool,
close_tx: watch::Sender<bool>,
close_finished: watch::Sender<bool>,
pub(crate) runtime: tokio::runtime::Handle,
}
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
match mutex.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
fn invalid_frame(error: serde_json::Error) -> FacadeError {
protocol_error(error.to_string())
}
fn protocol_error(message: impl Into<String>) -> FacadeError {
FacadeError::Protocol(ProtocolError::new(message, None))
}
fn initialize_params() -> InitializeParams {
InitializeParams {
client_info: ClientInfo {
name: "muse_code_sdk".to_owned(),
version: env!("CARGO_PKG_VERSION").to_owned(),
title: Some("Muse Code Rust SDK".to_owned()),
},
capabilities: None,
}
}
fn command_id_minter() -> impl Fn() -> String + Send + Sync + 'static {
let client_nonce = NEXT_CLIENT_NONCE.fetch_add(1, Ordering::Relaxed);
let sequence = AtomicU64::new(0);
move || mint_command_id(client_nonce, sequence.fetch_add(1, Ordering::Relaxed))
}
fn missing_host_pipe(name: &str) -> FacadeError {
FacadeError::Transport(io::Error::new(
io::ErrorKind::BrokenPipe,
format!("spawned host has no {name} pipe"),
))
}
fn handshake_error(error: HandshakeError<ConnectionError>) -> FacadeError {
match error {
HandshakeError::Encode(error) | HandshakeError::InvalidResult(error) => {
invalid_frame(error)
}
HandshakeError::Transport(error) => connection_error(error),
}
}
fn connection_error(error: ConnectionError) -> FacadeError {
match error {
ConnectionError::Closed => FacadeError::TransportEnded,
ConnectionError::Transport(error) => FacadeError::Transport(error),
ConnectionError::Msp(error) => FacadeError::Msp(error),
ConnectionError::Protocol(error) => FacadeError::Protocol(error),
}
}
fn mint_command_id(client_nonce: u64, sequence: u64) -> String {
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_millis() as u64)
& 0x0000_ffff_ffff_ffff;
let process = u64::from(std::process::id());
let mixed = sequence ^ client_nonce.rotate_left(31) ^ process.rotate_left(17);
format!(
"{:08x}-{:04x}-7{:03x}-8{:03x}-{:012x}",
millis >> 16,
millis & 0xffff,
(mixed >> 60) & 0x0fff,
(mixed >> 48) & 0x0fff,
mixed & 0x0000_ffff_ffff_ffff
)
}
#[cfg(test)]
mod tests {
use super::mint_command_id;
#[test]
fn minted_command_ids_pin_the_uuid_v7_and_variant_shape() {
let id = mint_command_id(0x1234, 0x5678);
let bytes = id.as_bytes();
assert_eq!(id.len(), 36);
assert_eq!(&id[8..9], "-");
assert_eq!(&id[13..14], "-");
assert_eq!(&id[18..19], "-");
assert_eq!(&id[23..24], "-");
assert_eq!(bytes[14], b'7');
assert!(matches!(bytes[19], b'8' | b'9' | b'a' | b'b'));
assert!(id.chars().all(|ch| ch == '-' || ch.is_ascii_hexdigit()));
}
}