通知
属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io
提供业务事务一致的站内信与基于 Outbox 租约的多通道可靠通知投递。站内信随业务写入原子同提交;在线 WebSocket 实时推送与自定义外部渠道(短信、邮件、Slack/飞书 Webhook)写入 Outbox 后由后台 NotifyRelay 按租约投递,内置指数退避重试、死信队列与 CLI 运维工具。完整实战见 通知教程。
flowchart LR
biz["ctx.notify(&to, n).within(&txn)"] --> txn["同一数据库事务提交"]
txn --> inbox["kxed_notifications 站内信表(立即可读)"]
txn --> outbox["kxed_notify_outbox 待投递表"]
outbox --> relay["后台 NotifyRelay(租约领取 + 退避重试)"]
relay --> push["InstalledUserPush 在线实时推送(WebSocket)"]
relay --> ext["应用外部渠道(短信 / Webhook / 邮件,超限入死信)"]快速接入#
在 Cargo.toml 开启主包 kxed 的通知与数据库特性(若使用内置 JSON Webhook 通道 HttpChannel,一并开启 http-client;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["notify", "seaorm-sqlite"] }):
[dependencies]
kxed = { version = "0.0.5-alpha", features = [
"notify",
"http-client",
"seaorm-sqlite",
"seaorm-migration",
] }将 NotifyStore::migrations() 并入应用的数据库迁移,注册 NotifyPlugin::new(),即可在业务事务内原子发送通知并查询未读站内信:
use kxed::plugins::notify::{Channels, DatabaseNotification, Notification, NotifyPlugin, NotifyStore, Recipient};
use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;
use serde_json::{json, Value};
struct OrderShipped {
order_id: i64,
}
impl Notification for OrderShipped {
const NAME: &'static str = "order_shipped";
fn via(&self, _to: &Recipient) -> Channels {
Channels::new().database().push()
}
fn to_database(&self) -> Value {
json!({ "title": "订单已发货", "order_id": self.order_id })
}
}
#[mutation(name = "orders.ship", post = "/api/orders/{order_id}/ship")]
pub async fn ship_order(ctx: &AppCtx, order_id: i64) -> Result<(), AppErr> {
let to = ctx.require_identity().await?.uid();
let txn = ctx.db()?.begin_write().await?;
// 在同一个 txn 中更新订单状态...
ctx.notify(&to, OrderShipped { order_id }).within(&txn).await?;
txn.commit().await?;
Ok(())
}
#[query(name = "inbox.unread", get = "/api/inbox")]
pub async fn unread_inbox(ctx: &AppCtx, query: CursorQuery) -> Result<Collection<DatabaseNotification>, AppErr> {
let me = ctx.require_identity().await?.uid();
Ok(ctx.notifications(&me).unread().page(&query).await?)
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("app.migrations")))
.plugin(NotifyPlugin::new())
.run()
.await
}核心用法#
定义与发送通知#
为每种业务通知实现 Notification(NAME 为客户端识别标识,via 按收件人返回投递通道组合,返回空 Channels::new() 时静默跳过;在线推送载荷默认复用 to_database,也可单独覆写 to_push):
use kxed_core::{AppCtx, AppErr, GuardName, Uid};
use kxed_plugins::notify::{AppCtxNotify, Channels, Notification, Recipient};
use kxed_plugins::seaorm::sea_orm::{SqliteTransactionMode, TransactionOptions, TransactionTrait};
use kxed_plugins::seaorm::AppCtxDatabase;
use serde_json::{json, Value};
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 })
}
}
async fn pay(ctx: AppCtx, guard: &GuardName, user_id: &str, invoice: u64) -> Result<(), AppErr> {
let to = Uid::of(guard, user_id);
let immediate = TransactionOptions {
sqlite_transaction_mode: Some(SqliteTransactionMode::Immediate),
..TransactionOptions::default()
};
let transaction = ctx.db()?.begin_with_options(immediate).await?;
ctx.notify(&to, InvoicePaid { invoice }).within(&transaction).await?;
transaction.commit().await?;
Ok(())
}收件人(Recipient)寻址与多租户隔离规则:
- 按 Guard 隔离用户收件人:有登录上下文时传
identity.uid(),后台任务只有用户 ID 时传Uid::of(&ctx.default_guard()?, id)(格式<guard>:<subject>,严禁传不带 guard 的裸字符串 ID)。 - 组织或项目级收件人:使用
Recipient::entity("team", id),支持写入站内信与自定义应用通道(不支持在线连接push)。多租户应用若希望同一用户的站内信按租户独立分箱,可用Recipient::entity("member", format!("{tenant}:{user}"))存取站内信,另用identity.uid()触发实时推送。
站内信#
调用 ctx.notifications(&to) 获取绑定该收件人的站内信查询与状态更新句柄(to 必须取自已认证身份,切勿直接取客户端入参):
use kxed_core::{AppCtx, AppErr, Collection, CursorQuery};
use kxed_plugins::notify::{AppCtxNotify, DatabaseNotification};
async fn inbox(ctx: AppCtx, query: CursorQuery) -> Result<Collection<DatabaseNotification>, AppErr> {
let me = ctx.require_identity().await?.uid();
Ok(ctx.notifications(&me).unread().page(&query).await?)
}
async fn mark_read(ctx: AppCtx, id: String) -> Result<(), AppErr> {
let me = ctx.require_identity().await?.uid();
ctx.notifications(&me).mark_read(&id).await?;
Ok(())
}| 方法 | 作用 |
|---|---|
.page(&cursor_query) / .unread().page(&cursor_query) | 按时间倒序游标分页返回全部或未读站内信 Collection<DatabaseNotification> |
.unread_count() | 查询当前收件人的未读总数 |
.mark_read(id) / .mark_all_read() | 单条标记已读(跨收件人或已读返 false)或一键全部标为已读 |
.delete(id) | 删除指定站内信(过期历史消息可由应用自定义 Cron 定期按 created_at 清理) |
与 Fly 管理后台联动:Fly 顶部通知铃铛与抽屉直接读取此表(识别正文中的 title、body、url 或多语言键 title_key、body_key,见 Fly 通知中心)。在线 WebSocket 客户端收到的实时推送帧格式为 {"kind":"kxed.notification","body":{"id":"..","name":"..","body":{..}}},其中 id 与站内信主键一致,方便前端去重与调标记已读接口。
应用通道#
接入短信网关、邮件服务或企微/Slack/飞书机器人时,实现 NotifyChannel 并通过 NotifyPlugin::with_channel(name, channel) 注册;纯 JSON Webhook 可直接使用内置的 HttpChannel::post_json(url)(自动附带 Idempotency-Key: <outbox_id>):
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::notify::{ChannelDelivery, Channels, HttpChannel, Notification, NotifyChannel, NotifyPlugin, Recipient};
use serde_json::{json, Value};
struct SmsGateway;
impl SmsGateway {
async fn send(&self, _key: u64, _phone: &str, _text: &str) -> Result<(), AppErr> { Ok(()) }
}
struct SmsChannel;
impl NotifyChannel for SmsChannel {
type Error = AppErr;
async fn deliver(&self, ctx: &AppCtx, delivery: &ChannelDelivery) -> Result<(), AppErr> {
let gateway = ctx.require_state::<SmsGateway>()?;
let phone = delivery.body["phone"].as_str().ok_or_else(|| AppErr::unprocessable("missing phone"))?;
let text = delivery.body["text"].as_str().unwrap_or_default();
gateway.send(delivery.outbox_id, phone, text).await
}
}
struct LoginCode {
code: u32,
phone: String,
}
impl Notification for LoginCode {
const NAME: &'static str = "login_code";
fn via(&self, _to: &Recipient) -> Channels { Channels::new().custom("sms") }
fn to_database(&self) -> Value { json!({ "code": self.code }) }
fn to_channel(&self, _channel: &str) -> Value {
json!({ "phone": self.phone, "text": format!("Your code is {}", self.code) })
}
}
fn notify_plugin() -> NotifyPlugin {
NotifyPlugin::new()
.with_channel("sms", SmsChannel)
.with_channel("slack", HttpChannel::post_json("https://hooks.slack.com/services/T000/B000/XXXX"))
}重试与幂等去重:ChannelDelivery::outbox_id 在跨进程重试期间保持不变,可传给下游网关作幂等键;通道可覆写 NotifyChannel::deliver_outcome 返回 ChannelOutcome::Delivered、ChannelOutcome::Dropped(用于浏览器订阅或设备令牌已失效等场景,记 outcome="dropped" 且不进入死信队列)或 ChannelOutcome::RetryAfter(delay)(遵从上游 Retry-After 精确退避)。直接返回 Err 时,NotExecuted / Indeterminate 按指数退避重试至 notify.max_attempts 后移入死信,Settled 直接移入死信。
Web Push 与 FCM 推送通道#
- Web Push(
notify-webpush):基于ring实现 RFC 8292 P-256 ES256 VAPID JWT 与 RFC 8291aes128gcm内容加密,按WebPushConfig构造WebPushChannel投递WebPushMessage(含WebPushSubscription与WebPushUrgency)。默认开启公网目标校验防 SSRF,遇 410/404 失效订阅自动调用失效回调并返回ChannelOutcome::Dropped,遇 429/503 携带Retry-After时返回ChannelOutcome::RetryAfter。 - FCM HTTP v1(
notify-fcm):基于ringRS256 签发 Google Service Account JWT 并通过ArcSwap单飞缓存 OAuth2 访问令牌,按FcmConfig构造FcmChannel投递FcmMessage。遇 401 自动强制重刷令牌并重试一次,遇 404/UNREGISTERED自动触发失效回调并返回ChannelOutcome::Dropped,遇QUOTA_EXCEEDED返回RetryAfter或可重试限流错误。
邮件通道与大附件#
同时开启主包 notify 与 mail 特性并注册 MailPlugin 后,可直接挂载内置的 SmtpChannel 经 Outbox 异步可靠发信(详见 邮件发送插件):
use kxed::plugins::mail::MailPlugin;
use kxed::plugins::notify::{
Channels, Notification, NotifyPlugin, Recipient, SmtpChannel, SmtpChannelAttachment,
SmtpChannelMessage,
};
use kxed::prelude::*;
use serde_json::{json, Value};
struct InvoiceEmail {
email: String,
invoice_no: String,
pdf_key: String,
}
impl Notification for InvoiceEmail {
const NAME: &'static str = "invoice_email";
fn via(&self, _to: &Recipient) -> Channels {
Channels::new().database().custom("email")
}
fn to_database(&self) -> Value {
json!({ "title": "发票已生成", "invoice_no": self.invoice_no })
}
fn to_channel(&self, _channel: &str) -> Value {
SmtpChannelMessage::new(&self.email, format!("发票 {}", self.invoice_no))
.text("请查看附件中的电子发票。")
.template("mail/invoice.html", json!({ "invoice_no": self.invoice_no }))
.attachment(SmtpChannelAttachment::object_store(
None,
&self.pdf_key,
format!("invoice-{}.pdf", self.invoice_no),
"application/pdf",
))
.to_value()
}
}
fn plugins() -> (MailPlugin, NotifyPlugin) {
let smtp = SmtpChannel::new()
.with_from("Acme Billing <billing@example.com>")
.with_message_id_domain("example.com");
(MailPlugin::new(), NotifyPlugin::new().with_channel("email", smtp))
}- 稳定幂等
Message-ID与错误分级:SmtpChannel自动为每条 Outbox 记录生成<notify-{outbox_id}@{domain}>(也可在SmtpChannelMessage::message_id(...)中覆写),并在多次重试时保持不变;SMTP 4xx、连接抖动与对象存储临时故障按NotExecuted/Indeterminate指数退避重试,5xx 拒收、非法邮箱与缺失附件按Settled直接转入死信队列。 - 大附件走
object-store最佳实践:单条 Outbox 通道 JSON 上限为 16,384 字节,切勿把 Base64 编码的大文件直接塞入 Outbox 正文。业务侧应先将 PDF、报表或导出压缩包写入ObjectStorePlugin,再通过SmtpChannelAttachment::object_store(disk, key, filename, content_type)在 Outbox 中仅存对象键引用(小段文本附件可用SmtpChannelAttachment::text(...)),由NotifyRelay实际投递时再按mail.max_attachment_bytes预算分块流式拉取。
数据库表迁移#
在应用 Migrator::migrations() 最前面并入 NotifyStore::migrations()(自动建立 kxed_notifications、kxed_notify_outbox 与 kxed_notify_dead_letter 三张表;服务启动时自动校验表结构):
use kxed_plugins::notify::NotifyStore;
use kxed_plugins::seaorm::sea_orm_migration::async_trait::async_trait;
use kxed_plugins::seaorm::sea_orm_migration::{MigrationTrait, MigratorTrait};
use kxed_plugins::seaorm::{MigrationLock, SeaOrmPlugin};
struct Migrator;
#[async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
NotifyStore::migrations()
}
}
fn database() -> SeaOrmPlugin {
SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("app.migrations"))
}配置#
| key | default | contract |
|---|---|---|
notify.batch_size | 100 | 单轮领取的 Outbox 行数上限,范围 1..=1000 |
notify.delivery_concurrency | 8 | 单轮并发投递的不同收件人数上限(同一收件人的多条通知严格按序串行投递),范围 1..=64 |
notify.lease_duration | 30s | Outbox 行领取租约独占时长,范围 1s..=1h |
notify.poll_interval | 500ms | 空闲轮询间隔与失败退避起点,范围 10ms..=60s(须小于 lease_duration) |
notify.max_backoff | 1m | 指数退避最大间隔,范围 poll_interval..=1h |
notify.max_attempts | 10 | 转入死信队列前的最大尝试次数,范围 1..=1000 |
notify.dead_letter_retention | 7d | 死信记录自动清理保留期,范围 1m..=365d |
单条通知通道 JSON 正文上限为 16,384 字节,通知名 <= 128 字节可见 ASCII,越界返回 400 notify_invalid_request。
运行期边界、多实例与运维命令#
投递#
每个服务进程托管一个 NotifyRelay:
- 在线推送尽力而为,外部通道至少一次:在线推送(
push)在收件人当前离线时直接结清(计offline),因为持久事实已存入站内信;应用外部通道(短信/邮件等)则保证至少一次投递。 - 滚动升级与数据库抖动免罚:进程遇到尚不认识的新通道名(滚动发布过渡期)或遇到数据库临时故障时,自动退避或交还租约且不扣减
attempts;停机排空(drain)留出宽限期完成当前投递并主动交还剩余租约。
N>1#
- 跨节点自动分工与推送路由:多副本共享数据库三张表,通过 Outbox 条件更新租约自动分担投递(任一节点崩溃后租约到期由存活节点接手);执行投递的节点无需自己持有目标用户的 WebSocket 连接,底层自动按
Uid路由到连接所在节点下发。各节点时钟偏差需远小于notify.lease_duration。
运维命令与指标#
| CLI 命令 | 作用 |
|---|---|
notify status | 查看各通道当前待投递积压数、最老等待秒数与死信数 |
notify dead list [--channel <name>] [--limit <n>] [--after <id>] | 分页查看死信详情与失败原因 |
notify dead retry (<id>... | --all) [--channel <name>] | 将指定或全部死信重新放回 Outbox 投递(单次至多 10,000 条) |
notify dead purge (<id>... | --all) [--channel <name>] | 提前物理删除死信记录(破坏性命令,非交互终端带 --force) |
notify recipient update --guard <name> | 将缺少 guard 前缀的用户记录批量升级为 <guard>:<subject> |
开启主包 notify 特性后,/metrics 自动输出以下指标(NotifyError 映射为 400 notify_invalid_request、503 notify_unavailable 与 500 notify_failed):
| 指标 | 含义 |
|---|---|
kxed_notify_deliveries_total{channel,outcome} | 各通道投递计数(delivered/dropped/offline/unconfirmed/retried/unavailable/failed) |
kxed_notify_dead_letters_total{channel} | 累计进入死信队列的通知数 |
kxed_notify_outbox_pending_rows{channel} | 当前待投递积压行数(每 5s 刷新,封顶 100,000) |
kxed_notify_outbox_oldest_age_seconds{channel} | 最早一条未投递记录的等待秒数 |
kxed_notify_relay_round_failure_total | Relay 轮次因数据库异常失败的次数 |
kxed_notify_relay_last_success_timestamp_seconds | 最近一次成功完成投递轮次的 Unix 秒级时间戳 |