#tonic #grpc #interceptor #async #protobuf

tonic-async-interceptor

Tonic 的拦截器函数的异步版本

6 个版本 (3 个重大更新)

0.12.0 2024 年 7 月 8 日
0.11.1 2024 年 4 月 5 日
0.11.0 2024 年 3 月 15 日
0.10.0 2023 年 9 月 22 日
0.1.0-alpha.02022 年 8 月 29 日

网络编程 中排名第 1481

Download history 169/week @ 2024-05-02 147/week @ 2024-05-09 136/week @ 2024-05-16 240/week @ 2024-05-23 240/week @ 2024-05-30 213/week @ 2024-06-06 227/week @ 2024-06-13 253/week @ 2024-06-20 303/week @ 2024-06-27 266/week @ 2024-07-04 212/week @ 2024-07-11 159/week @ 2024-07-18 199/week @ 2024-07-25 428/week @ 2024-08-01 356/week @ 2024-08-08 671/week @ 2024-08-15

每月下载量 1,664

使用 MIT 许可证

25KB
435

Tonic Async Interceptor

Crates.io Documentation Crates.io

本 crate 包含 AsyncInterceptor,它是 Tonic 的 Interceptor 的异步版本。除了接受异步拦截器函数外,它与 Interceptor 的工作方式相同。

异步拦截器函数对于需要进行认证等任务的场景很有用,其中您需要在拦截器中异步调用另一个服务或数据库。

兼容性

主版本号/副版本号与 Tonic 相对应;因此,如果您正在使用 Tonic v0.12.x,则应同样使用 Tonic Async Interceptor v0.12.x。

用法

与 Tonic 内置的 Server/Router 一起使用

async fn my_async_interceptor(req: Request<()>) -> Result<Request<()>, Status> {
    // do things and stuff
    Ok(req)
}

async fn main() {
    use tonic::transport::server;
    use tonic_async_interceptor::async_interceptor;
    let router = server::Server::builder()
        .layer(async_interceptor(my_async_interceptor))
        .add_service(some_service)
        .add_service(another_service);
    // ...
}

设置自定义扩展

以下是一个示例,说明如何使用异步拦截器来验证用户并设置底层服务使用的自定义扩展。

// Your custom extension
struct UserContext {
    user_id: String,
}

// Async interceptor fn
async fn authenticate(req: Request<()>) -> Result<Request<()>, Status> {
    // Inspect the gRPC metadata.
    let auth_header_val = match req.metadata().get("x-my-auth-header") {
        Some(val) => val,
        None => return Err(Status::unauthorized("Request missing creds")),
    };
    // Call some async function (`verify_auth`).
    let maybe_user_id: Result<String> =
        verify_auth(auth_header_val).await;
    
    let user_id = match maybe_user_id {
        Ok(id) => id,
        Err(_) => return Err(Status::unauthorized("Invalid creds")),
    };
    
    // Insert an extension, which can be inspected by the service.
    req.extensions_mut().insert(UserContext { user_id });
    
    Ok(req)
}

为什么这是一个独立的 crate?

本 crate 中的代码最初打算与官方 Tonic crate 中的非异步拦截器代码一起存在。然而,维护者 决定不合并它,因为缺乏时间和与他对 Tonic 未来愿景的不一致。

依赖项

~4.5–6.5MB
~112K SLoC