use std::collections::BTreeMap;
use std::sync::Arc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use super::declaration::{Declaration, Group, Item, Kind, Node, Setting, at, gives_secret};
use super::explain::Origin;
use super::hub::{Change, Kept};
use super::layers::{Base, Layer, Stacked, not_read_from, set};
use super::marks::marked;
use super::rules;
pub(super) type Validate<T> = Box<dyn Fn(&T) -> Result<(), String> + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum View {
Rust,
#[cfg_attr(
not(all(feature = "config", any(test, feature = "wire", feature = "records"))),
expect(dead_code, reason = "only an SDK over the wire and a store's logger send it")
)]
Data,
}
pub(super) struct Making<'a, T> {
pub(super) declaration: &'a Declaration,
pub(super) validate: Option<&'a Validate<T>>,
pub(super) view: View,
}
#[derive(Debug)]
pub(super) struct Resolved<T> {
pub(super) value: Arc<T>,
pub(super) tree: Value,
pub(super) applied: BTreeMap<String, Change>,
pub(super) ignored: Vec<(String, Change, String)>,
pub(super) foreign: Vec<String>,
}
impl<T: DeserializeOwned> Making<'_, T> {
pub(super) fn layered(&self, base: &Base) -> Result<(T, Value), Vec<String>> {
let tree = base.tree();
let value = self.built(&tree).map_err(|why| self.culprits(base, &tree, &why))?;
if let Some(validate) = self.validate {
validate(&value).map_err(|why| vec![why])?;
}
Ok((value, tree))
}
pub(super) fn resolve(&self, layered: (&Arc<T>, &Value), kept: &Kept) -> Resolved<T> {
let (mut value, mut tree) = (Arc::clone(layered.0), layered.1.clone());
let (mut applied, mut ignored, mut foreign) = (BTreeMap::new(), Vec::new(), Vec::new());
for (path, change) in kept.in_order() {
if self.declaration.node(path).is_none() {
foreign.push(path.clone());
continue;
}
match self.applied_to(&tree, path, &change.value) {
Ok((next, next_tree)) => {
(value, tree) = (Arc::new(next), next_tree);
applied.insert(path.clone(), change.clone());
}
Err(why) => ignored.push((path.clone(), change.clone(), why)),
}
}
Resolved { value, tree, applied, ignored, foreign }
}
fn applied_to(&self, tree: &Value, path: &str, value: &Value) -> Result<(T, Value), String> {
let setting = self.declaration.setting(path).ok_or_else(|| "a group, not a setting".to_owned())?;
if setting.secret {
return Err("a secret, which only a layer gives".to_owned());
}
if !setting.live {
return Err("not live".to_owned());
}
let value = rules::check(setting, value)?;
let mut next = tree.clone();
set(&mut next, path, value);
let built = self.built(&next)?;
if let Some(validate) = self.validate {
validate(&built)?;
}
Ok((built, next))
}
pub(super) fn built(&self, tree: &Value) -> Result<T, String> {
let viewed = match self.view {
View::Rust => rust_view(self.declaration, tree),
View::Data => tree.clone(),
};
serde_json::from_value(viewed).map_err(|error| error.to_string())
}
fn culprits(&self, base: &Base, tree: &Value, why: &str) -> Vec<String> {
let settings: BTreeMap<String, &Setting> = self.declaration.settings_of(&base.shape).into_iter().collect();
let given: Vec<(&String, &Stacked, &Value)> = base
.stacks
.iter()
.filter_map(|(path, stack)| {
let last = stack.last().filter(|last| last.from != Origin::Declaration)?;
let default = settings.get(path)?.default.as_ref()?;
Some((path, last, default))
})
.collect();
let mut clean = tree.clone();
for (path, _, default) in &given {
set(&mut clean, path, (*default).clone());
}
if self.built(&clean).is_err() {
return vec![why.to_owned()];
}
let found: Vec<String> = given
.iter()
.filter_map(|(path, last, _)| {
let mut alone = clean.clone();
set(&mut alone, path, last.value.clone());
let secret = settings.get(path.as_str()).is_some_and(|setting| setting.secret);
let shown =
|why: String| if secret { "a secret that does not read as its type".to_owned() } else { why };
self.built(&alone).err().map(|why| named(&last.from, path, &shown(why)))
})
.collect();
if found.is_empty() { vec![why.to_owned()] } else { found }
}
}
impl<T: Serialize + DeserializeOwned> Making<'_, T> {
pub(super) fn written_at(&self, tree: &Value, path: &str, value: &Value) -> Option<Value> {
let mut probe = tree.clone();
set(&mut probe, path, value.clone());
let read = marked(&self.built(&probe).ok()?).ok()?;
Some(at(&read, path).cloned().unwrap_or(Value::Null))
}
pub(super) fn secrets_inside(&self, base: &Base, layers: &[Layer]) -> Result<(), Vec<String>> {
let refusing: Vec<String> = layers
.iter()
.filter_map(|layer| match layer {
Layer::File(file) if !file.gives_secrets() => Some(file.shown()),
_ => None,
})
.collect();
if refusing.is_empty() {
return Ok(());
}
let tree = base.tree();
let mut found = Vec::new();
for (path, setting) in self.declaration.settings_of(&base.shape) {
if !matches!(setting.kind, Kind::Object | Kind::List(_) | Kind::Any) {
continue;
}
for stacked in base.stacks.get(&path).into_iter().flatten() {
let Origin::File { path: file } = &stacked.from else { continue };
let read = || self.written_at(&tree, &path, &stacked.value);
if refusing.contains(file) && read().is_some_and(|read| gives_secret(&stacked.value, &read)) {
found.push(format!("{file}: {}", not_read_from(file, &path, layers)));
}
}
}
if found.is_empty() { Ok(()) } else { Err(found) }
}
}
fn named(from: &Origin, path: &str, why: &str) -> String {
match from {
Origin::Env { .. } => format!("{from}: {why}"),
Origin::File { .. } | Origin::Layer { .. } => format!("{from}: {path}: {why}"),
Origin::Declaration | Origin::Change { .. } => format!("{path}: {why}"),
}
}
fn rust_view(declaration: &Declaration, tree: &Value) -> Value {
let mut tree = tree.clone();
view_group(&declaration.root, &mut tree);
tree
}
fn view_group(group: &Group, tree: &mut Value) {
let Value::Object(map) = tree else { return };
for (key, node) in group {
let picked = match node {
Node::Chosen(chosen) => chosen.named(map.get(&chosen.by)).map(|(_, inner)| inner),
_ => None,
};
let Some(value) = map.get_mut(key) else { continue };
match node {
Node::Group(inner) => view_group(inner, value),
Node::Setting(setting) => view_kind(&setting.kind, value),
Node::Entries(entries) => {
if let Value::Object(each) = value {
each.values_mut().for_each(|entry| view_group(&entries.item, entry));
}
}
Node::Chosen(_) => picked.into_iter().for_each(|inner| view_group(inner, value)),
}
}
}
fn view_kind(kind: &Kind, value: &mut Value) {
match (kind, value) {
(Kind::Duration, value) => {
if let Some(millis) = value.as_u64() {
*value = json!({ "secs": millis / 1000, "nanos": millis % 1000 * 1_000_000 });
}
}
(Kind::List(item), Value::Array(items)) => {
for item_value in items {
match &**item {
Item::Value { kind, .. } => view_kind(kind, item_value),
Item::Group(group) => view_group(group, item_value),
}
}
}
_ => {}
}
}