Skip to main content

webserver_base/
environment.rs

1//! Which deployment this process is: a laptop, or the droplet. There is no dev
2//! or staging tier.
3//!
4//! [`Environment::Production`] is the strict one — error monitoring is required
5//! there, and analytics only fire there. Required everywhere rather than
6//! defaulted, because a default means a misconfigured deploy behaves like a
7//! laptop.
8
9use std::fmt::{self, Display, Formatter};
10use std::str::FromStr;
11
12use serde::{Deserialize, Serialize};
13
14use crate::env::{self, EnvError};
15
16/// The environment variable [`Environment::from_env`] reads.
17pub const ENV_ENVIRONMENT: &str = "WSB_ENVIRONMENT";
18
19/// Which deployment this process is.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "lowercase")]
22pub enum Environment {
23    /// Running on a development machine.
24    Local,
25    /// Running in production.
26    Production,
27}
28
29impl Environment {
30    /// The lowercase name, as written in `WSB_ENVIRONMENT`.
31    #[must_use]
32    pub const fn as_str(&self) -> &'static str {
33        match self {
34            Self::Local => "local",
35            Self::Production => "production",
36        }
37    }
38
39    /// Whether this is production.
40    #[must_use]
41    pub const fn is_production(&self) -> bool {
42        matches!(self, Self::Production)
43    }
44
45    /// Whether this is a development machine.
46    #[must_use]
47    pub const fn is_local(&self) -> bool {
48        matches!(self, Self::Local)
49    }
50
51    /// Reads [`ENV_ENVIRONMENT`]. Deliberately has no default.
52    ///
53    /// # Errors
54    ///
55    /// [`EnvError::Missing`] if unset, [`EnvError::Empty`] if blank, or
56    /// [`EnvError::Invalid`] if it is neither `local` nor `production`.
57    pub fn from_env() -> Result<Self, EnvError> {
58        Self::parse_value(env::required(ENV_ENVIRONMENT)?)
59    }
60
61    /// [`Environment::from_env`]'s logic over an already-read value, so it can
62    /// be tested without mutating the process environment.
63    ///
64    /// # Errors
65    ///
66    /// As [`Environment::from_env`].
67    pub fn from_value(raw: Option<&str>) -> Result<Self, EnvError> {
68        match raw {
69            None => Err(EnvError::Missing {
70                key: ENV_ENVIRONMENT.to_string(),
71            }),
72            Some(value) if value.trim().is_empty() => Err(EnvError::Empty {
73                key: ENV_ENVIRONMENT.to_string(),
74            }),
75            Some(value) => Self::parse_value(value.trim().to_string()),
76        }
77    }
78
79    fn parse_value(value: String) -> Result<Self, EnvError> {
80        value.parse::<Self>().map_err(|_| EnvError::Invalid {
81            key: ENV_ENVIRONMENT.to_string(),
82            expected: "environment (`local` or `production`)",
83            value,
84        })
85    }
86}
87
88/// The value was neither `local` nor `production`.
89#[derive(Debug, thiserror::Error)]
90#[error("`{value}` is not a supported environment; use `local` or `production`")]
91pub struct EnvironmentParseError {
92    /// What was supplied.
93    pub value: String,
94}
95
96impl FromStr for Environment {
97    type Err = EnvironmentParseError;
98
99    fn from_str(s: &str) -> Result<Self, Self::Err> {
100        match s.trim().to_lowercase().as_str() {
101            "local" => Ok(Self::Local),
102            "production" => Ok(Self::Production),
103            _ => Err(EnvironmentParseError {
104                value: s.to_string(),
105            }),
106        }
107    }
108}
109
110impl Display for Environment {
111    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
112        f.write_str(self.as_str())
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::{Environment, EnvironmentParseError};
119
120    #[test]
121    fn both_environments_round_trip_through_their_string_form() {
122        for expected in [Environment::Local, Environment::Production] {
123            let actual: Environment = expected
124                .as_str()
125                .parse::<Environment>()
126                .expect("its own as_str is always parseable");
127            assert_eq!(expected, actual);
128        }
129    }
130
131    #[test]
132    fn parsing_is_case_and_whitespace_insensitive() {
133        let expected: Environment = Environment::Production;
134        let actual: Environment = "  PRODUCTION  ".parse().expect("trimmed and lowercased");
135        assert_eq!(expected, actual);
136    }
137
138    #[test]
139    fn a_tier_that_does_not_exist_is_rejected_by_name() {
140        let error: EnvironmentParseError = "staging"
141            .parse::<Environment>()
142            .expect_err("there is no staging");
143
144        let expected: String =
145            String::from("`staging` is not a supported environment; use `local` or `production`");
146        let actual: String = error.to_string();
147        assert_eq!(expected, actual);
148    }
149
150    #[test]
151    fn the_predicates_agree_with_the_variant() {
152        assert!(Environment::Production.is_production());
153        assert!(!Environment::Production.is_local());
154        assert!(Environment::Local.is_local());
155        assert!(!Environment::Local.is_production());
156    }
157
158    #[test]
159    fn it_serializes_lowercase_for_template_data() {
160        let expected: String = String::from("\"production\"");
161        let actual: String =
162            serde_json::to_string(&Environment::Production).expect("plain enum serializes");
163        assert_eq!(expected, actual);
164    }
165}