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
pub mod create;
pub mod get;
pub mod list;
pub mod logs;

use std::{io::Write, time::Duration};

use anyhow::{bail, Context};
use wasmer_api::backend::{
    gql::{DeployApp, DeployAppVersion},
    BackendClient,
};
use wasmer_deploy_schema::schema::AppConfigV1;

use crate::cmd::AsyncCliCommand;

/// Manage Wasmer Deploy apps.
#[derive(clap::Subcommand, Debug)]
pub enum CmdApp {
    Get(get::CmdAppGet),
    Info(get::CmdAppInfo),
    List(list::CmdAppList),
    Logs(logs::CmdAppLogs),
    Create(create::CmdAppCreate),
    // CreateStaticSite(create::static_site::CmdCreateStaticSite),
}

impl AsyncCliCommand for CmdApp {
    fn run_async(self) -> futures::future::BoxFuture<'static, Result<(), anyhow::Error>> {
        match self {
            Self::Get(cmd) => cmd.run_async(),
            Self::Info(cmd) => cmd.run_async(),
            Self::Create(cmd) => cmd.run_async(),
            Self::List(cmd) => cmd.run_async(),
            Self::Logs(cmd) => cmd.run_async(),
            // Self::CreateStaticSite(cmd) => cmd.run_async(),
        }
    }
}

pub struct DeployAppOpts<'a> {
    pub app: &'a AppConfigV1,
    pub allow_create: bool,
    pub make_default: bool,
    pub owner: Option<String>,
    pub wait: WaitMode,
}

pub async fn deploy_app(
    client: &BackendClient,
    opts: DeployAppOpts<'_>,
) -> Result<DeployAppVersion, anyhow::Error> {
    let app = opts.app;
    let mut raw_config = app.clone().to_yaml()?.trim().to_string();
    raw_config.push('\n');

    // TODO: respect allow_create flag

    let version = wasmer_api::backend::publish_deploy_app(
        client,
        wasmer_api::backend::gql::PublishDeployAppVars {
            config: raw_config,
            name: app.name.clone().into(),
            owner: opts.owner.map(|o| o.into()),
            make_default: Some(opts.make_default),
        },
    )
    .await
    .context("could not create app in the backend")?;

    Ok(version)
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum WaitMode {
    /// Wait for the app to be deployed.
    Deployed,
    /// Wait for the app to be deployed and ready.
    Reachable,
}

/// Same as [Self::deploy], but also prints verbose information.
pub async fn deploy_app_verbose(
    client: &BackendClient,
    mut opts: DeployAppOpts<'_>,
) -> Result<(DeployApp, DeployAppVersion), anyhow::Error> {
    let owner = &opts.owner;
    let app = &opts.app;

    let pretty_name = if let Some(owner) = &owner {
        format!("{}/{}", owner, app.name)
    } else {
        app.name.clone()
    };

    let make_default = opts.make_default;

    eprintln!("Deploying app {pretty_name}...\n");

    let (owner, app_opt) = if let Some(owner) = owner {
        (Some(owner.clone()), None)
    } else if let Some(id) = &app.app_id {
        let app = wasmer_api::backend::get_app_by_id(client, id.clone())
            .await
            .context("could not fetch app from backend")?;

        (Some(app.owner.global_name.clone()), Some(app))
    } else {
        (None, None)
    };

    opts.owner = owner;

    let wait = opts.wait;
    let version = deploy_app(client, opts).await?;

    let app_id = version
        .app
        .as_ref()
        .context("app field on app version is empty")?
        .id
        .inner()
        .to_string();

    let app = if let Some(app) = app_opt {
        app
    } else {
        wasmer_api::backend::get_app_by_id(client, app_id.clone())
            .await
            .context("could not fetch app from backend")?
    };

    eprintln!(" ✅ App {pretty_name} was successfully deployed!");
    eprintln!();
    eprintln!("> App URL: {}", app.url);
    eprintln!("> Versioned URL: {}", version.url);
    eprintln!("> Admin dashboard: {}", app.admin_url);

    match wait {
        WaitMode::Deployed => {}
        WaitMode::Reachable => {
            eprintln!();
            eprintln!("Waiting for new deployment to become available...");
            eprintln!("(You can safely stop waiting now with CTRL-C)");

            let stderr = std::io::stderr();

            tokio::time::sleep(Duration::from_secs(2)).await;

            let start = tokio::time::Instant::now();
            let client = reqwest::Client::new();

            let check_url = if make_default { &app.url } else { &version.url };

            let mut sleep_millis: u64 = 1_000;
            loop {
                let total_elapsed = start.elapsed();
                if total_elapsed > Duration::from_secs(60 * 5) {
                    eprintln!();
                    bail!("\nApp still not reachable after 5 minutes...");
                }

                {
                    let mut lock = stderr.lock();
                    write!(&mut lock, ".").unwrap();
                    lock.flush().unwrap();
                }

                let request_start = tokio::time::Instant::now();

                match client.get(check_url).send().await {
                    Ok(res) => {
                        let header = res
                            .headers()
                            .get(wasmer_deploy_util::headers::HEADER_APP_VERSION_ID)
                            .and_then(|x| x.to_str().ok())
                            .unwrap_or_default();

                        if header == version.id.inner() {
                            eprintln!("\nNew version is now reachable at {check_url}");
                            eprintln!("Deployment complete");
                            break;
                        }

                        tracing::debug!(
                            current=%header,
                            expected=%app.active_version.id.inner(),
                            "app is not at the right version yet",
                        );
                    }
                    Err(err) => {
                        tracing::debug!(?err, "health check request failed");
                    }
                };

                let elapsed: u64 = request_start
                    .elapsed()
                    .as_millis()
                    .try_into()
                    .unwrap_or_default();
                let to_sleep = Duration::from_millis(sleep_millis.saturating_sub(elapsed));
                tokio::time::sleep(to_sleep).await;
                sleep_millis = (sleep_millis * 2).max(10_000);
            }
        }
    }

    Ok((app, version))
}

pub fn app_config_from_api(version: &DeployAppVersion) -> Result<AppConfigV1, anyhow::Error> {
    let app_id = version
        .app
        .as_ref()
        .context("app field on app version is empty")?
        .id
        .inner()
        .to_string();

    let cfg = &version.user_yaml_config;
    let mut cfg = AppConfigV1::parse_yaml(cfg)
        .context("could not parse app config from backend app version")?;

    cfg.app_id = Some(app_id);
    Ok(cfg)
}