Skip to main content

shep_client/
typed.rs

1//! Typed shorthands for the requests more than one caller makes.
2//!
3//! Each sends one [`Request`] and answers the one [`Response`] it expects,
4//! so a caller never writes the match or the error for any other answer.
5//! [`Client`] and [`ReconnectingClient`] carry the same set.
6
7use core::future::Future;
8
9use shep_core::config::DogTable;
10use shep_core::protocol::{
11    DogSectionToml, HostUsage, LogStream, LogTail, ProcessInfo, Request, Response, RpcError,
12    RpcErrorCode, SelectorSpec,
13};
14use shep_core::secrets::references_in;
15
16use crate::ReconnectingClient;
17use crate::client::{Client, LOG_PLANE_DEADLINE, RequestError};
18
19impl Client {
20    /// The dog `name`'s own section of `dogs.toml` with every
21    /// `{{secret:...}}` reference resolved, empty when it has none.
22    ///
23    /// Asks [`Request::DogConfigResolved`]. A shepherd too old to know it
24    /// is asked [`Request::DogConfig`] instead, and a section that still
25    /// holds a reference is refused rather than handed over unresolved.
26    ///
27    /// # Errors
28    ///
29    /// As [`Self::request`], and [`RequestError::UnexpectedReply`] for any
30    /// answer but [`Response::DogSection`]. [`RequestError::Rpc`] with
31    /// [`RpcErrorCode::Unsupported`] when an older shepherd's section names
32    /// a secret reference it cannot resolve.
33    pub async fn dog_config(&self, name: &str) -> Result<DogSectionToml, RequestError> {
34        resolved_dog_section(name, |body| self.request(body)).await
35    }
36
37    /// The sheep `name`'s `[app.dogs.<dog>]` table, with every
38    /// `{{secret:...}}` reference resolved in that sheep's own environment.
39    /// `None` when it carries no such table.
40    ///
41    /// Asks [`Request::SheepDogSettingsResolved`]. A shepherd too old to know
42    /// it is asked [`Request::DogSheepSettings`] instead, and a table still
43    /// holding a reference is refused rather than handed over unresolved.
44    ///
45    /// # Errors
46    ///
47    /// As [`Self::request`]: [`RpcErrorCode::NotFound`] for a name no sheep
48    /// holds, and [`RpcErrorCode::InvalidConfig`] for a reference that cannot
49    /// resolve. A different answer gives [`RequestError::UnexpectedReply`].
50    pub async fn sheep_dog_table(
51        &self,
52        name: &str,
53        dog: &str,
54    ) -> Result<Option<DogTable>, RequestError> {
55        resolved_sheep_dog_table(name, dog, |body| self.request(body)).await
56    }
57
58    /// Every supervised entry, dogs included.
59    ///
60    /// # Errors
61    ///
62    /// As [`Self::request`], and [`RequestError::UnexpectedReply`] for any
63    /// answer but [`Response::Flock`].
64    pub async fn list_flock(&self) -> Result<Vec<ProcessInfo>, RequestError> {
65        flock(self.request(Request::ListFlock).await?)
66    }
67
68    /// Reopens the log files of every sheep `selector` matches, under
69    /// [`LOG_PLANE_DEADLINE`], answering each one it matched.
70    ///
71    /// # Errors
72    ///
73    /// As [`Self::request`], and [`RequestError::UnexpectedReply`] for any
74    /// answer but [`Response::Reopened`].
75    pub async fn reopen(&self, selector: SelectorSpec) -> Result<Vec<ProcessInfo>, RequestError> {
76        let body = Request::Reopen { selector };
77        reopened(
78            self.request_with_deadline(body, Some(LOG_PLANE_DEADLINE))
79                .await?,
80        )
81    }
82
83    /// What the flock's machine is doing, or `None` where the shepherd
84    /// cannot read its host at all.
85    ///
86    /// # Errors
87    ///
88    /// As [`Self::request`], and [`RequestError::UnexpectedReply`] for any
89    /// answer but [`Response::HostUsage`].
90    pub async fn host_usage(&self) -> Result<Option<HostUsage>, RequestError> {
91        host(self.request(Request::HostUsage).await?)
92    }
93
94    /// Publishes `payload` as the event kind `event` of the dog on this
95    /// connection: it reaches subscribers as `dog.<name>.<event>`.
96    ///
97    /// Asks [`Request::PublishEvent`], which only a dog's own connection may
98    /// send. The shepherd checks that `event` is in the dog's manifest and
99    /// nothing about `payload`.
100    ///
101    /// # Errors
102    ///
103    /// As [`Self::request`]: [`RpcErrorCode::Forbidden`] naming the kind when
104    /// the dog did not declare it or this is not a dog's connection. A
105    /// different answer gives [`RequestError::UnexpectedReply`].
106    pub async fn publish_event(
107        &self,
108        event: &str,
109        payload: serde_json::Value,
110    ) -> Result<(), RequestError> {
111        published(
112            self.request(Request::PublishEvent {
113                event: event.to_owned(),
114                payload,
115            })
116            .await?,
117        )
118    }
119
120    /// The last `lines` lines of one sheep's out or err log, read by the
121    /// shepherd on its own host.
122    ///
123    /// A file that is absent, unreadable or not recorded is a [`LogTail`]
124    /// variant, not an error.
125    ///
126    /// # Errors
127    ///
128    /// As [`Self::request`], including [`RpcErrorCode::NotFound`] for an id
129    /// no sheep holds, and [`RequestError::UnexpectedReply`] for any answer
130    /// but [`Response::LogTail`].
131    pub async fn tail_log(
132        &self,
133        id: u32,
134        stream: LogStream,
135        lines: u32,
136    ) -> Result<LogTail, RequestError> {
137        log_tail(self.request(Request::TailLog { id, stream, lines }).await?)
138    }
139}
140
141impl ReconnectingClient {
142    /// Shorthand for [`Client::publish_event`] on the current generation.
143    ///
144    /// # Errors
145    ///
146    /// As [`Client::publish_event`].
147    pub async fn publish_event(
148        &self,
149        event: &str,
150        payload: serde_json::Value,
151    ) -> Result<(), RequestError> {
152        published(
153            self.request(Request::PublishEvent {
154                event: event.to_owned(),
155                payload,
156            })
157            .await?,
158        )
159    }
160
161    /// Shorthand for [`Client::dog_config`] on the current generation.
162    ///
163    /// # Errors
164    ///
165    /// As [`Client::dog_config`].
166    pub async fn dog_config(&self, name: &str) -> Result<DogSectionToml, RequestError> {
167        resolved_dog_section(name, |body| self.request(body)).await
168    }
169
170    /// Shorthand for [`Client::sheep_dog_table`] on the current generation.
171    ///
172    /// # Errors
173    ///
174    /// As [`Client::sheep_dog_table`].
175    pub async fn sheep_dog_table(
176        &self,
177        name: &str,
178        dog: &str,
179    ) -> Result<Option<DogTable>, RequestError> {
180        resolved_sheep_dog_table(name, dog, |body| self.request(body)).await
181    }
182
183    /// Shorthand for [`Client::list_flock`] on the current generation.
184    ///
185    /// # Errors
186    ///
187    /// As [`Client::list_flock`].
188    pub async fn list_flock(&self) -> Result<Vec<ProcessInfo>, RequestError> {
189        flock(self.request(Request::ListFlock).await?)
190    }
191
192    /// Shorthand for [`Client::reopen`] on the current generation.
193    ///
194    /// # Errors
195    ///
196    /// As [`Client::reopen`].
197    pub async fn reopen(&self, selector: SelectorSpec) -> Result<Vec<ProcessInfo>, RequestError> {
198        let body = Request::Reopen { selector };
199        reopened(
200            self.request_with_deadline(body, Some(LOG_PLANE_DEADLINE))
201                .await?,
202        )
203    }
204
205    /// Shorthand for [`Client::host_usage`] on the current generation.
206    ///
207    /// # Errors
208    ///
209    /// As [`Client::host_usage`].
210    pub async fn host_usage(&self) -> Result<Option<HostUsage>, RequestError> {
211        host(self.request(Request::HostUsage).await?)
212    }
213
214    /// Shorthand for [`Client::tail_log`] on the current generation.
215    ///
216    /// # Errors
217    ///
218    /// As [`Client::tail_log`].
219    pub async fn tail_log(
220        &self,
221        id: u32,
222        stream: LogStream,
223        lines: u32,
224    ) -> Result<LogTail, RequestError> {
225        log_tail(self.request(Request::TailLog { id, stream, lines }).await?)
226    }
227}
228
229fn dog_config_request(name: &str) -> Request {
230    Request::DogConfigResolved {
231        name: name.to_owned(),
232    }
233}
234
235/// Asks `ask` for the resolved section, and for the plain one when the
236/// shepherd does not know the request.
237///
238/// A shepherd built before the request refuses it with `Unsupported`, which
239/// `Request::Unrecognized` earns on the daemon side. `Unrecognized` covers a
240/// code this build was not taught.
241async fn resolved_dog_section<F, Fut>(name: &str, ask: F) -> Result<DogSectionToml, RequestError>
242where
243    F: Fn(Request) -> Fut,
244    Fut: Future<Output = Result<Response, RequestError>>,
245{
246    match ask(dog_config_request(name)).await {
247        Err(RequestError::Rpc(refusal)) if is_unknown_request(&refusal) => {
248            let plain = Request::DogConfig {
249                name: name.to_owned(),
250            };
251            let section = dog_section(ask(plain).await?)?;
252            if !references_in(section.as_str()).is_empty() {
253                return Err(RequestError::Rpc(RpcError {
254                    code: RpcErrorCode::Unsupported,
255                    message: format!(
256                        "the shepherd is too old to resolve secret references in the \
257                         `{name}` dog's section"
258                    ),
259                    daemon_version: refusal.daemon_version,
260                }));
261            }
262            Ok(section)
263        }
264        answer => dog_section(answer?),
265    }
266}
267
268/// Whether `refusal` is a shepherd saying it does not know the request.
269fn is_unknown_request(refusal: &RpcError) -> bool {
270    matches!(
271        refusal.code,
272        RpcErrorCode::Unsupported | RpcErrorCode::Unrecognized
273    )
274}
275
276/// Asks `ask` for the sheep's resolved table, and for every sheep's plain
277/// one when the shepherd does not know the request, as
278/// [`resolved_dog_section`] does for a section.
279async fn resolved_sheep_dog_table<F, Fut>(
280    name: &str,
281    dog: &str,
282    ask: F,
283) -> Result<Option<DogTable>, RequestError>
284where
285    F: Fn(Request) -> Fut,
286    Fut: Future<Output = Result<Response, RequestError>>,
287{
288    let resolved = Request::SheepDogSettingsResolved {
289        name: name.to_owned(),
290        dog: dog.to_owned(),
291    };
292    match ask(resolved).await {
293        Err(RequestError::Rpc(refusal)) if is_unknown_request(&refusal) => {
294            let plain = Request::DogSheepSettings {
295                dog: dog.to_owned(),
296            };
297            let table = match ask(plain).await? {
298                Response::DogSheepSettings { mut tables } => tables.remove(name),
299                other => return Err(unexpected("DogSheepSettings", &other)),
300            };
301            if table.is_none() {
302                ensure_a_sheep(name, &ask).await?;
303            }
304            if table
305                .as_ref()
306                .is_some_and(|table| !table.references().is_empty())
307            {
308                return Err(RequestError::Rpc(RpcError {
309                    code: RpcErrorCode::Unsupported,
310                    message: format!(
311                        "the shepherd is too old to resolve secret references in the \
312                         `{name}` sheep's `{dog}` table"
313                    ),
314                    daemon_version: refusal.daemon_version,
315                }));
316            }
317            Ok(table)
318        }
319        answer => match answer? {
320            Response::SheepDogTable { table } => Ok(table),
321            other => Err(unexpected("SheepDogSettingsResolved", &other)),
322        },
323    }
324}
325
326/// Succeeds when the flock holds a sheep named `name`, and is `NotFound`
327/// otherwise, a dog's own name included.
328///
329/// `DogSheepSettings` lists only the sheep that carry a table, so on its
330/// own it answers an unknown name and a sheep without the table alike.
331/// The request this stands in for tells them apart.
332async fn ensure_a_sheep<F, Fut>(name: &str, ask: &F) -> Result<(), RequestError>
333where
334    F: Fn(Request) -> Fut,
335    Fut: Future<Output = Result<Response, RequestError>>,
336{
337    let sheep = flock(ask(Request::ListFlock).await?)?;
338    if sheep
339        .iter()
340        .any(|entry| entry.name == name && entry.dog.is_none())
341    {
342        return Ok(());
343    }
344    Err(RequestError::Rpc(RpcError {
345        code: RpcErrorCode::NotFound,
346        message: format!("no sheep named {name}"),
347        daemon_version: None,
348    }))
349}
350
351fn dog_section(answer: Response) -> Result<DogSectionToml, RequestError> {
352    match answer {
353        Response::DogSection { toml } => Ok(toml),
354        other => Err(unexpected("DogConfigResolved", &other)),
355    }
356}
357
358fn flock(answer: Response) -> Result<Vec<ProcessInfo>, RequestError> {
359    match answer {
360        Response::Flock(flock) => Ok(flock),
361        other => Err(unexpected("ListFlock", &other)),
362    }
363}
364
365fn reopened(answer: Response) -> Result<Vec<ProcessInfo>, RequestError> {
366    match answer {
367        Response::Reopened(sheep) => Ok(sheep),
368        other => Err(unexpected("Reopen", &other)),
369    }
370}
371
372fn host(answer: Response) -> Result<Option<HostUsage>, RequestError> {
373    match answer {
374        Response::HostUsage(usage) => Ok(usage),
375        other => Err(unexpected("HostUsage", &other)),
376    }
377}
378
379fn published(answer: Response) -> Result<(), RequestError> {
380    match answer {
381        Response::EventPublished => Ok(()),
382        other => Err(unexpected("PublishEvent", &other)),
383    }
384}
385
386fn log_tail(answer: Response) -> Result<LogTail, RequestError> {
387    match answer {
388        Response::LogTail(tail) => Ok(tail),
389        other => Err(unexpected("TailLog", &other)),
390    }
391}
392
393fn unexpected(asked: &'static str, answer: &Response) -> RequestError {
394    RequestError::UnexpectedReply {
395        asked,
396        answered: answer.name(),
397    }
398}
399
400#[cfg(test)]
401mod tests;