fundaia 0.25.1

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
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use flate2::write::GzEncoder;
use flate2::Compression;
use ignore::WalkBuilder;
use owo_colors::OwoColorize;

use crate::api::client::ApiClient;
use crate::commands::deploy;
use crate::output::{self, Format};
use crate::render::theme;

/// Anything past this is refused before a byte leaves the machine.
///
/// The server refuses it too and that one is the rule; this is the courtesy —
/// finding out after uploading a hundred megabytes over a domestic connection
/// is a minute somebody does not get back. Kept in step with
/// `defaultUploadLimitBytes` on the platform.
const LIMIT_BYTES: u64 = 100 * 1024 * 1024;

/// Directories nobody ever means to deploy, whatever the ignore files say.
///
/// `.git` is the one that matters: it is frequently larger than the code, it is
/// not in `.gitignore` for obvious reasons, and no build has ever needed it.
/// The other two are what a previous build left behind, and shipping them means
/// uploading megabytes so the image can overwrite them.
const ALWAYS_EXCLUDED: [&str; 4] = [".git", ".hg", "node_modules", ".venv"];

/// What a packed directory turned out to be.
pub struct Packed {
    pub bytes: Vec<u8>,
    pub files: usize,
}

/// Uploads the code in a directory and watches it deploy.
///
/// The whole verb `fundaia up` is: a service built from uploaded code has no
/// branch to read, so the archive arriving *is* the push. Packing happens here
/// rather than on the server for the obvious reason and one less obvious one —
/// the ignore rules that decide what a build needs are files in the directory
/// being packed, and sending everything so the server can drop most of it is
/// the transfer this exists to avoid.
pub async fn run(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    directory: &Path,
    deploy_it: 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 packed = pack(directory)?;
    let name = archive_name(directory);

    if !format.is_json() {
        println!();
        println!(
            "  {} {} {} — {} archivos, {}",
            theme::ARROW.style(theme::accent()),
            project.name.style(theme::muted()),
            service.name.style(theme::strong()),
            packed.files.style(theme::strong()),
            human_size(packed.bytes.len() as u64).style(theme::strong()),
        );
        println!();
    }

    let accepted = client
        .upload(&service.id, packed.bytes, &name, deploy_it)
        .await?;

    let Some(deployment) = accepted.deployment else {
        // Nothing was built, so there is no pipeline to draw and nothing to
        // wait for: the archive is stored and that is the whole outcome.
        if format.is_json() {
            output::emit(&accepted.upload);
        } else {
            println!(
                "  {} Código guardado. Despliégalo con: fundaia deploy {} {}",
                theme::CHECK.style(theme::success()),
                project.slug,
                service.slug,
            );
        }
        return Ok(());
    };

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

    if !follow {
        println!(
            "  {}",
            format!(
                "Despliegue #{} en marcha. Síguelo con: fundaia logs {} {}",
                deployment.number, project.slug, service.slug
            )
            .style(theme::muted()),
        );
        return Ok(());
    }

    deploy::watch(client, &deployment).await
}

/// The archives this service has been given, newest first.
pub async fn list(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let page = client.uploads(&service.id).await?;

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

    if page.uploads.is_empty() {
        println!();
        println!(
            "  {}",
            "Este servicio no tiene código todavía. Súbelo con `fundaia up`.".style(theme::muted()),
        );
        println!();
        return Ok(());
    }

    println!();
    for upload in &page.uploads {
        let current = page.current.as_deref() == Some(upload.id.as_str());
        // The one it builds from is marked rather than listed first: the order
        // is by arrival, and reordering it would hide when a rollback moved it.
        let mark = if current {
            theme::CHECK.style(theme::success()).to_string()
        } else {
            " ".to_owned()
        };
        let digest: String = upload.digest.chars().take(12).collect();

        println!(
            "  {} {}  {}  {}",
            mark,
            upload.file_name.style(theme::strong()),
            human_size(upload.size_bytes).style(theme::muted()),
            digest.style(theme::muted()),
        );
    }
    println!();
    Ok(())
}

/// Walks a directory into a gzipped tar, honouring every ignore file it finds.
///
/// `ignore` is the crate ripgrep uses, and taking it rather than reading
/// `.gitignore` by hand is the whole reason this is short: it already handles
/// nested ignore files, negations, `**`, the global git excludes and a
/// directory that is not a repository at all. `.fundaiaignore` is added as a
/// custom name so a project can exclude something from a deployment without
/// excluding it from git — test fixtures, a local database, a directory of
/// screenshots.
///
pub fn pack(directory: &Path) -> Result<Packed> {
    if !directory.is_dir() {
        bail!("{} is not a directory", directory.display());
    }

    let encoder = GzEncoder::new(Vec::new(), Compression::default());
    let mut archive = tar::Builder::new(encoder);
    let mut files = 0usize;
    let mut bytes = 0u64;

    let mut walker = WalkBuilder::new(directory);
    /*
     * Spelled out rather than called as a method, and it is not style.
     * `OwoColorize` is implemented for every type and carries a `hidden()` of
     * its own — the ANSI attribute — so `walker.hidden(false)` resolves to the
     * colour trait and fails on the argument. Naming the type is what picks the
     * walker's.
     *
     * Hidden files are kept on purpose: `.env.example`, `.dockerignore` and
     * `.npmrc` are all hidden and all matter to a build.
     */
    WalkBuilder::hidden(&mut walker, false);
    walker.git_ignore(true);
    walker.git_global(true);
    walker.git_exclude(true);
    walker.add_custom_ignore_filename(".fundaiaignore");
    walker.filter_entry(|entry: &ignore::DirEntry| {
        !ALWAYS_EXCLUDED.contains(&entry.file_name().to_string_lossy().as_ref())
    });

    for entry in walker.build() {
        let entry = entry.context("could not read the directory")?;
        if !entry.file_type().is_some_and(|kind| kind.is_file()) {
            continue;
        }

        let relative = entry
            .path()
            .strip_prefix(directory)
            .context("a file walked out of the directory being packed")?;

        bytes += entry.metadata().map(|meta| meta.len()).unwrap_or(0);
        if bytes > LIMIT_BYTES {
            bail!(
                "the code is larger than {} — leave out what the build does not need with a .fundaiaignore",
                human_size(LIMIT_BYTES)
            );
        }

        archive
            .append_path_with_name(entry.path(), relative)
            .with_context(|| format!("could not pack {}", relative.display()))?;
        files += 1;
    }

    if files == 0 {
        bail!("there is nothing to upload in {}", directory.display());
    }

    let encoder = archive
        .into_inner()
        .context("could not finish the archive")?;
    let bytes = encoder.finish().context("could not compress the archive")?;

    Ok(Packed { bytes, files })
}

/// What the archive is called in the history: the directory's own name.
///
/// A person recognises `panel-web.tar.gz` and recognises nothing at all in a
/// timestamp, and the platform already records when it arrived.
pub fn archive_name(directory: &Path) -> String {
    let absolute = directory
        .canonicalize()
        .unwrap_or_else(|_| PathBuf::from(directory));

    let stem = absolute
        .file_name()
        .map(|name| name.to_string_lossy().to_string())
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| "código".to_owned());

    format!("{stem}.tar.gz")
}

/// Bytes as somebody would say them, which is never in bytes past a kilobyte.
pub fn human_size(bytes: u64) -> String {
    const KIB: f64 = 1024.0;
    let value = bytes as f64;

    if value < KIB {
        return format!("{bytes} B");
    }
    if value < KIB * KIB {
        return format!("{:.0} KB", value / KIB);
    }
    format!("{:.1} MB", value / (KIB * KIB))
}

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

    /// A directory with a `.gitignore`, something it ignores, and a `.git`.
    fn project() -> tempdir::Directory {
        let directory = tempdir::Directory::new();
        fs::write(directory.path().join("package.json"), "{}").unwrap();
        fs::write(directory.path().join(".gitignore"), "secret.txt\n").unwrap();
        fs::write(directory.path().join("secret.txt"), "shhh").unwrap();
        fs::create_dir(directory.path().join(".git")).unwrap();
        fs::write(directory.path().join(".git").join("HEAD"), "ref: x").unwrap();
        fs::create_dir(directory.path().join("node_modules")).unwrap();
        fs::write(directory.path().join("node_modules").join("a.js"), "x").unwrap();
        directory
    }

    fn packed_names(directory: &Path) -> Vec<String> {
        let packed = pack(directory).expect("the directory packs");
        let decoder = flate2::read::GzDecoder::new(packed.bytes.as_slice());
        let mut archive = tar::Archive::new(decoder);

        archive
            .entries()
            .expect("the archive can be read")
            .map(|entry| {
                entry
                    .expect("an entry")
                    .path()
                    .expect("a path")
                    .to_string_lossy()
                    .to_string()
            })
            .collect()
    }

    #[test]
    fn it_should_pack_the_files_a_build_needs() {
        let directory = project();

        assert!(packed_names(directory.path()).contains(&"package.json".to_owned()));
    }

    #[test]
    fn it_should_leave_out_what_gitignore_excludes() {
        let directory = project();

        assert!(!packed_names(directory.path()).contains(&"secret.txt".to_owned()));
    }

    /// `.git` is not in `.gitignore` for obvious reasons, and is frequently
    /// larger than the code it holds the history of.
    #[test]
    fn it_should_leave_out_the_git_directory() {
        let directory = project();

        assert!(!packed_names(directory.path())
            .iter()
            .any(|name| name.starts_with(".git/")));
    }

    #[test]
    fn it_should_leave_out_node_modules() {
        let directory = project();

        assert!(!packed_names(directory.path())
            .iter()
            .any(|name| name.starts_with("node_modules/")));
    }

    /// Hidden and load-bearing: a Containerfile reads `.dockerignore`, a build
    /// reads `.npmrc`, and the walker's own default would drop both.
    #[test]
    fn it_should_keep_a_hidden_file_a_build_reads() {
        let directory = project();
        fs::write(directory.path().join(".npmrc"), "registry=x").unwrap();

        assert!(packed_names(directory.path()).contains(&".npmrc".to_owned()));
    }

    #[test]
    fn it_should_refuse_a_directory_with_nothing_in_it() {
        let directory = tempdir::Directory::new();

        assert!(pack(directory.path()).is_err());
    }

    #[test]
    fn it_should_name_the_archive_after_the_directory() {
        let directory = tempdir::Directory::new();

        assert!(archive_name(directory.path()).ends_with(".tar.gz"));
    }

    #[test]
    fn it_should_print_megabytes_once_there_are_any() {
        assert_eq!(human_size(3 * 1024 * 1024), "3.0 MB");
    }

    #[test]
    fn it_should_print_plain_bytes_below_a_kilobyte() {
        assert_eq!(human_size(512), "512 B");
    }

    /// A temporary directory that removes itself, because a test that leaves
    /// one behind on every run fills a laptop a megabyte at a time.
    mod tempdir {
        use std::path::{Path, PathBuf};
        use std::sync::atomic::{AtomicUsize, Ordering};

        static COUNTER: AtomicUsize = AtomicUsize::new(0);

        pub struct Directory(PathBuf);

        impl Directory {
            pub fn new() -> Self {
                let unique = COUNTER.fetch_add(1, Ordering::Relaxed);
                let path = std::env::temp_dir()
                    .join(format!("fundaia-up-{}-{unique}", std::process::id()));
                std::fs::create_dir_all(&path).expect("a temporary directory");
                Self(path)
            }

            pub fn path(&self) -> &Path {
                &self.0
            }
        }

        impl Drop for Directory {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
    }
}