use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context, Result};
use async_trait::async_trait;
use axum::Router;
use bytes::Bytes;
use folk_api::{BoxFuture, PluginContext, RpcMethodDef, ServerPlugin, StreamConn};
use prost_reflect::DescriptorPool;
use tonic::transport::{Identity, Server, ServerTlsConfig};
use tracing::{debug, info, warn};
use crate::client::{ClientCallEnvelope, ClientRegistry, ClientStreamEnvelope};
use crate::config::GrpcConfig;
use crate::metrics::GrpcMetrics;
use crate::service::{GrpcState, grpc_handler};
pub struct GrpcPlugin {
config: GrpcConfig,
}
impl GrpcPlugin {
pub fn new(config: GrpcConfig) -> Self {
Self { config }
}
}
#[async_trait]
impl ServerPlugin for GrpcPlugin {
fn name(&self) -> &'static str {
"grpc"
}
async fn run(&self, ctx: PluginContext) -> Result<()> {
let metrics = ctx
.metrics_registry
.as_ref()
.map(|r| GrpcMetrics::new(r.as_ref()));
if metrics.is_some() {
info!("gRPC metrics registered");
}
if !self.config.clients.is_empty() {
let registry = Arc::new(ClientRegistry::build(&self.config.clients));
let client_count = registry.len();
if let Some(reg) = &ctx.rpc_registrar {
let registry = registry.clone();
reg.register_raw(
"grpc.client.call".into(),
Arc::new(move |payload: Bytes| -> BoxFuture<'static, Result<Bytes>> {
let registry = registry.clone();
Box::pin(async move {
let env: ClientCallEnvelope = serde_json::from_slice(&payload)
.context("decode grpc.client.call envelope")?;
let response = registry.call(env).await;
Ok(Bytes::from(serde_json::to_vec(&response)?))
})
}),
)
.await;
info!(
clients = client_count,
"gRPC client transport enabled (grpc.client.call)"
);
} else {
warn!("[grpc.clients] configured but no RPC registrar available; client disabled");
}
if let Some(sreg) = &ctx.stream_registrar {
let registry = registry.clone();
sreg.register_stream(
"grpc.client.stream".into(),
Arc::new(
move |payload: Bytes| -> BoxFuture<'static, Result<StreamConn>> {
let registry = registry.clone();
Box::pin(async move {
let env: ClientStreamEnvelope = serde_json::from_slice(&payload)
.context("decode grpc.client.stream envelope")?;
Ok(registry.open_stream(env).await)
})
},
),
)
.await;
info!(
clients = client_count,
"gRPC client streaming enabled (grpc.client.stream)"
);
} else {
warn!(
"[grpc.clients] configured but no stream registrar available; streaming disabled"
);
}
}
let Some(listen) = self.config.listen else {
info!("gRPC client-only mode (no [grpc] listen); server not started");
let mut sd = ctx.shutdown.clone();
if let Err(e) = sd.changed().await {
tracing::error!(error = %e, "shutdown sender dropped unexpectedly");
}
return Ok(());
};
let proto_files = expand_proto_paths(&self.config.proto);
let descriptors = if self.config.transcode {
match build_descriptor_pool(&proto_files, self.config.descriptor_set.as_deref()) {
Ok(pool) => {
info!(files = pool.files().count(), "gRPC transcoding enabled");
Some(Arc::new(pool))
}
Err(e) => {
warn!(error = %e, "transcode enabled but descriptor pool build failed; using raw passthrough");
None
}
}
} else {
None
};
let state = GrpcState {
executor: ctx.executor.clone(),
max_recv_message_size: self.config.max_recv_message_size,
max_send_message_size: self.config.max_send_message_size,
compression: self.config.compression,
metrics,
descriptors,
};
let router: axum::Router = Router::new().fallback(grpc_handler).with_state(state);
let mut sd = ctx.shutdown.clone();
info!(listen = %listen, "gRPC server listening");
let mut builder = if let Some(ref tls) = self.config.tls {
let cert = std::fs::read(&tls.cert)
.with_context(|| format!("read TLS cert: {}", tls.cert.display()))?;
let key = std::fs::read(&tls.key)
.with_context(|| format!("read TLS key: {}", tls.key.display()))?;
let identity = Identity::from_pem(cert, key);
let tls_config = ServerTlsConfig::new().identity(identity);
info!(cert = %tls.cert.display(), "gRPC TLS enabled");
Server::builder()
.tls_config(tls_config)
.context("TLS config")?
} else {
Server::builder()
};
if let Some(timeout) = self.config.timeout {
builder = builder.timeout(timeout);
info!(timeout = ?timeout, "gRPC server timeout configured");
}
if let Some(max_streams) = self.config.max_concurrent_streams {
builder = builder.max_concurrent_streams(max_streams);
}
if let Some(ref ka) = self.config.keepalive {
builder = builder
.http2_keepalive_interval(Some(ka.interval))
.http2_keepalive_timeout(Some(ka.timeout));
info!(interval = ?ka.interval, timeout = ?ka.timeout, "gRPC keepalive configured");
}
let mut router = builder.add_routes(tonic::service::Routes::from(router));
let (health_reporter, health_service) = tonic_health::server::health_reporter();
health_reporter
.set_service_status("", tonic_health::ServingStatus::Serving)
.await;
router = router.add_service(health_service);
info!("gRPC health checking enabled");
{
let proto_fds = if !proto_files.is_empty() {
match export_descriptors(&proto_files) {
Ok(fds) => {
info!(proto_files = proto_files.len(), "gRPC reflection enabled");
Some(fds)
}
Err(e) => {
warn!(error = %e, "failed to build proto reflection; continuing without it");
None
}
}
} else {
None
};
let mut reflection_builder = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(tonic_health::pb::FILE_DESCRIPTOR_SET);
if let Some(ref fds) = proto_fds {
reflection_builder = reflection_builder.register_encoded_file_descriptor_set(fds);
}
match reflection_builder.build_v1() {
Ok(reflection) => {
router = router.add_service(reflection);
}
Err(e) => {
warn!(error = %e, "failed to build reflection service");
}
}
}
let listener = bind_reuseport(listen)?;
let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener);
router
.serve_with_incoming_shutdown(incoming, async move {
if let Err(e) = sd.changed().await {
tracing::error!(error = %e, "shutdown sender dropped unexpectedly");
}
})
.await?;
Ok(())
}
fn rpc_methods(&self) -> Vec<RpcMethodDef> {
if self.config.clients.is_empty() {
vec![]
} else {
vec![RpcMethodDef::new(
"grpc.client.call",
"call an upstream gRPC unary method (Folk as client)",
)]
}
}
}
fn bind_reuseport(addr: std::net::SocketAddr) -> Result<tokio::net::TcpListener> {
use socket2::{Domain, Protocol, Socket, Type};
let domain = if addr.is_ipv6() {
Domain::IPV6
} else {
Domain::IPV4
};
let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
socket.set_reuse_address(true)?;
socket.set_reuse_port(true)?;
socket.set_nonblocking(true)?;
socket.bind(&addr.into())?;
socket.listen(1024)?;
Ok(tokio::net::TcpListener::from_std(socket.into())?)
}
pub fn export_descriptors(proto_files: &[String]) -> Result<Vec<u8>> {
let cwd = std::env::current_dir().context("get cwd")?;
let mut include_paths = BTreeSet::new();
let mut visited = BTreeSet::new();
for proto in proto_files {
let abs = cwd.join(proto);
resolve_imports(&abs, &cwd, &mut include_paths, &mut visited);
}
for proto in proto_files {
let abs = cwd.join(proto);
if let Some(parent) = abs.parent() {
include_paths.insert(parent.to_path_buf());
}
}
debug!(paths = include_paths.len(), "resolved proto include paths");
let paths: Vec<_> = include_paths.iter().collect();
let mut compiler = protox::Compiler::new(paths.iter().map(|p| p.as_path()))
.context("create protox compiler")?;
compiler.include_imports(true);
for proto in proto_files {
let path = Path::new(proto);
let file_name = path
.file_name()
.and_then(|n| n.to_str())
.context("invalid proto file name")?;
compiler
.open_file(file_name)
.with_context(|| format!("compile {proto}"))?;
}
let fds = compiler.file_descriptor_set();
Ok(prost::Message::encode_to_vec(&fds))
}
pub fn expand_proto_paths(entries: &[String]) -> Vec<String> {
let mut files = Vec::new();
for entry in entries {
let path = Path::new(entry);
if path.is_dir() {
collect_protos(path, &mut files);
} else {
files.push(entry.clone());
}
}
files.sort();
files.dedup();
files
}
fn collect_protos(dir: &Path, out: &mut Vec<String>) {
let Ok(read) = std::fs::read_dir(dir) else {
return;
};
for entry in read.flatten() {
let path = entry.path();
if path.is_dir() {
collect_protos(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("proto") {
if let Some(s) = path.to_str() {
out.push(s.to_string());
}
}
}
}
pub fn build_descriptor_pool(
proto_entries: &[String],
bundle: Option<&str>,
) -> Result<DescriptorPool> {
let mut pool = DescriptorPool::new();
let proto_files = expand_proto_paths(proto_entries);
if !proto_files.is_empty() {
let fds = export_descriptors(&proto_files).context("compile proto for transcoding")?;
pool.decode_file_descriptor_set(fds.as_slice())
.context("load compiled proto into descriptor pool")?;
}
if let Some(path) = bundle {
let bytes =
std::fs::read(path).with_context(|| format!("read descriptor_set bundle: {path}"))?;
pool.decode_file_descriptor_set(bytes.as_slice())
.with_context(|| format!("load descriptor_set bundle: {path}"))?;
}
if pool.files().count() == 0 {
anyhow::bail!(
"transcode = true but no descriptors provided (empty proto and no descriptor_set)"
);
}
Ok(pool)
}
fn resolve_imports(
proto_path: &Path,
project_root: &Path,
include_paths: &mut BTreeSet<PathBuf>,
visited: &mut BTreeSet<PathBuf>,
) {
if !proto_path.is_file() || !visited.insert(proto_path.to_path_buf()) {
return;
}
let content = match std::fs::read_to_string(proto_path) {
Ok(c) => c,
Err(_) => return,
};
for line in content.lines() {
let line = line.trim();
if !line.starts_with("import ") {
continue;
}
let Some(start) = line.find('"') else {
continue;
};
let Some(end) = line[start + 1..].find('"') else {
continue;
};
let import_path = &line[start + 1..start + 1 + end];
if import_path.starts_with("google/protobuf/") {
continue;
}
if let Some(found) = find_best_match(project_root, import_path) {
if let Some(base) = found
.to_str()
.and_then(|f| f.strip_suffix(import_path))
.map(PathBuf::from)
{
if !base.as_os_str().is_empty() {
include_paths.insert(base);
}
} else if let Some(parent) = found.parent() {
include_paths.insert(parent.to_path_buf());
}
resolve_imports(&found, project_root, include_paths, visited);
}
}
}
fn find_best_match(root: &Path, relative: &str) -> Option<PathBuf> {
let mut candidates = Vec::new();
let direct = root.join(relative);
if direct.is_file() {
candidates.push(direct);
}
find_all_recursive(root, relative, &mut candidates);
if candidates.len() <= 1 {
return candidates.into_iter().next();
}
candidates
.into_iter()
.max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
}
fn find_all_recursive(dir: &Path, relative: &str, results: &mut Vec<PathBuf>) {
let candidate = dir.join(relative);
if candidate.is_file() && !results.contains(&candidate) {
results.push(candidate);
}
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let name = entry.file_name();
if name.to_str().is_some_and(|n| n.starts_with('.')) {
continue;
}
find_all_recursive(&path, relative, results);
}
}
}