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::{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        // --- Server builder ---
55        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        // --- Accumulate services ---
87        let mut router = builder.add_routes(tonic::service::Routes::from(router));
88
89        // Health checking (grpc.health.v1)
90        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        // Reflection (always includes health service descriptor)
98        {
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        // --- Serve ---
135        // Phase 79: bind via SO_REUSEPORT so every forked worker binds the same
136        // address and the kernel load-balances gRPC connections across them.
137        let listener = bind_reuseport(self.config.listen)?;
138        let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener);
139        router
140            .serve_with_incoming_shutdown(incoming, async move {
141                if let Err(e) = sd.changed().await {
142                    tracing::error!(error = %e, "shutdown sender dropped unexpectedly");
143                }
144            })
145            .await?;
146
147        Ok(())
148    }
149
150    fn rpc_methods(&self) -> Vec<RpcMethodDef> {
151        vec![]
152    }
153}
154
155/// Bind a `SO_REUSEPORT` TCP listener (phase 79 fork model) — every worker
156/// process binds the same address; the kernel balances connections.
157fn bind_reuseport(addr: std::net::SocketAddr) -> Result<tokio::net::TcpListener> {
158    use socket2::{Domain, Protocol, Socket, Type};
159
160    let domain = if addr.is_ipv6() {
161        Domain::IPV6
162    } else {
163        Domain::IPV4
164    };
165    let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
166    socket.set_reuse_address(true)?;
167    socket.set_reuse_port(true)?;
168    socket.set_nonblocking(true)?;
169    socket.bind(&addr.into())?;
170    socket.listen(1024)?;
171    Ok(tokio::net::TcpListener::from_std(socket.into())?)
172}
173
174/// Compile proto files and return encoded FileDescriptorSet.
175///
176/// Import paths are resolved automatically:
177/// - Parses `import` statements from each proto file
178/// - Searches for imported files within the project root (cwd)
179/// - Never searches outside the working directory
180fn build_reflection_descriptors(proto_files: &[String]) -> Result<Vec<u8>> {
181    let cwd = std::env::current_dir().context("get cwd")?;
182    let mut include_paths = BTreeSet::new();
183
184    // Resolve imports starting from each proto file
185    let mut visited = BTreeSet::new();
186    for proto in proto_files {
187        let abs = cwd.join(proto);
188        resolve_imports(&abs, &cwd, &mut include_paths, &mut visited);
189    }
190
191    // Always include the directory of each proto file itself
192    for proto in proto_files {
193        let abs = cwd.join(proto);
194        if let Some(parent) = abs.parent() {
195            include_paths.insert(parent.to_path_buf());
196        }
197    }
198
199    debug!(paths = include_paths.len(), "resolved proto include paths");
200
201    let paths: Vec<_> = include_paths.iter().collect();
202    let mut compiler = protox::Compiler::new(paths.iter().map(|p| p.as_path()))
203        .context("create protox compiler")?;
204    compiler.include_imports(true);
205
206    for proto in proto_files {
207        let path = Path::new(proto);
208        let file_name = path
209            .file_name()
210            .and_then(|n| n.to_str())
211            .context("invalid proto file name")?;
212        compiler
213            .open_file(file_name)
214            .with_context(|| format!("compile {proto}"))?;
215    }
216
217    let fds = compiler.file_descriptor_set();
218    Ok(prost::Message::encode_to_vec(&fds))
219}
220
221/// Parse a proto file for `import` statements and find each imported file
222/// within the project root. Adds the containing directory to include_paths.
223/// Recurses into found imports.
224fn resolve_imports(
225    proto_path: &Path,
226    project_root: &Path,
227    include_paths: &mut BTreeSet<PathBuf>,
228    visited: &mut BTreeSet<PathBuf>,
229) {
230    if !proto_path.is_file() || !visited.insert(proto_path.to_path_buf()) {
231        return;
232    }
233
234    let content = match std::fs::read_to_string(proto_path) {
235        Ok(c) => c,
236        Err(_) => return,
237    };
238
239    for line in content.lines() {
240        let line = line.trim();
241        // Match: import "path/to/file.proto";
242        // Match: import public "path/to/file.proto";
243        if !line.starts_with("import ") {
244            continue;
245        }
246        let Some(start) = line.find('"') else {
247            continue;
248        };
249        let Some(end) = line[start + 1..].find('"') else {
250            continue;
251        };
252        let import_path = &line[start + 1..start + 1 + end];
253
254        // Skip well-known google types — protox has them built-in
255        if import_path.starts_with("google/protobuf/") {
256            continue;
257        }
258
259        // Find the best match for this import within the project
260        if let Some(found) = find_best_match(project_root, import_path) {
261            // Compute the include base: found = base / import_path
262            if let Some(base) = found
263                .to_str()
264                .and_then(|f| f.strip_suffix(import_path))
265                .map(PathBuf::from)
266            {
267                if !base.as_os_str().is_empty() {
268                    include_paths.insert(base);
269                }
270            } else if let Some(parent) = found.parent() {
271                include_paths.insert(parent.to_path_buf());
272            }
273
274            resolve_imports(&found, project_root, include_paths, visited);
275        }
276    }
277}
278
279/// Find the best match for a proto import within the project tree.
280/// If multiple files match, picks the largest one (avoids stubs/overlays).
281fn find_best_match(root: &Path, relative: &str) -> Option<PathBuf> {
282    let mut candidates = Vec::new();
283
284    // Direct from root
285    let direct = root.join(relative);
286    if direct.is_file() {
287        candidates.push(direct);
288    }
289
290    find_all_recursive(root, relative, &mut candidates);
291
292    if candidates.len() <= 1 {
293        return candidates.into_iter().next();
294    }
295
296    // Multiple matches — pick the largest file (real source, not a stub)
297    candidates
298        .into_iter()
299        .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
300}
301
302fn find_all_recursive(dir: &Path, relative: &str, results: &mut Vec<PathBuf>) {
303    let candidate = dir.join(relative);
304    if candidate.is_file() && !results.contains(&candidate) {
305        results.push(candidate);
306    }
307
308    let entries = match std::fs::read_dir(dir) {
309        Ok(e) => e,
310        Err(_) => return,
311    };
312
313    for entry in entries.flatten() {
314        let path = entry.path();
315        if path.is_dir() {
316            // Only skip hidden directories
317            let name = entry.file_name();
318            if name.to_str().is_some_and(|n| n.starts_with('.')) {
319                continue;
320            }
321            find_all_recursive(&path, relative, results);
322        }
323    }
324}