| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use session::App; |
| 5 | |
| 6 | pub(crate) const SLEEP_AFTER: Duration = Duration::from_secs(180); |
| 7 | |
| 8 | /// What keeps the web views running; any of these blocks closing them. |
| 9 | #[derive(Debug, Clone, Copy, Default)] |
| 10 | pub(crate) struct Activity { |
| 11 | pub restarting: bool, |
| 12 | pub all_parked: bool, |
| 13 | pub login_pending: bool, |
| 14 | pub held: bool, |
| 15 | pub in_flight: bool, |
| 16 | pub dialogs_open: bool, |
| 17 | pub subscribed: bool, |
| 18 | } |
| 19 | |
| 20 | /// Names a protocol call without its content: the method, or for a script the host and first path segments it fetches. |
| 21 | pub(crate) fn call_label(method: &str, params: &serde_json::Value) -> String { |
| 22 | if method != "Runtime.evaluate" { |
| 23 | return method.to_owned(); |
| 24 | } |
| 25 | let expression = params |
| 26 | .get("expression") |
| 27 | .and_then(serde_json::Value::as_str) |
| 28 | .unwrap_or_default(); |
| 29 | if let Some(start) = expression.find("\"url\":\"https://") { |
| 30 | let rest = &expression[start + "\"url\":\"https://".len()..]; |
| 31 | let end = rest.find(['"', '?', '\\']).unwrap_or(rest.len()); |
| 32 | return rest[..end].split('/').take(3).collect::<Vec<_>>().join("/"); |
| 33 | } |
| 34 | if expression.contains("return token;") { |
| 35 | return "token lookup".to_owned(); |
| 36 | } |
| 37 | "script".to_owned() |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Default)] |
| 41 | pub(crate) struct CallTally { |
| 42 | counts: HashMap<String, u32>, |
| 43 | } |
| 44 | |
| 45 | impl CallTally { |
| 46 | pub(crate) fn note(&mut self, label: String) { |
| 47 | *self.counts.entry(label).or_default() += 1; |
| 48 | } |
| 49 | |
| 50 | pub(crate) fn summary(&mut self) -> String { |
| 51 | let mut counts: Vec<(String, u32)> = self.counts.drain().collect(); |
| 52 | counts.sort_by(|first, second| second.1.cmp(&first.1).then_with(|| first.0.cmp(&second.0))); |
| 53 | counts |
| 54 | .iter() |
| 55 | .take(6) |
| 56 | .map(|(label, count)| format!("{label} x{count}")) |
| 57 | .collect::<Vec<_>>() |
| 58 | .join(", ") |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub(crate) fn blocker(activity: Activity) -> Option<&'static str> { |
| 63 | [ |
| 64 | (activity.restarting, "restarting"), |
| 65 | (!activity.all_parked, "an app is not parked"), |
| 66 | (activity.login_pending, "sign-in pending"), |
| 67 | (activity.held, "an app is held"), |
| 68 | (activity.in_flight, "a protocol call is running"), |
| 69 | (activity.dialogs_open, "a dialog is open"), |
| 70 | (activity.subscribed, "a tab subscriber is attached"), |
| 71 | ] |
| 72 | .into_iter() |
| 73 | .find_map(|(blocked, reason)| blocked.then_some(reason)) |
| 74 | } |
| 75 | |
| 76 | /// The web views close once both apps are parked and idle, and come back on the next protocol call, at the park page. |
| 77 | #[derive(Debug)] |
| 78 | pub(crate) struct Sleep<C> { |
| 79 | asleep: bool, |
| 80 | last_use: Instant, |
| 81 | loading: HashSet<App>, |
| 82 | queued: HashMap<App, Vec<C>>, |
| 83 | } |
| 84 | |
| 85 | impl<C> Default for Sleep<C> { |
| 86 | fn default() -> Self { |
| 87 | Sleep { |
| 88 | asleep: false, |
| 89 | last_use: Instant::now(), |
| 90 | loading: HashSet::new(), |
| 91 | queued: HashMap::new(), |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | impl<C> Sleep<C> { |
| 97 | pub(crate) fn touch(&mut self, now: Instant) { |
| 98 | self.last_use = now; |
| 99 | } |
| 100 | |
| 101 | pub(crate) fn asleep(&self) -> bool { |
| 102 | self.asleep |
| 103 | } |
| 104 | |
| 105 | pub(crate) fn should_sleep(&self, activity: Activity, now: Instant) -> bool { |
| 106 | self.quiet(now) && blocker(activity).is_none() |
| 107 | } |
| 108 | |
| 109 | /// Answers whether the views have been idle long enough to close. |
| 110 | pub(crate) fn quiet(&self, now: Instant) -> bool { |
| 111 | !self.asleep && self.loading.is_empty() && now.duration_since(self.last_use) >= SLEEP_AFTER |
| 112 | } |
| 113 | |
| 114 | pub(crate) fn fall_asleep(&mut self) { |
| 115 | self.asleep = true; |
| 116 | } |
| 117 | |
| 118 | /// Answers whether the views have to be created now. |
| 119 | pub(crate) fn wake(&mut self) -> bool { |
| 120 | if !self.asleep { |
| 121 | return false; |
| 122 | } |
| 123 | self.asleep = false; |
| 124 | self.loading = App::ALL.into_iter().collect(); |
| 125 | true |
| 126 | } |
| 127 | |
| 128 | /// A call for an app that is still loading its page waits; `Some` hands it back to run now. |
| 129 | pub(crate) fn admit(&mut self, app: App, command: C) -> Option<C> { |
| 130 | if self.loading.contains(&app) { |
| 131 | self.queued.entry(app).or_default().push(command); |
| 132 | None |
| 133 | } else { |
| 134 | Some(command) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | pub(crate) fn loaded(&mut self, app: App) -> Vec<C> { |
| 139 | self.loading.remove(&app); |
| 140 | self.queued.remove(&app).unwrap_or_default() |
| 141 | } |
| 142 | |
| 143 | pub(crate) fn reset(&mut self) -> Vec<C> { |
| 144 | self.asleep = false; |
| 145 | self.loading.clear(); |
| 146 | self.queued |
| 147 | .drain() |
| 148 | .flat_map(|(_, commands)| commands) |
| 149 | .collect() |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | #[cfg(test)] |
| 154 | mod tests { |
| 155 | use super::*; |
| 156 | |
| 157 | fn idle() -> Activity { |
| 158 | Activity { |
| 159 | all_parked: true, |
| 160 | ..Activity::default() |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | #[test] |
| 165 | fn parked_idle_views_sleep_after_the_quiet_period() { |
| 166 | let sleep: Sleep<u32> = Sleep::default(); |
| 167 | let start = sleep.last_use; |
| 168 | assert!(!sleep.should_sleep(idle(), start + SLEEP_AFTER - Duration::from_secs(1))); |
| 169 | assert!(sleep.should_sleep(idle(), start + SLEEP_AFTER)); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn a_running_app_a_login_or_any_user_keeps_them_awake() { |
| 174 | let sleep: Sleep<u32> = Sleep::default(); |
| 175 | let later = sleep.last_use + SLEEP_AFTER; |
| 176 | assert!(!sleep.should_sleep( |
| 177 | Activity { |
| 178 | all_parked: false, |
| 179 | ..idle() |
| 180 | }, |
| 181 | later |
| 182 | )); |
| 183 | for blocked in [ |
| 184 | Activity { |
| 185 | login_pending: true, |
| 186 | ..idle() |
| 187 | }, |
| 188 | Activity { |
| 189 | held: true, |
| 190 | ..idle() |
| 191 | }, |
| 192 | Activity { |
| 193 | in_flight: true, |
| 194 | ..idle() |
| 195 | }, |
| 196 | Activity { |
| 197 | dialogs_open: true, |
| 198 | ..idle() |
| 199 | }, |
| 200 | Activity { |
| 201 | subscribed: true, |
| 202 | ..idle() |
| 203 | }, |
| 204 | Activity { |
| 205 | restarting: true, |
| 206 | ..idle() |
| 207 | }, |
| 208 | ] { |
| 209 | assert!(!sleep.should_sleep(blocked, later), "{blocked:?}"); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn calls_are_named_by_what_they_fetch() { |
| 215 | let fetch = serde_json::json!({"expression": "(async () => {})({\"requests\":[{\"method\":\"GET\",\"url\":\"https://teams.cloud.microsoft/api/csa/emea/api/v1/x?y=1\"}]})"}); |
| 216 | assert_eq!( |
| 217 | call_label("Runtime.evaluate", &fetch), |
| 218 | "teams.cloud.microsoft/api/csa" |
| 219 | ); |
| 220 | let token = serde_json::json!({"expression": "x; return token;"}); |
| 221 | assert_eq!(call_label("Runtime.evaluate", &token), "token lookup"); |
| 222 | assert_eq!( |
| 223 | call_label("Page.reload", &serde_json::Value::Null), |
| 224 | "Page.reload" |
| 225 | ); |
| 226 | let mut tally = CallTally::default(); |
| 227 | tally.note("b".into()); |
| 228 | tally.note("a".into()); |
| 229 | tally.note("a".into()); |
| 230 | assert_eq!(tally.summary(), "a x2, b x1"); |
| 231 | assert_eq!(tally.summary(), ""); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn the_first_blocker_is_named() { |
| 236 | assert_eq!(blocker(idle()), None); |
| 237 | assert_eq!( |
| 238 | blocker(Activity { |
| 239 | held: true, |
| 240 | dialogs_open: true, |
| 241 | ..idle() |
| 242 | }), |
| 243 | Some("an app is held") |
| 244 | ); |
| 245 | } |
| 246 | |
| 247 | #[test] |
| 248 | fn calls_wait_for_the_page_after_waking_and_run_in_order() { |
| 249 | let mut sleep = Sleep::default(); |
| 250 | sleep.fall_asleep(); |
| 251 | assert!(sleep.wake()); |
| 252 | assert!(!sleep.wake()); |
| 253 | assert_eq!(sleep.admit(App::Teams, 1), None); |
| 254 | assert_eq!(sleep.admit(App::Teams, 2), None); |
| 255 | assert!(!sleep.should_sleep(idle(), sleep.last_use + SLEEP_AFTER)); |
| 256 | assert_eq!(sleep.loaded(App::Teams), vec![1, 2]); |
| 257 | assert_eq!(sleep.admit(App::Teams, 4), Some(4)); |
| 258 | sleep.fall_asleep(); |
| 259 | assert!(sleep.wake()); |
| 260 | assert_eq!(sleep.admit(App::Teams, 3), None); |
| 261 | assert_eq!(sleep.reset(), vec![3]); |
| 262 | assert_eq!(sleep.admit(App::Teams, 5), Some(5)); |
| 263 | } |
| 264 | } |