use std::{
collections::BTreeMap,
fs::{self, File, OpenOptions},
io,
path::PathBuf,
sync::{Arc, Mutex, PoisonError},
};
use anyhow::Context;
use fs2::FileExt;
use rho_protocol::SessionId;
use serde::{Deserialize, Serialize};
use crate::{
app::session_control::NewsKey,
config_writer::{write_bytes_atomically_with_durability, WriteDurability},
};
pub(crate) const DIR: &str = "mcp-serve";
const FILE: &str = "watches.json";
const LOCK: &str = "watches.lock";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct WatchFile {
#[serde(default)]
pub(crate) watches: Vec<WatchRecord>,
#[serde(default)]
pub(crate) deliveries: BTreeMap<String, DeliveryRecord>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) max_watches: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct WatchRecord {
pub(crate) session: SessionId,
pub(crate) token: String,
pub(crate) webhook: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) server: Option<String>,
#[serde(default)]
pub(crate) reported: Option<NewsKey>,
#[serde(default)]
pub(crate) error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DeliveryRecord {
pub(crate) at: u64,
pub(crate) session: SessionId,
pub(crate) result: DeliveryResult,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum DeliveryResult {
Delivered(u16),
Failed(String),
}
#[derive(Clone, Debug)]
pub(crate) struct WatchStore {
dir: PathBuf,
}
impl WatchStore {
pub(crate) fn new(dir: PathBuf) -> Self {
Self { dir }
}
pub(crate) fn path(&self) -> PathBuf {
self.dir.join(FILE)
}
pub(crate) fn lock_path(&self) -> PathBuf {
self.dir.join(LOCK)
}
pub(crate) fn lock(&self) -> anyhow::Result<Option<File>> {
crate::daemon::create_private_dir(&self.dir)
.with_context(|| format!("could not create {}", self.dir.display()))?;
let path = self.lock_path();
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.with_context(|| format!("could not open {}", path.display()))?;
match FileExt::try_lock_exclusive(&file) {
Ok(()) => Ok(Some(file)),
Err(error)
if error.kind() == io::ErrorKind::WouldBlock
|| error.raw_os_error() == fs2::lock_contended_error().raw_os_error() =>
{
Ok(None)
}
Err(error) => Err(error).with_context(|| format!("could not lock {}", path.display())),
}
}
pub(crate) fn load(&self) -> anyhow::Result<WatchFile> {
let path = self.path();
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Ok(WatchFile::default())
}
Err(error) => {
return Err(error).with_context(|| format!("could not read {}", path.display()))
}
};
serde_json::from_str(&text).with_context(|| {
format!(
"{} does not parse; fix or remove it to start the server",
path.display()
)
})
}
pub(crate) fn save(&self, file: &WatchFile) -> anyhow::Result<()> {
let path = self.path();
let mut contents = serde_json::to_vec_pretty(file)?;
contents.push(b'\n');
write_bytes_atomically_with_durability(&path, &contents, WriteDurability::Durable)
.and_then(|()| crate::daemon::sync_dir(&self.dir))
.with_context(|| format!("could not save {}", path.display()))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Snapshot {
pub(super) seq: u64,
pub(super) file: WatchFile,
}
#[derive(Debug)]
pub(super) struct Writer {
store: WatchStore,
written: Mutex<u64>,
}
impl Writer {
pub(super) fn new(store: WatchStore) -> Arc<Self> {
Arc::new(Self {
store,
written: Mutex::new(0),
})
}
pub(super) async fn write(self: &Arc<Self>, snapshot: Snapshot) -> anyhow::Result<()> {
let writer = Arc::clone(self);
tokio::task::spawn_blocking(move || writer.write_now(&snapshot))
.await
.context("the webhook watch store's writer stopped")?
}
pub(super) fn write_now(&self, snapshot: &Snapshot) -> anyhow::Result<()> {
let mut written = self.written.lock().unwrap_or_else(PoisonError::into_inner);
if *written >= snapshot.seq {
return Ok(());
}
self.store.save(&snapshot.file)?;
*written = snapshot.seq;
Ok(())
}
}
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;