use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs as std_fs;
use std::path::PathBuf;
use tokio::fs;
use crate::sys::home;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookStatus {
pub configured: bool,
pub port: Option<u16>,
pub healthy: bool,
pub fallback_mode: bool,
pub last_check_utc: Option<DateTime<Utc>>,
pub last_failure_reason: Option<String>,
pub startup_attempts: u32,
}
impl Default for WebhookStatus {
fn default() -> Self {
Self {
configured: false,
port: None,
healthy: false,
fallback_mode: true,
last_check_utc: None,
last_failure_reason: None,
startup_attempts: 0,
}
}
}
pub fn status_path() -> anyhow::Result<PathBuf> {
Ok(home::orch_home()?.join("webhook_status.json"))
}
impl WebhookStatus {
pub async fn save(&self) {
match status_path().and_then(|p| {
serde_json::to_string_pretty(self)
.map(|j| (p, j))
.map_err(anyhow::Error::from)
}) {
Ok((p, json)) => {
if let Err(e) = fs::write(&p, json).await {
tracing::warn!(error = ?e, "failed to persist webhook status");
}
}
Err(e) => tracing::warn!(?e, "failed to persist webhook status"),
}
}
pub fn load() -> Option<Self> {
let path = status_path().ok()?;
let json = std_fs::read_to_string(path).ok()?;
serde_json::from_str(&json).ok()
}
}