2. 应用依赖和入口
kxed 是提供默认组装与统一重导出的门面 crate;应用既可以只依赖 kxed,也可以直接依赖 kxed-core、kxed-runtime、kxed-livecell 与 kxed-plugins 自由组合:
[dependencies]
kxed = { path = "../../crates/kxed" }编写第三方插件通常只需依赖契约稳定的 kxed-core;业务工程也可混用默认门面与独立插件包,两者导出的是完全相同的底层 Rust 类型,无包装层或双份状态:
[dependencies]
kxed = { path = "../../crates/kxed" }
kxed-core = { path = "../../crates/core" }
kxed-plugins = { path = "../../crates/plugins", features = ["cache"] }SemVer 兼容性承诺仅覆盖逐名列出的公开 API,以下两类不作兼容承诺:
- 通配符重导出(glob re-export):
kxed::plugin(转出kxed_core::plugin::*、RouteInfo、RouteKind、StatSections、ManagementRoutes)、kxed::testing(转出kxed_core::testing::*)与kxed::tokio(转出::tokio::*),其变动跟随上游源 crate。 #[doc(hidden)]内部桥接项:如kxed::__private,仅供过程宏生成代码调用,业务代码严禁直接引用。
服务进程的入口统一使用 #[kxed::main]:
use kxed::prelude::*;
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.routes(|router| {
router.route("/", get(|| async { "hello\n" }));
})
.run()
.await
}#[kxed::main] 自建多线程 Tokio 运行时执行 async fn main,并在 run() 返回后设置 2 秒阻塞线程池收尾上限,防止卡死的 spawn_blocking 拖住进程退出(见第 13 节)。不启动 App 的独立小工具或单测可写 #[kxed::tokio::main] 或 #[kxed::tokio::test](自动补齐 crate = "kxed::tokio",免显式依赖 tokio)。kxed::Result<T> 专供入口函数使用,不放入 prelude 以免遮蔽标准库 Result<T, E>。
命令行分发与输出#
#[kxed::main] 固定要求签名为 async fn main() -> kxed::Result<()> 并捕获进程命令行参数,交由 run() 或 supervise() 分发:
- 服务模式与子命令模式分流:无参数、仅传全局选项或首参为
serve时启动常驻服务;否则按 clap 命令树(内建命令加本应用可见的#[derive(Command)])执行单次运维命令后退出(supervise()在命令成功时返回None,失败返回kxed::app::Exit)。 - 未标
#[kxed::main]时的保护:测试中未标该宏直接调run()时不走命令分发;若进程参数恰好命中已注册命令名,框架拒绝误起服务,在 stderr 提示补上#[kxed::main]并以 64 退出。测试代码内调命令请用App::call(argv)。 - 全局选项:支持
--json(结果输出单份 JSON,报错向 stderr 写{"error":{"code","message","exit"}})、--color <auto|always|never>、--env <name>、-v/-vv(提日志级别至 info / debug,对serve同样生效且优先于RUST_LOG)、-h与-V。将--json或显式--color传给serve会以 64 退出。
命令输出流与终端安全转义规则如下:
- 标准流职责分离:stdout 仅输出结构化结果,日志与报错一律写 stderr(命令进程默认日志级别为
warn)。 - 文本表格与 JSON 映射:文本表格无边框、列间距两空格;
--json下表格输出为对象数组(时间戳列统一命名为*_ms),分页结果固定为{items, next},单结果命令同样输出键值对象(如task cancel输出{id, cancelled, status}、--foreign-format输出{cancelled}、--all输出{cancelled, more};cron run输出{schedule, task_id};task dead purge输出{purged, more})。 - 终端转义注入防护:文本模式下所有控制字符与 Unicode 双向控制符一律替换为
U+FFFD(表格单元格与Output::Value连换行和制表符也一并替换),防止恶意存储内容向运维终端注入 ANSI 序列或伪造表格行。
破坏性命令(task cancel、task dead purge、notify dead purge、down、migrate down、migrate reset、migrate refresh、migrate fresh、db seed、db rekey、feature reset、search outbox purge、auth session revoke、auth user password、auth user disable、auth user delete、auth totp reset、fly user password、fly user disable、fly user delete、fly member remove、fly totp import、fly totp reset、rollups refresh、rollups crash reset)受二次确认保护(括号清单由 docs-check 逐项核对,完整用法见 运维命令教程):
- 交互式终端确认:打印环境名与完整命令(实现
Command::target的命令还会回显解析后的具体实体,如(user 2 "alice")),清空预输入缓冲后不回显等待键入y,答否打印Cancelled.并以 1 退出。 - 非交互管道与密钥读取:非终端环境必须显式传
--force,否则以 64 退出;改密命令在终端先确认再无回显读新密码(管道下带--force从 stdin 读首行),fly totp import同样从 stdin 读密钥。
批量分页、中途打断与缺省登记诊断规则如下:
- 统一分页约定(
kxed::command):--limit默认 64、上限 256;--all单轮上限 10000 行;存在下一页时才返回next供--after续传;首页为空输出No <things>.,翻页为空输出No more <things>.。 - 死信重放与中途打断
Output::interrupted:task dead retry固定输出old_id、new_id、error三列,存在重投失败行时以 1 退出(Output::failed)。批量重放或清理做到一半遇存储故障时,先向 stdout 刷出已完成部分,再向 stderr 写错误并按故障类别给退出码(如 503 对应 69)。Output、Cell、CommandTier、ArgKind、RouteKind均为#[non_exhaustive]。 - 未注册组件与参数名诊断:命令依赖的组件未注册时返回 422 并以 1 退出(
migration_not_registered、seeder_not_registered、seeder_not_found、search_sync_not_registered、auth_guards_not_registered、auth_store_not_registered、auth_accounts_not_registered、session_store_not_registered、fly_accounts_not_registered、database_connection_missing);--name或--guard传了不存在的名字时以 64 退出并列出合法候选。 - 跨节点统计
stat --remote:--json输出{nodes: [{node, stat, error}], total},total汇总各可达节点的在途请求、连接、本地在线数、Resident 实例与邮箱深度、Task 队列深度,并对版本号、集群在线数与存活节点数去重成数组(数组长度大于 1 即代表节点间视图未收敛);文本模式逐节点一行并附TOTAL汇总行。
命令的两档与退出码#
所有子命令按运行开销分为两档:
- 离线档(不连外部服务):只读编译期声明表与本地配置文件,不启动 Plugin、不绑端口,涵盖
about、ai describe、ai create、routes、config check、config show、credentials show、credentials update、event list、resident list、help、stat --remote以及写配置单元的setup/service。 - 启动档(复用插件依赖图):按第 2.1 节裁剪掉公开监听与后台 worker 后拉起全部 Plugin,执行命令体后逆序停机。收到 SIGINT/SIGTERM 时回滚或停机并以 130 退出,卡住时第二次信号以 1 强退;命令体成功但停机收尾报错时先输出 stdout 结果再以 1 退出。
命令按所属 Plugin 自动裁剪可见性:标有 #[command(owners = [P])] 的命令仅在 App 注册或声明了 P 时出现在帮助中(手工调用未注册插件的命令会附 note: "migrate up" belongs to SeaOrmPlugin, which this app does not register);命令路径重名冲突时以 70 退出并在 config check 报错。
| 退出码 | 触发条件与分类含义 |
|---|---|
0 | 执行成功(含 --help 与 --version) |
1 | 常规业务 AppErr;Output::failed 部分失败;交互确认答否;命令完成但停机收尾失败(stderr 以 command "<name>" completed 开头);停机期间收到第二次中断信号 |
64 | 未知子命令(附相近拼写建议)、usage_error、参数越界或名称不存在、缺少必填互斥参数、非终端执行破坏性命令漏传 --force |
69 | 存储或远程节点不可用:503 或 NotExecuted 类错误、stat --remote 存在失联节点、命令进程缺少共享 Task 存储(code task_shared_storage_required) |
70 | 命令路径注册冲突,或命令体发生 panic |
78 | 配置加载或预检失败:config check 为 FAIL、命令体抛出 ConfigError,以及启动阶段的插件配置、依赖图、公网暴露或进程内存储分裂拦截 |
130 | 启动期或执行期收到 SIGINT / SIGTERM,已回滚或停机(启动期中断不执行命令体) |
--json 模式下错误对象的 code 优先取 AppErr 机器码,框架级错误分别映射为 usage、config、command_conflict、panic、interrupted、cancelled、unavailable 或 error。
命令钩子与自省命令补充细节:
- 破坏性命令生命周期:严格按「解析参数 -> 非终端无
--force直接退 64 -> 启动插件 ->check(&self, ctx)-> 交互端target(&mut self, ctx)并提示确认 ->run」顺序推进,target将查到的唯一标识写回自身字段防止并发改名误删。 routes与about输出:routes --json返回{items, unlisted_plugins, unexpanded_mounts};about的task_storage显示实际后端协议、custom或not opened,并同步输出fabric_topology、fabric_discovery_mode与fabric_membership_backend。
公开名字与 prelude#
每个公开名字只有一条规范路径,另外最多出现在 prelude 里。根路径 kxed:: 只有下面这些名字:
| 类别 | 名字 |
|---|---|
| 类型 | App、AppCtx、AppErr、Result、CallFailure(trait 与 derive 同名) |
| 宏 | main、dispatch、task、event、on、resident、handles、query、mutation、subscription、command_group、username_or_id_command |
| 依赖 crate | axum、bytes、garde、metrics、serde、serde_json、tower_http、tracing |
其余名字按主题放在模块里:
| 模块 | 内容 |
|---|---|
kxed::app | Running、Supervised、PluginSet、AddrFile、AppCtxAccess、命令失败的 Exit |
kxed::command | Cell、Command(trait 与 derive)、CommandArg、CommandProcess、IntoRow、Output、Record、Table、usage_error、USAGE_CODE,分页列表命令的 PAGE_LIMIT、MAX_PAGE_LIMIT、MAX_RUN_ROWS、assert_page_limits、page_of、empty_page,读密码与密钥的 prompt_password、prompt_secret(终端上不回显,管道下读 stdin 第一行);登记组说明的宏 kxed::command_group! 与声明「用户名或 --id」参数组的 kxed::username_or_id_command! 在根路径 |
kxed::config | ConfigLoader、ConfigRepository、ConfigSection(trait 与 derive)、ConfigError、ConfigSources、EnvironmentOrigin、Secret、SecretString、ExposeSecret、config_schema_error、预检报告 ConfigReport、DeclaredName、NameKind |
kxed::http | Router、RouteGroup、MethodRoute、IntoMethodRoute、资源路由的动作表 ResourceRoutes 与 get、post、put、patch、delete、head、options、any、on、MethodFilter、StatusCode、RequestContext、HttpDrainSignal,多站点策略(SitePolicy、SiteSessionPolicy、SiteSessionCookieOverride、SiteSameSite、SiteSecurityPolicy、SiteCsrfPolicy、SiteLocalePolicy),页面元信息(PageHead、HeadAlternate、OpenGraph、TwitterCard、serialize_json_ld、escape_json_ld_raw),按来源计数的聚合函数 source_prefix,浏览器导航判定 accepts_html 与站内回跳地址校验 local_return_path(上限 MAX_RETURN_PATH_BYTES),列表响应 Collection、PageMeta、PageLinks、Cursor,带弱 ETag 的 JSON 响应 Etagged,只出现在类型里的作用域标记 Grouped 与 TopLevel,子模块 sitemap、sse 与 extract(Json、Path、Query、Form、PageQuery、CursorQuery、ClientIp、RequestScheme、PeerAddr、RawRequestUri、HostCaptures、IdempotencyKeyHeader、Accepts,feature 下的 Multipart、MultipartError、FileRule、FormPart、FilePart、Valid、ValidationRejection、FieldViolation、validation_error) |
kxed::net | Ws、WsExt、WsFrame、WsRoutes、ConnectionSink、Socket、Msg、Topic、Conn、EventCx、FromConn、Route、ChannelParams、CloseReason、ConnectionId、Tcp、TcpService、Udp、UdpService、Uid,子模块 codec(tokio-util 的 Decoder、Encoder、LengthDelimitedCodec、LinesCodec、BytesCodec、AnyDelimiterCodec) |
kxed::identity | Identity、IdentitySet、Guard、GuardName、Authenticated,写进 Task 与 Resident payload 的发起人身份 TaskIdentity(identity.for_task() 返回),错误 IdentityError、IdentitySetError、GuardNameError |
kxed::error | FailureClass、CallRetry、Retried、Reject、call_failure_error_of、AfterSideEffect、SideEffectFailure |
kxed::dispatch | DispatchError |
kxed::fabric | 可插拔节点发现与成员面扩展点:PeerDiscovery、StaticPeerDiscovery、SeedDiscovery、MulticastDiscovery、StorageDiscovery、StorageDiscoveryClient、DiscoveryCtx、DiscoveryCancel、PeerSink、FabricDiscoveryMode、MembershipBackend、MembershipTermination、ChitchatMembership、StaticMembership、StaticPeer、FabricMembershipBackend、LivePeer、LivePeerSnapshot、GossipMetricsSnapshot、NodeId、ProcessCapabilities、TaskAdmissionGates |
kxed::presence | AppCtxPush、AppCtxPresence、Broadcast、PushError、BroadcastError、TopicMembers、TopicMembersError,服务端订阅 topic 的 TopicSubscription(ctx.subscribe_topic(..) 的返回值)、按 Event 名过滤并解码的 TopicEvents 与其消息 TopicMessage,丢帧时的码 TOPIC_LAGGED,成员跟踪的 TopicPresence(ctx.topic_presence(..) 的返回值)与其成员 PresenceMember |
kxed::event | AppCtxEvent、Event、Emit、EmitError;capability 层的 EventService 不经 facade 导出,自定义 assembly 直接依赖 kxed-runtime |
kxed::resident | 声明与上下文(Resident、ResidentCtx、Handles、DeclaredResident、DeactivateReason、OwnershipToken)、调用(AppCtxResidents、ResidentRef、ResidentId、ResidentCallFuture、ResidentNotifyFuture)、服务与观测(ResidentService、PlacementWatch、PlacementMetricsSnapshot、ResidentMetricsSnapshot)、错误(ResidentCallError、ResidentError、ResidentIdError) |
kxed::procedure | 契约与登记(Procedure、ProcedureDescriptor、ProcedureKind、ProcedureRegistration、ProcedureReturn、OutputShape、Access、Position、Delivery、HttpMethod、HttpRoute、LayerUse、LayerKey、ProcedureLayer、ProcedureLayers、ProcedureBind、ErrorCode、error_code、error_codes、procedures、public_list、public_rpc_paths、matches_public_http、matches_public_rpc_or_asset、find、describe_metrics)、调用与会话(AppCtxProcedures、SystemCall、Session、CallRequest、CallMeta、Caller、Credential、Origin、Capabilities、Connection、IdentityResolution、BearerResolution、RecentAuthVerifier、CONFIRMATION_HEADER)、输入输出、错误码与上限(Id、WithId、ListInput、OptionsInput、FilterValue、SortDirection、SortKey、Streamed、StreamElement、WireOutput、WireItem、Frame、TaskRef、UploadRef、UploadService、UploadTicket、STREAM_BUFFER、MAX_PER_PAGE、MAX_SEARCH_CHARS、APP_ERROR、AUTHENTICATION_EXPIRED、AUTHENTICATION_UNAVAILABLE、AUTHZ_RECHECK_EVERY、AUTH_PASSWORD_CONFIRMATION_REQUIRED、FORBIDDEN、INVALID_JSON、NOT_FOUND、RATE_LIMITED、TRANSPORT_UNSUPPORTED、UNAUTHORIZED、UPLOAD_INVALID、UPLOAD_VERIFIER_NOT_REGISTERED、VALIDATION_FAILED)、订阅与可靠推送(AppCtxPublish、EventName、EventRegistration、EventStream、SnapshotRead、TopicBus、SharedTopicBus、TopicEvent、ReliablePush、SharedReliablePush、Replay、REPLAY_LIMIT、TOPIC_LAGGED)、内置传输与放置(ProcedurePlugin、ProcedureTransportEndpoint、RpcConfig、RpcEndpoint、RpcState、ProcedurePlacement、RemoteProcedures、document、placement_conflict、CLIENT_SCRIPT、RPC_CLIENT_PATH、RPC_PREFIX、RPC_WS_PATH,以及 procedure-client feature 下的 Placement、RpcRouter) |
kxed::task | task 位置的 procedure 的内置查询与取消(task_status、task_cancel、TaskRefInput、TaskView、TaskViewFailure)、上下文与声明(TaskCtx、MapCtx、ReduceCtx、NormalTask、MapTask、MapReduceTask、TaskSpec、TaskMode、TaskOrigin、ChildKey、ChildOutcomeOf、MapChildOutcome、MapReport)、中间件(TaskMiddleware、TaskNext、TaskFuture)、提交(AppCtxTasks、Submit、RetryPolicy、IdempotencyKey、TaskPriority、TaskAffinity、CancellationToken、AtTrigger、AfterTrigger、InstanceTrigger)、句柄与服务(TaskHandle、TaskId、IntoTaskId、TaskStatus、TaskOutcome、TaskResult、TaskFailure、TaskInfo、TaskBacklog、TaskService、CancelOutcome、PendingCancelReport、RetentionWarnings)、死信(DeadLetter、DeadLetterFailure、DeadLetterPage、DeadLetterQuery、DeadLetterCursor、DeadLetterReplay、DeadCensus)、队列控制、互斥、唯一键与限额(QueueState、Exclusive、ExclusivePolicy、Unique、UniquePolicy、UniqueConflict、TaskRate)、批次进度(BatchProgress)、Cron(CronSchedule、IntoCronSchedule、CronHandle、CronScheduleId、IntoCronScheduleId、CronScheduleInfo、CronSchedulePage、CronScheduleRow、CronMisfire、CronOverlap、CronOccurrence、CronOccurrenceId、CronOccurrenceCursor、CronCancelOutcome)、错误(TaskSubmitError、TaskOutputError、TaskLookupError、TaskControlError、TaskStatusError、TaskKeyError、TaskOptionsError、ResultReadError、MapEmitError、QueueControlError、TriggerError、ParseTaskIdError、ParseDeadLetterCursorError、CronScheduleError、CronControlError、CronLookupError、CronReadError、CronReconcileError、CronTriggerError、ParseCronScheduleIdError、ParseCronOccurrenceIdError),子模块 storage |
kxed::maintenance | 维护模式:Maintenance、MaintenanceError、MaintenanceSnapshot,读写经 ctx.tasks()? 的 maintenance() 与 set_maintenance(..),见 TASK 第 8 节 |
kxed::limits | 框架的上限、下限与缺省常量 |
kxed::grpc(feature) | GrpcRoutes、ctx、status |
kxed::crypto | Crypto、CryptoError、Signer、SignatureError、AppKey、AppConfig、AppCtxCrypto、Cookies、Cookie、SameSite、CookieLayer、require_signature、VerifiedWebhook、Webhook、WebhookScheme、WebhookSecretError、WebhookConfigError、WebhookSource、WebhooksConfig、WEBHOOK_TOLERANCE 等,见加密与签名 |
kxed::tenant | CurrentTenant、tenant_route、TenantId、TenantSource、TenantRoute、TenantRouteService 与错误码常量 TENANT_MISMATCH、TENANT_REQUIRED;开任一 seaorm-* feature 时是 SeaORM plugin 的 tenant 模块,另有 TenantScoped、insert_in、update_in、update_many_in、delete_in 与写入 builder 的返回类型 TenantInsert、TenantInsertMany、TenantUpdateMany,同名属性宏 #[kxed::tenant] 声明租户列 |
kxed::lock_version(任一 seaorm-* feature) | SeaORM plugin 的 lock_version 模块:LockVersion、update_checked、VERSION_CONFLICT,同名属性宏 #[kxed::lock_version] 声明版本列;乐观锁一律写这条根路径,kxed::plugins::seaorm::lock_version 是同一个模块 |
kxed::report | ErrorReporter、ErrorEvent、ErrorOrigin 与上报设置不合法时的 ReportingError;reporter 只经 App::report_errors 注册,见 错误上报合同 |
kxed::utils | 零运行时依赖的通用工具集(kxed-utils):codec、time、text、algo、retry、net、redact,按 utils-compression、utils-crypto、utils-crypto-rsa、utils-id、utils-algo-graph 与 utils-all feature 开启压缩、密码学、RSA、ID 与图算法 |
| 其他 | logging、plugin、plugins、access、audit、tokio,testing(feature) |
kxed::plugins::auth(feature) | Plugin 与配置(AuthPlugin、AuthConfig、AuthGuard、AuthGuardConfig、AuthGuards、GuardPathConfig、StatefulAuthConfig、PasswordConfig、JwtConfig、JwtKeyConfig、JwtKeyMaterial、JwtAlgorithm、IdentityClaimConfig、AnonymousPaths、AnonymousRule、AuthPolicy、LoginPolicy、AuthCapability、BuiltinAccountsCapability、LoginPageRegistration、AuthMetrics、AuthAudit、AuthKind、AuthOutcome、AuthStoreOrigin、UnavailableCause)、签发与会话(AppCtxAuth、AuthSessions、AuthPrincipal、AuthSessionInfo、AuthSessionValidator、IssuedToken、LoginOptions、RevokeScope、TokenScope、StoredAuthSession)、登录页(login_url、回跳地址校验 return_path;auth-session feature 下 AuthSessions 另有 take_intended)、通用三维防撞库限流(AuthRateLimiter、AuthRateQuotas、AUTH_SOURCE_QUOTA、AUTH_IDENTIFIER_SOURCE_QUOTA、AUTH_IDENTIFIER_QUOTA)、存储(AuthStore、SharedAuthStore、MemoryAuthStore,SQL feature 下的 SqlAuthStore 与 sea_orm)、账户表(SQL feature 下的 SeaOrmAccounts、TotpRekey、users、user_recovery_codes、MIN_PASSWORD_CHARS、LOGIN_QUOTA、ACCOUNT_LOGIN_QUOTA、SOURCE_QUOTA,经 ctx.accounts()? 取;账户 JSON 路由 AccountApiPlugin、ACCOUNT_API_CONFIRMATION_AGE)、密码(PasswordVerifier、PasswordCheck、PasswordVerifyError、argon2)、近期重认证(RecentAuth、require_recent_auth、RequireRecentAuth、RequireRecentAuthService、RECENT_AUTH_HEADER、RECENT_AUTH_SESSION_KEY、RECENT_AUTH_LIFETIME、RECENT_AUTH_QUOTA、PASSWORD_CONFIRMATION_QUOTA)、TOTP 管理(TotpSetup、TotpAccounts、TotpEnrollment、TOTP_SETUP_LIFETIME、RECOVERY_CODE_COUNT)、两步登录(LoginStep、TwoFactorLogin、PendingLogin、TwoFactorAccounts、StoredTotp、TotpSecret、TotpError、LOGIN_CHALLENGE_LIFETIME、TWO_FACTOR_QUOTA、TOTP_STEP_SECONDS、recovery_codes、hash_recovery_code、matches_recovery_code)、OAuth2/OIDC 与第三方绑定(auth-oauth feature 下的 OAuthClient、OAuthClientConfig、OAuthProviderConfig、JwksCache、OAuthAuthorizationOptions、OAuthAuthorizationStart、OAuthPendingState、OAuthTokenResponse、OAuthUserInfo、OAuthIdentityProfile、OidcClaims、OidcDiscoveryDocument、OAuthIdentityLink、OAuthIdentityStore、MemoryOAuthIdentityStore、SqlOAuthIdentityStore、OAuthEmailMatch、OAuthError、TelegramLoginPayload、pkce_s256_challenge、verify_telegram_login、can_auto_link_by_email、resolve_email_match、oauth_migrations、OAUTH_IDENTITIES_TABLE、DEFAULT_STATE_LIFETIME、DEFAULT_JWKS_TTL、DEFAULT_JWKS_MIN_REFRESH_INTERVAL、DEFAULT_DISCOVERY_TTL、DEFAULT_CLOCK_SKEW、TELEGRAM_MAX_FUTURE_SKEW)、认证事件(AuthObserver、AuthEvent)、AuthError、jsonwebtoken、install_crypto_provider、RING_PROVIDER |
kxed::plugins::authz(feature) | AuthorizationPlugin、AuthorizationConfig、AuthorizationCapability、AppCtxAuthorization、AuthorizationService、AuthorizationOutcome、AuthorizationMetrics、AuthorizationError,策略(PolicyRule、PolicyAction、PolicyEffect、PolicyPrincipal、GroupingRule、ObjectMatch) |
kxed::plugins::batch_ingest(feature batch-ingest) | 插件与服务(BatchIngestPlugin、BatchIngestConfig、BatchIngestBackendKind、BatchIngestCapability、AppCtxBatchIngest、BatchIngestService、BatchIngester、BatchIngestMetricsSnapshot、BatchIngestError、batch_ingest_error_of、validate_pipeline_name)、管道与死信(BatchPipelineSpec、BatchPipelineOptions、BackpressurePolicy、BatchSink、BatchFlushError、BatchRecordCodec、JsonRecordCodec、BatchDeadLetterSink、DeadLetterKind、DeadLetterPolicy、DeadLetterReason)、默认值与指标常量(DEFAULT_DRAIN_TIMEOUT、DEFAULT_FLUSH_INTERVAL、DEFAULT_INITIAL_BACKOFF、DEFAULT_MAX_BACKOFF、DEFAULT_MAX_BATCH_BYTES、DEFAULT_MAX_BATCH_ITEMS、DEFAULT_MAX_BUFFERED_BYTES、DEFAULT_MAX_BUFFERED_ITEMS、DEFAULT_MAX_RETRIES、DEFAULT_REDIS_CLAIM_IDLE_TIMEOUT、DEFAULT_REDIS_CONSUMER_GROUP、DEFAULT_REDIS_KEY_PREFIX、DEFAULT_REDIS_POLL_INTERVAL、DEFAULT_REDIS_STREAM_MAX_LEN、DEFAULT_WAIT_TIMEOUT、METRIC_BUFFERED_BYTES、METRIC_BUFFERED_ITEMS、METRIC_DEAD_LETTER_TOTAL、METRIC_ENQUEUE_TOTAL、METRIC_FLUSH_DURATION_SECONDS、METRIC_FLUSH_TOTAL),batch-ingest-redis feature 下另有 FredStreamTransport、RedisAutoClaimReply、RedisBatchAddOutcome、RedisStreamEntry、RedisStreamEnvelope、RedisStreamPipeline、RedisStreamTransport、is_busygroup_error、parse_xautoclaim_value、parse_xreadgroup_value、stream_key_for_pipeline |
kxed::plugins::cache(feature) | CachePlugin、CacheConfig、CacheRedisConfig、CacheBackendKind、CacheCapability、AppCtxCache、Cache、CacheKey、CacheValue、CacheScope、CacheLocality、CacheLock、CacheLockRenewal、CacheUsage、CacheError、SortedSet、TaggedCache、MAX_KEY_BYTES、MAX_TTL、TAG_GENERATION_TTL、WEBHOOK_PROCESSING_TTL,另有 cache-http feature 下的 ResponseCache、ResponseCacheConfig、ResponseCacheLayer、ResponseCacheQueryMode、ResponseCacheService、response_cache、DEFAULT_RESPONSE_CACHE_TTL、DEFAULT_MAX_BODY_BYTES |
kxed::plugins::consensus(feature) | 插件与配置(ConsensusPlugin、ConsensusConfig、ConsensusMode、PeerConfig、ConsensusCapability、ConsensusHandle、ClusterStatus、NodeId、NodeRole、ConsensusError)、引擎与状态机(ConsensusEngine、RaftEngine、StandaloneEngine、StateMachine、KvStateMachine、KvCommand、KvQuery、KvQueryResponse、KvResponse、ClientRequestId)、日志与快照(LogStore、FileWalLogStore、LogEntry、EntryPayload、CommittedEntry、LogId、LogIndex、Term、VoteState、Snapshot、SnapshotMeta)、传输(ConsensusTransport、TcpConsensusTransport、ConsensusRpc、ConsensusRpcResponse、RpcHandler)与子模块 testing(含 FaultNetwork、InMemoryTransport、MemoryLogStore) |
kxed::plugins::device(feature) | 插件与解析(DevicePlugin、DeviceConfig、DeviceUpdateConfig、DeviceCapability、AppCtxDevice、DeviceDetector、ClientHints、DeviceInfo、DeviceKind、BrandVersion、DeviceError)、规则快照(RuleSnapshot、RuleReloadSummary、DeviceRuleSpec、OsRuleSpec、BrowserRuleSpec、BrandGroupSpec、BrandModelSpec、AppRuleSpec、BotRuleSpec)、上限常量(DEFAULT_CACHE_CAPACITY、DEFAULT_MAX_RULES_BYTES、DEFAULT_MAX_UA_BYTES、DEFAULT_UPDATE_INTERVAL、DEFAULT_UPDATE_TIMEOUT、MAX_CACHE_CAPACITY、MAX_MAX_UA_BYTES、MAX_REGEX_PATTERN_BYTES、MAX_TOTAL_RULES、MIN_MAX_RULES_BYTES、MIN_MAX_UA_BYTES) |
kxed::plugins::device_lease(feature) | DeviceLeasePlugin、DeviceLeaseCapability、DeviceLease、Lease、DeviceLeaseError、AppCtxDeviceLease |
kxed::plugins::draw(feature) | 函数 shuffle、shuffle_with、pick_without_replacement、pick_without_replacement_with、draw_bytes_with,熵源 EntropySource、OsEntropy,见证 Seed、Commitment、Reveal,DrawError |
kxed::plugins::features(feature) | FeaturesPlugin、FeaturesConfig、FeatureRollout、AppCtxFeatures、Features、FeaturesError,路由 layer(require_feature、RequireFeature、RequireFeatureService),覆盖表名 FEATURES_TABLE,上限 MAX_FEATURE_NAME_BYTES、MAX_SCOPE_BYTES、MAX_OVERRIDES |
kxed::plugins::http_client(feature) | HttpClientPlugin、HttpClientConfig、HttpClientCapability、AppCtxHttp、HttpClient、HttpRequest、HttpResponse、Method、HttpClientError、MAX_RESPONSE_BYTES,另有 testing feature 下的 HttpFake、FakeResponse、RecordedRequest |
kxed::plugins::i18n(feature) | I18nPlugin、I18nConfig、I18nCapability、AppCtxI18n、I18n、DateLength、TextDirection、Catalog、CatalogBuilder、CatalogLookup、OverlayCatalog、Locale、LocaleInputs、LocaleCookie、RequestLanguage、LanguageSetup、Language、PageLanguage、MessageArg、I18nError、check_setup、load_dir、negotiate、cookie_locale、locale_set_cookie、validate_message_ftl、render_metrics、LOCALE_COOKIE、LOCALE_COOKIE_MAX_AGE、MAX_ACCEPT_LANGUAGE_BYTES、MAX_LOCALE_BYTES,另有 i18n-db feature 下的 DynamicTranslations、I18nDbConfig、TranslationEntry、TranslationUpdated、translations_migrations、TRANSLATIONS_TABLE |
kxed::plugins::ip(feature) | IpPlugin、IpConfig、IpUpdateConfig、AppCtxIp、IpDatabase、IpInfo(也是提取器)、IpError,路由 layer(require_country、RequireCountry、RequireCountryService) |
kxed::plugins::ledger(feature) | 插件与服务(LedgerPlugin、LedgerConfig、LedgerBackendKind、LedgerCapability、AppCtxLedger、LedgerService、LedgerRuntimeConfig、LedgerError、GroupCommitter、LedgerPlacement、LedgerOwnership、LocalLedgerPlacement、InstalledLedgerPlacement)、内核与局内账本(LedgerEngine、LedgerEngineConfig、LedgerPolicy、AllowAllPolicy、Account、AccountFlags、Transfer、TransferFlags、TransferStatus、CreateAccountResult、CreateTransferResult、TrialBalance、CommittedBatch、CommittedTransfer、PendingState、StoredTransfer、TombstoneRecord、RefundDelta、ResolvedPending、SessionLedger、SeatBalance、SessionCheckpoint、SettlementEntry、SessionError)、存储契约(LedgerStore、StoreFuture、StoreError、MemoryLedgerStore、LocalWalStore、GroupState、GroupSnapshot、CommitReceipt、ColdTransferLookup、LedgerCommitEvent),另有 ledger-sql feature 下的 SqlLedgerStore |
kxed::plugins::livecell(feature) | 运行时与 Plugin(LivecellPlugin、LivecellConfig、LivecellRuntime、LivecellLimits、LivecellMetricsSnapshot、LivecellAppCtx、AppCtxLivecell、Livecell、RecoveryConfig、ForwardConfig、LivecellSwitchMode、LivecellCookieConfig、runtime_metrics、idle_metrics、PROTOCOL_VERSION、not_found_page)、组件(LiveComponent、ComponentBox、ComponentCall、ComponentEvent、ComponentFuture、ComponentOperation、ComponentUpdate、MountCtx、MountReason、MountError、MountedPage、EventCtx、EventAction、QueryCtx、RenderCtx、RenderOperation、Effect、EffectDelivery、DomEvent、FieldErrors、StreamAt、StreamItem、StreamSpec、LiveStream、Dispatch、RemountReason、Remounted、LiveTest、ProcedureUsage、LiveProcedures、Procedures、OwnedProcedures、ProcedureInfo、ProcedureKind、ProcedureRunner、current_procedures,另有 testing feature 下的 LiveBrowser)、页面与 HTML(Document、DocumentError、Layout、PageChrome、HeadTag、page_head_tags、Html、Text、Slot、elements、html、escape_attribute、escape_text、url、lint、ConnectedPage、ConnectOutcome、PageAddressing、LocalAddressing、AddressError、PageCallError、ClientKind、ClientMessage、DecodedMessage、ServerMessage、NoticeCopy)、资产(Assets、AssetConfig、AssetSource、AssetDescriptor、AssetDescriptorSource、AssetDirError、AssetOverrideReport、AssetPublishReport、check_asset_directory、content_hash、Script、ScriptOrder、Style、script、style、ALPINE_VERSION、ASSET_VERSION、REQUIRED_CSP、RUNTIME_JS、STYLE_CSS、THEME_ATTRIBUTE、THEME_STORAGE_KEY)、访问者与多语言(Viewer、ViewerProfile、ViewerTenant、AuthorizeReason、NavigationAuthorizeRequest、NavigationAuthorizer、NavigationDecision、Catalog、CatalogBuilder、Locale、LocaleInputs、MessageArg、PageLanguage、Language、RequestLanguage、RequestViewer、I18nError、negotiate、LOCALE_COOKIE)、topic 与多实例(TopicMessage、LivecellForward、LivecellInbound、InboxFuture、mesh、store、MAX_TOPIC_MESSAGE_BYTES)、上传(UploadHandler、UploadRequest、UploadReservation、UploadCredentials、UploadLocality、UploadTokenKey、UploadedFile,另有 livecell-object-store feature 下的 ObjectStoreUploads、ObjectStoreUploadConfig)、通知(NotificationRecord、NotificationRenderer、LiveNotice)、错误(LiveError、LiveErrorKind、LiveResult、LiveResultExt、RuntimeError、ProtocolError、CommandError、into_live_error、runtime_error_of)、字段动作常量(FIELD_ADD、FIELD_APPEND、FIELD_DATE、FIELD_DUPLICATE、FIELD_LOAD_MORE、FIELD_NEXT、FIELD_PREV、FIELD_REMOVE、FIELD_REORDER、FIELD_SELECT、FIELD_TOGGLE);子模块 sdui(livecell-sdui feature)与 fly(livecell-fly feature,整体再导出 kxed-livecell,另有与 ResourceError 同处导入的 into_resource_error),livecell-fly 下另有 FlyAccountPlugin、FlyAccountConfig、FlyAccounts、FlyActor、FlyAdmin、FlyRecordAudit、FlyTwoFactor、FlyAccountResourceError、USERNAME_TAKEN_CODE,livecell-fly-seaorm 下另有 FlyDatabaseAccountPlugin、FlyPanels、TotpVault |
kxed::plugins::mail(feature) | MailPlugin、MailConfig、MailTlsMode、MailCapability、AppCtxMail、Mailer、MailAddress、MailMessage、MailAttachment、MailAttachmentData、MailReceipt、MailError、MailFake、RecordedMail、RecordedAttachment、DEFAULT_MAX_ATTACHMENT_BYTES、DEFAULT_MAX_RECIPIENTS、MAX_ATTACHMENT_BYTES_LIMIT、MAX_RECIPIENTS_LIMIT |
kxed::plugins::notify(feature) | NotifyPlugin、NotifyConfig、NotifyCapability、AppCtxNotify、Notify、Notification、DatabaseNotification、Notifications、Recipient、RecipientUpdate、Channels、ChannelStatus、NotifyChannel、ChannelDelivery、ChannelOutcome、HttpChannel(另开 http-client)、SmtpChannel、SmtpChannelAttachment、SmtpChannelMessage(另开 mail)、Sent、NotifyStore、NotifyRelay、RelayReport、DeadLetter、DeadLetterReplay、NotifyError,表名与上限(NOTIFICATIONS_TABLE、OUTBOX_TABLE、DEAD_LETTER_TABLE、MAX_BATCH_SIZE、MAX_BODY_BYTES、MAX_COUNTED_PENDING_ROWS、MAX_NAME_BYTES、MAX_PURGE_IDS、MAX_RECIPIENT_ID_BYTES、MAX_RECIPIENT_KIND_BYTES、MAX_REPLAY_ROWS),另有 notify-webpush feature 下的 WebPushChannel、WebPushConfig、WebPushSubscription、WebPushMessage、WebPushUrgency、WebPushError、encrypt_web_push_payload、sign_vapid_jwt、DEFAULT_VAPID_EXPIRATION、DEFAULT_WEBPUSH_TTL、MAX_VAPID_EXPIRATION、MAX_WEBPUSH_PAYLOAD_BYTES,另有 notify-fcm feature 下的 FcmChannel、FcmConfig、FcmMessage、FcmError、DEFAULT_FCM_ENDPOINT_BASE、DEFAULT_FCM_TOKEN_URI |
kxed::plugins::object_store(feature) | ObjectStorePlugin、S3Config、本机目录后端的 LocalStoreConfig、两种后端共用的 ObjectStoreConfig、ObjectStoreMirrorPolicy、ObjectStoreCapability、AppCtxObjectStore、ObjectStoreClient、ObjectPath、ObjectPage、MAX_LIST_PAGE、ObjectReader、ObjectWriter、SignedUrlOptions、VariantSpec、ObjectStoreError、上游 crate object_store、FilePartStore、StoredFile,另有 object-store-tus feature 下的 TusConfig、TusService、TusHooks、TusCreateRequest、TusCompletedUpload、TusError、TusSession、TusSessionLock、TusSessionStore、CacheTusSessionStore、TusSweepReport、TUS_VERSION、MIN_PART_SIZE_BYTES、DEFAULT_PART_SIZE_BYTES、DEFAULT_MAX_PATCH_BYTES、DEFAULT_MAX_SIZE_BYTES、DEFAULT_SESSION_LIFETIME、DEFAULT_LOCK_LEASE、DEFAULT_LOCK_WAIT、DEFAULT_STAGING_PREFIX |
kxed::plugins::inspect(feature) | InspectPlugin、InspectConfig、InspectedRequests、InspectedRequest、InspectedStatement、InspectedLog、layer、MAX_ENTRIES |
kxed::plugins::openapi(feature) | OpenApiPlugin、OpenApiConfig、Routes、宏 routes!、上游 crate utoipa |
kxed::plugins::otp(feature) | OtpPlugin、OtpCapability、OtpConfig、OtpService、AppCtxOtp、OtpMetrics、OtpStore、CacheOtpStore、OtpFormat、OtpIssueOptions、IssuedOtp、OtpVerification、OtpStatus、OtpRecord、OtpStoreFuture、OtpStoreDecision、OtpStoreMutation、OtpError、MIN_CODE_LEN、MAX_CODE_LEN、MIN_TOKEN_BYTES、MAX_TOKEN_BYTES、MAX_PURPOSE_BYTES、MAX_TARGET_BYTES、MAX_METADATA_BYTES、ALPHANUMERIC_UPPER_ALPHABET |
kxed::plugins::reliable_push(feature) | ReliablePushPlugin、ReliablePushConfig |
kxed::plugins::redis(feature) | RedisPlugin、RedisConfig、RedisCapability、RedisPool、AppCtxRedis、RedisError、redis_error_of、上游 crate fred,另有 redis-replicas feature 下的 RedisReplicaConfig |
kxed::plugins::rollups(feature) | 插件与核心(RollupsPlugin、RollupsConfig、RollupsGuardMode、RollupsCapability、AppCtxRollups、Rollups、RollupEngine、RollupError、UnmarkedSourceWriteError、ReportCutoff)、契约与时钟(RollupKey、RollupSlice、RollupMeasures、RollupRow、RollupSpec、RollupSource、RollupSourceSpec、WatchedTableRule、RollupClock、SharedRollupClock、SystemRollupClock、UtcDay、RollupDayValue)、存储与快照护栏(RollupStore、WindowRow、MarkRow、DoneDays、RollupWriteLock、WriteLockGuard、SnapshotBackend、SnapshotSession、SnapshotCtx、SnapshotUsage、SnapshotUsageCollector、NoopSnapshotUsageCollector、WriteGuard、GuardedConnection、GuardedTransaction)、报告与事实流(TickReport、WorkReport、RollupWorkKind、CheckReport、RollupsStatusSnapshot、RollupStatusEntry、FactFeed、SourceFacts、FactSourceSpec、FactPageOptions、FactPage、FactRecord、FactCountEntry、SinceCursor)、函数(add_duration、build_insert_statement、compute_cell_diff、cutoff_not_published_response、datetime_to_micros、elapsed_secs、floor_tick、format_sql_timestamp、into_fact_http_response、is_untracked、is_within_migration、load_existing_rows、micros_to_datetime、mysql_physical_clock_sql、next_tick_after、postgres_physical_clock_sql、refresh_rollup、refresh_rollup_day、refresh_rollup_slices、require_published_cutoff、sub_duration、tidb_as_of_sql、tidb_physical_clock_sql、tidb_session_snapshot_sql、transaction_options_for、untracked、upsert_typed_rows_within、validate_table_prefix、within_marked_tx、within_migration)与常量(APP_WINDOW_KEY、DEFAULT_FACT_PAGE_LIMIT、DEFAULT_MAX_RECOMPUTE_BYTES、DEFAULT_MAX_ROWS_PER_TX、DEFAULT_SLICES_PER_CALL、DEFAULT_SLICE_CHUNK_SIZE、DEFAULT_TABLE_PREFIX、FACT_RETRY_AFTER_SECS、MARKS_TABLE_SUFFIX、MAX_FACT_PAGE_LIMIT、MAX_TABLE_PREFIX_BYTES、METRIC_DRIFT_TOTAL、METRIC_LAG_SECONDS、METRIC_ROUND_DURATION_SECONDS、METRIC_WRITTEN_ROWS_TOTAL、WINDOWS_TABLE_SUFFIX) |
kxed::plugins::rpc_grpc(feature rpc-grpc) | GrpcProceduresPlugin |
kxed::plugins::rpc_java(feature rpc-java) | generate,命令 rpc java;不是生命周期 plugin,引用这个模块只为把命令编进 binary |
kxed::plugins::rpc_jsonrpc(feature rpc-jsonrpc) | JsonRpcPlugin、JsonRpcRequest、JsonRpcResponse、JsonRpcId、JsonRpcError、APP_ERROR_MAX、APP_ERROR_MIN、DEFAULT_MAX_BATCH_SIZE、DEFAULT_MAX_BODY_BYTES、DEFAULT_PATH、INTERNAL_ERROR、INVALID_PARAMS、INVALID_REQUEST、JSONRPC_VERSION、METHOD_NOT_FOUND、PARSE_ERROR,另开 http-client 时有 JsonRpcClient、JsonRpcClientError、JsonRpcBatchItem、JsonRpcBatchOutcome |
kxed::plugins::rpc_mcp(feature rpc-mcp) | McpPlugin、McpGovernanceConfig、ProcedureGovernance、ProcedureRisk、DEFAULT_MAX_EXECUTE_CALLS、DEFAULT_MAX_SEARCH_LIMIT、DEFAULT_SEARCH_LIMIT、EXECUTE_TOOLS_NAME、SEARCH_TOOLS_NAME |
kxed::plugins::rpc_php(feature rpc-php) | generate,命令 rpc php;不是生命周期 plugin,引用这个模块只为把命令编进 binary |
kxed::plugins::rpc_ts(feature rpc-ts) | RpcTarget、RpcInt64Mode、RpcTsOptions、generate、generate_with,命令 rpc ts;不是生命周期 plugin,引用这个模块只为把命令编进 binary |
kxed::plugins::search(feature) | Plugin 与句柄(SearchPlugin、SearchConfig、SearchCapability、AppCtxSearch、Search、ConfiguredSearchEngine、SearchLimits、SearchError)、检索(Searchable、SearchRequest、SearchHits、SearchPage、Scope、Filter、FilterValue、Comparison、Sort、SortOrder、Total、Hydrated、hydrate、scope_condition)、索引(IndexSchema、IndexWriter、IndexOperation、OperationOutcome、FieldType、ColumnMeta、ColumnRole、sync)、聚合(AnalyticsConfig、AnalyticsEngine、AnalyticsQuery、AnalyticsOrder、AnalyticsRows、Dimension、Metric、Having、Interval、RawQuery)、引擎(Engine、EngineCapabilities、SearchEngineKind、SearchEngine、DatabaseEngine、MemoryEngine,各引擎 feature 下的 ElasticsearchEngine、ElasticsearchOptions、OpenSearchEngine、OpenSearchOptions、ClusterAuth、ClusterConfig、Refresh、RefreshSetting、ClickHouseConfig、ClickHouseEngine、ClickHouseOptions、LakeConfig、LakeEngine、LakeTable、TextMatch、TextMatchSetting、DEFAULT_LAKE_QUERY_TIMEOUT、MAX_LAKE_QUERY_TIMEOUT、MeilisearchConfig、MeilisearchEngine、TypesenseConfig、TypesenseEngine)、上限(DEFAULT_ANALYTICS_ROWS、DEFAULT_LIMIT、DEFAULT_TEXT_SEARCH_CONFIG、MAX_ANALYTICS_ROWS、MAX_IN_VALUES、MAX_LIMIT、MAX_TEXT_BYTES、MAX_WINDOW) |
kxed::plugins::security(feature) | SecurityPlugin、SecurityConfig、SecurityCapability、SecurityMetrics、SecurityRejectReason、SecurityHeadersConfig、CorsConfig、CsrfConfig、HttpsRedirectConfig、TrustedProxyConfig、TrustedProxyPolicy,限流(RateLimitConfig、RouteRateLimitConfig、RateLimitBackendKind、AppCtxRateLimiter、RateLimiter、RateQuota、RateStatus、RateLimitError、RateQuotaError) |
kxed::plugins::session(feature) | Plugin 与配置(SessionPlugin、SessionConfig、SessionCookieConfig、SessionMemoryConfig、SessionAnonymousConfig、SameSiteConfig、CookieProtection、SessionBackend、SessionBackendKind、SessionCapability、SessionMetrics、SessionBackendOperation、AppCtxSession)、会话锁(session_block、SessionBlock、SessionBlockService)、extractor 与记录(Session、SessionError、FlashedInput、SessionExpiry、Expiry、SessionClass、SessionKey、ParseSessionKeyError、SessionRecords、LoadedRecord、StoredRecord)、存储(SessionStore、SessionReader、SessionStoreLocality、SessionStoreScope、MemorySessionStore,session-redis 下的 RedisSessionStore,seaorm-* 下的 SqlSessionStore)、认证与 CSRF(mark_authenticated、clear_authenticated、is_authenticated、cycle_id_keep_old、persist_until、csrf_token、verify_csrf、CsrfToken、CsrfError、RequireCsrfHeader、AUTHENTICATED_KEY、CSRF_HEADER、CSRF_SESSION_KEY、PERSIST_UNTIL_KEY)、上游 crate tower_sessions |
kxed::plugins::settings(feature) | SettingsPlugin、SettingsConfig、SettingsGroup(trait 与 derive)、AppCtxSettings、SettingsError,设置页字段 SettingsField、SettingsFieldKind,再开 livecell-fly 时的 Fly 设置页 SettingsPage,表名 SETTINGS_TABLE,上限 MAX_SETTINGS_BYTES |
kxed::plugins::spreadsheet(feature) | 插件与编解码(SpreadsheetPlugin、SpreadsheetConfig、SpreadsheetCapability、AppCtxSpreadsheet、SpreadsheetError、spreadsheet_error_of、TabularFormat、TabularSchema、TabularSheet、ColumnSpec、ColumnFormat、CellValue、TabularReader、TabularWriter、TabularReadOptions、TabularWriteOptions、CsvReader、CsvWriter、CsvOptions、TemplateOptions)、导入导出(ImportMode、ImportOptions、ImportReport、ImportRowError、ImportedRow、RawRow、MappedRow、RowMapper、FieldIssue、HeaderResolution、ReceiptColumns、BatchApplyOutcome、StreamingExport、ExportOptions、ExportSheet、CursorPage、ExportAuditEvent、TransferDispatchMode、AsyncExportOutcome、AsyncExportRequest、AsyncImportOutcome、AsyncImportRequest、SpreadsheetJobProgress、classify_transfer_size、normalize_header_token、run_import)、上限常量(DEFAULT_BATCH_SIZE、DEFAULT_DOWNLOAD_URL_LIFETIME、DEFAULT_EXPORT_PAGE_SIZE、DEFAULT_MAX_COLUMNS、DEFAULT_MAX_COMPRESSION_RATIO、DEFAULT_MAX_DECOMPRESSED_BYTES、DEFAULT_MAX_EXPORT_ROWS、DEFAULT_MAX_IMPORT_ROWS、DEFAULT_MAX_SYNC_BYTES、DEFAULT_MAX_SYNC_ROWS),object-store 下有 AsyncSpreadsheetRunner,spreadsheet-xlsx 下有 inspect_zip_bytes、XlsxOptions、XlsxReader、XlsxWriter、ZipInspection(再开 livecell-fly 有 fly_transfer_formats、XlsxExportFormat、XlsxImportFormat),notify 下有 notify_job_completed、SpreadsheetJobNotification,seaorm-* 下有 SeaOrmFindFuture、SeaOrmImportCtx、SeaOrmImportStrategy、SeaOrmImporter、SeaOrmRowBinder |
kxed::plugins::state_machine(feature) | Plugin 与配置(StateMachinePlugin、StateMachineConfig、StateMachineBackendKind、StateMachineCapability、AppCtxStateMachine、StateMachineHandle、BoundMachine、TypedRecord、StateMachineError)、声明式定义(MachineDefinition、MachineBuilder、StateKey、EventKey、TransitionRule、GuardCtx、TransitionGuard、AfterTransitionEvent、AfterTransitionHook、BoxFuture、FireOptions、TransitionOutcome)、存储适配器(StateMachineStore、StoreFuture、StoreError、MachineRecord、TransitionRecord、CreateResult、CommitRequest、CommitResult、HistoryQuery、MemoryStateMachineStore,state-machine-redis 下的 RedisStateMachineStore,seaorm-* 下的 SqlStateMachineStore 与 PendingTxTransition) |
kxed::plugins::templates(feature) | TemplatesPlugin、TemplatesConfig、TemplatesCapability、AppCtxTemplates、Templates、Rendered、上游 crate minijinja |
kxed::plugins::vite(feature vite) | PLUGIN_SOURCE、PLUGIN_REV、plugin_source、plugin_rev,命令 vite plugin;不是生命周期 plugin,引用这个模块只为把命令编进 binary |
kxed::plugins::seaorm(任一 seaorm-* feature) | Plugin 与连接(SeaOrmPlugin、DatabaseConfig、DatabaseCapability、DatabaseConnection、DatabaseConnectionName、NamedConnection、NamedConnections、AppCtxDatabase、AsConnection、SqlDialect、SqliteJournalMode、SlowStatementLevel、ErrorCause、DATABASE_CONNECTION_MISSING、dialect、bound_release、close_budget、fence、lock_for_ddl、schema_current、transaction、上游 crate sea_orm)、路由模型绑定与加密列(Found、FoundOf、FoundWithTrashed、FoundWithTrashedOf、RouteBinding、Encrypted、Translatable)、分页与列表 procedure(PaginateJson、ListSpec、SortColumns、AppCtxList)、子模块 audit、tenant、lock_version、种子(Seed、Seeder、Seeders、NamedSeeders),seaorm-migration 下的迁移(sea_orm_migration、async_trait、MigrationLock、MigrationState、SeaOrmMigrations、NamedMigrations、SerializedMigration、RollbackError、migrate_serialized、down_serialized),seaorm-object-store 下的附件列(Attachment),testing feature 下的子模块 testing |
task、event、resident、dispatch 以及 seaorm-* 下的 audit、tenant、lock_version 同时存在于宏命名空间与模块命名空间,互不冲突。各内置能力的底层 Plugin 与 Settings 类型不经门面重导出,自定义组装请直接依赖对应 capability crate。上表由 docs-check 对照源码导出逐名核验。
prelude 只放写 handler、Task、Resident 与监听服务时常用的名字:
| 类别 | 名字 |
|---|---|
| 宏 | dispatch、event、handles、on、resident、task、query、mutation、subscription,Serialize、Deserialize、Validate、CallFailure 与 ConfigSection derive |
| 类型 | App、AppCtx、AppErr、SideEffectFailure、ConfigLoader、ConfigSection、DispatchError、TaskCtx、NormalTask、TaskFailure、CronSchedule、CronMisfire、CronOverlap、Resident、Handles、ResidentCtx、Socket、Msg、Topic、Conn、CloseReason、Command(trait 与 derive)、Output、usage_error,以及开任一 seaorm-* feature 时的记录绑定 Found |
| 匿名引入的 trait | AppCtxAccess(含 ctx.http_drain_signal())、AppCtxCrypto(ctx.crypto()、ctx.signer()、ctx.webhook::<S>())、AppCtxTasks、AppCtxEvent、AppCtxResidents(ctx.resident(id)、ctx.residents())、AppCtxProcedures(ctx.call(..)、ctx.system()、ctx.is_dry_run()、ctx.expected_version())、AppCtxPush、AppCtxPublish、AppCtxPresence、AfterSideEffect、CallFailure、ExposeSecret、WsExt,打开 auth、authz、batch-ingest、cache、device、device-lease、features、http-client、i18n、ip、ledger、livecell、mail、notify、object-store、otp、redis、rollups、search、security、session、settings、state-machine、templates、seaorm-* feature 时另有 AppCtxAuth(ctx.default_guard()、ctx.password_verifier()、ctx.auth_sessions()、ctx.auth_sessions_of(guard)、ctx.two_factor_login()、ctx.two_factor_login_of(guard)、ctx.totp_setup(accounts)、ctx.totp_setup_of(guard, accounts)、ctx.recent_auth(),再开任一 seaorm-* 时的 ctx.accounts())、AppCtxAuthorization(ctx.authorization())、AppCtxBatchIngest(ctx.batch_ingest())、AppCtxCache(ctx.cache()、ctx.cache_scope())、AppCtxDevice(ctx.device_detector())、AppCtxDeviceLease(ctx.device_lease())、AppCtxFeatures(ctx.features())、AppCtxHttp(ctx.http())、AppCtxI18n(ctx.i18n())、AppCtxIp(ctx.ip_info(ip))、AppCtxLedger(ctx.ledger())、AppCtxLivecell(ctx.livecell(),再开 livecell-fly 时的 ctx.fly_accounts() 与 ctx.fly_two_factor(),再开 livecell-object-store 时的 ctx.livecell_uploads())、AppCtxMail(ctx.mailer())、AppCtxNotify(ctx.notify(..)、ctx.notifications(..))、AppCtxObjectStore、AppCtxOtp(ctx.otp())、AppCtxRedis(ctx.redis())、AppCtxRollups(ctx.rollups()、ctx.rollup_mark::<R>(..)、ctx.report_cutoff())、AppCtxSearch(ctx.search())、AppCtxRateLimiter(ctx.rate_limiter())、AppCtxSession(ctx.session_scope()、ctx.session_reader())、AppCtxSettings(ctx.settings::<T>()、ctx.save_settings(..))、AppCtxStateMachine(ctx.state_machine())、AppCtxTemplates(ctx.render_template(..))、AppCtxDatabase(ctx.db()、ctx.db_of(name)、ctx.db_dialect()、ctx.db_connections()、ctx.transaction(attempts, work)、ctx.transaction_of(name, attempts, work))、AppCtxList(ctx.list(spec, &input))、PaginateJson(find() 链上的 paginate_json、cursor_json、cursor_json_desc)、TenantScoped(泛型代码的 E::scoped(&ctx))、FilePartStore(file.store(&stores, &path))、BeginWrite(开 task-sqlite、task-postgres、task-mysql 或 seaorm-* 时 sea-orm 连接上的 db.begin_write(),.within(&txn) 的事务用它开) |
| 其他 | tokio、Json、Form、Path、Query(解析拒绝见第 5.1 节),分页 PageQuery、CursorQuery、Collection,procedure 类型 Streamed、TaskRef、error_code、UploadRef、Id、WithId、ListInput、OptionsInput,ToSchema 与 utoipa,连接与多站点元信息 ClientIp(可信代理见第 3.2 节,bucket() 聚合来源)、RequestScheme(Http/Https)、PeerAddr、RawRequestUri、HostCaptures、SitePolicy、SiteSessionPolicy、SiteSessionCookieOverride、SiteSameSite、SiteSecurityPolicy、SiteCsrfPolicy、SiteLocalePolicy,路由方法 get、post、put、patch、delete、head、options,访问控制 require_role、require_permission、Policy、Decision、Grants,多租户 tenant_route、CurrentTenant,加密与验签 Cookies、Cookie、require_signature、VerifiedWebhook、WebhookSource、WebhookScheme,错误上报 ErrorEvent、ErrorReporter,StatusCode,Bytes |
匿名引入的 trait 仅挂载上下文方法,不占用用户类型命名空间;未注册对应插件时调用其方法统一返回 500 state_not_registered。kxed::prelude::tokio 即 tokio 本身,prelude 与门面均不暴露任何 Fabric 节点层 API。
示例与多进程验证#
全部可运行示例清单见 examples/README.md,界面组件行为见 LIVECELL.md 与 FLY.md。其中三个示例直接承担真实多进程门禁验证:
examples/full-backend(cargo xtask task-cluster-smoke):双进程placement.quorum=2验证跨节点 Task 查询/取消、亲和 Task 检查点与推迟、执行者 SIGKILL 后接管续跑,以及 Cron 跨节点取消不复活。examples/livecell-cluster(cargo xtask livecell-cluster-smoke):验证多进程 Pinned 会话归址、跨节点透明转发、共享对象存储上传与节点故障后的快照重挂。examples/fly-tenant(cargo xtask fly-cluster):验证多租户后台登录、行级权限隔离与跨节点会话重挂。
2.1 命令进程#
同一个应用二进制根据启动参数自动进入常驻服务、离线命令或启动档命令进程:
flowchart TD
bin["应用 binary 入口 #[kxed::main]"] --> arg{"命令行参数"}
arg -->|"无参数或 serve"| srv["服务进程:按原配置启动 Fabric 与全部 Plugin,接流量并监听信号"]
arg -->|"离线档子命令(about / routes / config check 等)"| off["只读编译期声明与配置文件,不启动 Plugin,输出结果退出"]
arg -->|"启动档子命令(migrate / task / auth 等)"| cmd["命令进程:裁剪执行面配置(关公网端口、Task 执行、Resident 承载与集群加入)"]
cmd --> boot["启动全部 Plugin(注入 CommandProcess 标记) -> 执行 check/run -> 逆序停机退出"]启动档命令复用服务进程的同一份配置加载器,但在启动前强制覆盖以下执行面配置:
- 将
tasks.execution.enabled、tasks.scheduling.enabled、residents.hosting.enabled、server.public.enabled全部置为false。 - 清空
fabric.seeds、fabric.cluster.bind、fabric.gossip.bind,将fabric.discovery.mode设为"none",将expected_nodes与quorum设为1,并清空fabric.psk*、各advertise、pod_ip与fabric.advertise_cidr。 - 将 HTTP 绑到
127.0.0.1:0,关闭独立运维端口与独立 WebSocket 端口,清空server.addr_file,且跳过App::cron计划注册。
因此命令进程不接外部流量、不跑后台任务、不承载 Resident、也不加入集群;已注册插件照常启动并可通过框架状态 CommandProcess 识别当前环境(如 Search 停用后台 relay、SeaORM 跳过自动迁移、Livecell 不起转发器)。
在命令进程中调用各能力的结局如下:
| 调用接口 | 命令进程内的行为与返回 |
|---|---|
ctx.submit(task)、TaskService 死信与 Cron 管理 | 正常生效:写入共享 Task 存储,交由在线的服务进程领取执行 |
ctx.emit(event) | durable 订阅者正常写入持久 Task;仅有普通或 every_process 订阅者时返回 EmitError::Emit(Reject::Closed)(code closed,退出 69);混合订阅时命令成功并写 warn;带 .within(..) 时提交后由服务进程统一派发 |
ctx.push(uid, event) | 拒绝:返回 Rejected(Reject::Closed)(503 closed,退出 69);命令进程没有任何连接 |
ctx.broadcast(topic, event) | 拒绝:返回 Rejected(Reject::Closed),同上 |
ctx.resident::<R>(id) 的 call 与 notify | 拒绝:立即返回 ResidentCallError::Closed(code resident_closed,退出 69),不等待重试 |
#[dispatch] 函数 | 拒绝:返回 DispatchError::NoExecutor(code dispatch_no_executor,退出 69),不在命令进程自己的状态上执行函数体 |
is_online、online_count、topic_members | 返回空视图(false、0、空列表),结束时向 stderr 输出一行提示(--json 下不输出) |
进程内 Moka Cache、RateLimiter、内存 ObjectStore | 只作用于命令进程自己的副本,进程退出即销毁,服务进程不可见;切为 Redis 或外部存储时读写共享数据 |
官方内建运维命令遇到未共享的进程内存储时一律以退出码 69 拒绝执行(不伪造空列表):
- 无共享 Task 存储(未打开存储、显式内存模式或
sqlite::memory:)时,task、cron与本机stat拒绝执行。 - 认证或会话采用内存后端时,
auth与session命令拒绝执行。 database.url为内存 SQLite 时,migrate、search与fly命令拒绝执行;自定义数据库命令可在开头调用DatabaseCapability::require_shared(ctx)?复用同一检查。