use super::*;
use crate::config_gate::{
capture::{SettingsCapture, UserFileMetadata},
review::expected_fields,
Transition,
};
use std::path::Path;
use std::sync::{Arc, Weak};
use subc_config::Digest;
pub(crate) const USER_FILE_POLL_INTERVAL: Duration = Duration::from_secs(2);
#[derive(Default)]
pub(crate) struct UserFileWatch {
metadata: Option<Option<UserFileMetadata>>,
served: Option<Arc<ConfigView>>,
restart: Option<UnstampedRestart>,
restarting: Weak<()>,
}
impl UserFileWatch {
pub(crate) fn take_restart(&mut self) -> Option<UnstampedRestart> {
self.restart.take()
}
fn stop(&mut self) -> UserFilePoll {
self.metadata = None;
self.served = None;
self.restart = None;
UserFilePoll::Stopped
}
}
#[derive(Debug)]
pub(crate) struct UnstampedRestart {
pub(crate) connection: ConnectionId,
pub(crate) fields: Vec<String>,
incarnation: Arc<()>,
_reservation: Arc<()>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UserFilePoll {
Stopped,
Unchanged,
Observed,
}
impl RuntimeOwner {
pub(crate) fn unstamped_restart_current(
&self,
module: &str,
request: &UnstampedRestart,
) -> Result<bool> {
let state = self.lock()?;
Ok(
state.store.loaded_admission_state().0 == StoreState::Unstamped
&& state.authority_exit.is_none()
&& Arc::ptr_eq(&state.authority_incarnation, &request.incarnation)
&& state
.declarations
.get(&request.connection)
.is_some_and(|(id, _)| id == module),
)
}
pub(super) fn log_user_file_observations(&self, captured: &SettingsCapture) {
for (module, accepted) in &captured.configuration.modules {
self.log_user_file_observation(module, &accepted.file.path, None);
}
for (module, digest) in &captured.refused_file_digests {
let error = &captured.file_errors[module];
if let Some(path) = &error.path {
self.log_user_file_observation(
module,
Path::new(path),
Some((digest, &error.code, &error.message)),
);
}
}
}
fn log_user_file_observation(
&self,
module: &str,
path: &Path,
refusal: Option<(&Digest, &str, &str)>,
) {
let Ok(mut refused) = self.user_file_refusals.lock() else {
return;
};
match refusal {
Some((digest, code, reason)) if refused.get(module) != Some(digest) => {
refused.insert(module.to_owned(), digest.clone());
tracing::warn!(module_id = %module, path = %path.display(), %code, %reason,
"user settings file refused");
}
None if refused.remove(module).is_some() => {
tracing::info!(module_id = %module, path = %path.display(),
"user settings file accepted after refusal");
}
_ => {}
}
}
pub(crate) fn poll_user_file(
&self,
connection: ConnectionId,
module: &str,
watch: &mut UserFileWatch,
) -> Result<UserFilePoll> {
let (declaration, served, incarnation) = {
crate::forwarding::assert_forwarding_unlocked("the configuration owner's state");
let state = self.inner.lock().map_err(|_| {
GateError::new("config_unavailable", "configuration owner lock is poisoned")
})?;
if state.store.loaded_admission_state().0 != StoreState::Unstamped
|| state.authority_exit.is_some()
{
return Ok(watch.stop());
}
let Some((_, declaration)) = state
.declarations
.get(&connection)
.filter(|(id, _)| id == module)
else {
return Ok(watch.stop());
};
(
declaration.clone(),
state.delivery.unstamped_views.get(&connection).cloned(),
state.authority_incarnation.clone(),
)
};
let path = Path::new(&declaration.user_file);
let metadata = UserFileMetadata::read(path)?;
if metadata
.as_ref()
.is_some_and(|metadata| !metadata.has_content_digest())
{
return Ok(UserFilePoll::Observed);
}
let same_view = match (&watch.served, &served) {
(Some(before), Some(after)) => std::sync::Arc::ptr_eq(before, after),
(None, None) => true,
_ => false,
};
if watch.metadata.as_ref() == Some(&metadata) && same_view {
return Ok(UserFilePoll::Unchanged);
}
let declarations = BTreeMap::from([(module.to_owned(), declaration.clone())]);
let captured = self
.capturer
.capture_module_settings(&declarations, &BTreeSet::from([module.to_owned()]))
.and_then(|mut captured| {
captured.modules.remove(module).ok_or_else(|| {
GateError::new("config_gated", "module declaration is unavailable")
})
});
let refusal = match &captured {
Ok(_) => None,
Err(error) => {
let Some(digest) = error
.settings_file
.as_ref()
.and_then(|file| file.content_digest.as_ref())
else {
return Err(error.clone());
};
if metadata.as_ref().and_then(UserFileMetadata::content_digest) != Some(digest) {
return Ok(UserFilePoll::Observed);
}
Some((digest, error.code.as_str(), error.detail.as_str()))
}
};
if UserFileMetadata::read(path)? != metadata {
return Ok(UserFilePoll::Observed);
}
let change = captured
.as_ref()
.ok()
.zip(served.as_deref())
.filter(|(captured, served)| &captured.view != *served);
let mut restart_fields = Vec::new();
let mut strongest = Transition::Live;
if let Some((captured, served)) = change {
let classified = expected_fields(
module,
&captured.schema,
Some(served),
Some(&captured.schema),
&captured.view,
)
.and_then(|fields| {
fields
.into_iter()
.map(|(path, field)| Ok((path, Transition::from_apply(field.apply)?)))
.collect::<Result<Vec<_>>>()
});
match classified {
Ok(fields) => {
for (path, transition) in fields {
strongest = strongest.max(transition);
if transition == Transition::ModuleRestart {
restart_fields.push(path);
}
}
}
Err(error) => {
tracing::warn!(module_id=%module, code=%error.code, "settings change could not be classified; sending it as a plain change");
}
}
}
let mut state = self.lock()?;
if state.store.loaded_admission_state().0 != StoreState::Unstamped
|| state.authority_exit.is_some()
|| !std::sync::Arc::ptr_eq(&incarnation, &state.authority_incarnation)
|| !state
.declarations
.get(&connection)
.is_some_and(|(id, declared)| id == module && declared == &declaration)
{
return Ok(watch.stop());
}
let current = state.delivery.unstamped_views.get(&connection);
let same_receipt = match (&served, current) {
(Some(before), Some(after)) => std::sync::Arc::ptr_eq(before, after),
(None, None) => true,
_ => false,
};
if !same_receipt {
return Ok(UserFilePoll::Observed);
}
watch.metadata = Some(metadata);
watch.served = served.clone();
self.log_user_file_observation(module, path, refusal);
if change.is_some() && watch.restarting.strong_count() == 0 {
if strongest == Transition::ModuleRestart {
let reservation = Arc::new(());
watch.restarting = Arc::downgrade(&reservation);
watch.restart = Some(UnstampedRestart {
connection,
fields: restart_fields,
incarnation,
_reservation: reservation,
});
state.unstamp_hints.remove(&connection);
} else {
state.unstamp_hints.insert(connection);
self.notify_delivery_changed();
}
}
Ok(UserFilePoll::Observed)
}
}