From 46b85a9d474cafad1034b1d249c736cc8cfa2ce4 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 2 Dec 2026 21:26:01 +0800 Subject: [PATCH] Generate typed cluster service clients and Axum routes from one contract --- Cargo.lock | 257 +++++++++++++++++++++++++++++- README.md | 9 +- crates/admin_backend/Cargo.toml | 4 + crates/admin_backend/src/lib.rs | 46 +++--- crates/admin_backend/src/rpc.rs | 19 +++ crates/admin_backend/tests/rpc.rs | 45 ++++++ crates/bedrock-rpc/Cargo.toml | 11 ++ crates/bedrock-rpc/README.md | 45 ++++++ crates/bedrock-rpc/src/lib.rs | 130 +++++++++++++++ 9 files changed, 539 insertions(+), 27 deletions(-) create mode 100644 crates/admin_backend/src/rpc.rs create mode 100644 crates/admin_backend/tests/rpc.rs create mode 100644 crates/bedrock-rpc/Cargo.toml create mode 100644 crates/bedrock-rpc/README.md create mode 100644 crates/bedrock-rpc/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index e63f0ac..a6b5b9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,9 +13,11 @@ name = "admin_backend" version = "0.1.0" dependencies = [ "axum", + "bedrock-rpc", "clusters", "serde", "subtle", + "tokio", ] [[package]] @@ -157,12 +159,28 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" 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 = [ + "axum", + "reqwest", + "serde_json", + "thiserror", +] + [[package]] name = "bitflags" version = "2.13.2" @@ -230,6 +248,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.2" @@ -647,8 +671,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", ] [[package]] @@ -802,6 +828,23 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.12", ] [[package]] @@ -810,13 +853,22 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2 0.6.5", "tokio", "tower-service", + "tracing", ] [[package]] @@ -933,6 +985,12 @@ dependencies = [ "hashbrown 0.17.2", ] +[[package]] +name = "ipnet" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" + [[package]] name = "itoa" version = "1.0.19" @@ -1021,6 +1079,12 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "matchit" version = "0.8.4" @@ -1114,7 +1178,7 @@ version = "0.35.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbb9f371618ce723f095c61fbcdc36e8936956d2b62832f9c7648689b338e052" dependencies = [ - "base64", + "base64 0.22.1", "bitflags", "btoi", "byteorder", @@ -1221,7 +1285,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] @@ -1268,7 +1332,7 @@ version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" dependencies = [ - "base64", + "base64 0.22.1", "byteorder", "bytes", "fallible-iterator 0.2.0", @@ -1318,6 +1382,62 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2 0.6.5", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.5", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -1385,6 +1505,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1423,6 +1552,44 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 1.0.12", +] + [[package]] name = "ring" version = "0.17.14" @@ -1451,6 +1618,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustix" version = "1.1.6" @@ -1493,6 +1666,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ + "web-time", "zeroize", ] @@ -1513,6 +1687,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "saturating" version = "0.1.0" @@ -1542,7 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" dependencies = [ "annotate-snippets", - "base64", + "base64 0.22.1", "encoding_rs_io", "granit-parser", "nohash-hasher", @@ -1605,6 +1785,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -1764,6 +1956,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -2003,6 +2198,24 @@ dependencies = [ "tower-service", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -2046,6 +2259,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "twox-hash" version = "2.1.5" @@ -2146,6 +2365,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2191,6 +2419,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.130" @@ -2233,6 +2472,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-roots" version = "0.26.11" diff --git a/README.md b/README.md index e63744f..1fd8410 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,13 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock supports named SQL roles and read replicas. The catalog can describe S3 buckets. Object I/O, workspace routing, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) +## Cluster service calls + +[bedrock-rpc](crates/bedrock-rpc/README.md) generates typed clients, handlers, +and Axum routes from a shared Rust declaration. The first contract reads +deployment status via `POST /admin/v1/deployment/status` with JSON body `{}` +and the admin listener's existing bearer authentication. + ## Web backend Run the Axum service with `cargo run --locked -p backend`. One process owns @@ -17,7 +24,7 @@ separate routers on the business and optional admin listeners. | Listener | Setting and default | Routes | |---|---|---| | Business | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` | -| Admin | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` when enabled | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` | +| Admin | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` when enabled | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status`, `POST /admin/v1/deployment/status` | The business readiness probe checks access to the current deployment revision. Set `BEDROCK_ADMIN_TOKEN` from a private credential source to enable the admin diff --git a/crates/admin_backend/Cargo.toml b/crates/admin_backend/Cargo.toml index 3c48bab..f2b2b46 100644 --- a/crates/admin_backend/Cargo.toml +++ b/crates/admin_backend/Cargo.toml @@ -6,6 +6,10 @@ rust-version.workspace = true [dependencies] axum.workspace = true +bedrock-rpc = { path = "../bedrock-rpc" } clusters.workspace = true serde.workspace = true subtle.workspace = true + +[dev-dependencies] +tokio = { workspace = true, features = ["net"] } 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/admin_backend/tests/rpc.rs b/crates/admin_backend/tests/rpc.rs new file mode 100644 index 0000000..008ed18 --- /dev/null +++ b/crates/admin_backend/tests/rpc.rs @@ -0,0 +1,45 @@ +use std::{sync::Arc, time::Duration}; + +use admin_backend::rpc::{Client, StatusRequest}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use bedrock_rpc::{Error, HttpTransport, Transport}; +use clusters::DeploymentConfig; + +#[tokio::test] +async fn status_rpc_uses_the_admin_listener_and_its_authentication() { + let config = DeploymentConfig::default().resolve().unwrap(); + let app = + admin_backend::router(Arc::new(config), Some("release-7".into()), "test".into()).unwrap(); + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let peer = |headers| HttpTransport::new(&origin, Duration::from_secs(3), headers).unwrap(); + let anonymous = Client(peer(HeaderMap::new())); + assert!(matches!( + anonymous.status(&StatusRequest {}).await, + Err(Error::Status(StatusCode::UNAUTHORIZED)) + )); + + let mut headers = HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer test"), + ); + let client = Client(peer(headers)); + let status = client.status(&StatusRequest {}).await.unwrap(); + assert_eq!(status.config_version.as_deref(), Some("release-7")); + assert_eq!(status.deployment, "default"); + + let malformed = client + .0 + .post("/admin/v1/deployment/status", b"{".to_vec()) + .await; + assert!(matches!( + malformed, + Err(Error::Status(StatusCode::BAD_REQUEST)) + )); + server.abort(); +} diff --git a/crates/bedrock-rpc/Cargo.toml b/crates/bedrock-rpc/Cargo.toml new file mode 100644 index 0000000..5a059b5 --- /dev/null +++ b/crates/bedrock-rpc/Cargo.toml @@ -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 diff --git a/crates/bedrock-rpc/README.md b/crates/bedrock-rpc/README.md new file mode 100644 index 0000000..9326697 --- /dev/null +++ b/crates/bedrock-rpc/README.md @@ -0,0 +1,45 @@ +# Bedrock RPC + +每个服务用一个 Rust 模块发布契约。编译时,`service!` 将前缀、方法名、请求类型和响应类型展开成三个入口。调用方使用 `Client`,服务实现 `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 { + 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, 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。已有字段类型、方法名或语义需要改变时,发布新的版本前缀并在滚动升级期间并行提供两个版本。调用超时后,服务端可能已经执行操作,写入方法需要业务定义幂等语义。 diff --git a/crates/bedrock-rpc/src/lib.rs b/crates/bedrock-rpc/src/lib.rs new file mode 100644 index 0000000..da81c0e --- /dev/null +++ b/crates/bedrock-rpc/src/lib.rs @@ -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), + #[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)) + } + }; +}