fundaia 0.10.0

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
//! The read-only half of the tool: everything that answers a question.
//!
//! Every one of these prints a table and nothing else. That is a rule rather
//! than a habit — the output of this tool is read by people and by scripts, and
//! a command that also prints a friendly sentence is a command whose second
//! line breaks `awk`.
//!
//! With `--json` each one prints the server's own DTOs back out instead, so a
//! program never has to parse a table that was laid out for eyes.

use anyhow::Result;
use owo_colors::OwoColorize;

use crate::api::client::ApiClient;
use crate::output::{self, Format};
use crate::render::table::{truncate, Cell, Table};
use crate::render::theme;
use crate::render::time;
use crate::render::time::{epoch_millis, format_millis};

pub async fn status(client: &ApiClient, format: Format) -> Result<()> {
    // Concurrent because they are independent, and `status` is the command an
    // agent runs before every decision — the round trips should overlap.
    let (projects, version) = tokio::join!(client.projects(), client.version());
    let projects = projects?;
    // Best effort, and never fatal. An instance too old to answer `/api/version`
    // is exactly the case this line exists to surface, so failing to read it
    // must not take the rest of the screen down with it.
    let version = version.ok();

    if format.is_json() {
        output::emit(&serde_json::json!({
            "url": client.base(),
            "cli": env!("CARGO_PKG_VERSION"),
            "server": version,
            "projects": projects,
        }));
        return Ok(());
    }

    let services: u32 = projects.iter().map(|project| project.service_count).sum();
    let online: u32 = projects.iter().map(|project| project.online_count).sum();

    println!();
    println!("  {}", client.base().style(theme::strong()));

    if let Some(version) = version {
        let mine = env!("CARGO_PKG_VERSION");
        let note = if version.platform == mine {
            String::new()
        } else {
            format!(" · este binario es {mine}")
        };

        println!(
            "  {}{}",
            format!("servidor {}", version.platform).style(theme::muted()),
            note.style(theme::muted()),
        );
    }

    println!(
        "  {} proyectos · {} servicios · {} en marcha",
        projects.len().style(theme::strong()),
        services.style(theme::strong()),
        if online == services && services > 0 {
            format!("{}", online.style(theme::success()))
        } else if online == 0 && services > 0 {
            format!("{}", online.style(theme::danger()))
        } else {
            format!("{}", online.style(theme::warning()))
        },
    );
    println!();

    let mut table = Table::new(&["proyecto", "entorno", "servicios", "estado"]);

    for project in &projects {
        // The dots are the service states in creation order, which is the same
        // order the canvas lays them out — one glance says which one is red.
        let dots: String = project
            .services
            .iter()
            .map(|service| theme::state_dot(&service.state))
            .collect::<Vec<_>>()
            .join(" ");

        table.push(vec![
            Cell::styled(project.name.clone(), theme::strong()),
            Cell::styled(project.environment_name.clone(), theme::muted()),
            Cell::plain(format!(
                "{}/{}",
                project.online_count, project.service_count
            )),
            Cell::plain(dots),
        ]);
    }

    if table.is_empty() {
        println!(
            "  {}",
            "Todavía no hay ningún proyecto.".style(theme::muted())
        );
    } else {
        table.print();
    }
    println!();

    Ok(())
}

pub async fn projects(client: &ApiClient, format: Format) -> Result<()> {
    let projects = client.projects().await?;

    if format.is_json() {
        output::emit(&projects);
        return Ok(());
    }

    let mut table = Table::new(&["id", "nombre", "slug", "servicios"]);

    for project in &projects {
        table.push(vec![
            Cell::styled(project.id.clone(), theme::muted()),
            Cell::styled(project.name.clone(), theme::strong()),
            Cell::plain(project.slug.clone()),
            Cell::plain(format!(
                "{}/{}",
                project.online_count, project.service_count
            )),
        ]);
    }

    if table.is_empty() {
        println!("Todavía no hay ningún proyecto.");
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn services(client: &ApiClient, project_reference: &str, format: Format) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let page = client.services(&project.id).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    let mut table = Table::new(&["servicio", "estado", "origen", "host", "depende de"]);

    for service in &page.services {
        // Named rather than by id: the arrow is for a person, and an id in a
        // dependency column is unreadable next to a name in the first one.
        let dependencies: Vec<String> = page
            .edges
            .iter()
            .filter(|edge| edge.from == service.id)
            .filter_map(|edge| page.services.iter().find(|target| target.id == edge.to))
            .map(|target| target.name.clone())
            .collect();

        table.push(vec![
            Cell::styled(service.name.clone(), theme::strong()),
            Cell::styled(
                format!(
                    "{} {}",
                    theme::state_dot(&service.state),
                    theme::state_word(&service.state)
                ),
                theme::state_style(&service.state),
            ),
            Cell::styled(
                service
                    .repo_full_name
                    .clone()
                    .or_else(|| service.brand.clone())
                    .unwrap_or_else(|| "".to_owned()),
                theme::muted(),
            ),
            Cell::styled(
                service.host.clone().unwrap_or_else(|| "".to_owned()),
                theme::muted(),
            ),
            Cell::plain(if dependencies.is_empty() {
                "".to_owned()
            } else {
                dependencies.join(", ")
            }),
        ]);
    }

    if table.is_empty() {
        println!("`{}` todavía no tiene servicios.", project.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn service(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let detail = client.service_detail(&found.id).await?;

    if format.is_json() {
        output::emit(&detail);
        return Ok(());
    }

    println!();
    println!(
        "  {} {} {}",
        theme::state_dot(&detail.environment.state),
        detail.service.name.style(theme::strong()),
        theme::state_word(&detail.environment.state)
            .style(theme::state_style(&detail.environment.state)),
    );
    println!(
        "  {} {}",
        "id".style(theme::muted()),
        detail.environment.id.style(theme::muted())
    );
    println!(
        "  {} {} MB · {} CPU · {}",
        "recursos".style(theme::muted()),
        detail.environment.memory_mb,
        detail.environment.cpus,
        if detail.environment.sleep_enabled {
            "duerme sin tráfico"
        } else {
            "siempre despierto"
        },
    );

    // Serving ones only. A summary is read as "where is this", and a hostname
    // that is switched off is not an answer to that.
    for domain in detail.domains.iter().filter(|domain| domain.enabled) {
        println!(
            "  {} {}",
            "host".style(theme::muted()),
            domain.url.style(theme::accent())
        );
    }

    if let Some(deployment) = &detail.active_deployment {
        println!(
            "  {} #{} {}",
            "activo".style(theme::muted()),
            deployment.number,
            deployment
                .commit_subject
                .clone()
                .unwrap_or_else(|| deployment.trigger.clone())
                .style(theme::muted()),
        );
    }

    println!();
    Ok(())
}

pub async fn history(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    limit: usize,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let deployments = client.deployments(&found.id).await?;

    if format.is_json() {
        let limited: Vec<_> = deployments.iter().take(limit).collect();
        output::emit(&limited);
        return Ok(());
    }

    let mut table = Table::new(&["#", "estado", "motivo", "commit", "duración", "asunto"]);

    for deployment in deployments.iter().take(limit) {
        let duration = match (
            &deployment.finished_at,
            epoch_millis(&deployment.created_at),
        ) {
            (Some(finished), Some(created)) => epoch_millis(finished)
                .map(|end| format_millis(end - created))
                .unwrap_or_else(|| "".to_owned()),
            _ => "".to_owned(),
        };

        table.push(vec![
            Cell::plain(format!("{}", deployment.number)),
            Cell::styled(
                deployment.status.clone(),
                theme::deployment_status_style(&deployment.status),
            ),
            Cell::styled(deployment.trigger.clone(), theme::muted()),
            Cell::styled(
                deployment
                    .commit_sha
                    .as_ref()
                    .map(|sha| sha.chars().take(7).collect::<String>())
                    .unwrap_or_else(|| "".to_owned()),
                theme::muted(),
            ),
            Cell::plain(duration),
            Cell::plain(truncate(
                deployment
                    .failure_message
                    .as_ref()
                    .or(deployment.commit_subject.as_ref())
                    .map(String::as_str)
                    .unwrap_or(""),
                52,
            )),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no se ha desplegado nunca.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn metrics(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    minutes: u32,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let samples = client.usage(&found.id, minutes).await?;

    if format.is_json() {
        output::emit(&samples);
        return Ok(());
    }

    let Some(latest) = samples.last() else {
        println!("Todavía no hay medidas de `{}`.", found.name);
        return Ok(());
    };

    // `checked_div` rather than a guard: a limit of zero means the runtime never
    // reported one, and "no percentage" is honestly zero rather than a division
    // somebody has to remember to protect.
    let share = (latest.memory_bytes * 100)
        .checked_div(latest.memory_limit_bytes)
        .unwrap_or(0) as u32;

    println!();
    println!(
        "  {} {} mCPU",
        "cpu    ".style(theme::muted()),
        latest.cpu_millicores.style(theme::strong())
    );
    println!(
        "  {} {} MB de {} MB",
        "memoria".style(theme::muted()),
        (latest.memory_bytes / 1_000_000).style(theme::strong()),
        latest.memory_limit_bytes / 1_000_000,
    );
    println!("  {} {}", "límite ".style(theme::muted()), bar(share));
    println!();

    // The sparkline is the point of asking for a window rather than a reading:
    // one number says how it is, forty say where it is going.
    let cpu: Vec<u64> = samples
        .iter()
        .map(|sample| u64::from(sample.cpu_millicores))
        .collect();
    let memory: Vec<u64> = samples
        .iter()
        .map(|sample| sample.memory_bytes / 1_000_000)
        .collect();

    println!("  {} {}", "cpu    ".style(theme::muted()), sparkline(&cpu));
    println!(
        "  {} {}",
        "memoria".style(theme::muted()),
        sparkline(&memory)
    );
    println!(
        "  {}",
        format!("{} medidas de los últimos {minutes} minutos", samples.len()).style(theme::muted()),
    );
    println!();

    Ok(())
}

/// A meter, in twenty characters.
fn bar(percent: u32) -> String {
    let filled = (percent.min(100) as usize) / 5;
    let style = if percent > 90 {
        theme::danger()
    } else if percent > 70 {
        theme::warning()
    } else {
        theme::success()
    };

    format!(
        "{}{} {percent}%",
        "".repeat(filled).style(style),
        "".repeat(20 - filled).style(theme::muted()),
    )
}

/// Braille-free sparkline: eight block heights, scaled to the largest reading.
///
/// Scaled to the window rather than to the limit, because the question a
/// sparkline answers is "is this changing", and a series pinned to the bottom
/// of a 512 MB axis answers nothing.
pub fn sparkline(values: &[u64]) -> String {
    const BLOCKS: [char; 8] = ['', '', '', '', '', '', '', ''];

    let Some(highest) = values.iter().copied().max() else {
        return String::new();
    };
    if highest == 0 {
        return BLOCKS[0].to_string().repeat(values.len());
    }

    values
        .iter()
        .map(|value| {
            let index = ((value * 7) / highest) as usize;
            BLOCKS[index.min(7)]
        })
        .collect()
}

pub async fn variables(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    reveal: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let variables = client.variables(&found.id).await?;

    if format.is_json() {
        // The DTO plus, under `--reveal`, a `value` the server never sends on
        // the list — each reveal is its own audited request, same as the table.
        let mut entries = Vec::with_capacity(variables.len());
        for variable in &variables {
            let mut entry = serde_json::to_value(variable)?;
            if reveal && variable.kind == "secret" && !variable.write_only && !variable.is_sealed()
            {
                if let Ok(value) = client.reveal_variable(&variable.id).await {
                    entry["value"] = value.into();
                }
            }
            entries.push(entry);
        }
        output::emit(&entries);
        return Ok(());
    }

    let mut table = Table::new(&["clave", "tipo", "valor"]);

    for variable in &variables {
        // Revealing is per variable and audited server-side, so it is one call
        // each rather than a bulk endpoint that would log one access for many.
        // A sealed one is skipped rather than attempted: the server would refuse
        // it, and a row of failed requests is a worse way to say "no".
        let value =
            if reveal && variable.kind == "secret" && !variable.write_only && !variable.is_sealed()
            {
                client
                    .reveal_variable(&variable.id)
                    .await
                    .unwrap_or_else(|_| "".to_owned())
            } else if variable.is_sealed() {
                "sellada · solo se puede borrar".to_owned()
            } else {
                variable
                    .preview
                    .clone()
                    .unwrap_or_else(|| "••••••••".to_owned())
            };

        let kind = if variable.is_sealed() {
            "sellada".to_owned()
        } else {
            variable.kind.clone()
        };

        table.push(vec![
            Cell::styled(variable.key.clone(), theme::strong()),
            Cell::styled(
                kind,
                match (variable.is_sealed(), variable.kind.as_str()) {
                    (true, _) => theme::warning(),
                    (false, "reference") => theme::accent(),
                    (false, "secret") => theme::warning(),
                    _ => theme::muted(),
                },
            ),
            Cell::plain(truncate(&value, 60)),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no define ninguna variable.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn domains(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let domains = client.domains(&found.id).await?;

    if format.is_json() {
        output::emit(&domains);
        return Ok(());
    }

    let mut table = Table::new(&["host", "tipo", "estado", "id"]);

    for domain in &domains {
        // A disabled hostname is not `failed` and not `pending`: nothing went
        // wrong with it, the service was taken off the internet. Painting its
        // DNS state would say the opposite in red.
        let (state, style) = if domain.enabled {
            (
                domain.state.clone(),
                match domain.state.as_str() {
                    "active" => theme::success(),
                    "failed" => theme::danger(),
                    _ => theme::warning(),
                },
            )
        } else {
            ("desactivado".to_string(), theme::muted())
        };

        table.push(vec![
            Cell::styled(
                domain.host.clone(),
                if domain.enabled {
                    theme::strong()
                } else {
                    theme::muted()
                },
            ),
            Cell::styled(domain.kind.clone(), theme::muted()),
            Cell::styled(state, style),
            Cell::styled(domain.id.clone(), theme::muted()),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no responde en ningún host.", found.name);
        return Ok(());
    }

    table.print();

    if domains.iter().all(|domain| !domain.enabled) {
        println!();
        println!(
            "  {}",
            "El servicio es privado. Sus dominios vuelven con `fundaia expose`."
                .style(theme::muted()),
        );
    }

    for domain in domains
        .iter()
        .filter(|domain| domain.enabled && domain.dns_instructions.is_some())
    {
        println!();
        println!(
            "  {} {}",
            "!".style(theme::warning()),
            domain.dns_instructions.clone().unwrap_or_default(),
        );
    }

    Ok(())
}

/// The persistent directories a service has, and whether the running container
/// actually has them.
///
/// `mounted` is the column worth reading: attaching a volume does not restart
/// anything, so a directory added five minutes ago is not in the container
/// until the next deployment — and a table that only listed names would hide
/// exactly that.
pub async fn volumes(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let volumes = client.volumes(&found.id).await?;

    if format.is_json() {
        output::emit(&volumes);
        return Ok(());
    }

    let mut table = Table::new(&["ruta", "nombre", "montado", "id"]);

    for volume in &volumes {
        table.push(vec![
            Cell::styled(volume.mount_path.clone(), theme::strong()),
            Cell::plain(volume.name.clone()),
            Cell::styled(
                if volume.mounted {
                    ""
                } else {
                    "en el próximo despliegue"
                }
                .to_owned(),
                if volume.mounted {
                    theme::success()
                } else {
                    theme::warning()
                },
            ),
            Cell::styled(volume.id.clone(), theme::muted()),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no tiene ningún volumen.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

/// The Containerfile a service builds with.
///
/// Printed on stdout with nothing around it when `--plain` is given, because
/// the useful thing to do with it is `> Containerfile`, edit, and hand it back
/// to `recipe edit`.
pub async fn recipe(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    plain: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let recipe = client.recipe(&found.id).await?;

    // `--plain` beats `--json`: it exists to be redirected into a file, and a
    // Containerfile wrapped in a JSON string is not one.
    if format.is_json() && !plain {
        output::emit(&recipe);
        return Ok(());
    }

    if plain {
        print!("{}", recipe.containerfile);
        return Ok(());
    }

    println!();
    println!(
        "  {}  {}",
        recipe.builder.style(theme::strong()),
        match recipe.source.as_str() {
            "edited" => "editado a mano — no se vuelve a generar".to_owned(),
            _ => "generado".to_owned(),
        }
        .style(theme::muted()),
    );

    if let Some(port) = recipe.exposed_port {
        println!("  {}", format!("puerto {port}").style(theme::muted()));
    }

    for warning in &recipe.warnings {
        println!("  {} {}", "!".style(theme::warning()), warning);
    }

    println!();
    for line in recipe.containerfile.lines() {
        println!("  {line}");
    }
    println!();

    for note in &recipe.notes {
        println!("  {}", note.style(theme::muted()));
    }

    Ok(())
}

/// A service's copies, newest first.
///
/// The size and the age are the two columns somebody scans for, and `guardada`
/// is the third: a locked copy is the one that will still be there next month,
/// and that is exactly what you want to know before deleting anything.
pub async fn backups(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let page = client.backups(&found.id).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    if !page.supported {
        println!(
            "`{}` no tiene volumen, así que no hay nada que copiar.",
            found.name
        );
        return Ok(());
    }

    println!();
    println!(
        "  {} {}",
        "programación".style(theme::muted()),
        if page.schedules.is_empty() {
            "ninguna — este servicio no se copia solo".to_owned()
        } else {
            page.schedules.join(", ")
        }
        .style(theme::strong()),
    );
    if let Some(next) = &page.next_at {
        println!(
            "  {} {}",
            "siguiente".style(theme::muted()),
            next.style(theme::muted())
        );
    }
    println!();

    let mut table = Table::new(&["id", "origen", "tamaño", "estado", "hecha"]);

    for backup in &page.backups {
        table.push(vec![
            Cell::styled(backup.id.clone(), theme::muted()),
            Cell::plain(match &backup.schedule {
                Some(schedule) => schedule.clone(),
                None => "a mano".to_owned(),
            }),
            Cell::plain(human_size(backup.size_bytes)),
            Cell::styled(
                if backup.locked {
                    format!("{} · guardada", backup.status)
                } else {
                    backup.status.clone()
                },
                match backup.status.as_str() {
                    "ready" => theme::success(),
                    "failed" => theme::danger(),
                    _ => theme::warning(),
                },
            ),
            Cell::styled(backup.created_at.clone(), theme::muted()),
        ]);
    }

    if table.is_empty() {
        println!("Todavía no hay ninguna copia de `{}`.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

/// Bytes as a person reads them. Two significant figures is all a size column needs.
fn human_size(bytes: u64) -> String {
    const UNITS: [&str; 4] = ["B", "KB", "MB", "GB"];
    let mut size = bytes as f64;
    let mut unit = 0;

    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }

    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{size:.1} {}", UNITS[unit])
    }
}

/// What has been done to a project, newest first.
///
/// The terminal half of the panel on the canvas, from the same endpoint and the
/// same sentences — `describeActivity` runs on the server precisely so a history
/// read here and one read in a browser cannot disagree about what happened.
///
/// It covers both surfaces because the recording does: every write goes through
/// a service that both the web and this tool call, so a variable changed from a
/// terminal appears in the panel and a deployment started from the panel appears
/// here, with nobody having had to instrument either one twice.
pub async fn activity(
    client: &ApiClient,
    project_reference: &str,
    limit: usize,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let entries = client.activity(&project.id, limit).await?;

    if format.is_json() {
        output::emit(&entries);
        return Ok(());
    }

    if entries.is_empty() {
        println!("Todavía no se ha hecho nada en `{}`.", project.name);
        return Ok(());
    }

    println!();
    let mut table = Table::new(&["cuándo", "quién", "qué"]);

    for entry in &entries {
        table.push(vec![
            Cell::styled(
                time::relative_time(&entry.at).unwrap_or_else(|| "".to_string()),
                theme::muted(),
            ),
            Cell::styled(
                entry
                    .actor
                    .display_name
                    .clone()
                    .unwrap_or_else(|| entry.actor.id.clone()),
                theme::strong(),
            ),
            Cell::plain(entry.summary.clone()),
        ]);
    }

    table.print();
    println!();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_should_draw_one_block_per_reading() {
        assert_eq!(sparkline(&[1, 2, 3]).chars().count(), 3);
    }

    #[test]
    fn it_should_draw_the_largest_reading_at_full_height() {
        assert!(sparkline(&[1, 10]).ends_with(''));
    }

    #[test]
    fn it_should_draw_a_flat_series_of_zeroes_at_the_floor() {
        assert_eq!(sparkline(&[0, 0, 0]), "▁▁▁");
    }

    #[test]
    fn it_should_draw_nothing_for_no_readings() {
        assert_eq!(sparkline(&[]), "");
    }

    #[test]
    fn it_should_fill_a_full_meter_completely() {
        assert!(bar(100).contains(&"".repeat(20)));
    }

    #[test]
    fn it_should_leave_an_empty_meter_unfilled() {
        assert!(bar(0).contains(&"".repeat(20)));
    }
}