fundaia 0.5.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
//! Everything that changes something.
//!
//! Each of these prints one line saying what happened, and that line names the
//! thing it happened to. `deploy` is not here — it is long-lived enough to have
//! a view of its own.

use anyhow::{bail, Context, Result};
use owo_colors::OwoColorize;

use crate::api::client::{ApiClient, ApiError};
use crate::api::models::NewService;
use crate::commands::dotenv;
use crate::render::theme;

pub async fn set_variable(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    key: &str,
    value: &str,
    secret: bool,
    sealed: bool,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    client
        .set_variable(&service.id, key, value, secret, sealed)
        .await?;

    println!(
        "  {} {} en {}{}",
        theme::CHECK.style(theme::success()),
        key.style(theme::strong()),
        service.name.style(theme::strong()),
        match (sealed, secret) {
            (true, _) => " (sellada)",
            (false, true) => " (secreto)",
            _ => "",
        },
    );
    if sealed {
        println!(
            "  {}",
            "Su valor ya no se puede leer ni cambiar en ningún sitio. Solo borrarla."
                .style(theme::muted()),
        );
    }
    println!(
        "  {}",
        "El próximo despliegue la recogerá; el contenedor actual no la ve.".style(theme::muted()),
    );

    Ok(())
}

/// Seals an existing variable.
///
/// The key has to be typed back, the same way deleting a service asks for its
/// name. This cannot be undone and it is one letter away from `set` in a shell
/// history — a flag on its own is a guard people learn to type without reading.
pub async fn seal_variable(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    key: &str,
    confirmation: Option<&str>,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let variables = client.variables(&service.id).await?;
    let Some(variable) = variables.into_iter().find(|variable| variable.key == key) else {
        bail!(
            "`{}` no define ninguna variable llamada `{key}`",
            service.name
        );
    };

    if variable.is_sealed() {
        println!(
            "  {} {} ya estaba sellada",
            theme::CHECK.style(theme::success()),
            key.style(theme::strong())
        );
        return Ok(());
    }

    if variable.kind == "reference" {
        bail!("`{key}` es una referencia: no guarda ningún valor propio. Sella la variable a la que apunta.");
    }

    if confirmation != Some(key) {
        bail!(
            "escribe `--confirm {key}` para sellarla: dejará de poder verse y de poder cambiarse, y no se deshace"
        );
    }

    client.seal_variable(&variable.id).await?;

    println!(
        "  {} {} sellada en {}",
        theme::CHECK.style(theme::success()),
        key.style(theme::strong()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "El contenedor la sigue recibiendo. Nadie más vuelve a verla.".style(theme::muted()),
    );

    Ok(())
}

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

    let variables = client.variables(&service.id).await?;
    let Some(variable) = variables.into_iter().find(|variable| variable.key == key) else {
        bail!(
            "`{}` no define ninguna variable llamada `{key}`",
            service.name
        );
    };

    client.remove_variable(&variable.id).await?;
    println!(
        "  {} {} eliminada",
        theme::CHECK.style(theme::success()),
        key.style(theme::strong())
    );

    Ok(())
}

/// Wires one service to another, letting the server decide what that means.
///
/// The CLI never invents the variables. Which keys a Postgres hands over is a
/// rule that lives in `domain/connectors.ts`, and duplicating it here would be
/// two implementations of one convention, drifting.
pub async fn connect(
    client: &ApiClient,
    project_reference: &str,
    consumer_reference: &str,
    provider_reference: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let consumer = client.find_service(&project.id, consumer_reference).await?;
    let provider = client.find_service(&project.id, provider_reference).await?;

    let connection = client.connect(&consumer.id, &provider.id).await?;

    println!(
        "  {} {} {} {}",
        theme::CHECK.style(theme::success()),
        consumer.name.style(theme::strong()),
        theme::ARROW.style(theme::muted()),
        connection.provider_name.style(theme::strong()),
    );
    println!("  {}", connection.summary.style(theme::muted()));

    for key in &connection.keys {
        println!("    {} {}", "+".style(theme::success()), key);
    }

    Ok(())
}

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

    if candidates.is_empty() {
        println!("No hay nada a lo que `{}` pueda conectarse.", service.name);
        return Ok(());
    }

    for candidate in &candidates {
        println!(
            "  {} {}",
            candidate.name.style(theme::strong()),
            candidate.summary.style(theme::muted()),
        );
    }

    Ok(())
}

pub async fn add_domain(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    host: Option<&str>,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let domain = client.add_domain(&service.id, host).await?;

    println!(
        "  {} {}",
        theme::CHECK.style(theme::success()),
        domain.url.style(theme::accent())
    );

    if let Some(instructions) = &domain.dns_instructions {
        println!("  {} {}", "!".style(theme::warning()), instructions);
    }

    Ok(())
}

pub async fn remove_domain(client: &ApiClient, domain_id: &str) -> Result<()> {
    client.remove_domain(domain_id).await?;
    println!(
        "  {} Dominio eliminado",
        theme::CHECK.style(theme::success())
    );
    Ok(())
}

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

    client.stop(&service.id).await?;
    println!(
        "  {} {} parado — despertará con la siguiente petición",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );

    Ok(())
}

/// What `fundaia new` was asked for, before any of it is resolved.
///
/// A struct rather than eight parameters, and not only to satisfy a lint: the
/// three sources are mutually exclusive and the check that says so reads far
/// better against one value than against a signature nobody can call without
/// consulting it.
pub struct ServiceRequest<'a> {
    pub project: &'a str,
    pub name: &'a str,
    pub repo: Option<&'a str>,
    pub image: Option<&'a str>,
    /// A component from the catalogue: `postgres-16`, `bucket`, `claude-code`.
    pub template: Option<&'a str>,
    pub branch: &'a str,
    /// Services it should be able to talk to, by whatever name a person types.
    pub connect_to: &'a [String],
}

/// Creates a service, and optionally wires it up in the same breath.
///
/// `--connect-to` accepts the names a person can see, resolved here rather than
/// on the server, because the server keys on ids and a CLI that demanded ids
/// would be a CLI nobody types twice.
pub async fn create_service(client: &ApiClient, request: ServiceRequest<'_>) -> Result<()> {
    let project = client.find_project(request.project).await?;

    let source_kind = match (request.repo, request.image, request.template) {
        (Some(_), None, None) => "github",
        (None, Some(_), None) => "image",
        (None, None, Some(_)) => "template",
        (None, None, None) => bail!("say where it comes from: --repo, --image or --template"),
        _ => bail!("--repo, --image and --template are alternatives, not a set"),
    };

    let mut providers = Vec::new();
    for reference in request.connect_to {
        providers.push(client.find_service(&project.id, reference).await?.id);
    }

    let draft = NewService {
        name: request.name.to_owned(),
        source_kind: source_kind.to_owned(),
        repo_full_name: request.repo.map(str::to_owned),
        branch: request.repo.map(|_| request.branch.to_owned()),
        image: request.image.map(str::to_owned),
        template_key: request.template.map(str::to_owned),
        // Every catalogue component is created as `database`, Claude Code
        // included, because that is what the web sends and two clients that
        // disagree produce two kinds of the same service. Nothing keys on it
        // anyway: a connector recognises its provider by the template key.
        kind: request.template.map(|_| "database".to_owned()),
        connect_to: providers,
    };

    if let Err(error) = client.create_service(&project.id, &draft).await {
        return Err(match request.template {
            Some(key) => explain_template_refusal(error, key),
            None => error,
        });
    }

    println!(
        "  {} {} creado en {}",
        theme::CHECK.style(theme::success()),
        request.name.style(theme::strong()),
        project.name.style(theme::strong()),
    );

    if !request.connect_to.is_empty() {
        println!(
            "  {} conectado a {}",
            theme::ARROW.style(theme::muted()),
            request.connect_to.join(", "),
        );
    }

    Ok(())
}

/// Says what a `not_found` on a template can mean, because the server will not.
///
/// A component only the instance owner may add — `claude-code` today — answers
/// exactly like a key that does not exist. That is deliberate on the server's
/// side: which components an instance offers somebody else is not a stranger's
/// business. It makes a good answer and a useless message, so the tool names
/// both readings rather than printing a 404 nobody can interpret.
///
/// The original stays in the chain as the cause, and the exit code is unchanged:
/// this reworded a failure, it did not forgive one.
fn explain_template_refusal(error: anyhow::Error, key: &str) -> anyhow::Error {
    let missing = error
        .downcast_ref::<ApiError>()
        .is_some_and(|api| api.code == "not_found");

    if !missing {
        return error;
    }

    error.context(format!(
        "el componente `{key}` no está disponible: o no existe en esta instancia, \
         o solo su dueño puede añadirlo — `fundaia templates` lista los que \
         esta cuenta sí puede crear"
    ))
}

pub async fn templates(client: &ApiClient) -> Result<()> {
    for template in client.templates().await? {
        println!(
            "  {}  {}  {}",
            template.key.style(theme::strong()),
            template.display_name,
            template.image.style(theme::muted()),
        );
    }
    Ok(())
}

/// A project, which is the one thing this tool could not make until now.
pub async fn create_project(
    client: &ApiClient,
    name: &str,
    description: Option<&str>,
    workspace_reference: Option<&str>,
) -> Result<()> {
    // Resolved here rather than passed through, so `--workspace equipo` works
    // the same way every other name in this tool does.
    let workspace = match workspace_reference {
        Some(reference) => Some(client.find_workspace(Some(reference)).await?),
        None => None,
    };

    let project = client
        .create_project(name, description, workspace.as_ref().map(|w| w.id.as_str()))
        .await?;

    println!(
        "  {} {} {}",
        theme::CHECK.style(theme::success()),
        project.name.style(theme::strong()),
        format!("({})", project.slug).style(theme::muted()),
    );
    println!(
        "  {}",
        format!("fundaia new {} <nombre> --repo <owner/repo>", project.slug).style(theme::muted()),
    );

    Ok(())
}

/// A persistent directory. Nothing is deployed: the volume is in the container
/// from the next deployment on, and saying so is better than restarting a
/// service somebody was only configuring.
pub async fn attach_volume(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    mount_path: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let volume = client.attach_volume(&service.id, mount_path).await?;

    println!(
        "  {} {} en {}",
        theme::CHECK.style(theme::success()),
        volume.mount_path.style(theme::strong()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "Estará dentro del contenedor a partir del próximo despliegue.".style(theme::muted()),
    );

    Ok(())
}

/// Replaces the Containerfile, after which it is never regenerated.
///
/// The file comes from a path or from stdin, because the shape of this is
/// `fundaia recipe show … --plain > Containerfile`, edit it, hand it back.
pub async fn edit_recipe(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    file: &str,
) -> Result<()> {
    let containerfile = read_text(file)?;

    if containerfile.trim().is_empty() {
        bail!("el Containerfile está vacío");
    }

    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    client.edit_recipe(&service.id, &containerfile).await?;

    println!(
        "  {} Containerfile de {}",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "A partir de ahora se despliega este, no el generado.".style(theme::muted()),
    );

    Ok(())
}

/// A whole `.env` in one request.
pub async fn import_variables(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    file: &str,
    secret: bool,
) -> Result<()> {
    let variables = dotenv::variables_in(&read_text(file)?, secret);

    if variables.is_empty() {
        bail!("no hay ninguna variable en {file}");
    }

    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let imported = client.import_variables(&service.id, &variables).await?;

    println!(
        "  {} {} en {}{}",
        theme::CHECK.style(theme::success()),
        format!("{imported} variables").style(theme::strong()),
        service.name.style(theme::strong()),
        if secret { " (secretas)" } else { "" },
    );

    for variable in variables.iter().take(5) {
        println!("  {}", variable.key.style(theme::muted()));
    }
    if variables.len() > 5 {
        println!(
            "  {}",
            format!("y {} más", variables.len() - 5).style(theme::muted())
        );
    }

    Ok(())
}

/// A path, or `-` for standard input.
fn read_text(file: &str) -> Result<String> {
    if file == "-" {
        let mut text = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut text)
            .context("no se ha podido leer la entrada estándar")?;
        return Ok(text);
    }

    std::fs::read_to_string(file).with_context(|| format!("no se ha podido leer {file}"))
}

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

    fn refusal(code: &str) -> anyhow::Error {
        ApiError {
            status: StatusCode::NOT_FOUND,
            code: code.to_owned(),
            message: "template 'claude-code' does not exist".to_owned(),
        }
        .into()
    }

    #[test]
    fn it_should_say_who_may_add_a_component_the_server_refused() {
        let explained = explain_template_refusal(refusal("not_found"), "claude-code");
        assert!(explained
            .to_string()
            .contains("solo su dueño puede añadirlo"));
    }

    #[test]
    fn it_should_name_the_component_it_could_not_add() {
        let explained = explain_template_refusal(refusal("not_found"), "claude-code");
        assert!(explained.to_string().contains("claude-code"));
    }

    #[test]
    fn it_should_keep_the_server_answer_as_the_cause() {
        let explained = explain_template_refusal(refusal("not_found"), "claude-code");
        assert!(explained.downcast_ref::<ApiError>().is_some());
    }

    #[test]
    fn it_should_leave_a_failure_that_is_not_a_missing_component_alone() {
        let explained = explain_template_refusal(refusal("conflict"), "claude-code");
        assert!(!explained.to_string().contains("dueño"));
    }
}