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
use std::time::Duration;

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

use crate::api::client::ApiClient;
use crate::api::models::Deployment;
use crate::output::{self, Format};
use crate::render::logs::{render_line, LineFormat};
use crate::render::pipeline::PipelineView;
use crate::render::theme;
use crate::render::time::{epoch_millis, format_millis};

/// Deploying, watched.
///
/// The whole reason this command is worth having over `curl`: it starts the
/// deployment and then *stays*, redrawing the six stages in place while a tail
/// of the build scrolls underneath. What you get is the shape of a pipeline —
/// which step it is on, how long each one took, and where it stopped — rather
/// than a status word you have to poll for by hand.
///
/// Two loops, deliberately not one. The pipeline is polled, because it is a
/// derived view the server recomputes and there is nothing to stream; the log
/// is streamed, because it is a firehose and polling it would either lag or
/// hammer. They run concurrently and write to the same terminal, which is why
/// the pipeline is redrawn below the log rather than above it.
pub async fn run(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    restart: bool,
    follow: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let deployment = if restart {
        client.restart(&service.id).await?
    } else {
        client.deploy(&service.id).await?
    };

    if format.is_json() {
        if !follow {
            output::emit(&deployment);
            return Ok(());
        }
        return watch_json(client, &deployment).await;
    }

    println!();
    println!(
        "  {} {} {} despliegue #{}",
        theme::ARROW.style(theme::accent()),
        project.name.style(theme::muted()),
        service.name.style(theme::strong()),
        deployment.number.style(theme::strong()),
    );
    println!();

    if !follow {
        println!(
            "  {}",
            format!(
                "Sigue el progreso con: fundaia logs {} {}",
                project.slug, service.slug
            )
            .style(theme::muted()),
        );
        return Ok(());
    }

    watch(client, &deployment).await
}

/// Builds one deployment's own commit again, and watches that go out.
///
/// The verb between `deploy` and `rollback`. `deploy` reads the branch, so it
/// ships whatever landed on it since; `rollback` reuses the image and never
/// builds, so a variable fixed since is not picked up. This one builds that
/// exact commit against the configuration as it stands now.
pub async fn redeploy(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    number: u32,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let deployments = client.deployments(&service.id).await?;
    let Some(target) = deployments
        .iter()
        .find(|deployment| deployment.number == number)
    else {
        bail!("`{}` has no deployment #{number}", service.name);
    };

    let started = client.redeploy(&target.id).await?;

    if format.is_json() {
        return watch_json(client, &started).await;
    }

    println!();
    println!(
        "  {} Reconstruyendo el commit de #{} en {}",
        theme::ARROW.style(theme::accent()),
        number.style(theme::strong()),
        service.name.style(theme::strong()),
    );
    println!();

    watch(client, &started).await
}

/// Puts a previous deployment back, and watches that go out.
///
/// The image is reused rather than rebuilt, which is the whole point of a
/// rollback — so the pipeline it draws skips the checkout and the build, and
/// says so rather than showing two stages that never move.
pub async fn rollback(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    number: u32,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let deployments = client.deployments(&service.id).await?;
    let Some(target) = deployments
        .iter()
        .find(|deployment| deployment.number == number)
    else {
        bail!("`{}` has no deployment #{number}", service.name);
    };

    let started = client.rollback(&target.id).await?;

    if format.is_json() {
        return watch_json(client, &started).await;
    }

    println!();
    println!(
        "  {} Volviendo {} a #{}",
        theme::ARROW.style(theme::accent()),
        service.name.style(theme::strong()),
        number.style(theme::strong()),
    );
    println!();

    watch(client, &started).await
}

/// Stops a deployment that has not finished.
///
/// The one in flight unless a number names another, because "the one in
/// flight" is the only one anybody means: a service has at most one, and the
/// number of a build somebody is watching scroll past is not in front of them.
/// Nothing is watched afterwards — the answer already carries the pipeline as
/// it stopped, which is what `--json` prints.
pub async fn cancel(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    number: Option<u32>,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let deployments = client.deployments(&service.id).await?;
    let target = deployment_to_cancel(&deployments, number, &service.name)?;
    let detail = client.cancel(&target.id).await?;

    if format.is_json() {
        output::emit(&serde_json::json!({
            "deployment": detail.deployment,
            "pipeline": detail.pipeline,
        }));
        return Ok(());
    }

    println!();
    println!(
        "  {} Despliegue #{} de {} cancelado — lo que estaba sirviendo sigue en pie",
        theme::CHECK.style(theme::success()),
        detail.deployment.number.style(theme::strong()),
        service.name.style(theme::strong()),
    );
    println!();

    Ok(())
}

/// Which deployment `cancel` means: the numbered one, or the one in flight.
///
/// Refuses rather than guesses when there is nothing in flight — cancelling
/// "whatever is newest" would reach a deployment that already finished, and the
/// server would refuse that with a sentence about a number nobody typed.
fn deployment_to_cancel<'a>(
    deployments: &'a [Deployment],
    number: Option<u32>,
    service_name: &str,
) -> Result<&'a Deployment> {
    match number {
        Some(wanted) => deployments
            .iter()
            .find(|deployment| deployment.number == wanted)
            .ok_or_else(|| anyhow::anyhow!("`{service_name}` has no deployment #{wanted}")),
        None => deployments
            .iter()
            .find(|deployment| is_in_flight(&deployment.status))
            .ok_or_else(|| anyhow::anyhow!("`{service_name}` has no deployment in flight")),
    }
}

/// The three statuses a deployment holds before it has finished — the same
/// three the server lets a cancel reach.
fn is_in_flight(status: &str) -> bool {
    matches!(status, "queued" | "building" | "deploying")
}

/// Follows a deployment to its end, or to the first Ctrl-C.
pub async fn watch(client: &ApiClient, deployment: &Deployment) -> Result<()> {
    let interactive = std::io::IsTerminal::is_terminal(&std::io::stdout());
    let mut view = PipelineView::new(interactive);

    let logs = tokio::spawn({
        // Cloned rather than borrowed: the task outlives this scope, and the
        // clone shares the connection pool so it costs nothing.
        let client = client.clone();
        let deployment_id = deployment.id.clone();
        async move { stream_logs(&client, &deployment_id).await }
    });

    let outcome = poll_pipeline(client, &deployment.id, &mut view).await;

    // The log task ends on its own when the server closes the stream; aborting
    // covers the case where the deployment failed before anything was written.
    logs.abort();

    outcome
}

/// The same wait, answered as one JSON object when it is over.
///
/// No pipeline redrawing and no log tail: stdout carries exactly one value,
/// which is what lets `fundaia deploy --json | jq .deployment.status` work.
/// The log is a question `logs --json` answers separately. The exit code still
/// says whether it worked, so the object is detail rather than the verdict.
pub async fn watch_json(client: &ApiClient, deployment: &Deployment) -> Result<()> {
    loop {
        let detail = client.deployment(&deployment.id).await?;

        if detail.pipeline.finished {
            let succeeded = detail.pipeline.succeeded;
            let failure = detail.deployment.failure_message.clone();

            output::emit(&serde_json::json!({
                "deployment": detail.deployment,
                "pipeline": detail.pipeline,
            }));

            if !succeeded {
                bail!(failure.unwrap_or_else(|| "the deployment failed".to_owned()));
            }
            return Ok(());
        }

        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

async fn poll_pipeline(
    client: &ApiClient,
    deployment_id: &str,
    view: &mut PipelineView,
) -> Result<()> {
    loop {
        let detail = client.deployment(deployment_id).await?;

        if detail.pipeline.finished {
            view.finish(&detail.pipeline);
            return report(&detail.deployment, detail.pipeline.succeeded);
        }

        view.draw(&detail.pipeline);
        // A second is the granularity of the thing being watched: stages take
        // seconds to minutes, and polling faster only costs the server.
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

fn report(deployment: &Deployment, succeeded: bool) -> Result<()> {
    let elapsed = deployment
        .finished_at
        .as_ref()
        .and_then(|finished| Some(epoch_millis(finished)? - epoch_millis(&deployment.created_at)?))
        .map(format_millis)
        .unwrap_or_else(|| "—".to_owned());

    println!();

    if succeeded {
        println!(
            "  {} Despliegue #{} en marcha en {}",
            theme::CHECK.style(theme::success()),
            deployment.number,
            elapsed.style(theme::strong()),
        );
        println!();
        return Ok(());
    }

    println!(
        "  {} Despliegue #{} ha fallado tras {}",
        theme::CROSS.style(theme::danger()),
        deployment.number,
        elapsed,
    );
    println!();

    // A non-zero exit, so `fundaia deploy … && something` behaves.
    bail!(deployment
        .failure_message
        .clone()
        .unwrap_or_else(|| "the deployment failed".to_owned()))
}

/// The build's own output, under the pipeline.
async fn stream_logs(client: &ApiClient, deployment_id: &str) -> Result<()> {
    client
        .stream_log(deployment_id, 0, None, |line| {
            println!("  {}", render_line(&line, LineFormat::plain()));
        })
        .await
}

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

    fn deployment(number: u32, status: &str) -> Deployment {
        Deployment {
            id: format!("dep_{number}"),
            number,
            status: status.into(),
            trigger: "manual".into(),
            commit_sha: None,
            commit_subject: None,
            failure_message: None,
            created_at: "2026-09-05T10:00:00.000Z".into(),
            finished_at: None,
        }
    }

    /// The history arrives newest first, and the one in flight is the newest —
    /// but "newest" is not the rule, "in flight" is, and the list here says so.
    #[test]
    fn it_should_pick_the_deployment_in_flight_when_no_number_is_given() {
        let history = [deployment(3, "building"), deployment(2, "active")];
        assert_eq!(
            deployment_to_cancel(&history, None, "api").unwrap().number,
            3
        );
    }

    #[test]
    fn it_should_pick_the_deployment_somebody_numbered() {
        let history = [deployment(3, "building"), deployment(2, "active")];
        assert_eq!(
            deployment_to_cancel(&history, Some(2), "api")
                .unwrap()
                .number,
            2
        );
    }

    /// Nothing in flight is a refusal here, not a guess at the newest one.
    #[test]
    fn it_should_refuse_when_nothing_is_in_flight() {
        let history = [deployment(2, "active"), deployment(1, "superseded")];
        assert!(deployment_to_cancel(&history, None, "api").is_err());
    }

    #[test]
    fn it_should_refuse_a_number_the_service_never_had() {
        let history = [deployment(1, "active")];
        assert!(deployment_to_cancel(&history, Some(7), "api").is_err());
    }

    #[test]
    fn it_should_count_a_queued_deployment_as_in_flight() {
        assert!(is_in_flight("queued"));
    }

    #[test]
    fn it_should_not_count_a_cancelled_deployment_as_in_flight() {
        assert!(!is_in_flight("cancelled"));
    }
}