use std::{sync::Arc, time::Duration};
use pretty_assertions::assert_eq;
use rho_protocol::{
self as wire,
methods::{SessionConfigure, SessionPrompt},
BuildId, Client, ClientHello, ClientInfo, ContentBlock, DaemonInfo, DaemonStatus, RestartCost,
RpcError, Service, SessionChange, SessionConfigureParams, SessionConfigureResponse,
SessionPromptAnswer, SessionPromptParams, SettingsService,
};
use tempfile::TempDir;
use tokio::time::timeout;
use super::super::{
test_sessions::{load, prompts_shown, until, Load},
Sessions,
};
use crate::app::{
daemon_host::{
jobs::{JobRegistry, JobStore},
wire::session_to_wire,
},
pull_requests::ScriptedForge,
};
const TEST_BUDGET: Duration = Duration::from_secs(5);
struct Serving(Arc<Sessions>);
impl Service for Serving {
fn refused_newer(&self, _: wire::ProtocolVersion) -> RestartCost {
RestartCost {
in_progress: 0,
clients: 0,
}
}
fn skewed(&self, _: &ClientInfo, _: &BuildId) -> RestartCost {
RestartCost {
in_progress: 0,
clients: 0,
}
}
async fn status(&self) -> DaemonStatus {
unreachable!("the test asks no status")
}
async fn stop(&self) {}
async fn restart(&self) {}
async fn list_jobs(&self) -> wire::JobListResponse {
unreachable!("the test lists no jobs")
}
async fn answer_prompt(
&self,
params: SessionPromptParams,
) -> Result<SessionPromptAnswer, RpcError> {
self.0.prompt(params).await
}
async fn configure_session(
&self,
params: SessionConfigureParams,
) -> Result<SessionConfigureResponse, RpcError> {
self.0.configure(params).await
}
fn session_order(&self) -> &impl wire::SessionOrder {
&*self.0
}
}
impl SettingsService for Serving {}
#[derive(Debug, PartialEq)]
enum Seen {
Options(wire::PermissionMode),
Prompt,
}
#[tokio::test]
async fn a_prompt_read_after_a_change_runs_after_it_however_slow_the_change() {
let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
let sessions = Sessions::new(
Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
home.path(),
ScriptedForge::new(),
);
let session = load(&sessions, &root, Load::Saved).await;
let id = session_to_wire(session.id.clone());
let (stream, served) = tokio::io::duplex(1 << 20);
let info = DaemonInfo {
version: "test".into(),
pid: 0,
build: BuildId::of_this_crate(),
};
let service = Arc::new(Serving(Arc::clone(&sessions)));
tokio::spawn(async move {
rho_protocol::serve_connection(served, &info, service, std::future::pending()).await
});
let hello = ClientHello::command(ClientInfo {
name: "session-line-test".into(),
version: "0".into(),
});
let (client, _notifications, _) = Client::handshake(stream, hello).await.unwrap();
let held = sessions.hold_changes.write().await;
let plan_mode = SessionConfigureParams {
session: id.clone(),
change: SessionChange::PermissionMode {
mode: wire::PermissionMode::Plan,
},
};
let hello = SessionPromptParams {
author: wire::PromptAuthor::Person,
session: id.clone(),
content: vec![ContentBlock::Text {
text: "hello".into(),
}],
timeout_ms: None,
environment: std::iter::empty::<(String, String)>().collect(),
idempotency_key: None,
grant: None,
};
let configure = client.request::<SessionConfigure>(&plan_mode);
let prompt = client.request::<SessionPrompt>(&hello);
tokio::pin!(configure, prompt);
assert!(futures_util::poll!(configure.as_mut()).is_pending());
assert!(futures_util::poll!(prompt.as_mut()).is_pending());
until(
|| prompts_shown(&session) > 0 || sessions.lines.waiting(&id) > Some(0),
"the prompt started its turn or lined up",
)
.await;
drop(held);
let prompted = timeout(TEST_BUDGET, prompt)
.await
.expect("the prompt's turn saves its prompt")
.is_ok();
session.cancel_turn();
let changed = timeout(TEST_BUDGET, configure)
.await
.expect("the change applies")
.map(|changed| changed.options.permission_mode.current)
.ok();
let seen: Vec<_> = session
.feed
.buffered_for_tests()
.into_iter()
.filter_map(|event| match event {
wire::SessionEvent::OptionsChanged { options } => {
Some(Seen::Options(options.permission_mode.current))
}
wire::SessionEvent::UserMessage { .. } => Some(Seen::Prompt),
_ => None,
})
.collect();
assert_eq!(
(prompted, changed, seen, sessions.lines.waiting(&id)),
(
true,
Some(wire::PermissionMode::Plan),
vec![Seen::Options(wire::PermissionMode::Plan), Seen::Prompt],
None,
)
);
}