diff --git a/crates/minimald-rpc/src/lib.rs b/crates/minimald-rpc/src/lib.rs index ad7442d8a8..46649adf68 100644 --- a/crates/minimald-rpc/src/lib.rs +++ b/crates/minimald-rpc/src/lib.rs @@ -190,3 +190,23 @@ impl OneshotSshRpc for CreateSession { type Request<'a> = CreateSessionRequest; type Response = Errorable; } + +/// An RPC to rename an existing session. +pub struct RenameSession; + +/// The request for a [`RenameSession`] RPC. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RenameSessionRequest { + pub id: SessionId, + pub new_name: String, +} + +/// The response for a [`RenameSession`] RPC. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct RenameSessionResponse; + +impl OneshotSshRpc for RenameSession { + const NAME: &'static str = constcat::concat!(RPC_SUBSYSTEM_PREFIX, "RenameSession"); + type Request<'a> = RenameSessionRequest; + type Response = Errorable; +} diff --git a/crates/minimald/src/rpc.rs b/crates/minimald/src/rpc.rs index 4d2cf472ca..6f23e7347a 100644 --- a/crates/minimald/src/rpc.rs +++ b/crates/minimald/src/rpc.rs @@ -1,7 +1,8 @@ use minimald_rpc::{ CreateSession, CreateSessionResponse, Errorable, GetSessionRecord, GetSessionRecordRequest, GetSessionRecordResponse, GetVersion, GetVersionResponse, ListSessions, ListSessionsEntry, - ListSessionsResponse, OneshotSshRpc, RPC_SUBSYSTEM_PREFIX, + ListSessionsResponse, OneshotSshRpc, RPC_SUBSYSTEM_PREFIX, RenameSession, + RenameSessionResponse, }; use russh::{ Channel as RuChannel, ChannelId, @@ -151,6 +152,27 @@ async fn serve_create_session(s: ServerStateHandle, c: RuChannel) { } } +async fn serve_rename_session(s: ServerStateHandle, c: RuChannel) { + let res = RenameSession + .handle_channel(c, async |req| { + let res = s + .sessions_manager() + .await + .rename_session(req.id, req.new_name) + .await; + match res { + Ok(()) => Ok(Errorable::Ok(RenameSessionResponse)), + Err(e) => Ok(Errorable::Err { + error: e.to_string(), + }), + } + }) + .await; + if let Err(e) = res { + tracing::warn!("RPC handler for {} failed: {}", RenameSession::NAME, e); + } +} + pub(crate) const STREAM_WORKSPACE_FILES: &str = constcat::concat!(RPC_SUBSYSTEM_PREFIX, "WorkspaceFilesTarZst"); @@ -223,6 +245,7 @@ pub async fn handle_ssh_rpc( | ListSessions::NAME | GetSessionRecord::NAME | CreateSession::NAME + | RenameSession::NAME | STREAM_WORKSPACE_FILES => { let mut conn_lock = c.lock().await; let c_hnd = match conn_lock.take(id) { @@ -252,6 +275,7 @@ pub async fn handle_ssh_rpc( ListSessions::NAME => spawn(serve_list_sessions(s, channel)), GetSessionRecord::NAME => spawn(serve_get_session_record(s, channel)), CreateSession::NAME => spawn(serve_create_session(s, channel)), + RenameSession::NAME => spawn(serve_rename_session(s, channel)), STREAM_WORKSPACE_FILES => spawn(serve_stream_workspace_files(s, config, channel)), _ => unreachable!(), }; @@ -261,7 +285,7 @@ pub async fn handle_ssh_rpc( #[cfg(test)] mod tests { - use minimald_rpc::{CreateSession, CreateSessionRequest}; + use minimald_rpc::{CreateSession, CreateSessionRequest, RenameSessionRequest}; use paths::HostAbsPath; use sessions::SessionId; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -531,4 +555,61 @@ mod tests { } ); } + + #[tokio::test] + async fn rename_session_propagates_into_the_running_session() { + let server = TestServer::new().await; + let mut client = server.connect().await; + let session_id = fresh_session(&mut client).await; + + // Bring the session up before renaming, so the rename has to reach the + // live actor's in-memory record rather than only touching disk. + let mngr = server.state.sessions_manager().await; + let handle = mngr + .get_session(SessionKeyPredicate::Id(session_id)) + .await + .unwrap() + .expect("freshly-created session should be retrievable"); + + let resp = client + .call::(&RenameSessionRequest { + id: session_id, + new_name: "renamed".to_string(), + }) + .await; + assert_eq!(resp, Errorable::Ok(RenameSessionResponse)); + + // The record held by the running session reflects the new name... + let record = handle.record().await; + assert_eq!(record.name.as_deref(), Some("renamed")); + // ...while its id is untouched by the rename. + assert_eq!(record.id, session_id); + + // The rename is reflected by GetRecord... + let get_session = client + .call::(&GetSessionRecordRequest::Id(record.id)) + .await; + assert_eq!( + get_session.record.as_ref().unwrap().name, + Some("renamed".to_string()) + ); + } + + #[tokio::test] + async fn rename_session_errors_for_unknown_id() { + let server = TestServer::new().await; + let mut client = server.connect().await; + + let resp = client + .call::(&RenameSessionRequest { + id: SessionId::nil(), + new_name: "renamed".to_string(), + }) + .await; + + assert!( + matches!(resp, Errorable::Err { error } if error.contains("no session with ID")), + "expected an unknown-id error", + ); + } } diff --git a/crates/minimald/src/session.rs b/crates/minimald/src/session.rs index 04813765fe..4735cf8f7d 100644 --- a/crates/minimald/src/session.rs +++ b/crates/minimald/src/session.rs @@ -5,7 +5,7 @@ use crate::{ use mctx::ConfigBuilder; use paths::DaemonAbsPath; use russh::{Channel, server::Msg}; -use sessions::store::SessionObject; +use sessions::{Record, store::SessionObject}; use std::fmt::{self}; use tokio::sync::{mpsc, oneshot}; @@ -41,6 +41,9 @@ enum SessionMessage { ChannelConfig, ), GetHostAttrs(oneshot::Sender>), + RefreshRecord(Record), + #[cfg(test)] + GetRecord(oneshot::Sender), } /// Manages a running session. @@ -86,6 +89,7 @@ impl Session { self.handle_message(msg).await; } } + /// Handles a specific message recieved by the session. async fn handle_message(&mut self, msg: SessionMessage) { match msg { @@ -105,6 +109,13 @@ impl Session { Some(h) => h.get_attrs().await.ok(), }); } + SessionMessage::RefreshRecord(r) => { + self.session.refresh_from_record(r); + } + #[cfg(test)] + SessionMessage::GetRecord(r) => { + let _ = r.send(self.session.record().clone()); + } } } @@ -213,6 +224,26 @@ impl SessionHandle { recv.await.expect("corresponding session is dead") } + /// Returns the session record currently held by the live session actor. + /// + /// This reads the actor's in-memory copy, not the on-disk record, so + /// tests can assert that updates have propagated into the running session. + #[cfg(test)] + pub(crate) async fn record(&self) -> Record { + let (send, recv) = oneshot::channel(); + // Ignore send errors - the recv will also fail. + let _ = self.0.send(SessionMessage::GetRecord(send)).await; + recv.await.expect("corresponding session is dead") + } + + /// Tell the session that the underlying session record was updated. + pub(crate) async fn apply_record(&self, new_record: Record) { + self.0 + .send(SessionMessage::RefreshRecord(new_record)) + .await + .expect("corresponding session is dead"); + } + pub async fn attach( &self, channel: Channel, diff --git a/crates/minimald/src/sessions.rs b/crates/minimald/src/sessions.rs index 098c5be647..fc79795865 100644 --- a/crates/minimald/src/sessions.rs +++ b/crates/minimald/src/sessions.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::{collections::BTreeMap, io::ErrorKind::NotFound}; use crate::{ session::{Session, SessionHandle}, @@ -53,6 +53,7 @@ enum ManagerMessage { GetRecord(SessionKeyPredicate, Responder>), GetSession(SessionKeyPredicate, Responder>), CreateSession(sessions::Record, Responder), + RenameSession(SessionId, String, Responder<()>), } /// Manages session instances, and session state on disk. @@ -185,6 +186,25 @@ impl Manager { }) .await; } + // Renames an existing session with the given ID. + ManagerMessage::RenameSession(id, new_name, r) => { + r.handle(async { + match self.store.find_by_id(&id)? { + None => Err(std::io::Error::new( + NotFound, + format!("no session with ID `{}`", id.as_ref()), + )), + Some(k) => { + self.store.rename(&k, new_name.clone())?; + if let Some(hnd) = self.running.get(&k) { + hnd.apply_record(self.store.get(&k)?.record().clone()).await; + } + Ok(()) + } + } + }) + .await + } } } } @@ -237,4 +257,19 @@ impl ManagerHandle { let _ = self.0.send(ManagerMessage::GetSession(pred, send)).await; recv.await.expect("corresponding sessions manager is dead") } + + /// Renames the given session to the given name. + pub async fn rename_session( + &self, + id: SessionId, + new_name: String, + ) -> Result<(), SessionsError> { + let (send, recv) = Responder::channel(); + // Ignore send errors - the recv will also fail. + let _ = self + .0 + .send(ManagerMessage::RenameSession(id, new_name, send)) + .await; + recv.await.expect("corresponding sessions manager is dead") + } } diff --git a/crates/sessions/src/store.rs b/crates/sessions/src/store.rs index f54c1b8cd2..26ca65777d 100644 --- a/crates/sessions/src/store.rs +++ b/crates/sessions/src/store.rs @@ -1,6 +1,6 @@ //! Manages session state on disk. -use std::collections::BTreeMap; +use std::{collections::BTreeMap, io::ErrorKind::AlreadyExists}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -10,10 +10,12 @@ use paths::{DaemonAbsPath, DaemonRelPath, sub_path}; use crate::{Record, SessionId}; /// Describes the session object yielded by [`Loader`]. -pub trait SessionObject: Sized + Send + 'static + std::fmt::Debug { +pub trait SessionObject: Sized + Send + Clone + 'static + std::fmt::Debug { type Key: SessionKey; fn record(&self) -> &Record; + fn refresh_from_record(&mut self, r: Record); + fn key(&self) -> &Self::Key; fn workspace_path(&self) -> DaemonAbsPath; } @@ -69,6 +71,15 @@ pub trait Loader { /// Returns an I/O error if the session directory, record, or index /// cannot be written. fn create(&mut self, record: Record) -> Result; + + /// Renames the session with the given key. + /// + /// # Errors + /// + /// Returns an I/O error if the session directory, record, or index + /// cannot be written. + /// `AlreadyExists` is returned if a session with that name already exists. + fn rename(&mut self, key: &Self::Key, new_name: String) -> Result<(), std::io::Error>; } /// The concrete key used to identify sessions from [`DiskLoader`]. @@ -85,7 +96,7 @@ impl SessionKey for DiskSessionKey { } /// The concrete session object from [`DiskLoader`]. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct DiskSession { key: DiskSessionKey, minimal_state_dir: DaemonAbsPath, @@ -98,6 +109,12 @@ impl SessionObject for DiskSession { fn record(&self) -> &Record { &self.record } + fn refresh_from_record(&mut self, r: Record) { + let id = self.record.id; + self.record = r; + self.record.id = id; // ID must never change + } + fn key(&self) -> &DiskSessionKey { &self.key } @@ -185,7 +202,7 @@ impl DiskLoader { /// The write is staged into a sibling temp file and then atomically /// renamed into place, so a crash mid-write can never leave a partially /// serialized `index.json` behind. - fn flush(&self) -> Result<(), std::io::Error> { + fn flush_index(&self) -> Result<(), std::io::Error> { let sessions_dir = self.minimal_dir.as_utf8_path().join("sessions"); let index_file = sessions_dir.join("index.json"); let tmp_file = sessions_dir.join("index.json.tmp"); @@ -202,6 +219,30 @@ impl DiskLoader { Ok(()) } + + /// Writes the given session record to disk. + /// + /// The write is staged into a sibling temp file and then atomically + /// renamed into place, so a crash mid-write can never leave a partially + /// serialized `record.json` behind. + fn write_record(&mut self, short: &String, record: &Record) -> Result<(), std::io::Error> { + let session_dir = self.minimal_dir.as_utf8_path().join("sessions").join(short); + std::fs::create_dir_all(&session_dir)?; + let record_file = session_dir.join("record.json"); + let tmp_file = session_dir.join("record.json.tmp"); + + let file = std::fs::File::create(&tmp_file)?; + serde_json::to_writer(&file, &record)?; + file.sync_all()?; + drop(file); + + #[cfg(target_os = "linux")] + common::renameat2::renameat2_cwd(tmp_file.as_std_path(), record_file.as_std_path(), 0)?; + #[cfg(not(target_os = "linux"))] + std::fs::rename(&tmp_file, &record_file)?; + + Ok(()) + } } impl Loader for DiskLoader { @@ -232,18 +273,11 @@ impl Loader for DiskLoader { short = format!("{:05x}", n.wrapping_add(1)); } - let session_dir = self - .minimal_dir - .as_utf8_path() - .join("sessions") - .join(&short); - std::fs::create_dir_all(&session_dir)?; - let record_file = session_dir.join("record.json"); - serde_json::to_writer(std::fs::File::create(record_file)?, &record)?; + self.write_record(&short, &record)?; self.index .insert(short.clone(), SessionId(uuid), record.name); - self.flush()?; + self.flush_index()?; Ok(DiskSessionKey { session_id: SessionId(uuid), @@ -290,6 +324,28 @@ impl Loader for DiskLoader { record, }) } + + fn rename(&mut self, key: &Self::Key, new_name: String) -> Result<(), std::io::Error> { + if self.index.find_by_name(&new_name).is_some() { + return Err(std::io::Error::new( + AlreadyExists, + format!("a session with the name `{new_name}` already exists"), + )); + } + + let mut obj = self.get(key)?; + let short = obj.key.dir_key.to_string(); + if let Some(old_name) = &obj.record.name { + self.index.name_to_id.remove(old_name); + } + + obj.record.name = Some(new_name.clone()); + self.write_record(&short, &obj.record)?; + + self.index.name_to_id.insert(new_name, obj.record.id); + self.flush_index()?; + Ok(()) + } } #[cfg(test)] @@ -408,4 +464,113 @@ mod tests { assert_eq!(&stored.record().id, original.id()); assert_eq!(stored.record().name.as_deref(), Some("my-session")); } + + #[test] + fn rename_updates_the_on_disk_record() { + let tmp = TempDir::new().unwrap(); + let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap(); + + let key = loader.create(sample_record()).unwrap(); + loader.rename(&key, "renamed".to_string()).unwrap(); + + // The record read back from disk reflects the new name. + assert_eq!( + loader.get(&key).unwrap().record().name.as_deref(), + Some("renamed") + ); + } + + #[test] + fn rename_remaps_the_name_index() { + let tmp = TempDir::new().unwrap(); + let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap(); + + let key = loader.create(sample_record()).unwrap(); + loader.rename(&key, "renamed".to_string()).unwrap(); + + // The new name resolves to the session... + assert_eq!(loader.find_by_name("renamed").unwrap(), Some(key)); + // ...and the old name no longer resolves to anything. + assert_eq!(loader.find_by_name("my-session").unwrap(), None); + } + + #[test] + fn rename_leaves_the_id_and_key_unchanged() { + let tmp = TempDir::new().unwrap(); + let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap(); + + let key = loader.create(sample_record()).unwrap(); + let id = *key.id(); + loader.rename(&key, "renamed".to_string()).unwrap(); + + // Renaming touches only the name; the id and short key are stable. + assert_eq!(loader.find_by_id(&id).unwrap().as_ref(), Some(&key)); + assert_eq!(&loader.get(&key).unwrap().record().id, &id); + } + + #[test] + fn rename_persists_across_loader_reinit() { + let tmp = TempDir::new().unwrap(); + + let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap(); + let key = loader.create(sample_record()).unwrap(); + loader.rename(&key, "renamed".to_string()).unwrap(); + drop(loader); + + // Both the record write and the index flush must survive a reload. + let reloaded = DiskLoader::new(loader_dir(&tmp)).unwrap(); + assert_eq!( + reloaded.get(&key).unwrap().record().name.as_deref(), + Some("renamed") + ); + assert_eq!(reloaded.find_by_name("renamed").unwrap(), Some(key)); + assert_eq!(reloaded.find_by_name("my-session").unwrap(), None); + } + + #[test] + fn rename_errors_when_the_target_name_is_taken() { + let tmp = TempDir::new().unwrap(); + let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap(); + + let first = loader.create(sample_record()).unwrap(); + loader + .create({ + let mut record = sample_record(); + record.name = Some("other".to_string()); + record + }) + .unwrap(); + + // "other" is already taken, so renaming the first session onto it fails. + assert_eq!( + loader + .rename(&first, "other".to_string()) + .err() + .map(|e| e.kind()), + Some(ErrorKind::AlreadyExists) + ); + // The failed rename left the original name intact. + assert_eq!(loader.find_by_name("my-session").unwrap(), Some(first)); + } + + #[test] + fn rename_names_a_previously_unnamed_session() { + let tmp = TempDir::new().unwrap(); + let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap(); + + let key = loader + .create({ + let mut record = sample_record(); + record.name = None; + record + }) + .unwrap(); + loader.rename(&key, "now-named".to_string()).unwrap(); + + assert_eq!( + loader.get(&key).unwrap().record().name.as_deref(), + Some("now-named") + ); + assert_eq!(loader.find_by_name("now-named").unwrap(), Some(key)); + } }