Skip to main content

mortise_core/runtime/
environment.rs

1//! A running copy of an app, and what Mortise needs to ask it.
2//!
3//! Nothing here is a secret: the kind of credentials, a user name and a header name
4//! are kept in Mortise's settings, the secret itself in the credential store.
5
6use serde::{Deserialize, Serialize};
7
8/// What the app's middleware asks for.
9#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
10#[serde(tag = "kind", rename_all = "kebab-case")]
11pub enum Credentials {
12    /// Mortise sends no credentials. Right for a local app whose actuator is open.
13    #[default]
14    None,
15    /// A token, sent as `Authorization: Bearer`.
16    Bearer,
17    /// HTTP basic. The user name is not a secret.
18    Basic { user: String },
19    /// A header with a name and a value. The name is not a secret.
20    Header { name: String },
21}
22
23impl Credentials {
24    /// True when the kind needs a secret from the credential store.
25    pub fn needs_secret(&self) -> bool {
26        *self != Credentials::None
27    }
28}
29
30/// A running copy of an app that Mortise can ask for its runtime status.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct Environment {
33    /// `local`, `staging`, `production`.
34    pub name: String,
35    /// `https://shop-api.test`
36    pub base_url: String,
37    /// The path of the actuator under the base URL: `actuator` unless the app changed it.
38    pub path: String,
39    #[serde(default)]
40    pub credentials: Credentials,
41}
42
43impl Environment {
44    /// The address of the actuator, or of one of its endpoints.
45    pub fn url(&self, endpoint: &str) -> String {
46        let base = self.base_url.trim_end_matches('/');
47        let path = self.path.trim_matches('/');
48        let mut url = if path.is_empty() {
49            base.to_owned()
50        } else {
51            format!("{base}/{path}")
52        };
53        if !endpoint.is_empty() {
54            url.push('/');
55            url.push_str(endpoint);
56        }
57        url
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn the_address_of_an_endpoint_is_joined_without_double_slashes() {
67        let environment = Environment {
68            name: "local".into(),
69            base_url: "https://shop-api.test/".into(),
70            path: "/actuator/".into(),
71            credentials: Credentials::None,
72        };
73        assert_eq!(environment.url(""), "https://shop-api.test/actuator");
74        assert_eq!(
75            environment.url("health"),
76            "https://shop-api.test/actuator/health"
77        );
78        let root = Environment {
79            path: String::new(),
80            ..environment
81        };
82        assert_eq!(root.url("info"), "https://shop-api.test/info");
83    }
84}