Skip to main content

mgui_runtime/
startup.rs

1//! 启动顺序埋点与冒烟校验。
2//!
3//! `AppRunner` 在关键节点记录 [`StartupStep`](启动/窗口/AccessKit/后端/首帧/可见/
4//! 初始语义树),`--startup-smoke` 模式跑一遍隐藏(屏幕外)窗口后校验:
5//! **首帧 present 必须先于 `set_visible`**,**初始 a11y 树必须在可见后的第一帧推送**。
6//! 纯结构校验可单测,CI 无 GPU 时也能跑(配合软件回退)。
7
8/// 启动阶段(按期望发生顺序排列)
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum StartupStep {
11    Resumed,
12    WindowCreated,
13    AccessKitReady,
14    /// GPU Renderer 或软件回退后端就绪
15    BackendReady,
16    /// 首帧已成功 present(窗口仍不可见)
17    FirstFramePresented,
18    /// 调用 `set_visible(true)`(冒烟模式窗口位于屏幕外)
19    WindowVisible,
20    /// 可见后推送第一棵 AccessKit 语义树
21    A11yInitialPushed,
22    /// 完整桌面路径:菜单/托盘/单实例/快捷键服务均已注册(smoke 不记录)
23    ShellServicesReady,
24    /// 完整桌面路径:窗口可见后第一帧已成功 present(smoke 不记录)
25    FirstVisibleFramePresented,
26}
27
28impl StartupStep {
29    pub fn as_str(self) -> &'static str {
30        match self {
31            StartupStep::Resumed => "resumed",
32            StartupStep::WindowCreated => "window_created",
33            StartupStep::AccessKitReady => "accesskit_ready",
34            StartupStep::BackendReady => "backend_ready",
35            StartupStep::FirstFramePresented => "first_frame_presented",
36            StartupStep::WindowVisible => "window_visible",
37            StartupStep::A11yInitialPushed => "a11y_initial_pushed",
38            StartupStep::ShellServicesReady => "shell_services_ready",
39            StartupStep::FirstVisibleFramePresented => "first_visible_frame_presented",
40        }
41    }
42}
43
44/// 启动顺序记录(步骤 + 自启动起的毫秒数)
45#[derive(Clone, Debug, Default)]
46pub struct StartupTrace {
47    steps: Vec<(StartupStep, u64)>,
48}
49
50impl StartupTrace {
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    /// 记录一个阶段;同一步骤只记第一次(阶段是单向的)
56    pub fn record(&mut self, step: StartupStep, elapsed_ms: u64) {
57        if !self.has(step) {
58            self.steps.push((step, elapsed_ms));
59        }
60    }
61
62    pub fn has(&self, step: StartupStep) -> bool {
63        self.steps.iter().any(|(s, _)| *s == step)
64    }
65
66    pub fn steps(&self) -> &[(StartupStep, u64)] {
67        &self.steps
68    }
69
70    /// 校验关键顺序:
71    /// 1. 六个阶段齐全;
72    /// 2. `FirstFramePresented` 早于 `WindowVisible`(禁止白屏);
73    /// 3. `A11yInitialPushed` 晚于 `WindowVisible`(可见后首帧才推树)。
74    pub fn validate(&self) -> Result<(), String> {
75        let pos = |step: StartupStep| self.steps.iter().position(|(s, _)| *s == step);
76        let mut missing = Vec::new();
77        for step in [
78            StartupStep::Resumed,
79            StartupStep::WindowCreated,
80            StartupStep::AccessKitReady,
81            StartupStep::BackendReady,
82            StartupStep::FirstFramePresented,
83            StartupStep::WindowVisible,
84            StartupStep::A11yInitialPushed,
85        ] {
86            if pos(step).is_none() {
87                missing.push(step.as_str());
88            }
89        }
90        if !missing.is_empty() {
91            return Err(format!("缺少启动阶段: {}", missing.join(", ")));
92        }
93
94        let present = pos(StartupStep::FirstFramePresented).unwrap();
95        let visible = pos(StartupStep::WindowVisible).unwrap();
96        let a11y = pos(StartupStep::A11yInitialPushed).unwrap();
97        if present > visible {
98            return Err("首帧 present 晚于窗口显示(会白屏)".into());
99        }
100        if a11y < visible {
101            return Err("初始 a11y 树早于窗口显示(adapter 可能未激活)".into());
102        }
103        Ok(())
104    }
105
106    /// 冒烟报告:`first_frame=84ms window_visible=...;...`
107    pub fn report(&self) -> String {
108        self.steps.iter().map(|(s, ms)| format!("{}={}ms", s.as_str(), ms)).collect::<Vec<_>>().join(" ")
109    }
110
111    /// 从启动到首帧 present 的毫秒数;没走到首帧返回 None(不能当 0)。
112    pub fn first_frame_ms(&self) -> Option<u64> {
113        self.steps.iter().find(|(step, _)| *step == StartupStep::FirstFramePresented).map(|(_, ms)| *ms)
114    }
115
116    /// 启动阶段总耗时:取最后一个已记录阶段的时间戳。
117    pub fn total_ms(&self) -> Option<u64> {
118        self.steps.last().map(|(_, ms)| *ms)
119    }
120
121    /// 机器可解析的指标行;未采集阶段写 `unmeasured`,不写 0。
122    ///
123    /// `pid` 是进程自己的 id,给外部采样器在首帧后抓 RSS 用;RSS 刻意不放进
124    /// 这行——它属于进程级观测,不能由阶段时间戳伪造。默认路径标签为 `smoke`,
125    /// 完整桌面路径由宿主调用 [`Self::metrics_line_with_path`] 标为 `full`。
126    pub fn metrics_line(&self) -> String {
127        self.metrics_line_with_path("smoke")
128    }
129
130    /// 带路径标签的指标行。旧解析器按键名取值即可忽略 `path`。
131    pub fn metrics_line_with_path(&self, path: &str) -> String {
132        let first_frame = self.first_frame_ms().map(|v| v.to_string()).unwrap_or_else(|| "unmeasured".into());
133        let total = self.total_ms().map(|v| v.to_string()).unwrap_or_else(|| "unmeasured".into());
134        let path = if path.is_empty() { "smoke" } else { path };
135        format!(
136            "[startup-metrics] first_frame_ms={first_frame} total_ms={total} pid={} path={path}",
137            std::process::id()
138        )
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    fn valid_trace() -> StartupTrace {
147        let mut t = StartupTrace::new();
148        for (i, step) in [
149            StartupStep::Resumed,
150            StartupStep::WindowCreated,
151            StartupStep::AccessKitReady,
152            StartupStep::BackendReady,
153            StartupStep::FirstFramePresented,
154            StartupStep::WindowVisible,
155            StartupStep::A11yInitialPushed,
156        ]
157        .into_iter()
158        .enumerate()
159        {
160            t.record(step, i as u64 * 10);
161        }
162        t
163    }
164
165    #[test]
166    fn valid_order_passes() {
167        assert!(valid_trace().validate().is_ok());
168    }
169
170    #[test]
171    fn visible_before_first_frame_is_rejected() {
172        let mut t = StartupTrace::new();
173        for step in [
174            StartupStep::Resumed,
175            StartupStep::WindowCreated,
176            StartupStep::AccessKitReady,
177            StartupStep::BackendReady,
178            StartupStep::WindowVisible, // 抢在首帧前显示 → 白屏
179            StartupStep::FirstFramePresented,
180            StartupStep::A11yInitialPushed,
181        ] {
182            t.record(step, 0);
183        }
184        let err = t.validate().unwrap_err();
185        assert!(err.contains("白屏"), "错误信息应指出白屏: {err}");
186    }
187
188    #[test]
189    fn a11y_before_visible_is_rejected() {
190        let mut t2 = StartupTrace::new();
191        for step in [
192            StartupStep::Resumed,
193            StartupStep::WindowCreated,
194            StartupStep::AccessKitReady,
195            StartupStep::BackendReady,
196            StartupStep::FirstFramePresented,
197            StartupStep::A11yInitialPushed,
198            StartupStep::WindowVisible,
199        ] {
200            t2.record(step, 0);
201        }
202        let err = t2.validate().unwrap_err();
203        assert!(err.contains("a11y"), "错误信息应指出 a11y 顺序: {err}");
204    }
205
206    #[test]
207    fn missing_steps_are_reported() {
208        let mut t = StartupTrace::new();
209        t.record(StartupStep::Resumed, 0);
210        t.record(StartupStep::WindowCreated, 1);
211        let err = t.validate().unwrap_err();
212        assert!(err.contains("缺少启动阶段"), "{err}");
213        assert!(err.contains("first_frame_presented"), "{err}");
214    }
215
216    #[test]
217    fn metrics_line_never_reports_unmeasured_as_zero() {
218        let empty = StartupTrace::new();
219        let pid = std::process::id();
220        assert_eq!(
221            empty.metrics_line(),
222            format!("[startup-metrics] first_frame_ms=unmeasured total_ms=unmeasured pid={pid} path=smoke")
223        );
224        let trace = valid_trace();
225        assert_eq!(
226            trace.metrics_line(),
227            format!("[startup-metrics] first_frame_ms={} total_ms={} pid={} path=smoke", 4 * 10, 6 * 10, pid)
228        );
229        assert_eq!(
230            trace.metrics_line_with_path("full"),
231            format!("[startup-metrics] first_frame_ms={} total_ms={} pid={} path=full", 4 * 10, 6 * 10, pid)
232        );
233    }
234
235    #[test]
236    fn metrics_line_distinguishes_smoke_and_full_path() {
237        let trace = valid_trace();
238        let pid = std::process::id();
239        assert!(trace.metrics_line().ends_with("path=smoke"));
240        assert!(trace.metrics_line_with_path("full").ends_with("path=full"));
241        assert!(trace.metrics_line().contains(&pid.to_string()));
242    }
243
244    #[test]
245    fn optional_startup_steps_do_not_break_validation() {
246        let mut t = valid_trace();
247        t.record(StartupStep::ShellServicesReady, 5);
248        t.record(StartupStep::FirstVisibleFramePresented, 50);
249        assert!(t.validate().is_ok());
250        assert!(t.has(StartupStep::ShellServicesReady));
251        assert!(t.has(StartupStep::FirstVisibleFramePresented));
252    }
253
254    #[test]
255    fn duplicate_step_keeps_first_timestamp() {
256        let mut t = StartupTrace::new();
257        t.record(StartupStep::Resumed, 5);
258        t.record(StartupStep::Resumed, 99);
259        assert_eq!(t.steps(), &[(StartupStep::Resumed, 5)]);
260    }
261}