1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//! The event streams of the Rho subagent and workflow agent node runs the
//! daemon's sessions start (#1668), so a client follows a run as it
//! follows a session: by observing the session the run writes.
//!
//! A run's stream is a [`Feed`] like a loaded session's, with one turn: the
//! run. It opens when the run opens its session, which may be long after
//! the run started, while it waits for capacity; an observe meanwhile is
//! refused as any other of a session a job writes, and the client asks
//! again. The stream carries the run's events as its child sends them,
//! the run's job states, and how the run ended, then closes. Nobody
//! attaches to it to prompt, steer, or answer: a run's questions go to its
//! parent session.
use std::{
collections::HashMap,
path::PathBuf,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::{
self as wire, Cursor, DetachReason, SessionAttachResponse, Subscription, TurnOutcome,
};
use rho_sdk::SessionId;
use tokio::sync::watch;
use super::{attach_response, feed::Feed};
use crate::app::daemon_host::jobs::JobState;
/// The streams of the runs under way, by the session each writes.
#[derive(Clone, Default)]
pub(in crate::app::daemon_host) struct ChildFeeds {
runs: Arc<Mutex<HashMap<SessionId, Listed>>>,
}
/// One run's stream as an observe finds it.
#[derive(Clone)]
struct Listed {
workspace: PathBuf,
/// The run's feed, once the run opened its session.
feed: watch::Receiver<Option<Arc<Feed>>>,
}
impl ChildFeeds {
/// Lists the stream of a run about to write `session` in `workspace`,
/// whose job is in `state`. The stream is listed until the returned
/// [`ChildStream`] drops.
pub(in crate::app::daemon_host) fn list(
&self,
session: SessionId,
workspace: PathBuf,
state: &JobState,
) -> ChildStream {
let (feed, listed) = watch::channel(None);
self.runs().insert(
session.clone(),
Listed {
workspace,
feed: listed,
},
);
ChildStream {
feeds: self.clone(),
session,
turn: wire::TurnId::new(uuid::Uuid::new_v4().hyphenated().to_string()),
state: state.into(),
feed,
}
}
/// Subscribes a client to the stream of the run writing `session`,
/// resuming after its cursor when the stream still can. `None` when no
/// run under way writes `session`, or the run has not opened it yet: an
/// observe never waits on a run, which may be queued for long.
pub(super) fn attach(
&self,
session: &SessionId,
after: Option<&Cursor>,
) -> Option<(SessionAttachResponse, Subscription)> {
let listed = self.runs().get(session)?.clone();
let feed = listed.feed.borrow().clone()?;
Some(attach_response(&listed.workspace, feed.attach(after)))
}
/// What `rho/job/list` reports of the run writing `session` from its
/// stream; `None` when no run under way writes it, or the run has not
/// opened it yet.
pub(in crate::app::daemon_host) fn live(&self, session: &SessionId) -> Option<wire::JobLive> {
let listed = self.runs().get(session)?.clone();
let feed = listed.feed.borrow().clone()?;
Some(feed.live())
}
fn runs(&self) -> MutexGuard<'_, HashMap<SessionId, Listed>> {
// Entries are only inserted and removed whole.
self.runs.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// One run's stream, as the task that follows the run writes it. Dropping
/// it closes the stream and takes it off the list.
pub(in crate::app::daemon_host) struct ChildStream {
feeds: ChildFeeds,
session: SessionId,
/// The stream's one turn: the run.
turn: wire::TurnId,
/// Where the run's job is, which the feed opens in.
state: wire::JobState,
feed: watch::Sender<Option<Arc<Feed>>>,
}
impl ChildStream {
/// Opens the stream: the run opened its session, which runs with
/// `options` as agent `agent`.
pub(in crate::app::daemon_host) fn open(&self, options: wire::SessionOptions, agent: String) {
self.feed.send_if_modified(|feed| {
if feed.is_some() {
return false;
}
*feed = Some(Arc::new(Feed::new(
self.state,
Some(self.turn.clone()),
/*title*/ None,
options,
agent,
)));
true
});
}
/// Sends `events` to the clients following the run. A run sends none
/// before it opens its session.
pub(in crate::app::daemon_host) fn publish(
&self,
events: impl IntoIterator<Item = wire::SessionEvent>,
) {
if let Some(feed) = self.feed.borrow().as_ref() {
feed.publish(events);
}
}
/// Tells the clients following the run that its job is now in `state`.
pub(in crate::app::daemon_host) fn moved(&mut self, state: &JobState) {
self.state = state.into();
self.publish([self.state_event()]);
}
/// Ends the run's turn as `outcome`, if it has one to tell, with its
/// job in `state`, in one publish, as a session's turn ends.
pub(in crate::app::daemon_host) fn end(
&mut self,
outcome: Option<TurnOutcome>,
state: &JobState,
) {
self.state = state.into();
let ended = outcome.map(|outcome| wire::SessionEvent::TurnEnded {
turn: self.turn.clone(),
outcome,
});
self.publish(ended.into_iter().chain([self.state_event()]));
}
/// Tells the clients following the run its title is `title`, unless
/// they know.
pub(in crate::app::daemon_host) fn titled(&self, title: &str) {
if let Some(feed) = self.feed.borrow().as_ref() {
if feed.title().as_deref() != Some(title) {
feed.publish([wire::SessionEvent::TitleChanged {
title: title.to_owned(),
}]);
}
}
}
/// Detaches the clients following the run with `reason`, instead of
/// the [`DetachReason::NotLoaded`] a dropped stream closes with.
pub(in crate::app::daemon_host) fn close(&self, reason: DetachReason) {
if let Some(feed) = self.feed.borrow().as_ref() {
feed.close(reason);
}
}
fn state_event(&self) -> wire::SessionEvent {
wire::SessionEvent::State {
state: self.state,
turn: Some(self.turn.clone()),
}
}
}
impl Drop for ChildStream {
fn drop(&mut self) {
// The run's session is saved and no longer written: an observe
// reads it from its file from here on.
self.close(DetachReason::NotLoaded);
let mut runs = self.feeds.runs();
// A workflow node that runs again writes the same session, and may
// have listed its stream already.
if runs
.get(&self.session)
.is_some_and(|listed| listed.feed.same_channel(&self.feed.subscribe()))
{
runs.remove(&self.session);
}
}
}