Rust 游标分页实战:Macro 中 models_pagination 的类型安全分页体系

原创2026-10-30 18:38:481,866 阅读
文章标签:企业应用协同办公后端前端即时通讯AI Agent人工智能CRM桌面应用MCP Clients

Rust 游标分页实战:Macro 中 models_pagination 的类型安全分页体系

models_pagination 是 Macro 后端所有列表接口共用的分页基础设施,用一套泛型 + trait 契约把「游标编码、排序语义、分页切片」从具体业务实体中剥离出来。读完本文,你将掌握该 crate 的三条核心 trait 约定(Identify / Sortable / SortOn)、base64 游标的真实结构、axum 请求参数的自动提取方式,以及如何为自己的实体新增一种排序方法并写出可验证的分页查询。

1. 定位:它是什么,不负责什么

根据 crate 说明,models_pagination 的职责边界非常清晰:

  • 拥有:游标编码格式、排序 trait 契约、面向分页列表接口的 axum 查询参数提取。
  • 不拥有:某个具体实体的 SQL 查询与排序实现——那部分留在领域 crate 里(例如 soup、messages)。
  • 依赖:不依赖任何领域模型,是纯分页机械(base64、ordered-float,可选的 axum / model-error-response)。实际依赖清单见 Cargo.toml:base64、chrono、either、ordered-float、serde、serde_json、thiserror、tracing,axum 与 model-error-response 为可选依赖。
  • 使用方:ai_tools、calendar_events、call、channels、complete_graph、databases_sql、email、email_db_client、foreign_entity、github_pull_requests、graphql_activity、graphql_calendar、graphql_initiative、graphql_soup、macro_db_client、messages、model、model_notifications、models_email、models_soup、notification、notification_db_client、skills、soup、teams 等几乎所有返回列表的 crate。

这种「纯机械 + 领域实现分离」的切分,使得游标格式在全仓统一:客户端换一个接口不用换解析方式,服务端改一个实体的排序也不用碰全局分页代码。

2. 三条 trait 契约:能分页的前提条件

crates/models_pagination/src/lib.rs 的 crate 级文档把分页成立的条件写成了三条「支柱」:

  1. Iterator::Item 必须实现 Identify,用于取出实体的唯一主键;
  2. 你打算用来分页的排序方式必须实现 Sortable,声明排序发生在什么类型的值上,比如 DateTime<Utc>;
  3. Iterator::Item 必须针对该 Sortable 实现 SortOn,把「排序方式」翻译成「该条目的游标值」。

三条 trait 的实际定义都在 src/cursor.rs:

/// defines type to be sortable, sortable types must have an associated Value
pub trait Sortable: std::fmt::Debug {
    /// the value which we sort on e.g. Utc timestamp, float, etc
    type Value: std::fmt::Debug + std::cmp::Ord;
}

/// the trait used to uniquely identify a record
pub trait Identify {
    type Id;
    fn id(&self) -> Self::Id;
}

pub trait SortOn<T: Sortable> {
    /// Given the input sort method T, return a function which produces the CursorVal for that T
    fn sort_on(sort: T) -> impl FnMut(&Self) -> CursorVal<T>;
}

几个值得注意的设计点:

  • Sortable::Value 要求 Ord,这是保证游标比较确定的必要条件。浮点数不满足 Ord,所以仓库用 ordered-float 的 OrderedFloat 包装 frecency 分数(见 src/sort.rs)。
  • SortOn::sort_on 返回的是 impl FnMut(&Self) -> CursorVal<T>,而不是直接返回值。分页器需要对同一批条目多次调用该函数(排序阶段和生成游标阶段),闭包形式避免了重复分配排序方法对象。
  • Identify::Id 没有 Copy/Ord 约束,因此主键可以是 Uuid、i64、String 等任意可序列化类型——Cursor 的 Serialize 约束在 into_page 上单独施加。

2.1 领域侧实现示例

messages crate 的实现非常典型,见 crates/messages/src/domain/models.rs:

impl models_pagination::Identify for MessageListItem {
    type Id = Uuid;
    fn id(&self) -> Uuid {
        self.message.id
    }
}
impl models_pagination::SortOn<models_pagination::CreatedAt> for MessageListItem {
    fn sort_on(
        sort_type: models_pagination::CreatedAt,
    ) -> impl FnMut(&Self) -> models_pagination::CursorVal<models_pagination::CreatedAt> {
        move |item| models_pagination::CursorVal {
            sort_type,
            last_val: item.message.created_at,
        }
    }
}

soup 的 SoupCandidate 则展示了「复合排序」的写法:排序方式为 Frecency 时,如果条目有 frecency 分数就用分数,否则回退到 updated_at 时间戳,见 crates/soup/src/domain/service.rs:

impl SortOn<Frecency> for SoupCandidate {
    fn sort_on(sort_type: Frecency) -> impl FnMut(&Self) -> CursorVal<Frecency> {
        move |candidate| CursorVal {
            sort_type,
            last_val: match &candidate.frecency_score {
                Some(frecency) => FrecencyValue::FrecencyScore(frecency.data.frecency_score),
                None => FrecencyValue::UpdatedAt(candidate.item.updated_at()),
            },
        }
    }
}

同时它还实现了 SortOn<SimpleSortMethod>,内部把工作委托给 SoupItem::sort_on(sort)(同一文件第 168-173 行),这说明 SortOn 可以在包装类型之间逐层转发,不必每个层级都重写映射逻辑。

3. 游标的数据结构:Cursor、CursorVal 与 Base64Str

3.1 Cursor 的四个字段

crates/models_pagination/src/cursor.rs 定义了游标本体:

pub struct Cursor<Id, C, F> {
    /// the unique id (e.g. i64, uuid, stc) that identifies the last entity on the previous page
    pub id: Id,
    /// the size of the previous page
    pub limit: usize,
    /// the value of the cursor, this is usually a CursorVal
    pub val: C,
    /// the value we are filtering on
    pub filter: F,
}

字段含义与实际用途对照:

字段 含义 为什么必须进游标
id 上一页最后一条记录的主键 同一排序值出现多行时用主键做 tie-breaker(键集分页的第二排序列)
limit 上一页的页大小 让服务端在执行 (sort_ts, id) < (?, ?) LIMIT n 时保持一致页大小,也便于校验
val 通常是 CursorVal,含排序方式与最后一个排序值 让后续页码无需客户端重复传排序参数也能还原排序语义
filter 过滤条件的类型参数 把「过滤条件」与游标绑定,避免翻页时条件漂移

两个常用类型别名简化了调用点:

pub type CursorWithVal<Id, V> = Cursor<Id, CursorVal<V>, ()>;
pub type CursorWithValAndFilter<Id, V, F> = Cursor<Id, CursorVal<V>, F>;

对应 src/cursor.rs。当接口没有过滤条件时用前者(F = ()),有过滤条件时用后者。

CursorVal 只做一件事:把「排序方式」与「上一页最后一条的排序值」打包:

pub struct CursorVal<C: Sortable> {
    pub sort_type: C,
    pub last_val: C::Value,
}

这个设计让游标自带排序类型标签。它带来的直接好处是「同值不同语义」的游标可以被区分开——比如 TouchedByMe 与 NotifiedAt 的 Value 都是 DateTime<Utc>,只能靠 sort_type 的序列化形态区分(详见第 5 节)。Cursor 还提供了 map_filter,可以在不改动 id/limit/val 的前提下变换过滤类型。

3.2 base64 包装:Base64Str<T>

对外暴露的游标是一个不透明字符串。实现方式是 Base64Str<T>(src/cursor.rs):

#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Base64Str<T> {
    data: String,
    #[serde(skip)]
    target: PhantomData<T>,
}

它在序列化上是透明的(JSON 里就是一个字符串),但类型上仍然携带 T,从而能在编译期保证「游标是用这个类型编码的」。

编码路径:Serialize → JSON 字符串 → general_purpose::STANDARD.encode:

pub fn encode_json(val: T) -> Self {
    Self::encode(val, serialize_json_string)
}

解码路径:base64 解码 → 回调反序列化。decode 接受一个泛型回调,从而可以复用任意序列化格式;decode_json 是 JSON 特化版本:

pub fn decode<F, E>(self, f: F) -> Result<T, Base64SerdeErr<E>>
where
    F: FnOnce(Vec<u8>) -> Result<T, E>,
{
    let bytes = general_purpose::STANDARD.decode(self.data.as_str())?;
    f(bytes).map_err(Base64SerdeErr::SerdeErr)
}

错误被建模成 Base64SerdeErr<E> 的两分支:DecodeErr(DecodeError) 表示 base64 层解不开;SerdeErr(E) 表示 base64 解开了但内容不是期望结构。这个区分在 axum 层被直接映射成两种不同的用户可读报错,见第 7 节。

4. 从迭代器到页面:Paginate / Paginator / into_page

分页的核心不是 SQL,而是「给定一串已经排序好的条目,怎么切一页并产出下一页游标」。

4.1 入口:paginate 与 paginate_on

Paginate 由「任意 Item 实现 Identify 的 Iterator」自动实现(src/cursor.rs):

impl<T> Paginate for T
where
    T: Iterator,
    T::Item: Identify,
{
    fn paginate<Cb, S>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, ()>
    where
        Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S>,
        S: Sortable,
    { /* ... */ }
}

paginate_on 是对 paginate 的语法糖:只要条目实现了 SortOn<T>,就可以直接把排序方法传进去,无需自己构造闭包(src/cursor.rs):

let cb = <<Self as Iterator>::Item as SortOn<T>>::sort_on(sort);
self.paginate(limit, cb)

4.2 链式配置:filter_on / sort_asc / sort_desc

Paginator 用类型状态模式把「过滤类型」从 () 逐步特化:

  • filter_on(filter) 只在 F = () 时可用,把 Paginator<Iter, Cb, S, ()> 变成 Paginator<Iter, Cb, S, F>。这样编译期就防止了重复设置过滤器。
  • sort_asc() / sort_desc() 设置 ensure_sort: Option<Direction>。源码注释明确说明这是逃生舱(escape hatch):理想情况下数据库应返回已排序结果,只有在「拼接多个数据库查询」时才需要它,见 src/cursor.rs。

4.3 into_page 的真实行为

into_page(src/cursor.rs)的逻辑值得逐段拆:

let res = match ensure_sort {
    Some(sort) => {
        let mut res: Vec<_> = iter.collect();
        res.sort_by_key(|r| {
            let cursor = cb(r);
            match sort {
                Direction::Asc => Either::Left(cursor.last_val),
                Direction::Desc => Either::Right(std::cmp::Reverse(cursor.last_val)),
            }
        });
        res.truncate(limit);
        res
    }
    None => iter.take(limit).collect(),
};
  1. 有 ensure_sort 时:全量收集、按 last_val 排序、再截断。用 Either::Left / Either::Right(Reverse(..)) 让升序与降序共用一次 sort_by_key,避免写两份比较逻辑。
  2. 无 ensure_sort 时:直接 take(limit),即信任输入已排序。这也是为什么 soup 在多源合并后要显式调用 sort_desc()(见第 10.2 节)。
  3. 游标生成条件:只有 res.len() >= limit 才产出 next_cursor;res.len() < limit 时 next_cursor = None,表示已到末页:
match res.len().cmp(&limit) {
    Ordering::Less => Paginated { items: res, next_cursor: None },
    Ordering::Equal | Ordering::Greater => Paginated {
        next_cursor: res.last().map(|last| Cursor {
            id: last.id(),
            limit,
            val: cb(last),
            filter: filter_on,
        }).map(Base64Str::encode_json),
        items: res,
    },
}

这里有个隐含前提:调用方必须保证「恰好等于 limit」时确实还有下一页,否则会多给一个指向空页的游标。仓库里的两种处理方式正好互为对照:

  • channels 列表先向服务层多取一行来判定 has_more,再用 next_cursor.filter(|_| has_more) 兜底,见 crates/channels/src/inbound/list_router.rs。
  • soup 的多源分页依赖 chain 后仍有更多候选,因此直接接受 Equal 分支语义。

4.4 Paginated 的容器能力

分页结果结构极简(src/cursor.rs):

pub struct Paginated<T, U> {
    pub items: Vec<T>,
    pub next_cursor: Option<U>,
}

它提供 map(变换条目类型而保留游标)、into_parts(解构为 (Vec<T>, Option<U>))与 from_parts(从两部分重建)。Paginated 标注了 #[non_exhaustive],意味着下游不能对它做穷尽式结构匹配,为将来加字段留了余地。

5. 内置排序方法:五种语义与一个「游标区分」问题

src/sort.rs 提供开箱即用的排序类型,全部以 snake_case 序列化(即 "viewed_at"、"created_at" 等)。

5.1 SimpleSortMethod:四种时间戳语义

pub enum SimpleSortMethod {
    ViewedAt,        // 按 viewed_at
    UpdatedAt,       // 按 updated_at
    CreatedAt,       // 按 created_at
    ViewedUpdated,   // 按 viewed/updated 合并语义
}
impl Sortable for SimpleSortMethod { type Value = DateTime<Utc>; }

ViewedUpdated 的具体合并规则落在 SQL 里。以 soup 的未展开查询为例,crates/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rs 用一条 CASE 把排序方法字符串映射成 sort_ts:

CASE $2
    WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", d."updatedAt")
    WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
    WHEN 'created_at'  THEN d."createdAt"
    ELSE d."updatedAt"
END::timestamptz as "sort_ts!"

注意 viewed_at 对未读条目回退到 1970 年(即排到最底部),而 viewed_updated 回退到 updatedAt。这正是「简单排序方法由领域 SQL 定义语义,crate 只负责把方法名带进游标」的分工体现。SimpleSortMethod 还实现了 Display,通过 serde_json 序列化再裁掉引号得到字符串,供 SQL 绑定参数使用(src/sort.rs)。

5.2 CreatedAt:只支持单一语义的场合

pub struct CreatedAt;
impl Sortable for CreatedAt { type Value = DateTime<Utc>; }

源码注释说明了它存在的理由:有些接口目前只支持 CreatedAt,而不支持全部 SimpleSortMethod。例如频道附件分页就固定用 CreatedAt,见 crates/channels/src/inbound/axum_router.rs。

5.3 Frecency 与 FrecencyValue:混合两种值域的可比较枚举

frecency 分页最棘手的地方在于:一部分条目有相关性分数,另一部分没有。解法是把值域建模成枚举并手工实现全序(src/sort.rs):

pub enum FrecencyValue {
    FrecencyScore(f64),
    UpdatedAt(DateTime<Utc>),
}

impl std::cmp::Ord for FrecencyValue {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match (self, other) {
            (FrecencyValue::FrecencyScore(a), FrecencyValue::FrecencyScore(b)) =>
                OrderedFloat(*a).cmp(&OrderedFloat(*b)),
            (FrecencyValue::UpdatedAt(a), FrecencyValue::UpdatedAt(b)) => a.cmp(b),
            // score is always ranked before a timestamp
            (FrecencyValue::FrecencyScore(_), FrecencyValue::UpdatedAt(_)) =>
                std::cmp::Ordering::Greater,
            (FrecencyValue::UpdatedAt(_), FrecencyValue::FrecencyScore(_)) =>
                std::cmp::Ordering::Less,
        }
    }
}

「分数永远排在时间戳之前」这条不变量与 SortOn<Frecency> 的回退逻辑配合,形成确定的扫描顺序:先遍历所有有分数的条目,分数耗尽后再按 updated_at 继续。这一点在 FrecencyValue 的字段注释里写得很直白:UpdatedAt 分支表示「已经越过所有有分数的条目,回退到创建/更新时间继续分页」。

Frecency 自身序列化为 null(因为它是一个无字段的单元结构体且没有自定义 serde),而 CursorVal 的外部标签序列化会把 sort_type 一起写进去——这就是 TouchedByMe/NotifiedAt 需要特殊标记的原因。

5.4 TouchedByMe 与 NotifiedAt:用标记位区分同形游标

这两个排序的语义都不是简单时间戳:

  • TouchedByMe:按「当前用户最近一次修改该实体的时间」排序,数据来自 activity log。它同时充当过滤器——用户从未修改过的实体没有排序值,不会出现在结果里。
  • NotifiedAt:按「当前用户最近一次收到该实体通知的时间」排序,数据来自 user_notification。同样兼作过滤器。

二者 Value 都是 DateTime<Utc>,而 TouchedByMe 序列化为 null。问题来了:如果 NotifiedAt 也序列化为 null,两个游标在 JSON 上完全同形,反序列化时无法判断该解成哪一个。于是 NotifiedAt 被实现为字符串标记:

const NOTIFIED_AT_TAG: &str = "notified_at";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct NotifiedAt;

impl From<NotifiedAt> for String {
    fn from(_: NotifiedAt) -> Self { NOTIFIED_AT_TAG.to_string() }
}

impl TryFrom<String> for NotifiedAt {
    type Error = String;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value == NOTIFIED_AT_TAG { Ok(NotifiedAt) }
        else { Err(format!("expected {NOTIFIED_AT_TAG:?}, got {value:?}")) }
    }
}

这段「看似绕远」的实现,被 src/sort/test.rs 的三个单元测试完整覆盖:

测试 断言内容
notified_at_marker_round_trips_as_a_string 序列化结果必须是 "notified_at",且能原样解析回来
notified_at_marker_rejects_other_tags "touched_by_me" 与 null 都必须解析失败
touched_and_notified_cursor_values_do_not_cross_decode 两个 CursorVal 交叉反序列化必须双向失败

第三个测试是这套设计的关键证明:它构造 CursorVal<TouchedByMe> 与 CursorVal<NotifiedAt> 的 JSON,断言 from_str::<CursorVal<NotifiedAt>>(&touched) 与反向均 is_err()。也就是说,游标类型安全不只在编译期成立,在运行期的 wire format 层面也成立。

这套机制在 soup 的路由层被用于四路游标分派(crates/soup/src/inbound/axum_router.rs):

type SoupCursor<R> = Either4<
    Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, R>>,
    Option<CursorWithValAndFilter<Uuid, Frecency, R>>,
    // String id, not Uuid: the touched keyset compares the raw stored
    // entity id byte-for-byte, so the cursor must not canonicalize it.
    Option<CursorWithValAndFilter<String, TouchedByMe, R>>,
    // Same value shape as the touched cursor; its `"notified_at"` sort
    // marker (touched serializes `null`) is what keeps it out of arm 3.
    Option<CursorWithValAndFilter<String, NotifiedAt, R>>,
>;

两个细节值得记住:TouchedByMe 的 id 用 String 而非 Uuid,因为键集比较是「原始存储字节逐个比较」,不能做 UUID 规范化;而 NotifiedAt 与 TouchedByMe 的可区分性完全依赖上文那个字符串标记。

6. Query:排序方法或游标,二选一

路由层拿到的参数要么是「排序方式 + 过滤条件」(首页请求),要么是「游标」(续页请求)。Query 把这两种情况统一建模(src/cursor.rs):

pub enum Query<I, T: Sortable, F> {
    Sort(T, F),
    Cursor(CursorWithValAndFilter<I, T, F>),
}

关键方法一览:

方法 作用
Query::new(maybe_cursor, sort, filter) 有游标走 Cursor,否则构造 Sort,是首页/续页分支的标准写法
sort_method() 两种变体都返回 &T,让存储层无需分支就能拿到排序方式
filter() 两种变体都返回 &F
vals() 返回 (Option<&I>, Option<&T::Value>);Sort 变体返回 (None, None)
map_filter(cb) 只变换过滤类型,保留其余字段
try_map_filter(cb) 同上但可失败
split_option() 针对 F = Option<F2>,把 Option 提到 Either 外层,得到「无过滤」与「有过滤」两条类型分支

split_option 的实战意义在 soup 里体现得最清楚:crates/soup/src/domain/models.rs 用 SimpleSortQuery 四态(无过滤 / 仅 frecency 过滤 / 仅 AST 过滤 / 两者叠加),把 Query<Uuid, SimpleSortMethod, Option<EntityFilterAst>> 静态地转换过去,于是每条下游查询分支的泛型参数都是具体类型,不需要运行期 if filter.is_some()。

vals() 的消费方是 SQL 层,例如 crates/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rs:

let sort_method_str = cursor.sort_method().to_string();
let (cursor_id, cursor_timestamp) = cursor.vals();
let cursor_id = cursor_id.map(|u| u.to_string());

随后这两个值作为 $4、$5 绑定进键集条件(同文件第 191-203 行):

SELECT * FROM Combined
WHERE ($4::timestamptz IS NULL)
    OR ("sort_ts!", "id!") < ($4, $5)
ORDER BY "sort_ts!" DESC, "id!" DESC
LIMIT $3

($4 IS NULL) 分支让首页请求(无游标)也能复用同一条 SQL——这正是 Query::Sort 变体 vals() 返回 (None, None) 的用途。("sort_ts", "id") < (?, ?) 是行值比较,等价于「排序值更小,或排序值相同但 id 更小」,即标准的 keyset pagination。

7. axum 集成(feature = "axum")

开启 axum feature 后,Cursor/BidirectionalCursor 可以直接作为 handler 参数出现,无需手写 query 解析。

7.1 单向前进游标:Option<Cursor<...>>

crates/models_pagination/src/axum.rs 为 Cursor<Id, CursorVal<Sort>, F> 实现了 OptionalFromRequestParts:

  1. 用一个私有 Params { cursor: Option<String> } 结构体通过 Query 提取 cursor 查询参数;解析失败映射为 InvalidQueryParamsErr。
  2. 未提供 cursor 时返回 Ok(None)——这就是为什么 handler 里可以直接写 cursor: Option<CursorWithValAndFilter<..>>。
  3. 提供时先做长度检查,超过 32 000 字节则返回 SizeErr;然后再 base64 解码 + JSON 反序列化。
  4. 整个函数带 #[tracing::instrument(err(level = Level::WARN), skip(parts, state))],解码失败会自动产生一条 WARN 级 trace,无需在 handler 里手工记录。

7.2 双向游标:BidirectionalCursor

BidirectionalCursor 支持「加载更新」方向(src/axum.rs):

pub enum BidirectionalCursor<Id, S: Sortable, F> {
    /// The client provided a cursor to fetch the next page.
    Next(Cursor<Id, CursorVal<S>, F>),
    /// The client provided a cursor to fetch the previous page.
    Previous(Cursor<Id, CursorVal<S>, F>),
}

它同时读取 cursor 与 previous_cursor 两个查询参数,三态处理:

参数组合 行为
两个都提供 MutuallyExclusiveErr
只有 cursor BidirectionalCursor::Next(..)
只有 previous_cursor BidirectionalCursor::Previous(..)
都不提供 Ok(None)(首页)

「互斥而非优先级」是刻意的:静默忽略其中一个会让客户端以为自己的翻页方向生效了,实际却在往反方向走。

7.3 错误到 HTTP 的映射

CursorExtractErr(src/axum.rs)实现了 IntoResponse,把所有变体统一映射成 400,但保留区分度不同的 message:

变体 HTTP 状态 响应 message
DecodeErr(DecodeErr(..)) 400 failed to decode cursor value
DecodeErr(SerdeErr(..)) 400 the cursor contained unexpected data
SizeErr 400 Query is too large, must be <32kb
InvalidQueryParamsErr 400 invalid cursor query parameters
MutuallyExclusiveErr 400 provide only one of cursor or previous_cursor

注意 SizeErr 的检查发生在 base64 解码之前(第 90-93 行先取 encoded.len() 再 decode),因此在恶意构造超长游标时不会先做一遍昂贵的解码与 JSON 解析。

7.4 CursorOptionExt:一行完成 Option → Query

pub trait CursorOptionExt<Id, S: Sortable, F> {
    fn into_query(self, sort: S, filter: F) -> crate::cursor::Query<Id, S, F>;
}

它把 Option<CursorWithValAndFilter<I, S, F>> 直接转成 Query。调用点因此非常短,见 crates/channels/src/inbound/axum_router.rs:

cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {
    let limit = params.limit.unwrap_or(50);
    let has_cursor = cursor.is_some();
    let query = cursor.into_query(CreatedAt, ());

8. 类型擦除与响应模型

内部处理希望保留完整类型信息(Cursor<Uuid, CursorVal<SimpleSortMethod>, EntityFilterAst>),但对外的响应只需要一个字符串。crate 提供两组别名 + 一个 trait:

pub type PaginatedCursor<T, I, C, F> = Paginated<T, Base64Str<CursorWithValAndFilter<I, C, F>>>;
pub type PaginatedOpaqueCursor<T> = Paginated<T, String>;

TypeEraseCursor 负责从前者转到后者(src/cursor.rs):

pub trait TypeEraseCursor<T> {
    fn type_erase(self) -> PaginatedOpaqueCursor<T>;
}

重要的是它实现了两遍:一次对 PaginatedCursor,一次对 Either<PaginatedCursor<..>, PaginatedCursor<..>>。第二个实现让「同一个接口可能返回两种游标类型」的场景(例如 soup 的 frecency 与简单排序走不同分支)无需在 handler 里写 match,直接 res.type_erase() 即可。Base64Str::type_erase() 只是把内部 String 取出来,不重新编码,所以类型擦除是零成本的。

调用点示例见 crates/soup/src/inbound/axum_router.rs:

let mut page = res.type_erase().map(SoupApiItem::from_frecency_soup_item);

Paginated::map 保留 next_cursor、只换 items,因此「领域条目 → API DTO」的转换与分页逻辑完全解耦。

响应结构上还有一层约定:SoupPage 把 next_cursor 直接暴露成 Option<String>(crates/soup/src/inbound/axum_router.rs),而 GraphQL 层同样以 Option<String> 输出(crates/graphql_soup/src/objects.rs)。这就是 PaginatedOpaqueCursor 设计成 Paginated<T, String> 的原因:HTTP 与 GraphQL 两条出口共用同一个「不透明游标字符串」契约。

9. 集合辅助:CollectByIds 与 CollectBy

分页拿到一页之后,常见需求是按主键建索引、或按字段分桶。src/collections.rs 提供两个迭代器扩展:

pub trait CollectByIds<A>: Iterator<Item = A>
where A: Identify, <A as Identify>::Id: Hash + Eq
{
    fn collect_by_ids(self) -> HashMap<<A as Identify>::Id, A>;
}

pub trait CollectBy: Iterator {
    fn group_by<F, Id>(self, cb: F) -> HashMap<Id, Vec<Self::Item>>
    where F: FnMut(&Self::Item) -> Id, Id: Hash + Eq;
}

collect_by_ids 直接复用 Identify,因此凡是为分页实现过 Identify 的类型,自动获得按主键 O(1) 查找的能力——这是「同一套 trait 复用于分页与批量装配」的典型收益。group_by 则用于分组响应(例如 soup 的 grouped 结果按 EntityType、Project、属性值分桶)。

10. 端到端案例

10.1 单表分页:频道列表

crates/channels/src/inbound/list_router.rs 是一个完整、可直接照抄的模板:

let limit = params.limit.unwrap_or(DEFAULT_CHANNEL_LIST_LIMIT).clamp(1, MAX_CHANNEL_LIST_LIMIT);
let res = service.inner.get_channels(GetChannelsRequest {
    macro_id: user.macro_user_id.clone(),
    // Fetch one extra row so pagination can distinguish a full final
    // page from a page with more results.
    limit: Some(limit.saturating_add(1)),
    include_frecency: true,
    query: cursor.into_query(SimpleSortMethod::UpdatedAt, ()).map_filter(|_| None),
}).await.map_err(|_| ChannelListRouterErr::Internal)?;

let has_more = res.len() > limit as usize;
let Paginated { items, next_cursor, .. } = res
    .into_iter()
    .paginate_on(limit as usize, SimpleSortMethod::UpdatedAt)
    .filter_on(())
    .into_page()
    .type_erase();

Ok(Json(ApiChannelListPage {
    items: items.into_iter().map(ApiChannelWithLatest::new_from_domain).collect(),
    next_cursor: next_cursor.filter(|_| has_more),
}))

值得逐条拆解的工程细节:

  1. 多取一行:limit + 1 让 res.len() > limit 能判定「还有更多」,解决第 4.3 节提到的 Equal 歧义;最后用 next_cursor.filter(|_| has_more) 修正。
  2. clamp 限制:页大小在路由层收敛,避免超大页拖垮数据库。
  3. map_filter(|_| None):领域请求的过滤类型是 Option<...>,这里显式置空;Map_filter 只动过滤字段,游标其余部分原样保留。
  4. filter_on(()):因为对外没有额外过滤条件,所以用空过滤器;() 会随游标一起序列化(在 JSON 中表现为 null)。

10.2 多源合并分页:soup

soup 需要把文档、邮件、频道、通话、CRM、外部分支等多个来源合并成一个时间线。做法是先用 chain 拼接多个迭代器,再做一次分页:

let paginator = main_soup?
    .chain(email_soup?)
    .chain(comms_soup?)
    .chain(comms_thread_soup?)
    .chain(call_soup?)
    .chain(crm_company_soup?)
    .chain(crm_contact_soup?)
    .chain(foreign_entity_soup?)
    .paginate_on(limit.into(), sort_method)
    .filter_on(entity_filter);

let page = match sort_direction {
    SoupSortDirection::Asc => paginator.sort_asc(),
    SoupSortDirection::Desc => paginator.sort_desc(),
}.into_page();

见 crates/soup/src/domain/service.rs。这就是 sort_asc/sort_desc 存在的真实理由:每个来源各自返回有序片段,chain 之后整体无序,必须由 into_page 内部的排序兜底。同一文件的 frecency 分支更短:

self.handle_advanced_sort(cursor, req.soup_type, req.user, limit, include_projection)
    .await?
    .paginate_on(limit.into(), Frecency)
    .filter_on(entity_filter)
    .into_page()

(第 1818-1830 行。)注意 Frecency 分支不调用 sort_desc()——高级排序的候选集已由查询层按分数排好。

10.3 手工构造游标:当分页机制不足以表达语义时

TouchedByMe / NotifiedAt 的候选集来自 activity log 与通知表,其「下一页位置」不是「最后一条的排序值」那么简单,于是服务层直接构造 Cursor 并调用 Base64Str::encode_json(crates/soup/src/domain/service.rs):

let next_cursor = next.map(|position| {
    Base64Str::encode_json(Cursor {
        id: position.entity_id,
        limit: limit.into(),
        val: CursorVal {
            sort_type: TouchedByMe,
            last_val: position.occurred_at,
        },
        // ...
    })
});

这说明 Paginator 只是便利路径,而 Cursor + Base64Str 才是协议本体。只要产出的 JSON 结构与提取端期望的 CursorWithValAndFilter<I, S, F> 一致,就可以绕过 Paginator 手工编码。

10.4 测试中的用法:从生成游标到回传

crates/soup/src/inbound/axum_router/tests.rs 演示了完整的往返流程:

impl SortOn<Frecency> for Data {
    fn sort_on(_sort: Frecency) -> impl FnMut(&Self) -> models_pagination::CursorVal<Frecency> {
        |v| CursorVal {
            sort_type: Frecency,
            last_val: FrecencyValue::FrecencyScore(v.0 as f64),
        }
    }
}

let res = (0..1000)
    .map(|x| Data(x, Uuid::new_v4()))
    .paginate_on(100, Frecency)
    .filter_on(filter)
    .into_page();

let cursor = res.type_erase().next_cursor.unwrap();
// 把 cursor 拼进 /soup?cursor=... 再发一次请求

这段测试同时验证了三件事:SortOn 可以作用于任意测试数据结构;paginate_on(100, ..) 对 1000 个条目必然产出 next_cursor;type_erase().next_cursor 得到的字符串可以直接作为真实 HTTP 查询参数回传并被服务端按 FrecencyCursor 正确识别。

11. 操作手册:新增一种排序方法

CLAUDE.md 给出的配方是一条三步链路:

src/sort.rs(impl Sortable / SortOn)→ 调用方的 Identify 实现 → 它的列表查询。

展开成可执行步骤:

第一步:定义排序类型并实现 Sortable。 在 src/sort.rs 里加类型;若是无字段单元结构体,注意它的 serde 形态(Frecency、TouchedByMe 序列化为 null,NotifiedAt 则自定义为字符串)。如果你的新方法与已有方法「值类型相同、序列化形态相同」,就必须像 NotifiedAt 那样引入独立标记,否则游标会交叉解码。

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct MySort;

impl Sortable for MySort {
    type Value = DateTime<Utc>; // 必须是 Ord
}

第二步:为目标条目实现 SortOn<MySort>。 放在条目类型所在的领域 crate 里,而不是 models_pagination 中——这是 crate 边界要求。可参考 MessageListItem 或 SoupCandidate 的写法。若条目已被包装(如 SoupCandidate 包裹 SoupItem),可以把调用转发给内层类型。

第三步:确保领域查询能消费该排序方法。 这是唯一需要真正写 SQL / 查询逻辑的地方:把 cursor.sort_method() 映射成排序列,把 cursor.vals() 的两个值绑定到 (sort_col, id) < (?, ?) 条件,并保留 IS NULL 分支以支持首页。soup 的 CASE $2 ... END as "sort_ts!" 是最有代表性的实现。

第四步:若该排序支持升序,检查方向处理。 soup 的 handler 对 asc 与 frecency、touched_by_me、notified_at 的组合直接返回错误(crates/soup/src/inbound/axum_router.rs),因为这类排序的游标比较假设了降序。API 文档注释(同文件第 92-99 行)也明确写了「每个分页都要重发 sort_direction,它不在游标里」。新增方法时必须在同样的位置决定:支持升序、拒绝升序,还是把方向写进游标。

第五步:补测试。 至少两条:一条验证新排序类型的 serde 形态;若是引入标记的类型,再加一条交叉解码必须失败的断言(照 touched_and_notified_cursor_values_do_not_cross_decode 写)。

12. 校验与常见坑

12.1 运行测试

cargo test -p models_pagination

CLAUDE.md 特别注明需要 SQLX_OFFLINE 未设置。原因从依赖就能看出:该 crate 本身是纯分页机械,测试不触数据库,而不设置 SQLX_OFFLINE 可以确保整个 workspace 的 sqlx 宏行为与在线编译期检查一致,不会因预生成的离线元数据掩盖问题。

12.2 常见坑清单

坑 现象 规避方式
Equal 分支误判还有下一页 客户端多拿到一个空页 像 channels 那样多取一行 + `next_cursor.filter(
多源 chain 后忘记排序 结果顺序错乱 soup 用 sort_asc()/sort_desc() 兜底
未排序输入 + 无 ensure_sort 顺序由数据源决定 让数据库 ORDER BY 负责排序,或显式调用方向方法
浮点排序值 无法满足 Ord 用 ordered-float 的 OrderedFloat 包装
新排序类型序列化为 null 且值类型与已有类型相同 游标交叉解码到错误类型 自定义 serde(into/try_from = "String") 标记,见 NotifiedAt
游标里放不可控大小的过滤条件 请求被 32KB 上限拒绝 压缩过滤条件表示,或把其在游标中降到最小
用 Uuid 表示需要字节比较的 id 规范化导致键集跳过/重复 TouchedByMe 使用 String id(见 SoupCursor 注释)
同时传 cursor 与 previous_cursor 400 provide only one of cursor or previous_cursor 客户端保证二选一

12.3 这份设计带来的三个收益

  1. 协议统一:所有列表接口的 next_cursor 都是不透明 base64 字符串,客户端不需要知道内部是时间戳还是分数。
  2. 类型安全贯穿到 wire format:CursorVal 携带 sort_type,NotifiedAt 的字符串标记与交叉解码测试把「运行期串味」变成可测的失败。
  3. 职责单一:models_pagination 只管「怎么切页、怎么编码」,语义(viewed_updated 怎么算、frecency 怎么排序)留给领域 SQL。这也解释了为什么 soup 的 CASE $2 会出现在数据库层而不是这个 crate 里。

13. 相关文件速查

关注点 文件
crate 导出的全部公共 API crates/models_pagination/src/lib.rs
Identify/Sortable/SortOn/Cursor/Paginator/Query/Base64Str crates/models_pagination/src/cursor.rs
内置排序方法与其单元测试 crates/models_pagination/src/sort.rs、crates/models_pagination/src/sort/test.rs
axum 提取器与错误映射 crates/models_pagination/src/axum.rs
集合辅助 trait crates/models_pagination/src/collections.rs
依赖与 feature 定义 crates/models_pagination/Cargo.toml
单表分页范例 crates/channels/src/inbound/list_router.rs
多源合并、手工游标范例 crates/soup/src/domain/service.rs
四路游标分派与方向校验 crates/soup/src/inbound/axum_router.rs
键集 SQL 实现 crates/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rs
GraphQL 出口 crates/graphql_soup/src/objects.rs
登录后查看全文
macro