From 7a7ee457614461382e3a815a78617dd675dcc48e Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 2 Dec 2026 21:23:38 +0800 Subject: [PATCH 1/2] Generate typed bindings for versioned cluster RPC contracts --- Cargo.lock | 10 ++ crates/bedrock-rpc/Cargo.toml | 13 ++ crates/bedrock-rpc/README.md | 32 +++++ crates/bedrock-rpc/examples/cluster_probe.rs | 85 +++++++++++ crates/bedrock-rpc/src/lib.rs | 142 +++++++++++++++++++ crates/bedrock-rpc/tests/contract.rs | 65 +++++++++ 6 files changed, 347 insertions(+) create mode 100644 crates/bedrock-rpc/Cargo.toml create mode 100644 crates/bedrock-rpc/README.md create mode 100644 crates/bedrock-rpc/examples/cluster_probe.rs create mode 100644 crates/bedrock-rpc/src/lib.rs create mode 100644 crates/bedrock-rpc/tests/contract.rs diff --git a/Cargo.lock b/Cargo.lock index e63f0ac..6c2a358 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -163,6 +163,16 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bedrock-rpc" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "tokio", +] + [[package]] name = "bitflags" version = "2.13.2" diff --git a/crates/bedrock-rpc/Cargo.toml b/crates/bedrock-rpc/Cargo.toml new file mode 100644 index 0000000..c8eec97 --- /dev/null +++ b/crates/bedrock-rpc/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "bedrock-rpc" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tokio = { workspace = true, features = ["io-util", "net", "time"] } diff --git a/crates/bedrock-rpc/README.md b/crates/bedrock-rpc/README.md new file mode 100644 index 0000000..1d96c31 --- /dev/null +++ b/crates/bedrock-rpc/README.md @@ -0,0 +1,32 @@ +# Bedrock RPC + +业务模块在共享的 Rust 契约中声明服务名、稳定的方法编号、请求类型和返回类型。编译调用方和接收方时,`service!` 分别生成可直接调用的 `Client`、由业务代码实现的 `Service` trait,以及把请求交给相应方法的 `dispatch`。一个契约占用一个 Rust 模块,请求和返回值使用可由 Serde JSON 往返编码的自有类型。 + +```rust +mod replica { + bedrock_rpc::service! { + "bedrock.replica.v1" { + 1 => revision(()) -> u64, + } + } +} +``` + +一次调用的路径如下。 + +1. 调用方用已绑定目标的适配器构造 `replica::Client(peer)`,调用 `revision(()).await`。 +2. 客户端把类型化参数编码成请求。此例的 JSON 为 `{"service":"bedrock.replica.v1","method":1,"payload":null}`。 +3. 业务代码实现的 `Transport::exchange` 将请求交给目标实例。接收端将请求交给 `replica::dispatch(&handler, request)`。分派器检查服务和方法,解码参数,再调用 handler。 +4. 成功响应形如 `{"success":42}`。客户端按声明解码为 `u64`。传输故障、远端拒绝和本端编解码错误分别返回。业务领域错误可直接建模为返回类型的枚举。 + +## 集群边界 + +同一份契约可用于同集群的服务地址和另一集群的网关。调用方通过适配器选择目标。跨集群的适配器负责身份认证、TLS、截止时间和连接管理。接收端在 dispatch 之前鉴权。业务 handler 可持有 Bedrock 数据库连接或经过鉴权的调用上下文。多个服务共用一个入口时,入口按 request.service 选择对应分派器。 + +[回环 TCP 示例](examples/cluster_probe.rs) 把组帧、连接和收发实现在契约外,用一次连接对应一个请求。示例使用本地明文监听和固定的测试修订号,可在远程 runner 执行 `cargo run --locked -p bedrock-rpc --example cluster_probe`。现有 backend 的路由与启动配置没有接入该示例。 + +## 兼容与交付语义 + +服务名包含协议主版本。增量发布使用新的方法编号,给新增的可选请求字段设置反序列化默认值。保留已发布方法的编号及请求、响应含义。破坏兼容性的修改使用新服务名。旧节点收到新方法会返回 unknown_method,调用方可据此处理滚动升级。 + +框架支持一问一答。连接中断可能发生在服务已经处理请求之后。框架不会自动重试。需要重试写操作时,由业务协议定义幂等键和去重行为。 diff --git a/crates/bedrock-rpc/examples/cluster_probe.rs b/crates/bedrock-rpc/examples/cluster_probe.rs new file mode 100644 index 0000000..6dbb855 --- /dev/null +++ b/crates/bedrock-rpc/examples/cluster_probe.rs @@ -0,0 +1,85 @@ +//! One request per TCP connection. The destination is bound when constructing the client. +use std::{io, net::SocketAddr, time::Duration}; + +use bedrock_rpc::{Fault, Reply, Request, Transport}; +use serde::{Serialize, de::DeserializeOwned}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + time::timeout, +}; + +mod probe { + bedrock_rpc::service! { + "bedrock.probe.v1" { + 1 => revision(()) -> u64, + } + } +} + +struct Replica(u64); + +impl probe::Service for Replica { + async fn revision(&self, (): ()) -> Result { + Ok(self.0) + } +} + +const MAX_FRAME: usize = 64 * 1024; + +async fn read_frame(stream: &mut TcpStream) -> io::Result { + let len = stream.read_u32().await? as usize; + if len > MAX_FRAME { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "oversized RPC frame", + )); + } + let mut bytes = vec![0; len]; + stream.read_exact(&mut bytes).await?; + Ok(serde_json::from_slice(&bytes)?) +} + +async fn write_frame(stream: &mut TcpStream, value: &impl Serialize) -> io::Result<()> { + let bytes = serde_json::to_vec(value)?; + if bytes.len() > MAX_FRAME { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "oversized RPC frame", + )); + } + stream.write_u32(bytes.len() as u32).await?; + stream.write_all(&bytes).await +} + +struct TcpPeer(SocketAddr); + +impl Transport for TcpPeer { + type Error = io::Error; + + async fn exchange(&self, request: Request) -> io::Result { + let mut stream = TcpStream::connect(self.0).await?; + write_frame(&mut stream, &request).await?; + read_frame(&mut stream).await + } +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let listener = TcpListener::bind(("127.0.0.1", 0)).await?; + let client = probe::Client(TcpPeer(listener.local_addr()?)); + let serve = async { + let (mut stream, _) = listener.accept().await?; + let request = read_frame(&mut stream).await?; + let reply = probe::dispatch(&Replica(42), request).await; + write_frame(&mut stream, &reply).await + }; + let (served, reply) = timeout(Duration::from_secs(5), async { + tokio::join!(serve, client.revision(())) + }) + .await?; + served?; + assert_eq!(reply?, 42); + println!("replica revision = 42"); + Ok(()) +} diff --git a/crates/bedrock-rpc/src/lib.rs b/crates/bedrock-rpc/src/lib.rs new file mode 100644 index 0000000..4276233 --- /dev/null +++ b/crates/bedrock-rpc/src/lib.rs @@ -0,0 +1,142 @@ +//! Build-time bindings for unary cluster services. +use std::future::Future; + +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::Value; +use thiserror::Error; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Request { + pub service: String, + pub method: u32, + pub payload: Value, +} + +/// Stable wire errors. A service can model richer domain outcomes in its return type. +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Error)] +#[serde(rename_all = "snake_case")] +pub enum Fault { + #[error("unknown service or major version")] + UnknownService, + #[error("unknown method")] + UnknownMethod, + #[error("invalid request")] + InvalidRequest, + #[error("service unavailable")] + Unavailable, + #[error("internal service error")] + Internal, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Reply { + Success(Value), + Failure(Fault), +} + +/// An adapter bound to one destination. Each exchange must return its own reply. +pub trait Transport: Sync { + type Error; + fn exchange(&self, request: Request) + -> impl Future> + Send; +} + +#[derive(Debug, Error)] +pub enum CallError { + #[error("transport error: {0}")] + Transport(E), + #[error("remote error: {0}")] + Remote(Fault), + #[error("payload codec error: {0}")] + Codec(serde_json::Error), +} + +#[doc(hidden)] +pub async fn call( + transport: &T, + service: &str, + method: u32, + input: I, +) -> Result> { + let payload = serde_json::to_value(input).map_err(CallError::Codec)?; + let request = Request { + service: service.into(), + method, + payload, + }; + match transport + .exchange(request) + .await + .map_err(CallError::Transport)? + { + Reply::Failure(fault) => Err(CallError::Remote(fault)), + Reply::Success(value) => serde_json::from_value(value).map_err(CallError::Codec), + } +} + +#[doc(hidden)] +pub async fn invoke(payload: Value, handler: impl FnOnce(I) -> F) -> Reply +where + I: DeserializeOwned, + O: Serialize, + F: Future>, +{ + let Ok(input) = serde_json::from_value(payload) else { + return Reply::Failure(Fault::InvalidRequest); + }; + match handler(input).await { + Ok(output) => match serde_json::to_value(output) { + Ok(value) => Reply::Success(value), + Err(_) => Reply::Failure(Fault::Internal), + }, + Err(fault) => Reply::Failure(fault), + } +} + +/// Declare one versioned service per module. Method numbers are stable wire IDs. +/// +/// ```compile_fail +/// bedrock_rpc::service! { +/// "bedrock.example.v1" { +/// 1 => first(()) -> (), +/// 1 => second(()) -> (), +/// } +/// } +/// ``` +#[macro_export] +macro_rules! service { + ($service:literal { $($id:literal => $method:ident($input:ty) -> $output:ty),+ $(,)? }) => { + pub const SERVICE: &str = $service; + // Duplicate discriminants are hard errors even for downstream dependencies. + const _: () = { + #[allow(dead_code, non_camel_case_types)] + #[repr(u32)] + enum Method { $($method = $id),+ } + }; + + pub trait Service: Sync { + $(fn $method(&self, input: $input) -> impl ::std::future::Future< + Output = ::std::result::Result<$output, $crate::Fault> + > + Send;)+ + } + + pub struct Client(pub T); + + impl Client { + $(pub async fn $method(&self, input: $input) -> ::std::result::Result<$output, $crate::CallError> { + $crate::call(&self.0, SERVICE, $id, input).await + })+ + } + + pub async fn dispatch(handler: &impl Service, request: $crate::Request) -> $crate::Reply { + if request.service != SERVICE { + return $crate::Reply::Failure($crate::Fault::UnknownService); + } + match request.method { + $($id => $crate::invoke(request.payload, |input| handler.$method(input)).await,)+ + _ => $crate::Reply::Failure($crate::Fault::UnknownMethod), + } + } + }; +} diff --git a/crates/bedrock-rpc/tests/contract.rs b/crates/bedrock-rpc/tests/contract.rs new file mode 100644 index 0000000..5c3fc1c --- /dev/null +++ b/crates/bedrock-rpc/tests/contract.rs @@ -0,0 +1,65 @@ +use bedrock_rpc::{CallError, Fault, Reply, Request, Transport}; +use serde_json::json; + +mod catalog { + bedrock_rpc::service! { + "bedrock.catalog.v1" { + 3 => lookup(String) -> u64, + 8 => ready(()) -> bool, + } + } +} + +struct Catalog; + +impl catalog::Service for Catalog { + async fn lookup(&self, key: String) -> Result { + if key == "documents" { + Ok(17) + } else { + Err(Fault::Unavailable) + } + } + + async fn ready(&self, (): ()) -> Result { + Ok(true) + } +} + +struct Local; + +impl Transport for Local { + type Error = std::convert::Infallible; + async fn exchange(&self, request: Request) -> Result { + Ok(catalog::dispatch(&Catalog, request).await) + } +} + +#[tokio::test] +async fn typed_calls_and_remote_failures() { + let client = catalog::Client(Local); + assert_eq!(client.lookup("documents".into()).await.unwrap(), 17); + assert!(client.ready(()).await.unwrap()); + assert!(matches!( + client.lookup("missing".into()).await, + Err(CallError::Remote(Fault::Unavailable)) + )); +} + +#[tokio::test] +async fn rejects_incompatible_requests() { + for (service, method, fault) in [ + ("bedrock.catalog.v2", 3, Fault::UnknownService), + (catalog::SERVICE, 7, Fault::UnknownMethod), + (catalog::SERVICE, 3, Fault::InvalidRequest), + ] { + let request = Request { + service: service.into(), + method, + payload: json!(false), + }; + assert!( + matches!(catalog::dispatch(&Catalog, request).await, Reply::Failure(actual) if actual == fault) + ); + } +} From 6a81ed95a177df9c1703009faadc4696e0454855 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 04:44:00 +0800 Subject: [PATCH 2/2] Preserve the in-progress cluster RPC experiment for archival --- Cargo.lock | 11 ++ crates/admin_backend/Cargo.toml | 1 + crates/admin_backend/src/lib.rs | 46 +++---- crates/admin_backend/src/rpc.rs | 19 +++ crates/bedrock-rpc/Cargo.toml | 13 ++ crates/bedrock-rpc/README.md | 32 +++++ crates/bedrock-rpc/examples/cluster_probe.rs | 85 +++++++++++++ crates/bedrock-rpc/src/lib.rs | 126 +++++++++++++++++++ crates/bedrock-rpc/tests/contract.rs | 65 ++++++++++ 9 files changed, 376 insertions(+), 22 deletions(-) create mode 100644 crates/admin_backend/src/rpc.rs create mode 100644 crates/bedrock-rpc/Cargo.toml create mode 100644 crates/bedrock-rpc/README.md create mode 100644 crates/bedrock-rpc/examples/cluster_probe.rs create mode 100644 crates/bedrock-rpc/src/lib.rs create mode 100644 crates/bedrock-rpc/tests/contract.rs diff --git a/Cargo.lock b/Cargo.lock index e63f0ac..51fd917 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,6 +13,7 @@ name = "admin_backend" version = "0.1.0" dependencies = [ "axum", + "bedrock-rpc", "clusters", "serde", "subtle", @@ -163,6 +164,16 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bedrock-rpc" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "tokio", +] + [[package]] name = "bitflags" version = "2.13.2" diff --git a/crates/admin_backend/Cargo.toml b/crates/admin_backend/Cargo.toml index 3c48bab..c1f20ba 100644 --- a/crates/admin_backend/Cargo.toml +++ b/crates/admin_backend/Cargo.toml @@ -6,6 +6,7 @@ rust-version.workspace = true [dependencies] axum.workspace = true +bedrock-rpc = { path = "../bedrock-rpc" } clusters.workspace = true serde.workspace = true subtle.workspace = true diff --git a/crates/admin_backend/src/lib.rs b/crates/admin_backend/src/lib.rs index 822721d..d1f8744 100644 --- a/crates/admin_backend/src/lib.rs +++ b/crates/admin_backend/src/lib.rs @@ -1,3 +1,5 @@ +pub mod rpc; + use std::{io, sync::Arc}; use axum::{ @@ -9,7 +11,7 @@ use axum::{ routing::get, }; use clusters::{DOCUMENTS, ResolvedDeployment, SqlDriver}; -use serde::Serialize; +use rpc::DeploymentStatus; use subtle::ConstantTimeEq; #[derive(Clone)] @@ -20,29 +22,27 @@ struct AdminState { read_only: bool, } -#[derive(Serialize)] -struct DeploymentStatus<'a> { - deployment: &'a str, - config_version: Option<&'a str>, - storage_driver: &'static str, - read_only: bool, -} - impl AdminState { - fn status(&self) -> DeploymentStatus<'_> { + fn status(&self) -> DeploymentStatus { let config = &self.config; DeploymentStatus { - deployment: &config.deployment, + deployment: config.deployment.clone(), config_version: self .config_version - .as_deref() - .or(Some(&config.config_version)), - storage_driver: self.storage_driver, + .clone() + .or_else(|| Some(config.config_version.clone())), + storage_driver: self.storage_driver.to_owned(), read_only: self.read_only, } } } +impl rpc::Service for AdminState { + async fn status(&self, _: rpc::StatusRequest) -> Result { + Ok(self.status()) + } +} + pub fn router( config: Arc, config_version: Option, @@ -71,8 +71,16 @@ pub fn router( }; let read_only = settings.read_only; + let state = AdminState { + config, + config_version, + storage_driver, + read_only, + }; let admin = Router::new() - .route("/status", get(deployment_status)) + .route("/admin/v1/status", get(deployment_status)) + .with_state(state.clone()) + .merge(rpc::router(state)) .route_layer(middleware::from_fn_with_state( Arc::::from(token), require_admin, @@ -80,13 +88,7 @@ pub fn router( Ok(Router::new() .route("/healthz", get(|| async { StatusCode::NO_CONTENT })) .route("/readyz", get(|| async { StatusCode::NO_CONTENT })) - .nest("/admin/v1", admin) - .with_state(AdminState { - config, - config_version, - storage_driver, - read_only, - })) + .merge(admin)) } async fn deployment_status(State(state): State) -> Response { diff --git a/crates/admin_backend/src/rpc.rs b/crates/admin_backend/src/rpc.rs new file mode 100644 index 0000000..9fa33a7 --- /dev/null +++ b/crates/admin_backend/src/rpc.rs @@ -0,0 +1,19 @@ +//! Shared wire contract for querying the Bedrock instance serving the request. +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, Serialize)] +pub struct StatusRequest {} + +#[derive(Deserialize, Serialize)] +pub struct DeploymentStatus { + pub deployment: String, + pub config_version: Option, + pub storage_driver: String, + pub read_only: bool, +} + +bedrock_rpc::service! { + "/admin/v1/deployment" { + fn status(StatusRequest) -> DeploymentStatus; + } +} diff --git a/crates/bedrock-rpc/Cargo.toml b/crates/bedrock-rpc/Cargo.toml new file mode 100644 index 0000000..c8eec97 --- /dev/null +++ b/crates/bedrock-rpc/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "bedrock-rpc" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tokio = { workspace = true, features = ["io-util", "net", "time"] } diff --git a/crates/bedrock-rpc/README.md b/crates/bedrock-rpc/README.md new file mode 100644 index 0000000..1d96c31 --- /dev/null +++ b/crates/bedrock-rpc/README.md @@ -0,0 +1,32 @@ +# Bedrock RPC + +业务模块在共享的 Rust 契约中声明服务名、稳定的方法编号、请求类型和返回类型。编译调用方和接收方时,`service!` 分别生成可直接调用的 `Client`、由业务代码实现的 `Service` trait,以及把请求交给相应方法的 `dispatch`。一个契约占用一个 Rust 模块,请求和返回值使用可由 Serde JSON 往返编码的自有类型。 + +```rust +mod replica { + bedrock_rpc::service! { + "bedrock.replica.v1" { + 1 => revision(()) -> u64, + } + } +} +``` + +一次调用的路径如下。 + +1. 调用方用已绑定目标的适配器构造 `replica::Client(peer)`,调用 `revision(()).await`。 +2. 客户端把类型化参数编码成请求。此例的 JSON 为 `{"service":"bedrock.replica.v1","method":1,"payload":null}`。 +3. 业务代码实现的 `Transport::exchange` 将请求交给目标实例。接收端将请求交给 `replica::dispatch(&handler, request)`。分派器检查服务和方法,解码参数,再调用 handler。 +4. 成功响应形如 `{"success":42}`。客户端按声明解码为 `u64`。传输故障、远端拒绝和本端编解码错误分别返回。业务领域错误可直接建模为返回类型的枚举。 + +## 集群边界 + +同一份契约可用于同集群的服务地址和另一集群的网关。调用方通过适配器选择目标。跨集群的适配器负责身份认证、TLS、截止时间和连接管理。接收端在 dispatch 之前鉴权。业务 handler 可持有 Bedrock 数据库连接或经过鉴权的调用上下文。多个服务共用一个入口时,入口按 request.service 选择对应分派器。 + +[回环 TCP 示例](examples/cluster_probe.rs) 把组帧、连接和收发实现在契约外,用一次连接对应一个请求。示例使用本地明文监听和固定的测试修订号,可在远程 runner 执行 `cargo run --locked -p bedrock-rpc --example cluster_probe`。现有 backend 的路由与启动配置没有接入该示例。 + +## 兼容与交付语义 + +服务名包含协议主版本。增量发布使用新的方法编号,给新增的可选请求字段设置反序列化默认值。保留已发布方法的编号及请求、响应含义。破坏兼容性的修改使用新服务名。旧节点收到新方法会返回 unknown_method,调用方可据此处理滚动升级。 + +框架支持一问一答。连接中断可能发生在服务已经处理请求之后。框架不会自动重试。需要重试写操作时,由业务协议定义幂等键和去重行为。 diff --git a/crates/bedrock-rpc/examples/cluster_probe.rs b/crates/bedrock-rpc/examples/cluster_probe.rs new file mode 100644 index 0000000..6dbb855 --- /dev/null +++ b/crates/bedrock-rpc/examples/cluster_probe.rs @@ -0,0 +1,85 @@ +//! One request per TCP connection. The destination is bound when constructing the client. +use std::{io, net::SocketAddr, time::Duration}; + +use bedrock_rpc::{Fault, Reply, Request, Transport}; +use serde::{Serialize, de::DeserializeOwned}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + time::timeout, +}; + +mod probe { + bedrock_rpc::service! { + "bedrock.probe.v1" { + 1 => revision(()) -> u64, + } + } +} + +struct Replica(u64); + +impl probe::Service for Replica { + async fn revision(&self, (): ()) -> Result { + Ok(self.0) + } +} + +const MAX_FRAME: usize = 64 * 1024; + +async fn read_frame(stream: &mut TcpStream) -> io::Result { + let len = stream.read_u32().await? as usize; + if len > MAX_FRAME { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "oversized RPC frame", + )); + } + let mut bytes = vec![0; len]; + stream.read_exact(&mut bytes).await?; + Ok(serde_json::from_slice(&bytes)?) +} + +async fn write_frame(stream: &mut TcpStream, value: &impl Serialize) -> io::Result<()> { + let bytes = serde_json::to_vec(value)?; + if bytes.len() > MAX_FRAME { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "oversized RPC frame", + )); + } + stream.write_u32(bytes.len() as u32).await?; + stream.write_all(&bytes).await +} + +struct TcpPeer(SocketAddr); + +impl Transport for TcpPeer { + type Error = io::Error; + + async fn exchange(&self, request: Request) -> io::Result { + let mut stream = TcpStream::connect(self.0).await?; + write_frame(&mut stream, &request).await?; + read_frame(&mut stream).await + } +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let listener = TcpListener::bind(("127.0.0.1", 0)).await?; + let client = probe::Client(TcpPeer(listener.local_addr()?)); + let serve = async { + let (mut stream, _) = listener.accept().await?; + let request = read_frame(&mut stream).await?; + let reply = probe::dispatch(&Replica(42), request).await; + write_frame(&mut stream, &reply).await + }; + let (served, reply) = timeout(Duration::from_secs(5), async { + tokio::join!(serve, client.revision(())) + }) + .await?; + served?; + assert_eq!(reply?, 42); + println!("replica revision = 42"); + Ok(()) +} diff --git a/crates/bedrock-rpc/src/lib.rs b/crates/bedrock-rpc/src/lib.rs new file mode 100644 index 0000000..d482eff --- /dev/null +++ b/crates/bedrock-rpc/src/lib.rs @@ -0,0 +1,126 @@ +//! Compile-time bindings for unary Bedrock service contracts. +use std::{future::Future, time::Duration}; + +use axum::http::StatusCode; +pub use reqwest::header::HeaderMap; + +#[doc(hidden)] +pub use axum; +#[doc(hidden)] +pub use serde_json; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid RPC origin (expected an HTTP(S) origin without a path or credentials)")] + Origin, + #[error("RPC transport error")] + Network(#[from] reqwest::Error), + #[error("RPC peer returned HTTP {0}")] + Status(StatusCode), + #[error("RPC body exceeds the size limit")] + TooLarge, + #[error("invalid RPC JSON")] + Json(#[from] serde_json::Error), +} + +/// Same limit for encoded requests and successful replies (2 MiB). +pub const MAX_BODY: usize = 2 * 1024 * 1024; + +/// Implement to route a call through an application-owned connection. +pub trait Transport: Sync { + fn post( + &self, + path: &'static str, + json: Vec, + ) -> impl Future, Error>> + Send; +} + +/// Reuses pooled connections to a single configured peer. +pub struct HttpTransport { + origin: reqwest::Url, + client: reqwest::Client, +} + +impl HttpTransport { + pub fn new(origin: &str, timeout: Duration, headers: HeaderMap) -> Result { + let origin = reqwest::Url::parse(origin).map_err(|_| Error::Origin)?; + if !matches!(origin.scheme(), "https" | "http") + || origin.host_str().is_none() + || !origin.username().is_empty() + || origin.password().is_some() + || origin.path() != "/" + || origin.query().is_some() + || origin.fragment().is_some() + { + return Err(Error::Origin); + } + let client = reqwest::Client::builder() + .timeout(timeout) + .redirect(reqwest::redirect::Policy::none()) + .default_headers(headers) + .build()?; + Ok(Self { origin, client }) + } +} + +impl Transport for HttpTransport { + async fn post(&self, path: &'static str, json: Vec) -> Result, Error> { + if json.len() > MAX_BODY { + return Err(Error::TooLarge); + } + let mut url = self.origin.clone(); + url.set_path(path); + let mut response = self.client.post(url) + .header(reqwest::header::CONTENT_TYPE, "application/json") + .body(json) + .send() + .await?; + if response.status() != StatusCode::OK { + return Err(Error::Status(response.status())); + } + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + if chunk.len() > MAX_BODY - bytes.len() { + return Err(Error::TooLarge); + } + bytes.extend_from_slice(&chunk); + } + Ok(bytes) + } +} + +/// Declare once inside a contract module. The service prefix and method names +/// are part of the wire protocol. See the crate README for evolution rules. +#[macro_export] +macro_rules! service { + ($prefix:literal { $(fn $method:ident($input:ty) -> $output:ty;)+ }) => { + pub trait Service: Send + Sync + 'static { + $(fn $method(&self, request: $input) -> impl ::std::future::Future< + Output = Result<$output, $crate::axum::http::StatusCode> + > + Send;)+ + } + + pub struct Client(pub T); + + impl Client { + $(pub async fn $method(&self, request: &$input) -> Result<$output, $crate::Error> { + let bytes = $crate::serde_json::to_vec(request)?; + let reply = self.0.post(concat!($prefix, "/", stringify!($method)), bytes).await?; + Ok($crate::serde_json::from_slice(&reply)?) + })+ + } + + pub fn router(service: S) -> $crate::axum::Router { + use $crate::axum::{Json, Router, extract::State, routing::post}; + use ::std::sync::Arc; + + Router::new() + $(.route(concat!($prefix, "/", stringify!($method)), post( + |State(service): State>, Json(request): Json<$input>| async move { + service.$method(request).await.map(Json) + } + )))+ + .with_state(Arc::new(service)) + } + }; +} diff --git a/crates/bedrock-rpc/tests/contract.rs b/crates/bedrock-rpc/tests/contract.rs new file mode 100644 index 0000000..5c3fc1c --- /dev/null +++ b/crates/bedrock-rpc/tests/contract.rs @@ -0,0 +1,65 @@ +use bedrock_rpc::{CallError, Fault, Reply, Request, Transport}; +use serde_json::json; + +mod catalog { + bedrock_rpc::service! { + "bedrock.catalog.v1" { + 3 => lookup(String) -> u64, + 8 => ready(()) -> bool, + } + } +} + +struct Catalog; + +impl catalog::Service for Catalog { + async fn lookup(&self, key: String) -> Result { + if key == "documents" { + Ok(17) + } else { + Err(Fault::Unavailable) + } + } + + async fn ready(&self, (): ()) -> Result { + Ok(true) + } +} + +struct Local; + +impl Transport for Local { + type Error = std::convert::Infallible; + async fn exchange(&self, request: Request) -> Result { + Ok(catalog::dispatch(&Catalog, request).await) + } +} + +#[tokio::test] +async fn typed_calls_and_remote_failures() { + let client = catalog::Client(Local); + assert_eq!(client.lookup("documents".into()).await.unwrap(), 17); + assert!(client.ready(()).await.unwrap()); + assert!(matches!( + client.lookup("missing".into()).await, + Err(CallError::Remote(Fault::Unavailable)) + )); +} + +#[tokio::test] +async fn rejects_incompatible_requests() { + for (service, method, fault) in [ + ("bedrock.catalog.v2", 3, Fault::UnknownService), + (catalog::SERVICE, 7, Fault::UnknownMethod), + (catalog::SERVICE, 3, Fault::InvalidRequest), + ] { + let request = Request { + service: service.into(), + method, + payload: json!(false), + }; + assert!( + matches!(catalog::dispatch(&Catalog, request).await, Reply::Failure(actual) if actual == fault) + ); + } +}