Skip to main content

trusty_code/
build_info.rs

1//! Build and version tracking.
2//!
3//! Why: We need a monotonic build counter that increments on every process
4//! start, independent of the semver version. The combined `vX.Y.Z build #N`
5//! string lets us correlate log lines and performance telemetry with the
6//! exact binary invocation that produced them. Keeping the counter on disk
7//! (rather than baked into the binary) lets a single `cargo build` produce
8//! many distinct "builds" across repeated `cargo run` invocations during
9//! development — which is exactly when we need the disambiguation.
10//!
11//! What: Reads `.open-mpm/state/build.json` relative to the current working
12//! directory, increments the `build` counter (defaulting to 0 if the file
13//! is missing or malformed), and writes the result back atomically via
14//! `rename(2)` from a sibling `.tmp` file.
15//!
16//! Test: `BuildInfo::load_and_increment` in an empty temp dir returns
17//! `build == 1`; calling it again returns `build == 2`; a corrupt
18//! `build.json` is treated as "build = 0" and replaced on the next call.
19
20use std::path::{Path, PathBuf};
21
22use anyhow::{Context, Result};
23use chrono::Utc;
24use serde::{Deserialize, Serialize};
25
26/// Compile-time semver from Cargo.toml.
27///
28/// Why: Canonical version string embedded in the binary so runtime code never
29/// needs to read Cargo.toml.
30/// What: `env!("CARGO_PKG_VERSION")` forwarded as a `'static str`.
31/// Test: Asserted non-empty in `version_string_contains_version`.
32pub const VERSION: &str = env!("CARGO_PKG_VERSION");
33
34/// The package name, resolved at compile time.
35///
36/// Why: Allows display strings to use the correct crate name without
37/// hardcoding it, so this module is reusable across trusty-agents and trusty-code.
38/// What: `env!("CARGO_PKG_NAME")` forwarded as a `'static str`.
39/// Test: Indirectly via `version_string_contains_version`.
40pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
41
42/// Short git commit hash captured at build time by `build.rs`.
43///
44/// Why: Correlates a running binary to the exact commit that produced it.
45/// What: Populated from `git rev-parse --short HEAD` during compilation;
46/// falls back to `"unknown"` when git is unavailable.
47/// Test: `version_string_contains_version` confirms both fields render.
48pub const GIT_HASH: &str = env!("GIT_COMMIT_HASH");
49
50/// Human-readable banner used by the CTRL REPL and `--version` output.
51///
52/// Why: One canonical format keeps log grep and support reports consistent.
53/// What: Returns `<pkg-name> vX.Y.Z (<git-hash>)`.
54/// Test: `version_string_contains_version` checks both substrings render.
55pub fn version_string() -> String {
56    format!("{PKG_NAME} v{VERSION} ({GIT_HASH})")
57}
58
59/// On-disk shape of `build.json`.
60///
61/// Why: Kept as a private struct so callers go through `BuildInfo` for
62/// `started_at`/`version` handling instead of reading raw JSON.
63/// What: Just the two persisted fields; version is a compile-time constant
64/// and doesn't round-trip through disk.
65/// Test: Serialized/deserialized in unit tests below.
66#[derive(Debug, Serialize, Deserialize)]
67struct PersistedBuild {
68    build: u64,
69    started_at: String,
70}
71
72/// Runtime build metadata surfaced to logs, the `--version` flag, and
73/// downstream instrumentation.
74///
75/// Why: Centralizes "which binary + which invocation" so later instrumentation
76/// can tag every telemetry event with the same build stamp the startup log
77/// line shows.
78/// What: Holds the compile-time semver, the incremented build counter, and
79/// the ISO8601 UTC start timestamp.
80/// Test: `display_string` returns `<pkg-name> vX.Y.Z build #N`.
81#[derive(Debug, Clone)]
82pub struct BuildInfo {
83    pub version: &'static str,
84    pub build: u64,
85    // Exposed for the performance instrumentation module which will stamp
86    // telemetry events with the process start time.
87    #[allow(dead_code)]
88    pub started_at: String,
89}
90
91impl BuildInfo {
92    /// Load the persistent counter, increment it, and persist back using
93    /// the given state directory.
94    ///
95    /// Why: Single entry point ensures every process start gets a fresh
96    /// build number even if the caller forgets to save.
97    /// What: Uses `<state_dir>/build.json`. See `load_and_increment_in` for
98    /// the testable, directory-parameterized version.
99    /// Test: See `load_and_increment_in` tests.
100    pub async fn load_and_increment(state_dir: &Path) -> Result<Self> {
101        tokio::fs::create_dir_all(state_dir).await?;
102        Self::load_and_increment_in(state_dir).await
103    }
104
105    /// Same as `load_and_increment` but with an explicit base directory.
106    ///
107    /// Why: Tests need to drive the counter against a temp dir without
108    /// mutating the real state directory in the project.
109    /// What: Creates `<dir>` if missing, reads/parses `<dir>/build.json`
110    /// (treating missing or malformed as build=0), increments, writes back
111    /// atomically.
112    /// Test: See unit tests at the bottom of this file.
113    pub async fn load_and_increment_in(dir: &Path) -> Result<Self> {
114        tokio::fs::create_dir_all(dir)
115            .await
116            .with_context(|| format!("failed to create {}", dir.display()))?;
117
118        let file = dir.join("build.json");
119        let previous = read_previous(&file).await;
120
121        let next = previous.saturating_add(1);
122        let started_at = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
123
124        let persisted = PersistedBuild {
125            build: next,
126            started_at: started_at.clone(),
127        };
128        write_atomic(dir, &file, &persisted).await?;
129
130        Ok(Self {
131            version: env!("CARGO_PKG_VERSION"),
132            build: next,
133            started_at,
134        })
135    }
136
137    /// Human-readable banner used by the startup log line and `--version`.
138    ///
139    /// Why: Single canonical format so grep/tooling can match it uniformly.
140    /// What: `<pkg-name> vX.Y.Z build #N`.
141    /// Test: Asserted directly in unit tests.
142    pub fn display_string(&self) -> String {
143        format!("{PKG_NAME} v{} build #{}", self.version, self.build)
144    }
145}
146
147/// Read the previous `build` counter from `file`, returning 0 if the file
148/// is missing, unreadable, or corrupt.
149///
150/// Why: We never want to fail startup just because the counter file got
151/// wedged; treating it as 0 means the next write replaces the bad content.
152/// What: Async read + `serde_json` parse.
153/// Test: `load_and_increment_in` tests cover missing + corrupt cases.
154async fn read_previous(file: &Path) -> u64 {
155    match tokio::fs::read(file).await {
156        Ok(bytes) => match serde_json::from_slice::<PersistedBuild>(&bytes) {
157            Ok(p) => p.build,
158            Err(_) => 0,
159        },
160        Err(_) => 0,
161    }
162}
163
164/// Atomic write: serialize to `<file>.tmp`, fsync implicit via rename.
165///
166/// Why: A crash during write must never leave `build.json` half-written —
167/// `rename(2)` on the same filesystem is atomic, so readers always see a
168/// complete file.
169/// What: Writes to `<dir>/build.json.tmp`, renames over the target path.
170/// Test: Covered by `load_and_increment_in` tests.
171async fn write_atomic(dir: &Path, file: &Path, payload: &PersistedBuild) -> Result<()> {
172    let tmp: PathBuf = dir.join("build.json.tmp");
173    let bytes = serde_json::to_vec_pretty(payload).context("serialize build.json")?;
174    tokio::fs::write(&tmp, &bytes)
175        .await
176        .with_context(|| format!("failed to write {}", tmp.display()))?;
177    tokio::fs::rename(&tmp, file)
178        .await
179        .with_context(|| format!("failed to rename {} -> {}", tmp.display(), file.display()))?;
180    Ok(())
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[tokio::test]
188    async fn starts_at_one_when_missing() {
189        let dir = tempfile::tempdir().unwrap();
190        let info = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
191        assert_eq!(info.build, 1);
192        assert_eq!(info.version, env!("CARGO_PKG_VERSION"));
193        assert!(info.started_at.ends_with('Z'));
194
195        // File exists and is valid JSON with build=1.
196        let bytes = tokio::fs::read(dir.path().join("build.json"))
197            .await
198            .unwrap();
199        let p: PersistedBuild = serde_json::from_slice(&bytes).unwrap();
200        assert_eq!(p.build, 1);
201    }
202
203    #[tokio::test]
204    async fn increments_across_calls() {
205        let dir = tempfile::tempdir().unwrap();
206        let a = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
207        let b = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
208        let c = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
209        assert_eq!(a.build, 1);
210        assert_eq!(b.build, 2);
211        assert_eq!(c.build, 3);
212    }
213
214    #[tokio::test]
215    async fn corrupt_file_resets_to_one() {
216        let dir = tempfile::tempdir().unwrap();
217        tokio::fs::create_dir_all(dir.path()).await.unwrap();
218        tokio::fs::write(dir.path().join("build.json"), b"not json at all")
219            .await
220            .unwrap();
221
222        let info = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
223        assert_eq!(info.build, 1, "corrupt file should be treated as build=0");
224    }
225
226    #[tokio::test]
227    async fn display_string_format() {
228        let info = BuildInfo {
229            version: "0.1.0",
230            build: 42,
231            started_at: "2026-04-22T17:31:30Z".to_string(),
232        };
233        // PKG_NAME is "trusty-code" in this crate.
234        let s = info.display_string();
235        assert!(s.contains("v0.1.0"), "got: {s}");
236        assert!(s.contains("build #42"), "got: {s}");
237    }
238
239    #[test]
240    fn version_string_contains_version() {
241        let s = version_string();
242        assert!(s.contains("v"));
243        assert!(s.contains(VERSION));
244        // GIT_HASH is either a short hash or "unknown"; rendered in parens.
245        assert!(s.contains(GIT_HASH));
246    }
247
248    #[tokio::test]
249    async fn creates_missing_parent_dir() {
250        let root = tempfile::tempdir().unwrap();
251        let nested = root.path().join("deep").join(".state");
252        assert!(!nested.exists());
253
254        let info = BuildInfo::load_and_increment_in(&nested).await.unwrap();
255        assert_eq!(info.build, 1);
256        assert!(nested.join("build.json").exists());
257    }
258}