Skip to main content

shep_client/dogs/
sheep_settings.rs

1//! A dog's one settings type, set for every sheep in `[<dog>]` and per sheep
2//! in `[app.dogs.<dog>]`.
3//!
4//! [`DogRuntime::sheep_settings`] does the layering, so a dog author writes
5//! one type and calls one function with nothing to merge by hand.
6
7use core::fmt;
8use std::collections::{BTreeMap, BTreeSet};
9
10use serde::de::DeserializeOwned;
11use shep_core::config::DogTable;
12use shep_core::dogs::manifest::Serves;
13use shep_core::protocol::{Request, Response};
14
15use super::{DogConfig, DogRuntime, SectionError};
16use crate::RequestError;
17
18/// One sheep's settings could not be built.
19///
20/// Carries no parser message and no table value, which can hold a credential.
21/// A key name is a field of the dog's own type, so it is safe to print.
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum ServedSheepError {
25    /// The sheep's table sets a key the dog marks `#[shep(dog_wide)]`, which
26    /// is set in `[<dog>]` only.
27    DogWide {
28        /// The sheep.
29        sheep: String,
30        /// Each dog-wide key the sheep's table sets, in order.
31        keys: Vec<String>,
32    },
33    /// The section with the sheep's table over it does not fit the dog's
34    /// settings type.
35    DoesNotFit {
36        /// The dog.
37        dog: String,
38        /// The sheep.
39        sheep: String,
40    },
41    /// The shepherd could not resolve a `{{secret:...}}` in the sheep's
42    /// table.
43    Unresolved {
44        /// The sheep.
45        sheep: String,
46        /// The shepherd's reason.
47        reason: String,
48    },
49}
50
51impl ServedSheepError {
52    /// The sheep whose settings this is about.
53    #[must_use]
54    pub fn sheep(&self) -> &str {
55        match self {
56            Self::DogWide { sheep, .. }
57            | Self::DoesNotFit { sheep, .. }
58            | Self::Unresolved { sheep, .. } => sheep,
59        }
60    }
61}
62
63impl fmt::Display for ServedSheepError {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            Self::DogWide { sheep, keys } => write!(
67                f,
68                "the table on {sheep} sets {}, which is dog-wide: set it in the dog's own section",
69                keys.join(", ")
70            ),
71            Self::DoesNotFit { dog, sheep } => write!(
72                f,
73                "the settings for {sheep}, its [app.dogs.{dog}] table over [{dog}], do not fit this dog's settings"
74            ),
75            Self::Unresolved { sheep, reason } => {
76                write!(
77                    f,
78                    "a secret in the table on {sheep} did not resolve: {reason}"
79                )
80            }
81        }
82    }
83}
84
85impl core::error::Error for ServedSheepError {}
86
87/// The settings of no sheep could be read.
88#[derive(Debug)]
89#[non_exhaustive]
90pub enum SheepSettingsReadError {
91    /// The dog's own section is not a TOML table.
92    Section(SectionError),
93    /// The shepherd could not list the sheep or their tables.
94    Request(RequestError),
95}
96
97impl fmt::Display for SheepSettingsReadError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::Section(err) => write!(f, "{err}"),
101            Self::Request(err) => write!(f, "a request to the shepherd failed: {err}"),
102        }
103    }
104}
105
106impl core::error::Error for SheepSettingsReadError {
107    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
108        match self {
109            Self::Section(err) => Some(err),
110            Self::Request(err) => Some(err),
111        }
112    }
113}
114
115impl From<SectionError> for SheepSettingsReadError {
116    fn from(err: SectionError) -> Self {
117        Self::Section(err)
118    }
119}
120
121impl From<RequestError> for SheepSettingsReadError {
122    fn from(err: RequestError) -> Self {
123        Self::Request(err)
124    }
125}
126
127/// `section` without the keys in `dog_wide`, with the sheep's `own` table
128/// over it, read as `T`.
129fn settings_for<T: DeserializeOwned>(
130    dog: &str,
131    dog_wide: &BTreeSet<String>,
132    section: &DogTable,
133    sheep: &str,
134    own: Option<&DogTable>,
135) -> Result<T, ServedSheepError> {
136    let set_here: Vec<String> = own
137        .into_iter()
138        .flat_map(|own| own.as_map().keys())
139        .filter(|key| dog_wide.contains(*key))
140        .cloned()
141        .collect();
142    if !set_here.is_empty() {
143        return Err(ServedSheepError::DogWide {
144            sheep: sheep.to_owned(),
145            keys: set_here,
146        });
147    }
148    let mut shared = section.as_map().clone();
149    shared.retain(|key, _| !dog_wide.contains(key));
150    let shared = DogTable::from(shared);
151    let merged = match own {
152        Some(own) => DogTable::layered(&[&shared, own]),
153        None => shared,
154    };
155    serde_json::from_value(serde_json::Value::Object(merged.into_map())).map_err(|_| {
156        ServedSheepError::DoesNotFit {
157            dog: dog.to_owned(),
158            sheep: sheep.to_owned(),
159        }
160    })
161}
162
163impl DogRuntime {
164    /// Each served sheep's settings, read as `T`: this dog's `[<dog>]`
165    /// section without its dog-wide keys, then the sheep's own
166    /// `[app.dogs.<dog>]` table over it.
167    ///
168    /// `serves` is what the dog declared with [`Probe::serves`](super::Probe::serves).
169    /// A `#[shep(dog_wide)]` field needs a default; read it with
170    /// [`Self::config`].
171    ///
172    /// # Errors
173    ///
174    /// - [`SheepSettingsReadError::Section`]: the section is not a TOML table.
175    /// - [`SheepSettingsReadError::Request`]: the sheep or tables failed to list.
176    ///
177    /// # Examples
178    ///
179    /// ```no_run
180    /// use shep_client::dogs::{DogRuntime, Serves};
181    ///
182    /// #[shep_client::dogs::dog_config]
183    /// #[derive(Default, serde::Deserialize, schemars::JsonSchema)]
184    /// #[serde(default)]
185    /// struct Jobs {
186    ///     #[shep(dog_wide)]
187    ///     poll: String,
188    ///     model: String,
189    /// }
190    ///
191    /// # async fn read(runtime: &DogRuntime) -> Result<(), Box<dyn core::error::Error>> {
192    /// for (sheep, settings) in runtime.sheep_settings::<Jobs>(Serves::EverySheep).await? {
193    ///     match settings {
194    ///         Ok(settings) => println!("{sheep}: {}", settings.model),
195    ///         Err(err) => eprintln!("{sheep}: {err}"),
196    ///     }
197    /// }
198    /// # Ok(())
199    /// # }
200    /// # let _ = read;
201    /// ```
202    pub async fn sheep_settings<T>(
203        &self,
204        serves: Serves,
205    ) -> Result<BTreeMap<String, Result<T, ServedSheepError>>, SheepSettingsReadError>
206    where
207        T: DogConfig + schemars::JsonSchema + DeserializeOwned,
208    {
209        let dog = self.identity().section();
210        let dog_wide = super::dog_wide::dog_wide_keys::<T>();
211        let section = super::section::section_table(dog, self.section().as_str())?;
212        let carrying = self.sheep_with_a_table().await?;
213        let sheep = match serves {
214            Serves::EverySheep => self
215                .client()
216                .list_flock()
217                .await?
218                .into_iter()
219                .filter(|entry| entry.dog.is_none())
220                .map(|entry| entry.name)
221                .collect(),
222            _ => carrying.clone(),
223        };
224        let mut settings = BTreeMap::new();
225        for name in sheep {
226            if !carrying.contains(&name) {
227                settings.insert(
228                    name.clone(),
229                    settings_for(dog, &dog_wide, &section, &name, None),
230                );
231                continue;
232            }
233            let mut own = self.own_table(&name).await?;
234            if own.as_ref().is_some_and(|own| !own.references().is_empty()) {
235                match self.client().sheep_dog_table(&name, dog).await {
236                    Ok(resolved) => {
237                        own = own.map(|own| resolved_like(&own, resolved.as_ref()));
238                    }
239                    Err(err) => {
240                        let fault = ServedSheepError::Unresolved {
241                            sheep: name.clone(),
242                            reason: err.to_string(),
243                        };
244                        settings.insert(name, Err(fault));
245                        continue;
246                    }
247                }
248            }
249            let one = settings_for(dog, &dog_wide, &section, &name, own.as_ref());
250            settings.insert(name, one);
251        }
252        Ok(settings)
253    }
254
255    /// The sheep carrying an `[app.dogs.<dog>]` table.
256    ///
257    /// Only the names are read from this reply: each sheep's own table comes
258    /// from its config.
259    async fn sheep_with_a_table(&self) -> Result<BTreeSet<String>, RequestError> {
260        let asked = Request::DogSheepSettings {
261            dog: self.identity().section().to_owned(),
262        };
263        match self.client().request(asked).await? {
264            Response::DogSheepSettings { tables } => Ok(tables.into_keys().collect()),
265            other => Err(RequestError::UnexpectedReply {
266                asked: "DogSheepSettings",
267                answered: other.name(),
268            }),
269        }
270    }
271
272    /// `sheep`'s own `[app.dogs.<dog>]` table as the sheep's config holds it:
273    /// no operator default under it, references unresolved.
274    async fn own_table(&self, sheep: &str) -> Result<Option<DogTable>, RequestError> {
275        let asked = Request::SheepConfig {
276            name: sheep.to_owned(),
277        };
278        match self.client().request(asked).await? {
279            Response::SheepConfig(view) => {
280                Ok(view.config.dogs.get(self.identity().section()).cloned())
281            }
282            other => Err(RequestError::UnexpectedReply {
283                asked: "SheepConfig",
284                answered: other.name(),
285            }),
286        }
287    }
288}
289
290/// `own` with each leaf replaced by the value `resolved` holds at the same
291/// path.
292///
293/// `resolved` is `own` under the operator's default with every reference
294/// replaced, and `own` wins at every leaf it sets, so the default's keys
295/// are left behind.
296fn resolved_like(own: &DogTable, resolved: Option<&DogTable>) -> DogTable {
297    fn walk(
298        own: &serde_json::Map<String, serde_json::Value>,
299        resolved: Option<&serde_json::Map<String, serde_json::Value>>,
300    ) -> serde_json::Map<String, serde_json::Value> {
301        own.iter()
302            .map(|(key, value)| {
303                let there = resolved.and_then(|resolved| resolved.get(key));
304                let value = match value {
305                    serde_json::Value::Object(inner) => {
306                        serde_json::Value::Object(walk(inner, there.and_then(|v| v.as_object())))
307                    }
308                    other => there.cloned().unwrap_or_else(|| other.clone()),
309                };
310                (key.clone(), value)
311            })
312            .collect()
313    }
314    DogTable::from(walk(own.as_map(), resolved.map(DogTable::as_map)))
315}
316
317#[cfg(test)]
318mod tests;