Skip to main content

day_core/
lifecycle.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! App-lifecycle callbacks (docs/lifecycle.md). An app registers closures for [`day_spec::Lifecycle`]
5//! phases with [`on_lifecycle`]; each backend, at the matching moment in its native app/activity
6//! delegate, emits `Event::Lifecycle(phase)` (or day-core dispatches the launch phases uniformly),
7//! and the event pump routes it here to run the closures inside a reactive batch, the same rails
8//! as `Event::MenuAction`, so a lifecycle handler that writes signals updates the UI like any
9//! callback.
10//!
11//! Not every platform has every phase (a desktop app doesn't really enter the background), so a
12//! handler registered for a phase the running backend doesn't deliver gets a one-time warning, and
13//! apps can guard with [`lifecycle_supported`] (runtime) or `day::require_lifecycle!` (compile time).
14
15use std::cell::RefCell;
16use std::collections::HashMap;
17use std::rc::Rc;
18
19use day_spec::Lifecycle;
20
21/// The registered handlers for one phase.
22type 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    /// Phases we've already warned about being unsupported (warn once, not per-handler).
29    static WARNED: RefCell<std::collections::HashSet<Lifecycle>> =
30        RefCell::new(std::collections::HashSet::new());
31}
32
33/// `DidExit` was delivered (it is delivered once). Process-global rather than thread-local:
34/// the delivery from `atexit` can run after the thread-locals are gone.
35static EXITED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
36/// What the exit line names: the app's display name, its version, and when it launched.
37/// Process-global for the same reason.
38static 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
47/// Record the app's name and version for the exit line, and start its clock. Called by
48/// `launch_with` before `WillLaunch`.
49pub 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
61/// Day's last line: `Clean exit for <app> v<version> (<profile>) after HH:MM:SS. Memory usage:
62/// <n> MB`. The version is the app's (`WindowOptions::version`), else the `DAY_APP_VERSION` the
63/// CLI sets on a launch; the profile is this build's; the time is since `launch_with`; the memory
64/// is the process's resident set, where the platform tells (`resident_memory`).
65fn 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
98/// The exit line's text; see `exit_summary`. Factored for the test below.
99fn 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/// The process's resident memory in bytes, from the platform's own accounting: the task's
123/// physical footprint on Apple platforms, the resident set from `/proc` on Linux and its
124/// relatives, the working set on Windows, the linear memory on wasm. `None` where none is
125/// readable, which the exit line reports as unknown.
126#[must_use]
127pub fn resident_memory() -> Option<u64> {
128    #[cfg(any(target_os = "macos", target_os = "ios"))]
129    {
130        // task_info(TASK_VM_INFO): `phys_footprint` is what Xcode's memory gauge shows.
131        #[repr(C)]
132        struct TaskVmInfo {
133            // The struct is long; only the fields up to `phys_footprint` matter here, and
134            // `task_info` fills as many bytes as asked for.
135            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        // SAFETY: `task_info` writes at most `count` 32-bit words into `info`, which is sized to
164        // hold them, and reports what it wrote back in `count`.
165        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        // SAFETY: a zero return means the kernel filled the structure.
177        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        // /proc/self/statm: size resident shared text lib data dt, in pages.
194        let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
195        let resident: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
196        // SAFETY: sysconf reads a system constant and has no preconditions.
197        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        // SAFETY: the counters structure is sized by `cb`, and the pseudo-handle needs no
227        // closing.
228        let ok = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), counters.as_mut_ptr(), cb) };
229        if ok == 0 {
230            return None;
231        }
232        // SAFETY: a non-zero return means the structure was filled.
233        return Some(unsafe { counters.assume_init() }.working_set_size as u64);
234    }
235    #[cfg(target_arch = "wasm32")]
236    {
237        // The linear memory's size in 64 KiB pages: what the module has asked the host for.
238        return Some(core::arch::wasm32::memory_size(0) as u64 * 65536);
239    }
240    #[allow(unreachable_code)]
241    None
242}
243
244/// Forget every registered handler: a re-mount (docs/settings.md "Appearance on Android").
245/// The app's `root()` is about to run again and re-register, and handlers left from the
246/// previous mount would fire a second time for every phase.
247pub fn reset_handlers() {
248    HANDLERS.with(|h| h.borrow_mut().clear());
249    WARNED.with(|w| w.borrow_mut().clear());
250}
251
252/// Register `f` to run whenever the app reaches `phase`. Handlers run in registration order, in a
253/// reactive batch (signal writes coalesce into one UI update). Register early (before `launch`, or
254/// at the top of the root builder) so `WillLaunch`/`DidLaunch` handlers are in place when they
255/// fire.
256///
257/// If the running backend doesn't deliver `phase` (e.g. `DidEnterBackground` on desktop), the handler
258/// is kept but will never run, and a one-time warning is logged. Prefer guarding the registration with
259/// [`lifecycle_supported`] or the `day::require_lifecycle!` compile-time check.
260pub 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 the backend is already up we can check support now; otherwise `launch_with` sweeps
263    // pre-registered phases once the tree exists (see `warn_unsupported_registrations`).
264    if crate::tree::has_tree() {
265        warn_if_unsupported(phase);
266    }
267}
268
269/// Run every handler registered for `phase`, in a reactive batch. Called by the event pump on
270/// `Event::Lifecycle`, and directly by `launch_with` for the launch phases and for `DidExit`.
271///
272/// `DidExit` is delivered once: the first delivery runs the handlers and then writes Day's exit
273/// line (`exit_summary`), and any later one is dropped, since a backend may emit it at its last
274/// native moment and `launch_with` emits it again when the loop returns.
275pub fn dispatch_lifecycle(phase: Lifecycle) {
276    // The last moment the windows still answer for their frames (docs/windows.md
277    // "Remembered frames"); a platform that ends the app itself (AppKit's terminate) passes here.
278    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        // From `atexit` the thread-locals may already be gone (Rust tears them down at exit
287        // too, in an order nobody controls); the handlers need them, the line does not.
288        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            // Lifecycle callbacks run inside native trampolines (applicationWillTerminate,
308            // GApplication::shutdown, the Android onDestroy JNI frame, …) that abort the process on
309            // unwind. Contain each handler like the event pump does (DESIGN.md §8.5): a panic here
310            // (classically an `eprintln!` hitting a closed stderr pipe during teardown) would
311            // otherwise turn a clean exit into a spurious crash. `notify_contained_panic` runs
312            // per-panic so a crash reporter (day-piece-crash-reporter) downgrades that handler's report to
313            // contained, not fatal.
314            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    // Reset the reactive runtime after the batch closes: `recover_from_panic` rewrites the batch
325    // depth, so calling it mid-batch underflows the close.
326    if any_panicked {
327        day_reactive::recover_from_panic();
328    }
329}
330
331/// Does the running backend deliver `phase`? Use this to guard registration at runtime:
332/// `if day::lifecycle_supported(Lifecycle::DidEnterBackground) { on_lifecycle(...) }`.
333///
334/// Returns the universal answer (`phase.is_universal()`) if called before the backend is up.
335#[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
359/// Warn once for every ALREADY-registered phase the (now-known) backend doesn't deliver. Called by
360/// `launch_with` right after the backend/tree is installed, covering handlers registered before launch.
361pub 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        // Every platform the tests run on has a probe; the test process is at least a megabyte.
394        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        // A phase with no handlers is a silent no-op.
431        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        // A handler that panics (e.g. an `eprintln!` on a broken stderr pipe during teardown) must
440        // not propagate; dispatch runs inside a native trampoline that would abort on unwind.
441        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        // Returns normally (containment) rather than unwinding, and the sibling still ran.
449        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}