1use 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 pub async fn dog_config(&self, name: &str) -> Result<DogSectionToml, RequestError> {
34 resolved_dog_section(name, |body| self.request(body)).await
35 }
36
37 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 pub async fn list_flock(&self) -> Result<Vec<ProcessInfo>, RequestError> {
65 flock(self.request(Request::ListFlock).await?)
66 }
67
68 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 pub async fn host_usage(&self) -> Result<Option<HostUsage>, RequestError> {
91 host(self.request(Request::HostUsage).await?)
92 }
93
94 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 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 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 pub async fn dog_config(&self, name: &str) -> Result<DogSectionToml, RequestError> {
167 resolved_dog_section(name, |body| self.request(body)).await
168 }
169
170 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 pub async fn list_flock(&self) -> Result<Vec<ProcessInfo>, RequestError> {
189 flock(self.request(Request::ListFlock).await?)
190 }
191
192 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 pub async fn host_usage(&self) -> Result<Option<HostUsage>, RequestError> {
211 host(self.request(Request::HostUsage).await?)
212 }
213
214 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
235async 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
268fn is_unknown_request(refusal: &RpcError) -> bool {
270 matches!(
271 refusal.code,
272 RpcErrorCode::Unsupported | RpcErrorCode::Unrecognized
273 )
274}
275
276async 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
326async 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;