webserver_base/
environment.rs1use std::fmt::{self, Display, Formatter};
10use std::str::FromStr;
11
12use serde::{Deserialize, Serialize};
13
14use crate::env::{self, EnvError};
15
16pub const ENV_ENVIRONMENT: &str = "WSB_ENVIRONMENT";
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "lowercase")]
22pub enum Environment {
23 Local,
25 Production,
27}
28
29impl Environment {
30 #[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 #[must_use]
41 pub const fn is_production(&self) -> bool {
42 matches!(self, Self::Production)
43 }
44
45 #[must_use]
47 pub const fn is_local(&self) -> bool {
48 matches!(self, Self::Local)
49 }
50
51 pub fn from_env() -> Result<Self, EnvError> {
58 Self::parse_value(env::required(ENV_ENVIRONMENT)?)
59 }
60
61 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#[derive(Debug, thiserror::Error)]
90#[error("`{value}` is not a supported environment; use `local` or `production`")]
91pub struct EnvironmentParseError {
92 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}