功能开关与灰度放量
属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io
在代码中声明功能开关与默认灰度放量比例(支持基于 blake3 的跨实例稳定分桶),并通过 CLI 运维命令或 API 在运行期按具体用户/租户或全局紧急开启、关闭覆盖(持久化在业务库 kxed_features 表中,多实例自动同步)。
快速接入#
在 Cargo.toml 开启主包 kxed 的功能开关与数据库特性(独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["features", "seaorm-sqlite"] }):
[dependencies]
kxed = { version = "0.0.5-alpha", features = [
"features",
"seaorm-sqlite",
"seaorm-migration",
] }将 FeaturesPlugin::migrations() 并入应用迁移,注册开关及其默认放量比例,即可在业务 Procedure 中调用 ctx.features()?.is_active(name, scope) 判定分支:
use kxed::plugins::features::{FeatureRollout, FeaturesPlugin};
use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;
#[query(name = "checkout.flow", get = "/api/checkout/flow")]
pub async fn checkout_flow(ctx: &AppCtx) -> Result<&'static str, AppErr> {
let who = ctx.require_identity().await?;
let scope = format!("{}:{}", who.guard(), who.subject());
if ctx.features()?.is_active("checkout-v2", &scope).await? {
Ok("v2")
} else {
Ok("v1")
}
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
let features = FeaturesPlugin::new()
.with_feature("checkout-v2", FeatureRollout::percent(10))
.with_feature("dark-theme", FeatureRollout::all());
App::new()
.plugin(SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("app.migrations")))
.plugin(features)
.run()
.await
}子 crate 独立接入与迁移并入示例:
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::features::{AppCtxFeatures, FeatureRollout, FeaturesPlugin};
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>> {
FeaturesPlugin::migrations()
}
}
fn plugins() -> (SeaOrmPlugin, FeaturesPlugin) {
let database = SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("app"));
let features = FeaturesPlugin::new()
.with_feature("billing-v2", FeatureRollout::percent(10))
.with_feature("new-search", FeatureRollout::none());
(database, features)
}
async fn search(ctx: AppCtx, user: u64) -> Result<&'static str, AppErr> {
if ctx.features()?.is_active("new-search", &format!("user:{user}")).await? {
return Ok("new");
}
Ok("classic")
}核心用法#
判定优先级与稳定哈希分桶#
调用 ctx.features()?.is_active(name, scope).await? 按以下三层优先级返回首个命中的结论(未声明的开关名返 500 feature_not_registered,空 scope 返 400 feature_invalid_scope):
- 特定主体覆盖:数据库中针对该
(feature, scope)写入的强制开启/关闭记录。 - 全局覆盖:数据库中不带
--scope写入的整站强制开启/关闭记录。 - 代码默认放量:
FeatureRollout::all()全开、none()全关、percent(p)按blake3(name, 0x00, scope)前 8 字节对 100 取余,当桶号< p时开启。把比例从10调大到30时已命中的用户保持开启不抖动,且不同开关名之间分桶互不关联。
路由门禁中间件#
原生 HTTP 路由组可直接挂载 require_feature("billing-v2"):已登录请求自动以 <guard>:<subject> 作为 scope 判定(匿名请求只看全局覆盖与全开/全关),未命中时返回 404 feature_denied:
use axum::routing::get;
use kxed_plugins::features::require_feature;
fn routes() -> axum::Router {
axum::Router::new().route("/billing/v2", get(|| async { "v2" }).layer(require_feature("billing-v2")))
}覆盖与命令#
无需改代码重新发版,直接通过内建 CLI 命令(或代码中的 Features::enable、disable、reset)为白名单客户定向开通或紧急熔断功能:
| CLI 命令 | 作用 |
|---|---|
./app feature enable <FEATURE> [--scope <SCOPE>] | 强制打开某开关(指定 --scope user:42 仅对该主体生效,不带则全局打开) |
./app feature disable <FEATURE> [--scope <SCOPE>] | 强制关闭某开关(优先级高于代码灰度比例,用于线上紧急止损) |
./app feature reset <FEATURE> [--scope <SCOPE>] | 删除该条动态覆盖,恢复按代码声明比例判定(破坏性命令,非交互终端带 --force) |
容量上限与操作审计:覆盖表最多容纳 MAX_OVERRIDES(10,000)条记录(多实例通过 kxed_features_write_lock 串行校验容量,满表新增返 409 feature_overrides_exhausted)。链式调用 FeaturesPlugin::new().with_audit_log() 可将每次启停与重置操作在同一事务内记入 kxed_audit_log(见 审计变更历史)。
Config#
| key | default | contract |
|---|---|---|
features.refresh_interval | 5s | 后台重读 kxed_features 覆盖表的等待间隔,范围 10ms..=10m |
运行期边界与错误码#
N>1 的一致性#
服务进程在启动时加载覆盖表快照,运行期由受管任务 features-refresh 每隔 features.refresh_interval 重读同步(本进程执行写覆盖后立即刷新本地快照);由于分桶哈希只依赖开关名与 scope,所有同版本节点对同一主体计算出的灰度结论完全一致。数据库短暂不可达时保留上一份内存快照继续服务,停机时立即放弃在途后台重读而不拖延关池。数据库不可达与未知存储错误分别映射为 503 feature_unavailable 与 500 feature_failed。