flareapp-core 0.1.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! Reads the git commit from the source folder of the app when the Flare client
//! starts:
//! `git.hash`, `git.branch` and `git.tag`.
//!
//! This only works when the app runs where its source is, like with `cargo run`
//! on your own machine. Production builds usually run without the source, so they
//! get the commit at compile time instead. See [`Config::git_hash`].

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};

use flareapp_otlp::KeyValue;

use crate::config::Config;

/// The longest time that all `git` commands together can take. The same as the
/// PHP client.
const TIMEOUT: Duration = Duration::from_secs(1);

/// How often a running `git` command is checked.
const POLL_INTERVAL: Duration = Duration::from_millis(5);

/// Returns the folder to read the git commit from: the application path, when the
/// config has no git hash yet and the folder exists on this machine.
pub(crate) fn source_folder(config: &Config) -> Option<PathBuf> {
    if config.git_hash.is_some() {
        return None;
    }

    let folder = PathBuf::from(config.application_path.as_deref()?);

    folder.is_dir().then_some(folder)
}

/// Runs `git` in `folder` and returns the commit as resource attributes. Returns
/// an empty list when `folder` is not in a git repository, when `git` is not
/// installed, or when `git` takes too long.
pub(crate) fn attributes(folder: &Path) -> Vec<KeyValue> {
    let deadline = Instant::now() + TIMEOUT;

    let Some(hash) = run(folder, &["rev-parse", "HEAD"], deadline) else {
        return Vec::new();
    };
    let mut attributes = vec![KeyValue::new("git.hash", hash)];

    // `git symbolic-ref` fails on a detached HEAD. Then `git.branch` is left out.
    if let Some(branch) = run(folder, &["symbolic-ref", "--short", "HEAD"], deadline) {
        attributes.push(KeyValue::new("git.branch", branch));
    }
    // Read the newest tag in the repository, the same as the PHP client.
    if let Some(tag) = run(
        folder,
        &[
            "for-each-ref",
            "--count=1",
            "--sort=-creatordate",
            "--format=%(refname:short)",
            "refs/tags",
        ],
        deadline,
    ) {
        attributes.push(KeyValue::new("git.tag", tag));
    }

    attributes
}

/// Runs `git` with `args` in `folder` and returns its trimmed output. Returns
/// `None` when `git` fails, prints nothing, or is still running at `deadline`.
fn run(folder: &Path, args: &[&str], deadline: Instant) -> Option<String> {
    let mut child = Command::new("git")
        .arg("-C")
        .arg(folder)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;

    // The commands print one short line at most, so the output never fills the
    // pipe while this function waits.
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if Instant::now() < deadline => thread::sleep(POLL_INTERVAL),
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                return None;
            }
        }
    };

    let mut output = String::new();
    child.stdout.take()?.read_to_string(&mut output).ok()?;
    let output = output.trim();

    (status.success() && !output.is_empty()).then(|| output.to_owned())
}

/// Creates a git repository in a new temporary folder, with one commit on `main`
/// and the tag `v1.0.0`. The caller removes the folder.
#[cfg(test)]
pub(crate) fn test_repository() -> PathBuf {
    use std::sync::atomic::{AtomicUsize, Ordering};

    static COUNT: AtomicUsize = AtomicUsize::new(0);
    let folder = std::env::temp_dir().join(format!(
        "flareapp-git-{}-{}",
        std::process::id(),
        COUNT.fetch_add(1, Ordering::Relaxed)
    ));
    let _ = std::fs::remove_dir_all(&folder);
    std::fs::create_dir_all(&folder).unwrap();

    let git = |args: &[&str]| {
        let status = Command::new("git")
            .arg("-C")
            .arg(&folder)
            .args([
                "-c",
                "user.name=Flare",
                "-c",
                "user.email=flare@example.test",
            ])
            .args(["-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"])
            .args(args)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        assert!(status.unwrap().success(), "git {args:?} failed");
    };
    git(&["init", "--initial-branch=main"]);
    git(&["commit", "--allow-empty", "--message", "Add the checkout"]);
    git(&["tag", "v1.0.0"]);

    folder
}

#[cfg(test)]
mod tests {
    use flareapp_otlp::AnyValue;

    use super::*;
    use crate::test_support::attribute;

    #[test]
    fn skips_the_source_folder_when_the_hash_is_known() {
        let folder = env!("CARGO_MANIFEST_DIR");

        assert_eq!(
            source_folder(&Config::new().application_path(folder)),
            Some(PathBuf::from(folder))
        );
        assert_eq!(
            source_folder(&Config::new().application_path(folder).git_hash("4f2a9c1e")),
            None
        );
        assert_eq!(
            source_folder(&Config::new().application_path("/does/not/exist")),
            None
        );
    }

    #[test]
    fn reads_nothing_outside_a_repository() {
        assert_eq!(
            attributes(&std::env::temp_dir().join("flareapp-no-such-folder")),
            Vec::new()
        );
    }

    #[test]
    fn reads_the_commit_of_a_repository() {
        let folder = test_repository();

        let attributes = attributes(&folder);
        std::fs::remove_dir_all(&folder).unwrap();

        let text = |key| attribute(&attributes, key).and_then(AnyValue::as_str);
        assert_eq!(text("git.hash").map(str::len), Some(40));
        assert_eq!(text("git.branch"), Some("main"));
        assert_eq!(text("git.tag"), Some("v1.0.0"));
        assert_eq!(attributes.len(), 3);
    }
}