service_probe_client/
lib.rs

1// SPDX-FileCopyrightText: OpenTalk Team <mail@opentalk.eu>
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! # Service probe client
6//!
7//! This crate provides an easy way to access the a HTTP server that can be used for
8//! making the status of a service transparent to observers.
9#![deny(
10    bad_style,
11    missing_debug_implementations,
12    missing_docs,
13    overflowing_literals,
14    patterns_in_fns_without_body,
15    trivial_casts,
16    trivial_numeric_casts,
17    unsafe_code,
18    unused,
19    unused_extern_crates,
20    unused_import_braces,
21    unused_qualifications,
22    unused_results
23)]
24
25pub use service_probe_common::ServiceState;
26use snafu::Snafu;
27use url::Url;
28
29/// The error that can happen during startup of the service probe.
30#[derive(Debug, Snafu)]
31pub enum ProbeClientError {
32    /// The socket cannot be used for providing the service probe.
33    ServiceProbeEndpointUnavailable {
34        /// The source error
35        source: reqwest::Error,
36    },
37}
38
39/// fetch service state from given endpoint
40pub async fn fetch_service_state(endpoint: &Url) -> Result<ServiceState, ProbeClientError> {
41    log::info!("Fetching state from {endpoint}");
42    let body = reqwest::get(endpoint.clone())
43        .await
44        .map_err(|err| ProbeClientError::ServiceProbeEndpointUnavailable { source: err })?
45        .text()
46        .await;
47
48    match body {
49        Ok(content) => {
50            if content.lines().any(|line| line == "READY") {
51                Ok(ServiceState::Ready)
52            } else {
53                Ok(ServiceState::Up)
54            }
55        }
56
57        Err(err) => Err(ProbeClientError::ServiceProbeEndpointUnavailable { source: err }),
58    }
59}
60
61/// returns true if the service state of the given endpoint is ready
62pub async fn is_ready(endpoint: &Url) -> Result<bool, ProbeClientError> {
63    match fetch_service_state(endpoint).await {
64        Ok(state) => Ok(state == ServiceState::Ready),
65        Err(err) => Err(err),
66    }
67}