Skip to main content

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