fundaia 0.4.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
//! 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`.

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

use crate::api::client::ApiClient;
use crate::render::pipeline::{epoch_millis, format_millis};
use crate::render::table::{truncate, Cell, Table};
use crate::render::theme;

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

    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()));

    // 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.
    if let Ok(version) = client.version().await {
        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) -> Result<()> {
    let projects = client.projects().await?;
    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) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let page = client.services(&project.id).await?;

    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,
) -> 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?;

    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"
        },
    );

    for domain in &detail.domains {
        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,
) -> 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?;

    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,
) -> 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?;

    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,
) -> 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?;

    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.
        let value = if reveal && variable.kind == "secret" && !variable.write_only {
            client
                .reveal_variable(&variable.id)
                .await
                .unwrap_or_else(|_| "".to_owned())
        } else {
            variable
                .preview
                .clone()
                .unwrap_or_else(|| "••••••••".to_owned())
        };

        table.push(vec![
            Cell::styled(variable.key.clone(), theme::strong()),
            Cell::styled(
                variable.kind.clone(),
                match variable.kind.as_str() {
                    "reference" => theme::accent(),
                    "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,
) -> 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?;

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

    for domain in &domains {
        table.push(vec![
            Cell::styled(domain.host.clone(), theme::strong()),
            Cell::styled(domain.kind.clone(), theme::muted()),
            Cell::styled(
                domain.state.clone(),
                match domain.state.as_str() {
                    "active" => theme::success(),
                    "failed" => theme::danger(),
                    _ => theme::warning(),
                },
            ),
            Cell::styled(domain.id.clone(), theme::muted()),
        ]);
    }

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

    table.print();

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

    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)));
    }
}