通知

通知用来给指定用户发站内信、实时弹窗和邮件提醒,并自带收件箱分页、未读计数与已读标记。本篇在发票付款事务里发送一条通知,让收款人落库收到站内信并在连接在线时立刻收到推送。

架构图示

写代码#

第 1 步:新建 Cargo.toml,启用 SQLite、迁移与 notify 插件:

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

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

第 2 步:新建 config/database.toml(通知表与业务表共用这个库,记得把 billing.sqlite* 加入 .gitignore):

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

第 3 步:新建 src/inbox.rs,定义 InvoicePaid 通知、收件箱查询接口和 WebSocket 连接绑定:

Rust
use kxed::net::{Uid, Ws};
use kxed::plugins::notify::{Channels, DatabaseNotification, Notification, Recipient};
use kxed::prelude::*;
use kxed::serde_json::{json, Value};

/// 本篇不接认证,用户 id 写在路径里,账户都归在应用自己起名的 guard `user` 下;同一个 uid 既是站内信的收件人,也是连接绑定的 uid。
fn account(user: &str) -> Uid {
    Uid::of("user", user)
}

pub(crate) struct InvoicePaid {
    invoice: u64,
}

impl Notification for InvoicePaid {
    const NAME: &'static str = "invoice_paid";

    fn via(&self, _to: &Recipient) -> Channels {
        Channels::new().database().push()
    }

    fn to_database(&self) -> Value {
        json!({ "invoice": self.invoice })
    }
}

pub(crate) async fn pay(ctx: AppCtx, Path((user, invoice)): Path<(String, u64)>) -> Result<StatusCode, AppErr> {
    let transaction = ctx.db()?.begin_write().await?;
    // 把发票标成已付的业务写入用同一个 transaction。
    ctx.notify(account(&user), InvoicePaid { invoice }).within(&transaction).await?;
    transaction.commit().await?;
    Ok(StatusCode::CREATED)
}

#[derive(Serialize)]
pub(crate) struct NotificationView {
    name: String,
    body: Value,
    read: bool,
}

impl From<DatabaseNotification> for NotificationView {
    fn from(notification: DatabaseNotification) -> Self {
        Self { name: notification.name, body: notification.body, read: notification.read_at.is_some() }
    }
}

pub(crate) async fn index(ctx: AppCtx, Path(user): Path<String>, query: CursorQuery) -> Result<Collection<NotificationView>, AppErr> {
    let page = ctx.notifications(account(&user)).page(&query).await?;
    Ok(page.map(NotificationView::from))
}

pub(crate) async fn unread(ctx: AppCtx, Path(user): Path<String>) -> Result<Json<Value>, AppErr> {
    let unread = ctx.notifications(account(&user)).unread_count().await?;
    Ok(Json(json!({ "unread": unread })))
}

pub(crate) async fn read_all(ctx: AppCtx, Path(user): Path<String>) -> Result<Json<Value>, AppErr> {
    let marked = ctx.notifications(account(&user)).mark_all_read().await?;
    Ok(Json(json!({ "marked": marked })))
}

#[derive(Deserialize)]
struct Join {
    user: String,
}

/// 自定义协议:第一帧自报 `user` 并绑定,之后这条连接只接收推送。
pub(crate) async fn socket(mut socket: Ws) -> Result<(), AppErr> {
    let Some(first) = socket.recv().await? else {
        return Ok(());
    };
    let join: Join = first.json()?;
    socket.bind(account(&join.user))?;
    while socket.recv().await?.is_some() {}
    Ok(())
}

第 4 步:把 NotifyStore::migrations() 放进数据库迁移最前面并注册 NotifyPlugin,写 src/main.rs:

Rust
mod inbox;

use kxed::plugins::notify::{NotifyPlugin, NotifyStore};
use kxed::plugins::seaorm::sea_orm_migration::{MigrationTrait, MigratorTrait};
use kxed::plugins::seaorm::{async_trait, MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;

struct Migrator;

#[async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        NotifyStore::migrations()
    }
}

pub(crate) fn app() -> App {
    App::new()
        .plugin(SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("billing.migrations")))
        .plugin(NotifyPlugin::new())
        .routes(|router| {
            router
                .route("/users/{user}/invoices/{invoice}/pay", post(inbox::pay))
                .route("/users/{user}/notifications", get(inbox::index))
                .route("/users/{user}/notifications/unread", get(inbox::unread))
                .route("/users/{user}/notifications/read", post(inbox::read_all));
        })
        .ws("/ws", inbox::socket)
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    app().run().await
}
  • 统一收件人 Uid:接入 认证 后不用从 URL 传用户名,直接传 ctx.require_identity().await?.uid()(后台任务里传 Uid::of(&ctx.default_guard()?, id));同一个 Uid 在站内信、WebSocket push 和 Livecell 通知条之间通用(见 术语表)。

验证#

在干净的数据库上运行 cargo run,另开终端给 alice 付两张发票,查询收件箱与未读数、全部标为已读,并核对 bob 的未读数(约定见 怎么读):

Shell
curl --silent --output /dev/null --write-out '%{http_code}\n' -X POST http://127.0.0.1:8080/users/alice/invoices/7/pay
curl --silent --output /dev/null --write-out '%{http_code}\n' -X POST http://127.0.0.1:8080/users/alice/invoices/8/pay
curl --fail --silent http://127.0.0.1:8080/users/alice/notifications; echo
curl --fail --silent http://127.0.0.1:8080/users/alice/notifications/unread; echo
curl --fail --silent -X POST http://127.0.0.1:8080/users/alice/notifications/read; echo
curl --fail --silent http://127.0.0.1:8080/users/alice/notifications/unread; echo
curl --fail --silent http://127.0.0.1:8080/users/bob/notifications/unread; echo

预期输出:

输出
201
201
{"data":[{"name":"invoice_paid","body":{"invoice":8},"read":false},{"name":"invoice_paid","body":{"invoice":7},"read":false}],"meta":{"limit":15,"next_cursor":null,"has_more":false},"links":{"first":"/users/alice/notifications","last":null,"prev":null,"next":null}}
{"unread":2}
{"marked":2}
{"unread":0}
{"unread":0}

最新通知排在最前,alice 标已读后未读数归零,bob 始终看不到 alice 的通知。如果提前用 websocat ws://127.0.0.1:8080/ws 连上并发首帧 {"user":"alice"},付款瞬间还会收到实时推送帧:

JSON
{"kind":"kxed.notification","body":{"id":"0199c2f0a1b27c3e9d4f5a6b7c8d9e0f","name":"invoice_paid","body":{"invoice":9}}}
  • 客户端去重:推送里的 body.id 就是站内信主键,网络抖动重推时前端按这个 ID 去重即可;原生 Ws handler 记得先调 socket.bind(uid) 才能收到推送。

自动化测试#

开启 testing 特性后,可以用内存 SQLite 隔离每个测试用例,并直接通过 app.notifications(&uid) 断言收件箱状态(测 WebSocket 推送帧用 app.ws(path),见 testing README)。

第 1 步:在 Cargo.toml 末尾追加:

TOML
[dev-dependencies]
kxed = { version = "0.0.5-alpha", features = ["testing"] }

第 2 步:新建 src/tests.rs:

Rust
use kxed::net::Uid;
use kxed::prelude::*;
use kxed::testing::TestApp;

#[kxed::tokio::test(flavor = "multi_thread")]
async fn paying_an_invoice_leaves_one_unread_notification() {
    // 业务库换成测试独享的内存库。
    let config = kxed::testing::ephemeral(ConfigLoader::new()).with_override("database.url", "sqlite::memory:").unwrap();
    let app = TestApp::start(crate::app().config(config)).await.unwrap();
    app.post("/users/carol/invoices/7/pay").await.assert_status(201);
    app.get("/users/carol/notifications/unread").await.assert_status(200).assert_json_path("/unread", 1);
    let carol = Uid::of("user", "carol");
    assert_eq!(app.notifications(&carol).unread_count().await.unwrap(), 1);
    app.shutdown().await.unwrap();
}

第 3 步:挂载测试模块并运行 cargo test,到这一步 src/main.rs 的完整内容是:

Rust
mod inbox;
#[cfg(test)]
mod tests;

use kxed::plugins::notify::{NotifyPlugin, NotifyStore};
use kxed::plugins::seaorm::sea_orm_migration::{MigrationTrait, MigratorTrait};
use kxed::plugins::seaorm::{async_trait, MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;

struct Migrator;

#[async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        NotifyStore::migrations()
    }
}

pub(crate) fn app() -> App {
    App::new()
        .plugin(SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("billing.migrations")))
        .plugin(NotifyPlugin::new())
        .routes(|router| {
            router
                .route("/users/{user}/invoices/{invoice}/pay", post(inbox::pay))
                .route("/users/{user}/notifications", get(inbox::index))
                .route("/users/{user}/notifications/unread", get(inbox::unread))
                .route("/users/{user}/notifications/read", post(inbox::read_all));
        })
        .ws("/ws", inbox::socket)
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    app().run().await
}

常用写法速查#

要做的事写法
定义一种通知实现 Notification,设好固定 NAME 与 to_database(推送内容不同时另写 to_push)
同时发站内信与在线推送via 返回 Channels::new().database().push()
发给当前登录用户ctx.notify(identity.uid(), InvoicePaid { .. }).await?(加 .within(&txn) 随业务事务同成同败)
发给团队或门店等非个人实体收件人传 Recipient::entity("team", id)(仅支持 database 站内信,选 push 返回 400)
查未读列表、单条已读、删除ctx.notifications(&to).unread().page(&query)、mark_read(id)、delete(id)(操作他人通知返回 false)
查积压与重放死信运行 cargo run -- notify status 与 notify dead list/retry/purge
  • 站内信与实时推送搭配:database() 直接写入收件箱表,push() 先写同事务 outbox 表再由后台推给当前在线连接(离线不补发);重要通知同时勾选两者,用户在线能秒收弹窗,离线回来打开收件箱也不会漏看。
  • 多实例自动协同:多个实例连同一个数据库即可按租约分担 outbox 投递,并自动把实时推送路由到持有该用户连接的节点(见 Notify N>1)。

应用通道#

要同时发邮件、短信或飞书/钉钉群机器人通知时,实现 NotifyChannel 并注册到 NotifyPlugin(纯 JSON Webhook 可直接注册内置的 HttpChannel::post_json(url),见 应用通道):

Rust
struct MailChannel;

impl NotifyChannel for MailChannel {
    type Error = AppErr;

    async fn deliver(&self, ctx: &AppCtx, delivery: &ChannelDelivery) -> Result<(), AppErr> {
        let mailer = ctx.require_state::<Mailer>()?;
        let to = delivery.body["to"].as_str().unwrap_or_default();
        let message_id = format!("<notify-{}@example.com>", delivery.outbox_id);
        send_mail(&mailer, &message_id, to, "Your order has shipped", String::new()).await
    }
}

impl Notification for OrderShipped {
    const NAME: &'static str = "order_shipped";

    fn via(&self, _to: &Recipient) -> Channels {
        Channels::new().database().custom("mail")
    }

    fn to_database(&self) -> Value {
        json!({ "order": self.order_id })
    }

    fn to_channel(&self, _channel: &str) -> Value {
        json!({ "to": self.email, "order": self.order_id })
    }
}

App::new().plugin(NotifyPlugin::new().with_channel("mail", MailChannel))
  • 自包含正文与幂等去重:后台异步投递时没有原 HTTP 请求上下文,收件邮箱或手机号要写进 to_channel 返回的 JSON 里;delivery.outbox_id 在多次重试间保持不变,用来拼邮件 Message-ID 或短信幂等键。502/503 错误自动退避重试,4xx 错误或超过 notify.max_attempts 后进入死信(用 notify dead list --channel mail 查看)。

常见排错#

现象原因解决方法
发送通知时报错找不到 kxed_notifications 表数据库 Migrator 里漏加了通知插件的系统表迁移在 Migrator::migrations() 开头合入 NotifyStore::migrations()
站内信已落库,但在线 WebSocket 没收到实时帧原生 Ws 连接建立后未调用 socket.bind(uid),或两边的 Uid guard 名不一致握手后调 socket.bind(account)?,确保与 ctx.notify 传入完全相同的 Uid
给团队实体发通知返回 400Recipient::entity("team", id) 非个人连接实体不支持实时 push()在 via 中根据 _to 判断,实体收件人只返回 Channels::new().database()

参考#