Skip to main content

buildfix_receipts_cargo_bloat/
lib.rs

1use anyhow::Result;
2use buildfix_adapter_sdk::{Adapter, AdapterError, AdapterMetadata, ReceiptBuilder};
3use buildfix_types::receipt::{Finding, Location, ReceiptEnvelope, Severity, VerdictStatus};
4use camino::Utf8PathBuf;
5use serde::Deserialize;
6use std::path::Path;
7
8const SIZE_THRESHOLD_BYTES: u64 = 50_000;
9
10pub struct CargoBloatAdapter {
11    sensor_id: String,
12}
13
14impl CargoBloatAdapter {
15    pub fn new() -> Self {
16        Self {
17            sensor_id: "cargo-bloat".to_string(),
18        }
19    }
20}
21
22impl Default for CargoBloatAdapter {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl Adapter for CargoBloatAdapter {
29    fn sensor_id(&self) -> &str {
30        &self.sensor_id
31    }
32
33    fn load(&self, path: &Path) -> Result<ReceiptEnvelope, AdapterError> {
34        let content = std::fs::read_to_string(path).map_err(AdapterError::Io)?;
35        convert_cargo_bloat_json(&content, &self.sensor_id)
36    }
37}
38
39impl AdapterMetadata for CargoBloatAdapter {
40    fn name(&self) -> &str {
41        "cargo-bloat"
42    }
43
44    fn version(&self) -> &str {
45        env!("CARGO_PKG_VERSION")
46    }
47
48    fn supported_schemas(&self) -> &[&str] {
49        &["cargo-bloat.report.v1"]
50    }
51}
52
53fn convert_cargo_bloat_json(
54    content: &str,
55    sensor_id: &str,
56) -> Result<ReceiptEnvelope, AdapterError> {
57    let parsed: serde_json::Value = serde_json::from_str(content).map_err(AdapterError::Json)?;
58    let report: CargoBloatReport = serde_json::from_value(parsed).map_err(AdapterError::Json)?;
59
60    let mut findings = Vec::new();
61
62    if let Some(ref crates) = report.crate_info {
63        for krate in crates {
64            if krate.size >= SIZE_THRESHOLD_BYTES {
65                let check_id = if krate.is_lib {
66                    "size.large_crate".to_string()
67                } else {
68                    "bloat.large_dependency".to_string()
69                };
70
71                let message = if krate.is_lib {
72                    format!(
73                        "Crate '{}' contributes {} bytes ({}) to binary size",
74                        krate.name, krate.size, krate.percent
75                    )
76                } else {
77                    format!(
78                        "Dependency '{}' contributes {} bytes ({}) to binary size",
79                        krate.name, krate.size, krate.percent
80                    )
81                };
82
83                findings.push(Finding {
84                    severity: Severity::Info,
85                    check_id: Some(check_id),
86                    code: None,
87                    message: Some(message),
88                    location: Some(Location {
89                        path: Utf8PathBuf::from("Cargo.toml"),
90                        line: None,
91                        column: None,
92                    }),
93                    fingerprint: None,
94                    data: Some(serde_json::json!({
95                        "crate_name": krate.name,
96                        "size_bytes": krate.size,
97                        "percent": krate.percent,
98                        "is_lib": krate.is_lib,
99                    })),
100                    ..Default::default()
101                });
102            }
103        }
104    }
105
106    let status = if !findings.is_empty() {
107        VerdictStatus::Warn
108    } else {
109        VerdictStatus::Pass
110    };
111
112    let mut builder = ReceiptBuilder::new(sensor_id)
113        .with_schema("cargo-bloat.report.v1")
114        .with_status(status)
115        .with_counts(findings.len() as u64, 0, findings.len() as u64);
116
117    for finding in findings {
118        builder = builder.with_finding(finding);
119    }
120
121    let mut receipt = builder.build();
122    receipt.data = Some(serde_json::json!({
123        "analyzed": report.analyzed,
124        "total_size": report.total_size,
125        "crate_count": report.crate_info.as_ref().map(|c| c.len()).unwrap_or(0),
126        "top_functions_count": report.top_functions.as_ref().map(|f| f.len()).unwrap_or(0),
127    }));
128
129    Ok(receipt)
130}
131
132#[derive(Debug, Deserialize)]
133#[allow(dead_code)]
134struct CargoBloatReport {
135    analyzed: String,
136    total_size: u64,
137    crate_info: Option<Vec<CrateInfo>>,
138    top_functions: Option<Vec<TopFunction>>,
139}
140
141#[derive(Debug, Deserialize)]
142#[allow(dead_code)]
143struct CrateInfo {
144    name: String,
145    size: u64,
146    percent: String,
147    #[serde(rename = "is_lib")]
148    is_lib: bool,
149}
150
151#[derive(Debug, Deserialize)]
152#[allow(dead_code)]
153struct TopFunction {
154    name: String,
155    size: u64,
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn test_adapter_sensor_id() {
164        let adapter = CargoBloatAdapter::new();
165        assert_eq!(adapter.sensor_id(), "cargo-bloat");
166    }
167
168    #[test]
169    fn test_convert_cargo_bloat_json_with_large_crates() {
170        let json = r#"{
171          "analyzed": "target/release/myapp",
172          "total_size": 1000000,
173          "crate_info": [
174            {"name": "serde", "size": 50000, "percent": "5.0", "is_lib": true},
175            {"name": "tokio", "size": 80000, "percent": "8.0", "is_lib": true},
176            {"name": "small", "size": 1000, "percent": "0.1", "is_lib": true}
177          ],
178          "top_functions": [
179            {"name": "serde::serialize", "size": 10000},
180            {"name": "tokio::run", "size": 8000}
181          ]
182        }"#;
183
184        let receipt = convert_cargo_bloat_json(json, "cargo-bloat").unwrap();
185
186        assert_eq!(receipt.findings.len(), 2);
187        assert_eq!(receipt.verdict.status, VerdictStatus::Warn);
188
189        let serde_finding = &receipt.findings[0];
190        assert_eq!(serde_finding.check_id, Some("size.large_crate".to_string()));
191        assert!(serde_finding.message.as_ref().unwrap().contains("serde"));
192        assert_eq!(serde_finding.severity, Severity::Info);
193
194        let tokio_finding = &receipt.findings[1];
195        assert_eq!(tokio_finding.check_id, Some("size.large_crate".to_string()));
196        assert!(tokio_finding.message.as_ref().unwrap().contains("tokio"));
197    }
198
199    #[test]
200    fn test_convert_cargo_bloat_json_no_large_crates() {
201        let json = r#"{
202          "analyzed": "target/release/myapp",
203          "total_size": 100000,
204          "crate_info": [
205            {"name": "small", "size": 1000, "percent": "1.0", "is_lib": true}
206          ],
207          "top_functions": []
208        }"#;
209
210        let receipt = convert_cargo_bloat_json(json, "cargo-bloat").unwrap();
211
212        assert_eq!(receipt.findings.len(), 0);
213        assert_eq!(receipt.verdict.status, VerdictStatus::Pass);
214    }
215
216    #[test]
217    fn test_convert_cargo_bloat_json_non_lib_dependency() {
218        let json = r#"{
219          "analyzed": "target/release/myapp",
220          "total_size": 1000000,
221          "crate_info": [
222            {"name": "some_binary_dep", "size": 60000, "percent": "6.0", "is_lib": false}
223          ],
224          "top_functions": []
225        }"#;
226
227        let receipt = convert_cargo_bloat_json(json, "cargo-bloat").unwrap();
228
229        assert_eq!(receipt.findings.len(), 1);
230        let finding = &receipt.findings[0];
231        assert_eq!(finding.check_id, Some("bloat.large_dependency".to_string()));
232        assert!(finding.message.as_ref().unwrap().contains("Dependency"));
233    }
234
235    #[test]
236    fn test_convert_cargo_bloat_json_empty() {
237        let json = r#"{
238          "analyzed": "target/release/myapp",
239          "total_size": 1000,
240          "crate_info": [],
241          "top_functions": []
242        }"#;
243
244        let receipt = convert_cargo_bloat_json(json, "cargo-bloat").unwrap();
245
246        assert_eq!(receipt.findings.len(), 0);
247        assert_eq!(receipt.verdict.status, VerdictStatus::Pass);
248    }
249
250    #[test]
251    fn test_convert_cargo_bloat_json_null_fields() {
252        let json = r#"{
253          "analyzed": "target/release/myapp",
254          "total_size": 1000,
255          "crate_info": null,
256          "top_functions": null
257        }"#;
258
259        let receipt = convert_cargo_bloat_json(json, "cargo-bloat").unwrap();
260
261        assert_eq!(receipt.findings.len(), 0);
262        assert_eq!(receipt.verdict.status, VerdictStatus::Pass);
263    }
264}