ek_ui/plugin.rs
1//! `UiPlugin` —— 总线面:`eLog` 入环形日志、`ePlugUp/Down` 记事件 + rev、
2//! `eBar`./`eBarUpdate.` 记行情库(K线窗数据面)、`eTick.` 记 tick 库(v4 行情带
3//! 唯一源,S7 上屏地面)、`eContract.`/`eContractFinish` 记合约表,
4//! **0.5 M1 起 `eOrder.`/`eTrade.`/`ePosition.`/`eAccount.` 四条推送线入交易账本**
5//! (基线 BaseMonitor 同形:后台只 put,界面自己 process_event)。
6//! `eTimer`(1s 宿主自带)那一拍只做三件事:管制面快照(`svctl.list`,每
7//! `LIST_POLL_TICKS` 拍)、摊平的状态轮询(每拍最多 `STATUS_ASKS_PER_TICK` 个账户)、
8//! 被标记时才问一次的装配显形(`oms.pipeline_status`)。**这一拍不再问交易数据,
9//! 也不再辞行操作指令** —— 指令由命令线程执行(0.5 M5,点击即发)。
10//!
11//! 纪律(D1):UI 不周期取数;唯一例外是观测面 `svctl.list`(基线里对应物是同进程
12//! 直读,不是推送)。纪律(D2):后台只 put、不驱动界面 —— 入账 worker 里没有任何 ask。唯一管制面是 ask 契约(svctl / dm.reload /
13//! oms 查询与 submit_order·cancel_order / ctp 配置订阅,全部与
14//! headless 同源;`PluginContext` 只在 worker 可用)。0.1.1 BD-UI-30:
15//! 下单/撤单直发网关的旁路口删除——风控与守卫不可绕过。0.2.10 BD-UI-38:
16//! sim 纸面网关退场(流控查询口随之撤)。
17
18use std::sync::OnceLock;
19use std::time::Duration;
20
21use ek_core::context::PluginContext;
22use ek_core::plugin::Plugin;
23use ek_core::service::{PlugNotice, ServiceDesc};
24use ek_core::{EVENT_PLUG_DOWN, EVENT_PLUG_UP};
25use ek_ctp::plugin::{
26 ConfigureReply, ConfigureReq, DisconnectReply, DisconnectReq, GatewayStatus, StatusReq,
27 SubscribeReply as CtpSubscribeReply, SubscribeReq as CtpSubscribeReq,
28};
29use ek_data::account::AccountData;
30use ek_data::event::{EVENT_BAR, EVENT_CONTRACT, EVENT_LOG, EVENT_TICK};
31use ek_data::log::LogData;
32use ek_data::order::OrderData;
33use ek_data::position::PositionData;
34use ek_data::trade::TradeData;
35use ek_dm::plugin::{EVENT_BAR_UPDATE, ReloadReq};
36use ek_event::EVENT_TIMER;
37use ek_oms::plugin::{
38 GetAllAccountsReq, GetAllOrdersReq, GetAllPositionsReq, GetAllTradesReq, OmsCancelOrderReq,
39 OmsCancelReply, PipelineStatusReq, SubmitOrderReq,
40};
41use ek_oms::{SubmitReply, SubmitStatus};
42use ek_station::wire::{
43 ListReq, PlugRow, RemoveReq, RemoveRes, SVC_LIST, SVC_REMOVE, SVC_START, StartReq, StartRes,
44};
45
46// 配置托底三口的 ask 面(0.6.0 环节8);id 以 ek-cfg `cfg_services()` 单源
47// (逐角取,不本地复定义字面 —— 服务名将来若改,编译/运行端对上就行)。
48// 类型面三口契约(id 与类型单源同在 ek-cfg):
49// cfg.save = CfgSaveReq/CfgSaveRes(落一段;ui 只在「重存段」面上用)
50// cfg.list = CfgListReq/CfgListRes(目录;零值面)
51// cfg.delete = CfgDeleteReq/CfgDeleteRes(抹键/清段)
52use ek_cfg::wire::{
53 DeleteReq as CfgDeleteReq, DeleteRes as CfgDeleteRes, ListReq as CfgListReq,
54 ListRes as CfgListRes, SaveReq as CfgSaveReq, SaveRes as CfgSaveRes,
55};
56
57/// `cfg.list` / `cfg.delete` 服务 id(单源自 ek-cfg `wire::cfg_services()` 的
58/// 表位;此处取第 2/3 行)。加载期一次,不重复算。
59fn cfg_svc_ids() -> (String, String, String) {
60 let descs = ek_cfg::wire::cfg_services();
61 let id = |i: usize| -> String {
62 descs
63 .get(i)
64 .map_or_else(|| format!("cfg.svc[{i}]"), |d| d.id.clone())
65 };
66 (id(0), id(1), id(2))
67}
68
69/// 配置托底存储根(与 station 工厂 `ek_cfg::CfgPlugin::eco_or_local` 同口径:
70/// eco 成功 = 生态配置目录;失败 = 仓内 `./ekcfg-local`)。命令线程直接落库
71/// 的「重存段」與目录行共根的保证点。
72fn ui_cfg_store() -> ek_cfg::Store {
73 match ek_cfg::Store::eco() {
74 Ok(s) => s,
75 Err(e) => {
76 eprintln!("ek-cfg:运维修复根 eco 失败({e}),回落仓内 ./ekcfg-local(显形口径)");
77 ek_cfg::Store::with_root(std::path::PathBuf::from("ekcfg-local"))
78 }
79 }
80}
81
82use crate::state::{BusSnap, UiShared};
83
84/// 注册名 = 工厂名 = `"ui"`(BD-U5:两者一致)。
85pub const UI_NAME: &str = "ui";
86
87/// 界面邮箱容量(0.5 M6:取代对账机制)。
88///
89/// ek-event 的总线队列是无界的(照 Python `queue.Queue`,engine.rs:21-22),会丢事件的
90/// 只有 ek-core 这一跳有界邮箱 —— 而界面不再每秒自己问四次之后,它邮箱里就只剩
91/// 「别人推来的事件」。1024 格在 30 条/秒的行情下只够 34 秒积压;10 万格 ≈ 55 分钟,
92/// 溢出从常态变成异常。溢出仍然当场显形(0.4.5 P7d 的运维窗上色 + toast),但不再触发
93/// 自动修复:基线没有对账,因为它不丢事件。
94pub const UI_MAILBOX_CAP: usize = 100_000;
95
96/// 交易四表的推送线(基线 `event.py:13-18`;ek-ctp 0.4.0 起发裸键,ek-core 精确匹配)。
97/// 名字单源取 ek-oms::wire —— 同一条线在链上只有一份拼写。
98const W_ORDER: &str = ek_oms::wire::EVENT_ORDER;
99const W_TRADE: &str = ek_oms::wire::EVENT_TRADE;
100const W_POSITION: &str = ek_oms::wire::EVENT_POSITION;
101const W_ACCOUNT: &str = ek_oms::wire::EVENT_ACCOUNT;
102
103/// 常驻观测插件(窗口面在 [`crate::runtime`] 持 [`UiShared`] 渲染)。
104pub struct UiPlugin {
105 shared: std::sync::Arc<UiShared>,
106 ctx: OnceLock<PluginContext>,
107 /// 命令线程的停线位(0.5 M5;on_stop 置真,线程自己退)。
108 cmd_stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
109}
110
111impl UiPlugin {
112 /// 与窗口面共用的共享状态句柄。
113 pub fn new(shared: std::sync::Arc<UiShared>) -> Self {
114 Self {
115 shared,
116 ctx: OnceLock::new(),
117 cmd_stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
118 }
119 }
120
121 /// eTimer 节流回调(0.5:管制面快照 + 摊平的状态轮询 + 事件触发的装配显形)。
122 fn refresh(&self) {
123 let Some(ctx) = self.ctx.get() else {
124 return; // 未 init 就吃到 eTimer:忽略,等下轮
125 };
126 // 0.5 M3/M5:这一拍只做三件事,而且都不问交易数据。
127 // 指令辞行搬到命令线程(`spawn_cmd_thread`);四张表吃 eOrder. / eTrade. /
128 // ePosition. / eAccount. 推送入账(基线 BaseMonitor 同形)—— 这一拍里再出现
129 // 任何「取数类 ask」就是回到 0.4 的病。
130 if self.shared.list_poll_due() {
131 self.poll_list(ctx);
132 }
133 self.poll_status(ctx);
134 if self.shared.take_pipeline_due() {
135 self.poll_pipeline(ctx);
136 }
137 if self.shared.take_cfg_due() {
138 // 配置托底段目录(0.6.0 环节8):观测面读数,轻 IO 一次(与 poll_pipeline
139 // 同档的「观测面例外」,不进周期节拍 —— 只在钮触/回执后续问触发)。
140 self.poll_cfg(ctx);
141 }
142 }
143
144 /// 配置托底段目录(0.6.0;`cfg.list` 零值面,BD-CFG-17/18)。
145 fn poll_cfg(&self, ctx: &PluginContext) {
146 let (_, svc_list, _) = cfg_svc_ids();
147 match ctx.ask_service::<CfgListReq, CfgListRes>(svc_list.as_str(), CfgListReq, Duration::from_secs(2)) {
148 Ok(res) => {
149 self.shared.set_cfg_briefs(res.entries);
150 if !res.msg.is_empty() {
151 self.shared.log_line(format!("[cfg] 目录:{msg}", msg = res.msg));
152 }
153 }
154 Err(e) => self
155 .shared
156 .log_line(format!("[cfg] 段落目录失败(cfg 缺席或超时): {e:?}")),
157 }
158 }
159
160 /// 管制面快照(`svctl.list`):谁在场 + 服务目录 + 邮箱溢出计数。
161 ///
162 /// 0.5 M3 降到每 `LIST_POLL_TICKS` 拍一次。它给的不是交易数据而是「宿主长什么样」
163 /// 的观测面 —— 基线里的对应物是 `get_all_gateway_names` 的同进程直读,不是推送,
164 /// 所以它留在白名单里(「界面不周期取数」这条纪律的唯一例外)。
165 fn poll_list(&self, ctx: &PluginContext) {
166 match ctx.ask_service::<ListReq, Vec<PlugRow>>(SVC_LIST, ListReq, Duration::from_secs(2)) {
167 Ok(rows) => {
168 let mut services = Vec::with_capacity(rows.len());
169 for r in &rows {
170 let ids = ctx
171 .services_of(&r.name)
172 .map(|v| v.iter().map(|s| s.id.clone()).collect::<Vec<_>>())
173 .unwrap_or_default();
174 services.push((r.name.clone(), ids));
175 }
176 // 账户在场位回填 + 「实例没了就作废会话读数」。
177 // 0.5:「新装配」不再由这里检测 —— ePlugUp. 已订阅,即时且不靠轮询。
178 self.shared.sync_accounts_connected(&rows);
179 // 0.4.5(P7d):邮箱溢出的当场显形。运维窗那一列一直有 spilled,
180 // 但 ek-core 的 stderr 诊断每 128 条才打一条 —— 屏上此前没有任何东西。
181 self.shared.note_plugin_spill(&rows);
182 self.shared.set_snapshot(BusSnap { rows, services });
183 }
184 Err(e) => self.shared.log_line(format!("[ui] svctl.list 失败: {e:?}")),
185 }
186 }
187
188 /// 状态轮询(0.5 M3 摊平):每拍最多问 `STATUS_ASKS_PER_TICK` 个账户,环形推进。
189 ///
190 /// 只问「已装配且在场」的:实例已被摘除时 ask 会等到超时(2 秒),按账户串行就是
191 /// 按账户把整个刷新循环拖住 —— 而那种账户本来也没有会话可问。只读口不写日志
192 /// (ek-ctp D-STATUS ④),所以这条轮询不会冲 eLog 环。
193 fn poll_status(&self, ctx: &PluginContext) {
194 let present: Vec<String> = self
195 .shared
196 .accounts()
197 .iter()
198 .filter(|a| a.stage == crate::state::AccountStage::Assembled && a.connected)
199 .map(|a| a.gateway.clone())
200 .collect();
201 for gw in self.shared.status_batch(&present) {
202 let svc = format!("{gw}.status");
203 match ctx.ask_service::<StatusReq, GatewayStatus>(
204 &svc,
205 StatusReq,
206 Duration::from_secs(2),
207 ) {
208 Ok(st) => self.shared.note_gateway_status(&gw, &st),
209 Err(e) => self.shared.note_status_unreachable(&gw, &format!("{e:?}")),
210 }
211 }
212 }
213
214 /// 装配显形(0.5 M3 改事件触发):`oms.pipeline_status` 只在被标记的那一拍问一次。
215 ///
216 /// 标记来自启动、`ePlugUp.oms` 与运维窗的刷新钮。它此前是每 4 拍一次的轮询 ——
217 /// 装配很少变,而它是 oms worker 上又一次串行 ask;在事件驱动模型里这种轮询是多余的。
218 fn poll_pipeline(&self, ctx: &PluginContext) {
219 match ctx.ask_service::<PipelineStatusReq, Vec<String>>(
220 "oms.pipeline_status",
221 PipelineStatusReq,
222 Duration::from_secs(2),
223 ) {
224 Ok(lines) => self.shared.set_pipeline_lines(lines),
225 Err(e) => {
226 // 不每拍刷日志:oms 不在场是合法态(清单里没选它,ask 走 TargetGone
227 // 快错)。只在「从有到无」那一次显形一条,与状态轮询「只读口不冲 eLog 环」
228 // 同口径。读数清空 → 运维窗那一节整节不画。
229 if !self.shared.pipeline_lines().is_empty() {
230 self.shared
231 .log_line(format!("[ui] oms.pipeline_status 失手: {e:?}"));
232 }
233 self.shared.set_pipeline_lines(Vec::new());
234 }
235 }
236 }
237
238 /// 启动一次四问(0.5 M4;基线无对应物 —— 插件热插拔是 ek 独有场景)。
239 ///
240 /// 一次性,不是周期:之后四张表只吃推送。走 `note_*` 而不是 `seed_trade_snap`,
241 /// 是为了**合并而不是覆盖** —— 网关可能在 oms 还没消化完之前就已经把委托推给了
242 /// 界面,覆盖式播种会把界面已经看见的那一笔抹掉。
243 ///
244 /// 执行位置 = 命令线程(0.5 执行核查改的):原先它挂在 `on_start` 里,而 `on_start`
245 /// 是宿主启动序列的一部分 —— 四口最坏 4 × 2 秒会把后面插件的启动一起拖住;挂在
246 /// 入账 worker 上又违反「入账 worker 里没有任何 ask」。所以它跟着命令线程走。
247 fn reconcile_trade(shared: &UiShared, ctx: &PluginContext) {
248 let orders = ctx.ask_service::<GetAllOrdersReq, Vec<OrderData>>(
249 "oms.get_all_orders",
250 GetAllOrdersReq,
251 Duration::from_secs(2),
252 );
253 let trades = ctx.ask_service::<GetAllTradesReq, Vec<TradeData>>(
254 "oms.get_all_trades",
255 GetAllTradesReq,
256 Duration::from_secs(2),
257 );
258 let positions = ctx.ask_service::<GetAllPositionsReq, Vec<PositionData>>(
259 "oms.get_all_positions",
260 GetAllPositionsReq,
261 Duration::from_secs(2),
262 );
263 let funds = ctx.ask_service::<GetAllAccountsReq, Vec<AccountData>>(
264 "oms.get_all_accounts",
265 GetAllAccountsReq,
266 Duration::from_secs(2),
267 );
268 let mut n = 0usize;
269 if let Ok(rows) = &orders {
270 for o in rows {
271 shared.note_order(o);
272 }
273 n += rows.len();
274 }
275 if let Ok(rows) = &trades {
276 for t in rows {
277 shared.note_trade(t);
278 }
279 n += rows.len();
280 }
281 if let Ok(rows) = &positions {
282 for p in rows {
283 shared.note_position(p);
284 }
285 n += rows.len();
286 }
287 if let Ok(rows) = &funds {
288 for a in rows {
289 shared.note_funds(a);
290 }
291 n += rows.len();
292 }
293 // 只在真播种到东西时落一条;空清单(刚装配、柜台还没回报)不刷日志。
294 if n > 0 {
295 let bad = usize::from(orders.is_err())
296 + usize::from(trades.is_err())
297 + usize::from(positions.is_err())
298 + usize::from(funds.is_err());
299 shared.log_line(format!(
300 "[ui] 启动播种 {n} 行(委托 {} / 成交 {} / 持仓 {} / 资金 {};失手 {} 口)",
301 orders.as_ref().map_or(0, |v| v.len()),
302 trades.as_ref().map_or(0, |v| v.len()),
303 positions.as_ref().map_or(0, |v| v.len()),
304 funds.as_ref().map_or(0, |v| v.len()),
305 bad
306 ));
307 }
308 }
309
310 /// 命令线程(0.5 M5):点击即发,不等 eTimer 拍,也不占 ui 的入账 worker。
311 ///
312 /// 基线对应物是「UI 主线程直调 `main_engine.send_order`,立即返回」(engine.py:915-923)。
313 /// ek-core 的 ask 是同步的,所以把「等回包」这件事从入账线程挪走:入账线程从此只
314 /// 做「收事件 → 写账本」,每事件 O(1),永不被后端拖住。
315 /// 这一条线程也是「会等的东西」唯一允许待的地方:启动一次四问在这里跑
316 /// (见 `reconcile_trade`),既不占宿主的启动序列,也不占入账 worker。
317 fn spawn_cmd_thread(&self) {
318 let Some(ctx) = self.ctx.get().cloned() else {
319 return; // 未 init:没有管制面可用
320 };
321 let shared = std::sync::Arc::clone(&self.shared);
322 let stop = std::sync::Arc::clone(&self.cmd_stop);
323 if std::thread::Builder::new()
324 .name("ui-cmd".to_string())
325 .spawn(move || {
326 loop {
327 if stop.load(std::sync::atomic::Ordering::Acquire) {
328 break;
329 }
330 // 用户指令优先于播种:播种最坏 4 × 2 秒,不能把点击排到它后面。
331 if shared.cmd_pending() {
332 Self::run_cmds(&shared, &ctx);
333 continue;
334 }
335 // 播种档:启动一次 + 之后每次网关 / oms 上线各一次(标记是消费性的)。
336 if shared.take_trade_reseed() {
337 Self::reconcile_trade(&shared, &ctx);
338 continue;
339 }
340 std::thread::sleep(Duration::from_millis(20));
341 }
342 })
343 .is_err()
344 {
345 // 线程起不来 = 指令只会进队列不会执行。这一条必须上屏,不能静默降级。
346 self.shared
347 .log_line("[ui] 命令线程起不来:操作指令会滞留在队列里");
348 }
349 }
350
351 /// 辞行指令队列(0.5 M5:由命令线程调用,不在 ui worker 上;回执进日志,面板语义可断言)。
352 fn run_cmds(shared: &UiShared, ctx: &PluginContext) {
353 for cmd in shared.drain_cmds() {
354 match cmd {
355 crate::state::UiCmd::Start { factory, name } => {
356 match ctx.ask_service::<StartReq, StartRes>(
357 SVC_START,
358 StartReq {
359 factory: factory.clone(),
360 name: name.clone(),
361 },
362 Duration::from_secs(3),
363 ) {
364 Ok(StartRes::Started { name }) => {
365 shared.log_line(format!("[ops] svctl.start {factory} → {name} 上线"));
366 }
367 Ok(StartRes::Rejected { reason }) => {
368 shared.log_line(format!("[ops] start {factory} 被拒: {reason}"));
369 }
370 Err(e) => {
371 shared.log_line(format!("[ops] start {factory} 失败: {e:?}"));
372 }
373 }
374 // 起停回执之后重问一次管制面:运维窗那一行与账户在场位立刻动。
375 shared.request_list_refresh();
376 }
377 crate::state::UiCmd::Remove { name } => {
378 // 观测面自身的闸(0.4.3 BD-UI-64,审核 P1;0.5 M5 换了理由,闸不换):
379 // 0.4 的理由是「这条指令在 ui 自己的 worker 上执行 → 摘 ui = 自己等自己
380 // (ek-core `close_one` 只能走到 2 秒超时的 detach 分支)」。
381 // 0.5 执行者换成命令线程,「自己等自己」这一半不成立了,但结论一样:
382 // 摘掉 ui 之后没有 eTimer 拍再跑快照与状态轮询、入账 worker 也没了,
383 // 窗口还开着而里面全是上一帧。所以仍然直拒,不发 svctl。
384 // 管制面 `svctl` 的同一道闸长在 ek-station supervisor 侧(0.2.11)。
385 if name == UI_NAME {
386 shared.log_line(
387 "[ops] 拒绝移除 ui:观测面自身不可自摘(摘掉后没有下一拍执行任何指令)"
388 .to_string(),
389 );
390 continue;
391 }
392 match ctx.ask_service::<RemoveReq, RemoveRes>(
393 SVC_REMOVE,
394 RemoveReq { name: name.clone() },
395 Duration::from_secs(3),
396 ) {
397 Ok(RemoveRes::Removed { name }) => {
398 shared.log_line(format!("[ops] svctl.remove {name} 完成"));
399 }
400 Ok(RemoveRes::NoSuchName { name }) => {
401 shared.log_line(format!("[ops] remove {name} 不存在/不可摘"));
402 }
403 // 0.4.3:回执枚举增项(ek-station 0.2.11)—— 名字在场但不可摘,
404 // 或宿主另有错。原先这一档被塞进 NoSuchName 的 name 栏(错误文本
405 // 当名字打),这一栏现在照请求回填,错因只进 reason。
406 Ok(RemoveRes::Rejected { name, reason }) => {
407 shared.log_line(format!("[ops] remove {name} 被拒: {reason}"));
408 }
409 Err(e) => {
410 shared.log_line(format!("[ops] remove {name} 失败: {e:?}"));
411 }
412 }
413 shared.request_list_refresh();
414 }
415 crate::state::UiCmd::Reload {
416 interval,
417 symbol,
418 bars,
419 } => {
420 // 回灌走 dm.reload ask(push=true 逐条广播 → 行情板实时见回执面)。
421 match ctx.ask_service::<ReloadReq, usize>(
422 "dm.reload",
423 ReloadReq {
424 interval,
425 symbol: symbol.clone(),
426 bars: bars.clone(),
427 size: Some(bars.len()),
428 push: true,
429 },
430 Duration::from_secs(5),
431 ) {
432 Ok(n) => {
433 shared.market().note_reload();
434 shared.log_line(format!(
435 "[ops] dm.reload {symbol}@{interval}s 回灌 {n} 条"
436 ));
437 }
438 Err(e) => {
439 shared.log_line(format!("[ops] dm.reload {symbol} 失败: {e:?}"));
440 }
441 }
442 }
443 crate::state::UiCmd::SendOrder { req, gateway, mode } => {
444 // 0.1.1 BD-UI-30 薄下单者:五段管线全走 oms.submit_order
445 // (拆单/风控/逐腿发送/记账;直发 {gw}.send_order 旁路口删除,
446 // 守卫不可绕过)。parent 聚合逐腿显形进日志。
447 match ctx.ask_service::<SubmitOrderReq, SubmitReply>(
448 "oms.submit_order",
449 SubmitOrderReq {
450 req: req.clone(),
451 gateway_name: gateway.clone(),
452 mode,
453 },
454 Duration::from_secs(10),
455 ) {
456 Ok(reply) => {
457 let tag = match reply.status {
458 SubmitStatus::Sent => "SENT",
459 SubmitStatus::Partial => "PARTIAL",
460 SubmitStatus::Rejected => "REJECTED",
461 };
462 for leg in &reply.legs {
463 match (leg.ok, &leg.en_orderid, &leg.reason) {
464 (true, Some(id), _) => shared.log_line(format!(
465 "[ops] submit {} {} {}x{} → {id} (parent {})",
466 leg.req.symbol,
467 leg.req.direction.as_str(),
468 leg.req.offset.as_str(),
469 leg.req.volume,
470 reply.parent_id
471 )),
472 _ => shared.log_line(format!(
473 "[ops] submit {} {} {}x{} 被拒: {} (parent {})",
474 leg.req.symbol,
475 leg.req.direction.as_str(),
476 leg.req.offset.as_str(),
477 leg.req.volume,
478 leg.reason.as_deref().unwrap_or("?"),
479 reply.parent_id
480 )),
481 }
482 }
483 if reply.legs.is_empty() {
484 shared.log_line(format!(
485 "[ops] submit {} {}x{} {tag}:可平不足零腿 (parent {})",
486 req.symbol,
487 req.offset.as_str(),
488 req.volume,
489 reply.parent_id
490 ));
491 }
492 }
493 Err(e) => {
494 shared.log_line(format!("[ops] oms.submit_order 失败: {e:?}"));
495 }
496 }
497 }
498 crate::state::UiCmd::CancelOrder { orderid, gateway } => {
499 // 0.1.1 BD-UI-30:守卫撤单(尝试 ≤4000 在 oms;直发
500 // {gw}.cancel_order 旁路口删除)。en_orderid 组式与
501 // OrderData.en_orderid() 同式。
502 match ctx.ask_service::<OmsCancelOrderReq, OmsCancelReply>(
503 "oms.cancel_order",
504 OmsCancelOrderReq {
505 en_orderid: format!("{gateway}.{orderid}"),
506 gateway_name: gateway.clone(),
507 },
508 Duration::from_secs(10),
509 ) {
510 Ok(OmsCancelReply { ok: true, msg }) => {
511 shared.log_line(format!("[ops] {msg}"));
512 }
513 Ok(OmsCancelReply { ok: false, msg }) => {
514 shared.log_line(format!("[ops] 撤单被拒: {msg}"));
515 }
516 Err(e) => {
517 shared.log_line(format!("[ops] oms.cancel_order 失败: {e:?}"));
518 }
519 }
520 }
521 crate::state::UiCmd::CtpConfigure { gateway, form } => {
522 // 定盘口径:界面手工输入 → 插件自带配置口(插件不读文件)。
523 // 多账号面:服务名随网关走(`{gw}.configure`),不再硬编码 ctp。
524 let svc = format!("{gateway}.configure");
525 match ctx.ask_service::<ConfigureReq, ConfigureReply>(
526 svc.as_str(),
527 form.to_configure_req(),
528 Duration::from_secs(5),
529 ) {
530 // `..`:ConfigureReply 0.6.0 起带 product_classes(实际生效值)。
531 // 这里不回填表单勾选 —— 被拒时回带的是「网关当前仍在跑」的那一份,
532 // 用它覆盖用户刚点的勾选会把他的意图吃掉;日志里网关已写明收录产品类。
533 Ok(ConfigureReply { ok: true, msg, .. }) => {
534 shared.log_line(format!("[ops] {svc} 受理:{msg}"));
535 }
536 Ok(ConfigureReply { ok: false, msg, .. }) => {
537 shared.log_line(format!("[ops] {svc} 被拒:{msg}"));
538 }
539 Err(e) => {
540 shared.log_line(format!("[ops] {svc} 失败: {e:?}"));
541 }
542 }
543 }
544 crate::state::UiCmd::Connect { gateway, form } => {
545 // **四态分离的「连接」**(规划裁定「添加 ≠ 连接」):一次做完
546 // `svctl.start(factory=ctp)` + `{gw}.configure`,结果回写账户行
547 // (`Assembling → Assembled / AssembleFailed` + 失败原因留显形)。
548 // 失败**不回滚清册行** —— 行留着给『重试』(旧口径"必须先移除才能重试"作废)。
549 shared.note_connect_sent(&gateway);
550 // 单源纪律在此裁决:非行情源账户的 md 位就地清空,**留档与下发同一份**
551 // (旧口径只清下发不清留档,编辑页回填会带着一根用不上的行情前置)。
552 let form = shared.prepare_connect_form(&gateway, form);
553 let started = match ctx.ask_service::<StartReq, StartRes>(
554 SVC_START,
555 StartReq {
556 factory: "ctp".to_string(),
557 name: gateway.clone(),
558 },
559 Duration::from_secs(3),
560 ) {
561 Ok(StartRes::Started { name }) => {
562 shared.log_line(format!("[ops] svctl.start ctp → {name} 上线"));
563 true
564 }
565 Ok(StartRes::Rejected { reason }) => {
566 // 防重入(规划 Q7):实例已在场时重复点『连接』/『重试』不是失败,
567 // 重投凭据即可(否则会把正在跑的账户误判成"装配失败")。
568 if shared.account(&gateway).is_some_and(|a| a.connected) {
569 shared
570 .log_line(format!("[ops] {gateway} 已在场,重投凭据: {reason}"));
571 true
572 } else {
573 shared.log_line(format!("[ops] {gateway} 装配被拒: {reason}"));
574 shared.note_connect_result(&gateway, Err(reason));
575 continue;
576 }
577 }
578 Err(e) => {
579 shared.log_line(format!("[ops] {gateway} 装配失败: {e:?}"));
580 shared.note_connect_result(&gateway, Err(format!("{e:?}")));
581 continue;
582 }
583 };
584 if !started {
585 continue;
586 }
587 let svc = format!("{gateway}.configure");
588 match ctx.ask_service::<ConfigureReq, ConfigureReply>(
589 svc.as_str(),
590 form.to_configure_req(),
591 Duration::from_secs(5),
592 ) {
593 // `..`:ConfigureReply 带的 product_classes(实际生效值)不回填勾选
594 // (被拒时回带的是「网关仍在跑」的那一份,覆盖用户刚点的勾选会吃掉意图);
595 // 0.2.18 起把它显示出来(见 state::note_effective_product_classes)。
596 Ok(ConfigureReply {
597 ok: true,
598 msg,
599 product_classes,
600 }) => {
601 shared.log_line(format!("[ops] {svc} 受理:{msg}"));
602 shared.note_effective_product_classes(&gateway, &product_classes);
603 shared.note_connect_result(&gateway, Ok(()));
604 }
605 Ok(ConfigureReply { ok: false, msg, .. }) => {
606 shared.log_line(format!("[ops] {svc} 被拒:{msg}"));
607 shared.note_connect_result(&gateway, Err(msg));
608 }
609 Err(e) => {
610 shared.log_line(format!("[ops] {svc} 失败: {e:?}"));
611 shared.note_connect_result(&gateway, Err(format!("{e:?}")));
612 }
613 }
614 }
615 crate::state::UiCmd::CtpSubscribe { gateway, symbols } => {
616 // 多账号面:一律路由到行情元账号(渲染侧已按此入列);
617 // 纯 TD 账号收到订阅会**静默成功**(do_subscribe 恒 ok:true),
618 // 所以路由正确性靠界面纪律,不靠网关报错(规划 §9.4-21)。
619 let svc = format!("{gateway}.subscribe");
620 match ctx.ask_service::<CtpSubscribeReq, CtpSubscribeReply>(
621 svc.as_str(),
622 CtpSubscribeReq {
623 symbols: symbols.clone(),
624 },
625 Duration::from_secs(5),
626 ) {
627 Ok(CtpSubscribeReply { ok: true, msg }) => {
628 shared.note_subscriptions(&symbols);
629 shared.log_line(format!(
630 "[ops] {svc} {} 受理:{}",
631 symbols.join(","),
632 msg
633 ));
634 }
635 Ok(CtpSubscribeReply { ok: false, msg }) => {
636 shared.log_line(format!(
637 "[ops] {svc} {} 被拒:{}",
638 symbols.join(","),
639 msg
640 ));
641 }
642 Err(e) => {
643 shared.log_line(format!("[ops] {svc} 失败: {e:?}"));
644 }
645 }
646 }
647 crate::state::UiCmd::Disconnect { gateway } => {
648 // 0.2.19 规划裁定 1:『断开』= `{gw}.disconnect`(停会话),
649 // 『移除』= `svctl.remove`(停实例)—— 两条走两条不同的口,不共用。
650 // 发令即把该行标成「已断开」:用户按了钮就要立刻看到,不等下一轮轮询。
651 let svc = format!("{gateway}.disconnect");
652 match ctx.ask_service::<DisconnectReq, DisconnectReply>(
653 svc.as_str(),
654 DisconnectReq,
655 Duration::from_secs(5),
656 ) {
657 Ok(DisconnectReply { ok: true, msg }) => {
658 shared.mark_account_stopped(&gateway);
659 shared.log_line(format!("[账户] 断开 {gateway}:{msg}(实例仍在场)"));
660 }
661 Ok(DisconnectReply { ok: false, msg }) => {
662 shared.log_line(format!("[账户] 断开 {gateway} 未执行:{msg}"));
663 }
664 Err(e) => {
665 shared.log_line(format!(
666 "[账户] 断开 {gateway} 失败:{e:?}(网关不在场或超时)",
667 ));
668 }
669 }
670 }
671 crate::state::UiCmd::CfgList => {
672 // 目录刷新(命令线程执行档;与 worker poll_cfg 同一读数面)。
673 let (_, svc_list, _) = cfg_svc_ids();
674 match ctx.ask_service::<CfgListReq, CfgListRes>(svc_list.as_str(), CfgListReq, Duration::from_secs(2)) {
675 Ok(res) => {
676 shared.set_cfg_briefs(res.entries);
677 if !res.msg.is_empty() {
678 shared.log_line(format!("[cfg] 目录:{msg}", msg = res.msg));
679 }
680 }
681 Err(e) => shared.log_line(format!("[cfg] 段落目录失败: {e:?}")),
682 }
683 }
684 crate::state::UiCmd::CfgDelete { ns } => {
685 // 清段(BD-CFG-20 运维语义;空 key = 整段;零值面)。
686 let (svc_save, svc_list, svc_delete) = cfg_svc_ids();
687 let _ = (svc_save, svc_list);
688 match ctx.ask_service::<CfgDeleteReq, CfgDeleteRes>(
689 svc_delete.as_str(),
690 CfgDeleteReq { ns: ns.clone(), key: String::new() },
691 Duration::from_secs(2),
692 ) {
693 Ok(res) if res.ok => {
694 shared.log_line(format!(
695 "[cfg] 清段 {ns}:键 {} / 秘条 {}",
696 res.removed_keys, res.removed_secrets
697 ));
698 shared.request_cfg_refresh();
699 }
700 Ok(res) => shared.log_line(format!("[cfg] 清段 {ns} 未执行:{}", res.msg)),
701 Err(e) => shared.log_line(format!("[cfg] 清段 {ns} 失败: {e:?}")),
702 }
703 shared.arm_cfg_delete(None);
704 }
705 crate::state::UiCmd::CfgResave { ns } => {
706 // 重存段(0.6.0):明面按现状重读 → serialize → store。**值不变
707 // (BD-CFG-15:不输出 = 不持久,这里连「不重排空行」都不做之外的
708 // 改动一律没有)**;rev/格式修复口。兜底根与 cfg 实例同口径
709 // (BD-CFG-10 soft-centralized:直调用库,不拉起注册)。
710 let store = ui_cfg_store();
711 let loaded = store
712 .load(&ns)
713 .map_err(|e| e.to_string())
714 .and_then(|o| match o {
715 ek_cfg::LoadOutcome::Fresh => {
716 Err(format!("{ns} 段不存在,不持久空形"))
717 }
718 map @ ek_cfg::LoadOutcome::Loaded { .. } => Ok(map),
719 });
720 match loaded {
721 Ok(ek_cfg::LoadOutcome::Fresh) => {
722 unreachable!("Fresh 已被上面的 and_then 挡走");
723 }
724 Ok(ek_cfg::LoadOutcome::Loaded { map, warnings, backup_used }) => {
725 if !warnings.is_empty() {
726 shared.log_line(format!("[cfg] {ns} 重读警告:{warnings:?}"));
727 }
728 if backup_used {
729 shared.log_line(format!("[cfg] {ns} 走了 .bak 回落"));
730 }
731 match store.store(&ns, &map) {
732 Ok(()) => shared.log_line(format!("[cfg] {ns} 已重存(rev {})", map.rev)),
733 Err(e) => shared.log_line(format!("[cfg] {ns} 重存失败:{e}")),
734 }
735 }
736 Err(msg) => shared.log_line(format!("[cfg] {msg}")),
737 }
738 }
739 }
740 }
741 }
742}
743
744impl Plugin for UiPlugin {
745 fn name(&self) -> &str {
746 UI_NAME
747 }
748
749 fn deps(&self) -> &[&str] {
750 &[] // 纯观测;谁先上都能看到(bus 契约不依赖启动序)
751 }
752
753 fn routes(&self) -> Vec<std::borrow::Cow<'static, str>> {
754 vec![
755 std::borrow::Cow::Borrowed(EVENT_LOG),
756 std::borrow::Cow::Borrowed(EVENT_PLUG_UP),
757 std::borrow::Cow::Borrowed(EVENT_PLUG_DOWN),
758 std::borrow::Cow::Borrowed(EVENT_BAR),
759 std::borrow::Cow::Borrowed(EVENT_BAR_UPDATE),
760 std::borrow::Cow::Borrowed(EVENT_TICK),
761 std::borrow::Cow::Borrowed(EVENT_CONTRACT),
762 std::borrow::Cow::Borrowed("eContractFinish"),
763 // 0.5 M1 交易四表的推送线(基线 BaseMonitor 各自订阅自己的线)。
764 // 不订 eTradeSync.:ek-oms 处理完成交后重推的那一条(plugin.rs:305-308),
765 // 与 ek-ctp 的 eTrade. 是同一笔成交的两份 —— 订两条就是重复入账。
766 std::borrow::Cow::Borrowed(W_ORDER),
767 std::borrow::Cow::Borrowed(W_TRADE),
768 std::borrow::Cow::Borrowed(W_POSITION),
769 std::borrow::Cow::Borrowed(W_ACCOUNT),
770 std::borrow::Cow::Borrowed(EVENT_TIMER),
771 ]
772 }
773
774 fn mailbox_cap(&self) -> usize {
775 UI_MAILBOX_CAP
776 }
777
778 fn version(&self) -> std::borrow::Cow<'static, str> {
779 std::borrow::Cow::Borrowed(env!("CARGO_PKG_VERSION"))
780 }
781
782 fn services(&self) -> Vec<ServiceDesc> {
783 Vec::new() // 纯视图零服务;管制面在 svctl
784 }
785
786 fn on_init(&self, ctx: &PluginContext) {
787 let _ = self.ctx.set(ctx.clone());
788 }
789
790 fn on_start(&self) {
791 self.shared.log_line("[ui] 界面插件上线");
792 // 0.5 M5 + M4:命令线程先起(点击即发);启动一次四问在那条线程里跑 ——
793 // `on_start` 是 `engine.start()` 启动链的一环,四口最坏 4 × 2 秒不许把后面
794 // 插件的启动一起拖住,更不许占入账 worker。
795 self.spawn_cmd_thread();
796 // 启动一次四问的标记(on_start 是 `engine.start()` 启动链的一环,四口最坏
797 // 4 × 2 秒不许把后面插件的启动一起拖住,更不许占入账 worker)。
798 self.shared.request_trade_reseed();
799 self.shared.request_pipeline_refresh();
800 }
801
802 fn on_stop(&self) {
803 self.shared.log_line("[ui] 界面插件下线");
804 // 命令线程停线:它在 20ms 空转切片自查这个位,不会卡在 sleep 里。
805 self.cmd_stop
806 .store(true, std::sync::atomic::Ordering::Release);
807 }
808
809 fn on_mail(&self, event: &ek_event::Event) {
810 let ty = event.event_type.as_str();
811 if ty == EVENT_LOG {
812 if let Some(d) = event.data.downcast_ref::<LogData>() {
813 let tag = if d.is_warning_or_above() {
814 "WARN"
815 } else {
816 "INFO"
817 };
818 self.shared
819 .log_line(format!("[{tag}][{}] {}", d.gateway_name, d.msg));
820 // 0.5.0(用户定「链进行的状态改为事件日志推送」):`[链] ` 前缀的行除了进日志窗,
821 // 还落进账户行的「阶段」栏(ek-ctp 0.9.8 D-QUERY-GATE ⑧)。这一条是纯显示落账,
822 // 不参与 `apply_status` 那套在线/断供判据。
823 // 前缀这一份是本地常量(ek-ui 现在钉的还是 ek-ctp 0.9.7,那上面没有这个常量);
824 // 抬 pin 到 0.9.8 之后改引用 `ek_ctp::driver::CHAIN_STATE_PREFIX`,回到单源。
825 if let Some(note) = d.msg.strip_prefix(crate::state::CHAIN_STATE_PREFIX) {
826 self.shared.note_chain(&d.gateway_name, note);
827 }
828 } else {
829 self.shared.log_line("[eLog] 载荷类型异常(非 LogData)");
830 }
831 return;
832 }
833 if ty == EVENT_PLUG_UP || ty == EVENT_PLUG_DOWN {
834 if let Some(n) = event.data.downcast_ref::<PlugNotice>() {
835 let verb = if ty == EVENT_PLUG_UP {
836 "上线"
837 } else {
838 "下线"
839 };
840 self.shared
841 .log_line(format!("[host] 插件{verb} {} v{}", n.name, n.version));
842 // 在场位与运维窗那一行跟着这条线动(不等 4 拍的快照节拍)。
843 self.shared.request_list_refresh();
844 if ty == EVENT_PLUG_UP {
845 // 0.5 M3:装配显形改吃这条线 —— 不再靠每拍 list 去发现「谁新上线」。
846 if n.name == "oms" {
847 self.shared.request_pipeline_refresh();
848 }
849 // 0.5 执行核查补的第三处:网关 / oms 上线之后重播种一次四张表。
850 // 摘除一个网关账户会作废它名下的委托与成交行,而 oms 那边那些行还在;
851 // 重新添加时不重问一次,界面就永久少一段历史。顺带覆盖「ui 先于 oms
852 // 起来、第一次播种问空了」这一序。
853 let is_account = self.shared.accounts().iter().any(|a| a.gateway == n.name);
854 if n.name == "oms" || is_account {
855 self.shared.request_trade_reseed();
856 }
857 // 0.5 M3:订阅重放同样改吃这条线(与 `sync_accounts_connected` 的
858 // newly 回带是同一件事的两条路,留一条:这条即时、那条要等快照拍)。
859 let md = self.shared.md_source();
860 let subs = self.shared.subscriptions();
861 if !md.is_empty() && n.name == md && !subs.is_empty() {
862 self.shared.push_cmd(crate::state::UiCmd::CtpSubscribe {
863 gateway: n.name.clone(),
864 symbols: subs.clone(),
865 });
866 self.shared.log_line(format!(
867 "[ops] 行情源 {} 上线,重放订阅 {} 项",
868 n.name,
869 subs.len()
870 ));
871 }
872 } else {
873 // 0.5 M1:网关下线 = 它名下的委托 / 成交 / 持仓 / 资金行全部作废。
874 // 推送模型里没人再告诉界面「这一行已经不存在了」,不清就是替一个
875 // 已经不存在的会话说话(与 0.2.19「实例不在场就作废会话读数」同口径)。
876 let removed = self.shared.clear_gateway_rows(&n.name);
877 if removed > 0 {
878 self.shared.log_line(format!(
879 "[ui] 插件下线 {}:作废 {} 行交易数据",
880 n.name, removed
881 ));
882 }
883 // 0.5 执行核查补的第二处:摘掉 oms 之后管线读数不会自己清空。
884 // 0.4 是每 4 拍问一次,4 秒内自己就空了;改事件触发后没人再问,
885 // 运维窗那一节会替一个已经不存在的 oms 说话。标记一次:下一拍问一次
886 // → TargetGone 快错 → `poll_pipeline` 的 Err 分支清空并落一条日志。
887 if n.name == "oms" {
888 self.shared.request_pipeline_refresh();
889 }
890 }
891 }
892 self.shared.bump();
893 return;
894 }
895 if ty == EVENT_BAR {
896 if let Some(f) = event.data.downcast_ref::<ek_dm::wire::BarsFrame>() {
897 self.shared.market().on_frame(f);
898 }
899 self.shared.bump();
900 return;
901 }
902 if ty == EVENT_BAR_UPDATE {
903 if let Some(b) = event.data.downcast_ref::<ek_data::bar::BarData>() {
904 self.shared.market().on_update(b);
905 }
906 self.shared.bump();
907 return;
908 }
909 if ty == EVENT_TICK {
910 if let Some(t) = event.data.downcast_ref::<ek_data::tick::TickData>() {
911 self.shared.update_tick(t);
912 }
913 return;
914 }
915 if ty == EVENT_CONTRACT {
916 if let Some(c) = event.data.downcast_ref::<ek_data::contract::ContractData>() {
917 self.shared.update_contract(c);
918 }
919 return;
920 }
921 if ty == "eContractFinish" {
922 let gw = event
923 .data
924 .downcast_ref::<String>()
925 .cloned()
926 .unwrap_or_else(|| "?".to_string());
927 self.shared
928 .log_line(format!("[ctp] 合约流完成 {gw}(查询合约窗可勾选订阅)"));
929 return;
930 }
931 // 0.5 M1 交易四表:后台只把事件推过来,界面自己入账(基线 BaseMonitor.process_event)。
932 // 这里不 ask 任何东西,所以入账 worker 永不被后端拖住。
933 if ty == W_ORDER {
934 match event.data.downcast_ref::<OrderData>() {
935 Some(o) => self.shared.note_order(o),
936 None => self.shared.note_bad_payload(W_ORDER),
937 }
938 return;
939 }
940 if ty == W_TRADE {
941 match event.data.downcast_ref::<TradeData>() {
942 Some(t) => self.shared.note_trade(t),
943 None => self.shared.note_bad_payload(W_TRADE),
944 }
945 return;
946 }
947 if ty == W_POSITION {
948 match event.data.downcast_ref::<PositionData>() {
949 Some(p) => self.shared.note_position(p),
950 None => self.shared.note_bad_payload(W_POSITION),
951 }
952 return;
953 }
954 if ty == W_ACCOUNT {
955 match event.data.downcast_ref::<AccountData>() {
956 Some(a) => self.shared.note_funds(a),
957 None => self.shared.note_bad_payload(W_ACCOUNT),
958 }
959 return;
960 }
961 if ty == EVENT_TIMER {
962 self.refresh();
963 }
964 }
965}