BlueGit

ict rusty-teams

Files

rusty-teams / crates / webview / src / sleep.rs

sleep.rs

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