编写 Plugin
编写一个生产级 Plugin 只需按以下四步渐进扩展:
- 注入 State:在
build或start中调用ctx.provide(state)发布类型化状态,供 handler 经ctx.require_state::<T>()?读取(第 1、3 节)。 - 读取配置:用
#[derive(Deserialize, ConfigSection)]加#[config(owners = [MyPlugin])]声明强类型配置段,启动期自动完成校验与脱敏(第 8 节)。 - 挂路由与中间件:在
start中经ctx.http_transform合入 HTTP 路由或 Tower 层,或经WsRoutes挂载 WebSocket 处理器(第 5、6 节)。 - 后台协程与健康检查:用
ctx.spawn登记响应stop_token()的受管协程,用ctx.health()驱动/readyz就绪探针,退出时按逆拓扑两阶段排空释放(第 4、9、10 节)。
1. 五分钟跑通一个 Plugin#
下面用不到 30 行代码实现一个注入 Greeting 状态并挂载 GET /greeting 路由的完整插件(src/lib.rs):
use axum::routing::get;
use axum::Router;
use kxed_core::plugin::{HttpStage, Plugin, PluginBuild, PluginResult, PluginRun};
use kxed_core::{AppCtx, AppErr};
pub struct Greeting {
pub prefix: String,
}
#[derive(Default)]
pub struct GreetingPlugin;
impl Plugin for GreetingPlugin {
fn build(&mut self, ctx: &mut PluginBuild) -> PluginResult {
ctx.provide(Greeting {
prefix: "hello".to_owned(),
})?;
Ok(())
}
async fn start(&mut self, ctx: PluginRun) -> PluginResult {
ctx.http_transform(HttpStage::ApplicationHooks, |graphs| {
graphs.merge_main(Router::new().route("/greeting", get(greeting)))
})
}
}
async fn greeting(ctx: AppCtx) -> Result<String, AppErr> {
let greeting = ctx.require_state::<Greeting>()?;
Ok(format!("{}\n", greeting.prefix))
}配套的 Cargo.toml 如下(直接从 crates.io 引入 kxed-core,应用侧接入见 README 快速开始):
[package]
name = "kxed-plugin-greeting"
version = "0.0.5-alpha"
edition = "2024"
[dependencies]
axum = "0.8"
kxed-core = "0.0.5-alpha"
[dev-dependencies]
kxed-core = { version = "0.0.5-alpha", features = ["testing"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tower = { version = "0.5", features = ["util"] }在 src/lib.rs 末尾用 PluginHarness 验证完整生命周期(build -> start -> ready -> drain -> shutdown):
#[cfg(test)]
mod tests {
use super::GreetingPlugin;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::Router;
use kxed_core::testing::PluginHarness;
use tower::ServiceExt;
#[tokio::test]
async fn plugin_serves_its_route_through_one_lifecycle() {
let mut running = PluginHarness::new()
.plugin(GreetingPlugin)
.boot_http(Router::new(), None)
.await
.unwrap();
let request = Request::builder()
.uri("/greeting")
.body(Body::empty())
.unwrap();
let response = running.http().unwrap().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
running.shutdown().await.unwrap();
}
}在业务应用里挂载该插件只需一行(完整组装见第 12 节):
App::new().plugin(GreetingPlugin)2. 依赖边界#
合法依赖方向为 kxed-core <- 第三方 plugin:
| 依赖目标 | 是否允许 | 原因 |
|---|---|---|
kxed-core | 允许 | 包含 Plugin SPI、生命周期、配置、AppCtx / AppErr 与 Ws / WsRoutes / ConnectionSink |
| 生态基础库(axum、serde、tokio、tower 等) | 允许 | 插件内部实现依赖 |
官方 kxed-plugins 模块 | 允许 | 按 feature 单向前向复用(如 auth 依赖 session/security/seaorm) |
kxed-runtime(procedure / task feature) | 允许 | 仅依赖 kxed-core 与 kxed-macros,可用于传输适配或任务扩展插件 |
kxed facade | 禁止 | facade 依赖全部官方插件,反向依赖会产生循环 |
kxed-runtime(fabric feature) | 禁止 | Fabric 位于插件图下方,不参与插件拓扑编排 |
kxed-runtime(event / presence / resident feature) | 禁止 | 这些模块依赖 fabric;有状态 #[resident] 声明归属业务应用层而非插件 |
版本协同与建池说明:
- 锁定的底层版本:若直接依赖
tungstenite,须跟随 axum 内部tokio-tungstenite版本(当前 0.29)以支持错误向下转型;若直接依赖socket2,须跟随fred版本(当前 0.5)以兼容 Linuxtcp-user-timeouts。 - 预注册建池:需在注册前使用数据库连接池(如预执行迁移)时,可调用
kxed_plugins::seaorm::DatabaseConfig::connect()复用database配置并在database.startup_timeout内自动重试 SQLite 锁繁忙。 - 测试隔离:
kxed-core的testing特性仅写入[dev-dependencies],确保PluginHarness不进入生产二进制。
发布级插件的完整 Cargo.toml 模板:
[package]
name = "kxed-plugin-mail"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
license = "MIT OR Apache-2.0"
description = "Mail delivery plugin for kxed"
readme = "README.md"
[dependencies]
axum = { version = "0.8", features = ["ws"] }
bytes = "1"
kxed-core = "0.0.5-alpha"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["rt", "sync", "time"] }
tracing = "0.1"
[dev-dependencies]
kxed-core = { version = "0.0.5-alpha", features = ["testing"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util", "time"] }
tower = { version = "0.5", features = ["util"] }3. Plugin trait 的完整表面#
pub trait Plugin: Send + 'static {
fn declare(&self, _declaration: &mut PluginDeclaration) {}
fn embedded_plugins() -> Vec<PluginId> { .. }
fn build(&mut self, _ctx: &mut PluginBuild) -> PluginResult { .. }
fn process_local_surfaces(&self, _probe: &ProcessLocalProbe) -> PluginResult<Vec<ProcessLocalUse>> { .. }
fn check_config(&self, _probe: &ProcessLocalProbe) -> PluginResult { .. }
fn check_type_config(_probe: &ProcessLocalProbe) -> PluginResult { .. }
fn routes(&self, _config: &ConfigRepository) -> PluginResult<Vec<RouteInfo>> { .. }
fn start(&mut self, _ctx: PluginRun) -> impl Future<Output = PluginResult> + Send { .. }
fn ready(&mut self, _ctx: PluginRun) -> impl Future<Output = PluginResult> + Send { .. }
fn begin_drain(&mut self, _ctx: PluginStop) -> impl Future<Output = PluginResult> + Send { .. }
fn drain(&mut self, _ctx: PluginStop) -> impl Future<Output = PluginResult> + Send { .. }
fn shutdown(&mut self, _ctx: PluginStop) -> impl Future<Output = PluginResult> + Send { .. }
}Plugin 身份由 PluginId::of::<P>() 唯一标识,同一类型在一个组合根内至多注册一次;异步钩子采用 RPITIT(跨 .await 的值须满足 Send),全部钩子包裹在 catch_unwind 内防止单点 panic 中断后续清理:
| 生命周期钩子 | 同步性 | 调用时机与顺序 | 失败后果 |
|---|---|---|---|
declare | 同步 | 注册时立即执行一次,声明依赖、能力与发布项 | panic 转为 PluginError::Lifecycle{ phase: Register } |
build | 同步 | 按拓扑正序,仅校验配置与注入同步状态 | 清空 state 进入 LifecyclePhase::Failed,不跑停止钩子 |
start | async | 按拓扑正序获取外部资源、挂载路由与受管协程 | 触发已进入 start 插件的逆序 rollback |
ready | async | 按拓扑正序核验就绪,全部通过后开放准入 | 触发逆序 rollback |
begin_drain | async(受预算约束) | 逆拓扑停止接纳新工作,整轮完成后才进 drain | 记录错误并继续下一个插件 |
drain | async(受预算约束) | 逆拓扑等待在途工作与受管协程排空 | 记录错误并继续下一个插件 |
shutdown | async(受预算约束) | 逆拓扑释放底层连接与外部句柄 | 记录错误并继续下一个插件 |
各生命周期上下文的方法可用矩阵:
| 上下文方法 | PluginBuild | PluginRun (start) | PluginRun (ready) | PluginStop |
|---|---|---|---|---|
provide::<T>(value) | 可用 | 可用 | 返回 WrongPhase | 无 |
require_state::<T>()、app_state() | 可用 | 可用 | 可用 | 可用 |
config::<T>()、config_repository() | 可用 | 可用 | 可用 | 可用 |
health()、activation()、tasks()、spawn(..)、http_transform(..) | 无 | 可用 | 可用 | 无 |
seal_http_pipeline() | 无 | 返回 WrongPhase | 可用 | 无 |
stop_token() | 无 | 可用 | 可用 | 可用(drain/shutdown 期已取消) |
deadline()、remaining()、total_budget()、slice(..)、abandoned() | 无 | 无 | 无 | 可用 |
静态预检、复合插件与错误处理细则:
- 只读预检方法:
process_local_surfaces报告选用的进程内后端(覆盖session、cache、rate_limit、task_storage、search、auth、object_store、reliable_push、ledger、state_machine十个ProcessLocalSurface,供N>1拦截未在fabric.allow_process_local承认的本地实现);check_config与无self的check_type_config在build前与离线config check执行配置校验。 - 配置错误归类:
build、check_config、process_local_surfaces及ctx.config::<T>()?自动归为配置错误(退出码见 配置预检);start内判定的配置错误须显式调PluginError::config("..")或.map_err(PluginError::into_config)?,否则按外部连接失败处理(serve退出 1,启动档命令退出 69)。 - 复合插件转发:组合其他插件的复合插件通过
embedded_plugins()声明内嵌PluginId,并必须在全部钩子中完整转发内嵌插件的同名钩子(参考FlyDatabaseAccountPlugin)。 - 上下文时效与脱敏:
PluginRun仅在当次钩子内有效,运行期派生任务须在start保存ctx.tasks()?;SeaORMDbErr可直接?自动脱敏,切勿将含连接串或 SQL 的原始DbErr传给PluginError::context拼接;重复注入同类型状态返回DuplicateState。
4. lifecycle 与 rollback#
flowchart LR
register --> dependencies --> resolve["resolve graph"] --> build --> start --> ready --> admission
admission --> begin_drain["reverse begin_drain"] --> drain["reverse drain"] --> shutdown["reverse shutdown"] --> stopped["shutdown"]启停顺序、回滚覆盖范围与超时预算切分规则:
- 启动激活屏障:完成拓扑解析与
build -> start -> ready后,管理器统一激活常驻协程并等待首次poll、复查健康度,全部通过才置LifecyclePhase::Ready并开放准入。start中获取的外部资源须在下一次.await前存入插件字段以便回收。 - 两轮逆序停机:
begin_drain占剩余窗口 25%(按插件均分),保持已建连接可写供下发收尾帧;整轮返回后才依次执行逆序drain与shutdown,最后清空 state 进入Stopped(有错为Failed)。 - 回滚包含失败者自身:
start或ready失败触发相同的两轮逆拓扑清理,覆盖全部已进入过start的插件(含当前报错的那一个),若清理也报错则返回PluginError::Rollback { primary, errors };build失败直接 Drop 实例不走回滚,故需异步释放的资源必须在start获取。 - 超时丢弃与幂等重入:停止钩子超时先取消
stop_token()并给min(250ms, 阶段预算 10%)宽限,仍未返回则丢弃 future、记LifecycleTimeout并写入ctx.abandoned()。清理被外部取消时会在后台补跑(见 SPEC 第 3.1 节),停止钩子须用Option::take保持幂等并在Drop兜底 abort。
分段收尾统一用 ctx.slice(fraction, floor) 切分剩余预算,不写死固定秒数:
use kxed_core::plugin::{PluginError, PluginResult, PluginStop};
use std::time::Duration;
// self.flush() 返回 impl Future<Output = ()>。
async fn drain(&mut self, ctx: PluginStop) -> PluginResult {
let budget = ctx.slice(0.1, Duration::from_millis(250));
tokio::time::timeout(budget, self.flush())
.await
.map_err(|_| PluginError::message("flush timed out"))?;
Ok(())
}5. 注册 HTTP 路由#
在 start 中调用 ctx.http_transform 将路由或中间件挂入固定阶段的公网请求流水线:
use axum::routing::{get, post};
use axum::Router;
use kxed_core::plugin::{HttpStage, Plugin, PluginResult, PluginRun};
use kxed_core::{AppCtx, AppErr};
pub struct MailPlugin;
impl Plugin for MailPlugin {
async fn start(&mut self, ctx: PluginRun) -> PluginResult {
ctx.http_transform(HttpStage::ApplicationHooks, |graphs| {
graphs.merge_main(
Router::new()
.route("/mail/health", get(mail_health))
.route("/mail/send", post(mail_send)),
)
})
}
}
async fn mail_health(_ctx: AppCtx) -> Result<&'static str, AppErr> {
Ok("ok")
}
async fn mail_send(ctx: AppCtx) -> Result<String, AppErr> {
let identity = ctx.require_identity().await?;
Ok(identity.subject().to_owned())
}PublicHttpGraphs 提供 merge_main(router)(合入主路由)、map_main(|r| ..)(任意变换主路由)与 layer_all(layer)(同时包裹 HTTP 与独立 WS 路由);执行顺序由 HttpStage 固定,与代码注册先后无关:
HttpStage | 职责 | 进程内可注册次数 |
|---|---|---|
ErrorPages | 最外层改写下层非 HTML 4xx/5xx 响应(如 TemplatesPlugin::with_error_pages) | 单例(重复返 DuplicateHttpStage) |
Security | 安全头、CORS、请求体上限与限流(总超时由宿主 server.http.handler_timeout 提供) | 单例 |
Session | 会话读写层 | 单例 |
Authentication | 解析凭据并向 RequestContext 的 IdentitySet 写入身份(故障调 mark_unavailable 回 503) | 单例 |
Authorization | 路径与角色权限裁决 | 单例 |
ApplicationHooks | 业务路由与业务中间件(被依赖方处于外层,需包裹其他插件路由时由路由方声明 require/after) | 每插件 1 次(重复返 DuplicateHttpRegistration) |
路由保留路径与离线展示规则:
- 保留路径拦截:
/healthz、/readyz与/metrics为框架独占路径(可用kxed_core::is_reserved_http_path预检),transform 占用它们会在启动期失败,错误文本是a plugin transform claimed a reserved path。 - 离线路由导出:覆写
Plugin::routes返回RouteInfo(http、ws、mount、grpc、management),即可让不启动插件的./app routes列出本插件挂载的路径:
fn routes(&self, _config: &ConfigRepository) -> PluginResult<Vec<RouteInfo>> {
Ok(vec![
RouteInfo::http([Method::GET], "/mail/health"),
RouteInfo::http([Method::POST], "/mail/send"),
])
}6. 注册 WebSocket handler#
WebSocket 路由表 WsRoutes 必须在 build 或 start 阶段登记(宿主在首个 ready 前封存,封存后登记返回 kxed plugin protocol routes are already sealed,重名或占保留路径同样报错):
use kxed_core::plugin::{Plugin, PluginBuild, PluginResult};
use kxed_core::{AppErr, Ws, WsRoutes};
pub struct ChatPlugin;
impl Plugin for ChatPlugin {
fn build(&mut self, ctx: &mut PluginBuild) -> PluginResult {
ctx.require_state::<WsRoutes>()?.ws("/ws/echo", echo)?;
Ok(())
}
}
#[derive(serde::Deserialize)]
struct EchoRequest {
text: String,
}
pub async fn echo(mut socket: Ws) -> Result<(), AppErr> {
socket.bind("demo-user")?;
socket.join("lobby")?;
while let Some(frame) = socket.recv().await? {
let request: EchoRequest = frame.json()?;
socket.send_text_wait(format!("echo: {}", request.text)).await?;
}
socket.leave("lobby")?;
socket.unbind()?;
socket.close()?;
Ok(())
}Ws::recv() 返回 Ok(None) 代表对端已断开,连接随即进入终止清理并在下一挂起点取消 handler,故断连必释放的资源应放入 Drop:
Ws 方法组 | 核心行为 |
|---|---|
send_text / send_bytes / send_text_wait | 前两者非阻塞试发(满返 Reject::Busy,文本收 impl Into<Utf8Bytes>);send_text_wait 最多等 1 秒 |
bind / unbind / join / leave / subscribe / close | 维护在线 Uid 与 topic 订阅(subscribe 超限回 429 topic_limit_exceeded)及主动关闭连接 |
identity / require_identity / grants / require_role | 读取升级时身份,或异步复查认证记录与权限(撤销规则见 AUTH 撤销与活动) |
state / require_state / config / app | 经 kxed_core::AppCtxAccess 读取应用状态与配置 |
需为同路径普通 HTTP GET 提供自定义降级响应时,使用 ws_with_get:
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use kxed_core::RequestContext;
async fn upgrade_required(_request: RequestContext) -> Response {
(StatusCode::UPGRADE_REQUIRED, "websocket upgrade is required").into_response()
}ctx.require_state::<WsRoutes>()?
.ws_with_get("/ws/echo", echo, upgrade_required)?;7. 声明依赖#
在 declare 中声明拓扑依赖、能力标记、完成屏障与静态协作元数据(优先使用 require_capability 与软顺序 after 代替硬绑定具体类型):
use kxed_core::plugin::{Plugin, PluginCapability, PluginDeclaration};
pub struct MailPlugin;
pub struct MailCapability;
impl PluginCapability for MailCapability {}
impl Plugin for MailPlugin {
fn declare(&self, declaration: &mut PluginDeclaration) {
declaration
.require::<kxed_plugins::redis::RedisPlugin>()
.require_capability::<kxed_plugins::authz::AuthorizationCapability>()
.provide_capability::<MailCapability>()
.after::<kxed_plugins::cache::CachePlugin>();
}
}PluginDeclaration 方法 | 作用 | 缺失或冲突时的错误 |
|---|---|---|
require::<P>() | 硬依赖具体插件类型 P 并排在其后 | MissingDependency / DependencyCycle |
require_capability::<C>() | 硬依赖能力标记 C,不绑定具体实现类 | MissingCapability |
provide_capability::<C>() | 声明本插件提供能力 C | 重复提供返回 DuplicateCapability |
after::<P>() | 软顺序边,仅在 P 已注册时排在其后 | 目标未注册时无操作 |
completion_barrier(barrier) | 将 Drain 或 Shutdown 标为完成屏障,不按外层超时提前丢弃 future | 不适用 |
publish(value) | 发布构造期静态值,供其他插件在预检与 start 经 probe.published::<T>() 读取 | 无读者时无操作 |
publish 常用于两类跨插件静态协作(离线 config check 不执行 build):一是自挂登录页的插件发布 LoginPageRegistration 供 AuthPlugin 核验放行(见 AUTH 签发与使用);二是多路 Procedure 传输插件(如 McpPlugin、GrpcProceduresPlugin)发布公共入口路径,使外层路径策略放行并交由内部 Session 逐调用鉴权:
impl Plugin for McpPlugin {
fn declare(&self, declaration: &mut PluginDeclaration) {
declaration.publish(kxed_runtime::procedure::ProcedureTransportEndpoint::exact_post(
self.path.clone(),
));
}
}8. typed ConfigSection#
配置统一通过 kxed-core 重导出的 #[derive(ConfigSection)] 声明,不在插件内自行读文件、读环境变量或运行期热重载:
use kxed_core::plugin::Plugin;
use kxed_core::{ConfigSection, ExposeSecret, SecretString};
use serde::Deserialize;
use std::time::Duration;
const MAX_ENDPOINT_BYTES: usize = 2_048;
pub struct MailPlugin;
impl Plugin for MailPlugin {}
#[derive(Deserialize, ConfigSection)]
#[config(namespace = "plugins.mail", owners = [MailPlugin], check = check_mail)]
pub struct MailConfig {
pub endpoint: String,
pub api_key: SecretString,
#[serde(with = "kxed_duration")]
#[config(default = Duration::from_secs(5))]
pub timeout: Duration,
}
fn check_mail(config: &MailConfig) -> Result<(), String> {
if config.endpoint.is_empty() || config.endpoint.len() > MAX_ENDPOINT_BYTES {
return Err("endpoint must be 1..=2048 bytes".into());
}
if config.api_key.expose_secret().is_empty() {
return Err("api_key must not be empty".into());
}
if !(Duration::from_millis(1)..=Duration::from_secs(300)).contains(&config.timeout) {
return Err("timeout must be between 1ms and 5m".into());
}
Ok(())
}在 build 或 start 中调用 ctx.config::<MailConfig>()? 读取缓存的 Arc<MailConfig>(跨 crate 共享同一配置段时用 kxed_core::config_section!(MailConfig, owners = [DigestPlugin]); 追加归属,规则见 配置参考的 section 的归属):
async fn start(&mut self, ctx: PluginRun) -> PluginResult {
let config = ctx.config::<MailConfig>()?;
let client = MailClient::connect(&config).await?;
ctx.provide(client)?;
Ok(())
}source precedence#
配置来源从低到高叠加如下(第三方插件请使用 plugins.<domain> 等独立命名空间,勿占用 server、tasks、residents、fabric):
flowchart LR
s1["ConfigLoader::with_default"] --> s2["config/**/*.toml"]
s2 --> s3["config/environments/#lt;KXED_ENV#gt;/**/*.toml"]
s3 --> s4[".env"]
s4 --> s5[".env.#lt;KXED_ENV#gt;"]
s5 --> s6["进程 KXED__* 环境变量"]
s6 --> s7["ConfigLoader::with_override"]错误脱敏#
- 密码、密钥、连接串一律使用
SecretString(Debug/Display自动掩码,仅在连接处调expose_secret());嵌套结构体中的敏感字段在顶层补标#[config(secret_keys = ["provider.api_key"])]供config show脱敏。 check校验报错只写字段名与合法范围(如timeout must be between 1ms and 5m),严禁拼入配置原值或底层config库的未脱敏报错。
fail-closed#
配置未知字段(unknown typed field)、类型反序列化错误与 check 校验失败一律在预检与启动期直接拒绝启动,不为错误配置编写静默降级回退。
9. managed task#
严禁在插件内裸调 tokio::spawn(退出时无人等待回收),所有后台任务必须登记进受管作用域(每插件上限 1024 个、名称最长 256 字节):
async fn start(&mut self, ctx: PluginRun) -> PluginResult {
let stop = ctx.stop_token();
ctx.spawn("mail-retry", async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
loop {
tokio::select! {
_ = stop.cancelled() => return Ok(()),
_ = interval.tick() => { /* 一轮有界工作 */ }
}
}
})?;
ctx.provide(ctx.tasks()?)?;
Ok(())
}| 登记入口 | 任务类别 | 生命周期与异常行为 |
|---|---|---|
PluginRun::spawn(start/ready) | 常驻 service | 启动期做首次 poll;必须监听 stop_token(),在 drain 前返回 Ok(()) 视为异常退出 exited before plugin drain;超时未退被 abort 并记 TaskTimeout |
PluginTasks::spawn | 动态异步 work | 活跃期及 begin_drain 期间可提交一次性异步作业,进入本插件 drain 后关闭接纳 |
PluginTasks::spawn_blocking | 短时同步 work | 在进程级有界池执行同步闭包,返回 PluginBlockingTask<T>;开始后不可抢占,丢弃句柄不取消执行(限流 permit 须移入闭包内) |
若本插件 shutdown 或下游插件还需退出预算,可在 drain 前调 PluginTasks::reserve_after_drain(fraction, floor) 预留至多一半剩余窗口。受管任务报错或 panic 会拉低健康度并以 kxed::plugin 写出脱敏源码位置日志。
10. health 与 readiness#
ctx.health() 返回可克隆进后台探测协程的 PluginHealth(连续失败去抖可复用 kxed_core::plugin::HealthGate;应用级探针可直接用 App::health_check,见 SPEC 第 3.2 节):
PluginHealth 方法 | /readyz 与 kxed_ready | 节点放置与执行资格(accepting) | 是否可恢复 | 适用场景 |
|---|---|---|---|---|
ready() | 全部插件就绪时恢复 200 | 未进入 drain 时恢复开启 | 是 | 探针恢复正常(ready 钩子成功后框架自动调一次) |
not_ready_soft(reason) | 置 503 / 0(负载均衡摘流) | 保持开启(防 Resident 大规模冷迁移) | 是 | 数据库或 Redis 等外部依赖短暂抖动 |
not_ready(reason) | 置 503 / 0 | 立即关闭(drain 期除外) | 是 | 本节点暂时无法承担集群放置与执行 |
fail(message) | 置 503 / 0 | 立即关闭并触发 terminal_failure() 停机退出 | 否(终局) | 后台核心循环崩溃或不可恢复故障 |
对外网络准入在进入停机 drain 时立即关闭(SPEC 第 13 节),而内部 accepting 保持到全部 drain 完成后才关闭以保障在途任务收尾。
11. 用 PluginHarness 测试#
kxed_core::testing::PluginHarness(facade 同名重导出)驱动真实的 PluginManager 依赖图、健康状态与逆序清理,返回的 RunningPluginHarness 必须显式调用 .shutdown().await(漏调会在 Drop 时 panic,消息是 RunningPluginHarness must be shut down explicitly):
use kxed_core::testing::PluginHarness;| Builder 方法 | 用途 |
|---|---|
config(section) / config_override(path, value) | 注入完整配置段或覆盖单个点分键(默认隔离本地文件与进程环境变量) |
state(value) / plugin(p) / register_all(reg) | 预注入宿主状态,注册被测插件及其依赖 |
topology(ProcessTopology::cluster()) / shutdown_timeout(d) | 模拟多实例拓扑拦截,或收紧停机预算验证超时行为 |
boot() / boot_http(router, ws) | 仅运行生命周期,或组装完整 HTTP 流水线返回可 oneshot 的 Router(真实 WS 帧收发在 TestApp 测) |
新增插件必须通过公开状态、健康度与响应(严禁读源码文本)验证以下六项契约:
dependency#
#[tokio::test]
async fn missing_dependency_fails_before_any_hook_runs() {
let error = PluginHarness::new()
.plugin(MailPlugin)
.boot()
.await
.err()
.expect("a missing capability must fail closed");
assert!(error.to_string().contains("requires missing capability"));
}readiness#
通过 PluginStatus(plugin、ready、failure_count、transient_reason)断言 not_ready_soft 只拉低本插件就绪态而不关闭全局准入:
#[tokio::test]
async fn a_failing_probe_marks_this_plugin_not_ready_without_closing_admission() {
let mut running = PluginHarness::new().plugin(MailPlugin).boot().await.unwrap();
assert!(running.readiness().is_ready());
assert!(running.status::<MailPlugin>().unwrap().ready);
running.require_state::<MailProbe>().unwrap().force_failure();
assert!(!running.status::<MailPlugin>().unwrap().ready);
assert!(running.readiness().is_ready());
assert_eq!(
running.status::<MailPlugin>().unwrap().transient_reason.as_deref(),
Some("mail endpoint unreachable")
);
running.shutdown().await.unwrap();
}task ownership#
用 Drop 翻转的 AtomicBool 证明受管协程在停机时被停止并 join:
#[tokio::test]
async fn shutdown_stops_and_joins_the_plugin_owned_service() {
let stopped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let mut running = PluginHarness::new()
.plugin(MailPlugin::with_stop_signal(stopped.clone()))
.boot()
.await
.unwrap();
running.shutdown().await.unwrap();
assert!(stopped.load(std::sync::atomic::Ordering::Acquire));
}resident 归属#
仅依赖 kxed-core 的插件不持有 Resident 归属,本项在测试报告中明确标注 SKIP 与原因(应用层实体验证见 RESIDENT.md)。
rollback#
验证 start 失败时插件自身已获取的资源同样经过逆序回滚释放:
#[tokio::test]
async fn a_start_failure_releases_everything_this_plugin_acquired() {
let released = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let error = PluginHarness::new()
.config_override("plugins.mail.endpoint", "")
.plugin(MailPlugin::with_release_signal(released.clone()))
.boot()
.await
.err()
.expect("an invalid endpoint must fail closed");
assert!(error.to_string().contains("endpoint must be"));
assert!(released.load(std::sync::atomic::Ordering::Acquire));
}shutdown#
验证正常停机后状态清空且阶段到达 LifecyclePhase::Stopped(另配 shutdown_timeout 验证慢 drain 超时错误包含插件名与阶段名):
#[tokio::test]
async fn state_is_released_and_the_lifecycle_reaches_stopped() {
use kxed_core::plugin::LifecyclePhase;
let mut running = PluginHarness::new().plugin(MailPlugin).boot().await.unwrap();
assert_eq!(running.lifecycle_phase(), LifecyclePhase::Ready);
running.require_state::<MailClient>().unwrap();
running.shutdown().await.unwrap();
assert_eq!(running.lifecycle_phase(), LifecyclePhase::Stopped);
assert!(running.state::<MailClient>().is_none());
}12. 挂进应用#
在默认 facade 应用中注册插件(排在内置能力之后、Mailbox 与 Transport 之前):
use kxed::prelude::*;
use kxed_plugin_mail::MailPlugin;
fn build_app() -> App {
App::new().plugin(MailPlugin::new())
}不使用 facade 的自定义宿主需注入 ConfigRepository、ProcessTopology 与 WsRoutes,在 start 与 ready 之间调用 WsRoutes::seal()(升级前须显式将单帧与消息上限收紧至 64 KiB,见 DESIGN.md 第 6 节):
use kxed_core::plugin::{LifecyclePhase, PluginManager};
use kxed_core::{ConfigLoader, ProcessTopology, WsRoutes};
use kxed_plugin_mail::MailPlugin;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let repository = ConfigLoader::new().load()?;
let mut manager = PluginManager::new();
manager.provide_framework_state(repository)?;
manager.provide(ProcessTopology::default())?;
manager.provide_framework_state(WsRoutes::default())?;
manager.register(MailPlugin::new())?;
manager.build()?;
manager.start().await?;
let ws_routes = match manager.app_state().require::<WsRoutes>().and_then(|routes| routes.seal()) {
Ok(routes) => routes,
Err(error) => {
manager.shutdown().await?;
return Err(error.into());
}
};
manager.ready().await?;
assert_eq!(manager.lifecycle().phase(), LifecyclePhase::Ready);
// 自己的 server 循环,把 ws_routes 挂到自己的 server 上。
manager.shutdown().await?;
Ok(())
}HTTP 流水线由排在所有路由插件之后的宿主插件在 ready 阶段调用一次 seal_http_pipeline 封存取出(完整样例见 tests/repo/fixtures/ws-plugin-consumer/ 与 crates/core/tests/integration/open_composition.rs):
use kxed_core::plugin::{
Plugin, PluginResult, PluginRun, PublicHttpGraphs, SealedHttpPipeline,
};
use std::sync::{Arc, Mutex};
struct HostPlugin {
pipeline: Arc<Mutex<Option<SealedHttpPipeline>>>,
}
impl Plugin for HostPlugin {
async fn ready(&mut self, ctx: PluginRun) -> PluginResult {
*self.pipeline.lock().unwrap() = Some(ctx.seal_http_pipeline()?);
Ok(())
}
}let sealed = pipeline.lock().unwrap().take().expect("sealed HTTP pipeline");
let graphs = sealed.apply(PublicHttpGraphs::new(axum::Router::new(), None));
let (http, websocket) = graphs.into_parts();13. 贡献运维命令#
使用 #[derive(Command)] 加 owners = [P] 为应用二进制贡献 CLI 子命令,命令仅在 P 被注册、按类型声明或内嵌时展示(属性全集见 宏参考,官方参考见 crates/plugins/src/search/commands/mod.rs):
use kxed_core::command::{Command, Output, Record};
use kxed_core::{AppCtx, AppErr};
kxed_core::command_group!("mail", "Inspect the outgoing mail queue");
#[derive(Command)]
#[command(name = "mail queue stat", owners = [MailPlugin], about = "Show how many mails wait to be sent")]
pub struct MailPending {
#[arg(long, default = 100, range = 1..=1000, help = "Most queues to count")]
limit: usize,
}
impl Command for MailPending {
async fn run(self, ctx: &AppCtx) -> Result<Output, AppErr> {
let queue = ctx.require_state::<MailQueue>()?;
Ok(Record::new().field("pending", queue.pending(self.limit)).into())
}
}- 离线与启动分档:缺省为启动档命令;带后台消费循环的插件在
start用CommandProcess::is_active(&ctx.app_state())跳过启动消费者;只读配置的命令标#[command(offline, owners = [P])],改写状态的命令标#[command(destructive)](退出码见 SPEC 第 2 节,遇到进程内后端无法跨进程读取时返回 503)。 - 运维端口与
/stat接入:在start向StatSections注册段落接入stat --remote,或向ManagementRoutes合入只读诊断路由并在Plugin::routes返回RouteInfo::management;运维面无鉴权,严禁输出凭据或业务数据。
14. 发布 checklist#
| 检查维度 | 准出核对项 |
|---|---|
| 命名与依赖 | 包名 kxed-plugin-<domain>、类型 <Domain>Plugin、配置前缀独立(如 plugins.mail);kxed-core 用不带 rev 的 git 依赖,testing 仅放 [dev-dependencies],不依赖 kxed 或 kxed-runtime |
| 配置与后台协程 | 配置全进 ConfigSection 且 fail-closed;后台工作全走受管任务并监听 stop_token()(进行中的外部 I/O 同样需 select! 监听取消,避免拖慢下游 Resident 停用) |
| 资源回收与预算 | start 获取的资源在 drain/shutdown 幂等释放并有 Drop 兜底;停机超时从 slice(fraction, floor) 派生,不占满全部 remaining() |
| 就绪与状态边界 | 外部短暂抖动用 not_ready_soft;不使用全局静态变量保存状态,不在请求热路径重解析配置,不占用 /healthz、/readyz、/metrics |
| 文档与外部验证 | README 列全配置键默认值与 N>1 行为,公开项带 rustdoc;发布前跑通 cargo test、clippy -D warnings 与仓库外真实 consumer 编译 |