okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
11.6 KiB260 linesraw
1//! A page whose renderer dies is brought back, not left on the browser's error page (#5079).
2//!
3//! WebView2 (Windows) reports a dead renderer through its ProcessFailed event, and WKWebView (macOS) through
4//! `webViewWebContentProcessDidTerminate`; until now the shell listened to neither, so the window kept the browser's own "This page has a
5//! problem" page, nothing reached the log, and the person's Reload brought back the same chat that had just crashed. Linux does not need it:
6//! there the window is its own process and the shell moves to browser mode when it dies (supervisor.rs).
7//!
8//! This file is only decisions, so it builds and tests everywhere; the platform hooks are in main.rs.
9//!   - which failures are worth a reload (the page's own renderer; not a GPU process that restarts by itself, not a frame of the page);
10//!   - how many automatic recoveries are allowed in a window of time (a renderer that dies again at once is not reloaded for ever);
11//!   - where the reload goes: the same screen first, with the sidebar previews closed once; the home screen the second time.
12//! The page reads `?recovery=<n>` in apps/host/src/lib/recovery.ts. The chats are the host's: nothing here touches them.
13
14/// Automatic recoveries allowed inside `WINDOW_MS`; the next failure leaves the window as it is for the person to reload.
15pub const MAX_AUTOMATIC: usize = 2;
16/// The window of time the limit counts over.
17pub const WINDOW_MS: u64 = 120_000;
18/// Let the browser start a new renderer before the page is asked for again.
19pub const RELOAD_DELAY_MS: u64 = 400;
20
21/// WebView2's COREWEBVIEW2_PROCESS_FAILED_KIND values, by number.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Failure {
24    BrowserExited,
25    /// The renderer of the page itself.
26    RendererExited,
27    Unresponsive,
28    /// The renderer of a frame inside the page (a website preview); the page itself is alive.
29    FrameRendererExited,
30    Gpu,
31    Other(i32),
32}
33
34impl Failure {
35    pub fn from_webview2(kind: i32) -> Failure {
36        match kind {
37            0 => Failure::BrowserExited,
38            1 => Failure::RendererExited,
39            2 => Failure::Unresponsive,
40            3 => Failure::FrameRendererExited,
41            6 => Failure::Gpu,
42            other => Failure::Other(other),
43        }
44    }
45
46    /// Only the page's own renderer dying leaves a window that has to be loaded again. A GPU process is restarted by the browser, a frame
47    /// shows its own sad face, an unresponsive page may only be busy, and a dead browser process cannot navigate at all.
48    pub fn needs_reload(self) -> bool {
49        self == Failure::RendererExited
50    }
51
52    pub fn name(self) -> String {
53        match self {
54            Failure::BrowserExited => "browser process exited".into(),
55            Failure::RendererExited => "renderer exited".into(),
56            Failure::Unresponsive => "renderer unresponsive".into(),
57            Failure::FrameRendererExited => "frame renderer exited".into(),
58            Failure::Gpu => "gpu process exited".into(),
59            Failure::Other(n) => format!("process failure kind {n}"),
60        }
61    }
62}
63
64/// WebView2's COREWEBVIEW2_PROCESS_FAILED_REASON, for the log.
65pub fn reason_name(reason: i32) -> &'static str {
66    match reason {
67        0 => "unexpected",
68        1 => "unresponsive",
69        2 => "terminated",
70        3 => "crashed",
71        4 => "launch failed",
72        5 => "out of memory",
73        6 => "profile deleted",
74        _ => "unknown",
75    }
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum Action {
80    /// Load the page again; `attempt` is 1 for the first recovery of the window, 2 for the second.
81    Reload { attempt: usize },
82    /// Too many in a short time: leave the window alone.
83    Stop,
84}
85
86/// Counts recoveries over a sliding window of time. `now_ms` is any clock that only goes forward (the caller's uptime).
87#[derive(Default, Debug)]
88pub struct Guard {
89    times: Vec<u64>,
90}
91
92impl Guard {
93    pub const fn new() -> Guard {
94        Guard { times: Vec::new() }
95    }
96
97    pub fn on_failure(&mut self, now_ms: u64) -> Action {
98        self.times.retain(|t| now_ms.saturating_sub(*t) < WINDOW_MS);
99        if self.times.len() >= MAX_AUTOMATIC {
100            return Action::Stop;
101        }
102        self.times.push(now_ms);
103        Action::Reload { attempt: self.times.len() }
104    }
105}
106
107/// The address a recovery loads. The first goes back to the screen that died (its `#/...` part) with `?recovery=1`, which makes the page
108/// start with the sidebar previews closed once; the second goes to the home screen, in case the screen itself is what crashes.
109/// `failed` is the address the window was showing; it is used only when it is on `origin`.
110pub fn recovery_url(origin: &str, attempt: usize, failed: Option<&str>) -> String {
111    let origin = origin.trim_end_matches('/');
112    let base = format!("{origin}/?recovery={}", attempt.clamp(1, 9));
113    if attempt > 1 {
114        return base;
115    }
116    let Some(failed) = failed else { return base };
117    // on this origin: after it comes the end, a path, a query or a fragment (not another digit of a longer port)
118    let rest = match failed.strip_prefix(origin) {
119        Some(rest) if rest.is_empty() || rest.starts_with(['/', '?', '#']) => rest,
120        _ => return base,
121    };
122    match rest.find('#') {
123        Some(at) => {
124            let hash = &rest[at..];
125            // only what a page address holds: no spaces, quotes, angle brackets or control characters
126            let safe = hash.len() < 2048 && hash.starts_with("#/") && hash.chars().all(|c| c.is_ascii_graphic() && !matches!(c, '"' | '<' | '>' | '\\' | '`' | '{' | '}' | '|' | '^'));
127            if safe { format!("{base}{hash}") } else { base }
128        }
129        None => base,
130    }
131}
132
133/// What the shell does about one failure report.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub enum Plan {
136    /// Not a failure that leaves the window needing a reload: only logged.
137    Ignore,
138    /// A reload is due, to `url`.
139    Reload { attempt: usize, url: String },
140    /// Too many recent recoveries: the window is left as it is.
141    Stop,
142}
143
144/// One failure report in, the decision out. The platform hooks (main.rs) only collect the facts and carry the decision out.
145pub fn plan(guard: &mut Guard, now_ms: u64, origin: &str, failure: Failure, failed: Option<&str>) -> Plan {
146    if !failure.needs_reload() {
147        return Plan::Ignore;
148    }
149    match guard.on_failure(now_ms) {
150        Action::Stop => Plan::Stop,
151        Action::Reload { attempt } => Plan::Reload { attempt, url: recovery_url(origin, attempt, failed) },
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn only_the_pages_own_renderer_is_reloaded() {
161        assert!(Failure::from_webview2(1).needs_reload());
162        for kind in [0, 2, 3, 4, 5, 6, 7, 8, 9, 42] {
163            assert!(!Failure::from_webview2(kind).needs_reload(), "kind {kind}");
164        }
165        assert_eq!(Failure::from_webview2(6), Failure::Gpu);
166        assert_eq!(Failure::from_webview2(1).name(), "renderer exited");
167        assert_eq!(Failure::from_webview2(42).name(), "process failure kind 42");
168    }
169
170    #[test]
171    fn reasons_are_named_for_the_log() {
172        assert_eq!(reason_name(5), "out of memory");
173        assert_eq!(reason_name(3), "crashed");
174        assert_eq!(reason_name(99), "unknown");
175    }
176
177    #[test]
178    fn two_recoveries_in_two_minutes_then_the_window_is_left_alone() {
179        let mut g = Guard::new();
180        assert_eq!(g.on_failure(1_000), Action::Reload { attempt: 1 });
181        assert_eq!(g.on_failure(5_000), Action::Reload { attempt: 2 });
182        assert_eq!(g.on_failure(6_000), Action::Stop);
183        assert_eq!(g.on_failure(100_000), Action::Stop);
184        // the first has left the window: one more is allowed, and it is the second of the window
185        assert_eq!(g.on_failure(1_000 + WINDOW_MS), Action::Reload { attempt: 2 });
186        assert_eq!(g.on_failure(1_000 + WINDOW_MS + 1), Action::Stop);
187    }
188
189    #[test]
190    fn a_renderer_that_dies_later_starts_over_at_the_first_recovery() {
191        let mut g = Guard::new();
192        assert_eq!(g.on_failure(0), Action::Reload { attempt: 1 });
193        assert_eq!(g.on_failure(10), Action::Reload { attempt: 2 });
194        assert_eq!(g.on_failure(WINDOW_MS + 100), Action::Reload { attempt: 1 });
195    }
196
197    #[test]
198    fn a_stopped_loop_stays_stopped_until_the_window_has_passed() {
199        let mut g = Guard::new();
200        let mut reloads = 0;
201        // a renderer that dies every second for ten minutes: never more than two reloads in any two-minute window
202        let mut loaded = Vec::new();
203        for second in 0..600u64 {
204            if let Action::Reload { .. } = g.on_failure(second * 1_000) {
205                reloads += 1;
206                loaded.push(second);
207            }
208        }
209        assert!(reloads <= 2 * (600 / (WINDOW_MS / 1_000) as usize + 1));
210        for w in loaded.windows(3) {
211            assert!(w[2] - w[0] >= WINDOW_MS / 1_000, "three reloads inside one window: {w:?}");
212        }
213    }
214
215    #[test]
216    fn the_first_recovery_keeps_the_screen_and_the_second_goes_home() {
217        let o = "http://127.0.0.1:47831";
218        assert_eq!(recovery_url(o, 1, Some("http://127.0.0.1:47831/#/chat/s_abc")), "http://127.0.0.1:47831/?recovery=1#/chat/s_abc");
219        assert_eq!(recovery_url(o, 1, Some("http://127.0.0.1:47831/?recovery=1#/chat/s_abc")), "http://127.0.0.1:47831/?recovery=1#/chat/s_abc");
220        assert_eq!(recovery_url(o, 2, Some("http://127.0.0.1:47831/#/chat/s_abc")), "http://127.0.0.1:47831/?recovery=2");
221        assert_eq!(recovery_url(o, 1, None), "http://127.0.0.1:47831/?recovery=1");
222        assert_eq!(recovery_url("http://127.0.0.1:47831/", 1, None), "http://127.0.0.1:47831/?recovery=1");
223    }
224
225    #[test]
226    fn an_address_that_is_not_ours_or_not_plain_is_not_carried_over() {
227        let o = "http://127.0.0.1:47831";
228        for failed in [
229            "https://example.com/#/chat/x",
230            "http://127.0.0.1:47832/#/chat/x",
231            "http://127.0.0.1:47831/#/chat/x y",
232            "http://127.0.0.1:47831/#/chat/\"onload=",
233            "http://127.0.0.1:47831/#/chat/<script>",
234            "http://127.0.0.1:47831/#nothing",
235            "http://127.0.0.1:47831/#/chat/\u{e9}",
236            "chrome-error://chromewebdata/",
237        ] {
238            assert_eq!(recovery_url(o, 1, Some(failed)), "http://127.0.0.1:47831/?recovery=1", "{failed}");
239        }
240        let long = format!("http://127.0.0.1:47831/#/{}", "a".repeat(3000));
241        assert_eq!(recovery_url(o, 1, Some(&long)), "http://127.0.0.1:47831/?recovery=1");
242        // a look-alike host is not the origin
243        assert_eq!(recovery_url(o, 1, Some("http://127.0.0.1:478310/#/chat/x")), "http://127.0.0.1:47831/?recovery=1");
244    }
245
246    #[test]
247    fn a_failure_report_becomes_one_decision() {
248        let o = "http://127.0.0.1:47831";
249        let mut g = Guard::new();
250        let chat = Some("http://127.0.0.1:47831/#/chat/s_1");
251        // a GPU process or a frame going down never costs the person their page, and does not use up the allowance
252        assert_eq!(plan(&mut g, 0, o, Failure::Gpu, chat), Plan::Ignore);
253        assert_eq!(plan(&mut g, 1, o, Failure::FrameRendererExited, chat), Plan::Ignore);
254        assert_eq!(plan(&mut g, 2, o, Failure::Unresponsive, chat), Plan::Ignore);
255        assert_eq!(plan(&mut g, 3, o, Failure::BrowserExited, chat), Plan::Ignore);
256        assert_eq!(plan(&mut g, 1_000, o, Failure::RendererExited, chat), Plan::Reload { attempt: 1, url: "http://127.0.0.1:47831/?recovery=1#/chat/s_1".into() });
257        assert_eq!(plan(&mut g, 4_000, o, Failure::RendererExited, chat), Plan::Reload { attempt: 2, url: "http://127.0.0.1:47831/?recovery=2".into() });
258        assert_eq!(plan(&mut g, 7_000, o, Failure::RendererExited, chat), Plan::Stop);
259    }
260}