Skip to main content

acton_service/
build_utils.rs

1//! Build-time utilities for compiling protocol buffers
2//!
3//! This module provides helpers for `build.rs` scripts in projects using acton-service.
4//!
5//! ## Important Note
6//!
7//! These utilities run at **compile time** (in build.rs), not at runtime.
8//! They cannot access XDG config files or other runtime configuration.
9//!
10//! ## Configuration Priority
11//!
12//! Proto location is determined in this order:
13//! 1. `ACTON_PROTO_DIR` environment variable
14//! 2. `proto/` directory (convention)
15//!
16//! ## Usage in Your Project
17//!
18//! ```rust,no_run
19//! // In your project's build.rs
20//! fn main() -> Result<(), Box<dyn std::error::Error>> {
21//!     #[cfg(feature = "grpc")]
22//!     {
23//!         // Use default convention (proto/ directory)
24//!         acton_service::build_utils::compile_service_protos()?;
25//!
26//!         // Or specify a custom directory
27//!         acton_service::build_utils::compile_protos_from_dir("my-protos")?;
28//!     }
29//!     Ok(())
30//! }
31//! ```
32//!
33//! ## Environment Variables
34//!
35//! - `ACTON_PROTO_DIR`: Override the default proto directory location
36//! - `CARGO_PKG_NAME`: Used to generate descriptor file names (automatically set by Cargo)
37//! - `OUT_DIR`: Where generated files are placed (automatically set by Cargo)
38
39use std::path::{Path, PathBuf};
40
41/// Error type for build utilities
42#[derive(Debug)]
43pub enum BuildError {
44    Io(std::io::Error),
45    ProtoBuild(Box<dyn std::error::Error>),
46    NoProtoFiles(PathBuf),
47    InvalidProtoDir(PathBuf),
48}
49
50impl std::fmt::Display for BuildError {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        match self {
53            BuildError::Io(e) => write!(f, "IO error: {}", e),
54            BuildError::ProtoBuild(e) => write!(f, "Proto compilation error: {}", e),
55            BuildError::NoProtoFiles(dir) => {
56                write!(f, "No .proto files found in directory: {}", dir.display())
57            }
58            BuildError::InvalidProtoDir(dir) => write!(
59                f,
60                "Proto directory does not exist or is not a directory: {}",
61                dir.display()
62            ),
63        }
64    }
65}
66
67impl std::error::Error for BuildError {}
68
69impl From<std::io::Error> for BuildError {
70    fn from(e: std::io::Error) -> Self {
71        BuildError::Io(e)
72    }
73}
74
75pub type BuildResult<T> = Result<T, BuildError>;
76
77/// Compile all `.proto` files from a directory
78///
79/// This function:
80/// - Discovers all `.proto` files in the specified directory
81/// - Compiles them using `tonic_build`
82/// - Generates a file descriptor set for gRPC reflection
83/// - Names the descriptor based on the crate name
84///
85/// # Arguments
86///
87/// * `proto_dir` - Directory containing `.proto` files
88///
89/// # Example
90///
91/// ```rust,no_run
92/// // In build.rs
93/// fn main() -> Result<(), Box<dyn std::error::Error>> {
94///     acton_service::build_utils::compile_protos_from_dir("proto")?;
95///     Ok(())
96/// }
97/// ```
98pub fn compile_protos_from_dir<P: AsRef<Path>>(proto_dir: P) -> BuildResult<()> {
99    let proto_dir = proto_dir.as_ref();
100
101    // Validate directory exists
102    if !proto_dir.exists() || !proto_dir.is_dir() {
103        return Err(BuildError::InvalidProtoDir(proto_dir.to_path_buf()));
104    }
105
106    // Discover all .proto files
107    let proto_files: Vec<PathBuf> = discover_proto_files(proto_dir)?;
108
109    if proto_files.is_empty() {
110        return Err(BuildError::NoProtoFiles(proto_dir.to_path_buf()));
111    }
112
113    // Get output directory and package name from cargo
114    let out_dir = std::env::var("OUT_DIR").map_err(|e| {
115        BuildError::ProtoBuild(Box::new(std::io::Error::new(
116            std::io::ErrorKind::NotFound,
117            format!("OUT_DIR not set: {}", e),
118        )))
119    })?;
120
121    let pkg_name = std::env::var("CARGO_PKG_NAME")
122        .map_err(|e| {
123            BuildError::ProtoBuild(Box::new(std::io::Error::new(
124                std::io::ErrorKind::NotFound,
125                format!("CARGO_PKG_NAME not set: {}", e),
126            )))
127        })?
128        .replace('-', "_");
129
130    // Build descriptor set path
131    let descriptor_path = format!("{}/{}_descriptor.bin", out_dir, pkg_name);
132
133    println!(
134        "cargo:warning=Compiling {} proto files from {}",
135        proto_files.len(),
136        proto_dir.display()
137    );
138    for proto_file in &proto_files {
139        println!("cargo:warning=  - {}", proto_file.display());
140    }
141
142    // Compile protos
143    compile_protos_with_descriptor(&proto_files, proto_dir, &descriptor_path)?;
144
145    println!("cargo:warning=Generated descriptor: {}", descriptor_path);
146
147    Ok(())
148}
149
150/// Compile service protos using convention-based or environment-configured location
151///
152/// This is the recommended entry point for acton-service projects.
153///
154/// Location priority:
155/// 1. `ACTON_PROTO_DIR` environment variable
156/// 2. `proto/` directory (convention)
157///
158/// # Example
159///
160/// ```rust,no_run
161/// // In build.rs - uses default "proto/" directory
162/// fn main() -> Result<(), Box<dyn std::error::Error>> {
163///     acton_service::build_utils::compile_service_protos()?;
164///     Ok(())
165/// }
166/// ```
167///
168/// ```bash
169/// # Override proto location at build time
170/// ACTON_PROTO_DIR=../shared/protos cargo build
171/// ```
172pub fn compile_service_protos() -> BuildResult<()> {
173    let proto_dir = std::env::var("ACTON_PROTO_DIR").unwrap_or_else(|_| "proto".to_string());
174
175    println!("cargo:warning=Using proto directory: {}", proto_dir);
176
177    compile_protos_from_dir(proto_dir)
178}
179
180/// Discover all `.proto` files recursively in a directory
181fn discover_proto_files(dir: &Path) -> BuildResult<Vec<PathBuf>> {
182    let mut proto_files = Vec::new();
183
184    for entry in std::fs::read_dir(dir)? {
185        let entry = entry?;
186        let path = entry.path();
187
188        if path.is_file() {
189            if let Some(ext) = path.extension() {
190                if ext == "proto" {
191                    proto_files.push(path);
192                }
193            }
194        } else if path.is_dir() {
195            // Recursively search subdirectories
196            proto_files.extend(discover_proto_files(&path)?);
197        }
198    }
199
200    // Sort for deterministic builds
201    proto_files.sort();
202
203    Ok(proto_files)
204}
205
206/// Compile proto files with descriptor generation
207fn compile_protos_with_descriptor(
208    proto_files: &[PathBuf],
209    proto_include_dir: &Path,
210    descriptor_path: &str,
211) -> BuildResult<()> {
212    // Convert proto files to string refs
213    let proto_paths: Vec<&str> = proto_files
214        .iter()
215        .map(|p| p.to_str().expect("Invalid UTF-8 in proto path"))
216        .collect();
217
218    let include_dirs = vec![proto_include_dir
219        .to_str()
220        .expect("Invalid UTF-8 in include path")];
221
222    // Use tonic-prost-build to compile protos with file descriptor support
223    #[cfg(feature = "grpc")]
224    {
225        tonic_prost_build::configure()
226            .file_descriptor_set_path(descriptor_path)
227            .compile_protos(&proto_paths, &include_dirs)
228            .map_err(|e| BuildError::ProtoBuild(Box::new(e)))?;
229        Ok(())
230    }
231
232    #[cfg(not(feature = "grpc"))]
233    {
234        let _ = (proto_paths, include_dirs, descriptor_path);
235        Err(BuildError::ProtoBuild(Box::new(std::io::Error::other(
236            "grpc feature not enabled",
237        ))))
238    }
239}
240
241/// Advanced: Compile specific proto files with custom configuration
242///
243/// Use this when you need fine-grained control over proto compilation.
244///
245/// # Example
246///
247/// ```rust,no_run
248/// // In build.rs
249/// fn main() -> Result<(), Box<dyn std::error::Error>> {
250///     acton_service::build_utils::compile_specific_protos(
251///         &["proto/orders.proto", "proto/users.proto"],
252///         &["proto"],
253///         "my_descriptor.bin"
254///     )?;
255///     Ok(())
256/// }
257/// ```
258pub fn compile_specific_protos<P: AsRef<Path>>(
259    proto_files: &[P],
260    include_dirs: &[P],
261    descriptor_name: &str,
262) -> BuildResult<()> {
263    let out_dir = std::env::var("OUT_DIR").map_err(|e| {
264        BuildError::ProtoBuild(Box::new(std::io::Error::new(
265            std::io::ErrorKind::NotFound,
266            format!("OUT_DIR not set: {}", e),
267        )))
268    })?;
269
270    let descriptor_path = format!("{}/{}", out_dir, descriptor_name);
271
272    let proto_paths: Vec<&str> = proto_files
273        .iter()
274        .map(|p| p.as_ref().to_str().expect("Invalid UTF-8 in proto path"))
275        .collect();
276
277    let include_paths: Vec<&str> = include_dirs
278        .iter()
279        .map(|p| p.as_ref().to_str().expect("Invalid UTF-8 in include path"))
280        .collect();
281
282    compile_protos_with_descriptor(
283        &proto_paths.iter().map(PathBuf::from).collect::<Vec<_>>(),
284        Path::new(include_paths[0]),
285        &descriptor_path,
286    )?;
287
288    Ok(())
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn test_discover_proto_files() {
297        // This test would require setting up a test proto directory
298        // For now, just ensure the function signature is correct
299        let _result: BuildResult<Vec<PathBuf>> = discover_proto_files(Path::new("nonexistent"));
300    }
301}