use std::{
collections::HashMap,
fs::File,
path::PathBuf,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::SessionId;
use serde_json::{Map, Value};
use tokio::task::AbortHandle;
use super::webhooks::{Unbound, WebhookSet};
use crate::{
app::session_control::{
parse_arguments, Action, Caller, ControlError, DaemonUse, Holder, SessionControl,
},
credential_store::UntrackedCredentialStore,
};
mod book;
mod delivery;
mod ports;
mod store;
mod tools;
mod watcher;
use book::{Key, OverBudget, Slot, Start, WatchBook, Watched};
use delivery::{HttpPoster, RetrySchedule};
use ports::ServerPorts;
pub(crate) use store::{DeliveryRecord, DeliveryResult, WatchFile, WatchStore, DIR};
use store::{Snapshot, Writer};
use tools::{take_notify, UnwatchParams, WatchParams, UNWATCH, WATCH};
pub(crate) use tools::{tools as watch_tools, with_notify, HttpTool};
pub(crate) fn default_max_watches(max_sessions: u32) -> u32 {
max_sessions.saturating_mul(WATCHES_PER_SESSION)
}
const WATCHES_PER_SESSION: u32 = 5;
const NOT_SAVED: &str = "the server could not save its webhook watches, so a restart of the \
server will not keep this change; the server's log says why";
#[derive(Debug, thiserror::Error)]
pub(crate) enum WatchError {
#[error(transparent)]
Control(#[from] ControlError),
#[error(transparent)]
Unbound(#[from] Unbound),
#[error(transparent)]
Budget(#[from] OverBudget),
#[error(
"this server keeps no webhook watches: another `rho mcp serve --http` on this rho home keeps them"
)]
Off,
#[error("{0}")]
Failed(String),
}
#[derive(Clone)]
pub(crate) enum WatchMode {
On(Arc<Watches>),
Off,
}
impl WatchMode {
pub(crate) async fn call(
&self,
control: &SessionControl,
caller: &Caller,
tool: HttpTool,
mut arguments: Map<String, Value>,
) -> Result<Value, WatchError> {
match self {
Self::On(watches) => watches.call(caller, tool, arguments).await,
Self::Off => match tool {
HttpTool::Watch | HttpTool::Unwatch => Err(WatchError::Off),
HttpTool::Core(action) => match take_notify(action, &mut arguments)? {
Some(_) => Err(WatchError::Off),
None => Ok(control.call(caller, action, arguments).await?),
},
},
}
}
}
pub(crate) struct Watches {
control: Arc<SessionControl>,
server: String,
schedule: RetrySchedule,
poster: HttpPoster,
writer: Arc<Writer>,
state: Mutex<State>,
}
struct State {
book: WatchBook,
tasks: HashMap<Key, AbortHandle>,
_lock: File,
}
impl State {
fn abort(&mut self, key: &Key) {
if let Some(task) = self.tasks.remove(key) {
task.abort();
}
}
}
impl Watches {
pub(crate) fn open(
control: Arc<SessionControl>,
server: String,
max_watches: u32,
dir: PathBuf,
) -> anyhow::Result<WatchMode> {
let store = WatchStore::new(dir);
let Some(held) = store.lock()? else {
tracing::warn!(
lock = %store.lock_path().display(),
"another rho mcp serve --http keeps this rho home's webhook watches; this one refuses watch and notify"
);
return Ok(WatchMode::Off);
};
let writer = Writer::new(store.clone());
let (mut book, starts) = WatchBook::resume(store.load()?, max_watches);
writer.write_now(&book.snapshot())?;
let watches = Arc::new(Self {
control,
server,
schedule: RetrySchedule::DEFAULT,
poster: HttpPoster::new()?,
writer,
state: Mutex::new(State {
book,
tasks: HashMap::new(),
_lock: held,
}),
});
{
let mut state = lock(&watches.state);
for start in starts {
watches.spawn(&mut state, start);
}
}
Ok(WatchMode::On(watches))
}
pub(crate) fn instructions(&self) -> String {
format!(
"This server is {:?}. `watch`, or `notify` on `new` and `prompt`, has it POST a \
session's news to a webhook, naming the server as `server`: when the session \
waits for a person, and once when it settles, which ends the watch.",
self.server
)
}
pub(crate) async fn call(
self: &Arc<Self>,
caller: &Caller,
tool: HttpTool,
mut arguments: Map<String, Value>,
) -> Result<Value, WatchError> {
match tool {
HttpTool::Watch => self.watch(caller, parse_arguments(WATCH, arguments)?).await,
HttpTool::Unwatch => {
self.unwatch(caller, parse_arguments(UNWATCH, arguments)?)
.await
}
HttpTool::Core(action) => match take_notify(action, &mut arguments)? {
Some(webhook) => self.notify(caller, action, arguments, webhook).await,
None => Ok(self.control.call(caller, action, arguments).await?),
},
}
}
async fn watch(
self: &Arc<Self>,
caller: &Caller,
params: WatchParams,
) -> Result<Value, WatchError> {
let token = token_of(caller)?;
self.control
.check_follow(caller, ¶ms.session, DaemonUse::Call)
.await?;
load_webhooks().await?.for_token(token, ¶ms.webhook)?;
let key = (token.to_owned(), params.session);
let read = lock(&self.state).book.revision(&key);
let now = self.control.now(&key.1).await?;
let (watching, snapshot) = {
let mut state = lock(&self.state);
match state.book.watch(token, params.webhook, &now, read)? {
Watched::Unchanged { watching } => (watching, None),
Watched::Removed => {
state.abort(&key);
(false, Some(state.book.snapshot()))
}
Watched::Started(start) => {
self.spawn(&mut state, start);
(true, Some(state.book.snapshot()))
}
}
};
let mut result = watcher::body(&self.server, &now);
result.insert("watching".to_owned(), Value::Bool(watching));
if let Some(snapshot) = snapshot {
self.save_into(snapshot, &mut result).await;
}
Ok(Value::Object(result))
}
async fn unwatch(&self, caller: &Caller, params: UnwatchParams) -> Result<Value, WatchError> {
let token = token_of(caller)?;
let mut result = Map::new();
result.insert("watching".to_owned(), Value::Bool(false));
let snapshot = {
let mut state = lock(&self.state);
let key = (token.to_owned(), params.session);
state.abort(&key);
state.book.remove(&key).then(|| state.book.snapshot())
};
if let Some(snapshot) = snapshot {
self.save_into(snapshot, &mut result).await;
}
Ok(Value::Object(result))
}
async fn notify(
self: &Arc<Self>,
caller: &Caller,
action: Action,
arguments: Map<String, Value>,
webhook: String,
) -> Result<Value, WatchError> {
let token = token_of(caller)?;
load_webhooks().await?.for_token(token, &webhook)?;
let prompted = arguments
.get("session")
.and_then(Value::as_str)
.filter(|_| action == Action::Prompt)
.map(SessionId::new);
let reservation = Reservation::hold(&self.state, token, prompted.as_ref())?;
let mut result = match self.control.call(caller, action, arguments).await? {
Value::Object(result) => result,
other => return Ok(other),
};
let session = result
.get("session")
.and_then(Value::as_str)
.map(SessionId::new);
let Some(session) = session else {
tracing::error!(
action = action.name(),
"the core's result named no session, so nothing is watched"
);
result.insert("watching".to_owned(), Value::Bool(false));
result.insert(
"watch_error".to_owned(),
Value::String(format!("`{}` named no session to watch", action.name())),
);
return Ok(Value::Object(result));
};
let snapshot = {
let mut state = lock(&self.state);
let start = state.book.notify(reservation.take(), session, webhook);
self.spawn(&mut state, start);
state.book.snapshot()
};
result.insert("watching".to_owned(), Value::Bool(true));
self.save_into(snapshot, &mut result).await;
Ok(Value::Object(result))
}
fn spawn(self: &Arc<Self>, state: &mut State, start: Start) {
let Start {
key,
generation,
watching,
} = start;
state.abort(&key);
let ports = ServerPorts {
watches: Arc::clone(self),
key: key.clone(),
webhook: watching.webhook.clone(),
generation,
};
let task = tokio::spawn(async move {
let watches = &ports.watches;
let end = watcher::run(&ports, watches.schedule, &watches.server, watching).await;
ports.finish(end).await;
});
state.tasks.insert(key, task.abort_handle());
}
async fn save(&self, snapshot: Snapshot) -> bool {
match self.writer.write(snapshot).await {
Ok(()) => true,
Err(error) => {
tracing::error!(error = %format!("{error:#}"), "could not save the webhook watches");
false
}
}
}
async fn save_into(&self, snapshot: Snapshot, result: &mut Map<String, Value>) {
if !self.save(snapshot).await {
result.insert(
"watch_error".to_owned(),
Value::String(NOT_SAVED.to_owned()),
);
}
}
}
struct Reservation<'a> {
state: &'a Mutex<State>,
slot: Option<Slot>,
}
impl<'a> Reservation<'a> {
fn hold(
state: &'a Mutex<State>,
token: &str,
session: Option<&SessionId>,
) -> Result<Self, OverBudget> {
let slot = lock(state).book.reserve(token, session)?;
Ok(Self {
state,
slot: Some(slot),
})
}
fn take(mut self) -> Slot {
self.slot
.take()
.expect("a reservation holds its slot until taken")
}
}
impl Drop for Reservation<'_> {
fn drop(&mut self) {
if let Some(slot) = self.slot.take() {
lock(self.state).book.release(slot);
}
}
}
fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn token_of(caller: &Caller) -> Result<&str, WatchError> {
match &caller.grant.holder {
Holder::Token(name) => Ok(name),
Holder::Local | Holder::Session(_) => Err(WatchError::Failed(
"webhook watches are for HTTP tokens".to_owned(),
)),
}
}
async fn load_webhooks() -> Result<WebhookSet, WatchError> {
let loaded =
match tokio::task::spawn_blocking(|| WebhookSet::load(&UntrackedCredentialStore)).await {
Ok(loaded) => loaded,
Err(error) => Err(error.into()),
};
loaded.map_err(|error| {
tracing::error!(error = %format!("{error:#}"), "could not read the webhook targets");
WatchError::Failed(
"the server could not read its webhook targets; the server's log says why".to_owned(),
)
})
}