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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
mod env;
pub use env::*;

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use url::Url;
use wasmer_backend_api::WasmerClient;

pub static GLOBAL_CONFIG_FILE_NAME: &str = "wasmer.toml";
pub static DEFAULT_PROD_REGISTRY: &str = "https://registry.wasmer.io/graphql";

/// The default value for `$WASMER_DIR`.
pub static DEFAULT_WASMER_DIR: LazyLock<PathBuf> =
    LazyLock::new(|| match WasmerConfig::get_wasmer_dir() {
        Ok(path) => path,
        Err(e) => {
            if let Some(install_prefix) = option_env!("WASMER_INSTALL_PREFIX") {
                return PathBuf::from(install_prefix);
            }

            panic!("Unable to determine the wasmer dir: {e}");
        }
    });

/// The default value for `$WASMER_DIR`.
pub static DEFAULT_WASMER_CACHE_DIR: LazyLock<PathBuf> =
    LazyLock::new(|| DEFAULT_WASMER_DIR.join("cache"));

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
pub struct WasmerConfig {
    /// Whether or not telemetry is enabled.
    #[serde(default)]
    pub telemetry_enabled: bool,

    /// Whether or not updated notifications are enabled.
    #[serde(default)]
    pub update_notifications_enabled: bool,

    /// The registry that wasmer will connect to.
    pub registry: MultiRegistry,

    /// The proxy to use when connecting to the Internet.
    #[serde(default)]
    pub proxy: Proxy,
}

impl Default for WasmerConfig {
    fn default() -> Self {
        Self {
            telemetry_enabled: true,
            update_notifications_enabled: true,
            registry: Default::default(),
            proxy: Default::default(),
        }
    }
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Default)]
pub struct Proxy {
    pub url: Option<String>,
}

/// Struct to store login tokens for multiple registry URLs
/// inside of the wasmer.toml configuration file
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone)]
pub struct MultiRegistry {
    /// Currently active registry
    pub active_registry: String,
    /// Map from "RegistryUrl" to "LoginToken", in order to
    /// be able to be able to easily switch between registries
    pub tokens: Vec<RegistryLogin>,
}

impl Default for MultiRegistry {
    fn default() -> Self {
        MultiRegistry {
            active_registry: format_graphql(DEFAULT_PROD_REGISTRY),
            tokens: Vec::new(),
        }
    }
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone)]
pub struct Registry {
    pub url: String,
    pub token: Option<String>,
}

pub fn format_graphql(registry: &str) -> String {
    if let Ok(mut url) = Url::parse(registry) {
        // Looks like we've got a valid URL. Let's try to use it as-is.
        if url.has_host() {
            if url.path() == "/" {
                // make sure we convert http://registry.wasmer.io/ to
                // http://registry.wasmer.io/graphql
                url.set_path("/graphql");
            }

            return url.to_string();
        }
    }

    if !registry.contains("://") && !registry.contains('/') {
        return endpoint_from_domain_name(registry);
    }

    // looks like we've received something we can't deal with. Just pass it
    // through as-is and hopefully it'll either work or the end user can figure
    // it out
    registry.to_string()
}

/// By convention, something like `"wasmer.io"` should be converted to
/// `"https://registry.wasmer.io/graphql"`.
fn endpoint_from_domain_name(domain_name: &str) -> String {
    if domain_name.contains("localhost") {
        return format!("http://{domain_name}/graphql");
    }

    format!("https://registry.{domain_name}/graphql")
}

async fn test_if_registry_present(registry: &str) -> anyhow::Result<()> {
    let client = WasmerClient::new(url::Url::parse(registry)?, &DEFAULT_WASMER_CLI_USER_AGENT)?;

    wasmer_backend_api::query::current_user(&client)
        .await
        .map(|_| ())
}

#[derive(PartialEq, Eq, Copy, Clone)]
pub enum UpdateRegistry {
    Update,
    #[allow(unused)]
    LeaveAsIs,
}

impl MultiRegistry {
    /// Gets the current (active) registry URL
    pub fn remove_registry(&mut self, registry: &str) {
        let MultiRegistry { tokens, .. } = self;
        tokens.retain(|i| i.registry != registry);
        tokens.retain(|i| i.registry != format_graphql(registry));
    }

    #[allow(unused)]
    pub fn get_graphql_url(&self) -> String {
        self.get_current_registry()
    }

    /// Gets the current (active) registry URL
    pub fn get_current_registry(&self) -> String {
        format_graphql(&self.active_registry)
    }

    /// Checks if the current registry equals `registry`.
    pub fn is_current_registry(&self, registry: &str) -> bool {
        format_graphql(&self.active_registry) == format_graphql(registry)
    }

    #[allow(unused)]
    pub fn current_login(&self) -> Option<&RegistryLogin> {
        self.tokens
            .iter()
            .find(|login| login.registry == self.active_registry)
    }

    /// Sets the current (active) registry URL
    pub async fn set_current_registry(&mut self, registry: &str) {
        let registry = format_graphql(registry);
        if let Err(e) = test_if_registry_present(&registry).await {
            println!("Error when trying to ping registry {registry:?}: {e}");
            println!("WARNING: Registry {registry:?} will be used, but commands may not succeed.");
        }
        self.active_registry = registry;
    }

    /// Returns the login token for the registry
    pub fn get_login_token_for_registry(&self, registry: &str) -> Option<String> {
        let registry_formatted = format_graphql(registry);
        self.tokens
            .iter()
            .filter(|login| login.registry == registry || login.registry == registry_formatted)
            .last()
            .map(|login| login.token.clone())
    }

    /// Sets the login token for the registry URL
    pub fn set_login_token_for_registry(
        &mut self,
        registry: &str,
        token: &str,
        update_current_registry: UpdateRegistry,
    ) {
        let registry_formatted = format_graphql(registry);
        self.tokens
            .retain(|login| !(login.registry == registry || login.registry == registry_formatted));
        self.tokens.push(RegistryLogin {
            registry: format_graphql(registry),
            token: token.to_string(),
        });
        if update_current_registry == UpdateRegistry::Update {
            self.active_registry = format_graphql(registry);
        }
    }
}

impl WasmerConfig {
    /// Save the config to a file
    pub fn save<P: AsRef<Path>>(&self, to: P) -> anyhow::Result<()> {
        use std::{fs::File, io::Write};
        let config_serialized = toml::to_string(&self)?;
        let mut file = File::create(to)?;
        file.write_all(config_serialized.as_bytes())?;
        Ok(())
    }

    pub fn from_file(wasmer_dir: &Path) -> Result<Self, String> {
        let path = Self::get_file_location(wasmer_dir);
        match std::fs::read_to_string(path) {
            Ok(config_toml) => Ok(toml::from_str(&config_toml).unwrap_or_else(|_| Self::default())),
            Err(_e) => Ok(Self::default()),
        }
    }

    /// Creates and returns the `WASMER_DIR` directory (or $HOME/.wasmer as a fallback)
    pub fn get_wasmer_dir() -> Result<PathBuf, String> {
        Ok(
            if let Some(folder_str) = std::env::var("WASMER_DIR").ok().filter(|s| !s.is_empty()) {
                let folder = PathBuf::from(folder_str);
                std::fs::create_dir_all(folder.clone())
                    .map_err(|e| format!("cannot create config directory: {e}"))?;
                folder
            } else {
                let home_dir =
                    dirs::home_dir().ok_or_else(|| "cannot find home directory".to_string())?;
                let mut folder = home_dir;
                folder.push(".wasmer");
                std::fs::create_dir_all(folder.clone())
                    .map_err(|e| format!("cannot create config directory: {e}"))?;
                folder
            },
        )
    }

    #[allow(unused)]
    /// Load the config based on environment variables and default config file locations.
    pub fn from_env() -> Result<Self, anyhow::Error> {
        let dir = Self::get_wasmer_dir()
            .map_err(|err| anyhow::anyhow!("Could not determine wasmer dir: {err}"))?;
        let file_path = Self::get_file_location(&dir);
        Self::from_file(&file_path).map_err(|err| {
            anyhow::anyhow!(
                "Could not load config file at '{}': {}",
                file_path.display(),
                err
            )
        })
    }

    pub fn get_file_location(wasmer_dir: &Path) -> PathBuf {
        wasmer_dir.join(GLOBAL_CONFIG_FILE_NAME)
    }
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone)]
pub struct RegistryLogin {
    /// Registry URL to login to
    pub registry: String,
    /// Login token for the registry
    pub token: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_registries_switch_token() {
        let mut registries = MultiRegistry::default();

        registries
            .set_current_registry("https://registry.wasmer.wtf")
            .await;
        assert_eq!(
            registries.get_current_registry(),
            "https://registry.wasmer.wtf/graphql".to_string()
        );
        registries.set_login_token_for_registry(
            "https://registry.wasmer.io",
            "token1",
            UpdateRegistry::LeaveAsIs,
        );
        assert_eq!(
            registries.get_current_registry(),
            "https://registry.wasmer.wtf/graphql".to_string()
        );
        assert_eq!(
            registries.get_login_token_for_registry(&registries.get_current_registry()),
            None
        );
        registries
            .set_current_registry("https://registry.wasmer.io")
            .await;
        assert_eq!(
            registries.get_login_token_for_registry(&registries.get_current_registry()),
            Some("token1".to_string())
        );
        registries.remove_registry("https://registry.wasmer.io");
        assert_eq!(
            registries.get_login_token_for_registry(&registries.get_current_registry()),
            None
        );
    }

    #[test]
    fn format_registry_urls() {
        let inputs = [
            // Domain names work
            ("wasmer.io", "https://registry.wasmer.io/graphql"),
            ("wasmer.wtf", "https://registry.wasmer.wtf/graphql"),
            // Plain URLs
            (
                "https://registry.wasmer.wtf/graphql",
                "https://registry.wasmer.wtf/graphql",
            ),
            (
                "https://registry.wasmer.wtf/something/else",
                "https://registry.wasmer.wtf/something/else",
            ),
            // We don't automatically prepend the domain name with
            // "registry", but we will make sure "/" gets turned into "/graphql"
            ("https://wasmer.wtf/", "https://wasmer.wtf/graphql"),
            ("https://wasmer.wtf", "https://wasmer.wtf/graphql"),
            // local development
            (
                "http://localhost:8000/graphql",
                "http://localhost:8000/graphql",
            ),
            ("localhost:8000", "http://localhost:8000/graphql"),
        ];

        for (input, expected) in inputs {
            let url = format_graphql(input);
            assert_eq!(url, expected);
        }
    }
}