增量预聚合(Rollups)

本篇用 RollupsPlugin 与强类型派生宏搭建 5 分钟事件预聚合服务,在 SQLite 上验证增量刻度推进、状态查询与水位线报表读取。

创建工程与强类型汇总表#

工程基础见 第一个应用 与 迁移。

第 1 步,新建 Cargo.toml,启用 SQLite、迁移与 rollups 特性:

TOML
[package]
name = "guide-rollups"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"

[dependencies]
kxed = { version = "0.0.5-alpha", features = ["seaorm-sqlite", "seaorm-migration", "rollups"] }

第 2 步,配置本地 SQLite 文件供常驻服务与运维命令共享,并关闭后台自动刻度以便手动观察每轮推进。新建 config/database.toml:

TOML
url = "sqlite://rollups.sqlite?mode=rwc"

新建 config/rollups.toml:

TOML
tick_interval = "5m"
scheduler_enabled = false

第 3 步,定义原始事件表 raw_events、汇总表 event_rollups、强类型键/切片/指标派生结构与 EventRollupSpec 规范,新建 src/rollup.rs:

Rust
use kxed::plugins::rollups::{
    RollupError, RollupKey, RollupMeasures, RollupSlice, RollupSource, RollupSourceSpec,
    RollupSpec, RollupStore, SnapshotCtx, UtcDay, DEFAULT_TABLE_PREFIX,
};
use kxed::plugins::seaorm::async_trait;
use kxed::plugins::seaorm::sea_orm::{
    ColumnTrait, ConnectionTrait, DbErr, EntityTrait, QueryFilter,
};
use kxed::plugins::seaorm::sea_orm_migration::{
    MigrationName, MigrationTrait, MigratorTrait, SchemaManager,
};
use kxed::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;

pub mod raw_event {
    use kxed::plugins::seaorm::sea_orm::{self, entity::prelude::*};

    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "raw_events")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        pub day: String,
        pub group_name: String,
        pub amount: i64,
        pub updated_at: DateTimeUtc,
    }

    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}

    impl ActiveModelBehavior for ActiveModel {}
}

pub mod event_rollup {
    use kxed::plugins::seaorm::sea_orm::{self, entity::prelude::*};

    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "event_rollups")]
    pub struct Model {
        #[sea_orm(primary_key, auto_increment = false)]
        pub day: String,
        #[sea_orm(primary_key, auto_increment = false)]
        pub group_name: String,
        pub events: i64,
        pub amount_sum: i64,
    }

    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}

    impl ActiveModelBehavior for ActiveModel {}
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RollupKey)]
#[rollup(entity = event_rollup::Entity)]
pub struct EventKey {
    #[rollup(column = "Day")]
    pub day: String,
    #[rollup(column = "GroupName")]
    pub group_name: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, RollupSlice)]
#[rollup(entity = event_rollup::Entity)]
pub struct EventSlice {
    #[rollup(column = "Day", day)]
    pub day: String,
    #[rollup(column = "GroupName")]
    pub group_name: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, RollupMeasures)]
#[rollup(entity = event_rollup::Entity)]
pub struct EventMeasures {
    #[rollup(column = "Events", default = 0)]
    pub events: i64,
    #[rollup(column = "AmountSum", default = 0)]
    pub amount_sum: i64,
}

#[derive(Clone)]
pub struct EventRollupSpec;

#[async_trait]
impl RollupSpec for EventRollupSpec {
    type Key = EventKey;
    type Slice = EventSlice;
    type Measures = EventMeasures;

    const NAME: &'static str = "event_rollups";
    const VERSION: i32 = 1;

    fn sources(&self) -> Vec<Box<dyn RollupSource<Self::Slice>>> {
        let source = RollupSourceSpec::<raw_event::Entity, EventSlice>::one(
            raw_event::Column::UpdatedAt,
            |row| {
                Some(EventSlice {
                    day: row.day.clone(),
                    group_name: Some(row.group_name.clone()),
                })
            },
        )
        .with_lookback(Duration::from_secs(120))
        .with_watched_columns(&[raw_event::Column::Day, raw_event::Column::GroupName]);
        vec![Box::new(source)]
    }

    async fn recompute(
        &self,
        snapshot: &SnapshotCtx<'_>,
        slices: &[Self::Slice],
    ) -> Result<BTreeMap<Self::Key, Self::Measures>, RollupError> {
        let cutoff = snapshot.moment();
        let mut results: BTreeMap<EventKey, EventMeasures> = BTreeMap::new();
        for slice in slices {
            let mut query = raw_event::Entity::find()
                .filter(raw_event::Column::Day.eq(slice.day.clone()))
                .filter(raw_event::Column::UpdatedAt.lt(cutoff));
            if let Some(group) = &slice.group_name {
                query = query.filter(raw_event::Column::GroupName.eq(group.clone()));
            }
            let rows = query
                .all(snapshot.txn())
                .await
                .map_err(|error| RollupError::Storage(error.to_string()))?;
            for row in rows {
                let key = EventKey { day: row.day, group_name: row.group_name };
                let entry = results.entry(key).or_insert_with(EventMeasures::zero);
                entry.events += 1;
                entry.amount_sum += row.amount;
            }
        }
        Ok(results)
    }

    async fn day_slices(
        &self,
        snapshot: &SnapshotCtx<'_>,
        day: UtcDay,
    ) -> Result<Vec<Self::Slice>, RollupError> {
        let day_text = day.to_string();
        let rows = raw_event::Entity::find()
            .filter(raw_event::Column::Day.eq(day_text.clone()))
            .all(snapshot.txn())
            .await
            .map_err(|error| RollupError::Storage(error.to_string()))?;
        let groups: BTreeSet<String> = rows.into_iter().map(|row| row.group_name).collect();
        Ok(groups
            .into_iter()
            .map(|group| EventSlice { day: day_text.clone(), group_name: Some(group) })
            .collect())
    }

    fn rebuildable_from(&self) -> UtcDay {
        UtcDay::from_ymd(2026, 1, 1).expect("valid fixed day")
    }
}

pub struct Migrator;

#[async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        let mut all = RollupStore::migrations(DEFAULT_TABLE_PREFIX);
        all.push(Box::new(CreateEventTables));
        all
    }
}

struct CreateEventTables;

impl MigrationName for CreateEventTables {
    fn name(&self) -> &str {
        "m20261129_000002_create_guide_rollup_tables"
    }
}

#[async_trait]
impl MigrationTrait for CreateEventTables {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let db = manager.get_connection();
        db.execute_unprepared(
            "CREATE TABLE IF NOT EXISTS raw_events (\
             id INTEGER PRIMARY KEY AUTOINCREMENT, \
             day TEXT NOT NULL, \
             group_name TEXT NOT NULL, \
             amount BIGINT NOT NULL, \
             updated_at TEXT NOT NULL)",
        )
        .await?;
        db.execute_unprepared(
            "CREATE TABLE IF NOT EXISTS event_rollups (\
             day TEXT NOT NULL, \
             group_name TEXT NOT NULL, \
             events BIGINT NOT NULL DEFAULT 0, \
             amount_sum BIGINT NOT NULL DEFAULT 0, \
             PRIMARY KEY (day, group_name))",
        )
        .await?;
        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let db = manager.get_connection();
        db.execute_unprepared("DROP TABLE IF EXISTS event_rollups").await?;
        db.execute_unprepared("DROP TABLE IF EXISTS raw_events").await?;
        Ok(())
    }
}

编写事件写入与水位线报表接口#

在入口中同时注册 SeaOrmPlugin(挂载账本与业务表迁移)和 RollupsPlugin(登记 EventRollupSpec),并提供写入事件与读取水位线报表两个接口。新建 src/main.rs:

Rust
mod rollup;

use kxed::plugins::rollups::{
    sub_duration, RollupClock, RollupsPlugin, SystemRollupClock, UtcDay,
};
use kxed::plugins::seaorm::sea_orm::{
    ActiveModelTrait, EntityTrait, QueryOrder, Set, TransactionTrait,
};
use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;
use rollup::{event_rollup, raw_event, EventRollupSpec, EventSlice, Migrator};
use std::time::Duration;

async fn record_event(
    ctx: AppCtx,
    Path((group, amount)): Path<(String, i64)>,
) -> Result<String, AppErr> {
    let occurred = sub_duration(SystemRollupClock.now(), Duration::from_secs(600));
    let day = UtcDay::from_datetime(occurred).to_string();
    let db = ctx.db()?;
    let txn = db.begin().await?;
    raw_event::ActiveModel {
        day: Set(day.clone()),
        group_name: Set(group.clone()),
        amount: Set(amount),
        updated_at: Set(occurred),
        ..Default::default()
    }
    .insert(&txn)
    .await?;
    let slice = EventSlice { day, group_name: Some(group.clone()) };
    ctx.rollup_mark::<EventRollupSpec>(&txn, &slice).await?;
    txn.commit().await?;
    Ok(format!("recorded {group} {amount}\n"))
}

async fn read_report(ctx: AppCtx) -> Result<String, AppErr> {
    let cutoff = ctx.report_cutoff().await?;
    let published = cutoff.published_at().is_some();
    let rows = cutoff
        .remember("events_summary", &"all", Duration::from_secs(60), || async {
            let db = ctx.db().map_err(|error| kxed::plugins::rollups::RollupError::Storage(error.to_string()))?;
            let items = event_rollup::Entity::find()
                .order_by_asc(event_rollup::Column::GroupName)
                .all(db.as_ref())
                .await
                .map_err(|error| kxed::plugins::rollups::RollupError::Storage(error.to_string()))?;
            Ok(items
                .into_iter()
                .map(|row| format!("{} events={} amount={}", row.group_name, row.events, row.amount_sum))
                .collect::<Vec<_>>())
        })
        .await?;
    Ok(format!("published={published} {}\n", rows.join(",")))
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("guide_rollups")))
        .plugin(RollupsPlugin::new().with_rollup(EventRollupSpec))
        .routes(|router| {
            router
                .route("/events/{group}/{amount}", post(record_event))
                .route("/report", get(read_report));
        })
        .run()
        .await
}
  • record_event 将演示事件时间戳记在 10 分钟前(已封闭刻度内),并在同一事务内调用 ctx.rollup_mark::<EventRollupSpec>(&txn, &slice) 写入待重算切片标记。
  • read_report 通过 ctx.report_cutoff() 一次查询获取全局发布水位线,并按 (report, params, cutoff) 缓存汇总读取结果。

验证#

在第一个终端启动服务(启动时自动跑完账本表与业务表迁移):

Shell
cargo run

另开终端依次写入两条 checkout 事件,执行 rollups run 推进一轮 5 分钟刻度、用 rollups status 检查汇总表登记,再访问 /report 读取已发布水位线后的汇总结果:

Shell
curl --fail --silent -X POST http://127.0.0.1:8080/events/checkout/120
curl --fail --silent -X POST http://127.0.0.1:8080/events/checkout/80
cargo run -- rollups run | awk '/^(written_rows|recomputed_slices)/ {print $1, $2}'
cargo run -- rollups status | awk 'NR==2 {print $1, $2}'
curl --fail --silent http://127.0.0.1:8080/report

预期输出:

输出
recorded checkout 120
recorded checkout 80
written_rows 1
recomputed_slices 1
event_rollups 1
published=true checkout events=2 amount=200

常见排错#

现象原因解决方法
服务启动报错提示账本表缺失Migrator::migrations() 未加入 RollupStore::migrations(prefix),或未执行迁移把 RollupStore::migrations(DEFAULT_TABLE_PREFIX) 合并进 Migrator,或先跑 migrate up
rollups run 退出码 69 拒绝执行database.url 指向内存 SQLite(sqlite::memory:),命令进程与服务进程无法共享在 config/database.toml 改为本地文件 SQLite 或共享 PostgreSQL / MySQL / TiDB
新写入事件在当轮 rollups run 未出现事件 updated_at 晚于当前向下取整的 5 分钟水位线等待下一刻度或确认源表游标列采用统一 UTC 时钟

参考#

  • 增量预聚合插件参考:多库快照隔离、升版本自动回填、每晚漂移重扫、写入护栏与 FactFeed 说明
  • 迁移:编写与执行 SeaORM 建表迁移
  • 运维命令:查看全部 rollups 运维子命令与破坏性命令确认规则