fundaia 0.26.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
use anyhow::{bail, Result};
use owo_colors::OwoColorize;

use crate::api::client::ApiClient;
use crate::api::models::{Capacity, SettingsPatch};
use crate::output::{self, Format};
use crate::render::theme;

/// How much of the machine is left.
///
/// The question "how many services can I have" has an answer that surprises
/// people: nothing is created per service in Cloudflare, so the ceiling is this
/// machine's memory — the memory in use, not what the rows promise — and it
/// is much closer than anybody expects.
pub async fn capacity(client: &ApiClient, format: Format) -> Result<()> {
    let capacity = client.capacity().await?;

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

    println!();
    println!(
        "  {} de {} MB libres  {}",
        capacity.available_memory_mb.style(theme::strong()),
        capacity.total_memory_mb,
        capacity_detail(&capacity).style(theme::muted()),
    );
    println!(
        "  caben {} servicios más a 512 MB",
        capacity.remaining_at_default_size.style(theme::strong()),
    );
    println!(
        "  {}",
        format!(
            "puertos {} de {}",
            capacity.ports_in_use, capacity.ports_total
        )
        .style(theme::muted()),
    );

    if capacity.running_low {
        println!();
        println!(
            "  {} Queda poco sitio en esta máquina.",
            theme::PENDING.style(theme::warning()),
        );
    }
    println!();

    Ok(())
}

/// The figures behind the free number, in the words of whichever server answered.
///
/// A server that reports what is in use is the one whose verdicts are about
/// use; an older one still counts reservations, and saying "en uso" over its
/// committed figure would be a lie about what it refuses on.
fn capacity_detail(capacity: &Capacity) -> String {
    match capacity.used_memory_mb {
        Some(used) => format!(
            "({used} en uso, {} de margen para el sistema; las filas prometen {})",
            capacity.reserved_memory_mb, capacity.committed_memory_mb
        ),
        None => format!(
            "({} para el sistema, {} comprometidos)",
            capacity.reserved_memory_mb, capacity.committed_memory_mb
        ),
    }
}

/// Changes one or more settings, leaving the rest alone.
///
/// Every field is optional and nothing is sent that was not asked for, so this
/// can never overwrite a setting somebody changed in the browser a moment ago
/// with whatever the terminal happened to be holding.
#[allow(clippy::too_many_arguments)]
pub async fn set_settings(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    patch: SettingsPatch,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    client.update_settings(&service.id, &patch).await?;

    println!(
        "  {} Ajustes de {} guardados",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "Los que cambian el contenedor lo reinician. Dormido, los recoge al despertar."
            .style(theme::muted()),
    );

    Ok(())
}

/// Turns encryption at rest on or off for a storage service's buckets.
pub async fn encryption(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    enabled: bool,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    println!(
        "  {}",
        if enabled {
            "Cifrando… se reescribe lo que ya está guardado.".style(theme::muted())
        } else {
            "Quitando el cifrado por defecto…".style(theme::muted())
        }
    );

    let outcome = client.set_encryption(&service.id, enabled).await?;

    if !outcome.enabled {
        println!(
            "  {} Cifrado desactivado para lo nuevo en {} bucket(s)",
            theme::CHECK.style(theme::success()),
            outcome.buckets.len(),
        );
        return Ok(());
    }

    println!(
        "  {} Cifrado activado en {} bucket(s), {} objeto(s) reescrito(s)",
        theme::CHECK.style(theme::success()),
        outcome.buckets.len(),
        outcome.re_encrypted,
    );
    println!(
        "  {}",
        "La clave vive en el llavero de la plataforma. Si se pierde, los objetos no se recuperan."
            .style(theme::muted()),
    );

    Ok(())
}

/// Publishes a service on the internet, or takes it off.
///
/// The project network is never in question: every service is always reachable
/// there by name, which is what makes a private database useful rather than
/// unreachable. What this turns off is the hostname on top of that.
pub async fn expose(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    public: bool,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let outcome = client.set_public_access(&service.id, public).await?;

    if !public {
        println!(
            "  {} {} sale de internet",
            theme::CHECK.style(theme::success()),
            service.name.style(theme::strong()),
        );
        println!(
            "  {}",
            "Sus dominios quedan apagados y sus registros DNS borrados. Los demás servicios del \
             proyecto lo siguen alcanzando por su nombre."
                .style(theme::muted()),
        );
        return Ok(());
    }

    println!(
        "  {} {} vuelve a ser público",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );

    // The response carries what is serving as of now, so this lists hostnames
    // rather than promising one on the next deployment — which is what it said
    // back when a deployment was the only thing that handed them out.
    let serving: Vec<_> = outcome
        .domains
        .iter()
        .filter(|domain| domain.enabled)
        .collect();

    if serving.is_empty() {
        println!(
            "  {}",
            "Todavía sin dominio. Dale uno con `fundaia domains add`.".style(theme::muted()),
        );
    } else {
        for domain in serving {
            println!("    https://{}", domain.host);
        }
    }

    Ok(())
}

/// Removes a service and everything under it.
///
/// The name has to be typed back. A destructive command whose only guard is a
/// flag is one that gets run with the flag out of habit.
pub async fn delete(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    confirmation: Option<&str>,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    if confirmation != Some(service.name.as_str()) {
        bail!(
            "escribe `--confirm {}` para eliminarlo: se van sus despliegues, dominios y variables",
            service.name
        );
    }

    client.delete_service(&service.service_id).await?;

    println!(
        "  {} {} eliminado",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );

    Ok(())
}

/// Renames a project, or rewrites its description, or both.
pub async fn rename_project(
    client: &ApiClient,
    project_reference: &str,
    name: Option<&str>,
    description: Option<&str>,
) -> Result<()> {
    if name.is_none() && description.is_none() {
        bail!("no has pedido ningún cambio: pasa un nombre o `--description`");
    }

    let project = client.find_project(project_reference).await?;
    client
        .rename_project(&project.id, name, description)
        .await?;

    println!(
        "  {} {} {} {}",
        theme::CHECK.style(theme::success()),
        project.name.style(theme::muted()),
        theme::ARROW,
        name.unwrap_or(&project.name).style(theme::strong()),
    );

    Ok(())
}

/// Renames a service, and says what that dragged along with it.
///
/// Said out loud because renaming is a contract change and not a label: the
/// server rewrites the `${{ Name.KEY }}` expressions and the internal addresses
/// that called it, and the public hostname follows on the next deployment.
/// Somebody who renames a service and is told only "listo" has no way to know
/// any of that happened.
pub async fn rename_service(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    name: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    client.rename_service(&service.service_id, name).await?;

    println!(
        "  {} {} {} {}",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::muted()),
        theme::ARROW,
        name.style(theme::strong()),
    );
    println!(
        "  {} variables y direcciones internas reescritas · el dominio cambia en el siguiente despliegue",
        theme::ARROW.style(theme::muted()),
    );

    Ok(())
}

/// Deletes a project and everything under it.
///
/// Typed back like a service's deletion is, and here it matters more: the name
/// on screen is the only thing standing between a slug that reads like another
/// project and the wrong one being erased — `Ejemplo 2` has the slug
/// `puffless`, and `Ejemplo 1` is somebody's live project next to it.
///
/// The check is repeated on the server, which is what makes it a rule rather
/// than a habit of this binary.
pub async fn delete_project(
    client: &ApiClient,
    project_reference: &str,
    confirmation: Option<&str>,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;

    if confirmation != Some(project.name.as_str()) && confirmation != Some(project.slug.as_str()) {
        bail!(
            "eliminar `{}` borra sus servicios, sus volúmenes con lo que tengan dentro y sus copias: repite el nombre con --confirm {}",
            project.name,
            project.slug,
        );
    }

    client
        .delete_project(&project.id, confirmation.unwrap_or_default())
        .await?;

    println!(
        "  {} {} eliminado",
        theme::CHECK.style(theme::success()),
        project.name.style(theme::strong()),
    );
    println!(
        "  {} servicios, contenedores, volúmenes, copias y dominios",
        theme::ARROW.style(theme::muted()),
    );

    Ok(())
}

/// Hands a project to another workspace, which is the whole of sharing it.
pub async fn move_project(
    client: &ApiClient,
    project_reference: &str,
    workspace_reference: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let workspace = client.find_workspace(Some(workspace_reference)).await?;

    client.move_project(&project.id, &workspace.id).await?;

    println!(
        "  {} {} {} {}",
        theme::CHECK.style(theme::success()),
        project.name.style(theme::strong()),
        theme::ARROW,
        workspace.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "Todo el que comparte ese espacio lo ve.".style(theme::muted()),
    );

    Ok(())
}

/// Undoes a connection.
///
/// What it removes are the variable references that were the connection — there
/// is no link table — so the count is worth printing: it is how many keys the
/// consumer stopped reading.
pub async fn disconnect(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    provider_reference: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let consumer = client.find_service(&project.id, service_reference).await?;
    let provider = client.find_service(&project.id, provider_reference).await?;

    let removed = client.disconnect(&consumer.id, &provider.id).await?;

    println!(
        "  {} {} ya no lee nada de {}",
        theme::CHECK.style(theme::success()),
        consumer.name.style(theme::strong()),
        provider.name.style(theme::strong()),
    );
    println!(
        "  {}",
        format!(
            "{} variables retiradas: {}",
            removed.len(),
            removed.join(", ")
        )
        .style(theme::muted()),
    );
    println!(
        "  {}",
        "Despliega el consumidor para que deje de recibirlas.".style(theme::muted()),
    );

    Ok(())
}

/// Takes a volume off a service. What is inside it is `VolumeService`'s
/// decision, and the server says which one it made.
pub async fn detach_volume(client: &ApiClient, volume_id: &str) -> Result<()> {
    client.detach_volume(volume_id).await?;

    println!(
        "  {} volumen {} retirado",
        theme::CHECK.style(theme::success()),
        volume_id.style(theme::strong()),
    );

    Ok(())
}

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

    fn capacity_from(used_memory_mb: Option<u64>) -> Capacity {
        Capacity {
            total_memory_mb: 12_288,
            used_memory_mb,
            reserved_memory_mb: 2048,
            committed_memory_mb: 10_240,
            available_memory_mb: 8192,
            ports_in_use: 4,
            ports_total: 1000,
            remaining_at_default_size: 16,
            running_low: false,
        }
    }

    #[test]
    fn it_should_say_what_is_in_use_when_the_server_reports_it() {
        assert!(capacity_detail(&capacity_from(Some(2048))).contains("2048 en uso"));
    }

    #[test]
    fn it_should_not_call_a_reservation_use_on_a_server_that_counts_reservations() {
        assert!(!capacity_detail(&capacity_from(None)).contains("en uso"));
    }
}