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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! Session marks over the socket (`rho/session/mark`), and the one the
//! daemon sets itself: a session is marked done when the last of the pull
//! requests linked to it merges, watched or not. For a session in a
//! worktree of its own, the pull request of its branch is one once a lookup
//! found it open (see `crate::app::pull_requests`' poller).
//!
//! A mark is saved with the session, beside its title (see
//! `crate::session`'s `mark`), so it needs no loaded session, and
//! `rho/session/list_detailed` reports it. A change tells a loaded session's
//! attached clients, as a rename does.
//!
//! Only the daemon reads a session's linked pull requests with no one
//! asking. The session is marked done at once, as the poll that read the
//! last merge ends ([`Sessions::mark_merged_done`]), which stands while
//! no turn follows; a daemon that stops between the read and the mark
//! never makes it. When the pull request was watched, a turn then tells
//! the agent of the merge, and the session is marked again as that turn
//! ends ([`turn_ended`]): its saves moved the session's `updated_at` past
//! the first mark, and clients read a session as done only while
//! `updated_at` is not after it. A prompt the person sends later moves
//! `updated_at` past the mark again, which clients read as active; the
//! mark stays, and the turn of such a prompt marks nothing, also when it
//! is the one to tell the agent news that waited.
//!
//! A merge that leaves another linked pull request unmerged, open or
//! closed, marks nothing either time: the session's work is not over, and
//! a session marked done by mistake is hidden, which is worse than one
//! left listed. The one exception is a pull request the daemon linked for
//! the session's branch that closed without merging, which the branch's
//! next pull request replaces. Neither does a pull request first read after it merged,
//! as one linked for reference. Nor does a merge while a job the session
//! started is still queued, running, or waiting for input, as a session
//! it started for a pull request not yet opened, or one it starts in the
//! turn that tells it of the merge: that work is the session's too.
//! Nothing marks the session when that job ends; it stays listed until
//! the person or a later merge settles it. Past that, [`after_merge`] is
//! the whole rule.
use rho_protocol::{self as wire, ErrorCode, RpcError};
use rho_sdk::SessionId;
use super::{
reopen::{not_found, parse_session},
store::store_blocking,
LoadedSession, Sessions,
};
use crate::{
app::{
pull_requests::{AllMerged, PullRequestInbox},
session_runtime::SessionRuntime,
},
session::{MarkChange, NewMark, Session as StoredSession, SessionMark},
};
impl Sessions {
/// Saves or clears a session's mark, then tells the clients attached
/// to it, if the daemon has it loaded.
pub(in crate::app::daemon_host) async fn mark(
&self,
params: wire::SessionMarkParams,
) -> Result<wire::SessionMarkResponse, RpcError> {
let id = parse_session(¶ms.session)?;
let asked = params.mark.map(new_mark).transpose()?;
let change = self
.change_saved_mark(&id, move |_, now| asked.map(|mark| mark.at(now)))
.await?
.ok_or_else(|| not_found(&id))?;
self.tell_mark(&id, change);
Ok(wire::SessionMarkResponse::new(
change.after.map(mark_to_wire),
))
}
/// Marks done each session whose linked pull requests have all merged,
/// as [`after_merge`] says, until the daemon starts stopping: a merge
/// it read before that is marked first. Not a session that started a
/// job still in progress, which nothing marks once that job ends.
pub(super) async fn mark_merged_done(&self) {
let Some(mut merged) = self.pull_requests.service().take_all_merged() else {
return;
};
loop {
let AllMerged { session, at } = tokio::select! {
biased;
Some(merged) = merged.recv() => merged,
() = self.stopping.cancelled() => return,
else => return,
};
if self.jobs.session_started_in_progress(&session) {
continue;
}
let merged_at = at / 1000;
let change = self
.change_saved_mark(&session, move |mark, now| after_merge(mark, merged_at, now));
match change.await {
Ok(Some(change)) => self.tell_mark(&session, change),
// Deleted since, or it never saved a turn.
Ok(None) => {}
Err(error) => tracing::warn!(
%session,
%error,
"could not mark a session done for its merged pull request"
),
}
}
}
/// Replaces the mark of the session saved under `id`, loaded or not,
/// with what `change` makes of the one it has and of the time now on
/// the session store's clock; `None` when nothing is saved under `id`.
async fn change_saved_mark(
&self,
id: &SessionId,
change: impl FnOnce(Option<SessionMark>, u64) -> Option<SessionMark> + Send + 'static,
) -> Result<Option<MarkChange>, RpcError> {
let (rho_home, id) = (self.rho_home.clone(), id.clone());
store_blocking("save the session's mark", move || {
StoredSession::change_mark_of(&rho_home, id.as_str(), change)
})
.await
}
/// Tells the clients attached to session `id`, if it is loaded, the
/// mark `change` left, if it changed it.
fn tell_mark(&self, id: &SessionId, change: MarkChange) {
let loaded = self.loaded().get(id).cloned();
if let Some(session) = loaded {
tell_mark(&session, change);
}
}
}
/// What started a turn, which decides whether its end marks the session
/// (see [`turn_ended`]).
#[derive(Clone, Copy)]
pub(super) enum TurnOrigin {
/// The daemon, to tell the agent what waited for it.
Daemon,
/// A prompt sent at `at`, in unix milliseconds.
Prompt { at: u64 },
}
/// Call as `session`'s turn on `runtime`, which `origin` started, ended,
/// after its last save and before its end is told. A turn that told the
/// agent a watched pull request merged, and leaves the session with every
/// linked pull request merged, marks it done again, as [`after_merge`]
/// says: at or after the `updated_at` the turn leaves, so clients read the
/// session as done once the turn is over. Not the turn of a prompt sent
/// since rho found the merge, as when the news waited for one: the person
/// turned to the session again, so it stays active. Nor one that leaves a
/// job the session started still in progress, as one the turn started on
/// hearing of the merge; nothing marks the session once that job ends.
pub(super) fn turn_ended(session: &LoadedSession, runtime: &SessionRuntime, origin: TurnOrigin) {
let told = runtime
.tools()
.pull_requests()
.and_then(PullRequestInbox::take_merge_told);
let Some(merged_at) = told else {
return;
};
match origin {
TurnOrigin::Daemon => {}
// The merge came while the prompt's turn ran.
TurnOrigin::Prompt { at } if at <= merged_at => {}
TurnOrigin::Prompt { .. } => return,
}
if session.jobs.session_started_in_progress(&session.id) {
return;
}
let merged_at = merged_at / 1000;
match runtime.change_mark(|mark, now| after_merge(mark, merged_at, now)) {
Ok(Some(change)) => tell_mark(session, change),
// It keeps no file.
Ok(None) => {}
Err(error) => tracing::warn!(
session = %session.id,
error = format!("{error:#}"),
"could not mark a session done after the turn that told of its merged pull request"
),
}
}
/// The mark of a session whose last unmerged pull request rho found merged at
/// `merged_at`, as of `now`, both unix seconds, given the `mark` it has:
/// done as of `now`, unless the person set it apart. A pinned session
/// stays pinned, and a snoozed one snoozed until its snooze ends. One the
/// person put back on the active list since the merge stays there, so the
/// second marking, at the end of the turn that tells the agent, does not
/// undo a restore made while that turn ran.
fn after_merge(mark: Option<SessionMark>, merged_at: u64, now: u64) -> Option<SessionMark> {
match mark {
Some(SessionMark::Pinned { .. }) => mark,
Some(SessionMark::Snoozed { until }) if until > now => mark,
Some(SessionMark::Kept { at }) if at >= merged_at => mark,
None
| Some(SessionMark::Done { .. } | SessionMark::Snoozed { .. } | SessionMark::Kept { .. }) => {
Some(SessionMark::Done { at: now })
}
}
}
/// Tells `session`'s attached clients the mark `change` left, if it
/// changed it.
fn tell_mark(session: &LoadedSession, change: MarkChange) {
if change.before != change.after {
session.feed.publish([wire::SessionEvent::MarkChanged {
mark: change.after.map(mark_to_wire),
}]);
}
}
/// The mark `rho/session/mark` asks for, which the store stamps.
fn new_mark(mark: wire::NewSessionMark) -> Result<NewMark, RpcError> {
match mark {
wire::NewSessionMark::Done => Ok(NewMark::Done),
wire::NewSessionMark::Snoozed { until } => Ok(NewMark::Snoozed { until }),
wire::NewSessionMark::Pinned => Ok(NewMark::Pinned),
wire::NewSessionMark::Kept => Ok(NewMark::Kept),
// Unreachable: this build's protocol crate decoded it, so it knows
// every kind; the enum is non-exhaustive for clients.
_ => Err(RpcError::new(
ErrorCode::InvalidParams,
"this daemon does not know that kind of mark",
)),
}
}
/// `mark` as `rho/session/list_detailed` and `mark_changed` send it.
pub(super) fn mark_to_wire(mark: SessionMark) -> wire::SessionMark {
match mark {
SessionMark::Done { at } => wire::SessionMark::Done { at },
SessionMark::Snoozed { until } => wire::SessionMark::Snoozed { until },
SessionMark::Pinned { at } => wire::SessionMark::Pinned { at },
SessionMark::Kept { at } => wire::SessionMark::Kept { at },
}
}
#[cfg(test)]
#[path = "marks_tests.rs"]
mod tests;