flareapp-core 0.2.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! Reads source paths: whether a file is application code, and the absolute path
//! of a report location.
//!
//! `Location::file()` and `file!()` are relative to the root of the Cargo
//! workspace, like `crates/app/src/main.rs`. The debug info joins the same path
//! with the folder the build ran in. Without joining them, Flare sees two different
//! files for one place, and puts the same error in two groups.

use std::ffi::OsStr;
use std::path::Path;

/// The crates of the Flare client. The code of these crates is never application
/// code. An app can use them through a path dependency. [`is_dependency`] does not
/// catch that case, because the path has none of the Cargo folders that
/// `is_dependency` looks for.
///
/// `flareapp-backtrace` also uses this list, through [`is_flare_crate`], to
/// remove the frames of the Flare client from the top of a stack trace. Add each
/// new Flare crate here.
const FLARE_CRATES: &[&str] = &[
    "cargo_flareapp",
    "flareapp",
    "flareapp_actix",
    "flareapp_anyhow",
    "flareapp_backtrace",
    "flareapp_core",
    "flareapp_log",
    "flareapp_macros",
    "flareapp_otlp",
    "flareapp_panic",
    "flareapp_reqwest",
    "flareapp_sqlx",
    "flareapp_tower",
    "flareapp_tracing",
    "flareapp_web",
];

/// Returns `true` when a source file is application code. Not part of the public
/// API.
///
/// Code in the standard library, in a dependency or in the Flare client is not
/// application code. A dependency listed in `app_crates`, which
/// `Config::app_crate` sets, is application code.
#[doc(hidden)]
pub fn is_application_file(file: &Path, app_crates: &[String]) -> bool {
    let crate_name = file_crate_name(file);
    if crate_name.as_deref().is_some_and(is_flare_crate) {
        return false;
    }

    !is_dependency(file) || crate_name.is_some_and(|name| app_crates.contains(&name))
}

/// Returns `true` when `name` is a crate of the Flare client, like
/// `flareapp_core`. The name must match exactly, so an app crate like
/// `flareapp_demo` is not a Flare crate. Not part of the public API.
#[doc(hidden)]
pub fn is_flare_crate(name: &str) -> bool {
    FLARE_CRATES.contains(&name)
}

/// Returns `true` when `file` is in the standard library or in a dependency that
/// Cargo downloaded. Not part of the public API.
///
/// Cargo's folders are matched without `.cargo`, because Docker images put them in
/// `/usr/local/cargo`:
///
/// - crates.io: `…/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54.1/…`
/// - git: `…/git/checkouts/axum-2b8ad3d5d0c2e5f1/a1b2c3d/…`
/// - the standard library: `/rustc/<commit>/library/…`, or
///   `…/lib/rustlib/src/rust/library/…` with the `rust-src` component
///
/// The whole shape must match, so an app folder like `crates/registry/src` stays
/// app code.
#[doc(hidden)]
pub fn is_dependency(file: &Path) -> bool {
    // Windows paths use `\`.
    let file = file.to_string_lossy().replace('\\', "/");
    let parts: Vec<&str> = file.split('/').collect();

    is_in_registry(&parts) || is_in_git_checkout(&parts) || is_in_standard_library(&parts)
}

/// Returns `true` when the folders in `parts` have the shape of a crate that
/// Cargo downloaded from a registry, like crates.io:
/// `registry/src/<index>/<name>-<version>`.
fn is_in_registry(parts: &[&str]) -> bool {
    parts.windows(4).any(|window| {
        matches!(window, ["registry", "src", _, crate_folder] if split_version(crate_folder).is_some())
    })
}

/// Returns `true` when the folders in `parts` have the shape of a git
/// dependency that Cargo checked out: `git/checkouts`.
fn is_in_git_checkout(parts: &[&str]) -> bool {
    parts
        .windows(2)
        .any(|window| matches!(window, ["git", "checkouts"]))
}

/// Returns `true` when the folders in `parts` have the shape of the standard
/// library: `rustc/<commit>`, or `rustlib/src` with the `rust-src` component.
fn is_in_standard_library(parts: &[&str]) -> bool {
    parts.windows(2).any(|window| match window {
        ["rustc", commit] => {
            !commit.is_empty() && commit.bytes().all(|byte| byte.is_ascii_hexdigit())
        }
        ["rustlib", "src"] => true,
        _ => false,
    })
}

/// Returns the name of the crate that `file` belongs to, with `-` written as `_`
/// like in a path in code: `md_5` for `…/registry/src/index/md-5-0.10.6/src/lib.rs`.
/// This function is not part of the public API.
#[doc(hidden)]
pub fn file_crate_name(file: &Path) -> Option<String> {
    crate_folder(file).map(code_crate_name)
}

/// Returns the name of a crate as Rust code writes the name, with each `-` as
/// `_`. Cargo allows a package name like `my-billing`, but a path in code says
/// `my_billing`.
pub(crate) fn code_crate_name(name: &str) -> String {
    name.replace('-', "_")
}

/// Returns the name of the crate folder that `file` is in, without the version,
/// like `tokio` for `…/registry/src/index/tokio-1.54.1/src/runtime/park.rs`.
fn crate_folder(file: &Path) -> Option<&str> {
    // From the end, `find` stops after the last `src`, so `next` returns the folder
    // above it.
    let mut parts = file.iter().rev().filter_map(OsStr::to_str);
    parts.find(|part| *part == "src")?;
    let folder = parts.next()?;

    Some(split_version(folder).map_or(folder, |(name, _)| name))
}

/// Splits the folder of a downloaded crate into its name and version, like
/// `md-5` and `0.10.6` for `md-5-0.10.6`. Returns `None` when the folder has no
/// version.
fn split_version(folder: &str) -> Option<(&str, &str)> {
    folder.match_indices('-').find_map(|(index, _)| {
        let version = folder.get(index + 1..)?;

        is_version(version).then_some((folder.get(..index)?, version))
    })
}

/// Returns `true` when `text` is a semver version, like `1.54.1` or
/// `0.2.0-beta.1`.
fn is_version(text: &str) -> bool {
    let is_number = |part: Option<&str>| {
        part.is_some_and(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
    };
    let mut parts = text.split('.');

    is_number(parts.next())
        && is_number(parts.next())
        && parts
            .next()
            .is_some_and(|patch| patch.starts_with(|c: char| c.is_ascii_digit()))
}

/// Finds the root of the Cargo workspace from the folder of a crate's
/// `Cargo.toml` and a `file!()` path in that crate. Not part of the public API:
/// `flareapp::config!` calls it.
///
/// With `manifest_dir` `/code/shop/crates/app` and `file` `crates/app/src/main.rs`,
/// the root is `/code/shop`. A crate outside a workspace is its own root.
#[doc(hidden)]
pub fn workspace_root(manifest_dir: &str, file: &str) -> String {
    let manifest_dir = Path::new(manifest_dir);
    let file = Path::new(file);

    // Walk up from `manifest_dir`. The root is the highest folder where the rest of
    // `manifest_dir`, like `crates/app`, is the start of `file`.
    manifest_dir
        .ancestors()
        .filter(|root| {
            manifest_dir
                .strip_prefix(root)
                .is_ok_and(|member| !member.as_os_str().is_empty() && file.starts_with(member))
        })
        .last()
        .unwrap_or(manifest_dir)
        .to_string_lossy()
        .into_owned()
}

/// Joins a relative `file` with the workspace root. Absolute paths, like the
/// files of dependencies, stay the same.
pub(crate) fn absolute(workspace_root: Option<&str>, file: &str) -> String {
    match workspace_root {
        Some(root) if Path::new(file).is_relative() => {
            Path::new(root).join(file).to_string_lossy().into_owned()
        }
        _ => file.to_owned(),
    }
}

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

    use super::*;

    #[test]
    fn a_crate_outside_a_workspace_is_its_own_root() {
        assert_eq!(workspace_root("/code/shop", "src/main.rs"), "/code/shop");
    }

    #[test]
    fn finds_the_root_of_a_workspace_member() {
        assert_eq!(
            workspace_root("/code/shop/crates/app", "crates/app/src/main.rs"),
            "/code/shop"
        );
    }

    #[test]
    fn files_outside_src_have_the_same_root() {
        assert_eq!(
            workspace_root("/code/shop/crates/app", "crates/app/examples/demo.rs"),
            "/code/shop"
        );
    }

    #[test]
    fn falls_back_to_the_crate_folder_for_absolute_files() {
        assert_eq!(
            workspace_root("/code/shop", "/code/shop/target/out/generated.rs"),
            "/code/shop"
        );
    }

    #[test]
    fn relative_files_are_joined_with_the_root() {
        let file = absolute(Some("/code/shop"), "crates/app/src/main.rs");

        // `Path` compares components, so the `\` that Windows joins with matches `/`.
        assert_eq!(
            Path::new(&file),
            Path::new("/code/shop/crates/app/src/main.rs")
        );
    }

    #[test]
    fn absolute_files_stay_the_same() {
        let file = "/home/me/.cargo/registry/src/axum-0.8.9/src/routing/mod.rs";

        assert_eq!(absolute(Some("/code/shop"), file), file);
    }

    #[test]
    fn relative_files_stay_the_same_without_a_root() {
        assert_eq!(absolute(None, "src/main.rs"), "src/main.rs");
    }

    #[test]
    fn flare_crates_in_a_path_dependency_are_not_application_code() {
        let file = Path::new("/code/flare-client-rust/crates/flareapp-tower/src/lib.rs");

        assert!(!is_application_file(file, &[]));
    }

    #[test]
    fn flare_crates_in_the_workspace_are_not_application_code() {
        assert!(!is_application_file(
            Path::new("crates/flareapp/src/lib.rs"),
            &[]
        ));
    }

    /// A crate missing from `FLARE_CRATES` counts as application code when an app
    /// uses it through a path dependency.
    #[test]
    fn flare_crates_are_the_crates_of_this_workspace() {
        let crates = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
        let mut names: Vec<String> = fs::read_dir(crates)
            .unwrap()
            .map(|entry| entry.unwrap())
            .filter(|entry| entry.path().is_dir())
            .map(|entry| code_crate_name(entry.file_name().to_str().unwrap()))
            .collect();
        names.sort_unstable();
        let mut flare_crates = FLARE_CRATES.to_vec();
        flare_crates.sort_unstable();

        assert_eq!(names, flare_crates);
    }

    #[test]
    fn app_crates_named_like_flare_crates_are_application_code() {
        let file = Path::new("/code/flareapp-demo/src/main.rs");

        assert!(is_application_file(file, &[]));
    }

    #[test]
    fn app_files_are_application_code() {
        assert!(is_application_file(
            Path::new("crates/app/src/main.rs"),
            &[]
        ));
    }

    #[test]
    fn downloaded_dependencies_are_not_application_code() {
        let tokio = Path::new(
            "/home/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.54.1/src/lib.rs",
        );

        assert!(!is_application_file(tokio, &[]));
    }

    #[test]
    fn dependencies_marked_as_app_crates_are_application_code() {
        let billing = Path::new(
            "/home/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/my-billing-1.2.0/src/lib.rs",
        );

        assert!(is_application_file(billing, &["my_billing".to_owned()]));
    }

    #[test]
    fn the_crate_folder_of_a_dependency_has_no_version() {
        let tokio =
            Path::new("/home/me/.cargo/registry/src/index/tokio-1.54.1/src/runtime/park.rs");

        assert_eq!(crate_folder(tokio), Some("tokio"));
    }

    #[test]
    fn the_crate_folder_of_a_workspace_crate_is_its_folder() {
        let file = Path::new("/app/crates/flareapp/src/lib.rs");

        assert_eq!(crate_folder(file), Some("flareapp"));
    }

    #[test]
    fn a_file_outside_a_src_folder_has_no_crate_folder() {
        assert_eq!(crate_folder(Path::new("/app/main.rs")), None);
    }

    #[test]
    fn splits_crate_folders_at_the_version() {
        assert_eq!(split_version("tokio-1.54.1"), Some(("tokio", "1.54.1")));
        assert_eq!(split_version("md-5-0.10.6"), Some(("md-5", "0.10.6")));
        assert_eq!(
            split_version("flareapp-backtrace-0.2.0-beta.1"),
            Some(("flareapp-backtrace", "0.2.0-beta.1"))
        );
        assert_eq!(split_version("users-2"), None);
    }
}