1use std::cell::RefCell;
16use std::collections::HashMap;
17use std::rc::Rc;
18
19use day_spec::Lifecycle;
20
21type Handlers = Vec<Rc<dyn Fn()>>;
23
24day_reactive::tls_slots! {
25 lifecycle;
26 static HANDLERS: RefCell<HashMap<Lifecycle, Handlers>> =
27 RefCell::new(HashMap::new());
28 static WARNED: RefCell<std::collections::HashSet<Lifecycle>> =
30 RefCell::new(std::collections::HashSet::new());
31}
32
33static EXITED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
36static LAUNCHED: std::sync::Mutex<Option<Launched>> = std::sync::Mutex::new(None);
39
40struct Launched {
41 name: String,
42 version: Option<String>,
43 #[cfg(not(target_arch = "wasm32"))]
44 at: std::time::Instant,
45}
46
47pub fn note_launch(name: String, version: Option<String>) {
50 crate::memory_profile::start();
51 if let Ok(mut l) = LAUNCHED.lock() {
52 *l = Some(Launched {
53 name,
54 version,
55 #[cfg(not(target_arch = "wasm32"))]
56 at: std::time::Instant::now(),
57 });
58 }
59}
60
61fn exit_summary() -> String {
66 let (name, version, elapsed) = {
67 let l = LAUNCHED.lock().ok();
68 let l = l.as_deref().and_then(Option::as_ref);
69 let name = l
70 .map(|l| l.name.clone())
71 .filter(|n| !n.is_empty())
72 .unwrap_or_else(|| "the app".to_string());
73 let version = l
74 .and_then(|l| l.version.clone())
75 .or_else(|| std::env::var("DAY_APP_VERSION").ok())
76 .filter(|v| !v.is_empty());
77 #[cfg(not(target_arch = "wasm32"))]
78 let elapsed = l.map(|l| l.at.elapsed().as_secs());
79 #[cfg(target_arch = "wasm32")]
80 let elapsed = crate::frame::uptime_secs();
81 (name, version, elapsed)
82 };
83 let memory = resident_memory();
84 let mut summary = format_exit_summary(
85 &name,
86 version.as_deref(),
87 cfg!(debug_assertions),
88 elapsed,
89 memory,
90 );
91 if let Some(profile) = crate::memory_profile::finish(memory) {
92 summary.push_str(". ");
93 summary.push_str(&profile);
94 }
95 summary
96}
97
98fn format_exit_summary(
100 name: &str,
101 version: Option<&str>,
102 debug: bool,
103 elapsed_secs: Option<u64>,
104 memory_bytes: Option<u64>,
105) -> String {
106 let version = match version {
107 Some(v) => format!(" v{v}"),
108 None => String::new(),
109 };
110 let profile = if debug { "debug" } else { "release" };
111 let elapsed = match elapsed_secs {
112 Some(s) => format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60),
113 None => "an unknown time".to_string(),
114 };
115 let memory = match memory_bytes {
116 Some(b) => format!("{:.2} MB", b as f64 / 1e6),
117 None => "unknown".to_string(),
118 };
119 format!("Clean exit for {name}{version} ({profile}) after {elapsed}. Memory usage: {memory}")
120}
121
122#[must_use]
127pub fn resident_memory() -> Option<u64> {
128 #[cfg(any(target_os = "macos", target_os = "ios"))]
129 {
130 #[repr(C)]
132 struct TaskVmInfo {
133 virtual_size: u64,
136 region_count: i32,
137 page_size: i32,
138 resident_size: u64,
139 resident_size_peak: u64,
140 device: u64,
141 device_peak: u64,
142 internal: u64,
143 internal_peak: u64,
144 external: u64,
145 external_peak: u64,
146 reusable: u64,
147 reusable_peak: u64,
148 purgeable_volatile_pmap: u64,
149 purgeable_volatile_resident: u64,
150 purgeable_volatile_virtual: u64,
151 compressed: u64,
152 compressed_peak: u64,
153 compressed_lifetime: u64,
154 phys_footprint: u64,
155 }
156 unsafe extern "C" {
157 fn mach_task_self() -> u32;
158 fn task_info(task: u32, flavor: u32, info: *mut TaskVmInfo, count: *mut u32) -> i32;
159 }
160 const TASK_VM_INFO: u32 = 22;
161 let mut info = std::mem::MaybeUninit::<TaskVmInfo>::zeroed();
162 let mut count = (std::mem::size_of::<TaskVmInfo>() / std::mem::size_of::<u32>()) as u32;
163 let ok = unsafe {
166 task_info(
167 mach_task_self(),
168 TASK_VM_INFO,
169 info.as_mut_ptr(),
170 &raw mut count,
171 )
172 };
173 if ok != 0 {
174 return None;
175 }
176 let info = unsafe { info.assume_init() };
178 return Some(if info.phys_footprint > 0 {
179 info.phys_footprint
180 } else {
181 info.resident_size
182 });
183 }
184 #[cfg(any(target_os = "linux", target_os = "android", target_env = "ohos"))]
185 {
186 unsafe extern "C" {
187 fn sysconf(name: i32) -> i64;
188 }
189 #[cfg(target_os = "android")]
190 const SC_PAGESIZE: i32 = 40;
191 #[cfg(not(target_os = "android"))]
192 const SC_PAGESIZE: i32 = 30;
193 let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
195 let resident: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
196 let page = unsafe { sysconf(SC_PAGESIZE) };
198 return Some(resident * u64::try_from(page).unwrap_or(4096));
199 }
200 #[cfg(windows)]
201 {
202 #[repr(C)]
203 struct ProcessMemoryCounters {
204 cb: u32,
205 page_fault_count: u32,
206 peak_working_set_size: usize,
207 working_set_size: usize,
208 quota_peak_paged_pool_usage: usize,
209 quota_paged_pool_usage: usize,
210 quota_peak_non_paged_pool_usage: usize,
211 quota_non_paged_pool_usage: usize,
212 pagefile_usage: usize,
213 peak_pagefile_usage: usize,
214 }
215 #[link(name = "kernel32")]
216 unsafe extern "system" {
217 fn GetCurrentProcess() -> isize;
218 fn K32GetProcessMemoryInfo(
219 process: isize,
220 counters: *mut ProcessMemoryCounters,
221 cb: u32,
222 ) -> i32;
223 }
224 let mut counters = std::mem::MaybeUninit::<ProcessMemoryCounters>::zeroed();
225 let cb = std::mem::size_of::<ProcessMemoryCounters>() as u32;
226 let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), counters.as_mut_ptr(), cb) };
229 if ok == 0 {
230 return None;
231 }
232 return Some(unsafe { counters.assume_init() }.working_set_size as u64);
234 }
235 #[cfg(target_arch = "wasm32")]
236 {
237 return Some(core::arch::wasm32::memory_size(0) as u64 * 65536);
239 }
240 #[allow(unreachable_code)]
241 None
242}
243
244pub fn reset_handlers() {
248 HANDLERS.with(|h| h.borrow_mut().clear());
249 WARNED.with(|w| w.borrow_mut().clear());
250}
251
252pub fn on_lifecycle(phase: Lifecycle, f: impl Fn() + 'static) {
261 HANDLERS.with(|h| h.borrow_mut().entry(phase).or_default().push(Rc::new(f)));
262 if crate::tree::has_tree() {
265 warn_if_unsupported(phase);
266 }
267}
268
269pub fn dispatch_lifecycle(phase: Lifecycle) {
276 if phase == Lifecycle::WillTerminate {
279 crate::windows::save_remembered_frames();
280 crate::present::shutdown_tasks();
281 }
282 if phase == Lifecycle::DidExit {
283 if EXITED.swap(true, std::sync::atomic::Ordering::SeqCst) {
284 return;
285 }
286 if HANDLERS.try_with(|_| ()).is_ok() {
289 crate::present::shutdown_tasks();
290 dispatch_handlers(phase);
291 }
292 log::info!("{}", exit_summary());
293 return;
294 }
295 dispatch_handlers(phase);
296}
297
298fn dispatch_handlers(phase: Lifecycle) {
299 crate::frame::lifecycle(phase);
300 let handlers = HANDLERS.with(|h| h.borrow().get(&phase).cloned().unwrap_or_default());
301 if handlers.is_empty() {
302 return;
303 }
304 let mut any_panicked = false;
305 day_reactive::batch(|| {
306 for f in &handlers {
307 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f())).is_err() {
315 any_panicked = true;
316 log::warn!(
317 "an on_lifecycle({}) handler panicked and was contained — the app continues.",
318 phase.name()
319 );
320 crate::notify_contained_panic();
321 }
322 }
323 });
324 if any_panicked {
327 day_reactive::recover_from_panic();
328 }
329}
330
331#[must_use]
336pub fn lifecycle_supported(phase: Lifecycle) -> bool {
337 if crate::tree::has_tree() {
338 crate::with_tree(|t| t.supports_lifecycle(phase))
339 } else {
340 phase.is_universal()
341 }
342}
343
344fn warn_if_unsupported(phase: Lifecycle) {
345 if lifecycle_supported(phase) {
346 return;
347 }
348 let first = WARNED.with(|w| w.borrow_mut().insert(phase));
349 if first {
350 log::warn!(
351 "an `on_lifecycle({})` handler was registered, but this backend never delivers \
352 that phase, so it will not run. Guard it with `day::lifecycle_supported(..)` or a \
353 `day::require_lifecycle!(..)` compile-time check (docs/lifecycle.md).",
354 phase.name()
355 );
356 }
357}
358
359pub fn warn_unsupported_registrations() {
362 let phases: Vec<Lifecycle> = HANDLERS.with(|h| h.borrow().keys().copied().collect());
363 for p in phases {
364 warn_if_unsupported(p);
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371 use std::cell::Cell;
372
373 #[test]
374 fn the_exit_line_reads_as_documented() {
375 assert_eq!(
376 format_exit_summary(
377 "Day Rise",
378 Some("0.4.5"),
379 true,
380 Some(3 * 3600 + 7 * 60 + 9),
381 Some(12_345_678)
382 ),
383 "Clean exit for Day Rise v0.4.5 (debug) after 03:07:09. Memory usage: 12.35 MB"
384 );
385 assert_eq!(
386 format_exit_summary("", None, false, None, None),
387 "Clean exit for (release) after an unknown time. Memory usage: unknown"
388 );
389 }
390
391 #[test]
392 fn resident_memory_is_readable_here() {
393 assert!(resident_memory().is_some_and(|b| b > 1 << 20));
395 }
396
397 #[test]
398 fn did_exit_runs_its_handlers_once() {
399 thread_local! {
400 static N: Cell<u32> = const { Cell::new(0) };
401 }
402 let task = crate::task(std::future::pending());
403 on_lifecycle(Lifecycle::DidExit, move || {
404 assert!(task.is_finished());
405 N.with(|c| c.set(c.get() + 1));
406 });
407 dispatch_lifecycle(Lifecycle::DidExit);
408 dispatch_lifecycle(Lifecycle::DidExit);
409 assert_eq!(N.with(Cell::get), 1);
410 EXITED.store(false, std::sync::atomic::Ordering::SeqCst);
411 }
412
413 #[test]
414 fn dispatch_runs_handlers_for_the_phase_only() {
415 thread_local! {
416 static A: Cell<u32> = const { Cell::new(0) };
417 static B: Cell<u32> = const { Cell::new(0) };
418 }
419 on_lifecycle(Lifecycle::DidLaunch, || A.with(|c| c.set(c.get() + 1)));
420 on_lifecycle(Lifecycle::DidLaunch, || A.with(|c| c.set(c.get() + 1)));
421 on_lifecycle(Lifecycle::WillTerminate, || B.with(|c| c.set(c.get() + 1)));
422
423 dispatch_lifecycle(Lifecycle::DidLaunch);
424 assert_eq!(A.with(Cell::get), 2, "both DidLaunch handlers ran");
425 assert_eq!(B.with(Cell::get), 0, "WillTerminate handler did not run");
426
427 dispatch_lifecycle(Lifecycle::WillTerminate);
428 assert_eq!(B.with(Cell::get), 1);
429
430 dispatch_lifecycle(Lifecycle::DidReceiveMemoryWarning);
432 }
433
434 #[test]
435 fn panicking_handler_is_contained_and_siblings_still_run() {
436 thread_local! {
437 static RAN: Cell<u32> = const { Cell::new(0) };
438 }
439 on_lifecycle(Lifecycle::WillResignActive, || {
442 panic!("boom in a lifecycle handler")
443 });
444 on_lifecycle(Lifecycle::WillResignActive, || {
445 RAN.with(|c| c.set(c.get() + 1));
446 });
447
448 dispatch_lifecycle(Lifecycle::WillResignActive);
450 assert_eq!(
451 RAN.with(Cell::get),
452 1,
453 "the non-panicking sibling handler still ran"
454 );
455 }
456}