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 ShellServicesReady,
24 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#[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 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 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 pub fn report(&self) -> String {
108 self.steps.iter().map(|(s, ms)| format!("{}={}ms", s.as_str(), ms)).collect::<Vec<_>>().join(" ")
109 }
110
111 pub fn first_frame_ms(&self) -> Option<u64> {
113 self.steps.iter().find(|(step, _)| *step == StartupStep::FirstFramePresented).map(|(_, ms)| *ms)
114 }
115
116 pub fn total_ms(&self) -> Option<u64> {
118 self.steps.last().map(|(_, ms)| *ms)
119 }
120
121 pub fn metrics_line(&self) -> String {
127 self.metrics_line_with_path("smoke")
128 }
129
130 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, 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}