folk-api 0.3.3

Plugin contract for the Folk PHP application server
Documentation
//! RPC method registration: plugins expose methods that PHP workers can invoke
//! on the master in-process (via the `folk_call()` native function).
//!
//! Two shapes of method exist:
//!
//! * **Unary** ([`RpcRegistrar`]) — one request `Bytes` → one response `Bytes`,
//!   driven by the synchronous `folk_call` bridge.
//! * **Streaming** ([`StreamRegistrar`], phase 88b) — one open → a stream of
//!   messages in either or both directions, driven by the handle-based blocking
//!   bridge (`folk_stream_open/recv/send/close`). The handler returns a
//!   [`StreamConn`] the bridge blocking-drains one message at a time.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use anyhow::Result;
use async_trait::async_trait;
use bytes::Bytes;
use futures_core::Stream;

/// Static description of an RPC method (advertised at server start; used
/// for introspection / documentation).
#[derive(Debug, Clone)]
pub struct RpcMethodDef {
    /// Method name, dotted: `"http.connections"`, `"jobs.stats"`.
    pub name: String,
    /// Human-readable description for documentation / admin UIs.
    pub description: String,
}

impl RpcMethodDef {
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
        }
    }
}

/// Boxed future returned by an RPC handler.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Type alias for an RPC handler: takes raw request bytes, returns raw response bytes.
pub type RpcHandler = Arc<dyn Fn(Bytes) -> BoxFuture<'static, Result<Bytes>> + Send + Sync>;

/// Allows plugins to register RPC method handlers at boot.
///
/// `folk-core` provides the concrete implementation.
#[async_trait]
pub trait RpcRegistrar: Send + Sync + 'static {
    /// Register a method by name. The handler receives raw request bytes and
    /// returns raw response bytes (JSON-encoded payloads).
    async fn register_raw(&self, name: String, handler: RpcHandler);
}

// ---------------------------------------------------------------------------
// Streaming (phase 88b)
// ---------------------------------------------------------------------------

/// One inbound message of a stream: raw response `Bytes`, or an error carrying a
/// gRPC-style status the bridge surfaces to PHP as an exception.
pub type StreamItem = Result<Bytes>;

/// Boxed inbound message stream. The bridge blocking-drains it one item at a time
/// (`folk_stream_recv` → `Some(bytes)` per item, `None` at end-of-stream).
pub type InboundStream = Pin<Box<dyn Stream<Item = StreamItem> + Send>>;

/// Outbound message channel for client-streaming / bidi: the bridge pushes
/// PHP-sent messages here (`folk_stream_send`), closing it half-closes the send
/// side (`folk_stream_close_send`). `tokio::sync::mpsc` gives natural backpressure.
pub type OutboundSender = tokio::sync::mpsc::Sender<Bytes>;

/// A live stream connection returned by a [`StreamHandler`]. The transport plugin
/// (e.g. `folk-plugin-grpc`) adapts its own stream type (tonic `Streaming`) into
/// this transport-agnostic pair; the bridge in `folk-ext` drives it.
///
/// `#[non_exhaustive]`: construct via [`StreamConn::server_streaming`] /
/// [`StreamConn::duplex`] so future fields (deadlines, trailing metadata) can be
/// added without breaking transport plugins.
#[non_exhaustive]
pub struct StreamConn {
    /// Server → client messages. Always present.
    pub inbound: InboundStream,
    /// Client → server channel. `None` for server-streaming (the client sends
    /// nothing after the initial request); `Some` for client-streaming / bidi.
    pub outbound: Option<OutboundSender>,
}

impl StreamConn {
    /// Server-streaming: one request already sent at open, only inbound messages.
    pub fn server_streaming(inbound: InboundStream) -> Self {
        Self {
            inbound,
            outbound: None,
        }
    }

    /// Client-streaming / bidi: messages flow in both directions.
    pub fn duplex(inbound: InboundStream, outbound: OutboundSender) -> Self {
        Self {
            inbound,
            outbound: Some(outbound),
        }
    }
}

/// A streaming handler: given the initial request bytes, opens a [`StreamConn`].
pub type StreamHandler = Arc<dyn Fn(Bytes) -> BoxFuture<'static, Result<StreamConn>> + Send + Sync>;

/// Allows plugins to register streaming method handlers at boot. Additive
/// counterpart to [`RpcRegistrar`]; `folk-core` provides the concrete impl.
#[async_trait]
pub trait StreamRegistrar: Send + Sync + 'static {
    /// Register a streaming method by name. The handler opens a stream per call.
    async fn register_stream(&self, name: String, handler: StreamHandler);
}