Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

6.4 KB
Raw Blame
//! Codegen for the `WarningType` enum from `warning_types.generated.json`.
//!
//! That JSON mirrors the whole Node.js registry (the single source of truth,
//! `nodejs/src/ingestion/common/ingestion-warning-types.ts`) via
//! `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types`. Generating the enum from the
//! committed artifact keeps Rust's warning types — and their category/severity classification —
//! from drifting out of the Node.js registry while respecting the isolated Rust build context
//! (the artifact lives inside this crate, so no cross-workspace file access is needed at build
//! time).

use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo");
    let json_path = Path::new(&manifest_dir).join("warning_types.generated.json");
    // Rerun only when the mirrored artifact changes.
    println!("cargo:rerun-if-changed={}", json_path.display());

    let raw = fs::read_to_string(&json_path)
        .unwrap_or_else(|e| panic!("read {}: {e}", json_path.display()));
    let parsed: serde_json::Value =
        serde_json::from_str(&raw).unwrap_or_else(|e| panic!("parse {}: {e}", json_path.display()));

    let entries: Vec<(String, String, String, bool)> = parsed
        .get("types")
        .and_then(|t| t.as_array())
        .unwrap_or_else(|| panic!("`types` array missing in {}", json_path.display()))
        .iter()
        .map(|v| {
            let get = |k: &str| {
                v.get(k)
                    .and_then(|s| s.as_str())
                    .unwrap_or_else(|| panic!("`{k}` missing in {}", json_path.display()))
                    .to_string()
            };
            let capture_produced = v
                .get("captureProduced")
                .and_then(|b| b.as_bool())
                .unwrap_or_else(|| panic!("`captureProduced` missing in {}", json_path.display()));
            (
                get("type"),
                get("category"),
                get("severity"),
                capture_produced,
            )
        })
        .collect();

    assert!(
        !entries.is_empty(),
        "warning types artifact {} is empty",
        json_path.display()
    );

    let variants: Vec<String> = entries
        .iter()
        .map(|(tag, _, _, _)| to_pascal_case(tag))
        .collect();

    let mut code = String::new();
    code.push_str("// @generated by build.rs from warning_types.generated.json — do not edit.\n");
    code.push_str("/// A warning type known to the v2 ingestion warnings pipeline.\n");
    code.push_str("///\n");
    code.push_str("/// Generated from the Node.js registry, together with each type's declared\n");
    code.push_str(
        "/// category and severity. Every variant's `as_str()` doubles as the produced\n",
    );
    code.push_str(
        "/// message `type` field and the `type` metric label, so the values must stay\n",
    );
    code.push_str("/// stable.\n");
    code.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n");
    code.push_str("pub enum WarningType {\n");
    for variant in &variants {
        code.push_str(&format!("    {variant},\n"));
    }
    code.push_str("}\n\n");

    code.push_str("impl WarningType {\n");
    code.push_str("    /// All registered warning types, for exhaustive tests.\n");
    code.push_str(&format!(
        "    pub const ALL: [WarningType; {}] = [\n",
        variants.len()
    ));
    for variant in &variants {
        code.push_str(&format!("        WarningType::{variant},\n"));
    }
    code.push_str("    ];\n\n");

    code.push_str(
        "    /// The message/metric `type` string. Matches the originating error tag 1:1.\n",
    );
    code.push_str("    pub const fn as_str(self) -> &'static str {\n");
    code.push_str("        match self {\n");
    for (variant, (tag, _, _, _)) in variants.iter().zip(entries.iter()) {
        code.push_str(&format!(
            "            WarningType::{variant} => \"{tag}\",\n"
        ));
    }
    code.push_str("        }\n    }\n\n");

    code.push_str("    /// The registry-declared category. Producers that serialize the final\n");
    code.push_str("    /// warning payload themselves stamp this into `details`.\n");
    code.push_str("    pub const fn category(self) -> &'static str {\n");
    code.push_str("        match self {\n");
    for (variant, (_, category, _, _)) in variants.iter().zip(entries.iter()) {
        code.push_str(&format!(
            "            WarningType::{variant} => \"{category}\",\n"
        ));
    }
    code.push_str("        }\n    }\n\n");

    code.push_str("    /// The registry-declared severity. Producers that serialize the final\n");
    code.push_str("    /// warning payload themselves stamp this into `details`.\n");
    code.push_str("    pub const fn severity(self) -> &'static str {\n");
    code.push_str("        match self {\n");
    for (variant, (_, _, severity, _)) in variants.iter().zip(entries.iter()) {
        code.push_str(&format!(
            "            WarningType::{variant} => \"{severity}\",\n"
        ));
    }
    code.push_str("        }\n    }\n\n");

    code.push_str("    /// Whether the Node consumer's trust allowlist for the capture envelope\n");
    code.push_str("    /// (`CAPTURE_PRODUCED_WARNING_TYPES`) contains this type. The registry\n");
    code.push_str("    /// test welds capture's `from_tag` emit allowlist to exactly this set.\n");
    code.push_str("    pub const fn capture_produced(self) -> bool {\n");
    code.push_str("        match self {\n");
    for (variant, (_, _, _, capture_produced)) in variants.iter().zip(entries.iter()) {
        code.push_str(&format!(
            "            WarningType::{variant} => {capture_produced},\n"
        ));
    }
    code.push_str("        }\n    }\n}\n");

    let out_dir = env::var("OUT_DIR").expect("OUT_DIR is set by cargo");
    let dest = Path::new(&out_dir).join("warning_types.rs");
    fs::write(&dest, code).unwrap_or_else(|e| panic!("write {}: {e}", dest.display()));
}

/// `missing_event_name` -> `MissingEventName`.
fn to_pascal_case(snake: &str) -> String {
    snake
        .split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect()
}