4 Commits

13 changed files with 556 additions and 405 deletions
Generated
+253 -4
View File
@@ -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"
+21 -2
View File
@@ -1,4 +1,16 @@
# Bedrock storage
# Bedrock 集群 RPC 原型归档
`codex/cluster-rpc-archive` 保存 Bedrock 早期的三个 Rust RPC 原型,供以后对照契约和传输实现。原型开发已暂停。Bedrock 的逻辑集群工作在 `codex/cluster-research` 的 `crates/clusters` 内继续。[研究分支 PR #33](https://gitea.entroia.com/Zayden-Jung/Bedrock/pulls/33)
| 原工作分支 | 值得查看的内容 | 完整版本 |
| --- | --- | --- |
| `codex/typed-service-bindings` | 同一份 Rust 声明生成 HTTP 客户端和 Axum 路由。部署状态查询接入管理监听器,集成测试覆盖鉴权和无效请求。归档分支默认展示这套源码。 | [`46b85a9`](https://gitea.entroia.com/Zayden-Jung/Bedrock/src/commit/46b85a9d474cafad1034b1d249c736cc8cfa2ce4) |
| `codex/typed-service-contracts` | 版本化服务名和稳定的方法编号驱动客户端与服务端分派。进程内测试和回环 TCP 示例展示同一契约如何适配不同传输。 | [`7a7ee45`](https://gitea.entroia.com/Zayden-Jung/Bedrock/src/commit/7a7ee457614461382e3a815a78617dd675dcc48e) |
| `codex/cluster-rpc` | 保存整理前的开发现场。HTTP 实现与方法编号版的示例、测试和依赖清单处于混用状态。此版本用于追溯中间改动。 | [`6a81ed9`](https://gitea.entroia.com/Zayden-Jung/Bedrock/src/commit/6a81ed95a177df9c1703009faadc4696e0454855) |
三个链接分别打开各自的源码树。这些提交都在本分支的合并历史中。原型中的 `crates/bedrock-rpc` 记录了当时单独分包的实验;后续实现可参考其中的契约和测试。以下为 HTTP 原型原有的项目说明。
## Bedrock storage
Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `database` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start.
@@ -8,6 +20,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 +36,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
+4
View File
@@ -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"] }
+24 -22
View File
@@ -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<DeploymentStatus, StatusCode> {
Ok(self.status())
}
}
pub fn router(
config: Arc<ResolvedDeployment>,
config_version: Option<String>,
@@ -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::<str>::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<AdminState>) -> Response {
+19
View File
@@ -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<String>,
pub storage_driver: String,
pub read_only: bool,
}
bedrock_rpc::service! {
"/admin/v1/deployment" {
fn status(StatusRequest) -> DeploymentStatus;
}
}
+45
View File
@@ -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();
}
+11
View File
@@ -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
+45
View File
@@ -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。已有字段类型、方法名或语义需要改变时,发布新的版本前缀并在滚动升级期间并行提供两个版本。调用超时后,服务端可能已经执行操作,写入方法需要业务定义幂等语义。
+130
View File
@@ -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))
}
};
}
+1 -4
View File
@@ -16,7 +16,4 @@ pub use organization::{Organization, OrganizationId, OrganizationMembership, Org
pub use rich_text::{Inline, RichText};
pub use tree::{DocumentTree, TreeError};
pub use user::{User, UserId};
pub use workspace::{
Workspace, WorkspaceAccess, WorkspaceAccessError, WorkspaceId, WorkspaceInvitation,
WorkspaceMembership, WorkspaceRole,
};
pub use workspace::{Workspace, WorkspaceId};
-15
View File
@@ -2,7 +2,6 @@ use super::contextualize::Contextualize;
use super::{
id::{IdError, validate_id},
user::UserId,
workspace::{Workspace, WorkspaceAccess, WorkspaceAccessError, WorkspaceId},
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
@@ -43,20 +42,6 @@ pub struct OrganizationMembership {
pub role: OrganizationRole,
}
impl Organization {
pub fn create_workspace(&self, id: WorkspaceId, name: impl Into<String>) -> Workspace {
Workspace::owned_by(id, name, self.id.clone())
}
pub fn set_workspace_access(
&self,
workspace: &mut Workspace,
access: WorkspaceAccess,
) -> Result<(), WorkspaceAccessError> {
workspace.set_organization_access(&self.id, access)
}
}
impl Contextualize for Organization {
fn render_context(&self) -> String {
format!("Organization: {}", self.name)
+3 -184
View File
@@ -1,12 +1,7 @@
use thiserror::Error;
use super::contextualize::Contextualize;
use super::{
Document,
id::{IdError, validate_id},
organization::{OrganizationId, OrganizationMembership},
tree::{DocumentTree, TreeError},
user::UserId,
organization::OrganizationId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
@@ -26,188 +21,12 @@ impl WorkspaceId {
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkspaceRole {
Owner,
Admin,
Editor,
Viewer,
}
/// Controls which roles can be granted to people outside the owning organization.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum WorkspaceAccess {
#[default]
MembersOnly,
ExternalViewers,
ExternalEditors,
}
impl WorkspaceAccess {
fn allows_external(self, role: WorkspaceRole) -> bool {
matches!(
(self, role),
(
Self::ExternalViewers | Self::ExternalEditors,
WorkspaceRole::Viewer
) | (Self::ExternalEditors, WorkspaceRole::Editor)
)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct OrganizationWorkspace {
id: OrganizationId,
access: WorkspaceAccess,
}
/// A workspace contains documents and may be owned by an organization.
/// A workspace belongs to one organization and contains documents.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Workspace {
pub id: WorkspaceId,
pub organization_id: OrganizationId,
pub name: String,
organization: Option<OrganizationWorkspace>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceInvitation {
workspace_id: WorkspaceId,
invitee: UserId,
role: WorkspaceRole,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceMembership {
pub workspace_id: WorkspaceId,
pub user_id: UserId,
pub role: WorkspaceRole,
}
#[derive(Debug, Error, Eq, PartialEq)]
pub enum WorkspaceAccessError {
#[error("the workspace does not belong to this organization")]
OrganizationMismatch,
#[error("the workspace access policy does not allow this role for the invitee")]
RoleNotAllowed,
#[error("the invitation is for a different workspace or user")]
InvitationMismatch,
}
impl Workspace {
pub fn independent(id: WorkspaceId, name: impl Into<String>) -> Self {
Self {
id,
name: name.into(),
organization: None,
}
}
pub(super) fn owned_by(
id: WorkspaceId,
name: impl Into<String>,
organization_id: OrganizationId,
) -> Self {
Self {
id,
name: name.into(),
organization: Some(OrganizationWorkspace {
id: organization_id,
access: WorkspaceAccess::default(),
}),
}
}
pub fn organization_id(&self) -> Option<&OrganizationId> {
self.organization
.as_ref()
.map(|organization| &organization.id)
}
pub fn organization_access(&self) -> Option<WorkspaceAccess> {
self.organization
.as_ref()
.map(|organization| organization.access)
}
pub(super) fn set_organization_access(
&mut self,
organization_id: &OrganizationId,
access: WorkspaceAccess,
) -> Result<(), WorkspaceAccessError> {
let organization = self
.organization
.as_mut()
.filter(|organization| &organization.id == organization_id)
.ok_or(WorkspaceAccessError::OrganizationMismatch)?;
organization.access = access;
Ok(())
}
/// Evaluates the invitee against the current policy. The caller supplies the
/// invitee's current membership in the owning organization, if any.
pub fn invite(
&self,
invitee: UserId,
role: WorkspaceRole,
organization_membership: Option<&OrganizationMembership>,
) -> Result<WorkspaceInvitation, WorkspaceAccessError> {
self.check_access(&invitee, role, organization_membership)?;
Ok(WorkspaceInvitation {
workspace_id: self.id.clone(),
invitee,
role,
})
}
/// Rechecks policy and membership so a pending invitation cannot preserve
/// privileges after either has changed.
pub fn accept_invitation(
&self,
user: &UserId,
invitation: &WorkspaceInvitation,
organization_membership: Option<&OrganizationMembership>,
) -> Result<WorkspaceMembership, WorkspaceAccessError> {
if invitation.workspace_id != self.id || &invitation.invitee != user {
return Err(WorkspaceAccessError::InvitationMismatch);
}
self.check_access(user, invitation.role, organization_membership)?;
Ok(WorkspaceMembership {
workspace_id: self.id.clone(),
user_id: user.clone(),
role: invitation.role,
})
}
/// Assembles an ordered tree of document nodes in this workspace.
pub fn document_tree(
&self,
root: Document,
descendants: impl IntoIterator<Item = Document>,
) -> Result<DocumentTree, TreeError> {
if root.key.workspace != self.id {
return Err(TreeError::WorkspaceMismatch);
}
DocumentTree::new(root, descendants)
}
fn check_access(
&self,
user: &UserId,
role: WorkspaceRole,
membership: Option<&OrganizationMembership>,
) -> Result<(), WorkspaceAccessError> {
let Some(organization) = &self.organization else {
return Ok(());
};
let internal = membership.is_some_and(|membership| {
membership.organization_id == organization.id && &membership.user_id == user
});
if internal || organization.access.allows_external(role) {
Ok(())
} else {
Err(WorkspaceAccessError::RoleNotAllowed)
}
}
}
impl Contextualize for Workspace {
-174
View File
@@ -1,174 +0,0 @@
use documents::{
Document, DocumentContent, DocumentId, DocumentKey, Organization, OrganizationId,
OrganizationMembership, OrganizationRole, TreeError, UserId, Workspace, WorkspaceAccess,
WorkspaceAccessError, WorkspaceId, WorkspaceRole,
};
fn organization(id: &str) -> Organization {
Organization {
id: OrganizationId::new(id).unwrap(),
name: id.into(),
}
}
fn member(organization: &Organization, user: &UserId) -> OrganizationMembership {
OrganizationMembership {
organization_id: organization.id.clone(),
user_id: user.clone(),
role: OrganizationRole::Member,
}
}
fn workspace_id(value: &str) -> WorkspaceId {
WorkspaceId::new(value).unwrap()
}
#[test]
fn organization_controls_the_roles_available_to_external_users() {
use WorkspaceAccess::{ExternalEditors, ExternalViewers, MembersOnly};
use WorkspaceRole::{Admin, Editor, Owner, Viewer};
let organization = organization("org");
let mut workspace = organization.create_workspace(workspace_id("workspace"), "Workspace");
let outside = UserId::new("outside").unwrap();
let inside = UserId::new("inside").unwrap();
let membership = member(&organization, &inside);
assert_eq!(workspace.organization_id(), Some(&organization.id));
assert_eq!(workspace.organization_access(), Some(MembersOnly));
for (policy, allowed) in [
(MembersOnly, &[][..]),
(ExternalViewers, &[Viewer][..]),
(ExternalEditors, &[Viewer, Editor][..]),
] {
organization
.set_workspace_access(&mut workspace, policy)
.unwrap();
for role in [Owner, Admin, Editor, Viewer] {
let invitation = workspace.invite(outside.clone(), role, None);
if allowed.contains(&role) {
let membership = workspace
.accept_invitation(&outside, &invitation.unwrap(), None)
.unwrap();
assert_eq!(membership.user_id, outside);
assert_eq!(membership.workspace_id, workspace.id);
assert_eq!(membership.role, role);
} else {
assert_eq!(invitation, Err(WorkspaceAccessError::RoleNotAllowed));
}
assert!(
workspace
.invite(inside.clone(), role, Some(&membership))
.is_ok()
);
}
}
}
#[test]
fn acceptance_checks_the_invite_target_and_current_policy() {
let owner = organization("owner");
let other = organization("other");
let mut workspace = owner.create_workspace(workspace_id("workspace"), "Workspace");
let independent = Workspace::independent(workspace_id("personal"), "Personal");
let outsider = UserId::new("outside").unwrap();
let insider = UserId::new("inside").unwrap();
let inside_membership = member(&owner, &insider);
let other_membership = member(&other, &outsider);
for membership in [&inside_membership, &other_membership] {
assert_eq!(
workspace.invite(outsider.clone(), WorkspaceRole::Admin, Some(membership)),
Err(WorkspaceAccessError::RoleNotAllowed)
);
}
let invitation = workspace
.invite(
insider.clone(),
WorkspaceRole::Admin,
Some(&inside_membership),
)
.unwrap();
assert_eq!(
workspace.accept_invitation(&insider, &invitation, None),
Err(WorkspaceAccessError::RoleNotAllowed)
);
assert_eq!(
independent.accept_invitation(&insider, &invitation, Some(&inside_membership)),
Err(WorkspaceAccessError::InvitationMismatch)
);
assert_eq!(
workspace.accept_invitation(&outsider, &invitation, None),
Err(WorkspaceAccessError::InvitationMismatch)
);
assert_eq!(independent.organization_id(), None);
assert!(
independent
.invite(outsider.clone(), WorkspaceRole::Editor, None)
.is_ok()
);
assert_eq!(
other.set_workspace_access(&mut workspace, WorkspaceAccess::ExternalEditors),
Err(WorkspaceAccessError::OrganizationMismatch)
);
owner
.set_workspace_access(&mut workspace, WorkspaceAccess::ExternalEditors)
.unwrap();
let external = workspace
.invite(outsider.clone(), WorkspaceRole::Editor, None)
.unwrap();
owner
.set_workspace_access(&mut workspace, WorkspaceAccess::ExternalViewers)
.unwrap();
assert_eq!(
workspace.accept_invitation(&outsider, &external, None),
Err(WorkspaceAccessError::RoleNotAllowed)
);
}
#[test]
fn workspace_contains_nested_documents_of_different_kinds() {
let workspace = Workspace::independent(workspace_id("workspace"), "Workspace");
let key = |id: &str| DocumentKey {
workspace: workspace.id.clone(),
document: DocumentId::new(id).unwrap(),
};
let page = Document::new(
key("page"),
DocumentContent::Page {
title: "Page".into(),
},
);
let mut child_page = Document::new(
key("subpage"),
DocumentContent::Page {
title: "Nested".into(),
},
);
child_page.parent_id = Some(page.key.document.clone());
let mut code = Document::new(
key("code"),
DocumentContent::Code {
language: "rust".into(),
source: "fn main() {}".into(),
},
);
code.parent_id = Some(child_page.key.document.clone());
let tree = workspace
.document_tree(page.clone(), [code, child_page])
.unwrap();
assert_eq!(
tree.nodes()
.map(|(depth, document)| (depth, document.key.document.as_str()))
.collect::<Vec<_>>(),
[(0, "page"), (1, "subpage"), (2, "code")]
);
let other = Workspace::independent(workspace_id("other"), "Other");
assert!(matches!(
other.document_tree(page, []),
Err(TreeError::WorkspaceMismatch)
));
}