wash-cli 0.29.1

wasmCloud Shell (wash) CLI tool
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::{bail, Context};
use clap::{Args, Subcommand};
use serde_json::json;
use wadm_client::Result;
use wadm_types::api::ModelSummary;
use wadm_types::validation::{validate_manifest_file, ValidationFailure, ValidationOutput};
use wash_lib::app::{load_app_manifest, AppManifest};
use wash_lib::cli::{CliConnectionOpts, CommandOutput, OutputKind};
use wash_lib::config::WashConnectionOptions;

use crate::appearance::spinner::Spinner;

mod output;

#[derive(Debug, Clone, Subcommand)]
pub enum AppCliCommand {
    /// List all applications available within the lattice
    #[clap(name = "list")]
    List(ListCommand),
    /// Get the application manifest for a specific version of an application
    #[clap(name = "get")]
    Get(GetCommand),
    /// Get the current status of a given application
    #[clap(name = "status")]
    Status(StatusCommand),
    /// Get the version history of a given application
    #[clap(name = "history")]
    History(HistoryCommand),
    /// Delete an application version
    #[clap(name = "delete", alias = "del")]
    Delete(DeleteCommand),
    /// Create an application version by putting the manifest into the wadm store
    #[clap(name = "put")]
    Put(PutCommand),
    /// Deploy an application to the lattice
    #[clap(name = "deploy")]
    Deploy(DeployCommand),
    /// Undeploy an application, removing it from the lattice
    #[clap(name = "undeploy")]
    Undeploy(UndeployCommand),
    /// Validate an application manifest
    #[clap(name = "validate")]
    Validate(ValidateCommand),
}

#[derive(Args, Debug, Clone)]
pub struct ListCommand {
    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct UndeployCommand {
    /// Name of the application to undeploy
    #[clap(name = "name")]
    app_name: String,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct DeployCommand {
    /// Name of the application to deploy, if it was already `put`, or a path to a file containing the application manifest
    #[clap(name = "application")]
    app_name: Option<String>,

    /// Version of the application to deploy, defaults to the latest created version
    #[clap(name = "version")]
    version: Option<String>,

    /// Whether or not wash should attempt to replace the resources by performing an optimistic delete shortly before applying resources.
    #[clap(long = "replace")]
    replace: bool,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct DeleteCommand {
    /// Name of the application to delete, or a path to a Wadm Application Manifest
    #[clap(name = "name")]
    app_name: String,

    /// Version of the application to delete. If not supplied, all versions are deleted
    #[clap(name = "version")]
    version: Option<String>,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct PutCommand {
    /// The source of the application manifest, either a file path, remote file http url, or stdin. If no source is provided (or arg marches '-'), stdin is used.
    source: Option<String>,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct GetCommand {
    /// The name of the application to retrieve
    #[clap(name = "name")]
    app_name: String,

    /// The version of the application to retrieve. If left empty, retrieves the latest version
    #[clap(name = "version")]
    version: Option<String>,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct StatusCommand {
    /// The name of the application
    #[clap(name = "name")]
    app_name: String,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct HistoryCommand {
    /// The name of the application
    #[clap(name = "name")]
    app_name: String,

    #[clap(flatten)]
    opts: CliConnectionOpts,
}

#[derive(Args, Debug, Clone)]
pub struct ValidateCommand {
    /// Path to the application manifest to validate
    #[clap(name = "application")]
    application: PathBuf,
}

pub async fn handle_command(
    command: AppCliCommand,
    output_kind: OutputKind,
) -> anyhow::Result<CommandOutput> {
    use AppCliCommand::*;
    let sp: Spinner = Spinner::new(&output_kind)?;
    let out: CommandOutput = match command {
        List(cmd) => {
            sp.update_spinner_message("Listing applications ...".to_string());
            get_applications(cmd).await?
        }
        Get(cmd) => {
            sp.update_spinner_message("Getting application manifest ... ".to_string());
            get_manifest(cmd).await?
        }
        Status(cmd) => {
            sp.update_spinner_message("Getting application status ... ".to_string());
            get_model_status(cmd).await?
        }
        History(cmd) => {
            sp.update_spinner_message("Getting application version history ... ".to_string());
            get_application_versions(cmd).await?
        }
        Delete(cmd) => {
            sp.update_spinner_message("Deleting application version ... ".to_string());
            delete_application_version(cmd).await?
        }
        Put(cmd) => {
            sp.update_spinner_message("Creating application version ... ".to_string());
            put_model(cmd).await?
        }
        Deploy(cmd) => {
            sp.update_spinner_message("Deploying application ... ".to_string());
            deploy_model(cmd).await?
        }
        Undeploy(cmd) => {
            sp.update_spinner_message("Undeploying application ... ".to_string());
            undeploy_model(cmd).await?
        }
        Validate(cmd) => {
            sp.update_spinner_message("Validating application manifest ... ".to_string());
            let (_manifest, validation_results) = validate_manifest_file(&cmd.application)
                .await
                .context("failed to validate Wadm manifest")?;
            show_validate_manifest_results(validation_results)
        }
    };
    sp.finish_and_clear();

    Ok(out)
}

async fn undeploy_model(cmd: UndeployCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    // If we have received a valid path to a model file, then read and extract the model name,
    // otherwise use the supplied name as a model name
    let model_name = if tokio::fs::try_exists(&cmd.app_name)
        .await
        .is_ok_and(|exists| exists)
    {
        let manifest = load_app_manifest(cmd.app_name.parse()?)
            .await
            .with_context(|| format!("failed to load app manifest at [{}]", cmd.app_name))?;
        manifest
            .name()
            .map(ToString::to_string)
            .context("failed to find name of manifest")?
    } else {
        cmd.app_name
    };

    wash_lib::app::undeploy_model(&client, lattice, &model_name).await?;

    let message = format!("Undeployed application: {}", model_name);
    let mut map = HashMap::new();
    map.insert("results".to_string(), json!(message));
    Ok(CommandOutput::new(message, map))
}

async fn deploy_model(cmd: DeployCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    let app_manifest = match cmd.app_name {
        Some(source) => load_app_manifest(source.parse()?).await?,
        None => load_app_manifest("-".parse()?).await?,
    };

    // If --replace was specified, we should attempt to replace the resources by deleting them beforehand
    if cmd.replace {
        if let (Some(name), version) = (
            app_manifest.name(),
            app_manifest.version().map(ToString::to_string),
        ) {
            if let Err(e) =
                wash_lib::app::delete_model_version(&client, lattice.clone(), name, version).await
            {
                eprintln!("🟨 Failed to delete model during replace operation: {e}");
            }
        }
    }

    deploy_model_from_manifest(&client, lattice, app_manifest, cmd.version).await
}

pub(crate) async fn deploy_model_from_manifest(
    client: &async_nats::Client,
    lattice: Option<String>,
    manifest: AppManifest,
    version: Option<String>,
) -> Result<CommandOutput> {
    let (name, version) = match manifest {
        AppManifest::SerializedModel(manifest) => {
            wash_lib::app::put_and_deploy_model(
                client,
                lattice,
                serde_yaml::to_string(&manifest)
                    .context("failed to convert manifest to string")?
                    .as_ref(),
            )
            .await
        }
        AppManifest::ModelName(model_name) => {
            wash_lib::app::deploy_model(client, lattice, &model_name, version.clone())
                .await
                .map(|_| (model_name.to_string(), version.unwrap_or_default()))
        }
    }?;

    let mut map = HashMap::new();
    map.insert("deployed".to_string(), json!(true));
    map.insert("model_name".to_string(), json!(name));
    map.insert("model_version".to_string(), json!(version));
    Ok(CommandOutput::new(
        format!("Deployed application \"{name}\", version \"{version}\""),
        map,
    ))
}

async fn put_model(cmd: PutCommand) -> anyhow::Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    let app_manifest = match &cmd.source {
        Some(source) => load_app_manifest(source.parse()?).await?,
        None => load_app_manifest("-".parse()?).await?,
    };

    let (name, version) = match app_manifest {
        AppManifest::SerializedModel(manifest) => wash_lib::app::put_model(
            &client,
            lattice,
            serde_yaml::to_string(&manifest)
                .context("failed to convert manifest to string")?
                .as_ref(),
        )
        .await
        .map_err(|e| anyhow::anyhow!(e)),
        AppManifest::ModelName(_) => {
            bail!("failed to retrieve manifest at `{:?}`", cmd.source)
        }
    }?;

    let mut map = HashMap::new();
    map.insert("deployed".to_string(), json!(true));
    map.insert("model_name".to_string(), json!(name));
    map.insert("model_version".to_string(), json!(version));
    Ok(CommandOutput::new(
        format!("Put application \"{name}\", version \"{version}\""),
        map,
    ))
}

async fn get_application_versions(cmd: HistoryCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    let versions = wash_lib::app::get_model_history(&client, lattice, &cmd.app_name).await?;
    let mut map = HashMap::new();
    map.insert("revisions".to_string(), json!(versions));
    Ok(CommandOutput::new(
        output::list_revisions_table(versions),
        map,
    ))
}

async fn get_model_status(cmd: StatusCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    let status = wash_lib::app::get_model_status(&client, lattice, &cmd.app_name).await?;

    let mut map = HashMap::new();
    map.insert("status".to_string(), json!(status));
    Ok(CommandOutput::new(
        output::status_table(cmd.app_name, status),
        map,
    ))
}

async fn get_manifest(cmd: GetCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    let manifest =
        wash_lib::app::get_model_details(&client, lattice, &cmd.app_name, cmd.version).await?;

    let mut map = HashMap::new();
    map.insert("application".to_string(), json!(manifest));
    let yaml = serde_yaml::to_string(&manifest).unwrap();
    Ok(CommandOutput::new(yaml, map))
}

async fn delete_application_version(cmd: DeleteCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;

    // If we have received a valid path to a model file, then read and extract the model name,
    // otherwise use the supplied name as a model name
    let (model_name, version): (String, Option<String>) = if tokio::fs::try_exists(&cmd.app_name)
        .await
        .is_ok_and(|exists| exists)
    {
        let manifest = load_app_manifest(cmd.app_name.parse()?)
            .await
            .with_context(|| format!("failed to load app manifest at [{}]", cmd.app_name))?;
        (
            manifest
                .name()
                .map(ToString::to_string)
                .context("failed to find name of manifest")?,
            manifest.version().map(ToString::to_string),
        )
    } else {
        (cmd.app_name, cmd.version)
    };

    let deleted =
        wash_lib::app::delete_model_version(&client, lattice, &model_name, version).await?;

    let mut map = HashMap::new();
    map.insert("deleted".to_string(), json!(deleted));
    let message = if deleted {
        format!("Deleted application version: {model_name}")
    } else {
        format!("Already deleted application version: {model_name}")
    };
    Ok(CommandOutput::new(message, map))
}

async fn get_applications(cmd: ListCommand) -> Result<CommandOutput> {
    let connection_opts =
        <CliConnectionOpts as TryInto<WashConnectionOptions>>::try_into(cmd.opts)?;
    let lattice = Some(connection_opts.get_lattice());

    let client = connection_opts.into_nats_client().await?;
    let models = wash_lib::app::get_models(&client, lattice).await?;

    let mut map = HashMap::new();
    map.insert("applications".to_string(), json!(models));
    Ok(CommandOutput::new(output::list_models_table(models), map))
}

fn show_validate_manifest_results(messages: impl AsRef<[ValidationFailure]>) -> CommandOutput {
    let messages = messages.as_ref();
    let valid = messages.valid();
    let warnings = messages
        .warnings()
        .into_iter()
        .cloned()
        .collect::<Vec<ValidationFailure>>();
    let errors = messages
        .errors()
        .into_iter()
        .cloned()
        .collect::<Vec<ValidationFailure>>();
    let message = if valid {
        "manifest is valid".into()
    } else {
        format!(
            r#"invalid manifest:
warnings: {warnings:#?}
errors: {errors:#?}
"#
        )
    };
    let json_output = HashMap::<String, serde_json::Value>::from([
        ("valid".into(), messages.valid().into()),
        ("warnings".into(), json!(warnings)),
        ("errors".into(), json!(errors)),
    ]);
    CommandOutput::new(message, json_output)
}