use std::time::Duration;
use rho_protocol::{
methods::{SessionDetach, SessionObserve},
Cursor, DaemonNotification, DetachReason, InputRequest, InputRequestId, JobState,
Notifications, Replay, Seq, SessionActivity, SessionAttachResponse, SessionDetachParams,
SessionEvent, SessionId, SessionObserveParams, StreamId, TurnId, TurnOutcome,
};
use serde::{Deserialize, Serialize};
use super::{
params::{format_cursor, WaitResult},
transcript::Transcript,
ControlError,
};
use crate::{
app::daemon_cli::{self, Reach},
daemon::{ConnectAs, Connection},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Connect {
Reach(Reach),
Restarted,
}
enum Notice {
Event(Seq, SessionEvent),
Detached(DetachReason),
Closed,
}
struct Attached {
connection: Connection,
session: SessionId,
response: SessionAttachResponse,
}
impl Attached {
async fn open(
connect: Connect,
session: &SessionId,
after: Option<Cursor>,
) -> Result<Self, ControlError> {
let connection = match connect {
Connect::Reach(reach) => daemon_cli::connect_with(reach, ConnectAs::Agent).await?,
Connect::Restarted => daemon_cli::connect_restarted(ConnectAs::Agent).await?,
};
let response = connection
.client
.request::<SessionObserve>(&SessionObserveParams {
session: session.clone(),
after,
})
.await?;
Ok(Self {
connection,
session: session.clone(),
response,
})
}
async fn next(&mut self) -> Notice {
let notifications: &mut Notifications = &mut self.connection.notifications;
loop {
match notifications.recv().await {
Some(DaemonNotification::SessionEvent(params))
if params.session == self.session =>
{
return Notice::Event(params.seq, params.event)
}
Some(DaemonNotification::SessionDetached(params))
if params.session == self.session =>
{
return Notice::Detached(params.reason)
}
Some(_) => {}
None => return Notice::Closed,
}
}
}
async fn detach(self) {
let _ = self
.connection
.client
.request::<SessionDetach>(&SessionDetachParams {
session: self.session,
})
.await;
}
}
pub(super) async fn transcript(reach: Reach, session: &SessionId) -> Result<String, ControlError> {
let mut attached = Attached::open(Connect::Reach(reach), session, None).await?;
let mut transcript = Transcript::default();
for _ in 0..attached.response.replay_events {
match attached.next().await {
Notice::Event(_, event) => transcript.push(&event),
Notice::Detached(_) => break,
Notice::Closed => return Err(rho_protocol::ClientError::Closed.into()),
}
}
attached.detach().await;
Ok(transcript.text())
}
pub(super) async fn wait(
reach: Reach,
session: SessionId,
after: Option<Cursor>,
timeout: Duration,
) -> Result<WaitResult, ControlError> {
let deadline = tokio::time::Instant::now() + timeout;
let mut follow = Follow::open(Connect::Reach(reach), session, after).await?;
let result = match tokio::time::timeout_at(deadline, follow.next()).await {
Err(_elapsed) => follow.now(),
Ok(Followed::News(result)) => result,
Ok(Followed::Ended(FollowEnd::Detached(_))) => return Ok(follow.now()),
Ok(Followed::Ended(FollowEnd::Closed)) => {
return Err(rho_protocol::ClientError::Closed.into())
}
};
follow.detach().await;
Ok(result)
}
pub(crate) struct Follow {
attached: Attached,
watch: Watch,
ended: Option<FollowEnd>,
progressed: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Followed {
News(WaitResult),
Ended(FollowEnd),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FollowEnd {
Detached(DetachReason),
Closed,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct NewsKey {
pub(crate) state: JobState,
#[serde(default)]
pub(crate) turn: Option<TurnId>,
#[serde(default)]
pub(crate) inputs: Vec<InputRequestId>,
}
impl NewsKey {
pub(crate) fn of(news: &WaitResult) -> Self {
Self {
state: news.state,
turn: news.turn.clone(),
inputs: news.inputs.iter().map(|open| open.id).collect(),
}
}
}
impl Follow {
pub(super) async fn open(
connect: Connect,
session: SessionId,
after: Option<Cursor>,
) -> Result<Self, ControlError> {
let mut attached = Attached::open(connect, &session, after.clone()).await?;
let response = &attached.response;
let resumed = after
.filter(|cursor| response.replay == Replay::Tail && cursor.stream == response.stream)
.map_or(Seq(0), |cursor| cursor.seq);
let mut watch = Watch {
session,
stream: response.stream.clone(),
seq: resumed,
state: response.state,
turn: response.turn.clone(),
ended: None,
inputs: response.inputs.clone(),
activity: None,
reported: None,
};
let mut ended = None;
for _ in 0..attached.response.replay_events {
match attached.next().await {
Notice::Event(seq, event) => watch.push(seq, &event),
Notice::Detached(reason) => {
ended = Some(FollowEnd::Detached(reason));
break;
}
Notice::Closed => {
ended = Some(FollowEnd::Closed);
break;
}
}
}
watch.finish_replay(attached.response.state, attached.response.turn.clone());
Ok(Self {
attached,
watch,
ended,
progressed: false,
})
}
pub(crate) fn now(&self) -> WaitResult {
self.watch.result()
}
pub(crate) async fn next(&mut self) -> Followed {
loop {
if let Some(news) = self.watch.news() {
return Followed::News(news);
}
if let Some(end) = self.ended {
return Followed::Ended(end);
}
match self.attached.next().await {
Notice::Event(seq, event) => {
self.progressed = true;
self.watch.push(seq, &event);
}
Notice::Detached(reason) => self.ended = Some(FollowEnd::Detached(reason)),
Notice::Closed => self.ended = Some(FollowEnd::Closed),
}
}
}
pub(crate) fn progressed(&self) -> bool {
self.progressed
}
pub(crate) async fn detach(self) {
if self.ended.is_none() {
self.attached.detach().await;
}
}
}
fn turn_runs(state: JobState) -> bool {
matches!(state, JobState::Running | JobState::Queued)
}
struct Watch {
session: SessionId,
stream: StreamId,
seq: Seq,
state: JobState,
turn: Option<TurnId>,
ended: Option<Ended>,
inputs: Vec<InputRequest>,
activity: Option<SessionActivity>,
reported: Option<NewsKey>,
}
#[derive(Clone)]
struct Ended {
turn: TurnId,
outcome: TurnOutcome,
before: Seq,
}
impl Watch {
fn finish_replay(&mut self, state: JobState, turn: Option<TurnId>) {
self.state = state;
self.turn = turn;
}
fn done(&self) -> bool {
match self.state {
JobState::WaitingForInput => true,
state if turn_runs(state) => false,
_ => self.activity.is_none_or(SessionActivity::is_settled) || !self.inputs.is_empty(),
}
}
fn news(&mut self) -> Option<WaitResult> {
if !self.done() {
self.reported = None;
return None;
}
let key = NewsKey {
state: self.state,
turn: self.turn.clone(),
inputs: self.inputs.iter().map(|open| open.id).collect(),
};
if self.reported.as_ref() == Some(&key) {
return None;
}
self.reported = Some(key);
Some(self.result())
}
fn push(&mut self, seq: Seq, event: &SessionEvent) {
let before = self.seq;
self.seq = self.seq.max(seq);
match event {
SessionEvent::State { state, turn } => {
self.state = *state;
self.turn.clone_from(turn);
}
SessionEvent::TurnEnded { turn, outcome } => {
self.ended = Some(Ended {
turn: turn.clone(),
outcome: outcome.clone(),
before,
});
}
SessionEvent::InputRequested { request } => {
if !self.inputs.iter().any(|open| open.id == request.id) {
self.inputs.push((**request).clone());
}
}
SessionEvent::InputResolved { id, .. } => self.inputs.retain(|open| open.id != *id),
SessionEvent::Activity { state } => self.activity = Some(*state),
_ => {}
}
}
fn result(&self) -> WaitResult {
let done = self.done();
let turn_over = !turn_runs(self.state) && self.state != JobState::WaitingForInput;
let end = self
.ended
.as_ref()
.filter(|end| Some(&end.turn) == self.turn.as_ref());
let checkpoint = match end {
Some(end) if !(done && turn_over) => end.before,
Some(_) | None => self.seq,
};
WaitResult {
session: self.session.clone(),
state: self.state,
done,
outcome: end.filter(|_| turn_over).map(|end| end.outcome.clone()),
turn: self.turn.clone(),
inputs: if done {
self.inputs.clone()
} else {
Vec::new()
},
cursor: (checkpoint > Seq(0)).then(|| {
format_cursor(&Cursor {
stream: self.stream.clone(),
seq: checkpoint,
})
}),
}
}
}
#[cfg(test)]
#[path = "follow_tests.rs"]
mod tests;