use std::{future::Future, time::Duration};
use rho_protocol::SessionId;
use super::{delivery::RetrySchedule, watcher::Denied};
use crate::{
app::{
mcp_server::{
remotes::{self, Asked, Lasts, RemoteError, RemoteSet},
token_store,
},
session_control::{NewsKey, WaitResult, MAX_WAIT_SECS},
},
caller_context::CallerContext,
};
const IDLE_POLL: Duration = Duration::from_secs(10);
pub(super) const REACH_RETRY: RetrySchedule = RetrySchedule {
first_gap: Duration::from_secs(2),
max_gap: Duration::from_secs(60),
horizon: Duration::from_secs(60 * 60),
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum WaitFailed {
Again(String),
Ended(String),
}
impl From<RemoteError> for WaitFailed {
fn from(error: RemoteError) -> Self {
match error {
RemoteError::Unreachable { .. }
| RemoteError::Refused { .. }
| RemoteError::Failed {
lasts: Lasts::ForNow,
..
} => Self::Again(error.to_string()),
RemoteError::Failed {
lasts: Lasts::ForGood,
..
} => Self::Ended(error.to_string()),
}
}
}
pub(super) trait RemoteWaits: Send + Sync {
fn wait(
&self,
cursor: Option<&str>,
) -> impl Future<Output = Result<WaitResult, WaitFailed>> + Send;
fn sleep(&self, gap: Duration) -> impl Future<Output = ()> + Send;
}
pub(super) struct RemoteFollow<W> {
waits: W,
schedule: RetrySchedule,
cursor: Option<String>,
reported: Option<NewsKey>,
}
impl<W: RemoteWaits> RemoteFollow<W> {
pub(super) fn new(waits: W, schedule: RetrySchedule) -> Self {
Self {
waits,
schedule,
cursor: None,
reported: None,
}
}
pub(super) async fn next(&mut self) -> Result<WaitResult, Denied> {
let mut gaps = self.schedule.gaps();
let mut attempts: u32 = 0;
loop {
attempts += 1;
let news = match self.waits.wait(self.cursor.as_deref()).await {
Ok(news) => news,
Err(WaitFailed::Again(why)) => match gaps.next() {
Some(gap) => {
self.waits.sleep(gap).await;
continue;
}
None => return Err(Denied::Stall(format!("{why}, after {attempts} attempts"))),
},
Err(WaitFailed::Ended(why)) => return Err(Denied::Drop(why)),
};
gaps = self.schedule.gaps();
attempts = 0;
let moved = news.cursor.is_some() && news.cursor != self.cursor;
if moved {
self.cursor.clone_from(&news.cursor);
}
if !news.done {
self.reported = None;
if !moved {
self.waits.sleep(IDLE_POLL).await;
}
continue;
}
let key = NewsKey::of(&news);
if self.reported.as_ref() == Some(&key) {
self.waits.sleep(IDLE_POLL).await;
continue;
}
self.reported = Some(key);
return Ok(news);
}
}
}
pub(super) struct ServerWaits {
pub(super) server: String,
pub(super) session: SessionId,
}
impl RemoteWaits for ServerWaits {
async fn wait(&self, cursor: Option<&str>) -> Result<WaitResult, WaitFailed> {
let remotes = token_store::load_fresh::<RemoteSet>()
.await
.map_err(|error| WaitFailed::Again(format!("{error:#}")))?;
let remote = remotes.require(&self.server).map_err(WaitFailed::Ended)?;
remotes::wait(
remote,
&self.session,
MAX_WAIT_SECS,
cursor,
&CallerContext::ROOT,
Asked::ByWatch,
)
.await
.map_err(WaitFailed::from)
}
async fn sleep(&self, gap: Duration) {
tokio::time::sleep(gap).await;
}
}
#[cfg(test)]
#[path = "remote_follow_tests.rs"]
mod tests;