Hiver Framework
A production-grade, high-availability web framework written in Rust.
Hiver 框架
用 Rust 编写的生产级、高可用 Web 框架。
Why Hiver? / 为什么选择 Hiver?
🚀 Custom io-uring RuntimeCustom async runtime built from scratch with io-uring (Linux), epoll, and kqueue (macOS). Thread-per-core architecture for linear scalability. 自定义 io-uring 运行时从零构建的自定义异步运行时,支持 io-uring、epoll 和 kqueue。Thread-per-core 架构实现线性扩展。 |
🏗️ Spring-like Annotations40+ procedural macro annotations inspired by Spring Boot: 类 Spring 注解40+ 过程宏注解,灵感来自 Spring Boot: |
🛡️ Resilience Built-inCircuit breakers, rate limiters, retry logic, and service discovery — production patterns out of the box. 内置弹性模式熔断器、限流器、重试逻辑和服务发现 — 开箱即用的生产级模式。 |
🌐 Web3 NativeFirst-class Ethereum support via Alloy: wallet management, smart contracts, RPC client, and chain abstraction. Web3 原生支持通过 Alloy 提供一流的以太坊支持:钱包管理、智能合约、RPC 客户端和链抽象。 |
📊 Full ObservabilityDistributed tracing (OpenTelemetry), metrics (Prometheus), and structured logging — zero-config integration. 完整可观测性分布式追踪(OpenTelemetry)、指标(Prometheus)和结构化日志 — 零配置集成。 |
🗄️ Data Layer (In Progress)Spring Data-like abstractions: Repository traits, ORM, ActiveRecord, QueryBuilder, and multi-database support. 数据层(开发中)类 Spring Data 抽象:Repository trait、ORM、ActiveRecord、QueryBuilder 和多数据库支持。 |
Quick Start / 快速开始
# Cargo.toml
[dependencies]
hiver-starter = "0.1"
use hiver_starter::HiverApp;
use hiver_router::Router;
#[hiver::handler]
async fn hello() -> &'static str {
"Hello, Hiver! / 你好,Hiver!"
}
fn main() -> std::io::Result<()> {
HiverApp::new()
.with_router(Router::new()
.get("/", hello)
.get("/users/:id", get_user)
.post("/users", create_user)
)
.run()
}
Performance / 性能
| Metric | Target | Status |
|---|---|---|
| Simple GET QPS | 1M+ | ✅ Achieved |
| P99 Latency (no middleware) | < 1ms | ✅ Achieved |
| Base Memory | < 10MB | ✅ Achieved |
| Startup Time | < 100ms | ✅ Achieved |
Architecture / 架构
┌─────────────────────────────────────────────┐
│ Application Layer │
├──────────┬──────────┬──────────┬────────────┤
│ HTTP │ Resilience│Observab. │ Web3 │
│ Router │ & HA │ Tracing │ Ethereum │
├──────────┴──────────┴──────────┴────────────┤
│ Core Framework (62 crates) │
├──────────┬──────────┬──────────┬────────────┤
│ Handlers │Extractors│Middleware│ Data │
├──────────┴──────────┴──────────┴────────────┤
│ Custom Async Runtime │
├──────────┬──────────┬──────────┬────────────┤
│ io-uring │ Thread- │ Timer │ MPSC │
│ Driver │per-core │ Wheel │ Channels │
└──────────┴──────────┴──────────┴────────────┘
10 domains, 62 crates — full Spring Boot feature parity in Rust.
Project Status / 项目状态
| Phase | Description | Status |
|---|---|---|
| 0 | Foundation (CI/CD, docs) | ✅ Complete |
| 1 | Runtime Core (io-uring, scheduler) | ✅ Complete |
| 2 | HTTP Core (server, router, extractors) | ✅ Complete |
| 3 | Middleware & Extensions | ✅ Complete |
| 4 | Resilience (circuit breaker, retry) | ✅ Complete |
| 5 | Observability (tracing, metrics) | ✅ Complete |
| 6 | Web3 Support (Ethereum, wallets) | ✅ Complete |
| 7 | Production Ready (optimization, security) | ✅ Complete |
| 8 | Data Layer (ORM, migrations) | 🔄 In Progress |
Resources / 资源
| Resource | Link |
|---|---|
| 📦 Crates.io | hiver-framework |
| 📖 API Docs | docs.rs/hiver |
| 💻 GitHub | ViewWay/hiver |
| 📄 Design Spec | design-spec.md |
| 🗺️ Implementation Plan | implementation-plan.md |
Spring Boot Equivalents / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
@RestController | #[handler] | HTTP handler |
@GetMapping | #[get("/path")] | GET endpoint |
@Autowired | #[inject] | DI injection |
@Repository | #[derive(Repository)] | Data repository |
@ConfigurationProperties | #[derive(PropertiesConfig)] | Config binding |
SpringApplication.run() | HiverApp::new().run() | App bootstrap |
@SpringBootApplication | hiver-starter | Auto-config |
| Resilience4j | hiver-resilience | Circuit breaker |
| Spring Security | hiver-security | Auth & security |
| Spring Data JPA | hiver-data-orm | ORM abstraction |
| Spring WebFlux | hiver-http | HTTP server |
Get Started → Installation
Introduction
简介
What is Hiver? / 什么是 Hiver?
Hiver is a production-grade, high-availability web framework written in Rust with a custom async runtime. It provides a full Spring Boot-equivalent feature set spanning 62 crates across 10 functional domains — from runtime and web layer through data, security, messaging, cloud, AI, and enterprise patterns.
Hiver 是一个用 Rust 编写的生产级、高可用 Web 框架,具有自定义异步运行时。它提供了完整的 Spring Boot 等价功能集,横跨 62 个 crate、10 个功能领域——从运行时和 Web 层到数据、安全、消息、云、AI 和企业级模式。
Design Philosophy / 设计理念
Performance First / 性能优先
- Thread-per-core architecture: No work stealing overhead / Thread-per-core 架构:无工作窃取开销
- io-uring based I/O: Zero-copy operations where possible / 基于 io-uring 的 I/O:尽可能零拷贝操作
- Ownership-based buffers: Safe buffer management / 基于所有权的缓冲区:安全的缓冲区管理
- 70% fewer syscalls vs epoll with io-uring / 使用 io-uring 比 epoll 减少 70% 系统调用
Developer Experience / 开发者体验
- Spring-like Annotations:
#[controller],#[service],#[repository],#[autowired],#[transactional], and 40+ more / 类 Spring 注解:#[controller]、#[service]、#[repository]、#[autowired]、#[transactional]等 40+ 注解 - Ergonomic API: Intuitive handlers and extractors / 符合人体工学的 API:直观的 handlers 和 extractors
- Bilingual Documentation: All public APIs documented in English and Chinese / 双语文档:所有公共 API 都有英文和中文文档
- Lombok-style macros:
#[derive(Getter)],#[derive(Data)],#[derive(Builder)]/ Lombok 风格宏:#[derive(Getter)]、#[derive(Data)]、#[derive(Builder)]
Production Ready / 生产就绪
- Data Layer: R2DBC, ORM (ActiveRecord), Redis, MongoDB, Flyway migrations / 数据层:R2DBC、ORM (ActiveRecord)、Redis、MongoDB、Flyway 迁移
- Resilience Patterns: Circuit breakers, retries, rate limiting / 弹性模式:熔断器、重试、限流
- Observability: Distributed tracing, Micrometer metrics / 可观测性:分布式追踪、Micrometer 指标
- Security: JWT, OAuth2 Authorization Server, RBAC, CSRF / 安全:JWT、OAuth2 授权服务器、RBAC、CSRF
- Web3 Native: Built-in blockchain support (ERC20/ERC721) / 原生 Web3:内置区块链支持 (ERC20/ERC721)
- AI Integration: OpenAI, Anthropic, Ollama; vector store; agent framework / AI 集成:OpenAI、Anthropic、Ollama;向量存储;代理框架
Architecture Overview / 架构概览
62 crates across 10 functional domains:
hiver-starter (Spring Boot auto-configuration)
│
├── Web: HTTP server, router, extractors, middleware, response, HATEOAS, OpenAPI
├── Data: Commons, RDBC, ORM (ActiveRecord), Redis, MongoDB, Flyway
├── Security: Authentication, JWT, OAuth2, RBAC, session management
├── AOP: Aspects, transactions, expression language (SpEL)
├── Messaging: Events, Kafka, AMQP/RabbitMQ, Integration (EIP), STOMP
├── Infra: Runtime (io-uring), core IoC, macros, Lombok, config
├── Cloud: Service discovery, AI, agent, Web3, Vault, LDAP, gRPC
├── Resilience: Circuit breaker, retry, observability, actuator
├── Enterprise: Batch, state machine, modular monolith, scheduling, SOAP
└── Tooling: Test containers, shell REPL, validation, benchmarks
Performance / 性能
| Metric / 指标 | Result / 结果 |
|---|---|
| HTTP Parsing (GET) | ~170 ns |
| Throughput | 6.8 GiB/s |
| Spawn latency | < 1 μs |
| Channel throughput | 10M+ msg/s |
Comparison with Other Frameworks / 与其他框架的比较
| Feature / 特性 | Hiver | Tokio-based (Axum) | Go (Gin) | Java (Spring Boot) |
|---|---|---|---|---|
| Custom Runtime | ✅ io-uring | ❌ Tokio | N/A | N/A |
| Thread-per-Core | ✅ Yes | Optional | No | No |
| Spring Annotations | ✅ 40+ | No | No | ✅ Native |
| Data Layer (ORM/R2DBC) | ✅ Yes | Via crates | Via libs | ✅ Spring Data |
| Web3 Native | ✅ Yes | Partial | No | Partial |
| AI Agent Framework | ✅ Yes | Via crates | No | Spring AI |
| Zero-Copy I/O | ✅ Yes | Partial | No | No |
| Startup Time | ~100ms | ~200ms | ~50ms | 2-5s |
| Memory (idle) | ~10MB | ~20MB | ~15MB | ~200MB |
Project Status / 项目状态
| Phase | Status | Description |
|---|---|---|
| Phase 0-7 | ✅ Complete | Runtime, HTTP, Router, Middleware, Resilience, Observability, Web3, Production |
| Phase 8 | 🔄 In Progress | Data Layer (8.1–8.3 core complete, structural refactoring ongoing) |
← Previous / 上一页 | Next / 下一页 →
Installation
安装
Requirements / 系统要求
Rust Toolchain / Rust 工具链
Hiver requires Rust 1.93 or later. Hiver 需要 Rust 1.93 或更高版本。
# Install Rust / 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Verify installation / 验证安装
rustc --version
cargo --version
Platform Support / 平台支持
| Platform / 平台 | Driver / 驱动 | Status / 状态 |
|---|---|---|
| Linux (5.1+) | io-uring | ✅ Fully Supported / 完全支持 |
| Linux (older) | epoll | ✅ Fully Supported / 完全支持 |
| macOS | kqueue | ✅ Fully Supported / 完全支持 |
| FreeBSD | kqueue | ✅ Fully Supported / 完全支持 |
| Windows | IOCP | ⚠️ Not Yet Supported / 暂不支持 |
Linux: io-uring Requirements / Linux: io-uring 要求
For best performance on Linux, ensure you have kernel 5.1+ with io-uring support: 为在 Linux 上获得最佳性能,请确保内核 5.1+ 并支持 io-uring:
# Check kernel version / 检查内核版本
uname -r
# For Ubuntu/Debian, install liburing-dev (optional)
# 对于 Ubuntu/Debian,安装 liburing-dev(可选)
sudo apt-get install liburing-dev
Adding Hiver to Your Project / 将 Hiver 添加到项目
Using Individual Crates / 使用单独的 Crate
Hiver is modular — add only what you need: Hiver 是模块化的 — 只添加你需要的:
[dependencies]
hiver-runtime = "0.1.0-alpha"
hiver-http = "0.1.0-alpha"
hiver-router = "0.1.0-alpha"
hiver-middleware = "0.1.0-alpha"
Or use cargo-add: 或使用 cargo-add:
cargo add hiver-runtime hiver-http hiver-router
From Git Repository / 从 Git 仓库安装
To use the latest development version: 使用最新的开发版本:
[dependencies]
hiver-runtime = { git = "https://github.com/ViewWay/hiver", package = "hiver-runtime" }
Verifying Installation / 验证安装
Create a simple test project: 创建一个简单的测试项目:
cargo new hello-hiver
cd hello-hiver
Edit Cargo.toml:
编辑 Cargo.toml:
[dependencies]
hiver-runtime = "0.1.0-alpha"
Edit src/main.rs:
编辑 src/main.rs:
use hiver_runtime::Runtime;
fn main() -> std::io::Result<()> {
let runtime = Runtime::new()?;
runtime.block_on(async {
println!("Hiver is working!");
println!("Hiver 运行正常!");
});
Ok(())
}
cargo run
If you see the output, installation is successful! 如果你看到输出,说明安装成功!
Building from Source / 从源码构建
# Clone the repository / 克隆仓库
git clone https://github.com/ViewWay/hiver.git
cd hiver
# Build all crates / 构建所有 crate
cargo build --workspace
# Build with optimizations / 优化构建
cargo build --workspace --release
# Run tests / 运行测试
cargo test --workspace
IDE Support / IDE 支持
Hiver works with any Rust IDE. Recommended extensions: Hiver 可与任何 Rust IDE 配合使用。推荐扩展:
- rust-analyzer: Language server for Rust
- Even Better TOML: TOML file support
- crates: Cargo.tomL dependency management
Troubleshooting / 故障排除
io-uring Not Available / io-uring 不可用
On Linux systems without io-uring support (kernel < 5.1), Hiver will automatically fall back to epoll. This is transparent and requires no configuration changes.
在没有 io-uring 支持的 Linux 系统上(内核 < 5.1),Hiver 会自动回退到 epoll。这是透明的,不需要配置更改。
Compilation Errors / 编译错误
-
Check Rust version: Ensure you’re using Rust 1.93+ 检查 Rust 版本:确保你使用的是 Rust 1.93+
-
Update dependencies: Run
cargo update更新依赖:运行cargo update -
Clean build: Run
cargo clean && cargo build清理构建:运行cargo clean && cargo build
Windows / Windows
Windows support is still in development. Use WSL2 for now. Windows 支持仍在开发中。目前请使用 WSL2。
← Previous / 上一页 | Next / 下一页 →
Quick Start
快速开始
This guide will help you create your first Hiver application in under 5 minutes. 本指南将帮助您在 5 分钟内创建第一个 Hiver 应用。
Create a New Project / 创建新项目
cargo new my-hiver-app
cd my-hiver-app
Add Dependencies / 添加依赖
Edit your Cargo.toml:
编辑您的 Cargo.toml:
[package]
name = "my-hiver-app"
version = "0.1.0"
edition = "2021"
[dependencies]
hiver-runtime = "0.1.0-alpha"
hiver-http = "0.1.0-alpha"
hiver-router = "0.1.0-alpha"
tracing = "0.1"
tracing-subscriber = "0.3"
Hello World Server / Hello World 服务器
Replace src/main.rs with:
用以下内容替换 src/main.rs:
use hiver_http::{Body, Response, Server, StatusCode};
use hiver_runtime::task::block_on;
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Initialize logging / 初始化日志
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();
tracing::info!("Starting server on http://127.0.0.1:8080");
// Run the server / 运行服务器
block_on(async {
Server::bind("127.0.0.1:8080")
.run(handle_request)
.await
})
}
async fn handle_request(req: hiver_http::Request) -> Result<Response, hiver_http::Error> {
let path = req.path();
match path {
"/" => Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", "text/plain")
.body(Body::from("Hello, Hiver!"))
.unwrap()),
"/health" => Ok(Response::builder()
.status(StatusCode::OK)
.body(Body::from("OK"))
.unwrap()),
_ => Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not Found"))
.unwrap()),
}
}
Run the Server / 运行服务器
cargo run
Test the Server / 测试服务器
# Test the root endpoint / 测试根端点
curl http://localhost:8080/
# Output: Hello, Hiver!
# Test the health endpoint / 测试健康端点
curl http://localhost:8080/health
# Output: OK
# Test 404 / 测试 404
curl http://localhost:8080/unknown
# Output: Not Found
Using the Router / 使用路由器
For more complex routing, use hiver-router:
对于更复杂的路由,使用 hiver-router:
use hiver_http::{Body, Response, StatusCode};
use hiver_router::{Router, Path};
use hiver_runtime::task::block_on;
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
tracing_subscriber::fmt::init();
// Create router with routes / 创建带路由的路由器
let router = Router::new()
.get("/", index)
.get("/users/:id", get_user)
.post("/users", create_user);
tracing::info!("Starting server on http://127.0.0.1:8080");
block_on(async {
// Start server with router / 使用路由器启动服务器
hiver_http::Server::bind("127.0.0.1:8080")
.run(move |req| {
let router = router.clone();
async move { router.handle(req).await }
})
.await
})
}
async fn index(_req: hiver_http::Request) -> Response {
Response::builder()
.status(StatusCode::OK)
.body(Body::from("Welcome to Hiver!"))
.unwrap()
}
async fn get_user(req: hiver_http::Request) -> Response {
// Extract path parameter / 提取路径参数
let id = req.path_var("id").unwrap_or("unknown");
Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Body::from(format!(r#"{{"id": "{}"}}"#, id)))
.unwrap()
}
async fn create_user(_req: hiver_http::Request) -> Response {
Response::builder()
.status(StatusCode::CREATED)
.body(Body::from(r#"{"status": "created"}"#))
.unwrap()
}
JSON Response Example / JSON 响应示例
#![allow(unused)]
fn main() {
use hiver_http::{Body, Response, StatusCode};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
email: String,
}
async fn get_user_json(_req: hiver_http::Request) -> Response {
let user = User {
id: 1,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
};
// Serialize to JSON / 序列化为 JSON
let json = serde_json::to_string(&user).unwrap();
Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Body::from(json))
.unwrap()
}
}
Using Async Tasks / 使用异步任务
#![allow(unused)]
fn main() {
use hiver_runtime::{spawn, sleep, Duration};
async fn background_task() {
// Spawn a background task / 生成后台任务
let handle = spawn(async {
sleep(Duration::from_secs(1)).await;
println!("Background task completed!");
42
});
// Continue with other work / 继续其他工作
println!("Doing other work...");
// Wait for result when needed / 需要时等待结果
let result = handle.await.unwrap();
println!("Task returned: {}", result);
}
}
Using Channels / 使用通道
#![allow(unused)]
fn main() {
use hiver_runtime::channel::bounded;
async fn channel_example() {
let (tx, rx) = bounded::<String>(10);
// Producer task / 生产者任务
spawn(async move {
for i in 0..5 {
tx.send(format!("Message {}", i)).await.unwrap();
}
});
// Consumer / 消费者
while let Ok(msg) = rx.recv().await {
println!("Received: {}", msg);
}
}
}
Next Steps / 下一步
- Runtime Details - Learn about the async runtime
- HTTP Server - Deep dive into HTTP handling
- Router - Advanced routing patterns
- Middleware - Request/response processing
← Previous / 上一页 | Next / 下一页 →
Hiver Tutorial / Hiver教程
This tutorial will guide you through building a complete REST API application with Hiver.
本教程将指导您使用Hiver构建完整的REST API应用程序。
Table of Contents / 目录
- Project Setup / 项目初始化
- Hello World / 你好世界
- Routing / 路由
- Request Handling / 请求处理
- Middleware / 中间件
- Error Handling / 错误处理
- Database Integration / 数据库集成
- Testing / 测试
1. Project Setup / 项目初始化
Create New Project / 创建新项目
# Create new Rust project / 创建新的Rust项目
cargo new my-api --bin
cd my-api
# Add Hiver dependencies / 添加Hiver依赖
cargo add hiver-runtime hiver-http hiver-router hiver-extractors
cargo add hiver-runtime
Update Cargo.toml / 更新Cargo.toml
[dependencies]
hiver-runtime = "0.1"
hiver-http = "0.1"
hiver-router = "0.1"
hiver-extractors = "0.1"
hiver-runtime = "0.1.0-alpha"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
2. Hello World / 你好世界
Minimal Server / 最小服务器
use hiver_http::Server;
use hiver_router::Router;
fn main() -> std::io::Result<()> {
let mut runtime = hiver_runtime::Runtime::new()?;
runtime.block_on(async {
let app = Router::new()
.get("/", || async { "Hello, Hiver!" });
Server::bind("127.0.0.1:8080")
.run(app)
.await?;
Ok(())
})
}
Run the Server / 运行服务器
cargo run
curl http://localhost:8080/
# Hello, Hiver!
3. Routing / 路由
Path Parameters / 路径参数
#![allow(unused)]
fn main() {
use hiver_http::{Request, Response, StatusCode};
use hiver_router::{Router, Params};
use hiver_extractors::Path;
async fn get_user(Path(id): Path<String>) -> Response {
Response::builder()
.status(StatusCode::OK)
.body(format!("User ID: {}", id).into())
.unwrap()
}
let app = Router::new()
.get("/users/:id", get_user);
}
Multiple Methods / 多种方法
#![allow(unused)]
fn main() {
let app = Router::new()
.get("/users", list_users)
.post("/users", create_user)
.get("/users/:id", get_user)
.put("/users/:id", update_user)
.delete("/users/:id", delete_user);
}
Nested Routes / 嵌套路由
#![allow(unused)]
fn main() {
let app = Router::new()
// Note: Router::nest() not yet implemented
// Planned API: .nest("/api/v1", Router::new()
// .get("/users", list_users)
// .post("/users", create_user)
// .get("/posts", list_posts)
// );
.get("/api/v1/users", list_users)
.post("/api/v1/users", create_user)
.get("/api/v1/posts", list_posts);
}
4. Request Handling / 请求处理
JSON Body / JSON请求体
#![allow(unused)]
fn main() {
use serde::Deserialize;
use hiver_extractors::Json;
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
async fn create_user(Json(payload): Json<CreateUserRequest>) -> Response {
Response::builder()
.status(StatusCode::CREATED)
.body(format!("Created user: {}", payload.name).into())
.unwrap()
}
}
Query Parameters / 查询参数
#![allow(unused)]
fn main() {
use hiver_extractors::Query;
use std::collections::HashMap;
async fn search_users(Query(params): Query<HashMap<String, String>>) -> Response {
let query = params.get("q").unwrap_or(&String::new());
Response::builder()
.body(format!("Searching for: {}", query).into())
.unwrap()
}
}
Headers / 请求头
#![allow(unused)]
fn main() {
use hiver_extractors::Header;
async fn get_auth_user(Header(authorization): Header<String>) -> Response {
// Validate token / 验证令牌
if authorization.starts_with("Bearer ") {
Response::new("Authorized".into())
} else {
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body("Unauthorized".into())
.unwrap()
}
}
}
5. Middleware / 中间件
Logging Middleware / 日志中间件
#![allow(unused)]
fn main() {
use hiver_middleware::Middleware;
use hiver_http::Request;
use std::sync::Arc;
struct Logger;
impl Middleware for Logger {
fn handle(
&self,
req: Request,
next: hiver_middleware::Next,
) -> hiver_middleware::BoxFuture<'static, Result<Response, hiver_http::Error>> {
println!("{} {}", req.method(), req.uri());
next.run(req)
}
}
// Applying middleware / 应用中间件
let app = Router::new()
.middleware(std::sync::Arc::new(Logger))
.get("/", handler);
}
CORS Middleware / CORS中间件
#![allow(unused)]
fn main() {
use hiver_middleware::Cors;
let app = Router::new()
.middleware(std::sync::Arc::new(
Cors::new()
.allow_origin("*")
.allow_methods(["GET", "POST", "PUT", "DELETE"])
))
.get("/", handler);
}
6. Error Handling / 错误处理
Custom Error Type / 自定义错误类型
#![allow(unused)]
fn main() {
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("User not found")]
UserNotFound,
#[error("Database error: {0}")]
DatabaseError(#[from] sqlx::Error),
#[error("Invalid input: {0}")]
InvalidInput(String),
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
Self::UserNotFound => StatusCode::NOT_FOUND,
Self::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
Self::InvalidInput(_) => StatusCode::BAD_REQUEST,
}
}
}
}
Error Handler / 错误处理器
#![allow(unused)]
fn main() {
async fn handle_error(err: AppError) -> Response {
Response::builder()
.status(err.status_code())
.body(format!(r#"{{"error":"{}"}}"#, err.to_string()).into())
.unwrap()
}
}
7. Database Integration / 数据库集成
Using SQLx / 使用SQLx
cargo add sqlx --features postgres,runtime-tokio
use sqlx::PgPool;
use std::sync::Arc;
// Stateful handlers receive (Request, Arc<S>) / 有状态处理器接收 (Request, Arc<S>)
async fn list_users(
req: Request,
state: Arc<PgPool>,
) -> Result<Json<Vec<User>>, AppError> {
let users = sqlx::query_as::<_, User>("SELECT * FROM users")
.fetch_all(&*state)
.await?;
Ok(Json(users))
}
fn main() -> std::io::Result<()> {
let mut runtime = hiver_runtime::Runtime::new()?;
runtime.block_on(async {
let pool = PgPool::connect("postgres://localhost/mydb").await?;
let app = Router::new()
.get("/users", list_users)
.with_state(pool);
Server::bind("127.0.0.1:8080")
.run(app)
.await?;
Ok(())
})
}
8. Testing / 测试
Unit Test / 单元测试
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
use super::*;
use hiver_http::Request;
#[test]
fn test_hello_world() -> std::io::Result<()> {
let runtime = hiver_runtime::Runtime::new()?;
runtime.block_on(async {
let req = Request::builder()
.uri("/")
.body(())
.unwrap();
let response = hello_world(req).await;
assert_eq!(response.status(), StatusCode::OK);
Ok(())
})
}
}
}
Integration Test / 集成测试
#![allow(unused)]
fn main() {
// tests/api_test.rs
use hiver_http::Server;
use hiver_router::Router;
#[test]
fn test_api_endpoint() -> std::io::Result<()> {
let runtime = hiver_runtime::Runtime::new()?;
runtime.block_on(async {
let app = Router::new()
.get("/api/health", || async { {"status": "ok"} });
let server = Server::bind("127.0.0.1:0")
.run(app)
.await?;
let addr = server.addr();
let url = format!("http://{}/api/health", addr);
let response = reqwest::get(&url).await.unwrap();
assert_eq!(response.status(), 200);
Ok(())
})
}
}
Complete Example / 完整示例
use hiver_http::{Server, Response, StatusCode};
use hiver_router::{Router, Params};
use hiver_extractors::{Json, Path, Query};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: String,
}
#[derive(Debug, Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
// In-memory database / 内存数据库
async fn list_users() -> Json<Vec<User>> {
Json(vec![
User { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string() },
User { id: 2, name: "Bob".to_string(), email: "bob@example.com".to_string() },
])
}
async fn get_user(Path(id): Path<String>) -> Result<Json<User>, StatusCode> {
match id.as_str() {
"1" => Ok(Json(User { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string() })),
"2" => Ok(Json(User { id: 2, name: "Bob".to_string(), email: "bob@example.com".to_string() })),
_ => Err(StatusCode::NOT_FOUND),
}
}
async fn create_user(Json(payload): Json<CreateUserRequest>) -> Response {
Response::builder()
.status(StatusCode::CREATED)
.body(format!("Created user: {}", payload.name).into())
.unwrap()
}
async fn health() -> &'static str {
"OK"
}
fn main() -> std::io::Result<()> {
let mut runtime = hiver_runtime::Runtime::new()?;
runtime.block_on(async {
let app = Router::new()
.get("/health", health)
.get("/users", list_users)
.post("/users", create_user)
.get("/users/:id", get_user);
println!("Starting server on http://127.0.0.1:8080");
Server::bind("127.0.0.1:8080")
.run(app)
.await?;
Ok(())
})
}
Next Steps / 下一步
- Explore Middleware for advanced request processing
- Learn about Resilience patterns
- Check Observability for monitoring
- See Examples for more
← Previous / 上一页 | Next / 下一页 →
Runtime / 运行时
Status: Phase 1 Complete ✅
状态: 第1阶段已完成 ✅
Overview / 概述
The Hiver runtime (hiver-runtime) is a high-performance async runtime built from scratch, designed specifically for web server workloads. Unlike Tokio-based frameworks, Hiver uses a custom runtime optimized for maximum throughput and minimal latency.
Hiver 运行时(hiver-runtime)是一个从零构建的高性能异步运行时,专为 Web 服务器工作负载设计。与基于 Tokio 的框架不同,Hiver 使用自定义运行时以实现最大吞吐量和最低延迟。
Key Design Principles / 核心设计原则
┌─────────────────────────────────────────────────────────────┐
│ Hiver Runtime │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Task │ │ Timer │ │ Channel │ │
│ │ Scheduler │ │ Wheel │ │ (MPSC) │ │
│ └──────┬──────┘ └──────┬──────┘ └─────────────┘ │
│ │ │ │
│ ┌──────┴────────────────┴──────┐ │
│ │ I/O Driver │ │
│ │ io-uring / epoll / kqueue │ │
│ └──────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Why custom runtime? / 为什么自定义运行时?
- io-uring first - Linux 5.1+ offers 70% fewer syscalls vs epoll
- Thread-per-core - Better cache locality, no lock contention
- Optimized for web - Tailored for HTTP request/response patterns
- Zero overhead - Only pay for what you use
io-uring优先 - Linux 5.1+ 比 epoll 减少 70% 系统调用
Thread-per-core - 更好的缓存局部性,无锁竞争
为 Web 优化 - 针对 HTTP 请求/响应模式定制
零开销 - 只为使用的功能付费
Getting Started / 入门
Installation / 安装
Add to your Cargo.toml:
[dependencies]
hiver-runtime = "0.1.0-alpha"
Hello Runtime / 你好,运行时
use hiver_runtime::Runtime;
fn main() -> std::io::Result<()> {
// Create runtime / 创建运行时
let mut runtime = Runtime::new()?;
// Execute async code / 执行异步代码
runtime.block_on(async {
println!("Hello from Hiver runtime!");
})?;
Ok(())
}
With Configuration / 带配置
use hiver_runtime::{Runtime, DriverType};
use std::time::Duration;
fn main() -> std::io::Result<()> {
let mut runtime = Runtime::builder()
.worker_threads(4) // 4 worker threads
.driver_type(DriverType::Auto) // Auto-detect best driver
.io_entries(512) // I/O queue depth
.park_timeout(Duration::from_millis(100))
.build()?;
runtime.block_on(async {
// Your async code here
})?;
Ok(())
}
I/O Drivers / I/O 驱动器
Automatic Driver Selection / 自动驱动选择
Hiver automatically selects the best I/O driver for your platform:
Hiver 自动为您的平台选择最佳 I/O 驱动器:
| Platform | Primary Driver | Fallback | Performance |
|---|---|---|---|
| Linux 5.1+ | io-uring | epoll | ⚡⚡⚡ Best |
| Linux < 5.1 | epoll | - | ⚡⚡ Good |
| macOS/BSD | kqueue | - | ⚡⚡ Good |
| Windows | IOCP (planned) | - | 📋 Future |
#![allow(unused)]
fn main() {
use hiver_runtime::{Runtime, DriverType};
// Auto-detect (recommended) / 自动检测(推荐)
let runtime = Runtime::new()?;
// Or force specific driver / 或强制特定驱动
let runtime = Runtime::builder()
.driver_type(DriverType::IOUring)
.build()?;
}
io-uring: The Modern Approach / io-uring:现代方法
Traditional epoll / 传统epoll:
每个I/O操作需要2+次系统调用:
1. submit操作(syscall)
2. epoll_wait(syscall)
3. read/write(syscall)
Result: High syscall overhead
结果:高系统调用开销
io-uring / io-uring:
批量I/O操作只需1次系统调用:
1. 提交10个操作到SQ(submission queue)
2. io_uring_enter(syscall)
3. 从CQ(completion queue)读取结果(无syscall)
Result: 70% fewer syscalls, 40% lower latency
结果:减少70%系统调用,降低40%延迟
Visual Comparison / 可视化对比:
epoll: io-uring:
用户态 内核态 用户态 内核态
accept() ────► [syscall] [SQE] ────┐
[SQE] │
read() ──────► [syscall] [SQE] ├─► [syscall]
[SQE] │ (1 time)
write() ─────► [syscall] [SQE] ────┘
▼
epoll_wait() ► [syscall] [CQE] ◄─── (no syscall)
[CQE]
[CQE]
4 syscalls 1 syscall
Task Scheduling / 任务调度
Thread-per-Core Scheduler / Thread-per-Core 调度器
Design Philosophy / 设计哲学:
Each CPU core runs an independent task queue with no synchronization:
每个 CPU 核心运行独立的任务队列,无需同步:
┌─────────────────────────────────────────────────────────────┐
│ Thread-per-core Architecture │
│ Thread-per-core 架构 │
├─────────────────────────────────────────────────────────────┤
│ │
│ Core 0 Core 1 Core 2 Core 3 │
│ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │Queue │ │Queue │ │Queue │ │Queue │ │
│ │ [T1] │ │ [T5] │ │ [T9] │ │[T13] │ │
│ │ [T2] │ │ [T6] │ │[T10] │ │[T14] │ │
│ │ [T3] │ │ [T7] │ │[T11] │ │[T15] │ │
│ │ [T4] │ │ [T8] │ │[T12] │ │[T16] │ │
│ └──────┘ └──────┘ └──────┘ └──────┘ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │Driver│ │Driver│ │Driver│ │Driver│ │
│ │ (io) │ │ (io) │ │ (io) │ │ (io) │ │
│ └──────┘ └──────┘ └──────┘ └──────┘ │
│ │
│ Benefits / 优势: │
│ ✅ No lock contention / 无锁竞争 │
│ ✅ Better CPU cache locality / 更好的CPU缓存局部性 │
│ ✅ Predictable latency / 可预测的延迟 │
│ ✅ Linear scalability / 线性可扩展性 │
│ │
│ Trade-offs / 权衡: │
│ ⚠️ Possible load imbalance / 可能的负载不平衡 │
│ ⚠️ Not ideal for CPU-bound tasks / 不适合CPU密集型任务 │
└─────────────────────────────────────────────────────────────┘
Timer Wheel / 时间轮
Hierarchical 4-Wheel Design / 分层 4 轮设计
Hiver uses a hierarchical timer wheel for O(1) timer operations:
Hiver 使用分层时间轮实现 O(1) 定时器操作:
┌─────────────────────────────────────────────────────────────┐
│ Hierarchical Timer Wheel │
│ 分层时间轮 │
├─────────────────────────────────────────────────────────────┤
│ │
│ Wheel 0: 1ms precision × 256 slots = 0-255ms │
│ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ │
│ │ 0 │ 1 │ 2 │...│254│255│ │ │ │ │ 1ms/slot │
│ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ │
│ ▲ │
│ │ Current tick / 当前刻度 │
│ │ Overflow ↓ │
│ │
│ Wheel 1: 256ms × 256 slots = 0-65s │
│ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ │
│ │ 0 │ 1 │ 2 │...│254│255│ │ │ │ │ 256ms/slot │
│ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ │
│ │ Overflow ↓ │
│ │
│ Wheel 2: 65s × 256 slots = 0-4.6h │
│ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ │
│ │ 0 │ 1 │ 2 │...│254│255│ │ │ │ │ 65s/slot │
│ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ │
│ │ Overflow ↓ │
│ │
│ Wheel 3: 4.6h × 256 slots = 0-49 days │
│ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ │
│ │ 0 │ 1 │ 2 │...│254│255│ │ │ │ │ 4.6h/slot │
│ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ │
│ │
│ Operations / 操作: │
│ ✅ Insert: O(1) - Find slot by time / 按时间找槽位 │
│ ✅ Remove: O(1) - Direct access / 直接访问 │
│ ✅ Tick: O(1) amortized - Process expired / 处理过期 │
│ ✅ Memory: O(n) where n = timer count / n=定时器数量 │
└─────────────────────────────────────────────────────────────┘
Timer API / 定时器 API
#![allow(unused)]
fn main() {
use hiver_runtime::{sleep, sleep_until, Duration, Instant};
async fn timer_examples() {
// Sleep for duration / 休眠一段时间
sleep(Duration::from_secs(2)).await;
println!("2 seconds passed");
// Sleep until specific time / 休眠到特定时间
let deadline = Instant::now() + Duration::from_secs(5);
sleep_until(deadline).await;
// Periodic timer / 周期定时器
loop {
sleep(Duration::from_millis(100)).await;
println!("Tick every 100ms");
}
}
}
Timeout Pattern / 超时模式
#![allow(unused)]
fn main() {
use hiver_runtime::{select_two, sleep, Duration};
use hiver_runtime::select::SelectTwoOutput;
async fn with_timeout() {
let operation = async {
// Slow operation / 慢操作
expensive_computation().await
};
let timeout = sleep(Duration::from_secs(5));
match select_two(operation, timeout).await {
SelectTwoOutput::First(result) => {
println!("Completed: {:?}", result);
}
SelectTwoOutput::Second(_) => {
println!("Timeout!");
}
}
}
}
Async Channels / 异步通道
MPSC Channels / MPSC 通道
Multiple-producer, single-consumer channels for task communication:
多生产者、单消费者通道用于任务通信:
#![allow(unused)]
fn main() {
use hiver_runtime::{bounded, unbounded, spawn};
async fn channel_demo() {
// Bounded channel (backpressure) / 有界通道(背压)
let (tx, rx) = bounded::<i32>(10);
// Spawn producer / 生成生产者
spawn(async move {
for i in 0..20 {
tx.send(i).await.unwrap();
println!("Sent: {}", i);
}
});
// Consume values / 消费值
while let Ok(value) = rx.recv().await {
println!("Received: {}", value);
}
}
}
Bounded vs Unbounded / 有界 vs 无界
┌─────────────────────────────────────────────────────────────┐
│ Bounded Channel │
│ 有界通道 │
├─────────────────────────────────────────────────────────────┤
│ ✅ Backpressure: Senders wait when full │
│ ✅ Bounded memory usage │
│ ✅ Flow control │
│ ⚠️ Can block senders │
│ │
│ Use for: / 适用于: │
│ - Network I/O │
│ - Rate limiting │
│ - Resource management │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Unbounded Channel │
│ 无界通道 │
├─────────────────────────────────────────────────────────────┤
│ ✅ No blocking on send │
│ ✅ Always available │
│ ⚠️ Unbounded memory growth │
│ ⚠️ Can cause OOM │
│ │
│ Use for: / 适用于: │
│ - Rare events │
│ - Shutdown signals │
│ - Low-frequency messages │
└─────────────────────────────────────────────────────────────┘
Example / 示例:
#![allow(unused)]
fn main() {
use hiver_runtime::{bounded, unbounded};
// Producer-consumer with backpressure / 带背压的生产者-消费者
let (tx, rx) = bounded::<WorkItem>(100);
// Shutdown signal (rare event) / 关闭信号(罕见事件)
let (shutdown_tx, shutdown_rx) = unbounded::<()>();
}
Task Spawning / 任务生成
Basic Task Spawning / 基本任务生成
#![allow(unused)]
fn main() {
use hiver_runtime::{spawn, JoinHandle};
async fn task_example() {
// Spawn single task / 生成单个任务
let handle = spawn(async {
println!("Background task");
42
});
// Wait for result / 等待结果
let result = handle.wait().await.unwrap();
assert_eq!(result, 42);
}
}
Concurrent Tasks / 并发任务
#![allow(unused)]
fn main() {
use hiver_runtime::spawn;
async fn parallel_processing() {
let mut handles = Vec::new();
// Spawn 10 tasks / 生成 10 个任务
for i in 0..10 {
let handle = spawn(async move {
// Process item / 处理项目
process_item(i).await
});
handles.push(handle);
}
// Wait for all / 等待全部完成
for handle in handles {
let result = handle.wait().await.unwrap();
println!("Result: {:?}", result);
}
}
}
Task Lifecycle / 任务生命周期
┌─────────────────────────────────────────────────────────────┐
│ Task Lifecycle │
│ 任务生命周期 │
├─────────────────────────────────────────────────────────────┤
│ │
│ spawn() │
│ │ │
│ ▼ │
│ Created ──────────► Running │
│ 创建 运行 │
│ │ │
│ │ poll() returns Pending │
│ ▼ │
│ Waiting ◄─────┐ │
│ 等待 │ │
│ │ │ │
│ │ wake() │ poll() → Pending │
│ │ │ │
│ └──────────┘ │
│ │ │
│ │ poll() returns Ready │
│ ▼ │
│ Completed │
│ 完成 │
│ │ │
│ ▼ │
│ JoinHandle::wait() returns result │
│ │
└─────────────────────────────────────────────────────────────┘
Select! Macro / Select! 宏
Wait on multiple futures concurrently:
并发等待多个 future:
Select Two / 选择两个
#![allow(unused)]
fn main() {
use hiver_runtime::{select_two, bounded};
use hiver_runtime::select::SelectTwoOutput;
async fn select_demo() {
let (tx1, rx1) = bounded::<i32>(1);
let (tx2, rx2) = bounded::<String>(1);
tx1.send(42).await.unwrap();
// Wait on both futures / 等待两个future
match select_two(rx1.recv(), rx2.recv()).await {
SelectTwoOutput::First(v) => {
println!("Received int: {:?}", v);
}
SelectTwoOutput::Second(v) => {
println!("Received string: {:?}", v);
}
}
}
}
Select Multiple / 选择多个
#![allow(unused)]
fn main() {
use hiver_runtime::select_multiple;
use hiver_runtime::select::SelectMultipleOutput;
async fn select_many() {
let futures = vec![
Box::pin(async { fetch_user(1).await }),
Box::pin(async { fetch_user(2).await }),
Box::pin(async { fetch_user(3).await }),
];
// Returns the first completed result / 返回第一个完成的结果
match select_multiple(futures).await {
SelectMultipleOutput::Completed(index, user) => {
println!("User at index {}: {:?}", index, user);
}
}
}
}
Network I/O / 网络 I/O
TCP Server / TCP 服务器
use hiver_runtime::{Runtime, io::TcpListener, spawn};
fn main() -> std::io::Result<()> {
let mut runtime = Runtime::new()?;
runtime.block_on(async {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Listening on 127.0.0.1:8080");
loop {
let (mut stream, addr) = listener.accept().await?;
println!("Connection from: {}", addr);
// Spawn task for each connection / 为每个连接生成任务
spawn(async move {
let mut buf = [0u8; 1024];
loop {
// Read data / 读取数据
let n = stream.read(&mut buf).await?;
if n == 0 { break; } // Connection closed / 连接关闭
// Echo back / 回显
stream.write_all(&buf[..n]).await?;
}
Ok::<_, std::io::Error>(())
});
}
})?;
Ok(())
}
TCP Client / TCP 客户端
#![allow(unused)]
fn main() {
use hiver_runtime::{Runtime, io::TcpStream};
async fn tcp_client() -> std::io::Result<()> {
// Connect to server / 连接到服务器
let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
// Send data / 发送数据
stream.write_all(b"Hello, server!").await?;
// Read response / 读取响应
let mut buf = [0u8; 1024];
let n = stream.read(&mut buf).await?;
println!("Server response: {}", String::from_utf8_lossy(&buf[..n]));
Ok(())
}
}
UDP Socket / UDP 套接字
#![allow(unused)]
fn main() {
use hiver_runtime::{Runtime, io::UdpSocket};
async fn udp_example() -> std::io::Result<()> {
// Bind socket / 绑定套接字
let socket = UdpSocket::bind("127.0.0.1:0").await?;
// Send datagram / 发送数据报
socket.send_to(b"Hello, UDP!", "127.0.0.1:8080").await?;
// Receive datagram / 接收数据报
let mut buf = [0u8; 1024];
let (n, addr) = socket.recv_from(&mut buf).await?;
println!("Received from {}: {}",
addr,
String::from_utf8_lossy(&buf[..n])
);
Ok(())
}
}
Advanced Topics / 高级主题
Runtime Configuration / 运行时配置
#![allow(unused)]
fn main() {
use hiver_runtime::{Runtime, DriverType};
use std::time::Duration;
let runtime = Runtime::builder()
// ===== Scheduler Configuration / 调度器配置 =====
.worker_threads(8) // 8 worker threads (default: CPU count)
.queue_size(1024) // Task queue size (default: 256)
.thread_name("my-worker") // Thread name prefix
// ===== Driver Configuration / 驱动配置 =====
.driver_type(DriverType::Auto) // Auto | IOUring | Epoll | Kqueue
.io_entries(2048) // I/O queue depth (default: 256)
// ===== Thread Parking / 线程休眠 =====
.enable_parking(true) // Allow threads to park when idle
.park_timeout(Duration::from_millis(100))
.build()?;
}
Driver Configuration / 驱动配置
The DriverConfig builder provides fine-grained control over I/O driver behavior:
DriverConfig 构建器提供对 I/O 驱动器行为的精细控制:
#![allow(unused)]
fn main() {
use hiver_runtime::driver::DriverConfig;
let config = DriverConfig::builder()
.entries(2048) // SQ/CQ size (rounded to next power of 2)
.submit_wait(true) // Wait for completion on submit (blocking mode)
.cpu_affinity(0) // Pin driver thread to CPU core 0
.defer_wakeup(true) // Enable deferred task wake-up
.max_ops_per_fd(64) // Max concurrent operations per file descriptor
.build();
}
Then pass the config when building the runtime:
然后在构建运行时时传入配置:
#![allow(unused)]
fn main() {
use hiver_runtime::{Runtime, RuntimeConfig, DriverType};
// Build a RuntimeConfig with custom driver settings
// 使用自定义驱动设置构建 RuntimeConfig
let mut config = RuntimeConfig::default();
config.driver_type = DriverType::IOUring;
config.driver_io = driver_config;
let mut runtime = Runtime::builder()
.config(config)
.build()?;
}
Performance Tuning / 性能调优
For high-throughput web servers / 高吞吐量 Web 服务器:
#![allow(unused)]
fn main() {
let runtime = Runtime::builder()
.worker_threads(num_cpus::get()) // One thread per core
.driver_type(DriverType::IOUring) // Use io-uring on Linux
.io_entries(1024) // Large I/O queue
.enable_parking(false) // Never park threads
.build()?;
}
For low-latency services / 低延迟服务:
#![allow(unused)]
fn main() {
let runtime = Runtime::builder()
.worker_threads(num_cpus::get())
.io_entries(256) // Smaller queue for lower latency
.park_timeout(Duration::from_millis(10)) // Quick wake-up
.build()?;
}
For CPU-bound workloads / CPU 密集型工作负载:
#![allow(unused)]
fn main() {
use hiver_runtime::driver::DriverConfig;
let driver_config = DriverConfig::builder()
.entries(512)
.submit_wait(true) // Blocking submit for CPU efficiency
.cpu_affinity(0) // Pin to specific core
.defer_wakeup(false) // Immediate wake-up
.build();
let mut config = RuntimeConfig::default();
config.driver_io = driver_config;
let runtime = Runtime::builder()
.worker_threads(num_cpus::get())
.config(config)
.build()?;
}
Platform-Specific Optimizations / 平台特定优化
Linux io-uring / Linux io-uring:
#![allow(unused)]
fn main() {
use hiver_runtime::driver::DriverConfig;
let config = DriverConfig::builder()
.entries(2048) // SQ/CQ size (rounded to next power of 2)
.submit_wait(false) // Non-blocking submit for async
.cpu_affinity(0) // Pin driver thread to core 0
.defer_wakeup(true) // Batch wake-ups for efficiency
.max_ops_per_fd(64) // More ops per FD for high throughput
.build();
let mut runtime_config = RuntimeConfig::default();
runtime_config.driver_type = DriverType::IOUring;
runtime_config.driver_io = config;
let mut runtime = Runtime::builder()
.config(runtime_config)
.build()?;
}
macOS kqueue / macOS kqueue:
#![allow(unused)]
fn main() {
// kqueue is used automatically on macOS / macOS 自动使用 kqueue
// No special configuration needed / 无需特殊配置
let runtime = Runtime::new()?;
}
Best Practices / 最佳实践
1. Task Management / 任务管理
#![allow(unused)]
fn main() {
// ✅ Good: Spawn tasks for concurrent work / 好:为并发工作生成任务
for request in requests {
spawn(async move {
handle_request(request).await
});
}
// ❌ Bad: Sequential processing / 不好:顺序处理
for request in requests {
handle_request(request).await; // Blocks other requests
}
}
2. Channel Usage / 通道使用
#![allow(unused)]
fn main() {
// ✅ Good: Use bounded channels for backpressure / 好:使用有界通道实现背压
let (tx, rx) = bounded::<Message>(100);
// ❌ Bad: Unbounded can cause memory issues / 不好:无界可能导致内存问题
let (tx, rx) = unbounded::<Message>();
}
3. Error Handling / 错误处理
#![allow(unused)]
fn main() {
// ✅ Good: Handle errors properly / 好:正确处理错误
spawn(async {
match risky_operation().await {
Ok(result) => process(result),
Err(e) => {
tracing::error!("Operation failed: {}", e);
// Handle error / 处理错误
}
}
});
// ❌ Bad: Unhandled panics crash the runtime / 不好:未处理的panic会崩溃运行时
spawn(async {
risky_operation().await.unwrap(); // Can panic!
});
}
4. Resource Cleanup / 资源清理
#![allow(unused)]
fn main() {
use hiver_runtime::spawn;
async fn resource_example() {
let file = open_file().await?;
// ✅ Good: Use guards for cleanup / 好:使用guard清理
let _guard = FileGuard(file);
// ❌ Bad: Easy to forget cleanup / 不好:容易忘记清理
// ... do work ...
// close_file(file); // What if early return?
}
}
Performance Tips / 性能技巧
1. Choose the Right Driver / 选择合适的驱动
#![allow(unused)]
fn main() {
// For web servers (I/O-bound) on Linux / Linux上的Web服务器(I/O密集)
let runtime = Runtime::builder()
.worker_threads(num_cpus::get())
.driver_type(DriverType::IOUring) // Best for I/O-bound
.build()?;
// For systems without io-uring / 没有io-uring的系统
let runtime = Runtime::builder()
.worker_threads(num_cpus::get())
.driver_type(DriverType::Epoll) // Fallback on Linux
.build()?;
}
2. Batch I/O Operations / 批量 I/O 操作
#![allow(unused)]
fn main() {
// ❌ Bad: Many small writes / 不好:许多小写入
for byte in data {
stream.write(&[byte]).await?; // Many syscalls
}
// ✅ Good: Batch writes / 好:批量写入
stream.write_all(&data).await?; // One syscall
}
3. Tune Queue Sizes / 调整队列大小
#![allow(unused)]
fn main() {
// High throughput: Larger queues / 高吞吐量:更大队列
let runtime = Runtime::builder()
.queue_size(1024)
.io_entries(2048)
.build()?;
// Low latency: Smaller queues / 低延迟:更小队列
let runtime = Runtime::builder()
.queue_size(256)
.io_entries(512)
.build()?;
}
Debugging / 调试
Enable Runtime Logging / 启用运行时日志
use tracing_subscriber;
fn main() -> std::io::Result<()> {
// Initialize tracing / 初始化追踪
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_target(true)
.init();
let mut runtime = Runtime::new()?;
runtime.block_on(async {
// Debug logs will show runtime events
// 调试日志将显示运行时事件
})?;
Ok(())
}
Common Issues / 常见问题
Issue / 问题: Task not progressing / 任务无进展
Cause / 原因: Forgot to .await a future
Solution / 解决方案:
#![allow(unused)]
fn main() {
// ❌ Bad / 不好
let result = some_future(); // Not awaited!
// ✅ Good / 好
let result = some_future().await;
}
Issue / 问题: High CPU usage when idle / 空闲时高CPU使用
Cause / 原因: Thread parking disabled
Solution / 解决方案:
#![allow(unused)]
fn main() {
let runtime = Runtime::builder()
.enable_parking(true) // Enable parking
.park_timeout(Duration::from_millis(100))
.build()?;
}
Issue / 问题: Slow startup / 启动慢
Cause / 原因: io-uring initialization overhead
Solution / 解决方案:
#![allow(unused)]
fn main() {
// Use epoll on systems where io-uring setup is slow
// 在io-uring设置慢的系统上使用epoll
let runtime = Runtime::builder()
.driver_type(DriverType::Epoll)
.build()?;
}
Testing / 测试
Unit Testing with Runtime / 使用运行时进行单元测试
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
use hiver_runtime::Runtime;
#[test]
fn test_async_function() {
let mut runtime = Runtime::new().unwrap();
runtime.block_on(async {
let result = async_operation().await;
assert_eq!(result, expected_value);
}).unwrap();
}
}
}
Integration Testing / 集成测试
#![allow(unused)]
fn main() {
// tests/integration_test.rs
use hiver_runtime::{Runtime, spawn, bounded};
#[test]
fn test_concurrent_tasks() {
let mut runtime = Runtime::new().unwrap();
runtime.block_on(async {
let (tx, rx) = bounded::<i32>(10);
// Spawn producer / 生成生产者
spawn(async move {
for i in 0..10 {
tx.send(i).await.unwrap();
}
});
// Verify all values received / 验证接收所有值
let mut sum = 0;
while let Ok(value) = rx.recv().await {
sum += value;
}
assert_eq!(sum, 45); // 0+1+2+...+9
}).unwrap();
}
}
Comparison with Other Runtimes / 与其他运行时对比
| Feature | Hiver | Tokio | async-std | Monoio |
|---|---|---|---|---|
| I/O Backend | io-uring first | epoll/kqueue | epoll/kqueue | io-uring only |
| Scheduler | Thread-per-core | Work-stealing | Work-stealing | Thread-per-core |
| Timer | Hierarchical wheel | Slab heap | Wheel | Wheel |
| QPS Target | 1M+ | ~800K | ~600K | 1M+ |
| P99 Latency | < 1ms | ~1.5ms | ~2ms | ~1ms |
| Memory (idle) | < 10MB | ~16MB | ~12MB | ~8MB |
Why choose Hiver? / 为什么选择 Hiver?
- ✅ Best I/O performance on Linux (io-uring)
- ✅ Multi-platform support (Linux/macOS/BSD)
- ✅ Lower latency for web servers
- ✅ Integrated with Hiver Framework features
- ✅ Better cache locality (thread-per-core)
Further Reading / 延伸阅读
- HTTP Server - Build web services with Hiver
- Router - HTTP request routing
- Middleware - Request/response processing
- Extractors - Type-safe data extraction
External Resources / 外部资源
- io-uring Paper - Linux async I/O
- Monoio - Similar runtime design
- Glommio - Thread-per-core architecture
← Previous / 上一页 | Next / 下一页 →
HTTP Server
HTTP服务器
The hiver-http crate provides HTTP server and client implementations optimized for the Hiver runtime.
hiver-http crate 提供针对 Hiver 运行时优化的 HTTP 服务器和客户端实现。
Overview / 概述
┌─────────────────────────────────────────────────────────────┐
│ HTTP Request Flow │
├─────────────────────────────────────────────────────────────┤
│ Client Request → Server → Handler → Response → Client │
│ ↓ │
│ Request Parsing │
│ ↓ │
│ Route Matching │
│ ↓ │
│ Middleware Chain │
│ ↓ │
│ Handler Execution │
│ ↓ │
│ Response Building │
└─────────────────────────────────────────────────────────────┘
Core Types / 核心类型
Request / 请求
#![allow(unused)]
fn main() {
use hiver_http::Request;
async fn handle(req: Request) -> Response {
// Access request properties / 访问请求属性
let method = req.method(); // HTTP method / HTTP 方法
let path = req.path(); // Request path / 请求路径
let uri = req.uri(); // Full URI / 完整 URI
// Access headers / 访问头部
let content_type = req.header("content-type");
let user_agent = req.header("user-agent");
// Access query parameters / 访问查询参数
let page = req.param("page"); // Single query param / 单个查询参数
let params = req.params(); // All query params / 所有查询参数
// Access path variables / 访问路径变量
let id = req.path_var("id"); // Single path variable / 单个路径变量
let vars = req.path_vars(); // All path variables / 所有路径变量
// Access body / 访问请求体
let body = req.body();
// ...
}
}
Response / 响应
#![allow(unused)]
fn main() {
use hiver_http::{Response, StatusCode, Body};
// Builder pattern / 构建器模式
let response = Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.header("x-custom-header", "value")
.body(Body::from(r#"{"message": "Hello"}"#))
.unwrap();
// Quick responses (no arguments) / 快速响应(无参数)
let ok = Response::ok();
let created = Response::created();
let not_found = Response::not_found();
let error = Response::internal_server_error();
// JSON helper / JSON 辅助方法
let json_resp = Response::json(&value);
}
Body / 请求体/响应体
#![allow(unused)]
fn main() {
use hiver_http::Body;
// From string / 从字符串
let body = Body::from("Hello, World!");
// From bytes / 从字节
let body = Body::from(vec![0u8, 1, 2, 3]);
// From JSON (with serde) / 从 JSON
let body = Body::from(serde_json::to_string(&data)?);
// Empty body / 空请求体
let body = Body::empty();
}
Status Codes / 状态码
#![allow(unused)]
fn main() {
use hiver_http::StatusCode;
// Common status codes / 常用状态码
StatusCode::OK // 200
StatusCode::CREATED // 201
StatusCode::NO_CONTENT // 204
StatusCode::BAD_REQUEST // 400
StatusCode::UNAUTHORIZED // 401
StatusCode::FORBIDDEN // 403
StatusCode::NOT_FOUND // 404
StatusCode::INTERNAL_SERVER_ERROR // 500
}
Server Configuration / 服务器配置
#![allow(unused)]
fn main() {
use hiver_http::Server;
// Basic server / 基础服务器
Server::bind("127.0.0.1:8080")
.run(handler)
.await?;
// With configuration / 带配置
Server::bind("0.0.0.0:8080")
.request_timeout(30) // Request timeout in seconds / 请求超时时间(秒)
.keep_alive_timeout(60) // Keep-alive timeout in seconds / 保活超时时间(秒)
.max_connections(10000) // Max connections / 最大连接数
.run(handler)
.await?;
}
IntoResponse Trait / IntoResponse Trait
The IntoResponse trait allows any type to be converted to an HTTP response:
IntoResponse trait 允许任何类型转换为 HTTP 响应:
#![allow(unused)]
fn main() {
use hiver_http::{IntoResponse, Response};
// Built-in implementations / 内置实现
// &str and String
"Hello".into_response()
String::from("Hello").into_response()
// StatusCode
StatusCode::NOT_FOUND.into_response()
// Vec<u8>
vec![1, 2, 3].into_response()
// ()
().into_response() // 204 No Content
}
FromRequest Trait / FromRequest Trait
Extract data from requests: 从请求中提取数据:
#![allow(unused)]
fn main() {
use hiver_http::FromRequest;
// Built-in extractors / 内置提取器
impl FromRequest for String { /* body as string */ }
impl FromRequest for Vec<u8> { /* body as bytes */ }
impl FromRequest for Method { /* HTTP method */ }
impl FromRequest for Json<T> { /* JSON body */ }
}
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
@ResponseBody | IntoResponse | Response conversion |
@RequestBody | FromRequest | Request extraction |
ResponseEntity<T> | Response | Response builder |
HttpServletRequest | Request | Request object |
HttpServletResponse | Response | Response object |
Example: JSON API / 示例:JSON API
#![allow(unused)]
fn main() {
use hiver_http::{Body, Json, Request, Response, StatusCode};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
#[derive(Serialize)]
struct User {
id: u64,
name: String,
email: String,
}
async fn create_user(req: Request) -> Response {
// Parse JSON body / 解析 JSON 请求体
let body = req.body().as_bytes().unwrap();
let input: CreateUser = match serde_json::from_slice(body) {
Ok(data) => data,
Err(_) => return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from(r#"{"error": "Invalid JSON"}"#))
.unwrap(),
};
// Create user / 创建用户
let user = User {
id: 1,
name: input.name,
email: input.email,
};
// Return JSON response / 返回 JSON 响应
Response::builder()
.status(StatusCode::CREATED)
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&user).unwrap()))
.unwrap()
}
}
← Previous / 上一页 | Next / 下一页 →
Router
路由
The hiver-router crate provides high-performance HTTP request routing using a trie-based data structure.
hiver-router crate 使用基于 trie 的数据结构提供高性能 HTTP 请求路由。
Overview / 概述
The router maps HTTP method + path combinations to handler functions:
路由器将 HTTP 方法 + 路径组合映射到处理函数:
#![allow(unused)]
fn main() {
use hiver_router::Router;
use hiver_http::{Response, StatusCode, Body};
let router = Router::new()
.get("/", index)
.get("/users", list_users)
.get("/users/{id}", get_user)
.post("/users", create_user)
.put("/users/{id}", update_user)
.delete("/users/{id}", delete_user);
}
Creating a Router / 创建路由器
Stateless Router / 无状态路由器
#![allow(unused)]
fn main() {
let router = Router::new();
}
Stateful Router / 有状态路由器
#![allow(unused)]
fn main() {
let router = Router::with_state(state);
}
Route Patterns / 路由模式
Static Routes / 静态路由
#![allow(unused)]
fn main() {
router.get("/api/health", health_check)
.get("/api/version", version_info)
}
Path Parameters / 路径参数
Use {name} syntax for dynamic segments:
使用 {name} 语法表示动态片段:
#![allow(unused)]
fn main() {
// Single parameter / 单参数
router.get("/users/{id}", get_user)
// Multiple parameters / 多参数
router.get("/users/{user_id}/posts/{post_id}", get_user_post)
// Access in handler / 在处理器中访问
async fn get_user(req: Request) -> Response {
let id = req.path_var("id").unwrap();
// ...
}
}
HTTP Methods / HTTP 方法
#![allow(unused)]
fn main() {
use hiver_router::Router;
let router = Router::new()
.get("/resource", handler) // GET
.post("/resource", handler) // POST
.put("/resource", handler) // PUT
.patch("/resource", handler) // PATCH
.delete("/resource", handler); // DELETE
// Note: .head(), .options(), .trace() are not yet implemented.
// 注意:.head()、.options()、.trace() 尚未实现。
}
Middleware Integration / 中间件集成
Use .middleware() with Arc<dyn Middleware<S>> to add middleware:
使用 .middleware() 配合 Arc<dyn Middleware<S>> 添加中间件:
#![allow(unused)]
fn main() {
use std::sync::Arc;
use hiver_router::Router;
let router = Router::new()
.get("/", index)
.get("/api/data", get_data)
// Apply middleware to all routes / 为所有路由应用中间件
.middleware(Arc::new(LoggerMiddleware::new()))
.middleware(Arc::new(CorsMiddleware::any()));
}
Path Extraction / 路径提取
Using Path Variables / 使用路径变量
#![allow(unused)]
fn main() {
// Access via Request::path_var() / 通过 Request::path_var() 访问
async fn get_user(req: Request) -> Response {
let id: u64 = req.path_var("id")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
// ...
}
}
Route Groups / 路由分组
Not yet implemented. The following methods are planned but not currently available:
merge(),nest(),fallback(),route(method, path, handler).尚未实现。 以下方法已计划但当前不可用:
merge()、nest()、fallback()、route(method, path, handler)。
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver Router | Description |
|---|---|---|
@GetMapping("/path") | .get("/path", handler) | GET route |
@PostMapping("/path") | .post("/path", handler) | POST route |
@PutMapping("/path") | .put("/path", handler) | PUT route |
@DeleteMapping("/path") | .delete("/path", handler) | DELETE route |
@PatchMapping("/path") | .patch("/path", handler) | PATCH route |
@PathVariable | Request::path_var() | Path parameter |
@RequestMapping | Not yet implemented / 尚未实现 | Generic route |
Performance / 性能
The trie-based router provides O(n) route matching where n is the path length, regardless of the number of registered routes.
基于 trie 的路由器提供 O(n) 的路由匹配,其中 n 是路径长度,与注册的路由数量无关。
| Routes | Match Time |
|---|---|
| 10 | ~50ns |
| 100 | ~50ns |
| 1000 | ~50ns |
| 10000 | ~50ns |
Complete Example / 完整示例
use hiver_router::Router;
use hiver_http::{Body, Request, Response, Result, StatusCode};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn list_users(_req: Request) -> Result<Response> {
let users = vec![
User { id: 1, name: "Alice".into() },
User { id: 2, name: "Bob".into() },
];
json_response(&users)
}
async fn get_user(req: Request) -> Result<Response> {
let id: u64 = req.path_var("id")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let user = User { id, name: format!("User {}", id) };
json_response(&user)
}
async fn create_user(_req: Request) -> Result<Response> {
Ok(Response::builder()
.status(StatusCode::CREATED)
.body(Body::from(r#"{"status": "created"}"#))
.unwrap())
}
fn json_response<T: Serialize>(data: &T) -> Result<Response> {
Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(data).unwrap()))
.unwrap())
}
fn main() {
let router = Router::new()
.get("/users", list_users)
.get("/users/{id}", get_user)
.post("/users", create_user);
// Use with server...
}
<< Previous / 上一页 | Next / 下一页 >>
Middleware
中间件
Middleware in Hiver provides a way to process requests and responses in a composable manner, similar to Spring’s Filter/Interceptor pattern.
Hiver 中的中间件提供了一种以可组合方式处理请求和响应的方法,类似于 Spring 的 Filter/Interceptor 模式。
Overview / 概述
Request → Middleware 1 → Middleware 2 → Handler
↓ ↓ ↓
Response ← Middleware 1 ← Middleware 2 ← Result
Middleware Trait / 中间件 Trait
#![allow(unused)]
fn main() {
use hiver_router::{Middleware, Next};
use hiver_http::{Request, Response, Result};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
pub trait Middleware<S>: Send + Sync + 'static {
/// Process the request and call next middleware/handler
/// 处理请求并调用下一个中间件/处理器
fn call(
&self,
req: Request,
state: Arc<S>,
next: Next<S>,
) -> Pin<Box<dyn Future<Output = Result<Response>> + Send>>;
}
}
Built-in Middleware / 内置中间件
Logger Middleware / 日志中间件
#![allow(unused)]
fn main() {
use hiver_middleware::LoggerMiddleware;
use std::sync::Arc;
let router = Router::new()
.get("/", handler)
.middleware(Arc::new(LoggerMiddleware::new()));
// Output:
// INFO GET /api/users 200 OK 15ms
}
CORS Middleware / CORS 中间件
#![allow(unused)]
fn main() {
use hiver_middleware::{CorsMiddleware, CorsConfig};
// Allow all origins / 允许所有来源
let cors = CorsMiddleware::any();
// Custom configuration / 自定义配置
let cors = CorsMiddleware::new(CorsConfig {
allowed_origins: vec!["https://example.com".into()],
allowed_methods: vec![Method::GET, Method::POST],
allowed_headers: vec!["Content-Type".into(), "Authorization".into()],
allow_credentials: true,
max_age: Some(Duration::from_secs(3600)),
});
let router = Router::new()
.get("/api/data", handler)
.middleware(Arc::new(cors));
}
Timeout Middleware / 超时中间件
#![allow(unused)]
fn main() {
use hiver_middleware::TimeoutMiddleware;
use std::time::Duration;
use std::sync::Arc;
let router = Router::new()
.get("/api/slow", slow_handler)
.middleware(Arc::new(TimeoutMiddleware::new(Duration::from_secs(30))));
}
Compression Middleware / 压缩中间件
#![allow(unused)]
fn main() {
use hiver_middleware::CompressionMiddleware;
use std::sync::Arc;
let router = Router::new()
.get("/api/data", handler)
.middleware(Arc::new(CompressionMiddleware::new()));
// Supports: gzip, deflate, br (brotli)
}
Creating Custom Middleware / 创建自定义中间件
Function-based Middleware / 函数式中间件
#![allow(unused)]
fn main() {
use hiver_router::{Middleware, Next};
use hiver_http::{Request, Response, Result};
use std::sync::Arc;
async fn auth_middleware<S>(req: Request, state: Arc<S>, next: Next<S>) -> Result<Response> {
// Check authorization header / 检查授权头
match req.header("authorization") {
Some(token) if is_valid_token(token) => {
// Continue to next middleware/handler
// 继续到下一个中间件/处理器
next.call(req, state).await
}
_ => {
Ok(Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::from("Unauthorized"))
.unwrap())
}
}
}
}
Struct-based Middleware / 结构体中间件
#![allow(unused)]
fn main() {
use std::time::Instant;
use std::pin::Pin;
use std::future::Future;
use std::sync::Arc;
use hiver_router::{Middleware, Next};
use hiver_http::{Request, Response, Result};
struct TimingMiddleware;
impl<S: Send + Sync + 'static> Middleware<S> for TimingMiddleware {
fn call(
&self,
req: Request,
state: Arc<S>,
next: Next<S>,
) -> Pin<Box<dyn Future<Output = Result<Response>> + Send>> {
Box::pin(async move {
let start = Instant::now();
let method = req.method().to_string();
let path = req.path().to_string();
// Call next middleware/handler / 调用下一个中间件/处理器
let response = next.call(req, state).await?;
let duration = start.elapsed();
tracing::info!(
method = %method,
path = %path,
status = %response.status(),
duration_ms = %duration.as_millis(),
"Request completed"
);
Ok(response)
})
}
}
}
Middleware with State / 带状态的中间件
#![allow(unused)]
fn main() {
use std::pin::Pin;
use std::future::Future;
use std::sync::Arc;
use std::collections::HashMap;
use tokio::sync::RwLock;
use hiver_router::{Middleware, Next};
use hiver_http::{Request, Response, Result, Body, StatusCode};
struct RateLimitMiddleware {
requests_per_second: u32,
limiter: Arc<RwLock<HashMap<String, u32>>>,
}
impl RateLimitMiddleware {
fn new(rps: u32) -> Self {
Self {
requests_per_second: rps,
limiter: Arc::new(RwLock::new(HashMap::new())),
}
}
}
impl<S: Send + Sync + 'static> Middleware<S> for RateLimitMiddleware {
fn call(
&self,
req: Request,
state: Arc<S>,
next: Next<S>,
) -> Pin<Box<dyn Future<Output = Result<Response>> + Send>> {
let limiter = self.limiter.clone();
let rps = self.requests_per_second;
Box::pin(async move {
let ip = req.remote_addr()
.map(|a| a.to_string())
.unwrap_or_default();
// Check rate limit / 检查速率限制
{
let mut limiter_guard = limiter.write().await;
let count = limiter_guard.entry(ip.clone()).or_insert(0);
if *count >= rps {
return Ok(Response::builder()
.status(StatusCode::TOO_MANY_REQUESTS)
.body(Body::from("Rate limit exceeded"))
.unwrap());
}
*count += 1;
}
next.call(req, state).await
})
}
}
}
Middleware Ordering / 中间件顺序
Middleware is applied in the order it’s added, but executed in reverse order for responses:
中间件按添加顺序应用,但响应按相反顺序执行:
#![allow(unused)]
fn main() {
use std::sync::Arc;
let router = Router::new()
.get("/", handler)
.middleware(Arc::new(LoggerMiddleware::new())) // 1st added, outermost
.middleware(Arc::new(CorsMiddleware::any())) // 2nd added
.middleware(Arc::new(TimeoutMiddleware::new(30s))); // 3rd added, innermost
// Request flow: Logger → CORS → Timeout → Handler
// Response flow: Handler → Timeout → CORS → Logger
}
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
Filter | Middleware trait | Request/response processing |
HandlerInterceptor | Middleware trait | Handler interception |
@CrossOrigin | CorsMiddleware | CORS configuration |
OncePerRequestFilter | - | Single execution per request |
| Filter chain | .middleware() chaining | Middleware composition |
Best Practices / 最佳实践
-
Keep middleware lightweight / 保持中间件轻量
- Avoid heavy computation in middleware
- Use async for I/O operations
-
Order matters / 顺序很重要
- Put authentication before authorization
- Put logging first to capture all requests
-
Use appropriate scope / 使用适当的作用域
- Global middleware: Add to root router
- Route-specific: Add to nested router
-
Handle errors gracefully / 优雅处理错误
- Return proper error responses
- Don’t panic in middleware
Complete Example / 完整示例
#![allow(unused)]
fn main() {
use hiver_router::Router;
use hiver_middleware::{
LoggerMiddleware,
CorsMiddleware,
TimeoutMiddleware,
CompressionMiddleware,
};
use std::time::Duration;
use std::sync::Arc;
fn build_router() -> Router {
// Public routes / 公共路由
let public = Router::new()
.get("/health", health_check)
.get("/version", version);
// Protected API routes / 受保护的 API 路由
let api = Router::new()
.get("/users", list_users)
.post("/users", create_user)
.middleware(Arc::new(AuthMiddleware)); // Auth only for API
// Build main router / 构建主路由
Router::new()
.merge(public)
.nest("/api", api)
// Global middleware / 全局中间件
.middleware(Arc::new(LoggerMiddleware::new()))
.middleware(Arc::new(CorsMiddleware::any()))
.middleware(Arc::new(CompressionMiddleware::new()))
.middleware(Arc::new(TimeoutMiddleware::new(Duration::from_secs(30))))
}
}
← Previous / 上一页 | Next / 下一页 →
Extractors
提取器
Extractors in Hiver provide a type-safe way to extract data from HTTP requests, similar to Spring’s @PathVariable, @RequestParam, @RequestBody, etc.
Hiver 中的提取器提供了一种类型安全的方式从 HTTP 请求中提取数据,类似于 Spring 的 @PathVariable、@RequestParam、@RequestBody 等。
Important Disclaimers / 重要说明
1. Two
FromRequesttraits / 两个FromRequesttraitThe codebase defines two separate
FromRequesttraits that serve different layers:
hiver_http::FromRequest(inhiver-http): Usesasync fn from_request(req: &Request) -> Result<Self>. This is the trait used by the#[handler]proc-macro to perform automatic parameter extraction.hiver_extractors::FromRequest(inhiver-extractors): Usesfn from_request(req: &Request) -> ExtractorFuture<Self>whereExtractorFuture<T> = Pin<Box<dyn Future<Output = Result<T, ExtractorError>> + Send>>. This is the trait used when implementing custom extractors manually with the extractor infrastructure.When writing a custom extractor, be sure to implement the correct trait for your use case. The code examples in this document use
hiver_extractors::FromRequestunless noted otherwise.2. Extractor-style handler signatures require the proc-macro system / 提取器风格的处理器签名需要过程宏系统
Handler function signatures with multiple extractor parameters (e.g.,
async fn handler(Path(id): Path<u64>, Query(params): Query<Params>)) only work when the function is decorated with the#[handler]attribute macro fromhiver-macros. The#[handler]macro generates a wrapper that accepts a rawRequest, callsFromRequest::from_request()for each parameter, and then invokes the original function.Plain handler functions registered via
Router::get()(or.post(), etc.) have the signaturefn(Request, Arc<S>) -> Pin<Box<dyn Future<Output = Result<Response>> + Send>>and must manually extract data from theRequest.The route-attribute macros (
#[get],#[post], etc. fromhiver-macros) register a raw function with the router and do not perform parameter extraction on their own. To get automatic extraction, combine#[handler]with a route attribute, or use#[handler]and register the wrapper manually.
Overview / 概述
#![allow(unused)]
fn main() {
use hiver_extractors::{Path, Query, Json, State, Header};
async fn handler(
Path(id): Path<u64>, // From URL path / 从 URL 路径
Query(params): Query<Params>, // From query string / 从查询字符串
Json(body): Json<CreateUser>, // From JSON body / 从 JSON 请求体
State(db): State<Database>, // Application state / 应用状态
Header(auth): Header<String>, // From header / 从请求头
) -> Response {
// ...
}
}
Built-in Extractors / 内置提取器
Path - Path Parameters / 路径参数
Extract values from URL path segments. 从 URL 路径段提取值。
#![allow(unused)]
fn main() {
use hiver_extractors::Path;
// Route: /users/:id
// URL: /users/123
// Single parameter / 单参数
async fn get_user(Path(id): Path<u64>) -> Response {
// id = 123
}
// Multiple parameters / 多参数
// Route: /users/:user_id/posts/:post_id
async fn get_post(Path((user_id, post_id)): Path<(u64, u64)>) -> Response {
// user_id, post_id
}
// Using struct / 使用结构体
#[derive(Deserialize)]
struct PostPath {
user_id: u64,
post_id: u64,
}
async fn get_post(Path(path): Path<PostPath>) -> Response {
// path.user_id, path.post_id
}
}
Spring equivalent / Spring 等价:
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
Query - Query Parameters / 查询参数
Extract values from URL query string. 从 URL 查询字符串提取值。
#![allow(unused)]
fn main() {
use hiver_extractors::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct ListParams {
page: Option<u32>,
limit: Option<u32>,
search: Option<String>,
}
// URL: /users?page=1&limit=10&search=alice
async fn list_users(Query(params): Query<ListParams>) -> Response {
let page = params.page.unwrap_or(1);
let limit = params.limit.unwrap_or(20);
// ...
}
}
Spring equivalent / Spring 等价:
@GetMapping("/users")
public List<User> listUsers(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "20") int limit
) { ... }
Json - JSON Body / JSON 请求体
Extract and deserialize JSON from request body. 从请求体提取并反序列化 JSON。
#![allow(unused)]
fn main() {
use hiver_extractors::Json;
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
age: Option<u32>,
}
async fn create_user(Json(user): Json<CreateUser>) -> Response {
// user.name, user.email, user.age
}
}
Spring equivalent / Spring 等价:
@PostMapping("/users")
public User createUser(@RequestBody CreateUser user) { ... }
Form - Form Data / 表单数据
Extract URL-encoded form data. 提取 URL 编码的表单数据。
#![allow(unused)]
fn main() {
use hiver_extractors::Form;
use serde::Deserialize;
#[derive(Deserialize)]
struct LoginForm {
username: String,
password: String,
}
async fn login(Form(form): Form<LoginForm>) -> Response {
// form.username, form.password
}
}
Spring equivalent / Spring 等价:
@PostMapping("/login")
public void login(@ModelAttribute LoginForm form) { ... }
State - Application State / 应用状态
Extract shared application state. 提取共享的应用状态。
#![allow(unused)]
fn main() {
use hiver_extractors::State;
use std::sync::Arc;
struct AppState {
db: Database,
config: Config,
}
async fn get_user(
State(state): State<Arc<AppState>>,
Path(id): Path<u64>,
) -> Response {
let user = state.db.find_user(id).await?;
// ...
}
// Setup router with state / 设置带状态的路由
let state = Arc::new(AppState { db, config });
let router = Router::new()
.get("/users/:id", get_user)
.with_state(state);
}
Spring equivalent / Spring 等价:
@Autowired
private UserService userService;
Header - Request Headers / 请求头
Extract values from HTTP headers. 从 HTTP 请求头提取值。
#![allow(unused)]
fn main() {
use hiver_extractors::{Header, NamedHeader};
// Extract specific header / 提取特定头
async fn handler(
Header(auth): Header<String>, // Authorization header
) -> Response {
// ...
}
// Named header / 命名头
async fn handler(
NamedHeader("x-request-id", id): NamedHeader<String>,
) -> Response {
// id = value of x-request-id header
}
// Optional header / 可选头
async fn handler(
HeaderOption(auth): HeaderOption<String>,
) -> Response {
if let Some(auth) = auth {
// Header present
}
}
}
Spring equivalent / Spring 等价:
@GetMapping("/data")
public void getData(@RequestHeader("Authorization") String auth) { ... }
Cookie - Cookies / Cookie
Extract values from cookies. 从 cookie 提取值。
#![allow(unused)]
fn main() {
use hiver_extractors::{Cookie, NamedCookie};
// Named cookie / 命名 cookie
async fn handler(
NamedCookie("session_id", session): NamedCookie<String>,
) -> Response {
// session = cookie value
}
// Optional cookie / 可选 cookie
async fn handler(
CookieOption(session): CookieOption<String>,
) -> Response {
if let Some(session) = session {
// Cookie present
}
}
}
Spring equivalent / Spring 等价:
@GetMapping("/profile")
public void profile(@CookieValue("session_id") String session) { ... }
Custom Extractors / 自定义提取器
Implement the FromRequest trait:
实现 FromRequest trait:
#![allow(unused)]
fn main() {
use hiver_extractors::{FromRequest, ExtractorError, ExtractorFuture};
use hiver_http::Request;
struct CurrentUser {
id: u64,
name: String,
}
impl FromRequest for CurrentUser {
fn from_request(req: &Request) -> ExtractorFuture<Self> {
Box::pin(async move {
// Extract user from token / 从令牌提取用户
let token = req.header("authorization")
.ok_or(ExtractorError::Missing("Authorization".into()))?;
let user = validate_token(token).await
.map_err(|e| ExtractorError::Invalid(e.to_string()))?;
Ok(CurrentUser {
id: user.id,
name: user.name,
})
})
}
}
// Use in handler / 在处理器中使用
async fn profile(user: CurrentUser) -> Response {
// user.id, user.name
}
}
Error Handling / 错误处理
Extractors return ExtractorError on failure:
提取失败时返回 ExtractorError:
#![allow(unused)]
fn main() {
#[derive(Debug, Error)]
pub enum ExtractorError {
#[error("Missing parameter: {0}")]
Missing(String),
#[error("Invalid parameter format: {0}")]
Invalid(String),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("Error: {0}")]
Other(String),
}
}
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
@PathVariable | Path<T> | URL path parameters |
@RequestParam | Query<T> | Query string parameters |
@RequestBody | Json<T> | JSON request body |
@ModelAttribute | Form<T> | Form data |
@RequestHeader | Header<T> | HTTP headers |
@CookieValue | Cookie<T> | Cookies |
@Autowired | State<T> | Dependency injection |
Complete Example / 完整示例
#![allow(unused)]
fn main() {
use hiver_extractors::{Path, Query, Json, State, Header};
use hiver_http::{Response, StatusCode, Body};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
// Application state / 应用状态
struct AppState {
db: Database,
}
// Request types / 请求类型
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
#[derive(Deserialize)]
struct ListParams {
page: Option<u32>,
limit: Option<u32>,
}
// Response types / 响应类型
#[derive(Serialize)]
struct User {
id: u64,
name: String,
email: String,
}
// Handlers / 处理器
async fn list_users(
State(state): State<Arc<AppState>>,
Query(params): Query<ListParams>,
) -> Response {
let page = params.page.unwrap_or(1);
let limit = params.limit.unwrap_or(20);
let users = state.db.list_users(page, limit).await;
json_response(&users)
}
async fn get_user(
State(state): State<Arc<AppState>>,
Path(id): Path<u64>,
) -> Response {
match state.db.find_user(id).await {
Some(user) => json_response(&user),
None => Response::not_found(),
}
}
async fn create_user(
State(state): State<Arc<AppState>>,
Header(auth): Header<String>,
Json(input): Json<CreateUser>,
) -> Response {
// Validate auth token / 验证认证令牌
if !is_valid_token(&auth) {
return Response::unauthorized();
}
let user = state.db.create_user(input).await;
Response::builder()
.status(StatusCode::CREATED)
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&user).unwrap()))
.unwrap()
}
fn json_response<T: Serialize>(data: &T) -> Response {
Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(data).unwrap()))
.unwrap()
}
}
← Previous / 上一页 | Next / 下一页 →
Data Layer / 数据层
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver provides a comprehensive data access layer similar to Spring Data, with repository abstractions, ORM support, and multi-database connectivity.
Status / 状态
This module is currently under active development as part of Phase 8 of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 8 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
RDBC - Database Connectivity / RDBC 数据库连接
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver RDBC provides a unified database client abstraction with connection pooling, similar to JDBC in the Java ecosystem.
Status / 状态
This module is currently under active development as part of Phase 8 of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 8 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
ORM - Object Relational Mapping / ORM 对象关系映射
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver ORM provides ActiveRecord pattern, Model derive macros, QueryBuilder, and relationship mapping similar to Spring Data JPA.
Status / 状态
This module is currently under active development as part of Phase 8 of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 8 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
MongoDB Support / MongoDB 支持
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver provides native MongoDB integration with async driver support and Spring Data MongoDB-like repositories.
Status / 状态
This module is currently under active development as part of Phase 8 of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 8 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Redis Support / Redis 支持
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver provides Redis integration for caching, session storage, and message pub/sub, similar to Spring Data Redis.
Status / 状态
This module is currently under active development as part of Phase 8 of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 8 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Database Migrations / 数据库迁移
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver Flyway provides database schema migration management, similar to Flyway in the Spring ecosystem.
Status / 状态
This module is currently under active development as part of Phase 8 of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 8 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Security / 安全
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver Security provides comprehensive authentication, authorization, and security features similar to Spring Security.
Status / 状态
This module is currently under active development as part of Phase 7+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 7+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
JWT Authentication / JWT 认证
Status: 🔄 In Development 状态: 开发中
Overview / 概述
JSON Web Token authentication support with token generation, validation, and refresh mechanisms.
Status / 状态
This module is currently under active development as part of Phase 7+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 7+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
OAuth2 Support / OAuth2 支持
Status: 🔄 In Development 状态: 开发中
Overview / 概述
OAuth2 client and resource server support for third-party authentication integration.
Status / 状态
This module is currently under active development as part of Phase 7+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 7+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Authorization / 授权
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Role-based access control and method-level authorization annotations.
Status / 状态
This module is currently under active development as part of Phase 7+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 7+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Resilience / 弹性
Status: Phase 4 Complete ✅ 状态: 第4阶段完成 ✅
Hiver provides comprehensive resilience patterns to make your applications fault-tolerant and highly available.
Hiver 提供全面的弹性模式,使您的应用程序具有容错性和高可用性。
Overview / 概述
Resilience patterns help your application handle failures gracefully:
弹性模式帮助您的应用程序优雅地处理故障:
┌─────────────────────────────────────────────────────────────┐
│ Resilience Patterns │
│ 弹性模式 │
├─────────────────────────────────────────────────────────────┤
│ │
│ Circuit Breaker ──► Fail fast when service is down │
│ 熔断器 ──► 服务关闭时快速失败 │
│ │
│ Rate Limiter ──► Control request rate │
│ 限流器 ──► 控制请求速率 │
│ │
│ Retry ──► Automatic retry with backoff │
│ 重试 ──► 带退避的自动重试 │
│ │
│ Timeout ──► Prevent hanging requests │
│ 超时 ──► 防止挂起请求 │
│ │
└─────────────────────────────────────────────────────────────┘
Circuit Breaker / 熔断器
Protect against cascading failures:
防止级联故障:
#![allow(unused)]
fn main() {
use hiver_resilience::{CircuitBreaker, CircuitBreakerConfig};
use std::time::Duration;
// Create circuit breaker / 创建熔断器
let circuit = CircuitBreaker::new(CircuitBreakerConfig {
error_threshold: 0.5, // Open after 50% errors
min_requests: 10, // Need 10 requests
timeout: Duration::from_secs(60), // Stay open for 60s
half_open_max_calls: 3, // Test with 3 calls
});
// Use with async operation / 与异步操作一起使用
async fn call_external_api() -> Result<String, Error> {
circuit.call(|| async {
http_client.get("https://api.example.com/data").await
}).await
}
}
Circuit States / 熔断器状态:
- CLOSED - Normal operation / 正常运行
- OPEN - Failing fast / 快速失败
- HALF-OPEN - Testing recovery / 测试恢复
Rate Limiter / 限流器
Control request rate:
控制请求速率:
#![allow(unused)]
fn main() {
use hiver_resilience::{RateLimiter, RateLimiterType};
// Token bucket rate limiter / Token bucket限流器
let limiter = RateLimiter::builder()
.rate(100) // 100 requests per second
.capacity(200) // Burst up to 200
.limiter_type(RateLimiterType::TokenBucket)
.build();
// Use with async operation / 与异步操作一起使用
async fn process_request() -> Result<Response, Error> {
limiter.acquire().await?; // Wait for permit
handle_request().await
}
}
Retry Policy / 重试策略
Automatic retry with backoff:
带退避的自动重试:
#![allow(unused)]
fn main() {
use hiver_resilience::{RetryPolicy, retry};
use std::time::Duration;
// Exponential backoff / 指数退避
let policy = RetryPolicy::exponential_backoff(
3, // Max 3 retries
Duration::from_secs(1), // Initial delay 1s
);
// Use with async operation / 与异步操作一起使用
async fn call_api() -> Result<String, Error> {
retry(policy, || async {
http_client.get("https://api.example.com").await
}).await
}
}
Timeout / 超时
Enforce request timeouts:
强制执行请求超时:
#![allow(unused)]
fn main() {
use hiver_resilience::Timeout;
use std::time::Duration;
// Create timeout / 创建超时
let timeout = Timeout::new(Duration::from_secs(5));
// Use with async operation / 与异步操作一起使用
async fn call_slow_api() -> Result<String, Error> {
timeout.timeout(|| async {
slow_api_call().await
}).await
}
}
Combining Patterns / 组合模式
Combine multiple resilience patterns:
组合多个弹性模式:
#![allow(unused)]
fn main() {
use hiver_resilience::{CircuitBreaker, RateLimiter, RetryPolicy};
struct ResilientClient {
circuit: CircuitBreaker,
limiter: RateLimiter,
retry: RetryPolicy,
}
impl ResilientClient {
async fn call(&self, request: Request) -> Result<Response, Error> {
// 1. Rate limit / 限流
self.limiter.acquire().await?;
// 2. Circuit breaker / 熔断器
let result = self.circuit.call(|| async {
// 3. Retry / 重试
retry(self.retry.clone(), || async {
http_client.send(request.clone()).await
}).await
}).await;
result
}
}
}
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
@CircuitBreaker | CircuitBreaker | Circuit breaker pattern |
@RateLimiter | RateLimiter | Rate limiting |
@Retry | RetryPolicy | Retry with backoff |
@Timeout | Timeout | Request timeout |
| Resilience4j | hiver-resilience | Resilience library |
Best Practices / 最佳实践
- Use circuit breakers for external calls / 对外部调用使用熔断器
- Rate limit per client / 每客户端限流
- Retry with exponential backoff / 指数退避重试
- Set appropriate timeouts / 设置适当的超时
← Previous / 上一页 | Next / 下一页 →
Observability / 可观测性
Status: Phase 5 Complete ✅ 状态: 第5阶段完成 ✅
Hiver provides comprehensive observability including distributed tracing, metrics, and structured logging.
Hiver 提供全面的可观测性,包括分布式追踪、指标和结构化日志。
Overview / 概述
Observability helps you understand what’s happening in your application:
可观测性帮助您了解应用程序中发生的情况:
┌─────────────────────────────────────────────────────────────┐
│ Observability Stack │
│ 可观测性堆栈 │
├─────────────────────────────────────────────────────────────┤
│ │
│ Tracing ──► Distributed request tracking │
│ 追踪 ──► 分布式请求追踪 │
│ │
│ Metrics ──► Performance and business metrics │
│ 指标 ──► 性能和业务指标 │
│ │
│ Logging ──► Structured application logs │
│ 日志 ──► 结构化应用程序日志 │
│ │
└─────────────────────────────────────────────────────────────┘
Distributed Tracing / 分布式追踪
Track requests across services:
跨服务追踪请求:
#![allow(unused)]
fn main() {
use hiver_observability::{Tracer, Span};
// Create tracer / 创建追踪器
let tracer = Tracer::new("my-service");
// Start span / 开始span
let span = tracer.span("handle_request")
.with_attribute("user_id", "123")
.with_attribute("method", "GET")
.start();
// Enter span context / 进入span上下文
let _guard = span.enter();
// Do work / 执行工作
process_request().await;
// End span / 结束span
span.end();
}
OpenTelemetry Compatibility / OpenTelemetry兼容性:
- Compatible with OpenTelemetry standard
- Export to Jaeger, Zipkin, etc.
Metrics / 指标
Collect application metrics:
收集应用程序指标:
#![allow(unused)]
fn main() {
use hiver_observability::{MetricsRegistry, Counter, Gauge, Histogram};
// Get metrics registry / 获取指标注册表
let metrics = MetricsRegistry::default();
// Counter - Incrementing value / 计数器 - 递增值
let requests = metrics.counter("http_requests_total")
.with_label("method", "GET")
.with_label("status", "200")
.build();
requests.inc();
// Gauge - Current value / 仪表 - 当前值
let active_connections = metrics.gauge("active_connections").build();
active_connections.set(42);
// Histogram - Distribution / 直方图 - 分布
let request_duration = metrics.histogram("request_duration_seconds")
.with_buckets(vec![0.1, 0.5, 1.0, 2.0, 5.0])
.build();
let start = Instant::now();
process_request().await;
request_duration.observe(start.elapsed().as_secs_f64());
}
Prometheus Compatibility / Prometheus兼容性:
- Prometheus-compatible metrics
- Expose
/metricsendpoint
Structured Logging / 结构化日志
Structured logging with context:
带上下文的结构化日志:
#![allow(unused)]
fn main() {
use hiver_observability::log;
use tracing::{info, error, warn};
// Basic logging / 基本日志
log::info!("User logged in");
log::error!("Failed to process request: {}", error);
// Structured logging / 结构化日志
log::info!(
user_id = 123,
action = "login",
ip = "127.0.0.1",
"User logged in"
);
// Log levels / 日志级别
log::trace!("Detailed debug info");
log::debug!("Debug information");
log::info!("Informational message");
log::warn!("Warning message");
log::error!("Error message");
}
Log Formats / 日志格式:
- Text - Human-readable / 人类可读
- JSON - Machine-readable / 机器可读
Hiver Logging / Hiver 日志
Hiver provides a unified logging system with two modes optimized for different environments:
Hiver 提供统一的日志系统,具有针对不同环境优化的两种模式:
| Mode | Use Case | Features |
|---|---|---|
| Verbose | Development | Timestamp, PID, Thread, Module, File location |
| Simple | Production | Level + Module + Message only (~30% faster) |
use hiver_observability::log::{Logger, LoggerConfig, LogLevel, LogMode};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Configure logging based on environment
let config = LoggerConfig {
level: LogLevel::Info,
mode: LogMode::from_profile(Some("dev")), // Auto: dev→Verbose, prod→Simple
..Default::default()
};
Logger::init_with_config(config)?;
// Use standard tracing macros
tracing::info!("Application started");
tracing::warn!("This is a warning");
tracing::error!("This is an error");
Ok(())
}
Configuration Options / 配置选项:
# Environment variables / 环境变量
export HIVER_LOG_LEVEL=DEBUG # TRACE, DEBUG, INFO, WARN, ERROR
export HIVER_LOG_MODE=verbose # verbose, simple
export HIVER_PROFILE=prod # dev, prod (affects default mode)
# Configuration file (hiver.toml) / 配置文件
[logging]
level = "INFO"
mode = "verbose" # or "simple"
format = "pretty" # pretty, compact, json
file = "logs/application.log"
[logging.rotation]
policy = "daily" # daily, hourly, never
max_files = 7
Output Comparison / 输出对比:
# Verbose mode (development) / 详细模式(开发环境)
2026-01-29 22:35:42.872 |INFO| 55377 [main ] n.http.server : Request received
# Simple mode (production) / 精简模式(生产环境)
INFO n.http.server: Request received
Spring Boot Style Startup / Spring Boot 风格启动:
use hiver_observability::log::Logger;
#[cfg(feature = "hiver-format")]
use hiver_observability::{Banner, StartupLogger};
fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "hiver-format")]
{
// Print banner / 打印横幅
Banner::print("MyApp", "0.1.0", 8080);
// Initialize logging / 初始化日志
Logger::init_spring_style()?;
// Log startup / 记录启动信息
let startup = StartupLogger::new();
startup.log_starting("MyApplication");
startup.log_profile(Some("dev"));
startup.log_server_started(8080, startup.elapsed_ms());
}
tracing::info!(target: "my.app", "Application running");
Ok(())
}
Startup Output / 启动输出:
_ _ ___ ____
| \ | | _____ ___ _ ___ / _ \/ ___|
| \| |/ _ \ \/ / | | / __| | | \___ \
| |\ | __/> <| |_| \__ \ |_| |___) |
|_| \_|\___/_/\_\\__,_|___/\___/|_____|
:: MyApp :: (v0.1.0)
2026-01-29T10:30:45 123 INFO 46293 --- [ main] my.Application : Starting Application
2026-01-29T10:30:45 123 INFO 46293 --- [ main] my.Application : Active profile: dev
2026-01-29T10:30:45 456 INFO 46293 --- [ main] o.s.b.w.e.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http)
2026-01-29T10:30:45 456 INFO 46293 --- [ main] my.Application : Started Application in 0.333 seconds
Features / 特性:
- Profile-based auto-switching (dev→verbose, prod→simple) / 基于配置文件的自动切换
- ~30% faster logging in Simple mode / Simple 模式快约 30%
- ANSI color support / ANSI 颜色支持
- File output with rotation / 带轮转的文件输出
- OpenTelemetry integration / OpenTelemetry 集成
See Logging Configuration Guide for detailed documentation.
详细文档请参阅 日志配置指南。
Integration / 集成
With HTTP Server / 与HTTP服务器集成
#![allow(unused)]
fn main() {
use hiver_observability::{tracer, metrics, log};
async fn handler(req: Request) -> Response {
// Start span / 开始span
let span = tracer().span("http_request")
.with_attribute("method", req.method().as_str())
.with_attribute("path", req.uri().path())
.start();
let _guard = span.enter();
// Log request / 记录请求
log::info!(
method = req.method().as_str(),
path = req.uri().path(),
"Incoming request"
);
// Record metric / 记录指标
metrics().counter("http_requests_total")
.with_label("method", req.method().as_str())
.inc();
// Process request / 处理请求
let response = process_request(req).await;
response
}
}
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
| Spring Cloud Sleuth | Tracer | Distributed tracing |
| Micrometer | MetricsRegistry | Metrics collection |
| Logback/Log4j | Logger | Structured logging |
| Actuator | - | Health/metrics endpoints |
← Previous / 上一页 | Next / 下一页 →
Web3 Integration / Web3集成
Status: Phase 6 Complete ✅ 状态: 第6阶段完成 ✅
Hiver provides native Web3 support for blockchain applications.
Hiver 为区块链应用程序提供原生 Web3 支持。
Overview / 概述
Web3 features include:
Web3 功能包括:
- Chain Abstraction / 链抽象 - EIP-155 chain ID support with pre-configured chains
- Wallet Management / 钱包管理 - Local wallet with signing capabilities
- Transaction Building / 交易构建 - EIP-1559 and Legacy transaction types
- RPC Client / RPC客户端 - HTTP client for blockchain node communication
- Smart Contract Interface / 智能合约接口 - ABI encoding/decoding with ERC20/ERC721 standards
Quick Start / 快速开始
use hiver_web3::{
ChainConfig, ChainId, Eip155Chain,
LocalWallet, Address, Contract, FunctionSelector, RpcClient
};
async fn run() -> Result<(), Box<dyn std::error::Error>> {
// Connect to Ethereum / 连接到以太坊
let chain_config = ChainConfig::ethereum_mainnet();
let rpc = RpcClient::new(&chain_config.rpc_urls[0])?;
// Create wallet / 创建钱包
let wallet = LocalWallet::new(Eip155Chain::ETHEREUM);
// Get address / 获取地址
let address = wallet.address();
println!("Wallet address: {}", address.to_checksummed());
// Interact with ERC20 contract / 与ERC20合约交互
let usdc_address = Address::from_hex("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")?;
let contract = Contract::new(usdc_address, &rpc);
// Get balance / 查询余额
let selector = FunctionSelector::from_signature("balanceOf(address)");
let mut call_data = Vec::new();
call_data.extend_from_slice(&selector.0);
call_data.extend_from_slice(&[0u8; 12]); // Pad to 32 bytes
call_data.extend_from_slice(&address.0);
let result = rpc.call_contract(&usdc_address, &call_data, hiver_web3::BlockNumber::Latest).await?;
Ok(())
}
Features / 功能
Chain Configuration / 链配置
use hiver_web3::{ChainConfig, ChainId, Eip155Chain};
// Pre-configured chains / 预配置的链
let mainnet = ChainConfig::ethereum_mainnet();
let sepolia = ChainConfig::sepolia_testnet();
let polygon = ChainConfig::polygon();
let base = ChainConfig::base();
// Custom chain / 自定义链
let custom = ChainConfig::new(
Eip155Chain::custom(12345),
"My Custom Chain",
vec!["https://rpc.example.com".to_string()],
);
Wallet Management / 钱包管理
use hiver_web3::{LocalWallet, Wallet, Address};
async fn run() -> Result<(), Box<dyn std::error::Error>> {
// Create new wallet / 创建新钱包
let wallet = LocalWallet::new(hiver_web3::Eip155Chain::ETHEREUM);
let address = wallet.address();
println!("Address: {}", address.to_checksummed());
// Sign message / 签名消息
let message = b"Hello, Web3!";
let signature = wallet.sign(message)?;
// Sign hash / 签名哈希
let hash = [0u8; 32];
let signature = wallet.sign_hash(&hash)?;
Ok(())
}
Transaction Building / 交易构建
use hiver_web3::{
TransactionBuilder, TxType, Address,
Eip155Chain, LocalWallet
};
async fn run() -> Result<(), Box<dyn std::error::Error>> {
// Build EIP-1559 transaction / 构建EIP-1559交易
let tx = TransactionBuilder::new()
.ty(TxType::Eip1559)
.chain_id(1)
.nonce(0)
.max_priority_fee_per_gas(1_500_000_000)
.max_fee_per_gas(30_000_000_000)
.gas_limit(21_000)
.to(Some(Address::from_hex("0x...")?))
.value(1000000000000000) // 0.001 ETH
.build()?;
// Sign transaction / 签名交易
let wallet = LocalWallet::new(Eip155Chain::ETHEREUM);
let signed_tx = wallet.sign_transaction(&tx)?;
Ok(())
}
RPC Client / RPC客户端
use hiver_web3::{RpcClient, Address, BlockNumber};
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let rpc = RpcClient::new("https://eth.llamarpc.com")?;
// Get block number / 获取区块号
let block_number = rpc.get_block_number().await?;
println!("Latest block: {}", block_number);
// Get balance / 获取余额
let address = Address::from_hex("0x...")?;
let balance = rpc.get_balance(&address, BlockNumber::Latest).await?;
// Get transaction count / 获取交易计数
let nonce = rpc.get_transaction_count(&address, BlockNumber::Latest).await?;
Ok(())
}
Smart Contracts / 智能合约
use hiver_web3::{Contract, FunctionSelector, Address, RpcClient};
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let rpc = RpcClient::new("https://eth.llamarpc.com")?;
let contract_address = Address::from_hex("0x...")?;
let contract = Contract::new(contract_address, &rpc);
// ERC20 balanceOf / ERC20余额查询
let user_address = Address::from_hex("0x...")?;
let selector = FunctionSelector::from_signature("balanceOf(address)");
let mut call_data = Vec::new();
call_data.extend_from_slice(&selector.0);
call_data.extend_from_slice(&[0u8; 12]);
call_data.extend_from_slice(&user_address.0);
let result = contract.call_read_only(&selector, &call_data).await?;
// Using ERC20 constants / 使用ERC20常量
use hiver_web3::ERC20;
assert_eq!(ERC20::BALANCE_OF.0, [0x70, 0xa0, 0x82, 0x31]);
assert_eq!(ERC20::TRANSFER.0, [0xa9, 0x05, 0x9c, 0xbb]);
Ok(())
}
API Reference / API参考
ChainId / 链ID
#![allow(unused)]
fn main() {
pub enum ChainId {
Ethereum, // 1
Polygon, // 137
Bsc, // 56
Arbitrum, // 42161
Optimism, // 10
Base, // 8453
Avalanche, // 43114
Fantom, // 250
Sepolia, // 11155111
Custom(u64),
}
}
Transaction Types / 交易类型
#![allow(unused)]
fn main() {
pub enum TxType {
Legacy = 0, // Legacy transaction
AccessList = 1, // Access list transaction
Eip1559 = 2, // EIP-1559 transaction
}
}
ERC20/ERC721 Selectors / 标准选择器
#![allow(unused)]
fn main() {
// ERC20
pub const BALANCE_OF: FunctionSelector; // 0x70a08231
pub const TRANSFER: FunctionSelector; // 0xa9059cbb
pub const APPROVE: FunctionSelector; // 0x095ea7b3
pub const TOTAL_SUPPLY: FunctionSelector; // 0x18160ddd
// ERC721
pub const OWNER_OF: FunctionSelector; // 0x6352211e
pub const TRANSFER_FROM: FunctionSelector; // 0x23b872dd
pub const SAFE_TRANSFER_FROM: FunctionSelector; // 0x4a39dc06
}
Implementation Status / 实现状态
Phase 6: Web3 Support ✅ (Complete / 已完成)
- Chain abstraction (EIP-155)
- Wallet with signing
- Transaction builder (EIP-1559, Legacy)
- RPC client (HTTP)
- Contract interface (ABI)
- ERC20/ERC721 standards
Future Enhancements / 未来增强
- WebSocket RPC support
- Event log filtering
- Contract deployment
- Hardware wallet support
- Multi-chain transaction relay
← Previous / 上一页 | Next / 下一页 →
Testing / 测试
Status: Phase 3+ Available ✅ 状态: 第3阶段+可用 ✅
Hiver provides comprehensive testing support including unit tests, integration tests, and data layer testing. Hiver 提供全面的测试支持,包括单元测试、集成测试和数据层测试。
Overview / 概述
Testing strategies: 测试策略:
- Unit Tests / 单元测试 — Test individual handlers and extractors
- Integration Tests / 集成测试 — Test with
TestClient - E2E Tests / 端到端测试 — Test full application flow
- Data Layer Tests / 数据层测试 — Test repositories and ORM models
Unit Testing / 单元测试
Testing Handlers / 测试处理器
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_handler() -> std::io::Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let response = handler(Request::default()).await;
assert_eq!(response.status(), StatusCode::OK);
Ok(())
})
}
}
}
Testing Extractors / 测试提取器
#![allow(unused)]
fn main() {
#[test]
fn test_path_extractor() -> std::io::Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let req = Request::builder()
.uri("/users/123")
.build();
let id: Path<u64> = Path::from_request(&req).await.unwrap();
assert_eq!(id.0, 123);
Ok(())
})
}
}
Testing JSON Serialization / 测试 JSON 序列化
#![allow(unused)]
fn main() {
#[test]
fn test_json_response() {
let user = User {
id: 1,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
};
let json = serde_json::to_string(&user).unwrap();
assert!(json.contains("Alice"));
let deserialized: User = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.id, 1);
}
}
Integration Testing / 集成测试
TestClient / 测试客户端
#![allow(unused)]
fn main() {
use hiver_test::TestClient;
#[test]
fn test_api() -> std::io::Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let app = create_app();
let client = TestClient::new(app);
// Test GET / 测试 GET
let response = client.get("/api/users").send().await;
assert_eq!(response.status(), 200);
// Test POST / 测试 POST
let response = client.post("/api/users")
.json(&user_data)
.send()
.await;
assert_eq!(response.status(), 201);
// Test with headers / 测试带请求头
let response = client.get("/api/profile")
.header("Authorization", "Bearer token123")
.send()
.await;
assert_eq!(response.status(), 200);
Ok(())
})
}
}
Testing Middleware / 测试中间件
#![allow(unused)]
fn main() {
#[test]
fn test_cors_middleware() -> std::io::Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let cors = Cors::new()
.allow_origin("*")
.allow_methods(["GET", "POST"]);
let app = Router::new()
.middleware(Arc::new(cors))
.get("/", || async { "ok" });
let client = TestClient::new(app);
let response = client.get("/").send().await;
assert_eq!(
response.headers().get("Access-Control-Allow-Origin").unwrap(),
"*"
);
Ok(())
})
}
}
Data Layer Testing / 数据层测试
Testing Repository / 测试仓库
#![allow(unused)]
fn main() {
use hiver_data_rdbc::DatabaseClient;
use hiver_data_orm::prelude::*;
#[test]
fn test_repository_crud() -> Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
// Use test database / 使用测试数据库
let client = DatabaseClient::connect("sqlite::memory:").await?;
let repo = UserRepository::new(client);
// Create / 创建
let user = repo.save(User {
name: "Alice".to_string(),
email: "alice@test.com".to_string(),
..Default::default()
}).await?;
assert!(user.id > 0);
// Read / 读取
let found = repo.find_by_id(user.id).await?;
assert_eq!(found.unwrap().name, "Alice");
// Update / 更新
let updated = repo.save(User {
id: user.id,
name: "Alice Updated".to_string(),
email: "alice@test.com".to_string(),
}).await?;
assert_eq!(updated.name, "Alice Updated");
// Delete / 删除
repo.delete_by_id(user.id).await?;
assert!(repo.find_by_id(user.id).await?.is_none());
Ok(())
})
}
}
Testing Query Methods / 测试查询方法
#![allow(unused)]
fn main() {
#[test]
fn test_derived_queries() -> Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let repo = setup_test_repo().await?;
// Test findBy... / 测试 findBy...
let users = repo.find_by_email("alice@test.com").await?;
assert_eq!(users.len(), 1);
// Test findBy...And... / 测试 findBy...And...
let users = repo.find_by_name_and_email("Alice", "alice@test.com").await?;
assert_eq!(users.len(), 1);
// Test pagination / 测试分页
let page = repo.find_all(PageRequest::of(0, 10)).await?;
assert!(page.total_elements() > 0);
Ok(())
})
}
}
Testing Migrations / 测试迁移
#![allow(unused)]
fn main() {
use hiver_flyway::{Flyway, MigrationConfig};
#[test]
fn test_migrations() -> Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let mut flyway = Flyway::new(MigrationConfig {
locations: vec!["migrations".to_string()],
..Default::default()
});
let result = flyway.migrate(&mut conn).await?;
assert_eq!(result.successful_migrations, 3);
Ok(())
})
}
}
E2E Testing / 端到端测试
#![allow(unused)]
fn main() {
#[test]
fn test_full_flow() -> std::io::Result<()> {
let rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let server = start_test_server().await;
let client = reqwest::Client::new();
// Create user / 创建用户
let response = client
.post("http://localhost:8080/api/users")
.json(&json!({"name": "Alice", "email": "alice@test.com"}))
.send().await.unwrap();
assert_eq!(response.status(), 201);
// Get user / 获取用户
let response = client
.get("http://localhost:8080/api/users/1")
.send().await.unwrap();
assert_eq!(response.status(), 200);
Ok(())
})
}
}
Test Organization / 测试组织
my-app/
├── src/
│ ├── lib.rs
│ └── handler.rs # #[cfg(test)] mod tests { ... }
├── tests/
│ ├── api_test.rs # Integration tests
│ └── data_test.rs # Data layer tests
└── migrations/
├── V1__create_users.sql
└── V2__add_posts.sql
Best Practices / 最佳实践
- Test in isolation — mock external dependencies / 隔离测试,模拟外部依赖
- Use
sqlite::memory:for data tests — fast, no setup / 数据测试用内存 SQLite - Test error cases — verify error responses / 测试错误情况
- Use
TestClientfor handler tests — no real HTTP needed / 用 TestClient 测试处理器 - Run migrations before data tests — ensure schema is current / 数据测试前先跑迁移
← Previous / 上一页 | Next / 下一页 →
Service Discovery / 服务发现
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Service registration and discovery with Consul and Nacos support, similar to Spring Cloud Discovery.
Status / 状态
This module is currently under active development as part of Phase 4+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 4+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
API Gateway / API 网关
Status: 🔄 In Development 状态: 开发中
Overview / 概述
API gateway pattern with routing, rate limiting, and load balancing.
Status / 状态
This module is currently under active development as part of Phase 4+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 4+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Apache Kafka / Apache Kafka
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Kafka producer and consumer integration with async support, similar to Spring Kafka.
Status / 状态
This module is currently under active development as part of Phase 7+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 7+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
AMQP / RabbitMQ / AMQP / RabbitMQ
Status: 🔄 In Development 状态: 开发中
Overview / 概述
AMQP protocol support with RabbitMQ integration, similar to Spring AMQP.
Status / 状态
This module is currently under active development as part of Phase 7+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 7+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
HTTP Client - Feign / HTTP 客户端
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Declarative HTTP client similar to Spring Cloud OpenFeign.
Status / 状态
This module is currently under active development as part of Phase 4+ of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Phase 4+ 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
AI Integration / AI 集成
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Hiver provides AI/LLM integration support for building intelligent applications.
Status / 状态
This module is currently under active development as part of Planned of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Planned 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
OpenAI Integration / OpenAI 集成
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Integration with OpenAI GPT models for chat completions, embeddings, and function calling.
Status / 状态
This module is currently under active development as part of Planned of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Planned 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Anthropic Integration / Anthropic 集成
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Integration with Anthropic Claude models for AI-powered features.
Status / 状态
This module is currently under active development as part of Planned of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Planned 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
Ollama Integration / Ollama 集成
Status: 🔄 In Development 状态: 开发中
Overview / 概述
Local LLM support via Ollama for privacy-sensitive AI applications.
Status / 状态
This module is currently under active development as part of Planned of the Hiver roadmap.
该模块目前正处于 Hiver 路线图 Planned 的积极开发中。
📝 Documentation is being written alongside implementation. Check back soon! 📝 文档正在与实现同步编写,请稍后查看!
API Reference / API 参考
Status: 62 Crates, 10 Domains / 62 个 Crate,10 个功能域 状态: 全阶段完成 ✅
Hiver provides comprehensive API documentation across multiple channels. Hiver 通过多个渠道提供全面的 API 文档。
Documentation Resources / 文档资源
| Resource / 资源 | Link / 链接 | Description / 描述 |
|---|---|---|
| AI-Optimized Reference | AGENTS.md | Compact LLM-injectable reference (62 crates) |
| JSON Schema | api-schema.json | Machine-parseable API catalog |
| Full API Reference | full-api-reference.md | Human-readable with code examples |
| Annotations Reference | annotations-reference.md | All 150+ procedural macros |
| Codemap | CODEMAP.md | Full crate reference, dependency graph |
| docs.rs | docs.rs/hiver | Auto-generated rustdoc |
Architecture Domains / 架构域
Runtime & Core / 运行时与核心
| Crate | Description / 描述 |
|---|---|
hiver-runtime | Custom async runtime (io-uring/epoll/kqueue) |
hiver-core | Core types, error handling |
hiver-http | HTTP/1.1 server, Request, Response |
hiver-router | Router with path params, state, middleware |
hiver-middleware | Middleware trait (CORS, compression, timeout) |
hiver-extractors | Request parameter extraction |
hiver-response | Response builders |
Data Layer / 数据层
| Crate | Description / 描述 |
|---|---|
hiver-data-commons | Repository traits, Page/Sort, entity metadata |
hiver-data-rdbc | Reactive database client, connection pool, RowMapper |
hiver-data-orm | ActiveRecord, Model derive, QueryBuilder, Relationships, Migrations |
hiver-data-redis | Redis template, distributed locks, caching |
hiver-data-mongodb | MongoDB template and repository |
hiver-flyway | Database migration framework |
hiver-data-annotations | @Entity, @Table, @Column, @Id |
hiver-data-macros | #[derive(Model)], #[derive(Repository)] |
Resilience & Observability / 弹性与可观测性
| Crate | Description / 描述 |
|---|---|
hiver-resilience | Circuit breaker, rate limiter, retry, timeout |
hiver-observability | Distributed tracing, metrics, structured logging |
Web3 / 区块链
| Crate | Description / 描述 |
|---|---|
hiver-web3 | Chain abstraction, wallet, transactions, RPC, smart contracts |
IoC & AOP / 控制反转与切面
| Crate | Description / 描述 |
|---|---|
hiver-ioc | Dependency injection container, @Component, @Autowired |
hiver-aop | Aspect-oriented programming, @Aspect |
Enterprise / 企业级
| Crate | Description / 描述 |
|---|---|
hiver-security | Authentication, authorization, password encoding |
hiver-validation | Bean Validation (JSR 380) |
hiver-validation-annotations | @NotNull, @Size, @Email, @Pattern |
hiver-scheduling | @Scheduled cron/fixed-rate/delay tasks |
hiver-i18n | Internationalization, MessageSource |
AI & Cloud / AI 与云
| Crate | Description / 描述 |
|---|---|
hiver-ai | AI/LLM integration, chat models, embeddings |
hiver-agent | AI agent framework (Spring AI Agent) |
hiver-cloud | Cloud-native support, service discovery |
hiver-ws | WebSocket server/client |
Tooling & Starter / 工具与启动器
| Crate | Description / 描述 |
|---|---|
hiver-macros | 150+ procedural macros |
hiver-lombok | @Data, @Getter, @Setter, @Builder |
hiver-retry-macros | @Retryable, @Recover |
hiver-spel | Spring Expression Language engine |
hiver-modulith | Modular monolith support |
hiver-starter | Auto-configuration, one-line startup |
hiver-test | Test utilities, TestClient |
Quick API Patterns / 常用 API 模式
Server Startup / 启动服务器
use hiver_http::Server;
use hiver_router::Router;
fn main() -> std::io::Result<()> {
let mut rt = hiver_runtime::Runtime::new()?;
rt.block_on(async {
let app = Router::new()
.get("/", || async { "Hello, Hiver!" });
Server::bind("0.0.0.0:8080").run(app).await
})
}
Using Starter / 使用启动器
use hiver_starter::HiverApp;
fn main() -> std::io::Result<()> {
HiverApp::new()
.with_router(Router::new().get("/", handler))
.run()
}
Data Repository / 数据仓库
#![allow(unused)]
fn main() {
use hiver_data_orm::prelude::*;
use hiver_data_annotations::{Entity, Table, Id, Column};
#[derive(Entity, Table, Model)]
#[table_name = "users"]
struct User {
#[id]
id: i64,
#[column]
name: String,
email: String,
}
// Auto-generated by #[derive(Repository)]
impl UserRepository {
async fn find_by_email(&self, email: &str) -> Result<Option<User>> { ... }
async fn find_by_name_and_email(&self, name: &str, email: &str) -> Result<Vec<User>> { ... }
}
}
← Previous / 上一页 | Next / 下一页 →
Annotations Reference / 注解参考
Status: ✅ Available 状态: 可用
Overview / 概述
Hiver provides 40+ Spring-like annotations via procedural macros for declarative programming.
Hiver 通过过程宏提供 40+ 类 Spring 注解,支持声明式编程。
Core Annotations / 核心注解
| Annotation | Description | Spring Equivalent |
|---|---|---|
#[handler] | HTTP handler method | @RequestMapping |
#[get("/path")] | GET endpoint | @GetMapping |
#[post("/path")] | POST endpoint | @PostMapping |
#[middleware] | Middleware component | @Component + Filter |
#[inject] | Dependency injection | @Autowired |
Data Annotations / 数据注解
| Annotation | Description | Spring Equivalent |
|---|---|---|
#[derive(Model)] | ORM model derive | @Entity |
#[derive(Repository)] | Repository derive | @Repository |
#[derive(PropertiesConfig)] | Config binding | @ConfigurationProperties |
📝 Full annotation reference is being compiled.
Configuration / 配置
Status: Phase 2+ Available ✅ 状态: 第2阶段+可用 ✅
Hiver provides flexible configuration management similar to Spring Boot, with multi-format support, profiles, and auto-configuration. Hiver 提供灵活的配置管理,类似于 Spring Boot,支持多格式、配置文件和自动配置。
Overview / 概述
Configuration features: 配置功能:
- Multiple Formats / 多格式 — Properties, YAML, TOML, JSON
- Environment Variables / 环境变量 — Override any config value
- Profiles / 配置文件 — Environment-specific configurations (dev/prod/test)
- Auto-Configuration / 自动配置 — Convention-over-configuration via
hiver-starter - Type-Safe Binding / 类型安全绑定 —
#[derive(PropertiesConfig)]
Configuration Files / 配置文件
Hiver looks for configuration files in order of priority: Hiver 按优先级顺序查找配置文件:
hiver.toml(preferred / 推荐)application.yml/application.yamlapplication.propertiesapplication.json
TOML (Recommended) / TOML(推荐)
[server]
host = "0.0.0.0"
port = 8080
workers = 4
[database]
url = "postgres://localhost/mydb"
pool_size = 10
timeout_secs = 30
[logging]
level = "INFO"
mode = "verbose" # verbose | simple
format = "pretty" # pretty | compact | json
[resilience.circuit_breaker]
error_threshold = 0.5
min_requests = 10
timeout_secs = 60
[resilience.rate_limiter]
rate = 100
capacity = 200
YAML / YAML
server:
host: 0.0.0.0
port: 8080
workers: 4
database:
url: postgres://localhost/mydb
pool_size: 10
logging:
level: INFO
mode: verbose
Properties / Properties
server.host=0.0.0.0
server.port=8080
database.url=postgres://localhost/mydb
logging.level=INFO
Type-Safe Configuration / 类型安全配置
#![allow(unused)]
fn main() {
use hiver_config::{Config, PropertiesConfig};
use serde::Deserialize;
#[derive(PropertiesConfig, Deserialize)]
#[prefix = "server"]
struct ServerConfig {
host: String,
port: u16,
workers: Option<usize>,
}
#[derive(PropertiesConfig, Deserialize)]
#[prefix = "database"]
struct DatabaseConfig {
url: String,
pool_size: Option<u32>,
timeout_secs: Option<u64>,
}
// Load configuration / 加载配置
let config = Config::load()?;
let server: ServerConfig = config.get()?;
let db: DatabaseConfig = config.get()?;
}
Environment Variables / 环境变量
Override any config value with environment variables using HIVER_ prefix:
使用 HIVER_ 前缀的环境变量覆盖任何配置值:
# Server config / 服务器配置
export HIVER_SERVER_PORT=9090
export HIVER_SERVER_HOST=0.0.0.0
# Database config / 数据库配置
export HIVER_DATABASE_URL=postgres://prod-server/mydb
export HIVER_DATABASE_POOL_SIZE=20
# Logging config / 日志配置
export HIVER_LOG_LEVEL=DEBUG
export HIVER_LOG_MODE=simple
# Active profile / 激活的配置文件
export HIVER_PROFILE=prod
Profiles / 配置文件
Environment-specific configurations with file naming convention:
使用文件命名约定的环境特定配置:
config/
├── hiver.toml # Default / 默认
├── hiver-dev.toml # Development / 开发
├── hiver-prod.toml # Production / 生产
└── hiver-test.toml # Testing / 测试
#![allow(unused)]
fn main() {
use hiver_config::{Config, Profile};
// Auto-detect from HIVER_PROFILE env / 从环境变量自动检测
let config = Config::builder()
.with_profile(Profile::from_env())
.build()?;
// Explicit profile / 显式指定
let config = Config::builder()
.with_profile(Profile::Production)
.build()?;
}
Profile-specific overrides / 配置文件覆盖:
# hiver-dev.toml
[logging]
level = "DEBUG"
mode = "verbose"
[database]
url = "postgres://localhost/mydb_dev"
# hiver-prod.toml
[logging]
level = "WARN"
mode = "simple"
[database]
url = "postgres://prod-server/mydb"
pool_size = 50
Auto-Configuration / 自动配置
hiver-starter provides Spring Boot-style auto-configuration:
hiver-starter 提供 Spring Boot 风格的自动配置:
use hiver_starter::HiverApp;
use hiver_router::Router;
fn main() -> std::io::Result<()> {
HiverApp::new()
.with_router(Router::new()
.get("/", handler)
.get("/users", list_users)
)
.run()
// Auto-configures: runtime, HTTP server, logging, middleware
// 自动配置:运行时、HTTP 服务器、日志、中间件
}
Auto-configured defaults / 自动配置默认值:
| Setting | Default | Override |
|---|---|---|
| Server host | 0.0.0.0 | HIVER_SERVER_HOST |
| Server port | 8080 | HIVER_SERVER_PORT |
| Workers | CPU cores | HIVER_SERVER_WORKERS |
| Log level | INFO | HIVER_LOG_LEVEL |
| Log mode | verbose (dev) / simple (prod) | HIVER_LOG_MODE |
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
@ConfigurationProperties | #[derive(PropertiesConfig)] | Type-safe config binding |
@Value | config.get::<T>() | Single value extraction |
application.yml | hiver.toml / application.yml | Config file |
@Profile | Profile enum | Environment profiles |
spring.profiles.active | HIVER_PROFILE | Active profile |
@SpringBootApplication | HiverApp::new() | Auto-configuration |
← Previous / 上一页 | Next / 下一页 →
Performance / 性能
Status: Phase 7 Complete ✅ (Performance & Hardening) 状态: 第7阶段完成 ✅(性能与加固)
Hiver is designed for high performance from the ground up with a thread-per-core architecture and io-uring-first I/O model. Hiver 从设计之初就追求高性能,采用 thread-per-core 架构和 io-uring-first I/O 模型。
Performance Goals / 性能目标
| Metric | Target | Achieved |
|---|---|---|
| QPS (simple echo) | 1M+ | ✅ Phase 7 |
| P99 latency (no middleware) | < 1ms | ✅ Phase 7 |
| Memory (idle) | < 10MB | ✅ Phase 7 |
| Startup time | < 50ms | ✅ Phase 7 |
Architecture Choices / 架构选择
Thread-per-Core / Thread-per-Core
- No work stealing — each core owns its task queue
- Zero lock contention on hot paths
- Better CPU cache locality
- Linear scalability with core count
Core 0 ──► Task Queue ──► io-uring/epoll ──► Handlers
Core 1 ──► Task Queue ──► io-uring/epoll ──► Handlers
Core 2 ──► Task Queue ──► io-uring/epoll ──► Handlers
io-uring First / io-uring 优先
- 70% fewer syscalls vs epoll (batched submission)
- 40% lower latency on Linux 5.1+
- Automatic fallback to epoll (Linux) / kqueue (macOS)
- Zero-copy buffer management via
Bytes
Zero-Copy I/O / 零拷贝 I/O
- Request/response body uses
Bytesfor zero-copy transfer - Minimal heap allocations on hot paths
- Efficient buffer pooling
Runtime Benchmarks / 运行时基准
Hiver includes a comprehensive benchmark suite using Criterion:
| Benchmark | Description |
|---|---|
| P1: Timer Wheel | Timer scheduling throughput |
| P2: MPSC Channel | Multi-producer single-channel throughput |
| P3: TCP Echo | Raw TCP echo latency |
| P4: HTTP Echo | HTTP request/response latency |
| P5: Router Matching | Route resolution speed |
| P6: Middleware Chain | Middleware overhead measurement |
| P7: Serialization | JSON serialization throughput |
| P8: Concurrent Connections | Max concurrent connection scaling |
| P9: Memory Footprint | Idle and peak memory usage |
| P10-P13: Mixed Workloads | Combined read/write/update benchmarks |
Run benchmarks / 运行基准测试:
cargo bench
TechEmpower Benchmark / TechEmpower 基准
Hiver includes a TechEmpower-compatible benchmark application:
# Build optimized binary / 构建优化二进制
cargo build --release --bin techempower_benchmark
# Run / 运行
./target/release/techempower_benchmark
Fuzzing / 模糊测试
Built-in fuzz targets for security-critical parsers:
cargo install cargo-fuzz
cd fuzzers
cargo fuzz run http_request_parsing
cargo fuzz run router_matching
cargo fuzz run compression
Optimization Tips / 优化技巧
Linux (Production) / Linux(生产环境)
- Enable io-uring — requires Linux kernel 5.1+, automatic on
hiver-runtime - Tune io-uring SQ/CQ sizes —
IoUringDriver::with_sq_entries(256) - CPU affinity — bind each runtime thread to a specific core
- Disable unnecessary middleware — each middleware adds latency
macOS (Development) / macOS(开发环境)
- kqueue driver — automatic, no configuration needed
- Use
releasemode —cargo run --releasefor accurate perf testing
General / 通用
- Reuse
Bytesbuffers — avoid unnecessary cloning - Use
&stroverStringin handlers when possible - Keep middleware chains short — minimize per-request overhead
- Monitor with
hiver-observability— identify bottlenecks via tracing
Performance Monitoring / 性能监控
#![allow(unused)]
fn main() {
use hiver_observability::{MetricsRegistry, Histogram};
use std::time::Instant;
let metrics = MetricsRegistry::default();
let latency = metrics.histogram("http_request_duration")
.with_buckets(vec![0.1, 0.5, 1.0, 2.0, 5.0])
.build();
async fn handler(req: Request) -> Response {
let start = Instant::now();
let resp = process(req).await;
latency.observe(start.elapsed().as_secs_f64());
resp
}
}
← Previous / 上一页 | Next / 下一页 →
Security / 安全
Status: Phase 3+ Available ✅ 状态: 第3阶段+可用 ✅
Hiver provides comprehensive security features inspired by Spring Security. Hiver 提供受 Spring Security 启发的全面安全功能。
Overview / 概述
Security features: 安全功能:
- Authentication / 身份验证 — User authentication with multiple mechanisms
- Authorization / 授权 — Role-based and expression-based access control
- Method Security / 方法安全 —
@PreAuthorize,@Securedannotations - Password Encoding / 密码编码 — BCrypt, Argon2 support
- JWT Authentication / JWT 认证 — Token-based stateless auth
- Input Validation / 输入验证 — Bean Validation (JSR 380)
Authentication / 身份验证
Basic Authentication / 基本认证
#![allow(unused)]
fn main() {
use hiver_security::{Authentication, AuthenticationManager};
let auth_manager = AuthenticationManager::new();
let auth = auth_manager.authenticate(username, password).await?;
}
JWT Authentication / JWT 认证
#![allow(unused)]
fn main() {
use hiver_security::jwt::{JwtProvider, JwtConfig, Claims};
use std::time::Duration;
// Configure JWT / 配置 JWT
let jwt = JwtProvider::new(JwtConfig {
secret: "your-secret-key",
expiration: Duration::from_secs(3600),
issuer: "my-app".to_string(),
});
// Generate token / 生成令牌
let claims = Claims::new("user123").with_role("ADMIN");
let token = jwt.generate_token(&claims)?;
// Validate token / 验证令牌
let verified = jwt.validate_token(&token)?;
assert_eq!(verified.sub(), "user123");
}
JWT Middleware / JWT 中间件
#![allow(unused)]
fn main() {
use hiver_middleware::Middleware;
use hiver_security::jwt::JwtProvider;
struct JwtAuth {
provider: JwtProvider,
}
impl Middleware for JwtAuth {
fn handle(&self, req: Request, next: Next) -> BoxFuture<'static, Result<Response, Error>> {
// Extract Authorization header / 提取 Authorization 头
let token = req.headers()
.get("Authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "));
match token {
Some(t) => match self.provider.validate_token(t) {
Ok(claims) => next.run(req), // Valid token / 有效令牌
Err(_) => Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body("Invalid token".into())
.unwrap(),
},
None => Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body("Missing token".into())
.unwrap(),
}
}
}
}
Authorization / 授权
Method-Level Security / 方法级安全
#![allow(unused)]
fn main() {
use hiver_macros::pre_authorize;
#[pre_authorize("hasRole('ADMIN')")]
async fn delete_user(id: u64) -> Result<(), Error> {
delete_user(id).await
}
}
Role-Based Security / 基于角色的安全
#![allow(unused)]
fn main() {
use hiver_macros::secured;
#[secured("ROLE_USER")]
async fn get_profile() -> Result<Profile, Error> {
get_current_user_profile().await
}
}
Password Encoding / 密码编码
#![allow(unused)]
fn main() {
use hiver_security::{PasswordEncoder, BcryptPasswordEncoder};
// Default bcrypt encoder / 默认 bcrypt 编码器
let encoder = PasswordEncoder::bcrypt();
// Custom cost / 自定义 cost
let encoder = BcryptPasswordEncoder::with_cost(12);
// Encode password / 编码密码
let encoded = encoder.encode("password123")?;
// Verify password / 验证密码
let is_valid = encoder.matches("password123", &encoded)?;
assert!(is_valid);
}
Input Validation / 输入验证
#![allow(unused)]
fn main() {
use hiver_validation_annotations::{NotNull, Size, Email, Pattern};
struct CreateUserRequest {
#[not_null]
#[size(min = 2, max = 50)]
name: String,
#[not_null]
#[email]
email: String,
#[pattern(r"^\d{10,11}$")]
phone: String,
}
}
Security Headers / 安全头
#![allow(unused)]
fn main() {
use hiver_middleware::SecurityHeaders;
let app = Router::new()
.middleware(Arc::new(SecurityHeaders::default()
.x_frame_options("DENY")
.x_content_type_options("nosniff")
.strict_transport_security("max-age=31536000")
))
.get("/", handler);
}
CORS Configuration / CORS 配置
#![allow(unused)]
fn main() {
use hiver_middleware::Cors;
let cors = Cors::new()
.allow_origin("https://example.com")
.allow_methods(["GET", "POST", "PUT", "DELETE"])
.allow_headers(["Authorization", "Content-Type"])
.max_age(3600);
let app = Router::new()
.middleware(Arc::new(cors))
.get("/", handler);
}
Spring Boot Comparison / Spring Boot 对比
| Spring Boot | Hiver | Description |
|---|---|---|
@PreAuthorize | #[pre_authorize] | Method authorization |
@Secured | #[secured] | Role-based security |
@Valid | #[derive(Model)] + annotations | Input validation |
UserDetails | Authentication | User representation |
PasswordEncoder | PasswordEncoder | Password hashing |
JwtProvider | JwtProvider | JWT token management |
| Spring Security Filter Chain | Middleware | Request security pipeline |
Best Practices / 最佳实践
- Always hash passwords — use
PasswordEncoder::bcrypt()with cost ≥ 10 - Use HTTPS in production — configure TLS or use a reverse proxy
- Validate all inputs — use
@NotNull,@Size,@Emailannotations - Use method-level security —
#[pre_authorize]for fine-grained control - Keep JWT secrets secure — use environment variables, never hardcode
- Set short JWT expiration — 15-60 minutes, use refresh tokens
- Enable security headers —
SecurityHeadersmiddleware for common protections