use std::{future::Future, time::Duration};
use rho_protocol::{DetachReason, JobState, SessionId};
use serde_json::{Map, Value};
use super::delivery::{verdict, Answer, RetrySchedule, Verdict};
use crate::app::{
mcp_server::webhooks::WebhookTarget,
session_control::{FollowEnd, Followed, NewsKey, WaitResult},
};
const MAX_REOPENS_WITHOUT_PROGRESS: u32 = 3;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Watching {
pub(super) session: SessionId,
pub(super) webhook: String,
pub(super) reported: Option<NewsKey>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum End {
Delivered,
Dropped(String),
Stalled(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Reconnect {
First,
Running,
Restarted,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Unfollowed {
UnknownSession,
Failed(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Denied {
Drop(String),
Stall(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Record<'a> {
Delivered { reported: &'a NewsKey, status: u16 },
Failed { error: &'a str },
}
pub(super) trait Ports: Send + Sync {
type Follow: FollowPort;
fn follow(
&self,
connect: Reconnect,
) -> impl Future<Output = Result<Self::Follow, Unfollowed>> + Send;
fn authorize(&self) -> impl Future<Output = Result<WebhookTarget, Denied>> + Send;
fn post(&self, target: &WebhookTarget, body: &Value) -> impl Future<Output = Answer> + Send;
fn sleep(&self, gap: Duration) -> impl Future<Output = ()> + Send;
fn record(&self, record: Record<'_>) -> impl Future<Output = ()> + Send;
}
pub(super) trait FollowPort: Send {
fn next(&mut self) -> impl Future<Output = Followed> + Send;
fn progressed(&self) -> bool;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum News {
Nothing,
Asks(NewsKey),
Settled(NewsKey),
}
impl News {
pub(super) fn of(news: &WaitResult) -> Self {
if !news.done {
return Self::Nothing;
}
match (news.inputs.is_empty(), news.state) {
(false, _) => Self::Asks(NewsKey::of(news)),
(true, JobState::WaitingForInput) => Self::Nothing,
(true, _) => Self::Settled(NewsKey::of(news)),
}
}
}
pub(super) fn body(server: &str, news: &WaitResult) -> Map<String, Value> {
let mut body = match serde_json::to_value(news) {
Ok(Value::Object(body)) => body,
_ => unreachable!("a wait result encodes as a JSON object"),
};
body.insert("server".to_owned(), Value::String(server.to_owned()));
body
}
pub(super) async fn run<P: Ports>(
ports: &P,
schedule: RetrySchedule,
server: &str,
mut watching: Watching,
) -> End {
let mut connect = Reconnect::First;
let mut stuck: u32 = 0;
loop {
let mut follow = match ports.follow(connect).await {
Ok(follow) => follow,
Err(Unfollowed::UnknownSession) => {
return End::Dropped(format!(
"no session {} is known to the rho daemon",
watching.session
))
}
Err(Unfollowed::Failed(error)) => {
return End::Stalled(format!(
"could not follow session {}: {error}",
watching.session
))
}
};
connect = loop {
let news = match follow.next().await {
Followed::News(news) => news,
Followed::Ended(FollowEnd::Detached(
reason @ (DetachReason::Lagged | DetachReason::NotLoaded),
)) => {
if follow.progressed() {
stuck = 0;
} else if stuck == MAX_REOPENS_WITHOUT_PROGRESS {
return End::Stalled(format!(
"the rho daemon ended {} follows in a row before they read anything new, the last {reason:?}; a watch reopens at most MAX_REOPENS_WITHOUT_PROGRESS ({MAX_REOPENS_WITHOUT_PROGRESS}) times without progress",
stuck + 1
));
} else {
stuck += 1;
}
break Reconnect::Running;
}
Followed::Ended(FollowEnd::Detached(DetachReason::Restarting)) => {
break Reconnect::Restarted
}
Followed::Ended(FollowEnd::Detached(DetachReason::Deleted)) => {
return End::Dropped(format!("session {} was deleted", watching.session))
}
Followed::Ended(FollowEnd::Detached(DetachReason::DaemonStopping)) => {
return End::Stalled("the rho daemon stopped".to_owned())
}
Followed::Ended(FollowEnd::Detached(reason)) => {
return End::Stalled(format!("the rho daemon ended the follow ({reason:?})"))
}
Followed::Ended(FollowEnd::Closed) => {
return End::Stalled("the connection to the rho daemon closed".to_owned())
}
};
let (about, settled) = match News::of(&news) {
News::Nothing => continue,
News::Asks(about) => (about, false),
News::Settled(about) => (about, true),
};
if watching.reported.as_ref() != Some(&about) {
match deliver(ports, schedule, server, &watching.webhook, &news).await {
Ok(status) => {
ports
.record(Record::Delivered {
reported: &about,
status,
})
.await;
}
Err(end) => return end,
}
watching.reported = Some(about);
}
if settled {
return End::Delivered;
}
};
}
}
async fn deliver<P: Ports>(
ports: &P,
schedule: RetrySchedule,
server: &str,
webhook: &str,
news: &WaitResult,
) -> Result<u16, End> {
let body = Value::Object(body(server, news));
let mut gaps = schedule.gaps();
let mut attempts: u32 = 0;
let mut waited = Duration::ZERO;
let error = loop {
let target = match ports.authorize().await {
Ok(target) => target,
Err(Denied::Drop(why)) => return Err(End::Dropped(why)),
Err(Denied::Stall(why)) => return Err(End::Stalled(why)),
};
attempts += 1;
let answer = ports.post(&target, &body).await;
match verdict(&answer) {
Verdict::Delivered(status) => return Ok(status),
Verdict::Retry => match gaps.next() {
Some(gap) => {
ports.sleep(gap).await;
waited += gap;
}
None => {
break format!(
"webhook {webhook:?} not delivered after {attempts} attempts, {} min of retry gaps between them: last {answer}",
waited.as_secs() / 60
)
}
},
Verdict::Stall => break format!("webhook {webhook:?} refused delivery: {answer}"),
}
};
tracing::error!(session = %news.session, %error, "could not deliver a watched session's news");
ports.record(Record::Failed { error: &error }).await;
Err(End::Stalled(error))
}
#[cfg(test)]
#[path = "watcher_tests.rs"]
mod tests;