1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum StartupStep {
11 Resumed,
12 WindowCreated,
13 AccessKitReady,
14 BackendReady,
16 FirstFramePresented,
18 WindowVisible,
20 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#[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 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 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 pub fn report(&self) -> String {
102 self.steps.iter().map(|(s, ms)| format!("{}={}ms", s.as_str(), ms)).collect::<Vec<_>>().join(" ")
103 }
104
105 pub fn first_frame_ms(&self) -> Option<u64> {
107 self.steps.iter().find(|(step, _)| *step == StartupStep::FirstFramePresented).map(|(_, ms)| *ms)
108 }
109
110 pub fn total_ms(&self) -> Option<u64> {
112 self.steps.last().map(|(_, ms)| *ms)
113 }
114
115 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, 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}