Skip to main content

folk_plugin_grpc/
plugin.rs

1use std::collections::BTreeSet;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use async_trait::async_trait;
6use axum::Router;
7use folk_api::{PluginContext, RpcMethodDef, ServerPlugin};
8use tonic::transport::Server;
9use tracing::{debug, info, warn};
10
11use crate::config::GrpcConfig;
12use crate::service::{GrpcState, grpc_handler};
13
14pub struct GrpcPlugin {
15    config: GrpcConfig,
16}
17
18impl GrpcPlugin {
19    pub fn new(config: GrpcConfig) -> Self {
20        Self { config }
21    }
22}
23
24#[async_trait]
25impl ServerPlugin for GrpcPlugin {
26    fn name(&self) -> &'static str {
27        "grpc"
28    }
29
30    async fn run(&self, ctx: PluginContext) -> Result<()> {
31        let state = GrpcState {
32            executor: ctx.executor.clone(),
33        };
34
35        let router: axum::Router = Router::new().fallback(grpc_handler).with_state(state);
36        let mut sd = ctx.shutdown.clone();
37
38        info!(listen = %self.config.listen, "gRPC server listening");
39
40        let routes = tonic::service::Routes::from(router);
41
42        if !self.config.proto.is_empty() {
43            match build_reflection_descriptors(&self.config.proto) {
44                Ok(encoded_fds) => {
45                    info!(proto_files = self.config.proto.len(), "gRPC reflection enabled");
46                    let reflection = tonic_reflection::server::Builder::configure()
47                        .register_encoded_file_descriptor_set(&encoded_fds)
48                        .build_v1()
49                        .context("build reflection service")?;
50                    Server::builder()
51                        .add_routes(routes)
52                        .add_service(reflection)
53                        .serve_with_shutdown(self.config.listen, async move {
54                            sd.changed().await.ok();
55                        })
56                        .await?;
57                    return Ok(());
58                },
59                Err(e) => {
60                    warn!(error = %e, "failed to build reflection; starting without it");
61                },
62            }
63        }
64
65        Server::builder()
66            .add_routes(routes)
67            .serve_with_shutdown(self.config.listen, async move {
68                sd.changed().await.ok();
69            })
70            .await?;
71
72        Ok(())
73    }
74
75    fn rpc_methods(&self) -> Vec<RpcMethodDef> {
76        vec![RpcMethodDef::new(
77            "grpc.services",
78            "list registered gRPC service names",
79        )]
80    }
81}
82
83/// Compile proto files and return encoded FileDescriptorSet.
84///
85/// Import paths are resolved automatically:
86/// - Parses `import` statements from each proto file
87/// - Searches for imported files within the project root (cwd)
88/// - Never searches outside the working directory
89fn build_reflection_descriptors(proto_files: &[String]) -> Result<Vec<u8>> {
90    let cwd = std::env::current_dir().context("get cwd")?;
91    let mut include_paths = BTreeSet::new();
92
93    // Resolve imports starting from each proto file
94    let mut visited = BTreeSet::new();
95    for proto in proto_files {
96        let abs = cwd.join(proto);
97        resolve_imports(&abs, &cwd, &mut include_paths, &mut visited);
98    }
99
100    // Always include the directory of each proto file itself
101    for proto in proto_files {
102        let abs = cwd.join(proto);
103        if let Some(parent) = abs.parent() {
104            include_paths.insert(parent.to_path_buf());
105        }
106    }
107
108    debug!(
109        paths = include_paths.len(),
110        "resolved proto include paths"
111    );
112
113    let paths: Vec<_> = include_paths.iter().collect();
114    let mut compiler = protox::Compiler::new(paths.iter().map(|p| p.as_path()))
115        .context("create protox compiler")?;
116    compiler.include_imports(true);
117
118    for proto in proto_files {
119        let path = Path::new(proto);
120        let file_name = path
121            .file_name()
122            .and_then(|n| n.to_str())
123            .context("invalid proto file name")?;
124        compiler
125            .open_file(file_name)
126            .with_context(|| format!("compile {proto}"))?;
127    }
128
129    let fds = compiler.file_descriptor_set();
130    Ok(prost::Message::encode_to_vec(&fds))
131}
132
133/// Parse a proto file for `import` statements and find each imported file
134/// within the project root. Adds the containing directory to include_paths.
135/// Recurses into found imports.
136fn resolve_imports(
137    proto_path: &Path,
138    project_root: &Path,
139    include_paths: &mut BTreeSet<PathBuf>,
140    visited: &mut BTreeSet<PathBuf>,
141) {
142    if !proto_path.is_file() || !visited.insert(proto_path.to_path_buf()) {
143        return;
144    }
145
146    let content = match std::fs::read_to_string(proto_path) {
147        Ok(c) => c,
148        Err(_) => return,
149    };
150
151    for line in content.lines() {
152        let line = line.trim();
153        // Match: import "path/to/file.proto";
154        // Match: import public "path/to/file.proto";
155        if !line.starts_with("import ") {
156            continue;
157        }
158        let Some(start) = line.find('"') else { continue };
159        let Some(end) = line[start + 1..].find('"') else { continue };
160        let import_path = &line[start + 1..start + 1 + end];
161
162        // Skip well-known google types — protox has them built-in
163        if import_path.starts_with("google/protobuf/") {
164            continue;
165        }
166
167        // Search for ALL locations of this file within the project root
168        let found_files = find_all_in_tree(project_root, import_path);
169        for found in &found_files {
170            // Compute the include base: found = base / import_path
171            if let Some(base) = found
172                .to_str()
173                .and_then(|f| f.strip_suffix(import_path))
174                .map(PathBuf::from)
175            {
176                if !base.as_os_str().is_empty() {
177                    include_paths.insert(base);
178                }
179            } else if let Some(parent) = found.parent() {
180                include_paths.insert(parent.to_path_buf());
181            }
182
183            // Recurse into found import
184            resolve_imports(found, project_root, include_paths, visited);
185        }
186    }
187}
188
189/// Find ALL locations of a file by relative path within the project root.
190/// Returns all matches — protox will pick the right one based on include order.
191fn find_all_in_tree(root: &Path, relative: &str) -> Vec<PathBuf> {
192    let mut results = Vec::new();
193
194    // Direct resolution from root
195    let direct = root.join(relative);
196    if direct.is_file() {
197        results.push(direct);
198    }
199
200    find_all_recursive(root, relative, &mut results);
201    results
202}
203
204fn find_all_recursive(dir: &Path, relative: &str, results: &mut Vec<PathBuf>) {
205    let candidate = dir.join(relative);
206    if candidate.is_file() && !results.contains(&candidate) {
207        results.push(candidate);
208    }
209
210    let entries = match std::fs::read_dir(dir) {
211        Ok(e) => e,
212        Err(_) => return,
213    };
214
215    for entry in entries.flatten() {
216        let path = entry.path();
217        if path.is_dir() {
218            let name = entry.file_name();
219            let name = name.to_str().unwrap_or("");
220            // Skip hidden dirs, build outputs, generated code
221            if name.starts_with('.')
222                || name == "node_modules"
223                || name == "target"
224                || name == "pb"
225                || name == "build"
226                || name == "dist"
227                || name == "out"
228            {
229                continue;
230            }
231            find_all_recursive(&path, relative, results);
232        }
233    }
234}