folk_api/rpc.rs
1//! RPC method registration: plugins expose methods that PHP workers can invoke
2//! on the master in-process (via the `folk_call()` native function).
3//!
4//! Two shapes of method exist:
5//!
6//! * **Unary** ([`RpcRegistrar`]) — one request `Bytes` → one response `Bytes`,
7//! driven by the synchronous `folk_call` bridge.
8//! * **Streaming** ([`StreamRegistrar`], phase 88b) — one open → a stream of
9//! messages in either or both directions, driven by the handle-based blocking
10//! bridge (`folk_stream_open/recv/send/close`). The handler returns a
11//! [`StreamConn`] the bridge blocking-drains one message at a time.
12
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16
17use anyhow::Result;
18use async_trait::async_trait;
19use bytes::Bytes;
20use futures_core::Stream;
21
22/// Static description of an RPC method (advertised at server start; used
23/// for introspection / documentation).
24#[derive(Debug, Clone)]
25pub struct RpcMethodDef {
26 /// Method name, dotted: `"http.connections"`, `"jobs.stats"`.
27 pub name: String,
28 /// Human-readable description for documentation / admin UIs.
29 pub description: String,
30}
31
32impl RpcMethodDef {
33 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
34 Self {
35 name: name.into(),
36 description: description.into(),
37 }
38 }
39}
40
41/// Boxed future returned by an RPC handler.
42pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
43
44/// Type alias for an RPC handler: takes raw request bytes, returns raw response bytes.
45pub type RpcHandler = Arc<dyn Fn(Bytes) -> BoxFuture<'static, Result<Bytes>> + Send + Sync>;
46
47/// Allows plugins to register RPC method handlers at boot.
48///
49/// `folk-core` provides the concrete implementation.
50#[async_trait]
51pub trait RpcRegistrar: Send + Sync + 'static {
52 /// Register a method by name. The handler receives raw request bytes and
53 /// returns raw response bytes (JSON-encoded payloads).
54 async fn register_raw(&self, name: String, handler: RpcHandler);
55}
56
57// ---------------------------------------------------------------------------
58// Streaming (phase 88b)
59// ---------------------------------------------------------------------------
60
61/// One inbound message of a stream: raw response `Bytes`, or an error carrying a
62/// gRPC-style status the bridge surfaces to PHP as an exception.
63pub type StreamItem = Result<Bytes>;
64
65/// Boxed inbound message stream. The bridge blocking-drains it one item at a time
66/// (`folk_stream_recv` → `Some(bytes)` per item, `None` at end-of-stream).
67pub type InboundStream = Pin<Box<dyn Stream<Item = StreamItem> + Send>>;
68
69/// Outbound message channel for client-streaming / bidi: the bridge pushes
70/// PHP-sent messages here (`folk_stream_send`), closing it half-closes the send
71/// side (`folk_stream_close_send`). `tokio::sync::mpsc` gives natural backpressure.
72pub type OutboundSender = tokio::sync::mpsc::Sender<Bytes>;
73
74/// A live stream connection returned by a [`StreamHandler`]. The transport plugin
75/// (e.g. `folk-plugin-grpc`) adapts its own stream type (tonic `Streaming`) into
76/// this transport-agnostic pair; the bridge in `folk-ext` drives it.
77///
78/// `#[non_exhaustive]`: construct via [`StreamConn::server_streaming`] /
79/// [`StreamConn::duplex`] so future fields (deadlines, trailing metadata) can be
80/// added without breaking transport plugins.
81#[non_exhaustive]
82pub struct StreamConn {
83 /// Server → client messages. Always present.
84 pub inbound: InboundStream,
85 /// Client → server channel. `None` for server-streaming (the client sends
86 /// nothing after the initial request); `Some` for client-streaming / bidi.
87 pub outbound: Option<OutboundSender>,
88}
89
90impl StreamConn {
91 /// Server-streaming: one request already sent at open, only inbound messages.
92 pub fn server_streaming(inbound: InboundStream) -> Self {
93 Self {
94 inbound,
95 outbound: None,
96 }
97 }
98
99 /// Client-streaming / bidi: messages flow in both directions.
100 pub fn duplex(inbound: InboundStream, outbound: OutboundSender) -> Self {
101 Self {
102 inbound,
103 outbound: Some(outbound),
104 }
105 }
106}
107
108/// A streaming handler: given the initial request bytes, opens a [`StreamConn`].
109pub type StreamHandler = Arc<dyn Fn(Bytes) -> BoxFuture<'static, Result<StreamConn>> + Send + Sync>;
110
111/// Allows plugins to register streaming method handlers at boot. Additive
112/// counterpart to [`RpcRegistrar`]; `folk-core` provides the concrete impl.
113#[async_trait]
114pub trait StreamRegistrar: Send + Sync + 'static {
115 /// Register a streaming method by name. The handler opens a stream per call.
116 async fn register_stream(&self, name: String, handler: StreamHandler);
117}