railwayapp 5.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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use colored::ColoredString;
use serde::Serialize;

use crate::commands::output::fields::{print_field, print_service_environment_context};
use crate::controllers::{
    outbound_networking::{self, FeatureAction, Ipv6Status, StaticIpStatus},
    project::{ServiceContext, resolve_service_context},
};

use super::*;

const FIELD_LABEL_WIDTH: usize = 20;
const STAGED_IPV6_MESSAGE: &str =
    "Commit staged environment changes to trigger redeploy: railway environment edit";

/// Manage outbound networking for a service
#[derive(Parser)]
#[clap(
    after_help = "Examples:\n\n  railway outbound-network status --service api\n  railway outbound-network static-ip enable --service api\n  railway outbound-network static-ip status --service api --json\n  railway outbound-network static-ip disable --service api\n  railway outbound-network ipv6 enable --service api\n  railway outbound-network ipv6 status --service api --json\n  railway outbound-network ipv6 disable --service api\n\nAutomation notes:\n  Static Outbound IP changes require a redeploy before outbound traffic changes.\n  Outbound IPv6 changes are staged; commit them with `railway environment edit` to trigger redeploy."
)]
pub struct Args {
    #[clap(subcommand)]
    command: Commands,

    /// Service name or ID (defaults to linked service)
    #[clap(short, long, global = true)]
    service: Option<String>,

    /// Environment to use (defaults to linked environment)
    #[clap(short, long, global = true)]
    environment: Option<String>,

    /// Project ID to use (defaults to linked project)
    #[clap(short = 'p', long, value_name = "PROJECT_ID", global = true)]
    project: Option<String>,

    /// Output in JSON format
    #[clap(long, global = true)]
    json: bool,
}

#[derive(Parser)]
enum Commands {
    /// Show outbound networking status
    Status,

    /// Manage Static Outbound IPs
    #[clap(name = "static-ip")]
    StaticIp(StaticIpArgs),

    /// Manage Outbound IPv6
    Ipv6(Ipv6Args),
}

#[derive(Parser)]
struct StaticIpArgs {
    #[clap(subcommand)]
    command: StaticIpCommands,
}

#[derive(Parser)]
enum StaticIpCommands {
    /// Show Static Outbound IP status
    Status,

    /// Enable Static Outbound IPs
    Enable,

    /// Disable Static Outbound IPs
    Disable,
}

#[derive(Parser)]
struct Ipv6Args {
    #[clap(subcommand)]
    command: Ipv6Commands,
}

#[derive(Parser)]
enum Ipv6Commands {
    /// Show Outbound IPv6 status
    Status,

    /// Stage enabling Outbound IPv6
    Enable,

    /// Stage disabling Outbound IPv6
    Disable,
}

pub async fn command(args: Args) -> Result<()> {
    let Args {
        command,
        service,
        environment,
        project,
        json,
    } = args;

    crate::util::reporter::set_mode(json);

    match command {
        Commands::Status => status(project, service, environment, json).await?,
        Commands::StaticIp(args) => match args.command {
            StaticIpCommands::Status => {
                static_ip_status(project, service, environment, json).await?
            }
            StaticIpCommands::Enable => {
                static_ip_enable(project, service, environment, json).await?
            }
            StaticIpCommands::Disable => {
                static_ip_disable(project, service, environment, json).await?
            }
        },
        Commands::Ipv6(args) => match args.command {
            Ipv6Commands::Status => ipv6_status(project, service, environment, json).await?,
            Ipv6Commands::Enable => ipv6_stage(project, service, environment, true, json).await?,
            Ipv6Commands::Disable => ipv6_stage(project, service, environment, false, json).await?,
        },
    }

    Ok(())
}

async fn status(
    project: Option<String>,
    service: Option<String>,
    environment: Option<String>,
    json: bool,
) -> Result<()> {
    let ctx = resolve_service_context(project, service, environment).await?;
    let (static_ip, ipv6) = tokio::try_join!(
        outbound_networking::fetch_static_ip_status(
            &ctx.client,
            &ctx.configs,
            &ctx.environment_id,
            &ctx.service_id,
        ),
        outbound_networking::fetch_ipv6_status(
            &ctx.client,
            &ctx.configs,
            &ctx.environment_id,
            &ctx.service_id,
        )
    )?;
    let output = OutboundNetworkingOutput::new(&ctx, static_ip, ipv6);

    if json {
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        print_outbound_networking_status(&output);
    }

    Ok(())
}

async fn static_ip_status(
    project: Option<String>,
    service: Option<String>,
    environment: Option<String>,
    json: bool,
) -> Result<()> {
    let ctx = resolve_service_context(project, service, environment).await?;
    let static_ip = outbound_networking::fetch_static_ip_status(
        &ctx.client,
        &ctx.configs,
        &ctx.environment_id,
        &ctx.service_id,
    )
    .await?;
    let output = StaticIpStatusOutput::new(&ctx, static_ip);

    if json {
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        print_static_ip_status(&output);
    }

    Ok(())
}

async fn static_ip_enable(
    project: Option<String>,
    service: Option<String>,
    environment: Option<String>,
    json: bool,
) -> Result<()> {
    let ctx = resolve_service_context(project, service, environment).await?;
    let (static_ip, action) = outbound_networking::enable_static_ips(
        &ctx.client,
        &ctx.configs,
        &ctx.environment_id,
        &ctx.service_id,
    )
    .await?;
    let output = StaticIpActionOutput::new(&ctx, action, static_ip);

    if json {
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        print_static_ip_action(&output);
    }

    Ok(())
}

async fn static_ip_disable(
    project: Option<String>,
    service: Option<String>,
    environment: Option<String>,
    json: bool,
) -> Result<()> {
    let ctx = resolve_service_context(project, service, environment).await?;
    let (static_ip, action) = outbound_networking::disable_static_ips(
        &ctx.client,
        &ctx.configs,
        &ctx.environment_id,
        &ctx.service_id,
    )
    .await?;
    let output = StaticIpActionOutput::new(&ctx, action, static_ip);

    if json {
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        print_static_ip_action(&output);
    }

    Ok(())
}

async fn ipv6_status(
    project: Option<String>,
    service: Option<String>,
    environment: Option<String>,
    json: bool,
) -> Result<()> {
    let ctx = resolve_service_context(project, service, environment).await?;
    let ipv6 = outbound_networking::fetch_ipv6_status(
        &ctx.client,
        &ctx.configs,
        &ctx.environment_id,
        &ctx.service_id,
    )
    .await?;
    let output = Ipv6StatusOutput::new(&ctx, ipv6);

    if json {
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        print_ipv6_status(&output);
    }

    Ok(())
}

async fn ipv6_stage(
    project: Option<String>,
    service: Option<String>,
    environment: Option<String>,
    value: bool,
    json: bool,
) -> Result<()> {
    let ctx = resolve_service_context(project, service, environment).await?;
    let (ipv6, action) = outbound_networking::stage_ipv6(
        &ctx.client,
        &ctx.configs,
        &ctx.environment_id,
        &ctx.service_id,
        value,
    )
    .await?;
    let output = Ipv6ActionOutput::new(&ctx, action, ipv6);

    if json {
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        print_ipv6_action(&output);
    }

    Ok(())
}

fn print_outbound_networking_status(output: &OutboundNetworkingOutput) {
    println!("{}", "Outbound networking".bold());
    println!();
    print_service_environment_context(
        &output.service.name,
        &output.environment.name,
        FIELD_LABEL_WIDTH,
    );
    println!();
    print_static_ip_fields(&output.static_ip);
    println!();
    print_ipv6_fields(&output.ipv6);
}

fn print_static_ip_status(output: &StaticIpStatusOutput) {
    println!("{}", "Static Outbound IPs".bold());
    println!();
    print_service_environment_context(
        &output.service.name,
        &output.environment.name,
        FIELD_LABEL_WIDTH,
    );
    println!();
    print_static_ip_fields(&output.static_ip);
}

fn print_ipv6_status(output: &Ipv6StatusOutput) {
    println!("{}", "Outbound IPv6".bold());
    println!();
    print_service_environment_context(
        &output.service.name,
        &output.environment.name,
        FIELD_LABEL_WIDTH,
    );
    println!();
    print_ipv6_fields(&output.ipv6);
}

fn print_static_ip_action(output: &StaticIpActionOutput) {
    if !output.changed {
        println!(
            "Static Outbound IPs are already {} for service {} in environment {}.",
            if output.enabled {
                "enabled"
            } else {
                "disabled"
            },
            output.service.name.bold(),
            output.environment.name.bold()
        );
        return;
    }

    println!(
        "{} Static Outbound IPs for service {} in environment {}.",
        past_tense(output.action.action),
        output.service.name.bold(),
        output.environment.name.bold()
    );
    if output.lifecycle.redeploy_required {
        println!(
            "Redeploy required before outbound traffic {} these IPs.",
            if output.enabled {
                "uses"
            } else {
                "stops using"
            }
        );
    }
    if output.enabled {
        println!();
        print_static_ip_table(&output.static_ip);
    }
}

fn print_ipv6_action(output: &Ipv6ActionOutput) {
    if !output.changed {
        if output.ipv6.pending_value == Some(output.enabled) {
            println!(
                "Outbound IPv6 is already staged to be {} for service {} in environment {}.",
                if output.enabled {
                    "enabled"
                } else {
                    "disabled"
                },
                output.service.name.bold(),
                output.environment.name.bold()
            );
        } else {
            println!(
                "Outbound IPv6 is already {} for service {} in environment {}.",
                if output.enabled {
                    "enabled"
                } else {
                    "disabled"
                },
                output.service.name.bold(),
                output.environment.name.bold()
            );
        }
        return;
    }

    if output.lifecycle.staged {
        if output.enabled {
            println!(
                "Staged Outbound IPv6 for service {} in environment {}.",
                output.service.name.bold(),
                output.environment.name.bold()
            );
        } else {
            println!(
                "Staged disabling Outbound IPv6 for service {} in environment {}.",
                output.service.name.bold(),
                output.environment.name.bold()
            );
        }
        println!("{STAGED_IPV6_MESSAGE}");
    } else {
        println!(
            "Cleared staged Outbound IPv6 change for service {} in environment {}.",
            output.service.name.bold(),
            output.environment.name.bold()
        );
    }
}

fn print_static_ip_fields(static_ip: &StaticIpStatus) {
    print_field(
        "Static IPs:",
        &status_label(static_ip.enabled),
        FIELD_LABEL_WIDTH,
    );
    if static_ip.enabled && static_ip.high_availability {
        print_field(
            "High Availability:",
            &"enabled".green().bold(),
            FIELD_LABEL_WIDTH,
        );
    }
    if static_ip.enabled {
        println!();
        print_static_ip_table(static_ip);
    }
}

fn print_ipv6_fields(ipv6: &Ipv6Status) {
    print_field(
        "Outbound IPv6:",
        &status_label(ipv6.enabled),
        FIELD_LABEL_WIDTH,
    );
    if let Some(value) = ipv6.pending_value {
        print_field(
            "Pending:",
            &(if value { "enable" } else { "disable" })
                .to_string()
                .yellow(),
            FIELD_LABEL_WIDTH,
        );
        print_field("Message:", &STAGED_IPV6_MESSAGE, FIELD_LABEL_WIDTH);
    }
}

fn print_static_ip_table(static_ip: &StaticIpStatus) {
    if static_ip.ips.is_empty() {
        return;
    }

    let ip_width = static_ip
        .ips
        .iter()
        .map(|ip| ip.ipv4.len())
        .max()
        .unwrap_or("IP Address".len())
        .max("IP Address".len())
        + 3;
    let region_width = static_ip
        .ips
        .iter()
        .map(|ip| ip.region.len())
        .max()
        .unwrap_or("Region".len())
        .max("Region".len())
        + 3;

    println!(
        "{:<ip_width$}{:<region_width$}Type",
        "IP Address".bold(),
        "Region".bold(),
        ip_width = ip_width,
        region_width = region_width
    );
    for ip in &static_ip.ips {
        println!(
            "{:<ip_width$}{:<region_width$}Shared",
            ip.ipv4,
            ip.region,
            ip_width = ip_width,
            region_width = region_width
        );
    }
}

fn status_label(enabled: bool) -> ColoredString {
    if enabled {
        "enabled".green().bold()
    } else {
        "disabled".yellow().bold()
    }
}

fn past_tense(action: &str) -> &'static str {
    match action {
        "enable" => "Enabled",
        "disable" => "Disabled",
        _ => "Updated",
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ResourceRef {
    id: String,
    name: String,
}

impl ResourceRef {
    fn service(ctx: &ServiceContext) -> Self {
        Self {
            id: ctx.service_id.clone(),
            name: ctx.service_name.clone(),
        }
    }

    fn environment(ctx: &ServiceContext) -> Self {
        Self {
            id: ctx.environment_id.clone(),
            name: ctx.environment_name.clone(),
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct OutboundNetworkingOutput {
    service: ResourceRef,
    environment: ResourceRef,
    static_ip: StaticIpStatus,
    ipv6: Ipv6Status,
}

impl OutboundNetworkingOutput {
    fn new(ctx: &ServiceContext, static_ip: StaticIpStatus, ipv6: Ipv6Status) -> Self {
        Self {
            service: ResourceRef::service(ctx),
            environment: ResourceRef::environment(ctx),
            static_ip,
            ipv6,
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct StaticIpStatusOutput {
    service: ResourceRef,
    environment: ResourceRef,
    static_ip: StaticIpStatus,
}

impl StaticIpStatusOutput {
    fn new(ctx: &ServiceContext, static_ip: StaticIpStatus) -> Self {
        Self {
            service: ResourceRef::service(ctx),
            environment: ResourceRef::environment(ctx),
            static_ip,
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Ipv6StatusOutput {
    service: ResourceRef,
    environment: ResourceRef,
    ipv6: Ipv6Status,
}

impl Ipv6StatusOutput {
    fn new(ctx: &ServiceContext, ipv6: Ipv6Status) -> Self {
        Self {
            service: ResourceRef::service(ctx),
            environment: ResourceRef::environment(ctx),
            ipv6,
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct StaticIpActionOutput {
    service: ResourceRef,
    environment: ResourceRef,
    #[serde(flatten)]
    action: FeatureAction,
    static_ip: StaticIpStatus,
}

impl StaticIpActionOutput {
    fn new(ctx: &ServiceContext, action: FeatureAction, static_ip: StaticIpStatus) -> Self {
        Self {
            service: ResourceRef::service(ctx),
            environment: ResourceRef::environment(ctx),
            action,
            static_ip,
        }
    }
}

impl std::ops::Deref for StaticIpActionOutput {
    type Target = FeatureAction;

    fn deref(&self) -> &Self::Target {
        &self.action
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Ipv6ActionOutput {
    service: ResourceRef,
    environment: ResourceRef,
    #[serde(flatten)]
    action: FeatureAction,
    ipv6: Ipv6Status,
}

impl Ipv6ActionOutput {
    fn new(ctx: &ServiceContext, action: FeatureAction, ipv6: Ipv6Status) -> Self {
        Self {
            service: ResourceRef::service(ctx),
            environment: ResourceRef::environment(ctx),
            action,
            ipv6,
        }
    }
}

impl std::ops::Deref for Ipv6ActionOutput {
    type Target = FeatureAction;

    fn deref(&self) -> &Self::Target {
        &self.action
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::controllers::outbound_networking::Lifecycle;
    use clap::Parser;

    #[test]
    fn parses_subcommands() {
        assert!(matches!(
            Args::parse_from(["outbound-network", "status"]).command,
            Commands::Status
        ));
        assert!(matches!(
            Args::parse_from(["outbound-network", "static-ip", "status"]).command,
            Commands::StaticIp(StaticIpArgs {
                command: StaticIpCommands::Status
            })
        ));
        assert!(matches!(
            Args::parse_from(["outbound-network", "static-ip", "enable"]).command,
            Commands::StaticIp(StaticIpArgs {
                command: StaticIpCommands::Enable
            })
        ));
        assert!(matches!(
            Args::parse_from(["outbound-network", "static-ip", "disable"]).command,
            Commands::StaticIp(StaticIpArgs {
                command: StaticIpCommands::Disable
            })
        ));
        assert!(matches!(
            Args::parse_from(["outbound-network", "ipv6", "enable"]).command,
            Commands::Ipv6(Ipv6Args {
                command: Ipv6Commands::Enable
            })
        ));
        assert!(matches!(
            Args::parse_from([
                "outbound-network",
                "--service",
                "api",
                "--environment",
                "production",
                "--project",
                "project-id",
                "--json",
                "ipv6",
                "disable"
            ])
            .command,
            Commands::Ipv6(Ipv6Args {
                command: Ipv6Commands::Disable
            })
        ));
    }

    #[test]
    fn action_output_has_lifecycle_shape() {
        let output = serde_json::json!({
            "feature": "staticIp",
            "action": "enable",
            "enabled": true,
            "changed": true,
            "lifecycle": Lifecycle::direct(true),
        });

        assert_eq!(output["lifecycle"]["mode"], "direct");
        assert_eq!(output["lifecycle"]["staged"], false);
        assert_eq!(output["lifecycle"]["committed"], true);
        assert_eq!(output["lifecycle"]["redeployRequired"], true);
        assert_eq!(output["lifecycle"]["redeployTriggered"], false);

        let output = serde_json::json!({
            "feature": "ipv6",
            "action": "enable",
            "enabled": true,
            "changed": true,
            "lifecycle": Lifecycle::environment_patch(true),
        });

        assert_eq!(output["lifecycle"]["mode"], "environmentPatch");
        assert_eq!(output["lifecycle"]["staged"], true);
        assert_eq!(output["lifecycle"]["committed"], false);
        assert_eq!(output["lifecycle"]["redeployRequired"], false);
        assert_eq!(output["lifecycle"]["redeployTriggered"], false);
    }
}