use core::time::Duration;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::sync::watch;
use shep_core::paths::ShepPaths;
use shep_core::permissions::Grants;
use shep_core::protocol::Reply;
use super::PtyStream;
use crate::bus::{Bus, TopicFilter};
use crate::host::HostState;
use crate::limits::stats::StatsState;
use crate::secrets::ProviderSecrets;
use crate::snapshot::{FlockRegistry, SnapshotError, write_atomic};
use crate::supervisor::SupervisorHandle;
pub(crate) const DEFAULT_DEADLINE_MS: u64 = 5_000;
pub(crate) const MAX_DEADLINE_MS: u64 = 60_000;
#[derive(Debug, Clone)]
pub(crate) struct KnownDogs {
dogs: Arc<Mutex<BTreeMap<String, Entry>>>,
}
#[derive(Debug, Clone, Default)]
struct Entry {
grants: Option<Grants>,
events: Vec<String>,
}
impl KnownDogs {
#[cfg(test)]
pub(crate) fn new(names: std::collections::BTreeSet<String>) -> Self {
Self::with_grants(names.into_iter().map(|name| (name, None, Vec::new())))
}
pub(crate) fn with_grants(
dogs: impl IntoIterator<Item = (String, Option<Grants>, Vec<String>)>,
) -> Self {
Self {
dogs: Arc::new(Mutex::new(
dogs.into_iter()
.map(|(name, grants, events)| (name, Entry { grants, events }))
.collect(),
)),
}
}
pub(crate) fn contains(&self, name: &str) -> bool {
self.lock().contains_key(name)
}
#[cfg(test)]
pub(crate) fn insert(&self, name: &str, grants: Option<Grants>) {
self.lock().insert(
name.to_owned(),
Entry {
grants,
events: Vec::new(),
},
);
}
pub(crate) fn replace(&self, name: &str, grants: Option<Grants>, events: Vec<String>) -> Held {
Held(
self.lock()
.insert(name.to_owned(), Entry { grants, events }),
)
}
pub(crate) fn restore(&self, name: &str, held: Held) {
match held.0 {
Some(entry) => self.lock().insert(name.to_owned(), entry),
None => self.lock().remove(name),
};
}
pub(crate) fn recorded(&self, name: &str) -> Option<Option<Grants>> {
self.lock().get(name).map(|entry| entry.grants.clone())
}
pub(crate) fn grants(&self, name: &str) -> Option<Grants> {
self.lock().get(name).and_then(|entry| entry.grants.clone())
}
pub(crate) fn events(&self, name: &str) -> Vec<String> {
self.lock()
.get(name)
.map(|entry| entry.events.clone())
.unwrap_or_default()
}
pub(crate) fn declares(&self, name: &str, kind: &str) -> bool {
self.lock()
.get(name)
.is_some_and(|entry| entry.events.iter().any(|declared| declared == kind))
}
fn lock(&self) -> MutexGuard<'_, BTreeMap<String, Entry>> {
self.dogs.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Debug)]
pub(crate) struct Held(Option<Entry>);
#[derive(Clone, Debug)]
pub struct RpcContext {
pub(crate) supervisor: SupervisorHandle,
pub(crate) events: Bus,
pub(crate) registry: FlockRegistry,
pub(crate) snapshot_path: PathBuf,
pub(crate) dogs_config: PathBuf,
pub(crate) known_dogs: KnownDogs,
pub(crate) dog_names: Vec<String>,
pub(crate) boot_first_dogs: Vec<String>,
pub(crate) paths: ShepPaths,
pub(crate) daemon_version: String,
pub(crate) dog_refusals: crate::dogs::DogRefusals,
pub(crate) peer_contacts: crate::dogs::PeerContacts,
pub(crate) pid: u32,
pub(crate) shutdown: watch::Sender<bool>,
pub(crate) stats: Arc<StatsState>,
pub(crate) host: Arc<HostState>,
pub(crate) provider_secrets: Arc<ProviderSecrets>,
pub(crate) host_environment: String,
pub(crate) pid_signals: Arc<dyn super::PidSignals>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SavedRoll {
pub path: PathBuf,
pub apps: u32,
}
impl RpcContext {
pub fn shutdown(&self) {
let _ = self.shutdown.send(true);
}
pub fn announce_dog_config(&self, dogs: &[String]) {
crate::bus::publish_dog_config_changed(&self.events, dogs);
}
pub async fn save_roll_now(&self) -> Result<Option<SavedRoll>, SnapshotError> {
let Ok(infos) = self.supervisor.list_checked().await else {
return Ok(None);
};
let roll = self.registry.roll(&infos, crate::now_ms());
write_atomic(&self.snapshot_path, &roll)?;
Ok(Some(SavedRoll {
path: self.snapshot_path.clone(),
apps: u32::try_from(roll.apps.len()).unwrap_or(u32::MAX),
}))
}
pub async fn snapshot_now(&self) -> Result<(), SnapshotError> {
self.save_roll_now().await.map(|_| ())
}
}
#[derive(Debug)]
pub(crate) enum Outcome {
Reply(Reply),
Subscribe {
reply: Reply,
filter: TopicFilter,
},
Attach {
reply: Reply,
output: PtyStream,
},
Shutdown(Reply),
}
#[must_use]
pub(crate) fn budget(deadline_ms: Option<u64>) -> Duration {
Duration::from_millis(
deadline_ms
.unwrap_or(DEFAULT_DEADLINE_MS)
.clamp(1, MAX_DEADLINE_MS),
)
}