folk-plugin-grpc 0.7.1

gRPC plugin for Folk — unary server + client (call upstreams from PHP) via tonic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
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");
        }

        // --- Client transport (phase 88) ---
        // Register `grpc.client.call` when any `[grpc.clients.*]` is configured. The
        // registry (per-client descriptor pools) is built here; channels open lazily
        // on first call inside this worker's runtime (per-worker pool). Independent
        // of the server side below — a client-only config (no `listen`) still gets it.
        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");
            }

            // Streaming client transport (phase 88b): `grpc.client.stream` opens a
            // server-streaming call via the handle-based bridge. Additive to the
            // unary `grpc.client.call` above; needs the streaming registrar.
            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"
                );
            }
        }

        // --- Server (only when `[grpc] listen` is set) ---
        // Omitting `listen` yields a client-only deployment: no listener is bound,
        // the worker just waits for shutdown after registering the client handler.
        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(());
        };

        // Expand proto entries (files + directories) into a flat `*.proto` list,
        // shared by reflection and the transcoding descriptor pool.
        let proto_files = expand_proto_paths(&self.config.proto);

        // Descriptor pool for proto↔native transcoding (phase 87). Built only when
        // `transcode = true`; any failure degrades to raw passthrough rather than
        // aborting the server.
        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");

        // --- Server builder ---
        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");
        }

        // --- Accumulate services ---
        let mut router = builder.add_routes(tonic::service::Routes::from(router));

        // Health checking (grpc.health.v1)
        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");

        // Reflection (always includes health service descriptor)
        {
            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");
                }
            }
        }

        // --- Serve ---
        // Phase 79: bind via SO_REUSEPORT so every forked worker binds the same
        // address and the kernel load-balances gRPC connections across them.
        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)",
            )]
        }
    }
}

/// Bind a `SO_REUSEPORT` TCP listener (phase 79 fork model) — every worker
/// process binds the same address; the kernel balances connections.
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())?)
}

/// Compile proto files and return an encoded `FileDescriptorSet` (protobuf bytes).
///
/// Shared by two callers: server startup (reflection descriptor pool) and the
/// descriptor-export path used by codegen (`folk_grpc_descriptors()` php function
/// / `folk-server grpc:descriptors` submode, phase 87 task 1.4). It needs only the
/// proto file list and the current working directory — no plugin instance, config,
/// tokio runtime, or booted server — which is what lets the export path run without
/// binding listeners or forking workers.
///
/// Import paths are resolved automatically:
/// - Parses `import` statements from each proto file
/// - Searches for imported files within the project root (cwd)
/// - Never searches outside the working directory
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();

    // Resolve imports starting from each proto file
    let mut visited = BTreeSet::new();
    for proto in proto_files {
        let abs = cwd.join(proto);
        resolve_imports(&abs, &cwd, &mut include_paths, &mut visited);
    }

    // Always include the directory of each proto file itself
    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))
}

/// Expand `[grpc] proto` entries into a flat list of `*.proto` file paths.
///
/// A directory entry is scanned recursively for `*.proto` (solution 5, phase 87);
/// a file entry is kept as-is. Non-existent entries pass through unchanged so the
/// downstream protox compiler reports them clearly.
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
}

/// Recursively collect `*.proto` files under `dir` into `out`.
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());
            }
        }
    }
}

/// Build a [`DescriptorPool`] for transcoding from proto files and/or a prebuilt
/// `FileDescriptorSet` bundle. Both sources merge into one pool (solution 5), so
/// `Any` can unpack any type present in either. Errors if neither yields any
/// descriptor (transcode was requested but nothing to transcode against).
pub fn build_descriptor_pool(
    proto_entries: &[String],
    bundle: Option<&str>,
) -> Result<DescriptorPool> {
    let mut pool = DescriptorPool::new();

    // Accept files or directories; expansion is idempotent on an already-flat list.
    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)
}

/// Parse a proto file for `import` statements and find each imported file
/// within the project root. Adds the containing directory to include_paths.
/// Recurses into found imports.
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();
        // Match: import "path/to/file.proto";
        // Match: import public "path/to/file.proto";
        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];

        // Skip well-known google types — protox has them built-in
        if import_path.starts_with("google/protobuf/") {
            continue;
        }

        // Find the best match for this import within the project
        if let Some(found) = find_best_match(project_root, import_path) {
            // Compute the include base: found = base / 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);
        }
    }
}

/// Find the best match for a proto import within the project tree.
/// If multiple files match, picks the largest one (avoids stubs/overlays).
fn find_best_match(root: &Path, relative: &str) -> Option<PathBuf> {
    let mut candidates = Vec::new();

    // Direct from root
    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();
    }

    // Multiple matches — pick the largest file (real source, not a stub)
    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() {
            // Only skip hidden directories
            let name = entry.file_name();
            if name.to_str().is_some_and(|n| n.starts_with('.')) {
                continue;
            }
            find_all_recursive(&path, relative, results);
        }
    }
}