ek_core/plugin.rs
1//! `Plugin` trait —— 插件实现的唯一契约(业务与宿主的边界)。
2//!
3//! 纪律(写进 doc,实施由宿主强制):
4//! - 收:只有 [`Plugin::on_mail`] 一个入口;订阅面由 [`Plugin::routes`] 静态声明,
5//! 宿主 start() 时统一装配 forwarder(v0.1 不支持运行期动态订阅)。
6//! - 发:只有 [`PluginContext`](crate::PluginContext) 四个出口(put/ask/notify/write_log)。
7//! - 状态:插件状态放对象内部自锁(`Mutex/RwLock`);on_mail 在插件 worker 线程串行执行。
8//! - 停:on_stop 之后不再收到任何邮件(close 五步第②步)。
9
10use crate::context::PluginContext;
11use crate::service::ServiceDesc;
12use std::any::Any;
13use std::borrow::Cow;
14use std::time::Duration;
15
16use ek_event::Event;
17
18/// 默认邮箱容量(D5,confirms:按插件覆写override)。
19pub const MAILBOX_CAP: usize = 1024;
20
21/// 连续 panic 熔断阈值(D3)。
22pub const PANIC_LIMIT: u32 = 3;
23
24/// 插件名规则(D2):首字母字母,其余 alnum/_/-,长度 1..=32。
25pub fn valid_plugin_name(name: &str) -> bool {
26 let b = name.as_bytes();
27 if b.is_empty() || b.len() > 32 {
28 return false;
29 }
30 if !b[0].is_ascii_alphabetic() {
31 return false;
32 }
33 b[1..]
34 .iter()
35 .all(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'-')
36}
37
38pub trait Plugin: Any + Send + Sync {
39 /// 注册键(D2 校验)。
40 fn name(&self) -> &str;
41
42 /// D1 显式依赖清单(宿主注册期校验存在性,start 期拓扑排序)。
43 fn deps(&self) -> &[&str] {
44 &[]
45 }
46
47 /// 订阅的 type 集合:广播 type(如业务常量 "eTick.")、
48 /// 自身的寻址 type(e_req_type(本名)/e_to_type(本名))。
49 /// 宿主 start() 装配 forwarder → 邮箱 → on_mail。
50 fn routes(&self) -> Vec<Cow<'static, str>> {
51 Vec::new()
52 }
53
54 /// 邮箱容量覆写(D5:按插件可小可大,默认 [`MAILBOX_CAP`])。
55 fn mailbox_cap(&self) -> usize {
56 MAILBOX_CAP
57 }
58
59 /// 插件版本(约定填 crate 版本)。默认空串 = 「未知版本」。
60 ///
61 /// ⚠ 陷阱(审核 F6):默认实现无法用 `env!(CARGO_PKG_VERSION)`
62 /// —— 该宏在 ek-core 定义处展开,填出的是 ek-core 的版本。
63 /// 插件侧必须显式覆写:
64 /// ```ignore
65 /// fn version(&self) -> Cow<'static, str> {
66 /// Cow::Borrowed(env!("CARGO_PKG_VERSION"))
67 /// }
68 /// ```
69 fn version(&self) -> Cow<'static, str> {
70 Cow::Borrowed("")
71 }
72
73 /// 服务目录自报(纯声明):只在 add_plugin 时被宿主读取一次抽 `id` 织入路由索引;
74 /// 之后 ctx.services_of/find_service/ask_service 需要明细时由宿主**现场**调用本方法取。
75 ///
76 /// 铁律(审核 F8):本方法必须纯/静态/无锁/不阻塞 —— 它会在宿主管理线程上被
77 /// 与插件 worker 并发调用;违反此纪律后果自负。
78 ///
79 /// 目录改版铁律(执行期 DV4 发现):插件目录随配置/状态变化时,必须
80 /// **先更新本方法返回的内容,再 ctx.publish_services(...) 申报** ——
81 /// 宿主现场取,先申报后换内容会造成 live 细节与索引脱节。
82 fn services(&self) -> Vec<ServiceDesc> {
83 Vec::new()
84 }
85
86 /// 可选:启动前纯接线(缓存 ctx、读配置)。禁止在此 put/注册 handler(规范)。
87 fn on_init(&self, _ctx: &PluginContext) {}
88
89 /// start() 按依赖拓扑序调用(只一次)。
90 fn on_start(&self) {}
91
92 /// close/remove 按逆依赖序调用;调用后保证不再收到邮件。
93 fn on_stop(&self) {}
94
95 /// ★ 唯一业务入口:永远在本插件 worker 线程上串行执行。
96 /// 广播事件、寻址请求(eReq.<本名>)、定向通知(eTo.<本名>)都从这里进。
97 fn on_mail(&self, event: &Event);
98}
99
100/// close() 的 join 等待上限(D4:超时告警不死等)。
101pub const CLOSE_JOIN_TIMEOUT: Duration = Duration::from_secs(2);