fundaia 0.7.2

Command line for the Fundaia deployment platform: projects, services, variables, deployments, logs and metrics
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
mod api;
mod commands;
mod config;
mod render;
mod update;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use owo_colors::OwoColorize;

use api::client::ApiClient;
use config::Config;
use render::theme;

/// The command line for the Fundaia deployment platform.
///
/// Shaped around the two questions a deployment platform actually gets asked —
/// *what is the state of things* and *make this change* — rather than around
/// the REST endpoints underneath. `status` answers the first for the whole
/// instance in one screen; `deploy` answers the second and then stays to show
/// the pipeline, which is the one thing a terminal does better than a browser
/// tab you have to keep switching to.
#[derive(Parser)]
#[command(
    name = "fundaia",
    version,
    about = "Proyectos, servicios, variables, despliegues, registros y métricas",
    long_about = None,
    propagate_version = true
)]
struct Cli {
    /// Which configured instance to talk to.
    #[arg(long, short, global = true, env = "FUNDAIA_PROFILE")]
    profile: Option<String>,

    /// Override the address, without saving it. Useful in CI.
    #[arg(long, global = true, env = "FUNDAIA_URL")]
    url: Option<String>,

    /// Override the token, without saving it. Useful in CI.
    #[arg(long, global = true, env = "FUNDAIA_TOKEN", hide_env_values = true)]
    token: Option<String>,

    /// Never colour the output, whatever the terminal says.
    #[arg(long, global = true)]
    no_color: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Authorise this terminal through the browser.
    Login {
        /// The instance to sign in to.
        #[arg(long, default_value = "https://infrastructure.fundaia.com")]
        url: String,

        /// The name to save it under.
        #[arg(long, default_value = "default")]
        as_profile: String,

        /// Print the address instead of opening it.
        #[arg(long)]
        no_browser: bool,
    },

    /// Forget a profile on this machine.
    Logout {
        #[arg(long)]
        profile: Option<String>,
    },

    /// Replace this binary with the newest published release.
    ///
    /// Rarely needed: every command already checks once a day and installs what
    /// it finds. This is the same work without waiting for that, and the way to
    /// see what happened when the automatic one stayed quiet.
    Upgrade {
        /// Only say whether there is a newer one.
        #[arg(long)]
        check: bool,
    },

    /// Who this terminal is signed in as.
    Whoami,

    /// Everything, in one screen.
    Status,

    /// Projects on this instance.
    Projects,

    /// Make one, rename one, archive one, or hand one to another space.
    Project {
        #[command(subcommand)]
        command: ProjectCommand,
    },

    /// Services in a project.
    Services { project: String },

    /// One service in detail.
    Service { project: String, service: String },

    /// Create a service.
    New {
        project: String,
        name: String,

        /// A GitHub repository, as `owner/name`.
        #[arg(long)]
        repo: Option<String>,

        /// A container image.
        #[arg(long)]
        image: Option<String>,

        /// A component from the catalogue: a database, a bucket or Claude Code.
        /// `fundaia templates` lists the ones this account may add.
        #[arg(long)]
        template: Option<String>,

        #[arg(long, default_value = "main")]
        branch: String,

        /// Services it should be able to talk to, by name.
        #[arg(long = "connect-to", value_delimiter = ',')]
        connect_to: Vec<String>,
    },

    /// The components on offer: databases, storage and Claude Code.
    ///
    /// What it lists is what *this account* may add. An instance offers some
    /// components to its owner only, and they are absent rather than shown and
    /// refused.
    Templates,

    /// Deploy a service, and watch the pipeline.
    Deploy {
        project: String,
        service: String,

        /// Reuse the current image instead of building.
        #[arg(long)]
        restart: bool,

        /// Start it and return, without watching.
        #[arg(long)]
        detach: bool,
    },

    /// Put a previous deployment back, by its number.
    Rollback {
        project: String,
        service: String,
        /// The number shown by `history`.
        number: u32,
    },

    /// Put a service to sleep. The next request wakes it.
    Stop { project: String, service: String },

    /// The deployments of a service, newest first.
    History {
        project: String,
        service: String,

        #[arg(long, default_value_t = 15)]
        limit: usize,
    },

    /// Follow what the platform is doing, live.
    ///
    /// The terminal half of the notices the web interface shows: a deployment
    /// somebody else started, a push that deployed on its own, a variable that
    /// changed under you. With no arguments it is everything this account can
    /// reach; name a project — or a project and a service — to narrow it.
    Watch {
        project: Option<String>,
        service: Option<String>,
    },

    /// A service's log.
    Logs {
        project: String,
        service: String,

        /// Follow the live output.
        #[arg(long, short)]
        follow: bool,

        #[arg(long, short = 'n', default_value_t = 200)]
        tail: usize,

        /// Only one stream: build, deploy, runtime or system.
        #[arg(long)]
        stream: Option<String>,

        /// Which deployment, by the number `history` shows. The newest by default.
        #[arg(long)]
        deployment: Option<u32>,

        /// Prefix each line with the time the platform recorded it.
        #[arg(long, short = 't')]
        timestamps: bool,
    },

    /// CPU and memory, now and over a window.
    Metrics {
        project: String,
        service: String,

        #[arg(long, default_value_t = 60)]
        minutes: u32,
    },

    /// A service's environment variables.
    #[command(alias = "vars")]
    Variables {
        #[command(subcommand)]
        command: VariableCommand,
    },

    /// Copies of a service's volume, and putting one back.
    #[command(alias = "backup")]
    Backups {
        #[command(subcommand)]
        command: BackupCommand,
    },

    /// Hostnames a service answers on.
    Domains {
        #[command(subcommand)]
        command: DomainCommand,
    },

    /// Wire one service to another.
    Connect {
        project: String,
        /// The service that will read the variables.
        service: String,
        /// The service it should be able to reach.
        provider: String,
    },

    /// Undo a connection: the consumer stops reading the provider's variables.
    Disconnect {
        project: String,
        /// The service that was reading the variables.
        service: String,
        /// The one it was reading them from.
        provider: String,
    },

    /// What a service could be connected to.
    Connectable { project: String, service: String },

    /// Directories that outlive the container.
    Volumes {
        #[command(subcommand)]
        command: VolumeCommand,
    },

    /// The Containerfile a service builds with.
    Recipe {
        #[command(subcommand)]
        command: RecipeCommand,
    },

    /// The shared spaces this account belongs to.
    #[command(alias = "workspaces")]
    Workspace {
        #[command(subcommand)]
        command: WorkspaceCommand,
    },

    /// How much of the machine is left.
    Capacity,

    /// Change a service's settings. Only what you pass is touched.
    Settings {
        project: String,
        service: String,

        /// Memory ceiling, in MB.
        #[arg(long)]
        memory: Option<u32>,

        /// How many containers to run behind the one hostname.
        #[arg(long)]
        replicas: Option<u32>,

        /// Which directory of the repository this service is, in a monorepo.
        #[arg(long)]
        root: Option<String>,

        /// What to run instead of the image's own entrypoint.
        #[arg(long = "start-command")]
        start_command: Option<String>,

        /// The path a deployment is considered live once it answers. Empty
        /// means the port opening is proof enough — what a database needs.
        #[arg(long = "health-path")]
        health_path: Option<String>,

        /// `always`, `on-failure` or `no`.
        #[arg(long = "restart")]
        restart_policy: Option<String>,

        /// Sleep when no traffic arrives, and wake on the next request.
        #[arg(long)]
        sleep: Option<bool>,

        /// Deploy on its own when the branch moves.
        #[arg(long = "auto-deploy")]
        auto_deploy: Option<bool>,

        /// Let the gateway hold this service's answers.
        #[arg(long = "cache")]
        cache_enabled: Option<bool>,

        /// How long a cached answer stays fresh, in seconds.
        #[arg(long = "cache-ttl")]
        cache_ttl_seconds: Option<u32>,
    },

    /// Publish a service on the internet, or take it off.
    ///
    /// Every service is always reachable inside its project by name; this is
    /// only about the hostname on top. A database behind an API wants none.
    Expose {
        project: String,
        service: String,

        /// Take it off the internet. Its domains are removed.
        #[arg(long)]
        off: bool,
    },

    /// Encryption at rest for a storage service's buckets.
    Encrypt {
        project: String,
        service: String,

        /// Turn it off instead. What is already encrypted stays encrypted.
        #[arg(long)]
        off: bool,
    },

    /// Remove a service and everything under it.
    Delete {
        project: String,
        service: String,

        /// The service's own name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },
}

/// Sharing a space, from a terminal.
///
/// The workspace is optional everywhere: most people are in one, and making
/// them name it on every call would be ceremony. Given, it takes an id, a slug
/// or the name shown on screen, the same as a project does.
#[derive(Subcommand)]
enum WorkspaceCommand {
    /// The spaces you are in.
    List,

    /// Who shares a space, and who has been invited to.
    #[command(alias = "who")]
    Members { workspace: Option<String> },

    /// Invite somebody by email.
    Invite {
        email: String,

        #[arg(long)]
        workspace: Option<String>,

        /// Let them invite others too.
        #[arg(long)]
        admin: bool,
    },

    /// Withdraw an invitation that has not been accepted.
    Revoke {
        /// The id shown by `members`.
        invitation_id: String,

        #[arg(long)]
        workspace: Option<String>,
    },

    /// Remove somebody from the space.
    Remove {
        /// The user id shown by `members`.
        user_id: String,

        #[arg(long)]
        workspace: Option<String>,
    },
}

/// A project is where everything else hangs from, so this is the first command
/// somebody runs on a new instance and was the one thing the tool could not do.
#[derive(Subcommand)]
enum ProjectCommand {
    /// Create one.
    New {
        name: String,

        #[arg(long)]
        description: Option<String>,

        /// Which shared space it belongs to. Yours, if you say nothing.
        #[arg(long)]
        workspace: Option<String>,
    },

    /// Change its name, its description, or both.
    Rename {
        project: String,
        /// The new name. Leave it out to only change the description.
        name: Option<String>,

        #[arg(long)]
        description: Option<String>,
    },

    /// Archive it, with everything under it.
    Archive {
        project: String,

        /// The project's own name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Hand it to another shared space, which is the whole of sharing it.
    Move { project: String, workspace: String },
}

#[derive(Subcommand)]
enum VolumeCommand {
    List {
        project: String,
        service: String,
    },

    /// Attach one. Nothing is deployed: it is inside the container from the
    /// next deployment on.
    Add {
        project: String,
        service: String,
        /// Where it is mounted, as an absolute path: `/data`.
        mount_path: String,
    },

    /// Take one off, by the id `list` shows.
    Remove {
        volume_id: String,
    },
}

#[derive(Subcommand)]
enum RecipeCommand {
    /// Print it, with what generated it.
    Show {
        project: String,
        service: String,

        /// Only the Containerfile, so it can be redirected into one.
        #[arg(long)]
        plain: bool,
    },

    /// Replace it. From then on it is never regenerated.
    Edit {
        project: String,
        service: String,

        /// The file to send, or `-` for standard input.
        #[arg(long, default_value = "-")]
        file: String,
    },
}

#[derive(Subcommand)]
enum VariableCommand {
    /// List them.
    List {
        project: String,
        service: String,

        /// Decrypt the secrets. Each one is recorded on the server.
        #[arg(long)]
        reveal: bool,
    },

    /// Set one.
    Set {
        project: String,
        service: String,
        key: String,
        value: String,

        /// Store it encrypted, and never show it again.
        #[arg(long)]
        secret: bool,

        /// Seal it on the way in: unreadable and unchangeable from the start.
        #[arg(long)]
        sealed: bool,
    },

    /// Seal one: the container keeps receiving it, nobody can read or change it.
    Seal {
        project: String,
        service: String,
        key: String,

        /// The key again. Sealing cannot be undone.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Remove one.
    Unset {
        project: String,
        service: String,
        key: String,
    },

    /// Read a `.env` and set every variable in it, in one request.
    Import {
        project: String,
        service: String,

        /// The file to read, or `-` for standard input.
        file: String,

        /// Store them all encrypted.
        #[arg(long)]
        secret: bool,
    },
}

#[derive(Subcommand)]
enum BackupCommand {
    /// List them, with the schedule and when the next one lands.
    List { project: String, service: String },

    /// Take one now. Waits for it.
    New { project: String, service: String },

    /// Which schedules run: daily, weekly, monthly. With none, it stops copying.
    Schedule {
        project: String,
        service: String,

        /// Any of `daily`, `weekly`, `monthly`, comma separated.
        #[arg(value_delimiter = ',')]
        schedules: Vec<String>,
    },

    /// Put one back. Overwrites the volume; the server copies it first.
    Restore {
        /// The id `backups list` shows.
        backup_id: String,

        /// The id again. This overwrites data.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Keep one past its retention.
    Keep { backup_id: String },

    /// Let retention have it again.
    Unkeep { backup_id: String },

    /// Delete one now.
    Remove { backup_id: String },
}

#[derive(Subcommand)]
enum DomainCommand {
    List {
        project: String,
        service: String,
    },

    /// Add one. With no host, generates one under the platform's domain.
    Add {
        project: String,
        service: String,
        host: Option<String>,
    },

    Remove {
        domain_id: String,
    },
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    if cli.no_color {
        owo_colors::set_override(false);
    }

    // Started before the command and collected after it, so asking crates.io
    // overlaps the work rather than being added to it. Every command talks to a
    // server, so in practice the answer is already in by the time it is read.
    let update = update::UpdateCheck::start(env!("CARGO_PKG_VERSION"));
    let outcome = run(cli).await;
    update.finish().await;

    if let Err(error) = outcome {
        // One line, on stderr, so a failure never lands in a pipe as data.
        eprintln!();
        eprintln!("  {} {error}", theme::CROSS.style(theme::danger()));

        // The chain is where the useful part usually is: "could not reach X"
        // over "connection refused" says both what was attempted and why not.
        for cause in error.chain().skip(1) {
            eprintln!("    {}", cause.style(theme::muted()));
        }

        if let Some(hint) = hint_for(&error) {
            eprintln!("    {}", hint.style(theme::muted()));
        }

        eprintln!();
        std::process::exit(1);
    }
}

/// What to try next, for the failures where there is an obvious answer.
///
/// Keyed on the server's own error code rather than on the message, because the
/// message is written for a person and is allowed to be reworded.
fn hint_for(error: &anyhow::Error) -> Option<&'static str> {
    let api = error.downcast_ref::<api::client::ApiError>()?;

    match api.code.as_str() {
        "unauthorized" => Some("Ejecuta `fundaia login` para volver a entrar."),
        "rate_limited" => Some("Demasiadas peticiones seguidas: espera un minuto."),
        "conflict" => Some("Ya hay algo con ese nombre, o hay un despliegue en curso."),
        _ => None,
    }
}

async fn run(cli: Cli) -> Result<()> {
    match &cli.command {
        Command::Login {
            url,
            as_profile,
            no_browser,
        } => return commands::login::run(url, as_profile, !no_browser).await,
        Command::Logout { profile } => return commands::login::logout(profile.as_deref()),
        // Nothing here needs an instance, a profile or a token: the registry
        // and the release are the only two things it talks to.
        Command::Upgrade { check } => {
            return update::upgrade(env!("CARGO_PKG_VERSION"), *check).await
        }
        _ => {}
    }

    let client = connect(&cli)?;

    match cli.command {
        Command::Login { .. } | Command::Logout { .. } | Command::Upgrade { .. } => {
            unreachable!("handled above")
        }

        Command::Whoami => {
            let identity = client.whoami().await?;
            match identity {
                Some(principal) => println!(
                    "  {} en {}",
                    principal.display_name.style(theme::strong()),
                    client.base().style(theme::muted()),
                ),
                None => println!("  No hay sesión."),
            }
            Ok(())
        }

        Command::Status => commands::read::status(&client).await,
        Command::Projects => commands::read::projects(&client).await,

        Command::Project { command } => match command {
            ProjectCommand::New {
                name,
                description,
                workspace,
            } => {
                commands::write::create_project(
                    &client,
                    &name,
                    description.as_deref(),
                    workspace.as_deref(),
                )
                .await
            }
            ProjectCommand::Rename {
                project,
                name,
                description,
            } => {
                commands::manage::rename_project(
                    &client,
                    &project,
                    name.as_deref(),
                    description.as_deref(),
                )
                .await
            }
            ProjectCommand::Archive { project, confirm } => {
                commands::manage::archive_project(&client, &project, confirm.as_deref()).await
            }
            ProjectCommand::Move { project, workspace } => {
                commands::manage::move_project(&client, &project, &workspace).await
            }
        },
        Command::Services { project } => commands::read::services(&client, &project).await,
        Command::Service { project, service } => {
            commands::read::service(&client, &project, &service).await
        }
        Command::Templates => commands::write::templates(&client).await,

        Command::New {
            project,
            name,
            repo,
            image,
            template,
            branch,
            connect_to,
        } => {
            commands::write::create_service(
                &client,
                commands::write::ServiceRequest {
                    project: &project,
                    name: &name,
                    repo: repo.as_deref(),
                    image: image.as_deref(),
                    template: template.as_deref(),
                    branch: &branch,
                    connect_to: &connect_to,
                },
            )
            .await
        }

        Command::Deploy {
            project,
            service,
            restart,
            detach,
        } => commands::deploy::run(&client, &project, &service, restart, !detach).await,

        Command::Rollback {
            project,
            service,
            number,
        } => commands::deploy::rollback(&client, &project, &service, number).await,

        Command::Stop { project, service } => {
            commands::write::stop(&client, &project, &service).await
        }

        Command::History {
            project,
            service,
            limit,
        } => commands::read::history(&client, &project, &service, limit).await,

        Command::Watch { project, service } => {
            commands::watch::run(&client, project.as_deref(), service.as_deref()).await
        }

        Command::Logs {
            project,
            service,
            follow,
            tail,
            stream,
            deployment,
            timestamps,
        } => {
            commands::logs::run(
                &client,
                &project,
                &service,
                commands::logs::LogQuery {
                    follow,
                    tail,
                    stream_filter: stream.as_deref(),
                    number: deployment,
                    timestamps,
                },
            )
            .await
        }

        Command::Metrics {
            project,
            service,
            minutes,
        } => commands::read::metrics(&client, &project, &service, minutes).await,

        Command::Variables { command } => match command {
            VariableCommand::List {
                project,
                service,
                reveal,
            } => commands::read::variables(&client, &project, &service, reveal).await,
            VariableCommand::Set {
                project,
                service,
                key,
                value,
                secret,
                sealed,
            } => {
                commands::write::set_variable(
                    &client, &project, &service, &key, &value, secret, sealed,
                )
                .await
            }
            VariableCommand::Seal {
                project,
                service,
                key,
                confirm,
            } => {
                commands::write::seal_variable(
                    &client,
                    &project,
                    &service,
                    &key,
                    confirm.as_deref(),
                )
                .await
            }
            VariableCommand::Unset {
                project,
                service,
                key,
            } => commands::write::unset_variable(&client, &project, &service, &key).await,
            VariableCommand::Import {
                project,
                service,
                file,
                secret,
            } => {
                commands::write::import_variables(&client, &project, &service, &file, secret).await
            }
        },

        Command::Backups { command } => match command {
            BackupCommand::List { project, service } => {
                commands::read::backups(&client, &project, &service).await
            }
            BackupCommand::New { project, service } => {
                commands::write::take_backup(&client, &project, &service).await
            }
            BackupCommand::Schedule {
                project,
                service,
                schedules,
            } => commands::write::schedule_backups(&client, &project, &service, &schedules).await,
            BackupCommand::Restore { backup_id, confirm } => {
                commands::write::restore_backup(&client, &backup_id, confirm.as_deref()).await
            }
            BackupCommand::Keep { backup_id } => {
                commands::write::lock_backup(&client, &backup_id, true).await
            }
            BackupCommand::Unkeep { backup_id } => {
                commands::write::lock_backup(&client, &backup_id, false).await
            }
            BackupCommand::Remove { backup_id } => {
                commands::write::delete_backup(&client, &backup_id).await
            }
        },

        Command::Domains { command } => match command {
            DomainCommand::List { project, service } => {
                commands::read::domains(&client, &project, &service).await
            }
            DomainCommand::Add {
                project,
                service,
                host,
            } => commands::write::add_domain(&client, &project, &service, host.as_deref()).await,
            DomainCommand::Remove { domain_id } => {
                commands::write::remove_domain(&client, &domain_id).await
            }
        },

        Command::Connect {
            project,
            service,
            provider,
        } => commands::write::connect(&client, &project, &service, &provider).await,

        Command::Disconnect {
            project,
            service,
            provider,
        } => commands::manage::disconnect(&client, &project, &service, &provider).await,

        Command::Connectable { project, service } => {
            commands::write::candidates(&client, &project, &service).await
        }

        Command::Volumes { command } => match command {
            VolumeCommand::List { project, service } => {
                commands::read::volumes(&client, &project, &service).await
            }
            VolumeCommand::Add {
                project,
                service,
                mount_path,
            } => commands::write::attach_volume(&client, &project, &service, &mount_path).await,
            VolumeCommand::Remove { volume_id } => {
                commands::manage::detach_volume(&client, &volume_id).await
            }
        },

        Command::Recipe { command } => match command {
            RecipeCommand::Show {
                project,
                service,
                plain,
            } => commands::read::recipe(&client, &project, &service, plain).await,
            RecipeCommand::Edit {
                project,
                service,
                file,
            } => commands::write::edit_recipe(&client, &project, &service, &file).await,
        },

        Command::Capacity => commands::manage::capacity(&client).await,

        Command::Settings {
            project,
            service,
            memory,
            replicas,
            root,
            start_command,
            health_path,
            restart_policy,
            sleep,
            auto_deploy,
            cache_enabled,
            cache_ttl_seconds,
        } => {
            commands::manage::set_settings(
                &client,
                &project,
                &service,
                api::models::SettingsPatch {
                    memory_mb: memory,
                    replicas,
                    root_directory: root,
                    start_command,
                    health_path,
                    restart_policy,
                    sleep_enabled: sleep,
                    auto_deploy,
                    cache_enabled,
                    cache_ttl_seconds,
                },
            )
            .await
        }

        Command::Expose {
            project,
            service,
            off,
        } => commands::manage::expose(&client, &project, &service, !off).await,

        Command::Encrypt {
            project,
            service,
            off,
        } => commands::manage::encryption(&client, &project, &service, !off).await,

        Command::Delete {
            project,
            service,
            confirm,
        } => commands::manage::delete(&client, &project, &service, confirm.as_deref()).await,

        Command::Workspace { command } => match command {
            WorkspaceCommand::List => commands::workspace::list(&client).await,
            WorkspaceCommand::Members { workspace } => {
                commands::workspace::members(&client, workspace.as_deref()).await
            }
            WorkspaceCommand::Invite {
                email,
                workspace,
                admin,
            } => commands::workspace::invite(&client, workspace.as_deref(), &email, admin).await,
            WorkspaceCommand::Revoke {
                invitation_id,
                workspace,
            } => commands::workspace::revoke(&client, workspace.as_deref(), &invitation_id).await,
            WorkspaceCommand::Remove { user_id, workspace } => {
                commands::workspace::remove(&client, workspace.as_deref(), &user_id).await
            }
        },
    }
}

/// The client for this invocation.
///
/// Flags beat the environment beats the saved profile, which is the order every
/// tool of this shape uses and the order that makes a one-off `--url` work
/// without disturbing what is saved.
fn connect(cli: &Cli) -> Result<ApiClient> {
    if let (Some(url), Some(token)) = (&cli.url, &cli.token) {
        return ApiClient::new(url, Some(token.clone()));
    }

    let config = Config::load().context("could not read the configuration")?;
    let (_, profile) = config.profile(cli.profile.as_deref())?;

    ApiClient::new(
        cli.url.as_deref().unwrap_or(&profile.url),
        Some(cli.token.clone().unwrap_or_else(|| profile.token.clone())),
    )
}