8000 feat(sessions): SubmitVerdict handler resumes pending sessions by evanspearman · Pull Request #618 · 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
103 changes: 94 additions & 9 deletions crates/minimal/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,93 @@ async fn cmd_ls(global: &GlobalArgs, args: LsArgs) -> Result<(), ()> {
Ok(())
}

/// [`PolicyHooks`] impl that aborts on every unapproved item.
///
/// `minimal2` has no interactive prompt yet, so anything the user's
/// policy can't auto-decide bubbles into here, and we treat that as
/// "abort the session creation, surface a clear error." The user can
/// widen their policy (`allow`/`ignore`) to admit specific items once
/// the policy-config story lands.
struct AbortOnUnapproved;

impl sessions::core::hooks::PolicyHooks for AbortOnUnapproved {
fn on_var_unapproved(
&self,
_policy: sessions::core::policy::VarsPolicy,
_items: &[sessions::core::hooks::Unapproved<'_, str>],
) -> sessions::core::hooks::HookResult<sessions::core::policy::VarsPolicy> {
sessions::core::hooks::HookResult::Abort
}

fn on_patch_unapproved(
&self,
_policy: sessions::core::policy::PatchPolicy,
_items: &[sessions::core::hooks::Unapproved<'_, camino::Utf8Path>],
) -> sessions::core::hooks::HookResult<sessions::core::policy::PatchPolicy> {
sessions::core::hooks::HookResult::Abort
}
}

/// Phase 3 + final SubmitVerdict round-trip for a `Pending` session.
///
/// Runs `handle_response` over the daemon's `ContributionResponse`
/// with [`UserPolicy::default`] (today's empty policy — see
/// [`AbortOnUnapproved`]); sends the resulting [`ContributionVerdict`]
/// over the [`SubmitVerdict`] RPC; unwraps the daemon's terminal
/// [`SessionStep::Active`] reply to the finalized session id.
///
/// [`UserPolicy::default`]: sessions::core::policy::UserPolicy::default
/// [`SubmitVerdict`]: minimald_rpc::SubmitVerdict
async fn drive_pending_to_active(
client: &mut client::Client,
response: sessions::wire::request::ContributionResponse,
) -> Result<sessions::SessionId, ()> {
use minimald_rpc::SubmitVerdict;
use sessions::client::handler::handle_response;
use sessions::core::compose::ComposeOptions;
use sessions::core::policy::UserPolicy;
use sessions::wire::request::SessionStep;

let hooks = AbortOnUnapproved;
let verdict = handle_response(
response,
&[],
UserPolicy::default(),
&hooks,
ComposeOptions::default(),
&|name| std::env::var(name),
)
.map_err(|e| eprintln!("Composition gating failed: {e}"))?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

let resp = client
.oneshot_rpc::<SubmitVerdict>(verdict)
.await
.map_err(|e| eprintln!("SubmitVerdict RPC failed: {e}"))?;
let step = match resp {
minimald_rpc::Errorable::Ok(s) => s,
minimald_rpc::Errorable::Err { error } => {
eprintln!("SubmitVerdict failed: {error}");
return Err(());
}
};
match step {
SessionStep::Active { id } => Ok(id),
SessionStep::Response { .. } => {
// The daemon's terminal reply today is always Active
// (single-round flow). Multi-round Response would be a
// future extension and the client isn't wired for it.
eprintln!(
"SubmitVerdict returned a follow-up Response, which this client cannot drive"
);
Err(())
}
SessionStep::Fault { error } => {
eprintln!("SubmitVerdict faulted: {error}");
Err(())
}
}
}

/// Create a new session via the `CreateSession` RPC.
async fn cmd_activate(global: &GlobalArgs, args: ActivateArgs) -> Result<(), ()> {
if let Err(e) = autospawn::ensure_daemon_running(global.minvmd, global.minimal_dir.as_deref()) {
Expand Down Expand Up @@ -495,17 +582,15 @@ async fn cmd_activate(global: &GlobalArgs, args: ActivateArgs) -> Result<(), ()>
return Err(());
}
};
// Today the daemon only ever produces `Ready` (the empty-
// contribution fast path). `Pending` lights up when Phase 2
// routing lands.
// The daemon may finalize immediately (`Ready`) or ask the
// client to gate items first (`Pending`). On `Pending`: run
// Phase 3 (`handle_response`) against the user's policy, then
// send the resulting verdict over `SubmitVerdict` and wait for
// the daemon's terminal `SessionStep::Active`.
let id = match created {
minimald_rpc::CreateSessionResponse::Ready { id } => id,
minimald_rpc::CreateSessionResponse::Pending { .. } => {
eprintln!(
"CreateSession returned Pending, but the composition pipeline \
is not wired in this client yet",
);
return Err(());
minimald_rpc::CreateSessionResponse::Pending { id: _, response } => {
drive_pending_to_active(&mut client, response).await?
}
};

Expand Down
34 changes: 33 additions & 1 deletion crates/minimald/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use minimald_rpc::{
GetSessionRecordResponse, GetVersion, GetVersionResponse, IssueClientCert,
IssueClientCertRequest, ListSessions, ListSessionsEntry, ListSessionsResponse, OneshotSshRpc,
RPC_SUBSYSTEM_PREFIX, RenameSession, RenameSessionResponse, Shutdown, ShutdownRequest,
ShutdownResponse,
ShutdownResponse, SubmitVerdict,
};
use russh::{
Channel as RuChannel, ChannelId,
Expand Down Expand Up @@ -161,6 +161,13 @@ async fn serve_create_session(
Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => Errorable::Err {
error: e.to_string(),
},
// The daemon's in-flight Pending stash is full
// (see `MAX_PENDING_SESSIONS`). Surface as a clean
// typed error so the client can retry rather than
// treat it as a transport failure.
Err(e) if e.kind() == std::io::ErrorKind::ResourceBusy => Errorable::Err {
error: e.to_string(),
},
Err(e) => return Err(ConnectionError::Internal(e.to_string())),
},
)
Expand All @@ -171,6 +178,29 @@ async fn serve_create_session(
}
}

/// `SubmitVerdict`: the client's per-item decisions for a `Pending`
/// session. Delegates to the manager actor, which pops the matching
/// `PendingComposeState`, runs `resume_from_verdict`, and promotes
/// the record `Pending → Active`. Replies with `Errorable::Ok(SessionStep)`
/// where the `SessionStep` is `Active { id }` on success or
/// `Fault { error }` for a structured failure (unknown id, wrong
/// state, or a `ComposeError`-mapped `WireError`). Manager-side
/// `io::Error`s bubble up as `ConnectionError::Internal`.
async fn serve_submit_verdict(s: ServerStateHandle, c: RuChannel<Msg>) {
let res = SubmitVerdict
.handle_channel(c, async |req| {
let mngr = s.sessions_manager().await;
match mngr.submit_verdict(req).await {
Ok(step) => Ok(Errorable::Ok(step)),
Err(e) => Err(ConnectionError::Internal(e.to_string())),
}
})
.await;
if let Err(e) = res {
tracing::warn!("RPC handler for {} failed: {}", SubmitVerdict::NAME, e);
}
}

async fn serve_rename_session(s: ServerStateHandle, c: RuChannel<Msg>) {
let res = RenameSession
.handle_channel(c, async |req| {
Expand Down Expand Up @@ -387,6 +417,7 @@ pub async fn handle_ssh_rpc(
| ListSessions::NAME
| GetSessionRecord::NAME
| CreateSession::NAME
| SubmitVerdict::NAME
| RenameSession::NAME
| DestroySession::NAME
| Shutdown::NAME
Expand Down Expand Up @@ -423,6 +454,7 @@ pub async fn handle_ssh_rpc(
ListSessions::NAME => drop(spawn(serve_list_sessions(s, channel))),
GetSessionRecord::NAME => drop(spawn(serve_get_session_record(s, channel))),
CreateSession::NAME => drop(spawn(serve_create_session(s, channel, ssh_username))),
SubmitVerdict::NAME => drop(spawn(serve_submit_verdict(s, channel))),
RenameSession::NAME => drop(spawn(serve_rename_session(s, channel))),
DestroySession::NAME => drop(spawn(serve_destroy_session(s, channel))),
Shutdown::NAME => drop(spawn(serve_shutdown(s, channel))),
Expand Down
Loading
Loading
0