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
use super::utils::Secret;
use crate::{
    commands::{app::util::AppIdentFlag, AsyncCliCommand},
    config::WasmerEnv,
};
use anyhow::Context;
use colored::Colorize;
use dialoguer::theme::ColorfulTheme;
use is_terminal::IsTerminal;
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
};
use wasmer_backend_api::WasmerClient;

/// Update an existing app secret.
#[derive(clap::Parser, Debug)]
pub struct CmdAppSecretsUpdate {
    /* --- Common args --- */
    #[clap(flatten)]
    pub env: WasmerEnv,

    /// Don't print any message.
    #[clap(long)]
    pub quiet: bool,

    /// Do not prompt for user input.
    #[clap(long, default_value_t = !std::io::stdin().is_terminal())]
    pub non_interactive: bool,

    /* --- Flags --- */
    /// The path to the directory where the config file for the application will be written to.
    #[clap(long = "app-dir", conflicts_with = "app")]
    pub app_dir_path: Option<PathBuf>,

    #[clap(flatten)]
    pub app_id: AppIdentFlag,

    /// Path to a file with secrets stored in JSON format to update secrets from.
    #[clap(
        long,
        name = "from-file",
        conflicts_with = "value",
        conflicts_with = "name"
    )]
    pub from_file: Option<PathBuf>,

    /// Whether or not to redeploy the app after creating the secrets.
    #[clap(long)]
    pub redeploy: bool,

    /* --- Parameters --- */
    /// The name of the secret to update.
    #[clap(name = "name")]
    pub secret_name: Option<String>,

    /// The value of the secret to update.
    #[clap(name = "value")]
    pub secret_value: Option<String>,
}

impl CmdAppSecretsUpdate {
    fn get_secret_name(&self) -> anyhow::Result<String> {
        if let Some(name) = &self.secret_name {
            return Ok(name.clone());
        }

        if self.non_interactive {
            anyhow::bail!("No secret name given. Provide one as a positional argument.")
        } else {
            let theme = ColorfulTheme::default();
            Ok(dialoguer::Input::with_theme(&theme)
                .with_prompt("Enter the name of the secret:")
                .interact_text()?)
        }
    }

    fn get_secret_value(&self) -> anyhow::Result<String> {
        if let Some(value) = &self.secret_value {
            return Ok(value.clone());
        }

        if self.non_interactive {
            anyhow::bail!("No secret value given. Provide one as a positional argument.")
        } else {
            let theme = ColorfulTheme::default();
            Ok(dialoguer::Input::with_theme(&theme)
                .with_prompt("Enter the value of the secret:")
                .interact_text()?)
        }
    }

    /// Given a list of secrets, checks if the given secrets already exist for the given app and
    /// returns a list of secrets that must be upserted.
    async fn filter_secrets(
        &self,
        client: &WasmerClient,
        app_id: &str,
        secrets: Vec<Secret>,
    ) -> anyhow::Result<Vec<Secret>> {
        let names = secrets.iter().map(|s| &s.name);
        let app_secrets =
            wasmer_backend_api::query::get_all_app_secrets_filtered(client, app_id, names).await?;
        let sset = HashSet::<&str>::from_iter(app_secrets.iter().map(|s| s.name.as_str()));

        let mut ret = vec![];

        for secret in secrets {
            if !sset.contains(secret.name.as_str()) {
                if self.non_interactive {
                    anyhow::bail!("Cannot update secret '{}' in app {app_id} as it does not exist yet. Use the `create` command instead.", secret.name.bold());
                } else {
                    eprintln!(
                        "Secret '{}' does not exist for the selected app.",
                        secret.name.bold()
                    );
                    let theme = ColorfulTheme::default();
                    let res = dialoguer::Confirm::with_theme(&theme)
                        .with_prompt("Do you want to create it?")
                        .interact()?;

                    if !res {
                        eprintln!("Cannot update secret '{}' as it does not exist yet. Use the `create` command instead.", secret.name.bold());
                    }
                }
            }

            ret.push(secret);
        }

        Ok(ret)
    }
    async fn update(
        &self,
        client: &WasmerClient,
        app_id: &str,
        secrets: Vec<Secret>,
    ) -> Result<(), anyhow::Error> {
        let res = wasmer_backend_api::query::upsert_app_secrets(
            client,
            app_id,
            secrets.iter().map(|s| (s.name.as_str(), s.value.as_str())),
        )
        .await?;
        let res = res.context(
            "Backend did not return any payload to confirm the successful update of the secret!",
        )?;

        if !res.success {
            anyhow::bail!("Secret creation failed!")
        } else {
            if !self.quiet {
                eprintln!("Succesfully updated secret(s):");
                for secret in &secrets {
                    eprintln!("{}", secret.name.bold());
                }

                let should_redeploy = self.redeploy || {
                    if !self.non_interactive && self.from_file.is_some() {
                        let theme = ColorfulTheme::default();
                        dialoguer::Confirm::with_theme(&theme)
                            .with_prompt("Do you want to redeploy your app?")
                            .interact()?
                    } else {
                        false
                    }
                };

                if should_redeploy {
                    wasmer_backend_api::query::redeploy_app_by_id(client, app_id).await?;
                    eprintln!("{} Deployment complete", "ð–¥”".yellow().bold());
                } else {
                    eprintln!(
                        "{}: In order for secrets to appear in your app, re-deploy it.",
                        "Info".bold()
                    );
                }
            }

            Ok(())
        }
    }

    async fn update_from_file(
        &self,
        client: &WasmerClient,
        path: &Path,
        app_id: &str,
    ) -> anyhow::Result<(), anyhow::Error> {
        let secrets = super::utils::read_secrets_from_file(path).await?;

        let secrets = self.filter_secrets(client, app_id, secrets).await?;
        self.update(client, app_id, secrets).await?;

        Ok(())
    }
}

#[async_trait::async_trait]
impl AsyncCliCommand for CmdAppSecretsUpdate {
    type Output = ();

    async fn run_async(self) -> Result<Self::Output, anyhow::Error> {
        let client = self.env.client()?;
        let app_id = super::utils::get_app_id(
            &client,
            self.app_id.app.as_ref(),
            self.app_dir_path.as_ref(),
            self.quiet,
            self.non_interactive,
        )
        .await?;

        if let Some(file) = &self.from_file {
            self.update_from_file(&client, file, &app_id).await
        } else {
            let name = self.get_secret_name()?;
            let value = self.get_secret_value()?;
            let secret = Secret { name, value };
            self.update(&client, &app_id, vec![secret]).await
        }
    }
}