1use std::collections::HashSet;
21use std::sync::Arc;
22use std::time::Duration;
23
24use super::AppState;
25use crate::backend::obj::{self, Block, Workspace};
26use crate::backend::rpc_types::FleetBroadcastProgressEvent;
27use crate::backend::storage::store::Store;
28
29pub(crate) const COST_ON_SCREEN: f32 = 1.0;
32pub(crate) const COST_OFF_SCREEN: f32 = 0.25;
35pub(crate) const COST_NONE: f32 = 0.0;
38
39const BURST: f32 = 2.0;
41const GAP: Duration = Duration::from_millis(400);
44const JITTER: f64 = 0.2;
47pub(crate) const CEILING: Duration = Duration::from_secs(6);
50
51pub(crate) fn start_offsets(costs: &[f32], mut noise: impl FnMut() -> f64) -> Vec<Duration> {
55 let total: f32 = costs.iter().map(|c| c.max(0.0)).sum();
56 let paced = (total - BURST).max(0.0) as f64;
57 let gap = if paced > 0.0 { GAP.as_secs_f64().min(CEILING.as_secs_f64() / paced) } else { 0.0 };
59 let mut spent = 0.0_f32;
60 costs
61 .iter()
62 .map(|cost| {
63 let cost = cost.max(0.0);
64 spent += cost;
65 let over = (spent - BURST) as f64;
66 if cost == 0.0 || over <= 0.0 {
67 return Duration::ZERO;
68 }
69 let jitter = (noise().clamp(0.0, 1.0) * 2.0 - 1.0) * JITTER * gap * cost as f64;
70 let at_ms = ((over * gap + jitter) * 1000.0).round().clamp(0.0, CEILING.as_millis() as f64);
72 Duration::from_millis(at_ms as u64)
73 })
74 .collect()
75}
76
77pub(crate) fn noise_from(seed: u64) -> impl FnMut() -> f64 {
80 let mut state = seed;
81 move || {
82 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
83 let mut z = state;
84 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
85 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
86 z ^= z >> 31;
87 (z >> 11) as f64 / (1u64 << 53) as f64
88 }
89}
90
91type Progress = Arc<dyn Fn(usize, usize) + Send + Sync>;
93
94pub(crate) struct Pace {
97 offsets: Vec<Duration>,
98 began: tokio::time::Instant,
99 progress: Option<Progress>,
100}
101
102impl Pace {
103 pub(crate) fn at_once() -> Self {
105 Self::new(Vec::new(), None)
106 }
107
108 pub(crate) fn new(offsets: Vec<Duration>, progress: Option<Progress>) -> Self {
110 Self { offsets, began: tokio::time::Instant::now(), progress }
111 }
112
113 pub(crate) async fn until_start(&self, index: usize) {
115 if let Some(offset) = self.offsets.get(index).filter(|d| !d.is_zero()) {
116 tokio::time::sleep_until(self.began + *offset).await;
117 }
118 }
119
120 pub(crate) fn ended(&self, done: usize, total: usize) {
122 if let Some(progress) = &self.progress {
123 progress(done, total);
124 }
125 }
126}
127
128pub(crate) fn blocks_on_screen(store: &Store, block_ids: &[String]) -> HashSet<String> {
131 let windows = store.get_all::<obj::Window>().unwrap_or_default();
132 let shown_tabs: HashSet<String> = store
133 .get_all::<Workspace>()
134 .unwrap_or_default()
135 .into_iter()
136 .filter(|ws| !ws.activetabid.is_empty() && windows.iter().any(|w| w.workspaceid == ws.oid))
137 .map(|ws| ws.activetabid)
138 .collect();
139 block_ids
140 .iter()
141 .filter(|id| {
142 let tab = store.get::<Block>(id).ok().flatten().and_then(|b| b.parentoref.strip_prefix("tab:").map(str::to_string));
143 tab.is_some_and(|t| shown_tabs.contains(&t))
144 })
145 .cloned()
146 .collect()
147}
148
149pub(crate) fn costs_of(targets: &[String], local: &HashSet<String>, on_screen: &HashSet<String>) -> Vec<f32> {
152 targets
153 .iter()
154 .map(|t| match (local.contains(t), on_screen.contains(t)) {
155 (true, true) => COST_ON_SCREEN,
156 (true, false) => COST_OFF_SCREEN,
157 (false, _) => COST_NONE,
158 })
159 .collect()
160}
161
162const PROGRESS_ID_MAX: usize = 64;
164
165pub(crate) async fn pace_for(state: &AppState, targets: &[String], local: HashSet<String>, msg_id: &str, progress_id: Option<String>) -> Pace {
169 let (store, ids) = (state.mstore.clone(), local.iter().cloned().collect::<Vec<_>>());
170 let on_screen = tokio::task::spawn_blocking(move || blocks_on_screen(&store, &ids)).await.unwrap_or_default();
172 let seed = uuid::Uuid::parse_str(msg_id).map(|id| id.as_u128() as u64).unwrap_or_default();
173 let offsets = start_offsets(&costs_of(targets, &local, &on_screen), noise_from(seed));
174 let progress = progress_id.filter(|id| !id.is_empty() && id.len() <= PROGRESS_ID_MAX).map(|id| {
175 let broker = state.broker.clone();
176 Arc::new(move |done: usize, total: usize| {
177 let event = FleetBroadcastProgressEvent { id: id.clone(), sent: done as u32, total: total as u32 };
178 broker.publish_event::<crate::backend::mps_events::FleetBroadcastProgress>(&event, vec![], 0);
179 }) as Progress
180 });
181 Pace::new(offsets, progress)
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 fn ms(costs: &[f32]) -> Vec<u64> {
189 start_offsets(costs, || 0.5).iter().map(|d| d.as_millis() as u64).collect()
190 }
191
192 #[test]
193 fn one_or_two_agents_get_it_at_once() {
194 assert_eq!(ms(&[COST_ON_SCREEN]), vec![0]);
195 assert_eq!(ms(&[COST_ON_SCREEN, COST_ON_SCREEN]), vec![0, 0]);
196 assert!(ms(&[]).is_empty());
197 }
198
199 #[test]
200 fn past_the_burst_the_starts_follow_at_a_steady_rate() {
201 assert_eq!(ms(&[COST_ON_SCREEN; 5]), vec![0, 0, 400, 800, 1200]);
202 }
203
204 #[test]
205 fn thirty_panes_on_screen_finish_at_the_ceiling_not_after_it() {
206 let offsets = ms(&[COST_ON_SCREEN; 30]);
207 assert_eq!(&offsets[..2], &[0, 0]);
208 assert_eq!(*offsets.last().unwrap(), CEILING.as_millis() as u64);
209 assert!(offsets.windows(2).all(|w| w[0] <= w[1]));
210 assert_eq!(offsets[2], 214);
212 }
213
214 #[test]
215 fn a_target_that_costs_nothing_is_never_delayed_wherever_it_sits() {
216 let costs = [COST_ON_SCREEN, COST_NONE, COST_ON_SCREEN, COST_ON_SCREEN, COST_NONE, COST_ON_SCREEN];
217 assert_eq!(ms(&costs), vec![0, 0, 0, 400, 0, 800]);
218 assert_eq!(ms(&[COST_NONE; 40]), vec![0; 40]);
219 }
220
221 #[test]
222 fn a_pane_no_window_shows_takes_a_quarter_of_a_slot() {
223 let costs = [COST_ON_SCREEN, COST_ON_SCREEN, COST_OFF_SCREEN, COST_OFF_SCREEN, COST_OFF_SCREEN, COST_OFF_SCREEN, COST_ON_SCREEN];
224 assert_eq!(ms(&costs), vec![0, 0, 100, 200, 300, 400, 800]);
225 }
226
227 #[test]
229 fn fourteen_panes_among_thirty_one_targets_start_over_about_five_seconds() {
230 let mut costs = vec![COST_NONE; 31];
231 for c in costs.iter_mut().step_by(2).take(14) {
232 *c = COST_ON_SCREEN;
233 }
234 let offsets = ms(&costs);
235 let on_screen: Vec<u64> = offsets.iter().zip(&costs).filter(|(_, c)| **c > 0.0).map(|(o, _)| *o).collect();
236 assert_eq!(on_screen.len(), 14);
237 assert_eq!(on_screen.last(), Some(&4800));
238 for (i, at) in on_screen.iter().enumerate() {
240 let in_the_next_second = on_screen[i..].iter().filter(|o| **o < at + 1000).count();
241 assert!(in_the_next_second <= 4, "{in_the_next_second} starts within a second of {at} ms");
242 }
243 assert!(offsets.iter().zip(&costs).filter(|(_, c)| **c == 0.0).all(|(o, _)| *o == 0));
244 }
245
246 #[test]
247 fn jitter_moves_a_start_by_a_fifth_of_its_gap_at_most_and_never_before_the_send_or_past_the_ceiling() {
248 let early: Vec<u64> = start_offsets(&[COST_ON_SCREEN; 5], || 0.0).iter().map(|d| d.as_millis() as u64).collect();
249 let late: Vec<u64> = start_offsets(&[COST_ON_SCREEN; 5], || 1.0).iter().map(|d| d.as_millis() as u64).collect();
250 assert_eq!(early, vec![0, 0, 320, 720, 1120]);
251 assert_eq!(late, vec![0, 0, 480, 880, 1280]);
252 let capped = start_offsets(&[COST_ON_SCREEN; 30], || 1.0);
253 assert!(capped.iter().all(|d| *d <= CEILING));
254 assert_eq!(start_offsets(&[COST_ON_SCREEN; 3], || 7.0)[2].as_millis(), 480);
256 }
257
258 #[test]
259 fn the_noise_is_repeatable_per_seed_and_stays_in_range() {
260 let mut a = noise_from(42);
261 let mut b = noise_from(42);
262 let mut c = noise_from(43);
263 let first: Vec<f64> = (0..50).map(|_| a()).collect();
264 assert_eq!(first, (0..50).map(|_| b()).collect::<Vec<f64>>());
265 assert_ne!(first, (0..50).map(|_| c()).collect::<Vec<f64>>());
266 assert!(first.iter().all(|v| (0.0..1.0).contains(v)));
267 assert!(first.iter().any(|v| *v < 0.5) && first.iter().any(|v| *v > 0.5));
269 }
270
271 fn tab_in(store: &Store, active: bool, with_window: bool) -> String {
272 use crate::backend::obj::Tab;
273 let mut shown = Tab { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
274 let mut other = Tab { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
275 store.insert(&mut shown).unwrap();
276 store.insert(&mut other).unwrap();
277 let mut ws = Workspace { oid: uuid::Uuid::new_v4().to_string(), tabids: vec![shown.oid.clone(), other.oid.clone()], activetabid: shown.oid.clone(), ..Default::default() };
278 store.insert(&mut ws).unwrap();
279 if with_window {
280 let mut w = obj::Window { oid: uuid::Uuid::new_v4().to_string(), workspaceid: ws.oid.clone(), ..Default::default() };
281 store.insert(&mut w).unwrap();
282 }
283 if active { shown.oid } else { other.oid }
284 }
285
286 fn block_in(store: &Store, tab_id: &str) -> String {
287 let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), parentoref: format!("tab:{tab_id}"), ..Default::default() };
288 store.insert(&mut block).unwrap();
289 block.oid
290 }
291
292 #[test]
293 fn a_pane_is_on_screen_only_in_the_active_tab_of_a_workspace_a_window_shows() {
294 let store = Store::open_in_memory().unwrap();
295 let shown = block_in(&store, &tab_in(&store, true, true));
296 let background_tab = block_in(&store, &tab_in(&store, false, true));
297 let no_window = block_in(&store, &tab_in(&store, true, false));
298 let ids = vec![shown.clone(), background_tab, no_window, "no-such-block".to_string()];
299 assert_eq!(blocks_on_screen(&store, &ids), HashSet::from([shown]));
300 assert!(blocks_on_screen(&store, &[]).is_empty());
301 }
302
303 #[test]
304 fn a_target_costs_by_where_its_turn_runs_and_whether_a_window_shows_it() {
305 let targets: Vec<String> = ["shown", "hidden", "remote"].iter().map(|s| s.to_string()).collect();
306 let local = HashSet::from(["shown".to_string(), "hidden".to_string()]);
307 let on_screen = HashSet::from(["shown".to_string()]);
308 assert_eq!(costs_of(&targets, &local, &on_screen), vec![COST_ON_SCREEN, COST_OFF_SCREEN, COST_NONE]);
309 }
310
311 fn ids(n: usize) -> Vec<String> {
312 (0..n).map(|i| format!("blk-{i}")).collect()
313 }
314
315 async fn paced_run(n: usize, each: Duration) -> (Vec<u64>, Vec<(usize, usize)>) {
318 use std::sync::Mutex;
319 let began = tokio::time::Instant::now();
320 let starts: Arc<Mutex<Vec<(String, u64)>>> = Arc::default();
321 let reports: Arc<Mutex<Vec<(usize, usize)>>> = Arc::default();
322 let (starts2, reports2) = (starts.clone(), reports.clone());
323 let pace = Pace::new(start_offsets(&vec![COST_ON_SCREEN; n], || 0.5), Some(Arc::new(move |done: usize, total: usize| reports2.lock().unwrap().push((done, total)))));
324 let out = super::super::fleet::run_broadcast(ids(n), "x", "m", pace, |b| Some(format!("agent-{b}")), move |block, _text, _origin| {
325 starts2.lock().unwrap().push((block, began.elapsed().as_millis() as u64));
326 async move {
327 tokio::time::sleep(each).await;
328 Ok(())
329 }
330 })
331 .await;
332 assert_eq!(out.iter().map(|o| o.block_id.clone()).collect::<Vec<_>>(), ids(n), "outcomes come back in target order");
333 let starts = starts.lock().unwrap();
334 let at = |id: &String| starts.iter().find(|(b, _)| b == id).map(|(_, ms)| *ms).unwrap();
335 let in_order = ids(n).iter().map(at).collect();
336 let reports = reports.lock().unwrap().clone();
337 (in_order, reports)
338 }
339
340 #[tokio::test(start_paused = true)]
341 async fn deliveries_start_at_their_paced_times_and_the_sender_hears_of_each() {
342 let (starts, reports) = paced_run(5, Duration::ZERO).await;
343 assert_eq!(starts, vec![0, 0, 400, 800, 1200]);
344 assert_eq!(reports, vec![(1, 5), (2, 5), (3, 5), (4, 5), (5, 5)]);
345 }
346
347 #[tokio::test(start_paused = true)]
349 async fn a_slow_delivery_holds_up_no_other() {
350 let (starts, reports) = paced_run(5, Duration::from_secs(2)).await;
351 assert_eq!(starts, vec![0, 0, 400, 800, 1200]);
352 assert_eq!(reports.last(), Some(&(5, 5)));
353 }
354
355 #[tokio::test(start_paused = true)]
356 async fn two_agents_are_sent_to_at_once() {
357 let (starts, reports) = paced_run(2, Duration::ZERO).await;
358 assert_eq!(starts, vec![0, 0]);
359 assert_eq!(reports, vec![(1, 2), (2, 2)]);
360 }
361}