railwayapp 4.22.0

Interact with Railway via CLI
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
use super::*;
use crate::{
    consts::TICK_STRING,
    controllers::project::{ensure_project_and_environment_exist, get_project},
    errors::RailwayError,
    queries::project::{
        ProjectProject, ProjectProjectEnvironmentsEdgesNodeVolumeInstancesEdgesNode,
    },
    util::prompt::{fake_select, prompt_confirm_with_default, prompt_options, prompt_text},
};
use anyhow::{anyhow, bail};
use clap::Parser;
use is_terminal::IsTerminal;
use std::{fmt::Display, time::Duration};

/// Manage project volumes
#[derive(Parser)]
pub struct Args {
    #[clap(subcommand)]
    command: Commands,

    /// Service ID
    #[clap(long, short)]
    service: Option<String>,

    /// Environment ID
    #[clap(long, short)]
    environment: Option<String>,
}
structstruck::strike! {
    #[strikethrough[derive(Parser)]]
    enum Commands {
        /// List volumes
        #[clap(alias = "ls")]
        List(struct {
            /// Output in JSON format
            #[clap(long)]
            json: bool,
        }),

        /// Add a new volume
        #[clap(alias = "create")]
        Add(struct {
            /// The mount path of the volume
            #[clap(long, short)]
            mount_path: Option<String>,
        }),

        /// Delete a volume
        #[clap(alias = "remove", alias = "rm")]
        Delete(struct {
            /// The ID/name of the volume you wish to delete
            #[clap(long, short)]
            volume: Option<String>
        }),

        /// Update a volume
        #[clap(alias = "edit")]
        Update(struct {
            /// The ID/name of the volume you wish to update
            #[clap(long, short)]
            volume: Option<String>,

            /// The new mount path of the volume (optional)
            #[clap(long, short)]
            mount_path: Option<String>,

            /// The new name of the volume (optional)
            #[clap(long, short)]
            name: Option<String>,

        }),

        /// Detach a volume from a service
        Detach(struct {
            /// The ID/name of the volume you wish to detach
            #[clap(long, short)]
            volume: Option<String>
        })

        /// Attach a volume to a service
        Attach(struct {
            /// The ID/name of the volume you wish to attach
            #[clap(long, short)]
            volume: Option<String>
        })
    }
}

pub async fn command(args: Args) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;
    let linked_project = configs.get_linked_project().await?;

    ensure_project_and_environment_exist(&client, &configs, &linked_project).await?;

    let project = get_project(&client, &configs, linked_project.project.clone()).await?;
    let service = args.service.or_else(|| linked_project.service.clone());
    let environment = args
        .environment
        .clone()
        .unwrap_or(linked_project.environment.clone());

    match args.command {
        Commands::Add(a) => add(service, environment, a.mount_path, project).await?,
        Commands::List(l) => list(environment, project, l.json).await?,
        Commands::Delete(d) => delete(environment, d.volume, project).await?,
        Commands::Update(u) => update(environment, u.volume, u.mount_path, u.name, project).await?,
        Commands::Detach(d) => detach(environment, d.volume, project).await?,
        Commands::Attach(a) => attach(environment, a.volume, service, project).await?,
    }

    Ok(())
}

async fn attach(
    environment: String,
    volume: Option<String>,
    service: Option<String>,
    project: ProjectProject,
) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;
    let volume = select_volume(project.clone(), environment.as_str(), volume)?.0;
    let service = service.ok_or_else(|| anyhow!("No service found. Please link one via `railway link` or specify one via the `--service` flag."))?;
    let service_name = &project
        .services
        .edges
        .iter()
        .find(|s| s.node.id == service)
        .ok_or_else(|| anyhow!("The service linked/provided doesn't exist"))?
        .node
        .name;
    if volume.service_id.is_some() {
        bail!(
            "Volume {} is already mounted to service {}. Please detach it via `railway volume detach` first.",
            volume.volume.name,
            project
                .services
                .edges
                .iter()
                .find(|a| a.node.id == volume.service_id.clone().unwrap_or_default())
                .ok_or(anyhow!(
                    "The service the volume is attached to doesn't exist"
                ))?
                .node
                .name
        )
    }
    let confirm = prompt_confirm_with_default(
        format!(
            "Are you sure you want to attach the volume {} to service {}?",
            volume.volume.name, service_name
        )
        .as_str(),
        false,
    )?;
    if confirm {
        let p = post_graphql::<mutations::VolumeAttach, _>(
            &client,
            configs.get_backboard(),
            mutations::volume_attach::Variables {
                volume_id: volume.volume.id.clone(),
                service_id: service.clone(),
                environment_id: environment.clone(),
            },
        )
        .await?;

        if p.volume_instance_update {
            println!(
                "Volume \"{}\" attached to service \"{}\"",
                volume.volume.name.blue(),
                service_name.blue()
            );
        } else {
            bail!("Failed to attach volume");
        }
    }

    Ok(())
}

async fn detach(
    environment: String,
    volume: Option<String>,
    project: ProjectProject,
) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;
    let volume = select_volume(project.clone(), environment.as_str(), volume)?.0;

    if volume.service_id.is_none() {
        bail!(
            "Volume {} is not attached to any service",
            volume.volume.name
        );
    }

    let service = project
        .services
        .edges
        .iter()
        .find(|a| a.node.id == volume.service_id.clone().unwrap_or_default())
        .ok_or(anyhow!(
            "The service the volume is attached to doesn't exist"
        ))?;
    let confirm = prompt_confirm_with_default(
        format!(
            "Are you sure you want to detach the volume {} from service {}?",
            volume.volume.name, service.node.name
        )
        .as_str(),
        false,
    )?;
    if confirm {
        let p = post_graphql::<mutations::VolumeDetach, _>(
            &client,
            configs.get_backboard(),
            mutations::volume_detach::Variables {
                volume_id: volume.volume.id.clone(),
                environment_id: environment,
            },
        )
        .await?;
        if p.volume_instance_update {
            println!(
                "Volume \"{}\" detached from service \"{}\"",
                volume.volume.name.blue(),
                service.node.name.blue()
            );
        } else {
            bail!("Failed to detach volume");
        }
    }

    Ok(())
}

async fn update(
    environment: String,
    volume: Option<String>,
    mount_path: Option<String>,
    name: Option<String>,
    project: ProjectProject,
) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;
    let volume = select_volume(project, environment.as_str(), volume)?;

    if mount_path.is_none() && name.is_none() {
        bail!(
            "In order to use the update command, please provide a new mount path or a new name via the flags"
        );
    }

    if let Some(mount_path) = mount_path {
        if !mount_path.starts_with('/') {
            bail!("All mount paths must start with /")
        }
        post_graphql::<mutations::VolumeMountPathUpdate, _>(
            &client,
            configs.get_backboard(),
            mutations::volume_mount_path_update::Variables {
                volume_id: volume.0.volume.id.clone(),
                service_id: volume.0.service_id.clone(),
                environment_id: environment.clone(),
                mount_path: mount_path.clone(),
            },
        )
        .await?;

        println!(
            "Successfully updated the mount path of volume \"{}\" to \"{}\"",
            volume.0.volume.name.blue(),
            mount_path.purple()
        );
    }

    if let Some(name) = name {
        post_graphql::<mutations::VolumeNameUpdate, _>(
            &client,
            configs.get_backboard(),
            mutations::volume_name_update::Variables {
                volume_id: volume.0.volume.id.clone(),
                name: name.clone(),
            },
        )
        .await?;

        println!(
            "Successfully updated the name of volume \"{}\" to \"{}\"",
            volume.0.volume.name.blue(),
            name.purple()
        );
    }

    Ok(())
}

async fn delete(
    environment: String,
    volume: Option<String>,
    project: ProjectProject,
) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;
    let volume = select_volume(project, environment.as_str(), volume)?;

    let confirm = prompt_confirm_with_default(
        format!(
            r#"Are you sure you want to delete the volume "{}"?"#,
            volume.0.volume.name
        )
        .as_str(),
        false,
    )?;
    if confirm {
        let is_two_factor_enabled = {
            let vars = queries::two_factor_info::Variables {};

            let info =
                post_graphql::<queries::TwoFactorInfo, _>(&client, configs.get_backboard(), vars)
                    .await?
                    .two_factor_info;

            info.is_verified
        };

        if is_two_factor_enabled {
            let token = prompt_text("Enter your 2FA code")?;
            let vars = mutations::validate_two_factor::Variables { token };

            let valid = post_graphql::<mutations::ValidateTwoFactor, _>(
                &client,
                configs.get_backboard(),
                vars,
            )
            .await?
            .two_factor_info_validate;

            if !valid {
                return Err(RailwayError::InvalidTwoFactorCode.into());
            }
        }
        let volume_id = volume.0.volume.id.clone();
        let p = post_graphql::<mutations::VolumeDelete, _>(
            &client,
            configs.get_backboard(),
            mutations::volume_delete::Variables { id: volume_id },
        )
        .await?;
        if p.volume_delete {
            println!("Volume \"{}\" deleted", volume.0.volume.name.blue());
        } else {
            bail!("Failed to delete volume");
        }
    }
    Ok(())
}

async fn list(environment: String, project: ProjectProject, json: bool) -> Result<()> {
    let env = project
        .environments
        .edges
        .iter()
        .find(|e| e.node.id == environment)
        .ok_or_else(|| anyhow!("Environment not found"))?;
    let environment_name = env.node.name.clone();

    let volumes = &env.node.volume_instances.edges;

    if volumes.is_empty() {
        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&serde_json::json!({ "volumes": [] }))?
            );
        } else {
            bail!(
                "No volumes found in environment {}",
                environment_name.blue()
            );
        }
    } else if json {
        let volumes_json: Vec<serde_json::Value> = volumes
            .iter()
            .map(|volume_edge| {
                let volume = &volume_edge.node;
                let service_name = project
                    .services
                    .edges
                    .iter()
                    .find(|s| s.node.id == volume.service_id.clone().unwrap_or_default())
                    .map(|s| s.node.name.clone());
                serde_json::json!({
                    "id": volume.volume.id,
                    "name": volume.volume.name,
                    "mountPath": volume.mount_path,
                    "serviceName": service_name,
                    "currentSizeMB": volume.current_size_mb,
                    "sizeMB": volume.size_mb,
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "project": project.name,
                "environment": environment_name,
                "volumes": volumes_json,
            }))?
        );
    } else {
        println!("Project: {}", project.name.cyan().bold());
        println!("Environment: {}", environment_name.cyan().bold());
        for volume_edge in volumes {
            println!();
            let volume = &volume_edge.node;
            println!("Volume: {}", volume.volume.name.green());
            let service = project
                .services
                .edges
                .iter()
                .find(|s| s.node.id == volume.service_id.clone().unwrap_or_default());
            println!(
                "Attached to: {}",
                if let Some(service) = service {
                    service.node.name.purple()
                } else {
                    "N/A".dimmed()
                }
            );
            println!("Mount path: {}", volume.mount_path.yellow());
            println!(
                "Storage used: {}{}/{}{}",
                volume.current_size_mb.round().to_string().blue(),
                "MB".blue(),
                volume.size_mb.to_string().red(),
                "MB".red()
            )
        }
    }
    Ok(())
}

async fn add(
    service: Option<String>,
    environment: String,
    mount: Option<String>,
    project: ProjectProject,
) -> Result<()> {
    let configs = Configs::new()?;
    let client = GQLClient::new_authorized(&configs)?;
    let service = service.ok_or_else(|| anyhow!("No service found. Please link one via `railway link` or specify one via the `--service` flag."))?;
    let mount = if let Some(mount) = mount {
        if mount.starts_with('/') {
            fake_select("Enter the mount path of the volume", mount.as_str());
            mount
        } else {
            bail!("Mount path must start with a `/`")
        }
    } else {
        prompt_text("Enter the mount path of the volume")?
    };

    let service_name = project
        .services
        .edges
        .iter()
        .find(|s| s.node.id == service)
        .map(|s| s.node.name.clone())
        .unwrap();
    let environment_name = project
        .environments
        .edges
        .iter()
        .find(|e| e.node.id == environment)
        .map(|e| e.node.name.clone())
        .unwrap();

    // check if there is a volume already mounted on the service in that environment
    let env = project
        .environments
        .edges
        .iter()
        .find(|e| e.node.id == environment)
        .ok_or_else(|| anyhow!("Environment not found"))?;
    if env
        .node
        .volume_instances
        .edges
        .iter()
        .any(|a| a.node.service_id == Some(service.clone()))
    {
        bail!(
            "A volume is already mounted on service {} in environment {}",
            service_name.blue(),
            environment_name.blue()
        );
    }
    let volume = mutations::volume_create::Variables {
        service_id: service.clone(),
        environment_id: environment.clone(),
        mount_path: mount.clone(),
        project_id: project.id,
    };
    if std::io::stdout().is_terminal() {
        let spinner = indicatif::ProgressBar::new_spinner()
            .with_style(
                indicatif::ProgressStyle::default_spinner()
                    .tick_chars(TICK_STRING)
                    .template("{spinner:.green} {msg}")?,
            )
            .with_message("Creating volume..");
        spinner.enable_steady_tick(Duration::from_millis(100));

        let details =
            post_graphql::<mutations::VolumeCreate, _>(&client, configs.get_backboard(), volume)
                .await?;

        spinner.finish_with_message(format!(
            "Volume \"{}\" created for service {} in environment {} at mount path \"{}\"",
            details.volume_create.name.blue(),
            service_name.blue(),
            environment_name.blue(),
            mount.cyan().bold()
        ));
    } else {
        println!("Creating volume..");
        let details =
            post_graphql::<mutations::VolumeCreate, _>(&client, configs.get_backboard(), volume)
                .await?;

        println!(
            "Volume \"{}\" created for service {} in environment {} at mount path \"{}\"",
            details.volume_create.name.blue(),
            service_name.blue(),
            environment_name.blue(),
            mount.cyan().bold()
        );
    }

    Ok(())
}

fn select_volume(
    project: ProjectProject,
    environment: &str,
    volume: Option<String>,
) -> Result<Volume, anyhow::Error> {
    let env = project
        .environments
        .edges
        .iter()
        .find(|e| e.node.id == environment)
        .ok_or_else(|| anyhow!("Environment not found"))?;
    let volumes: Vec<Volume> = env
        .node
        .volume_instances
        .edges
        .iter()
        .map(|a| Volume(a.node.clone()))
        .collect();
    let volume = if let Some(vol) = volume {
        let norm_vol = volumes.iter().find(|v| {
            (v.0.volume.name.to_lowercase() == vol.to_lowercase())
                || (v.0.volume.id.to_lowercase() == vol.to_lowercase())
        });
        if let Some(volume) = norm_vol {
            fake_select("Select a volume", &volume.0.volume.name);
            volume.clone()
        } else {
            return Err(RailwayError::VolumeNotFound(vol).into());
        }
    } else {
        // prompt
        let volume = prompt_options("Select a volume", volumes)?;
        volume.clone()
    };
    Ok(volume)
}

#[derive(Debug, Clone)]
struct Volume(ProjectProjectEnvironmentsEdgesNodeVolumeInstancesEdgesNode);

impl Display for Volume {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.volume.name)
    }
}