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}
23
24impl StartupStep {
25    pub fn as_str(self) -> &'static str {
26        match self {
27            StartupStep::Resumed => "resumed",
28            StartupStep::WindowCreated => "window_created",
29            StartupStep::AccessKitReady => "accesskit_ready",
30            StartupStep::BackendReady => "backend_ready",
31            StartupStep::FirstFramePresented => "first_frame_presented",
32            StartupStep::WindowVisible => "window_visible",
33            StartupStep::A11yInitialPushed => "a11y_initial_pushed",
34        }
35    }
36}
37
38/// 启动顺序记录(步骤 + 自启动起的毫秒数)
39#[derive(Clone, Debug, Default)]
40pub struct StartupTrace {
41    steps: Vec<(StartupStep, u64)>,
42}
43
44impl StartupTrace {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// 记录一个阶段;同一步骤只记第一次(阶段是单向的)
50    pub fn record(&mut self, step: StartupStep, elapsed_ms: u64) {
51        if !self.has(step) {
52            self.steps.push((step, elapsed_ms));
53        }
54    }
55
56    pub fn has(&self, step: StartupStep) -> bool {
57        self.steps.iter().any(|(s, _)| *s == step)
58    }
59
60    pub fn steps(&self) -> &[(StartupStep, u64)] {
61        &self.steps
62    }
63
64    /// 校验关键顺序:
65    /// 1. 六个阶段齐全;
66    /// 2. `FirstFramePresented` 早于 `WindowVisible`(禁止白屏);
67    /// 3. `A11yInitialPushed` 晚于 `WindowVisible`(可见后首帧才推树)。
68    pub fn validate(&self) -> Result<(), String> {
69        let pos = |step: StartupStep| self.steps.iter().position(|(s, _)| *s == step);
70        let mut missing = Vec::new();
71        for step in [
72            StartupStep::Resumed,
73            StartupStep::WindowCreated,
74            StartupStep::AccessKitReady,
75            StartupStep::BackendReady,
76            StartupStep::FirstFramePresented,
77            StartupStep::WindowVisible,
78            StartupStep::A11yInitialPushed,
79        ] {
80            if pos(step).is_none() {
81                missing.push(step.as_str());
82            }
83        }
84        if !missing.is_empty() {
85            return Err(format!("缺少启动阶段: {}", missing.join(", ")));
86        }
87
88        let present = pos(StartupStep::FirstFramePresented).unwrap();
89        let visible = pos(StartupStep::WindowVisible).unwrap();
90        let a11y = pos(StartupStep::A11yInitialPushed).unwrap();
91        if present > visible {
92            return Err("首帧 present 晚于窗口显示(会白屏)".into());
93        }
94        if a11y < visible {
95            return Err("初始 a11y 树早于窗口显示(adapter 可能未激活)".into());
96        }
97        Ok(())
98    }
99
100    /// 冒烟报告:`first_frame=84ms window_visible=...;...`
101    pub fn report(&self) -> String {
102        self.steps.iter().map(|(s, ms)| format!("{}={}ms", s.as_str(), ms)).collect::<Vec<_>>().join(" ")
103    }
104
105    /// 从启动到首帧 present 的毫秒数;没走到首帧返回 None(不能当 0)。
106    pub fn first_frame_ms(&self) -> Option<u64> {
107        self.steps.iter().find(|(step, _)| *step == StartupStep::FirstFramePresented).map(|(_, ms)| *ms)
108    }
109
110    /// 启动阶段总耗时:取最后一个已记录阶段的时间戳。
111    pub fn total_ms(&self) -> Option<u64> {
112        self.steps.last().map(|(_, ms)| *ms)
113    }
114
115    /// 机器可解析的指标行;未采集阶段写 `unmeasured`,不写 0。
116    ///
117    /// `pid` 是进程自己的 id,给外部采样器在首帧后抓 RSS 用;RSS 刻意不放进
118    /// 这行——它属于进程级观测,不能由阶段时间戳伪造。
119    pub fn metrics_line(&self) -> String {
120        let first_frame = self.first_frame_ms().map(|v| v.to_string()).unwrap_or_else(|| "unmeasured".into());
121        let total = self.total_ms().map(|v| v.to_string()).unwrap_or_else(|| "unmeasured".into());
122        format!("[startup-metrics] first_frame_ms={first_frame} total_ms={total} pid={}", std::process::id())
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    fn valid_trace() -> StartupTrace {
131        let mut t = StartupTrace::new();
132        for (i, step) in [
133            StartupStep::Resumed,
134            StartupStep::WindowCreated,
135            StartupStep::AccessKitReady,
136            StartupStep::BackendReady,
137            StartupStep::FirstFramePresented,
138            StartupStep::WindowVisible,
139            StartupStep::A11yInitialPushed,
140        ]
141        .into_iter()
142        .enumerate()
143        {
144            t.record(step, i as u64 * 10);
145        }
146        t
147    }
148
149    #[test]
150    fn valid_order_passes() {
151        assert!(valid_trace().validate().is_ok());
152    }
153
154    #[test]
155    fn visible_before_first_frame_is_rejected() {
156        let mut t = StartupTrace::new();
157        for step in [
158            StartupStep::Resumed,
159            StartupStep::WindowCreated,
160            StartupStep::AccessKitReady,
161            StartupStep::BackendReady,
162            StartupStep::WindowVisible, // 抢在首帧前显示 → 白屏
163            StartupStep::FirstFramePresented,
164            StartupStep::A11yInitialPushed,
165        ] {
166            t.record(step, 0);
167        }
168        let err = t.validate().unwrap_err();
169        assert!(err.contains("白屏"), "错误信息应指出白屏: {err}");
170    }
171
172    #[test]
173    fn a11y_before_visible_is_rejected() {
174        let mut t2 = StartupTrace::new();
175        for step in [
176            StartupStep::Resumed,
177            StartupStep::WindowCreated,
178            StartupStep::AccessKitReady,
179            StartupStep::BackendReady,
180            StartupStep::FirstFramePresented,
181            StartupStep::A11yInitialPushed,
182            StartupStep::WindowVisible,
183        ] {
184            t2.record(step, 0);
185        }
186        let err = t2.validate().unwrap_err();
187        assert!(err.contains("a11y"), "错误信息应指出 a11y 顺序: {err}");
188    }
189
190    #[test]
191    fn missing_steps_are_reported() {
192        let mut t = StartupTrace::new();
193        t.record(StartupStep::Resumed, 0);
194        t.record(StartupStep::WindowCreated, 1);
195        let err = t.validate().unwrap_err();
196        assert!(err.contains("缺少启动阶段"), "{err}");
197        assert!(err.contains("first_frame_presented"), "{err}");
198    }
199
200    #[test]
201    fn metrics_line_never_reports_unmeasured_as_zero() {
202        let empty = StartupTrace::new();
203        let pid = std::process::id();
204        assert_eq!(
205            empty.metrics_line(),
206            format!("[startup-metrics] first_frame_ms=unmeasured total_ms=unmeasured pid={pid}")
207        );
208        let trace = valid_trace();
209        assert_eq!(
210            trace.metrics_line(),
211            format!("[startup-metrics] first_frame_ms={} total_ms={} pid={}", 4 * 10, 6 * 10, pid)
212        );
213    }
214
215    #[test]
216    fn duplicate_step_keeps_first_timestamp() {
217        let mut t = StartupTrace::new();
218        t.record(StartupStep::Resumed, 5);
219        t.record(StartupStep::Resumed, 99);
220        assert_eq!(t.steps(), &[(StartupStep::Resumed, 5)]);
221    }
222}