8000 feat(minimald): implement RPC for creating sessions, index by session name also by twitchyliquid64 · Pull Request #265 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/minimald/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ edition.workspace = true
publish.workspace = true

[dependencies]
bytes.workspace = true
camino.workspace = true
clap.workspace = true
clap_complete.workspace = true
Expand Down
89 changes: 87 additions & 2 deletions crates/minimald/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ impl GetVersion {
pub struct ListSessions;

/// An entry in the ListSessions response.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ListSessionsEntry {
pub id: Uuid,
pub name: Option<String>,
Expand Down Expand Up @@ -193,6 +193,46 @@ impl GetSessionRecord {
}
}

/// An RPC to create a new session based on the given record.
pub struct CreateSession;

/// The request for a [`CreateSession`] RPC.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSessionRequest {
pub record: sessions::Record,
}
Comment thread
twitchyliquid64 marked this conversation as resolved.
Resolved

/// The response for a [`CreateSession`] RPC.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSessionResponse {
pub id: Uuid,
}

impl OneshotSshRpc for CreateSession {
const NAME: &'static str = constcat::concat!(RPC_SUBSYSTEM_PREFIX, "CreateSession");
type Request<'a> = CreateSessionRequest;
type Response = CreateSessionResponse;
}

impl CreateSession {
pub async fn handle(self, s: ServerStateHandle, c: RuChannel<Msg>) {
let res = self
.handle_channel(c, async |req| {
let mngr = s.sessions_manager().await;
Ok(CreateSessionResponse {
id: mngr
.create_session(req.record)
.await
.map_err(|e| ConnectionError::Internal(e.to_string()))?,
})
})
.await;
if let Err(e) = res {
tracing::warn!("RPC handler for {} failed: {}", Self::NAME, e);
}
}
}

/// Handles an RPC going over an SSH subsystem channel.
///
/// This method takes ownership of the ssh channel, including
Expand All @@ -211,7 +251,7 @@ pub async fn handle_ssh_rpc(
) -> Result<(), ConnectionError> {
// Take the channel from connection state if its a known RPC.
let channel = match name {
GetVersion::NAME | ListSessions::NAME | GetSessionRecord::NAME => {
GetVersion::NAME | ListSessions::NAME | GetSessionRecord::NAME | CreateSession::NAME => {
let mut conn_lock = c.lock().await;
let c_hnd = match conn_lock.take(id) {
None => {
Expand Down Expand Up @@ -239,6 +279,7 @@ pub async fn handle_ssh_rpc(
GetVersion::NAME => spawn(GetVersion.handle(channel)),
ListSessions::NAME => spawn(ListSessions.handle(s, channel)),
GetSessionRecord::NAME => spawn(GetSessionRecord.handle(s, channel)),
CreateSession::NAME => spawn(CreateSession.handle(s, channel)),
_ => unreachable!(),
};

Expand All @@ -247,6 +288,8 @@ pub async fn handle_ssh_rpc(

#[cfg(test)]
mod tests {
use sessions::paths::HostAbsPath;

use super::*;
use crate::test_harness::TestServer;

Expand Down Expand Up @@ -312,4 +355,46 @@ mod tests {
assert_eq!(resp.version, env!("CARGO_PKG_VERSION"));
}
}

#[tokio::test]
async fn create_session_shows_in_get_and_list() {
let server = TestServer::new().await;
let mut client = server.connect().await;

let create_session = client
.call::<CreateSession>(&CreateSessionRequest {
record: sessions::Record {
id: Uuid::nil(),
name: Some("my session".to_string()),
username: None,
project_path: HostAbsPath::try_new("/uwu").unwrap(),
attrs: Default::default(),
},
})
.await;

assert!(create_session.id != Uuid::nil());

let get_session = client
.call::<GetSessionRecord>(&GetSessionRecordRequest::Id(create_session.id))
.await;
assert_eq!(get_session.record.as_ref().unwrap().id, create_session.id);
assert_eq!(
get_session.record.as_ref().unwrap().name,
Some("my session".to_string())
);
assert_eq!(
get_session.record.as_ref().unwrap().project_path,
HostAbsPath::try_new("/uwu").unwrap()
);

let list_sessions = client.call::<ListSessions>(&()).await;
assert_eq!(
list_sessions.sessions,
vec![ListSessionsEntry {
id: create_session.id,
name: Some("my session".to_string()),
}]
);
}
}
22 changes: 21 additions & 1 deletion crates/minimald/src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::BTreeMap;
use crate::session::{Session, SessionHandle};
use sessions::{
paths::DaemonAbsPath,
store::{DiskLoader, Loader, SessionObject},
store::{DiskLoader, Loader, SessionKey, SessionObject},
};
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;
Expand Down Expand Up @@ -48,6 +48,7 @@ enum ManagerMessage {
List(Responder<Vec<SessionInfo>>),
GetRecord(SessionKeyPredicate, Responder<Option<sessions::Record>>),
GetSession(SessionKeyPredicate, Responder<Option<SessionHandle>>),
CreateSession(sessions::Record, Responder<Uuid>),
}

/// Manages session instances, and session state on disk.
Expand Down Expand Up @@ -155,6 +156,14 @@ impl<L: Loader> Manager<L> {
})
.await;
}
// Creates a session using the given record.
ManagerMessage::CreateSession(record, r) => {
r.handle(async {
let k = self.store.create(record)?;
Ok(*k.uuid())
})
.await;
}
}
}
}
Expand Down Expand Up @@ -183,6 +192,17 @@ impl ManagerHandle {
recv.await.expect("corresponding sessions manager is dead")
}

/// Creates a session based on the given record.
pub async fn create_session(&self, record: sessions::Record) -> Result<Uuid, ResponseError> {
let (send, recv) = Responder::channel();
// Ignore send errors - the recv will also fail.
let _ = self
.0
.send(ManagerMessage::CreateSession(record, send))
.await;
recv.await.expect("corresponding sessions manager is dead")
}

/// Gets a handle to the session corresponding with the given predicate.
pub async fn get_session(
&self,
Expand Down
1 change: 1 addition & 0 deletions crates/sessions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod vars;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
/// Unique ID describing this session.
#[serde(default = "Uuid::nil")]
pub id: Uuid,
Comment thread
twitchyliquid64 marked this conversation as resolved.
Resolved
/// The name a user assigned to this session, if
/// one was specifically assigned.
Expand Down
83 changes: 64 additions & 19 deletions crates/sessions/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::paths::{DaemonAbsPath, DaemonRelPath};
Expand Down Expand Up @@ -106,6 +107,21 @@ impl SessionObject for DiskSession {
}
}

#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
struct Index {
short_to_uuid: BTreeMap<String, Uuid>,
name_to_uuid: BTreeMap<String, Uuid>,
}

impl Index {
pub fn insert(&mut self, short: String, uuid: Uuid, name: Option<String>) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor, but do we want search to live in the index type as well?

self.short_to_uuid.insert(short, uuid);
if let Some(name) = name {
self.name_to_uuid.insert(name, uuid);
}
}
}

/// A loader of session state based on <minimal-state-dir>/sessions.
///
/// ./index.json maps short directory names to session UUIDs. Typically
Expand All @@ -115,7 +131,7 @@ impl SessionObject for DiskSession {
/// ./<short-dir-name>/record.json is the session record.
pub struct DiskLoader {
minimal_dir: DaemonAbsPath,
index: BTreeMap<String, Uuid>,
index: Index,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

10BC8

Just to clarify, is this going to be always kept in sync or is it going to be lazy? If lazy, we probably want to wrap it in RefCell so any future read-only methods don't need to take &mut self. Looks like it's kept in sync so far, just wanted to check.

}

impl DiskLoader {
Expand All @@ -132,7 +148,7 @@ impl DiskLoader {
let index = if std::fs::exists(&index_file)? {
serde_json::from_reader(std::fs::File::open(index_file)?)?
} else {
BTreeMap::new()
Index::default()
};

Ok(Self { minimal_dir, index })
Expand Down Expand Up @@ -167,6 +183,15 @@ impl Loader for DiskLoader {
type Object = DiskSession;

fn create(&mut self, mut record: Record) -> Result<Self::Key, std::io::Error> {
if let Some(name) = &record.name
&& self.index.name_to_uuid.contains_key(name)
{
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("a session with name `{name}` already exists"),
));
}

let uuid = Uuid::now_v7();
record.id = uuid;

Expand All @@ -175,7 +200,7 @@ impl Loader for DiskLoader {
// We got unlucky and the short name collided, 20 bits of entropy
// so rare but very possible. Increment the short name past
// any collisions in this case.
while self.index.contains_key(&short) {
while self.index.short_to_uuid.contains_key(&short) {
let n = u32::from_str_radix(&short, 16)
.expect("short dir name is always 5 hex chars from a UUID suffix");
short = format!("{:05x}", n.wrapping_add(1));
Expand All @@ -190,7 +215,7 @@ impl Loader for DiskLoader {
let record_file = session_dir.join("record.json");
serde_json::to_writer(std::fs::File::create(record_file)?, &record)?;

self.index.insert(short.clone(), uuid);
self.index.insert(short.clone(), uuid, record.name);
self.flush()?;

Ok(DiskSessionKey {
Expand All @@ -200,15 +225,19 @@ impl Loader for DiskLoader {
}

fn list(&self) -> impl Iterator<Item = Self::Key> {
self.index.iter().map(|(short, id)| Self::Key {
session_uuid: *id,
dir_key: DaemonRelPath::try_new(short).unwrap(),
})
self.index
.short_to_uuid
.iter()
.map(|(short, id)| Self::Key {
session_uuid: *id,
dir_key: DaemonRelPath::try_new(short).unwrap(),
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect this is something that's going to keep coming up. We probably want to newtype Uuid as SessionId (this would be good regardless) and either implement a to_daemon_rel_path on it.

We should probably also add new_unchecked constructors (with big warnings on them) for the path types and just be really careful about where we use them.

Don't think we can do From<SessionId> for DaemonRelPath since we were talking about moving the paths module to its own crate and the sessions crate will be downstream of that.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slightly out of scope but we probably want to rename this method to keys which is more standard.

})
}

fn find_by_uuid(&self, id: &Uuid) -> Result<Option<Self::Key>, std::io::Error> {
Ok(self
.index
.short_to_uuid
.iter()
.find(|(_short, iter_id)| *iter_id == id)
.map(|(short, id)| Self::Key {
Expand All @@ -217,20 +246,15 @@ impl Loader for DiskLoader {
}))
}
fn find_by_name<S: AsRef<str>>(&self, name: S) -> Result<Option<Self::Key>, std::io::Error> {
for k in self.list() {
let record = self.get(&k)?;
if let Some(stored_name) = &record.record().name
&& stored_name == name.as_ref()
{
return Ok(Some(k));
}
match self.index.name_to_uuid.get(name.as_ref()) {
Some(uuid) => self.find_by_uuid(uuid),
None => Ok(None),
}
Ok(None)
}

fn get(&self, key: &Self::Key) -> Result<Self::Object, std::io::Error> {
assert!(
self.index.contains_key(key.dir_key.as_str()),
self.index.short_to_uuid.contains_key(key.dir_key.as_str()),
"key {:?} not present in index — Keys are only handed out for sessions that exist",
key.dir_key,
);
Expand All @@ -253,7 +277,7 @@ impl Loader for DiskLoader {
mod tests {
use super::*;
use crate::paths::HostAbsPath;
use std::collections::BTreeSet;
use std::{collections::BTreeSet, io::ErrorKind};
use tempfile::TempDir;

fn loader_dir(tmp: &TempDir) -> DaemonAbsPath {
Expand Down Expand Up @@ -314,13 +338,34 @@ mod tests {
assert_eq!(&stored.record().id, key.uuid());
}

#[test]
fn create_errors_on_non_unique_name() {
let tmp = TempDir::new().unwrap();
let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap();

loader.create(sample_record()).unwrap();
assert_eq!(
loader.create(sample_record()).err().map(|e| e.kind()),
Some(ErrorKind::AlreadyExists)
);
}

#[test]
fn list_yields_a_key_for_every_created_session() {
let tmp = TempDir::new().unwrap();
let mut loader = DiskLoader::new(loader_dir(&tmp)).unwrap();

let created: BTreeSet<Uuid> = (0..5)
.map(|_| *loader.create(sample_record()).unwrap().uuid())
.map(|i| {
*loader
.create({
let mut record = sample_record();
record.name = Some(format!("session-{i}"));
record
})
.unwrap()
.uuid()
})
.collect();
let listed: BTreeSet<Uuid> = loader.list().map(|k| *k.uuid()).collect();

Expand Down
Loading
0