Generate typed cluster service clients and Axum routes from one contract
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "bedrock-rpc"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
@@ -0,0 +1,45 @@
|
||||
# Bedrock RPC
|
||||
|
||||
每个服务用一个 Rust 模块发布契约。编译时,`service!` 将前缀、方法名、请求类型和响应类型展开成三个入口。调用方使用 `Client<T>`,服务实现 `Service`,启动代码将 `router(service)` 合入 Axum。Rust 会检查调用参数、返回类型和处理方法是否齐全。跨版本节点的兼容性仍取决于线上的 JSON 格式和路径。
|
||||
|
||||
```rust
|
||||
mod replica {
|
||||
bedrock_rpc::service! {
|
||||
"/replica/v1" {
|
||||
fn revision(()) -> u64;
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Replica { applied_revision: u64 }
|
||||
impl replica::Service for Replica {
|
||||
async fn revision(&self, _: ()) -> Result<u64, bedrock_rpc::axum::http::StatusCode> {
|
||||
Ok(self.applied_revision)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
此方法通过 POST /replica/v1/revision 发送 JSON null。成功时返回 HTTP 200 和一个 JSON 整数。handler 可返回 HTTP 错误状态;调用方可以分别处理远端状态、网络失败和 JSON 解码失败。
|
||||
|
||||
## 目标集群与传输
|
||||
|
||||
发送方为目标创建一个可复用的 HttpTransport,传入 origin、每次请求的超时和请求头。集群内 origin 可指向服务 DNS,跨集群时指向已配置的 HTTPS 网关。网关需将契约路径转发至目标服务。服务发现、凭据分发和网关策略由部署方负责。发送凭据时应使用 HTTPS 或由服务网格保护的连接。自有传输可以实现 Transport::post,按路径传送 JSON 字节并返回响应。
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
use admin_backend::rpc::{Client, StatusRequest};
|
||||
use bedrock_rpc::{HeaderMap, HttpTransport};
|
||||
|
||||
async fn config_version(origin: &str, headers: HeaderMap)
|
||||
-> Result<Option<String>, bedrock_rpc::Error>
|
||||
{
|
||||
let peer = HttpTransport::new(origin, Duration::from_secs(3), headers)?;
|
||||
let status = Client(peer).status(&StatusRequest {}).await?;
|
||||
Ok(status.config_version)
|
||||
}
|
||||
```
|
||||
|
||||
Bedrock 已在管理监听器挂载 [deployment 契约](../admin_backend/src/rpc.rs)。调用方通过 headers 传入现有 Bearer 令牌。请求使用与 GET /admin/v1/status 相同的状态来源及鉴权中间件。
|
||||
|
||||
## 协议演进
|
||||
|
||||
首版支持一次请求返回一次响应。服务路径和方法名是协议标识,双方共享可由 Serde 编解码的 DTO。兼容扩展可添加新方法或带默认值的可选字段;旧节点收到未知路径返回 404。已有字段类型、方法名或语义需要改变时,发布新的版本前缀并在滚动升级期间并行提供两个版本。调用超时后,服务端可能已经执行操作,写入方法需要业务定义幂等语义。
|
||||
@@ -0,0 +1,130 @@
|
||||
//! 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("application transport failed")]
|
||||
Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
|
||||
#[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<u8>,
|
||||
) -> impl Future<Output = Result<Vec<u8>, 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<Self, Error> {
|
||||
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<u8>) -> Result<Vec<u8>, 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<T>(pub T);
|
||||
|
||||
impl<T: $crate::Transport> Client<T> {
|
||||
$(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<S: Service>(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<Arc<S>>, Json(request): Json<$input>| async move {
|
||||
service.$method(request).await.map(Json)
|
||||
}
|
||||
)))+
|
||||
.with_state(Arc::new(service))
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user