流式 Procedure
本篇实现批量导入进度推送、大表分页流式导出与带初始快照的订单实时订阅。需要持续反馈进度、分批流式返回大量记录或实时监听事件时,在 Procedure 中返回 Streamed<T>。
本篇在一个订单服务里提供五个流式与协同接口:
| 接口名 | 宏 | 返回类型 | 业务用途 |
|---|---|---|---|
orders.import | #[mutation] | Streamed<ImportEvent> | 逐条入库并推送导入进度,末帧返回汇总 |
orders.export | #[query] | Streamed<OrderView> | 按主键游标分页读取并流式导出,开流前限流 |
orders.ship | #[mutation] | () | 更新发货状态并向订单频道广播变更 |
orders.watch | #[subscription] | Streamed<OrderMoved> | 持续接收指定订单的后续发货事件 |
orders.board | #[subscription] | Streamed<BoardFrame> | 先推送当前快照,再无缝衔接后续增量事件 |
搭建订单流工程#
第 1 步,新建 Cargo.toml,启用认证、限流与 SQLite 迁移特性:
[package]
name = "guide-procedure-streams"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
[dependencies]
async-stream = "0.3"
futures-util = "0.3"
kxed = { version = "0.0.5-alpha", features = ["auth", "security", "seaorm-sqlite", "seaorm-migration"] }第 2 步,新建 config/database.toml:
url = "sqlite://orders.sqlite?mode=rwc"第 3 步,新建 src/auth.rs,内置 admin 与 member 演示账号并提供免登录的 POST /login 签发 Bearer 令牌:
use kxed::access::{AccessError, GuardAccess};
use kxed::identity::Identity;
use kxed::plugins::auth::{AuthError, AuthPrincipal, AuthSessionValidator, LoginOptions, StoredAuthSession};
use kxed::prelude::*;
const ACCOUNTS: [(&str, &str); 2] = [("1", "admin"), ("2", "member")];
pub(crate) struct Accounts;
impl AuthSessionValidator for Accounts {
async fn is_valid(&self, session: &StoredAuthSession) -> Result<bool, AuthError> {
Ok(ACCOUNTS.iter().any(|(id, _)| *id == session.principal.subject))
}
}
pub(crate) struct Roles;
impl GuardAccess for Roles {
async fn grants(&self, identity: &Identity) -> Result<Grants, AccessError> {
let role = ACCOUNTS.iter().find(|(id, _)| *id == identity.subject()).map(|(_, r)| *r);
Ok(Grants::roles_only(role)?)
}
}
#[derive(Debug, Serialize, Deserialize, Validate, ToSchema)]
pub struct DemoLogin {
#[garde(length(chars, min = 1, max = 16))]
pub role: String,
}
#[mutation(name = "demo.login", public, post = "/login")]
pub async fn demo_login(ctx: &AppCtx, input: DemoLogin) -> Result<String, AppErr> {
let Some((id, _)) = ACCOUNTS.iter().find(|(_, r)| *r == input.role) else {
return Err(AppErr::unauthorized());
};
let issued = ctx.auth_sessions()?.issue_token(AuthPrincipal::new(*id), LoginOptions::default()).await?;
Ok(issued.token.expose_secret().to_owned())
}第 4 步,新建 src/orders.rs,定义 orders 表、建表迁移与对象级权限策略:
use kxed::identity::Identity;
use kxed::plugins::seaorm::sea_orm::entity::prelude::*;
use kxed::plugins::seaorm::sea_orm::sea_query::Table;
use kxed::plugins::seaorm::sea_orm::{self, DbErr, Schema};
use kxed::plugins::seaorm::sea_orm_migration::{MigrationName, MigrationTrait, MigratorTrait, SchemaManager};
use kxed::plugins::seaorm::{async_trait, RouteBinding};
use kxed::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "orders")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub reference: String,
pub shipped: bool,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl RouteBinding for Entity {}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct OrderView {
pub id: i64,
pub reference: String,
pub shipped: bool,
}
impl From<Model> for OrderView {
fn from(row: Model) -> Self {
Self { id: row.id, reference: row.reference, shipped: row.shipped }
}
}
pub struct OrderPolicy;
impl Policy<Model> for OrderPolicy {
async fn check(&self, _who: &Identity, grants: &Grants, action: &str, _order: &Model) -> Decision {
match action {
"view" => Decision::Allow,
"ship" => grants.has_role("admin").into(),
_ => Decision::Deny,
}
}
}
pub(crate) struct Migrator;
#[async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> { vec![Box::new(CreateOrders)] }
}
struct CreateOrders;
impl MigrationName for CreateOrders {
fn name(&self) -> &str { "m20261120_000001_create_orders" }
}
#[async_trait]
impl MigrationTrait for CreateOrders {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.create_table(Schema::new(manager.get_database_backend()).create_table_from_entity(Entity)).await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.drop_table(Table::drop().table(Entity).to_owned()).await
}
}第 5 步,新建 src/streams.rs,实现流式导入落库、分页流式导出、发货广播与带首帧快照的实时订阅:
use crate::orders::{ActiveModel, Column, Entity, OrderView};
use futures_util::{stream, StreamExt, TryStreamExt};
use kxed::plugins::seaorm::sea_orm::sea_query::Expr;
use kxed::plugins::seaorm::sea_orm::{ActiveModelTrait, ActiveValue::Set, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QueryOrder, QuerySelect};
use kxed::plugins::security::RateQuota;
use kxed::prelude::*;
const PAGE: u64 = 100;
const EXPORT_QUOTA: RateQuota = RateQuota::per_hour("orders.export", 10, 3);
#[derive(Serialize, Deserialize, ToSchema)]
pub struct ImportReport {
pub created: u32,
pub skipped: u32,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ImportEvent {
Progress { done: u32, total: u32 },
Finished(ImportReport),
}
#[derive(Debug, Serialize, Deserialize, Validate, ToSchema)]
pub struct ImportRows {
#[garde(length(min = 1, max = 1000))]
pub references: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, Validate, ToSchema)]
pub struct ExportFilter {
#[garde(range(min = 0))]
pub after: i64,
}
#[event]
#[derive(ToSchema)]
pub struct OrderMoved {
pub order: i64,
pub shipped: bool,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BoardFrame {
Snapshot(OrderView),
Moved(OrderMoved),
}
async fn insert_order(db: &DatabaseConnection, reference: String) -> Result<(), AppErr> {
ActiveModel { reference: Set(reference), shipped: Set(false), ..Default::default() }
.insert(db)
.await?;
Ok(())
}
/// 逐条把合法单号写入数据库并推送进度帧,末帧返回导入汇总。
#[mutation(name = "orders.import", role = "admin")]
pub async fn import_orders(ctx: &AppCtx, input: ImportRows) -> Result<Streamed<ImportEvent>, AppErr> {
let ctx = ctx.clone();
Ok(Streamed::new(async_stream::try_stream! {
let db = ctx.db()?;
let total = input.references.len() as u32;
let (mut created, mut skipped) = (0, 0);
for (index, reference) in input.references.iter().enumerate() {
if reference.starts_with("ORD-") {
insert_order(db.as_ref(), reference.clone()).await?;
created += 1;
} else {
skipped += 1;
}
yield ImportEvent::Progress { done: index as u32 + 1, total };
}
yield ImportEvent::Finished(ImportReport { created, skipped });
}))
}
#[query(name = "orders.export", role = ["admin", "member"], rate_limit = EXPORT_QUOTA)]
pub async fn export_orders(ctx: &AppCtx, input: ExportFilter) -> Result<Streamed<OrderView>, AppErr> {
let ctx = ctx.clone();
Ok(Streamed::new(async_stream::try_stream! {
let db = ctx.db()?;
let mut after = input.after;
loop {
let page = Entity::find().filter(Column::Id.gt(after)).order_by_asc(Column::Id).limit(PAGE).all(db.as_ref()).await?;
let Some(last) = page.last().map(|row| row.id) else { break };
after = last;
for row in page {
yield OrderView::from(row);
}
}
}))
}
fn topic(order: i64) -> String { format!("orders.{order}") }
#[mutation(name = "orders.ship", role = ["admin", "member"], can = "ship")]
pub async fn ship_order(ctx: &AppCtx, found: Found<Entity>) -> Result<(), AppErr> {
Entity::update_many().col_expr(Column::Shipped, Expr::value(true)).filter(Column::Id.eq(found.id)).exec(ctx.db()?.as_ref()).await?;
if let Err(error) = ctx.broadcast(&topic(found.id), OrderMoved { order: found.id, shipped: true }).await {
kxed::tracing::warn!(%error, "the order change was not announced");
}
Ok(())
}
#[subscription(name = "orders.watch", role = ["admin", "member"], can = "view")]
pub async fn watch_order(ctx: &AppCtx, found: Found<Entity>) -> Result<Streamed<OrderMoved>, AppErr> {
Ok(Streamed::new(ctx.subscribe_topic(&topic(found.id))?.into_events::<OrderMoved>()))
}
/// 先建订阅缓冲、再查库取当前快照,避免两步之间的发货变更遗漏。
#[subscription(name = "orders.board", role = ["admin", "member"], can = "view")]
pub async fn order_board(ctx: &AppCtx, found: Found<Entity>) -> Result<Streamed<BoardFrame>, AppErr> {
let moves = ctx.subscribe_topic(&topic(found.id))?.into_events::<OrderMoved>();
let current = Entity::find_by_id(found.id).one(ctx.db()?.as_ref()).await?.ok_or_else(AppErr::not_found)?;
let first = stream::once(std::future::ready(Ok::<_, AppErr>(BoardFrame::Snapshot(OrderView::from(current)))));
Ok(Streamed::new(first.chain(moves.map_ok(BoardFrame::Moved))))
}第 6 步,注册策略、安全、数据库与认证插件,写 src/main.rs:
mod auth;
mod orders;
mod streams;
use kxed::plugins::auth::{AuthPlugin, MemoryAuthStore};
use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::plugins::security::SecurityPlugin;
use kxed::prelude::*;
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.policy::<orders::Model>(orders::OrderPolicy)
.plugin(SecurityPlugin::new())
.plugin(SeaOrmPlugin::new().migrate::<orders::Migrator>(MigrationLock::new("orders.migrations")))
.plugin(
AuthPlugin::new()
.with_store(MemoryAuthStore::new(1024)?, auth::Accounts)
.with_access(auth::Roles),
)
.run()
.await
}验证#
启动 cargo run,另开终端先验证匿名拦截 401,再用 admin 令牌实测流式导入、流式分页导出以及 orders.board 实时订阅首帧快照与发货增量帧:
curl --silent -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8080/_rpc/orders.import -H 'content-type: application/json' -d '{"references":["ORD-101"]}'
TOKEN=$(curl --fail --silent -X POST http://127.0.0.1:8080/login -H 'content-type: application/json' -d '{"role":"admin"}' | tr -d '"')
curl --fail --silent -X POST http://127.0.0.1:8080/_rpc/orders.import -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{"references":["ORD-101","BAD-1"]}' | grep '^data:'
curl --fail --silent -X POST http://127.0.0.1:8080/_rpc/orders.export -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{"after":0}' | grep '^data:'
curl --silent --no-buffer --max-time 3 -X POST http://127.0.0.1:8080/_rpc/orders.board -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{"id":1}' > board.txt &
sleep 1
curl --fail --silent -o /dev/null -X POST http://127.0.0.1:8080/_rpc/orders.ship -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{"id":1}'
wait
grep '^data:' board.txt预期输出:
401
data: {"kind":"item","payload":{"done":1,"total":2,"type":"progress"}}
data: {"kind":"item","payload":{"done":2,"total":2,"type":"progress"}}
data: {"kind":"item","payload":{"created":1,"skipped":1,"type":"finished"}}
data: {"kind":"done"}
data: {"kind":"item","payload":{"id":1,"reference":"ORD-101","shipped":false}}
data: {"kind":"done"}
data: {"kind":"item","payload":{"id":1,"reference":"ORD-101","shipped":false,"type":"snapshot"}}
data: {"kind":"item","payload":{"order":1,"shipped":true,"type":"moved"}}流式读写、实时快照与安全边界#
flowchart LR
A["1. subscribe_topic 建立缓冲"] --> B["2. 查库读取当前快照"]
B --> C["3. 先发 Snapshot 再接 Moved 流"]- 生命周期与背压:
Streamed<T>要求'static流,进入try_stream!前须先let ctx = ctx.clone();;出站自带容量 16 缓冲,客户端变慢时自动在yield边界反压暂停,中途断连也只在yield边界安全取消。 - 开流前鉴权与限流:角色检查、
can策略与rate_limit全部在建流前完成,未通过直接返回常规401/403/429JSON;长连接期间每 15 秒自动复查权限,被撤销即关闭流(见 SPEC 第 4.2 节)。 - 切勿裸拼订阅频道:
ctx.subscribe_topic(..)本身不鉴权,须像orders.board一样用Found<Entity>+can = "view"授权后再从found.id派生频道;消费滞后触发topic_lagged时客户端重调orders.board拉取最新快照恢复。
#[subscription] 常用声明式属性速查(完整规则见 Procedure 参考):
| 宏参数 | 写法示例 | 适用场景 |
|---|---|---|
topic | #[subscription(topic = "orders.{id}")] | 按入参同名字段自动订阅频道,配合 ctx.publish::<E>(key, event) 推送 |
snapshot | #[subscription(snapshot = read_board)] | 建流后自动先调一次 read_board(ctx) 输出首帧,重连自动重拉 |
delivery | delivery = "ordered" | "lossy" | "reliable" | 默认保序;高频行情用 lossy;断线按序号补发用 reliable(见 reliable-push) |
常见排错#
| 现象 | 原因 | 解决方法 |
|---|---|---|
try_stream! 报 ctx 生命周期不够长 | 流要求 'static,不能借用 &AppCtx 参数 | 在 try_stream! 宏之前写 let ctx = ctx.clone(); |
订阅流中途收到 topic_lagged 结束 | 客户端消费慢于广播速率,超出单条订阅 64 帧缓冲 | 捕获错误后重新调用 orders.board 拉取最新快照继续监听 |
配了 rate_limit 后启动失败 | 接口限流依赖 SecurityPlugin 提供限流器 | 在 App::new() 上补挂 .plugin(SecurityPlugin::new()) |
开启 delivery = "reliable" 后启动失败 | 可靠续订流需要序号与保留存储支持 | 开启 reliable-push 特性并注册 ReliablePushPlugin::new() |
参考#
- Procedure:常规
#[query]/#[mutation]读写契约与多端 SDK 生成 - Procedure 参考:流式帧格式、
/_rpc/ws多路复用与snapshot属性细则 - reliable-push 插件:带单调序号与断线
resume_from补发的可靠订阅