设计与取舍
1. 设计目标#
- 设计问题:常规后端需要同时承载 HTTP、长连接、后台队列、定时调度与跨节点协作。若按功能拼装多套运行时或引入外部消息总线,单机开发与多机部署就会分裂成两套代码与运维模型。
- 取舍结论:将全部网络协议、异步能力与生命周期收敛在单个 Tokio runtime 与单个二进制内。
kxedfacade 提供开箱即用的默认装配;直接组合kxed-runtime、kxed-livecell与kxed-plugins的应用仍共享同一套kxed-core契约,不强制绑定 facade。 - 机制要点:
- HTTP、WebSocket、业务 TCP 与业务 UDP 构成对外协议面,Procedure 在其上提供统一的类型化业务契约层。
- Task、Result dispatch 与 Event 对应三种独立的等待与重发语义;Task 严格限定三种执行模式与四种触发器。
- Presence、
push与broadcast仅负责在线连接路由与实时投递,不充当业务用户库或持久消息日志。 - Fabric 作为私有底座提供本机信箱、成员视图、加密会话、信用背压与跨节点等待槽,不向业务代码暴露节点身份。
- 类型化配置派生内部进程能力位,仅裁剪同一二进制内的运行组件;所有队列、槽位、帧长与停机等待均设硬上限。
flowchart LR
business["业务应用 crate"] --> default_assembly["kxed 默认装配"] --> runtime["kxed-runtime"]
custom["自定义装配或第三方插件"] --> contracts["kxed-core 契约"] --> selected["按需选用的能力与插件包"]
client["客户端"] --> listener["公开监听器"] --> handler["本机 handler / Procedure"]
handler --> response["本机响应"]
handler --> work["Task / dispatch / Event / push"]
cross["显式跨进程协调"] --> fabric["私有 Fabric 底座"]2. Workspace 和依赖方向#
- 设计问题:若能力包或官方插件反向依赖顶层
kxed,第三方插件就会被迫拉入全量依赖图甚至形成循环依赖。 - 取舍结论:工作区严格按 6 层单向无环边界划分(Layer 0 叶子包 -> Layer 1 宏与迁移 -> Layer 2
kxed-core与kxed-livecell-> Layer 3kxed-runtime-> Layer 4kxed-plugins-> Layer 5kxed顶层宿主)。 - 机制要点:
kxed-runtime的procedure与task模块不依赖fabric,跨节点路由由kxed私有装配经 SPI 反向注入;kxed-plugins的基础插件只依赖kxed-core,涉及 Procedure 或集群转发的插件按需通过可选 feature 依赖kxed-runtime。- Livecell 运行时、SDUI 组件库与 Fly 管理后台聚合在独立于
kxed-core的kxed-livecell包内(按 feature 分层),通过宿主适配器kxed-plugins接入生命周期。 - 完整的 6 层 Cargo 依赖图与目录职责见 仓库布局。
3. Facade 和 prelude#
- 设计问题:框架导出符号众多,全部平铺在根路径或
prelude会污染业务命名空间,而让业务手写大量第三方基础库依赖又会抬高起步门槛。 - 取舍结论:
kxed根命名空间只保留App、AppCtx、AppErr、Result、CallFailure、入口宏main与声明宏,其余公开类型按唯一路径归入主题模块(完整清单见 SPEC 第 2 节)。prelude只放高频声明宏、核心上下文类型与匿名引入的扩展 trait(as _)。 - 机制要点:
- 基础库重导出:facade 直接重导出
axum、bytes、serde、serde_json、tower_http、metrics与tracing;kxed::tokio将main与test包装为自带crate = "kxed::tokio"的宏,应用无需单独依赖tokio。 - 免额外依赖派生宏:上游 serde 派生宏硬编码
extern crate serde,kxed-macros通过生成同字段影子结构配合remote转发消除外部依赖;kxed::prelude::Validate直接展开到#core::__garde::Validate,对未标字段默认跳过,免去显式依赖garde与手写#[garde(skip)]。 - 隐藏宏展开桥:过程宏展开统一引用
kxed::__private,不受公开模块重排影响;TaskPlugin、ResidentPlugin等装配级 SPI 留在各自能力包内。 - 禁止
Deref到AppCtx:AppCtxAccess基于AsRef<AppCtx>实现,防止无请求上下文的TaskCtx与ResidentCtx误调ctx.identity()静默拿到None。 - 统一配置入口:配置与依赖注入收敛在
App::new().config(ConfigLoader)与App::provide_with(|config| ..),main无需预读配置,config check与正式启动共享同一份不可变ConfigRepository。
- 基础库重导出:facade 直接重导出
公开错误类型统一是 #[non_exhaustive],跨 crate 的 match 必须带通配臂;没带属性的公开错误枚举与 struct(名字以 Error 或 Err 结尾)必须列在下面「不加属性」一段,docs-check 按文件逐个核对。带属性的类型按所属列出:
- core(请求、身份与插件):
Reject、PushError、GuardNameError、IdentitySetError、IdentityError、AuditError、GrantsError、AccessError、PluginHarnessError、PluginError、AppErr、ArgError - core(配置、密码学与 Webhook):
ConfigError、ReportingError、CryptoError、SignatureError、AppKeyError、WebhookScheme、WebhookConfigError、WebhookSecretError - duration:
Error - utils:
EncodingError、DecompressError、CipherError、TimeError、IdError、GraphError、CidrError - facade:
EmitError、DispatchError、LoggingError、SitemapError与testing的TestWsError - resident:
ResidentCallError、ResidentError、ResidentRegistrationError、ResidentIdError、WireError、ResidentSettingsError - Task(提交与控制):
TaskSubmitError、TaskStatusError、ResultReadError、TaskControlError、QueueControlError、MaintenanceError、MaintenanceSnapshot、TaskLookupError、CronScheduleError、CronReadError、CronTriggerError、CronControlError、CronLookupError、CronReconcileError - Task(注册与存储):
MapEmitError、TaskStoreError、TaskKeyError、TaskOptionsError、TaskRegistryError、TaskRegisterError、TaskServiceError、TriggerError、TaskFailure、TaskOutputError、TaskSettingsError - Task(ID 与游标解析):
ParseTaskIdError、ParseCronScheduleIdError、ParseCronOccurrenceIdError与ParseDeadLetterCursorError - Event:
EventJsonError - Presence:
PresenceStartError、PresenceShutdownError、TopicMembersError、BroadcastError - Fabric 交给 Presence 适配:
UserPushError - Security:
SecurityRejectReason、RateLimitError、RateQuotaError - plugin(存储、认证与外呼):
ObjectStoreError、TusError、AuthError、OAuthError、OtpError、PasswordVerifyError、TotpError、AuthorizationError、CsrfError、CacheError、DeviceLeaseError、DrawError、LedgerError、BatchFlushError、BatchIngestError、DeviceError、JsonRpcClientError、MailError、RollupError、SpreadsheetError、UnmarkedSourceWriteError - plugin(开关、检索与会话):
FeaturesError、IpError、RedisError、SearchError、NotifyError、WebPushError、FcmError、RollbackError、HttpClientError、SessionError、ParseSessionKeyError、SettingsError、SettingsFieldKind、StateMachineError、StoreError、ConsensusError - Livecell:
DocumentError、I18nError(kxed-livecell)、AssetDirError、AddressError、MountError(应用的页面注册与 Fly 路由表返回它)、LiveError、CommandError、AttributeNameError、RuntimeError(应用只按LIVECELL.md列出的变体判断),host adapter 的PageCallError与FlyAccountResourceError - SDUI:
RecordError、TreeError、GlobalSearchError - i18n:
I18nError(kxed-i18n) - Fly:
AccountError、ApiTokenError、StoreError、ResourceError、OperatorsError、SheetError
TaskOutcome 的五个终态、Task 取消的结局 CancelOutcome 与 CronCancelOutcome、Fabric SPI 的 wire 枚举,以及框架内部合同与固定协议体的错误不加属性:前两类是封闭的业务结局,wire 枚举由 wire golden 锁定。不加属性的类型包括:
- livecell runtime 与 host adapter 之间的
ProtocolError(host adapter 穷尽匹配以免漏映射状态码) - 授权诊断细节
AccessDiagnosticError(kxed-plugins读 token scope 失败时按同一形状构造,再交给同一条日志路径) - Presence 的
FrameJsonError、FrameDeliveryError与FrameSink的FrameSendError #[doc(hidden)]的EventWireError、HandleFailure、DispatchRemoteError- Task 与 Mesh 的 SPI 错误
RemoteExecuteError、CronHandoffError、MeshHandlerError、MeshAskError - Fabric 模块(
kxed-runtime)内部的CodecError、AskError、AckError、AskHandlerError、FabricConfigError与LocalPushError(应用不直接依赖,facade 只在宏私有路径再导出AskHandlerError) - 电子表格逐行导入回执数据载体
ImportRowError(业务回调需字面量构造)与 JSON-RPC 2.0 固定{code, message, data}协议错误体JsonRpcError
字段全部公开的 pub struct *Config 同样强制带 #[non_exhaustive],通过配置加载或 Default 加 with_* 构造,保证新增配置键不破坏下游编译。
3.1 Router#
- 设计问题:原生 axum
Router::layer只包裹调用前已注册的路由,顺序写反就会漏掉后续路由;且路由嵌套后难以离线导出完整路径表。 - 取舍结论:
kxed::http::Router暂存作用域内的layer,在分组闭包返回或顶层封口时统一按route_layer包裹该范围的全部 HTTP 路由,使layer与书写位置无关。 - 机制要点:
group(prefix, |r| ..)将完整前缀展开进静态路由表供./app routes逐条列出,与只记录挂载点的nest_axum区分。/healthz、/readyz与/metrics为保留路径,启动前通过一次性守卫图拦截显式注册或merge_axum冲突,冲突时逆序清理已启动插件并返回错误而非 panic。
3.2 App 单实例#
- 设计问题:集成测试常在同一进程内连续启停多个
App,若用进程级全局变量保存服务句柄会导致跨测试串线。 - 取舍结论:进程内仅用
APP_SLOT互斥锁保证同一时刻至多运行一个生产App,而 Task、Event、Resident、push 与 dispatch 服务实例全部挂在当前AppCtx持有的AppState下,随生命周期干净释放。
3.3 Plugin 组合内核#
- 设计问题:多个插件同时持有数据库连接、后台协程与 HTTP 中间件时,单轮停机遍历会让上游还在排空请求时下游连接池已提前关闭。
- 取舍结论:
Plugin定义六阶段生命周期,停机拆分为begin_drain(停止接纳)与drain(等待排空)两轮独立的逆拓扑遍历,最后再逆序执行shutdown释放底层连接。
pub trait Plugin: Send + 'static {
fn declare(&self, declaration: &mut PluginDeclaration) {}
fn build(&mut self, ctx: &mut PluginBuild) -> PluginResult { Ok(()) }
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;
}flowchart LR
register["register"] --> resolve["resolve graph"] --> build["build"] --> start["start"] --> ready["ready"] --> activate["activate"] --> admit["admit"]
failure["failure"] --> fail_begin["reverse begin_drain"] --> fail_finish["reverse drain"] --> fail_shutdown["shutdown"] --> failed["failed"]
active["active"] --> draining["draining"] --> stop_begin["reverse begin_drain"] --> stop_finish["reverse drain"] --> not_accepting["accepting false"] --> stop_shutdown["shutdown"] --> stopped["stopped"]- 机制要点:
- 拓扑与阶段租约:
declare收集require、require_capability、provide_capability与软顺序after;PluginRun按阶段限制provide(仅start)与seal_http_pipeline(仅ready),钩子返回后上下文立即失效。 - 首次受控 poll 屏障:
PluginRun::spawn登记的常驻协程在全部ready通过后统一做一次受控poll;若提前返回、Err或 panic 则立即中止启动并逆序回滚,全员Pending后才原子开放Active与外部准入。 - 受管任务与阻塞池:
PluginTasks允许运行期派生至多 1024 个异步作业;spawn_blocking使用独立进程级有界线程池(1..=32 线程,队列 1024),停机到期取消排队项并放弃观察运行中闭包,不阻塞进程退出。 - 子预算与三态解耦:
begin_drain占剩余预算 25% 并按插件均分;PluginStop::slice(fraction, floor)切分子预算,即使总期限耗尽仍对每个清理钩子偏向poll一次完成同步释放。运行态拆分为activation、admission与operational三个标志。
- 拓扑与阶段租约:
3.4 HTTP request pipeline#
- 设计问题:业务中间件与安全、会话、认证、授权层的叠加顺序若靠注册先后决定,极易因插件装配顺序调整导致未认证请求穿透或限流误扣。
- 取舍结论:设立固定的五加一阶段流水线,在 Transport
ready阶段一次性逆向套叠封存(seal),请求热路径零锁直走编译好的 Tower 服务图。
flowchart LR
error_pages["ErrorPages"] --> security["Security"] --> session["Session"] --> authentication["Authentication"] --> authorization["Authorization"] --> hooks["ApplicationHooks"]最外层请求守卫采用手写 Tower Service(省去 from_fn 的多层克隆与装箱),单次栈拼 x-request-id、提取 W3C traceparent、注入共享 Arc<RequestContext>(含多 guard IdentitySet、截止时间与取消令牌),并在同一审计与 panic 边界内驱动下游。
| Plugin | 底层依赖 | 流水线与状态设计摘要 |
|---|---|---|
SecurityPlugin | tower-http、tower-governor | 单一静态服务层覆盖 HTTP 与 WS 升级:外层先做无状态 CSRF、CORS 与 WS Origin 拦截(被拒不扣限流令牌),内层还原可信代理 IP、执行分档限流与请求体限制;trusted_proxy.policy 默认 unset,公网监听强制显式选 peer 或 forwarded_headers(见 SECURITY) |
SessionPlugin | Tower Sessions、SeaORM、SHA-256 | new() 按 session.backend 的 memory、redis、database(缺省 memory)选 MemorySessionStore、RedisSessionStore 或在 SeaOrmPlugin 的连接上建的 SqlSessionStore;Cookie ID 经 SHA-256 哈希为 SessionKey 落库,不存明文 |
AuthPlugin | SHA-256、SeaORM、jsonwebtoken、Argon2 | 分离服务端可撤销认证记录与 Cookie 会话数据,杜绝并发写回恢复已登出身份;支持可选 JWT 与有界 Argon2 校验 |
AuthorizationPlugin | 自研 guard 索引引擎 | 依赖 AuthCapability,启动期编译不可变的多域 RBAC 前缀索引,按解码规范化路径执行 deny 优先与默认拒绝裁决 |
CachePlugin | Moka、Fred | 内存后端用 Moka 双维权重加 300ms 维护协程;Redis 后端用代次键 kxed:cache:<prefix>:<gen>:<key>,invalidate_all 仅递增代次号免全库扫描 |
RedisPlugin | Fred | 8192B URL 解析、有界命令缓冲与周期健康探测,空 URL 不建池 |
TemplatesPlugin | MiniJinja | 按扩展名统一决定 HTML/XML 自动转义与响应 Content-Type,支持开发态文件指纹重建 |
SeaOrmPlugin | SeaORM | 8192B URL、关闭每次取连 ping、改由后台周期探测维护就绪态并在停机时优雅关池 |
3.5 Config Repository#
- 设计问题:若按运行时实际注册的插件动态认领配置段,离线
config check与条件装配分支就会得出不一致的未知字段结论。 - 取舍结论:采用编译期节认领。所有编入当前二进制的
#[derive(ConfigSection)]自动认领各自顶层命名空间;在config.strict = true(默认)下,未认领的未知顶层段直接触发ConfigError::UnclaimedNamespaces拒绝启动,拦截环境变量前缀拼写错误(详见 配置参考)。
3.6 进程内状态的降级信号#
- 设计问题:单机开发常用的内存缓存、内存会话或本地 SQLite 在扩到多副本后会发生状态分裂,但运行期动态入群时若直接拉低
/readyz会导致全集群同时摘流下线。 - 取舍结论:注入只升不降的拓扑锁存器
ProcessTopology(兼顾静态fabric.seeds、显式fabric.discovery.mode与运行期 gossip 发现)。启动时已处集群且未在fabric.allow_process_local承认的进程内后端直接拒绝启动;运行期才入群则写 warn 并将对应*_degraded指标置 1,保持/readyz可用。Livecell 本地上传不设豁免,多实例集群强制使用共享对象存储。
4. 宏和 registration#
全仓声明宏统一通过 inventory 收集编译期静态描述符,不扫描源码目录,也不依赖 build.rs 生成注册表。
4.1 #[task]#
- 取舍结论:
#[task]直接标注在impl NormalTask、impl MapTask或impl MapReduceTask块上,从 trait 签名唯一推导模式、输出、错误与子任务类型,避免结构体属性重复声明(参数见 TASK 第 1 节)。 - 机制要点:线上信封与存储记录使用
kxed_core::key_of(name)派生的 64 位键替代易碰撞的 16 位手工编号;跨进程名称缺省直接取类型名(不含 crate 与模块路径),消除多二进制目标下 crate 名不同引发的漂移(见 SPEC 第 7.12 节)。
4.2 #[event] 和 #[on]#
- 取舍结论:
#[on(E)]默认采用单实例本地投递OnDelivery::Once,避免应用从单实例扩到 N 副本后发信或写库副作用静默放大 N 倍;需全实例广播刷新本地缓存时显式声明every_process。 - 机制要点:
#[on(E, durable)]复用持久 Task 存储,每次ctx.emit为各订阅者接纳kxed.event.durable任务(带.within(&txn)时同事务加写一条after commit记录,确保内存订阅也在提交后触发)。every_process作用域内通过 task-local 禁止再次提交 Task 或emit,阻断级联风暴。
4.3 #[dispatch]#
- 取舍结论:将首参为
&AppCtx的异步函数编译为位置透明调用,共享DISPATCH_KIND并按 8 字节函数键路由;参数与返回值使用保留字段名的 CBOR 编解码以支持#[serde(default)]滚动升级。 - 机制要点:选路命中本机时跳过 TCP 与信封组装,但仍执行相同的 64KiB 帧长校验、非平凡类型编解码往返与审计操作者作用域隔离,确保单机与跨机行为一致(见 SPEC 第 7.8 节)。
4.4 #[derive(Command)] 与命令层#
- 取舍结论:通过
#[kxed::main]在同一个应用二进制内直接内置运维 CLI,省去维护独立管理二进制的成本。 - 机制要点:
kxed-core仅保存纯静态CommandRegistration,将 clap 依赖隔离在kxedfacade 内,并按#[command(owners = [P])]随已注册插件裁剪可见命令。只读命令走不启插件的离线档;读写存储的命令以剥离了公开端口与集群密钥的隔离命令进程运行。
4.5 Procedure 流水线与 REST 投影#
- 设计问题:若为 REST、RPC、WebSocket、MCP、gRPC 与桌面 IPC 分别手写 handler,鉴权、限流、参数校验与对象级权限极易在某条入口漏检。
- 取舍结论:
#[query]、#[mutation]与#[subscription]将函数封装为同名单元结构,隐藏裸函数体,强制所有外部适配器与进程内ctx.call汇入kxed_runtime::procedure::execute的固定 8 步安全流水线(身份解析 -> 暴露面检查 -> 角色权限 -> 近期密码确认与入口限流 -> 输入与上传令牌校验 ->Found<E>记录绑定 ->Policy对象授权 -> 目标位置执行)。 - 机制要点:
- REST 输入自动合成:启动期按输入类型的规范化 JSON Schema,将
GET/DELETE查询串转为标量或数组,与POST/PUT/PATCH的 JSON 体合并,最后覆盖写入优先级最高的路径参数(如{id})。 - 双模状态码:
/_rpc固定返回 HTTP 200 以便生成的跨语言客户端统一解析;REST 投影支持定制201 Created或无响应体的204 No Content,兼顾标准 REST 语义与零胶水代码复用(见 Procedure 参考)。
- REST 输入自动合成:启动期按输入类型的规范化 JSON Schema,将
5. Runtime 和私有 assembly#
PluginManager 是唯一的生命周期协调器。FabricKernel 在插件图下方先行启动,将私有的 FabricHandle 与 FabricState 注入内置能力插件(实线为 require 强依赖,虚线为 after 顺序边):
flowchart LR
handle["FabricHandle"] --> presence["PresencePlugin"]
handle --> event["EventPlugin"]
handle --> resident["ResidentPlugin"]
presence --> view["RuntimeViewPlugin"]
event --> view
task["TaskPlugin"] -.-> view
state["FabricState"] --> view
view -.-> custom["应用与官方插件"]
custom -.-> mailbox["MailboxPlugin"]
view --> mailbox
mailbox --> transport["TransportPlugin"]
state --> mailbox| 内置 Plugin | 启动期(build / start / ready)所有权 | 停机期(begin_drain / drain / shutdown)所有权 |
|---|---|---|
PresencePlugin | 连接归属表、单持有者 LWW 路由与成员跟踪状态 | 发送最终退场同步帧并清理映射 |
EventPlugin | 类型化订阅队列、编解码桥与消费协程 | 关闭接纳、排空在途事件并回收消费协程 |
ResidentPlugin | 实体槽位、放置视图监听、租约续期与邮箱协程 | 拒绝新激活、以 Shutdown 停用实体并等待接任者视图更新 |
TaskPlugin | 任务与 Cron 注册表、队列、图协调器与存储适配器 | 双层门控切换、在途任务与子图排空、释放许可 |
RuntimeViewPlugin | 组装面向 handler 的受限 Runtime 视图与指标渲染器 | 清理运行时视图状态 |
MailboxPlugin | 按精确 wire kind 安装内部 tell/ask 路由表 | 先驱动 Task 完成屏障,再关闭业务路由准入并等待在途处理 |
TransportPlugin | 绑定运维端口及配置开启的 HTTP/WS/TCP/UDP 监听器 | 撤回就绪态、停止 accept、排空请求与长连接 |
MailboxPlugin 启动时排在 TaskPlugin 与自定义插件之后,停机 drain 时前置驱动一次 Task 完成屏障,确保在途持久子图与内存 Cron 交接在跨节点路由关闭前完成收尾。
6. HTTP 和 WebSocket 实现#
- 自管 HTTP 循环:基于
hyper自管 accept 循环与TaskTracker,支持证书后台热轮换 TLS 与 HTTP/2(独立 WS 端口与运维端口保持 HTTP/1)。业务请求受默认 4096 信号量守卫,许可随响应体持有至析构;HandlerDeadline扣除慢请求体读取时间,运维端点独占 64 槽信号量。 - 流式收尾:流式 gRPC 按 5 字节头逐帧核验
server.http.grpc.max_message_bytes,停机切片末尾提前写grpc-status: 1;SSE 收到停机信号主动发event: kxed.drain引导客户端重连,带身份流每秒复查凭据。 - WebSocket 读写泵与零拷贝广播:升级前将单帧与单消息上限收紧至 64KiB(替代 Axum 默认 64MiB),单连接协程并发驱动 handler、1 帧预读背压读泵与有界写泵(256 项且 1MiB)。广播时
ClientFrame通过OnceLock缓存单次 JSON 序列化结果,N条连接仅做O(1)引用计数克隆。
| 连接存活兜底机制 | 适用平台 | 触发行为 |
|---|---|---|
| 内核 TCP keepalive | 全平台 HTTP/WS 与业务 TCP(30s 空闲,3×10s 探测) | 发送缓冲为空时探测断网对端并回收连接槽 |
TCP_USER_TIMEOUT | Linux 与 Android(60s) | 有未确认出站字节持续 60s 时由内核直接断开 |
| 应用层写超时与固定 Ping | 全平台 WS 与 TCP 写协程(单次写上限 60s) | WS 按 read_idle_timeout / 4(至多 15s)发 Ping,读空闲到期即断开 |
7. 业务 TCP 实现#
- 分帧与合批写出:每个
App::tcp(name, TcpService)先经全局与来源连接配额准入,再构造连接独占的编解码器(默认小端u32长度前缀、上限 64KiB,支持with_codec替换),写侧用至多 32 帧IoSlice向量化合批写出。 - 公平份额与慢读驱逐:全进程共享 64MiB 出站字节预算;当余量低于 16MiB 时,已占满 256KiB 公平份额的连接暂停入队以保护轻载连接;持续积压达 120s 的慢读连接被主动驱逐回收许可;正常关闭执行至多 1s、1MiB lingering close(上限 256 槽)防内核 RST 冲掉尾帧。
8. 业务 UDP 实现#
- 无每包派生任务:每个
App::udp(name, UdpService)复用单块接收缓冲、容量 256 的FuturesUnordered池与 256 槽出站队列。 - 防反射放大:UDP 源地址可伪造,回复预算按来源是否已调用
bind(uid)完成业务认证分级控制;Presence 映射表按 64 分片管理至多 4096 个地址并后台定额清理空闲项。
| 来源绑定状态 | 回复字节限制 | 超限处置与指标 |
|---|---|---|
尚未调用 bind(uid) | 同一入站数据报触发的累计回复不超过入站长度的 3 倍 | 拒绝发送并返回 Reject::TooLarge,累加 kxed_udp_reply_reject_total{reason="amplification"} |
已完成业务认证并 bind(uid) | 解除 3 倍放大限制,受单包 65507B 与每地址 1MiB 驻留预算约束 | 正常入队发送 |
9. 连接、Presence 和 topic#
9.1 本机连接表#
本机 ConnMap 按 64 个分片维护 Uid -> Arc<[ConnEntry]> 写时复制快照:热路径扇出在锁内仅做 O(1) 指针克隆,序列化与入队均在锁外执行;连接关闭通过原子终止位触发最长 1s 写排空,保证连接槽与路由解绑恰好执行一次。
9.2 Single-owner LWW Presence#
- 设计问题:跨主机墙钟存在偏斜,若靠纯物理时间戳裁决在线路由归属,用户断线重连到时钟略慢的节点时会被旧路由压制。
- 取舍结论:集群级
PresenceTable(上限 262144 条且 64MiB uid 字节)采用混合逻辑时钟序号实现单持有者最后写入胜出(LWW),不依赖精准 NTP。 - 机制要点:
- 混合逻辑时钟:高 48 位为墙钟毫秒,低 16 位同毫秒自增,收发时
fetch_max吸收远端序号(超前本机墙钟逾 24 小时的异常帧以NoRoute拒收)。 - 孤儿连接自愈:远端抢占路由时不强踢本机旧连接;若远端持有者随后下线,本机 250ms 对账协程从有界「被顶替集合」中为仍存活的连接重发
Put恢复可达。 - 限频收敛扇出与流式反熵:未知路由推送执行每秒至多 4 次限频扇出,超时归为 504
PushError::Unconfirmed;新节点入网与 5s 周期对账采用Begin/Entry/End流式快照配合墓碑表合并:
- 混合逻辑时钟:高 48 位为墙钟毫秒,低 16 位同毫秒自增,收发时
| 快照握手阶段 | 异常指标归类 |
|---|---|
Begin 帧收到 NoRoute(身份或时钟超界) | kxed_presence_sync_failure_total{reason="no_route"} |
Begin 通过后 End 帧收到 NoRoute(条目不全或墓碑溢出) | kxed_presence_sync_failure_total{reason="incomplete"} |
9.3 Topic#
客户端主题订阅表仅存于本机(每连接 256 个,全进程默认 65536 条、16MiB 键字节),跨连接共享 Arc<str>。broadcast 先对本机 64 分片写时复制集合做锁外扇出,再向存活远端各发一帧 Dest::Topic;服务端 KIND_EVENT 跳过本机网络回环防重复执行。
10. Task 实现#
持久与显式内存 Task 的准入、租约续期、组提交、Cron 放置与子图重排实现见 TASK 第 9 节。
11. Result dispatch 和 Event#
11.1 Result dispatch#
#[dispatch] 在开启了 tasks.execution.enabled 的存活节点间按「采样队列深度 + 发送方预占在途数」选路(本机空闲时零锁直调)。调用端与执行端共享 dispatch.timeout(默认 5s);应答通过互斥标签区分业务 Err(E) 与基础设施错误,解码损坏返回 502 dispatch_reply_undecodable。
11.2 Event#
每个 #[on] 订阅者独占容量 256、1MiB 队列,全进程共享 64MiB 字节池(多路扇出共享单份 Bytes 租约)。普通订阅受 event.handler_timeout(默认 30s)与停机 10% 切片保护;跨节点事件帧使用 5 字节魔数头加零拷贝 CBOR 载荷,坏帧限频告警并计入 kxed_event_wire_reject_total 或 kxed_event_decode_reject_total。
12. Resident 放置与接管#
候选集计算、视图一致性 quorum、进程租约、接管握手与存储条件写栅栏的实现见 RESIDENT 第 11 节。
13. Fabric 本机路径#
同进程消息免过内核协议栈的内存直通实现见 FABRIC 第 1 节。
14. Fabric 成员和 mesh#
节点组网与状态复制采用四层可插拔抽象:第 1 层 PeerDiscovery 负责产出与刷新候选对端地址(内置静态 seeds/DNS、UDP 组播与共享存储心跳,允许自定义注入);第 2 层 MembershipBackend 维护集群存活视图(默认 ChitchatMembership 加密 UDP gossip,另提供无 UDP 的 StaticMembership 与自定义实现接口);第 3 层 ConsensusPlugin 作为可选官方插件提供复制状态机与 Raft 共识(单机 StandaloneEngine 直通、多节点 RaftEngine 复制,并抽象 ConsensusEngine、ConsensusTransport、LogStore 与 StateMachine);第 4 层由业务基于共识状态机实现分布式账本等强一致服务。
chitchat gossip 成员投影、可插拔发现与全网状加密 TCP 会话管理见 FABRIC 第 2 节。
15. Fabric frame 和队列#
帧编码、分级信用窗口、优先级写出与批量确认的实现见 FABRIC 第 3 节。
16. Process capability 组合#
三个顶层布尔配置在内部转换为进程能力位掩码,裁剪同一二进制的运行角色而不改变插件依赖图;对端能力位在会话 Hello 阶段固化,向无对应能力的节点发帧会在本机入队前同步返回 Busy:
| 运行组件 | server.public.enabled | tasks.execution.enabled | tasks.scheduling.enabled |
|---|---|---|---|
| 业务 HTTP / WS / TCP / UDP | 控制是否绑定与挂载 | 不影响 | 不影响 |
| 连接归属与在线表 | 控制是否接纳外部连接 | 不影响 | 不影响 |
TaskPlugin | 始终运行(保留提交与查询) | 控制 Normal 与子任务领取 | 控制 Cron 扫描与子图协调 |
ResidentPlugin | 始终运行 | residents.hosting.enabled 的前置条件 | 不影响 |
EventPlugin / PresencePlugin / FabricKernel | 始终运行 | 始终运行 | 始终运行 |
TransportPlugin | 公开加运维监听,或仅运维监听 | 不影响 | 不影响 |
17. 配置和地址#
零集群配置的单实例默认在 127.0.0.1:0 分配临时 Fabric 端口,同机运行多个应用互不冲突(启用 fabric.discovery.mode = "multicast" 或 "storage" 且未配 seeds 时同样可沿用临时端口免冲突;配置 fabric.seeds 或显式 fabric.discovery.mode = "seeds" 时默认取 127.0.0.1:7900 与 7901)。
多节点部署要求 advertise 为对端可达的单播地址(通配 bind 可由 fabric.advertise_cidr 或 fabric.pod_ip 自动补齐);fabric.node_id 与严格递增的 fabric.generation 必须成对显式配置或同时省略;fabric.placement.quorum 默认按 expected_nodes / 2 + 1 推导,详见 Fabric 传输。
18. Readiness、metrics 和日志#
18.1 Readiness#
- 探针分工:
/healthz仅反映进程存活;/readyz与kxed_ready共用实时谓词,要求插件图处于accepting、全部插件无故障、监听与 advertise 就绪、承载 Resident 的进程首次接管门控已放行(kxed_placement_takeover_settled == 1)且放置面未连续降级超 30 秒。 - 超限与故障收口:活节点超过 32 个仅降级放置面,不拉低已收敛节点的
/readyz以免第 33 个节点误入造成全站断流;受管常驻协程或 Fabric 核心协程发生终局故障时,Supervised::wait主动执行完整停机并以非零码退出交守护进程重启。
18.2 Metrics#
核心运维端点通过零全局锁的手写 Prometheus 文本渲染器输出固定 schema 指标,应用自定义 metrics 埋点与插件指标段追加在后;所有核心指标族在任意能力裁剪下始终输出(关闭面以 0 占位),确保监控面板与告警规则不因角色拆分断流(告警规则见 deploy/observability/README.md)。
18.2.1 核心运行时、Procedure、传输与 Fabric 指标#
| 领域 | Series |
|---|---|
| Runtime | kxed_ready、kxed_lifecycle_phase{phase}、kxed_plugin_ready{name}、kxed_plugin_failure_total{name}、kxed_connection_registry_entries、kxed_http_request_in_flight、kxed_http_request_limit、kxed_http_request_admission_reject_total{reason}、kxed_http_responses_total{class}、kxed_http_request_abandon_total{reason}、kxed_http_operation_in_flight、kxed_http_operation_limit、kxed_http_operation_admission_reject_total{reason}、kxed_handler_panic_total、kxed_handler_slow_polls_total{surface}、kxed_log_line_drop_total、kxed_error_report_drop_total、kxed_build_info{kxed_version,app_version,hello_version,revision,panic_strategy}、kxed_http_grpc_stream_drain_cancel_total、kxed_http_request_duration_seconds{method,route,class}、kxed_http_handler_timeout_total、kxed_connection_limit、kxed_connection_in_flight、kxed_connection_admission_reject_total{protocol,reason}、kxed_connection_read_timeout_total{protocol,reason}、kxed_dispatch_schema_mismatch_total{reason}、kxed_shutdown_reject_total{surface}、kxed_shutdown_cancel_total{surface}、kxed_shutdown_redirect_total{surface} |
| Procedure | kxed_procedure_calls_total{name,transport,origin,outcome}、kxed_procedure_stream_frames_total{name,transport} |
| Fabric | kxed_fabric_tell_ok_total{target}、kxed_fabric_tell_busy_total{target}、kxed_fabric_tell_reject_total{reason}、kxed_fabric_handshake_reject_total、kxed_fabric_auth_reject_total、kxed_fabric_gossip_auth_reject_total、kxed_fabric_foreign_settle_total、kxed_fabric_dial_failure_total、kxed_fabric_accept_handshake_failure_total、kxed_fabric_accept_peer_reject_total、kxed_fabric_hello_version_mismatch_total、kxed_fabric_cluster_consistent_mismatch_total、kxed_fabric_session_close_total{reason}、kxed_fabric_silent_session_reap_total、kxed_fabric_accept_error_total、kxed_fabric_task_reject_total、kxed_fabric_task_failure_total、kxed_fabric_wire_shape_mismatch_peers、kxed_fabric_psk_accept_total{key}、kxed_fabric_gossip_accept_total{key}、kxed_fabric_psk_accept_configured、kxed_fabric_seed_resolve_failure_total |
| Ask/ack | kxed_fabric_ask_ok_total、kxed_fabric_ask_timeout_total、kxed_fabric_ask_in_flight、kxed_fabric_ack_in_flight、kxed_fabric_ask_table_full_total、kxed_fabric_ack_table_full_total、kxed_fabric_ask_peer_quota_full_total、kxed_fabric_ack_peer_quota_full_total、kxed_fabric_ask_reject_total{reason}、kxed_fabric_remote_ask_in_flight、kxed_fabric_ask_cancel_send_total、kxed_fabric_ask_cancel_receive_total、kxed_fabric_ask_cancel_unknown_total、kxed_fabric_ask_cancel_queue_reject_total、kxed_fabric_ask_cancel_tombstone_evict_total |
| Mesh | kxed_fabric_sessions、kxed_fabric_live_nodes、kxed_fabric_peak_live_nodes、kxed_fabric_over_capacity、kxed_fabric_credit{peer}、kxed_fabric_inbound_drop_total{reason}、kxed_fabric_placement_quorum_undersized、kxed_fabric_placement_silent_peers、kxed_fabric_placement_excluded_peers、kxed_fabric_mesh_tick_stall_total、kxed_fabric_user_convergence_fanout_total、kxed_fabric_user_convergence_suppression_total、kxed_fabric_user_convergence_acked_full_total |
| Connection | kxed_presence_uids、kxed_presence_uid_bytes、kxed_presence_admission_reject_total、kxed_presence_sync_failure_total{reason}、kxed_presence_sync_complete_total、kxed_presence_final_snapshot_abandon_total、kxed_presence_sync_failing_peers、kxed_presence_resync_request_total、kxed_presence_delivery_miss_total、kxed_presence_sequence_ahead_reject_total、kxed_presence_clock_rebase_total、kxed_presence_peer_decode_reject_total{operation}、kxed_connection_push_reject_total{reason}、kxed_connection_admission_reject_total{protocol,reason}、kxed_topic_memberships、kxed_topic_key_bytes、kxed_topic_admission_reject_total{scope}、kxed_topic_partial_busy_total、kxed_topic_wire_drop_total、kxed_topic_subscription_drop_total、kxed_topic_outbound_filter_panic_total、kxed_connection_wire_drop_total |
| Event/UDP | kxed_event_drop_total{name}、kxed_event_in_flight_bytes、kxed_event_admission_reject_total{scope}、kxed_event_decode_reject_total、kxed_event_panic_total、kxed_event_wire_reject_total、kxed_event_handler_total{name}、kxed_event_handler_seconds_total{name}、kxed_event_handler_in_flight{name}、kxed_event_handler_timeout_total{name}、kxed_event_durable_skip_total{name}、kxed_event_durable_handler_missing_records、kxed_udp_drop_total{reason}、kxed_udp_handler_in_flight、kxed_udp_bindings、kxed_udp_binding_limit、kxed_udp_binding_admission_reject_total{reason}、kxed_udp_reply_reject_total{reason="amplification"}、kxed_protocol_busy_total{protocol}、kxed_protocol_error_total{protocol}、kxed_connection_stall_evict_total、kxed_connection_write_timeout_total{protocol,phase}、kxed_listener_error_total{protocol}、kxed_http_linger_connections、kxed_http_linger_skip_total |
18.2.2 业务能力与官方插件指标#
| 领域 | Series |
|---|---|
| Task | kxed_task_ready_items、kxed_task_ready_bytes、kxed_task_scheduled_items、kxed_task_scheduled_bytes、kxed_task_running_items、kxed_task_roots、kxed_task_children、kxed_task_results_items、kxed_task_results_bytes、kxed_task_result_reserved_bytes、kxed_task_cron_schedules、kxed_task_cron_occurrences、kxed_task_start_total{mode,trigger}、kxed_task_terminal_total{mode,state}、kxed_task_reject_total{scope,reason}、kxed_task_attempt_total{outcome}、kxed_task_panic_total{phase}、kxed_task_storage_error_total{operation}、kxed_task_storage_operation_total{operation}、kxed_task_storage_operation_seconds_total{operation}、kxed_task_settlement_ignore_total{reason}、kxed_task_route_total{scope}、kxed_task_cancel_total{outcome}、kxed_task_result_read_total{outcome}、kxed_task_lookup_total{outcome}、kxed_task_group_commit_batch_total、kxed_task_group_commit_write_total、kxed_task_group_commit_open_seconds_total、kxed_task_group_commit_apply_seconds_total、kxed_task_group_commit_commit_seconds_total、kxed_task_group_commit_queue_wait_seconds_total、kxed_task_group_commit_lanes、kxed_task_group_commit_lanes_busy、kxed_task_control_reject_total{reason}、kxed_task_cron_occurrence_total{outcome}、kxed_task_cron_migration_total、kxed_task_cron_cancel_total{outcome}、kxed_task_cron_fence_total{outcome}、kxed_task_cron_tombstone_evict_total{state}、kxed_task_cron_corrupt_total、kxed_task_cron_reconcile_retire_total、kxed_task_cron_reconcile_failure_total、kxed_task_remote_execute_total{outcome}、kxed_task_handoff_total{outcome}、kxed_task_cron_seen_transfer_total{outcome}、kxed_task_cron_placement_unavailable_total、kxed_task_duration_seconds{mode,state,name}、kxed_task_queue_wait_seconds{queue,name}、kxed_task_storage_degraded、kxed_task_unexplained_records_total{outcome}、kxed_task_storage_clock_jump_total{direction}、kxed_task_storage_clock_offset_seconds、kxed_task_unregistered_name_records、kxed_task_remote_reject_total{reason}、kxed_task_graph_phase_seconds_total{phase}、kxed_task_graph_phase_observations_total{phase} |
| Resident | kxed_resident_instances、kxed_resident_instance_limit、kxed_resident_mailbox_depth、kxed_resident_mailbox_bytes、kxed_resident_activate_total{outcome}、kxed_resident_activate_reject_total{reason}、kxed_resident_deactivate_total{reason}、kxed_resident_deactivate_force_total、kxed_resident_deactivate_panic_total、kxed_resident_call_total{outcome}、kxed_resident_handle_total{source,outcome}、kxed_resident_call_retry_total、kxed_resident_call_from_event_total、kxed_resident_mailbox_reject_total{reason}、kxed_resident_mailbox_drop_total、kxed_resident_notify_forward_total、kxed_resident_notify_drop_total{reason}、kxed_resident_supersede_total、kxed_resident_redirect_total、kxed_resident_release_total{outcome}、kxed_resident_call_abandon_total、kxed_resident_tick_total、kxed_resident_tick_error_total、kxed_resident_tick_in_flight、kxed_resident_tick_seconds_total、kxed_resident_activate_in_flight、kxed_resident_activate_seconds_total、kxed_resident_handle_in_flight{source}、kxed_resident_handle_seconds_total{source}、kxed_resident_deactivate_in_flight、kxed_resident_deactivate_seconds_total |
| Placement | kxed_placement_epoch、kxed_placement_candidates、kxed_placement_degraded、kxed_placement_degraded_reason{reason}、kxed_placement_quorum_agreeing_members、kxed_placement_quorum_size、kxed_placement_lease_expire_total、kxed_placement_lease_teardown_total、kxed_placement_clock_stall_total、kxed_placement_left_at_evict_total、kxed_placement_fence_skew_total、kxed_placement_fence_skew_max_seconds、kxed_placement_primed、kxed_placement_takeover_settled、kxed_placement_unstable_identity、kxed_placement_readiness、kxed_placement_claim_total{outcome} |
| Livecell | kxed_livecell_locate_total{outcome}、kxed_livecell_forward_total{operation,outcome}、kxed_livecell_forward_seconds_total{operation}、kxed_livecell_forward_owner_total{operation,outcome}、kxed_livecell_forward_owner_seconds_total{operation}、kxed_livecell_forward_in_flight_reject_total、kxed_livecell_forward_rate_reject_total、kxed_livecell_relay_total{target,outcome}、kxed_livecell_relay_asset_drop_total、kxed_livecell_push_drop_total{reason}、kxed_livecell_remount_total{outcome}、kxed_livecell_pages、kxed_livecell_sessions、kxed_livecell_replay_bytes{name}、kxed_livecell_mount_capacity_reject_total、kxed_livecell_retiring_components、kxed_livecell_command_busy_reject_total、kxed_livecell_session_push_lag_total、kxed_livecell_async_load_drop_total、kxed_livecell_retiring_overflow_total、kxed_livecell_drop_timeout_total、kxed_livecell_command_timeout_total、kxed_livecell_command_lock_timeout_total、kxed_livecell_mount_timeout_total、kxed_livecell_navigation_unavailable_total、kxed_livecell_upload_in_flight_bytes、kxed_livecell_upload_budget_reject_total、kxed_livecell_upload_handler_total{outcome}、kxed_livecell_upload_handler_seconds_total、kxed_livecell_upload_store_degraded、kxed_livecell_upload_discard_total{outcome}、kxed_livecell_upload_cleanup_fallback_total、kxed_livecell_streams、kxed_livecell_stream_bytes_total、kxed_livecell_stream_reject_total、kxed_livecell_i18n_miss_total{locale} |
| Security / Session / Cache / OTP | kxed_security_reject_total{reason}、kxed_security_rate_limit_process_local_clustered、kxed_security_forwarded_header_ignore_total;kxed_session_evict_total、kxed_session_anonymous_evict_total、kxed_session_record_reject_total{operation}、kxed_session_backend_error_total{operation}、kxed_session_sweep_failure_total、kxed_session_store_degraded;kxed_cache_degraded、kxed_cache_value_format_unknown_total、kxed_http_cache_requests_total{outcome};kxed_otp_issue_total{outcome}、kxed_otp_verify_total{outcome}、kxed_otp_revoke_total{outcome} |
| Auth / Authz / Fly | kxed_auth_decisions_total{guard,outcome}、kxed_auth_unavailable_total{reason}、kxed_auth_store_timeout_total{guard,source}、kxed_auth_store_pool_exhaustion_total、kxed_auth_renew_failure_total、kxed_auth_login_limit_saturation_total{limit}、kxed_auth_observer_drop_total;kxed_authz_decisions_total{guard,outcome};kxed_fly_login_limit_saturation_total{limit} |
| TLS / I18n / Object store | kxed_tls_certificate_expiry_timestamp_seconds、kxed_tls_reload_total{outcome}、kxed_tls_handshake_failure_total{protocol};kxed_i18n_miss_total{locale}、kxed_i18n_format_error_total{locale};kxed_object_store_mirror_failure_total{disk} |
| Database / Search / Notify | kxed_database_pool_exhaustion_total、kxed_database_release_close_total{reason}、kxed_database_query_duration_seconds{operation,outcome}、kxed_database_pool_connections{state}、kxed_database_pool_connection_limit;kxed_search_stale_keys_total{index}、kxed_search_sync_lag_seconds{index}、kxed_search_sync_pending_rows{index}、kxed_search_sync_operations_total{index,outcome}、kxed_search_sync_batches_total、kxed_search_sync_rebuild_abandon_total{index}、kxed_search_sync_relay_last_success_timestamp_seconds、kxed_search_sync_relay_round_failure_total、kxed_search_sync_status_last_success_timestamp_seconds、kxed_search_sync_status_failure_total、kxed_search_dead_letters_total{index}、kxed_search_import_rows_total{index};kxed_notify_deliveries_total{channel,outcome}、kxed_notify_dead_letters_total{channel}、kxed_notify_outbox_pending_rows{channel}、kxed_notify_outbox_oldest_age_seconds{channel}、kxed_notify_relay_round_failure_total、kxed_notify_relay_last_success_timestamp_seconds |
18.3 Logging#
- 设计问题:同步 stdout 日志在容器或管道拥塞时会阻塞 Tokio 工作线程,拖垮心跳与请求响应。
- 取舍结论:
App::run()与supervise()默认安装容量 8192 行的有界非阻塞 stdout 写入器,缓冲满时丢行并累加kxed_log_line_drop_total;命令进程改为同步写 stderr(默认warn),将纯净 stdout 留给--json输出。
| 环境条件 | 默认日志行为 |
|---|---|
RUST_LOG 未设或为空 | 默认级别 info |
KXED_LOG_FORMAT 未设或为空 | 默认 text,设为 json 输出结构化 JSON 行 |
| 过滤串或格式非法、全局 subscriber 已冲突 | 返回类型化 LoggingError,拒绝静默降级 |
高频过载与解码拒绝一律采用计数器加 30 秒窗口限频日志(附 suppressed 计数),框架日志永不打印密钥、凭据、业务载荷或原始 uid。
19. 退出设计#
收到停机信号(SIGTERM 先撤回 /readyz 等待 server.shutdown.drain_delay 让负载均衡摘流)或调用 Running::shutdown() 后,插件图在共享 12 秒预算内完成两轮排空与关闭,随后 FabricKernel 在独立预算内收尾(总预算构成见 SPEC 第 13 节)。
19.1 Drain 阶段等待点#
| 阶段顺序 | 等待点 | 预算约束 | 超时动作 |
|---|---|---|---|
begin_drain | 全部插件逆拓扑停止接纳 | 剩余时间的 25% 按插件数均分 | 丢弃钩子 future 并记超时 |
| Transport | 在途 HTTP 请求、SSE/长轮询连接与 UDP handler | HTTP 切片(总窗口 10%,至少 100ms) | 取消连接与 after_response 任务,中止 UDP 接收协程 |
| Transport | WS/TCP 写协程排空与运行时监听协程 join | 单连接写上限 1s,汇合受全局剩余约束 | abort 残余协程并 join |
| Mailbox | Task 完成屏障(drain_for 与 shutdown_for)及在途路由调用 | 剩余窗口扣除为 Resident 预留的 max(25%, 1s) | 中止调度器、记录入站超时告警并推进下游 |
| 自定义与官方插件 | 插件 drain 钩子与受管任务(含 reserve_after_drain 预留) | 全局剩余减去声明的后置预留 | 丢弃钩子、abort 未完受管任务并 join |
| Resident | 在册活跃实体 deactivate 回调与放置视图摘除确认 | min(call + deactivate + 10%≥250ms, 剩余 - 10%≥250ms) | abort 实体协程后在预留窗内 join 并报告清理错误 |
| Event / Presence | 在途 #[on] 订阅与 Presence 退场 Empty 快照确认 | Event 取 10%(≥100ms);Presence 取 min(剩余, 1s) | 丢弃未完订阅;对无响应死节点放弃重试并记 warn |
19.2 Shutdown 与底座等待点#
| 阶段顺序 | 等待点 | 预算约束 | 超时动作 |
|---|---|---|---|
shutdown | Resident 中止协程汇合 | max(剩余, 250ms) | 返回清理错误 |
shutdown | Task 存储池关闭(SQL 与 Redis) | SQL 取 max(10%≥250ms, connect_timeout + 250ms);Redis 取 10%≥250ms | 重连中客户端直接 abort,仅驱动 panic 报错 |
shutdown | RedisPlugin、SeaOrmPlugin 与 CachePlugin 收尾 | Redis/Cache 各 10%≥250ms;SeaORM 结合 release_ping_timeout | 超时 abort 或记录关池超时日志 |
shutdown | Livecell 页面组件 drop_component | 自有切片 25%(至少 500ms),单组件另受 drop_timeout 约束 | 累加超时计数并跳过剩余页面 |
Fabric | 关闭全部会话、gossip 与底座自有任务 | 独立绝对期限 | 强制 abort 全部残余底座任务 |
Presence 退场同步在多节点同时停机时识别对端 Departing 或已确认的同代 Empty 记录立即结束重试,避免浪费等待窗口;Running 在运行时外被意外 Drop 时触发无阻塞逆拓扑紧急清理。
20. 安全边界#
跨节点通信由 fabric.psk 派生的 Noise 会话与 AES-256-GCM gossip 封装保护,非回环部署缺 PSK 直接拒绝启动;运维端口与 Fabric 端口由网络策略隔离在私网。HTTP 公开监听离开回环时强制核验 SecurityPlugin、独立运维端口、security.trusted_proxy.policy 与 KXED_ENV。完整威胁模型与默认防线由 SECURITY.md 唯一维护。
21. 部署示例设计#
deploy/ 下三类生产模板运行同一个 kxed-example-full-backend 镜像,仅靠配置裁剪角色:
- Docker Compose(
deploy/compose):提供n1、nginx、caddy、split与full-stack五种拓扑,运维端口9090仅绑宿主机回环。 - EC2(
deploy/ec2):统一kxed.service配合LimitNOFILE=65536与 30s 停机窗口托管,NGINX/Caddy 屏蔽公网/metrics并限制单来源连接数。 - Kubernetes(
deploy/k8s):基于 Kustomize 提供app、split与两阶段rollback清单;cargo xtask kustomize-contract静态校验滚动发布不变量2 × quorum > sum(replicas + maxSurge)且sum(replicas) - sum(maxUnavailable) >= quorum,防止滚动期间双主脑裂或跌破多数派。
22. 验证设计#
框架采用黑盒边界验证原则,禁止读取源码文本断言行为,按八层故障模型正交覆盖:
| 验证层 | 证明目标 | 拦截的典型缺陷 |
|---|---|---|
| 编解码、状态机与 Fuzz | 协议往返、有界准入与畸形输入零崩溃 | 截断帧、整数溢出、重放与陈旧状态覆盖 |
| Plugin 生命周期夹具 | 拓扑顺序、激活屏障、回滚与逆序排空 | 启动失败泄漏、钩子死锁与晚到任务越界 |
| Task 与多后端存储 | 租约续期、组提交、取消竞态与容量归还 | 旧租约覆盖终态、幂等键分裂与字节配额泄漏 |
| Procedure、Livecell 与 Fly | 8 步安全流水线、多租户隔离、表单去重与跨节点重挂 | 主键枚举、跨租户越权、重复提交与 CSP 违规 |
| 多进程故障与可靠性 | SIGSTOP、SIGKILL、慢盘、写满与网络分区下的自愈 | 双重入账、死锁挂起、僵尸连接与孤儿实体 |
| 外部打包消费者 | .crate 归档在仓库外独立编译运行 | 遗漏依赖导出、误用工作区私有路径 |
| Release 性能与指令计数 | 吞吐、分位延迟、每请求指令数与 2 倍过载恢复 | 热路径多余装箱分配、锁竞争与内存缓慢爬升 |
| 部署静态与 kind 运行时 | 镜像、代理、Kustomize 与真实控制器端到端互通 | 清单渲染漂移、网络策略误拦与滚动断流 |
各层测试归属见 仓库布局第 10 节,本地门禁见 贡献指南,容量上限见 容量与限制,性能阈值见 性能与容量验收,故障注入判据见 可靠性场景。