1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use std::{convert::TryFrom, env::VarError, fs, net::AddrParseError, net::SocketAddr, num::ParseIntError, path::Path, str::FromStr};

use config::{Config, File, FileFormat};
use regex::Regex;
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct GloryConfig {
    /// The name of the WASM and JS files generated by wasm-bindgen. Defaults to the crate name with underscores instead of dashes
    pub output_name: String,
    /// The path of the all the files generated by glory-cli. This defaults to '.' for convenience when integrating with other
    /// tools.
    #[serde(default = "default_site_root")]
    pub site_root: String,
    /// The path of the WASM and JS files generated by wasm-bindgen from the root of your app
    /// By default, wasm-bindgen puts them in `pkg`.
    #[serde(default = "default_site_pkg_dir")]
    pub site_pkg_dir: String,
    /// Provides a way to control the address glory is served from.
    /// Using an env variable here would allow you to run the same code in dev and prod
    /// Defaults to `127.0.0.1:8000`
    #[serde(default = "default_site_addr")]
    pub site_addr: SocketAddr,
    /// The port the Websocket watcher listens on. Should match the `reload_port` in glory-cli(if using).
    /// Defaults to `8001`
    #[serde(default = "default_reload_port")]
    pub reload_port: u32,
    /// The port the Websocket watcher listens on when on the client, e.g., when behind a reverse proxy.
    /// Defaults to match reload_port
    #[serde(default)]
    pub reload_external_port: Option<u32>,
    /// The protocol the Websocket watcher uses on the client: `ws` in most cases, `wss` when behind a reverse https proxy.
    /// Defaults to `ws`
    #[serde(default)]
    pub reload_ws_protocol: ReloadWSProtocol,
    /// The path of a custom 404 Not Found page to display when statically serving content, defaults to `site_root/404.html`
    #[serde(default = "default_not_found_path")]
    pub not_found_path: String,
}

impl Default for GloryConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl GloryConfig {
    pub fn new() -> Self {
        Self::default()
    }

    /// Loads [GloryConfig] from a Cargo.toml with layered overrides. If an env var is specified, like `GLORY_ENV`,
    /// it will override a setting in the file. It takes in an optional path to a Cargo.toml file. If None is provided,
    /// you'll need to set the options as environment variables or rely on the defaults. This is the preferred
    /// approach for glory-cli. If Some("./Cargo.toml") is provided, Glory will read in the settings itself. This
    /// option currently does not allow dashes in file or folder names, as all dashes become underscores
    pub async fn load(path: impl Into<Option<&str>>) -> Result<Self, GloryConfigError> {
        if let Some(path) = path.into() {
            Self::load_from_file(&path).await
        } else {
            Self::load_from_env()
        }
    }

    /// Loads [GloryConfig] from a Cargo.toml with layered overrides. Glory will read in the settings itself. This
    /// option currently does not allow dashes in file or folder names, as all dashes become underscores
    pub async fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self, GloryConfigError> {
        let text = fs::read_to_string(path).map_err(|_| GloryConfigError::ConfigNotFound)?;
        Self::load_from_str(&text)
    }

    /// Loads [GloryConfig] from environment variables or rely on the defaults
    pub fn load_from_env() -> Result<Self, GloryConfigError> {
        Self::try_load_from_env()
    }

    fn try_load_from_env() -> Result<Self, GloryConfigError> {
        let output_name = env_with_default("GLORY_OUTPUT_NAME", std::option_env!("GLORY_OUTPUT_NAME",).unwrap_or_default())?;
        if output_name.is_empty() {
            eprintln!(
                "It looks like you're trying to compile Glory without the \
                 GLORY_OUTPUT_NAME environment variable being set. There are \
                 two options\n 1. glory-cli is not being used, but \
                 get_configuration() is being passed None. This needs to be \
                 changed to Some(\"Cargo.toml\")\n 2. You are compiling \
                 Glory without GLORY_OUTPUT_NAME being set with \
                 glory-cli. This shouldn't be possible!"
            );
        }
        Ok(GloryConfig {
            output_name,
            site_root: env_with_default("GLORY_SITE_ROOT", "target/site")?,
            site_pkg_dir: env_with_default("GLORY_SITE_PKG_DIR", "pkg")?,
            site_addr: env_with_default("GLORY_SITE_ADDR", "127.0.0.1:8000")?.parse()?,
            reload_port: env_with_default("GLORY_RELOAD_PORT", "3001")?.parse()?,
            reload_external_port: match env_without_default("GLORY_RELOAD_EXTERNAL_PORT")? {
                Some(val) => Some(val.parse()?),
                None => None,
            },
            reload_ws_protocol: ws_from_str(env_with_default("GLORY_RELOAD_WS_PROTOCOL", "ws")?.as_str())?,
            not_found_path: env_with_default("GLORY_NOT_FOUND_PATH", "/404")?,
        })
    }

    /// Loads [GloryConfig] from a Cargo.toml text content with layered overrides.
    /// If an env var is specified, like `GLORY_ENV`, it will override a setting in the file.
    pub fn load_from_str(text: &str) -> Result<Self, GloryConfigError> {
        let re: Regex = Regex::new(r"(?m)^\[package.metadata.glory\]").unwrap();
        let re_workspace: Regex = Regex::new(r"(?m)^\[\[workspace.metadata.glory\]\]").unwrap();

        let metadata_name;
        let start;
        match re.find(text) {
            Some(found) => {
                metadata_name = "[package.metadata.glory]";
                start = found.start();
            }
            None => match re_workspace.find(text) {
                Some(found) => {
                    metadata_name = "[[workspace.metadata.glory]]";
                    start = found.start();
                }
                None => return Err(GloryConfigError::ConfigSectionNotFound),
            },
        };

        // so that serde error messages have right line number
        let newlines = text[..start].matches('\n').count();
        let input = "\n".repeat(newlines) + &text[start..];
        let toml = input.replace(metadata_name, "[glory-web-config]");
        let settings = Config::builder()
            // Read the "default" configuration file
            .add_source(File::from_str(&toml, FileFormat::Toml))
            // Layer on the environment-specific values.
            // Add in settings from environment variables (with a prefix of GLORY and '_' as separator)
            // E.g. `GLORY_RELOAD_PORT=5001 would set `GloryConfig.reload_port`
            .add_source(config::Environment::with_prefix("GLORY").separator("_"))
            .build()?;

        settings.try_deserialize().map_err(|e| GloryConfigError::ConfigError(e.to_string()))
    }
}

/// An enum that can be used to define the websocket protocol Glory uses for hotreloading
/// Defaults to `ws`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub enum ReloadWSProtocol {
    WS,
    WSS,
}

impl Default for ReloadWSProtocol {
    fn default() -> Self {
        Self::WS
    }
}

fn ws_from_str(input: &str) -> Result<ReloadWSProtocol, GloryConfigError> {
    let sanitized = input.to_lowercase();
    match sanitized.as_ref() {
        "ws" | "WS" => Ok(ReloadWSProtocol::WS),
        "wss" | "WSS" => Ok(ReloadWSProtocol::WSS),
        _ => Err(GloryConfigError::EnvVarError(format!(
            "{input} is not a supported websocket protocol. Use only `ws` or \
             `wss`.",
        ))),
    }
}

impl FromStr for ReloadWSProtocol {
    type Err = ();
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        ws_from_str(input).or_else(|_| Ok(Self::default()))
    }
}

impl From<&str> for ReloadWSProtocol {
    fn from(str: &str) -> Self {
        ws_from_str(str).unwrap_or_else(|err| panic!("{}", err))
    }
}

impl From<&Result<String, VarError>> for ReloadWSProtocol {
    fn from(input: &Result<String, VarError>) -> Self {
        match input {
            Ok(str) => ws_from_str(str).unwrap_or_else(|err| panic!("{}", err)),
            Err(_) => Self::default(),
        }
    }
}

impl TryFrom<String> for ReloadWSProtocol {
    type Error = GloryConfigError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        ws_from_str(s.as_str())
    }
}

#[derive(Debug, Error, Clone)]
pub enum GloryConfigError {
    #[error("Cargo.toml not found in package root")]
    ConfigNotFound,
    #[error("package.metadata.glory section missing from Cargo.toml")]
    ConfigSectionNotFound,
    #[error("Failed to get Glory Environment. Did you set GLORY_ENV?")]
    EnvError,
    #[error("Config Error: {0}")]
    ConfigError(String),
    #[error("Config Error: {0}")]
    EnvVarError(String),
}
impl From<config::ConfigError> for GloryConfigError {
    fn from(e: config::ConfigError) -> Self {
        Self::ConfigError(e.to_string())
    }
}

impl From<ParseIntError> for GloryConfigError {
    fn from(e: ParseIntError) -> Self {
        Self::ConfigError(e.to_string())
    }
}

impl From<AddrParseError> for GloryConfigError {
    fn from(e: AddrParseError) -> Self {
        Self::ConfigError(e.to_string())
    }
}

fn default_site_root() -> String {
    ".".to_string()
}
fn default_site_pkg_dir() -> String {
    "pkg".to_string()
}
fn default_site_addr() -> SocketAddr {
    SocketAddr::from(([127, 0, 0, 1], 8000))
}
fn default_reload_port() -> u32 {
    8001
}
fn default_not_found_path() -> String {
    "/404".to_string()
}

fn env_with_default(key: &str, default: &str) -> Result<String, GloryConfigError> {
    match std::env::var(key) {
        Ok(val) => Ok(val),
        Err(VarError::NotPresent) => Ok(default.to_string()),
        Err(e) => Err(GloryConfigError::EnvVarError(format!("{key}: {e}"))),
    }
}
fn env_without_default(key: &str) -> Result<Option<String>, GloryConfigError> {
    match std::env::var(key) {
        Ok(val) => Ok(Some(val)),
        Err(VarError::NotPresent) => Ok(None),
        Err(e) => Err(GloryConfigError::EnvVarError(format!("{key}: {e}"))),
    }
}