folk_plugin_grpc/
plugin.rs1use 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
83fn 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 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 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
133fn 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 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 if import_path.starts_with("google/protobuf/") {
164 continue;
165 }
166
167 if let Some(found) = find_best_match(project_root, import_path) {
169 if let Some(base) = found
171 .to_str()
172 .and_then(|f| f.strip_suffix(import_path))
173 .map(PathBuf::from)
174 {
175 if !base.as_os_str().is_empty() {
176 include_paths.insert(base);
177 }
178 } else if let Some(parent) = found.parent() {
179 include_paths.insert(parent.to_path_buf());
180 }
181
182 resolve_imports(&found, project_root, include_paths, visited);
183 }
184 }
185}
186
187fn find_best_match(root: &Path, relative: &str) -> Option<PathBuf> {
190 let mut candidates = Vec::new();
191
192 let direct = root.join(relative);
194 if direct.is_file() {
195 candidates.push(direct);
196 }
197
198 find_all_recursive(root, relative, &mut candidates);
199
200 if candidates.len() <= 1 {
201 return candidates.into_iter().next();
202 }
203
204 candidates
206 .into_iter()
207 .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
208}
209
210fn find_all_recursive(dir: &Path, relative: &str, results: &mut Vec<PathBuf>) {
211 let candidate = dir.join(relative);
212 if candidate.is_file() && !results.contains(&candidate) {
213 results.push(candidate);
214 }
215
216 let entries = match std::fs::read_dir(dir) {
217 Ok(e) => e,
218 Err(_) => return,
219 };
220
221 for entry in entries.flatten() {
222 let path = entry.path();
223 if path.is_dir() {
224 let name = entry.file_name();
226 if name.to_str().is_some_and(|n| n.starts_with('.')) {
227 continue;
228 }
229 find_all_recursive(&path, relative, results);
230 }
231 }
232}