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::{Identity, Server, ServerTlsConfig};
9use tracing::{debug, info, warn};
10
11use crate::config::GrpcConfig;
12use crate::metrics::GrpcMetrics;
13use crate::service::{GrpcState, grpc_handler};
14
15pub struct GrpcPlugin {
16 config: GrpcConfig,
17}
18
19impl GrpcPlugin {
20 pub fn new(config: GrpcConfig) -> Self {
21 Self { config }
22 }
23}
24
25#[async_trait]
26impl ServerPlugin for GrpcPlugin {
27 fn name(&self) -> &'static str {
28 "grpc"
29 }
30
31 async fn run(&self, ctx: PluginContext) -> Result<()> {
32 let metrics = ctx
33 .metrics_registry
34 .as_ref()
35 .map(|r| GrpcMetrics::new(r.as_ref()));
36
37 if metrics.is_some() {
38 info!("gRPC metrics registered");
39 }
40
41 let state = GrpcState {
42 executor: ctx.executor.clone(),
43 max_recv_message_size: self.config.max_recv_message_size,
44 max_send_message_size: self.config.max_send_message_size,
45 compression: self.config.compression,
46 metrics,
47 };
48
49 let router: axum::Router = Router::new().fallback(grpc_handler).with_state(state);
50 let mut sd = ctx.shutdown.clone();
51
52 info!(listen = %self.config.listen, "gRPC server listening");
53
54 let mut builder = if let Some(ref tls) = self.config.tls {
56 let cert = std::fs::read(&tls.cert)
57 .with_context(|| format!("read TLS cert: {}", tls.cert.display()))?;
58 let key = std::fs::read(&tls.key)
59 .with_context(|| format!("read TLS key: {}", tls.key.display()))?;
60 let identity = Identity::from_pem(cert, key);
61 let tls_config = ServerTlsConfig::new().identity(identity);
62 info!(cert = %tls.cert.display(), "gRPC TLS enabled");
63 Server::builder()
64 .tls_config(tls_config)
65 .context("TLS config")?
66 } else {
67 Server::builder()
68 };
69
70 if let Some(timeout) = self.config.timeout {
71 builder = builder.timeout(timeout);
72 info!(timeout = ?timeout, "gRPC server timeout configured");
73 }
74
75 if let Some(max_streams) = self.config.max_concurrent_streams {
76 builder = builder.max_concurrent_streams(max_streams);
77 }
78
79 if let Some(ref ka) = self.config.keepalive {
80 builder = builder
81 .http2_keepalive_interval(Some(ka.interval))
82 .http2_keepalive_timeout(Some(ka.timeout));
83 info!(interval = ?ka.interval, timeout = ?ka.timeout, "gRPC keepalive configured");
84 }
85
86 let mut router = builder.add_routes(tonic::service::Routes::from(router));
88
89 let (health_reporter, health_service) = tonic_health::server::health_reporter();
91 health_reporter
92 .set_service_status("", tonic_health::ServingStatus::Serving)
93 .await;
94 router = router.add_service(health_service);
95 info!("gRPC health checking enabled");
96
97 {
99 let proto_fds = if !self.config.proto.is_empty() {
100 match build_reflection_descriptors(&self.config.proto) {
101 Ok(fds) => {
102 info!(
103 proto_files = self.config.proto.len(),
104 "gRPC reflection enabled"
105 );
106 Some(fds)
107 }
108 Err(e) => {
109 warn!(error = %e, "failed to build proto reflection; continuing without it");
110 None
111 }
112 }
113 } else {
114 None
115 };
116
117 let mut reflection_builder = tonic_reflection::server::Builder::configure()
118 .register_encoded_file_descriptor_set(tonic_health::pb::FILE_DESCRIPTOR_SET);
119
120 if let Some(ref fds) = proto_fds {
121 reflection_builder = reflection_builder.register_encoded_file_descriptor_set(fds);
122 }
123
124 match reflection_builder.build_v1() {
125 Ok(reflection) => {
126 router = router.add_service(reflection);
127 }
128 Err(e) => {
129 warn!(error = %e, "failed to build reflection service");
130 }
131 }
132 }
133
134 router
136 .serve_with_shutdown(self.config.listen, async move {
137 if let Err(e) = sd.changed().await {
138 tracing::error!(error = %e, "shutdown sender dropped unexpectedly");
139 }
140 })
141 .await?;
142
143 Ok(())
144 }
145
146 fn rpc_methods(&self) -> Vec<RpcMethodDef> {
147 vec![]
148 }
149}
150
151fn build_reflection_descriptors(proto_files: &[String]) -> Result<Vec<u8>> {
158 let cwd = std::env::current_dir().context("get cwd")?;
159 let mut include_paths = BTreeSet::new();
160
161 let mut visited = BTreeSet::new();
163 for proto in proto_files {
164 let abs = cwd.join(proto);
165 resolve_imports(&abs, &cwd, &mut include_paths, &mut visited);
166 }
167
168 for proto in proto_files {
170 let abs = cwd.join(proto);
171 if let Some(parent) = abs.parent() {
172 include_paths.insert(parent.to_path_buf());
173 }
174 }
175
176 debug!(paths = include_paths.len(), "resolved proto include paths");
177
178 let paths: Vec<_> = include_paths.iter().collect();
179 let mut compiler = protox::Compiler::new(paths.iter().map(|p| p.as_path()))
180 .context("create protox compiler")?;
181 compiler.include_imports(true);
182
183 for proto in proto_files {
184 let path = Path::new(proto);
185 let file_name = path
186 .file_name()
187 .and_then(|n| n.to_str())
188 .context("invalid proto file name")?;
189 compiler
190 .open_file(file_name)
191 .with_context(|| format!("compile {proto}"))?;
192 }
193
194 let fds = compiler.file_descriptor_set();
195 Ok(prost::Message::encode_to_vec(&fds))
196}
197
198fn resolve_imports(
202 proto_path: &Path,
203 project_root: &Path,
204 include_paths: &mut BTreeSet<PathBuf>,
205 visited: &mut BTreeSet<PathBuf>,
206) {
207 if !proto_path.is_file() || !visited.insert(proto_path.to_path_buf()) {
208 return;
209 }
210
211 let content = match std::fs::read_to_string(proto_path) {
212 Ok(c) => c,
213 Err(_) => return,
214 };
215
216 for line in content.lines() {
217 let line = line.trim();
218 if !line.starts_with("import ") {
221 continue;
222 }
223 let Some(start) = line.find('"') else {
224 continue;
225 };
226 let Some(end) = line[start + 1..].find('"') else {
227 continue;
228 };
229 let import_path = &line[start + 1..start + 1 + end];
230
231 if import_path.starts_with("google/protobuf/") {
233 continue;
234 }
235
236 if let Some(found) = find_best_match(project_root, import_path) {
238 if let Some(base) = found
240 .to_str()
241 .and_then(|f| f.strip_suffix(import_path))
242 .map(PathBuf::from)
243 {
244 if !base.as_os_str().is_empty() {
245 include_paths.insert(base);
246 }
247 } else if let Some(parent) = found.parent() {
248 include_paths.insert(parent.to_path_buf());
249 }
250
251 resolve_imports(&found, project_root, include_paths, visited);
252 }
253 }
254}
255
256fn find_best_match(root: &Path, relative: &str) -> Option<PathBuf> {
259 let mut candidates = Vec::new();
260
261 let direct = root.join(relative);
263 if direct.is_file() {
264 candidates.push(direct);
265 }
266
267 find_all_recursive(root, relative, &mut candidates);
268
269 if candidates.len() <= 1 {
270 return candidates.into_iter().next();
271 }
272
273 candidates
275 .into_iter()
276 .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
277}
278
279fn find_all_recursive(dir: &Path, relative: &str, results: &mut Vec<PathBuf>) {
280 let candidate = dir.join(relative);
281 if candidate.is_file() && !results.contains(&candidate) {
282 results.push(candidate);
283 }
284
285 let entries = match std::fs::read_dir(dir) {
286 Ok(e) => e,
287 Err(_) => return,
288 };
289
290 for entry in entries.flatten() {
291 let path = entry.path();
292 if path.is_dir() {
293 let name = entry.file_name();
295 if name.to_str().is_some_and(|n| n.starts_with('.')) {
296 continue;
297 }
298 find_all_recursive(&path, relative, results);
299 }
300 }
301}