ntex_server/balance.rs
1use std::hash::{BuildHasher, RandomState};
2use std::time::{Duration, Instant};
3
4use ntex_rt::Id;
5use ntex_util::HashMap;
6
7use crate::Worker;
8
9/// How the server distributes items between workers.
10#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum LoadBalancing {
13 /// Items are sent to the workers in turn.
14 ///
15 /// Workers whose runtime is blocked by a task are skipped while another
16 /// worker is available.
17 RoundRobin,
18 /// Each item is sent to the less loaded of two randomly chosen workers.
19 ///
20 /// A worker's load is its runtime utilization, averaged over the last
21 /// ~250 ms and not counting the time the runtime is blocked by a task.
22 /// Workers whose utilization differs by less than 10% are compared
23 /// by their open connections plus queued items. Workers whose runtime
24 /// is blocked by a task are skipped while another worker is available.
25 LeastLoaded,
26 /// Each connection is sent to the worker placed on the CPU that receives
27 /// its network packets, unless that worker is busier than other workers.
28 ///
29 /// The worker on the incoming CPU, or on an SMT sibling of it if no worker
30 /// is placed on that CPU, is used if its utilization exceeds the
31 /// [`LeastLoaded`](Self::LeastLoaded) choice by at most 20% and its load by
32 /// at most half plus 16. Otherwise, and for items without a known
33 /// incoming CPU, it works like [`LeastLoaded`](Self::LeastLoaded).
34 ///
35 /// The incoming CPU is the receive-side scaling (RSS) CPU of the
36 /// connection on Windows, known for connections over network adapters
37 /// with RSS, and the CPU that processed the connection's last packet
38 /// (`SO_INCOMING_CPU`) on Linux and Android. Requires worker affinity, see
39 /// [`Affinity`](crate::Affinity).
40 ///
41 /// This is the default.
42 #[default]
43 IncomingCpu,
44 /// Each worker accepts connections on its own TCP listener.
45 ///
46 /// Every TCP listener is replicated with `SO_REUSEPORT`, one socket per
47 /// worker, and each worker accepts on its own socket on its own thread,
48 /// so connections do not pass through an accept thread. A worker accepts
49 /// only while its service is ready, e.g. below the
50 /// [`max_connections`](crate::net::ServerBuilder::max_connections) limit,
51 /// otherwise connections wait in its socket's listen backlog.
52 ///
53 /// The kernel chooses the socket of a new connection. A socket of a
54 /// worker placed on a CPU has `SO_INCOMING_CPU` set to that CPU, so the
55 /// connection goes to the worker on the CPU that processes its packets,
56 /// with Linux 6.1 or later. Otherwise, and for packets processed on a
57 /// CPU without a worker, the kernel chooses by a hash of the connection
58 /// address. Spread the network interrupts, e.g. with RSS or RPS, over
59 /// the worker CPUs, see [`Affinity`](crate::Affinity).
60 ///
61 /// Connections are not rebalanced: connections waiting for a busy or
62 /// restarting worker are not taken by other workers. Connections queued
63 /// on a socket are reset when the server stops.
64 ///
65 /// Requires Linux or Android and the native `polling` or `io-uring`
66 /// runtime. Otherwise, and for Unix domain sockets and items submitted
67 /// with [`Server::process`](crate::Server::process), it works like
68 /// [`IncomingCpu`](Self::IncomingCpu).
69 Reuseport,
70}
71
72/// Minimum interval between worker load samples.
73const REFRESH: Duration = Duration::from_millis(10);
74/// Time constant of the utilization average.
75const TAU: Duration = Duration::from_millis(250);
76/// A runtime turn longer than this marks the worker as blocked.
77const BLOCKED: Duration = Duration::from_millis(100);
78/// Utilization difference below which workers are compared by load.
79const UTIL_SLACK: f64 = 0.1;
80/// Utilization by which the worker on the incoming CPU may exceed the
81/// least loaded choice.
82const LOCAL_UTIL_SLACK: f64 = 0.2;
83/// Load by which the worker on the incoming CPU may exceed the least loaded
84/// choice, on top of half of that choice's load.
85const LOCAL_LOAD_SLACK: usize = 16;
86
87#[derive(Copy, Clone, Debug, Default)]
88/// Worker runtime sample.
89pub(crate) struct Sample {
90 /// Total time the runtime has been busy, including the current turn.
91 busy: Option<Duration>,
92 /// How long the current runtime turn has been running.
93 turn: Duration,
94 /// The runtime is blocked by a task.
95 blocked: bool,
96}
97
98impl Sample {
99 fn of<T>(wrk: &Worker<T>, now: Instant) -> Sample {
100 let arb = wrk.arbiter();
101 let hnd = arb.handle();
102 let turn = hnd.current_turn().unwrap_or_default();
103 let blocked = turn >= BLOCKED
104 || arb.latency().is_some_and(|l| {
105 l.stalled
106 || l.last_sample
107 .is_some_and(|t| now.saturating_duration_since(t) >= l.interval + BLOCKED)
108 });
109 Sample {
110 busy: hnd.busy_duration(),
111 turn,
112 blocked,
113 }
114 }
115}
116
117#[derive(Debug, Default)]
118struct State {
119 busy: Option<Duration>,
120 at: Option<Instant>,
121 util: f64,
122 blocked: bool,
123}
124
125impl State {
126 fn update(&mut self, sample: Sample, now: Instant) {
127 // the busy time is taken at the start of the current turn, a turn
128 // counts once it ends
129 let busy = sample.busy.map(|b| b.saturating_sub(sample.turn));
130 let now = now.checked_sub(sample.turn).unwrap_or(now);
131 // a blocked worker is skipped, the time it is blocked is not load
132 if !self.blocked
133 && !sample.blocked
134 && let (Some(busy), Some(prev), Some(at)) = (busy, self.busy, self.at)
135 {
136 let dt = now.saturating_duration_since(at);
137 if !dt.is_zero() {
138 let used = busy.saturating_sub(prev).as_secs_f64() / dt.as_secs_f64();
139 let alpha = dt.as_secs_f64() / (TAU + dt).as_secs_f64();
140 self.util += alpha * (used.min(1.0) - self.util);
141 }
142 }
143 self.busy = busy;
144 self.at = Some(now);
145 self.blocked = sample.blocked;
146 }
147}
148
149#[derive(Debug)]
150/// Selects the worker for the next item.
151///
152/// Keeps a load state per worker, in the order of the manager's worker list.
153pub(crate) struct Balancer {
154 mode: LoadBalancing,
155 next: usize,
156 states: Vec<State>,
157 /// Indexes of the workers that are not blocked.
158 ready: Vec<usize>,
159 refreshed: Option<Instant>,
160 rng: u64,
161 /// Indexes of the workers placed on each CPU, or on an SMT sibling of a
162 /// CPU without its own worker.
163 local: HashMap<usize, Vec<usize>>,
164 /// `local` must be rebuilt.
165 local_stale: bool,
166 /// Load state of unavailable workers by name, with their arbiter.
167 parked: HashMap<String, (Id, State)>,
168}
169
170impl Balancer {
171 pub(crate) fn new(mode: LoadBalancing) -> Self {
172 Self {
173 mode,
174 next: 0,
175 states: Vec::new(),
176 ready: Vec::new(),
177 refreshed: None,
178 rng: RandomState::new().hash_one(0u64) | 1,
179 local: HashMap::default(),
180 local_stale: true,
181 parked: HashMap::default(),
182 }
183 }
184
185 #[cfg(test)]
186 /// A worker is inserted at `idx`.
187 pub(crate) fn insert(&mut self, idx: usize) {
188 self.insert_state(idx, State::default());
189 }
190
191 /// A worker that became available again is inserted at `idx`.
192 ///
193 /// Its load state is kept from when it became unavailable, unless the
194 /// worker was restarted on a new arbiter since then.
195 pub(crate) fn unpark(&mut self, idx: usize, name: &str, arbiter: Id) {
196 let state = match self.parked.remove(name) {
197 Some((id, state)) if id == arbiter => state,
198 _ => State::default(),
199 };
200 self.insert_state(idx, state);
201 }
202
203 fn insert_state(&mut self, idx: usize, state: State) {
204 self.states.insert(idx, state);
205 self.refreshed = None;
206 self.local_stale = true;
207 }
208
209 /// The worker at `idx` is replaced.
210 pub(crate) fn reset(&mut self, idx: usize) {
211 self.states[idx] = State::default();
212 self.refreshed = None;
213 self.local_stale = true;
214 }
215
216 /// The worker at `idx` is removed.
217 pub(crate) fn remove(&mut self, idx: usize) {
218 self.states.remove(idx);
219 self.refreshed = None;
220 self.local_stale = true;
221 }
222
223 /// The worker at `idx` became unavailable and is removed, its load state
224 /// is kept for [`unpark`](Self::unpark).
225 pub(crate) fn park(&mut self, idx: usize, name: &str, arbiter: Id) {
226 let state = self.states.remove(idx);
227 self.parked.insert(name.to_owned(), (arbiter, state));
228 self.refreshed = None;
229 self.local_stale = true;
230 }
231
232 /// Returns `true` if [`select`](Self::select) uses the incoming CPU of
233 /// items, i.e. the mode is [`LoadBalancing::IncomingCpu`] or
234 /// [`LoadBalancing::Reuseport`] and some
235 /// workers are placed on CPUs.
236 pub(crate) fn uses_incoming_cpu<T>(&mut self, workers: &[Worker<T>]) -> bool {
237 if !matches!(
238 self.mode,
239 LoadBalancing::IncomingCpu | LoadBalancing::Reuseport
240 ) {
241 return false;
242 }
243 if self.local_stale {
244 self.local_stale = false;
245 self.map_cpus(workers.iter().map(Worker::cpus));
246 }
247 !self.local.is_empty()
248 }
249
250 /// Returns the index of the worker for the next item, and whether it was
251 /// chosen for the incoming CPU of the item if that CPU is set.
252 ///
253 /// `workers` must not be empty.
254 pub(crate) fn select<T>(
255 &mut self,
256 workers: &[Worker<T>],
257 cpu: Option<usize>,
258 ) -> (usize, Option<bool>) {
259 match self.mode {
260 LoadBalancing::RoundRobin => (self.round_robin(workers.len()), None),
261 LoadBalancing::LeastLoaded | LoadBalancing::IncomingCpu | LoadBalancing::Reuseport => {
262 let now = Instant::now();
263 self.refresh(now, |idx| Sample::of(&workers[idx], now));
264 let load = |idx: usize| workers[idx].load();
265 let idx = self.least_loaded(load);
266 match cpu {
267 Some(cpu) if self.uses_incoming_cpu(workers) => {
268 let local = self.local_worker(cpu, idx, load);
269 (local.unwrap_or(idx), Some(local.is_some()))
270 }
271 _ => (idx, None),
272 }
273 }
274 }
275 }
276
277 /// Next worker in turn that is not blocked, `len` workers.
278 fn round_robin(&mut self, len: usize) -> usize {
279 if self.next >= len {
280 self.next = len - 1;
281 }
282 // blocked flags are refreshed by `sample`
283 (0..len)
284 .map(|i| (self.next + i) % len)
285 .find(|&i| !self.is_blocked(i))
286 .unwrap_or(self.next)
287 }
288
289 /// Refreshes the load state of the workers.
290 ///
291 /// Returns `true` if some workers are blocked and others are not.
292 pub(crate) fn sample<T>(&mut self, workers: &[Worker<T>]) -> bool {
293 let now = Instant::now();
294 self.refresh(now, |idx| Sample::of(&workers[idx], now));
295 !self.ready.is_empty() && self.ready.len() < self.states.len()
296 }
297
298 /// Returns `true` if the worker at `idx` was blocked when last sampled.
299 pub(crate) fn is_blocked(&self, idx: usize) -> bool {
300 self.states.get(idx).is_some_and(|st| st.blocked)
301 }
302
303 /// The item was sent to the worker at `idx`.
304 pub(crate) fn sent(&mut self, idx: usize, len: usize) {
305 self.next = (idx + 1) % len;
306 }
307
308 fn refresh(&mut self, now: Instant, sample: impl Fn(usize) -> Sample) {
309 if self
310 .refreshed
311 .is_some_and(|t| now.saturating_duration_since(t) < REFRESH)
312 {
313 return;
314 }
315 self.refreshed = Some(now);
316 self.ready.clear();
317 for (idx, st) in self.states.iter_mut().enumerate() {
318 st.update(sample(idx), now);
319 if !st.blocked {
320 self.ready.push(idx);
321 }
322 }
323 }
324
325 /// Power of two choices among the workers that are not blocked.
326 fn least_loaded(&mut self, load: impl Fn(usize) -> usize) -> usize {
327 let all = self.ready.is_empty();
328 let len = if all { self.states.len() } else { self.ready.len() };
329 if len < 2 {
330 return if all { 0 } else { self.ready[0] };
331 }
332
333 let a = self.random(len);
334 let mut b = self.random(len - 1);
335 if b >= a {
336 b += 1;
337 }
338 let (a, b) = if all {
339 (a, b)
340 } else {
341 (self.ready[a], self.ready[b])
342 };
343
344 let (ua, ub) = (self.states[a].util, self.states[b].util);
345 if (ua - ub).abs() > UTIL_SLACK {
346 if ua < ub { a } else { b }
347 } else if load(b) < load(a) {
348 b
349 } else {
350 a
351 }
352 }
353
354 /// Maps CPUs to the workers placed on them, `cpus` yields the CPU of
355 /// each worker followed by its SMT siblings.
356 fn map_cpus<'a>(&mut self, cpus: impl Iterator<Item = &'a [usize]>) {
357 let cpus: Vec<_> = cpus.collect();
358 self.local.clear();
359 for (idx, cpus) in cpus.iter().enumerate() {
360 if let Some(&cpu) = cpus.first() {
361 self.local.entry(cpu).or_default().push(idx);
362 }
363 }
364 let mut siblings = HashMap::<usize, Vec<usize>>::default();
365 for (idx, cpus) in cpus.iter().enumerate() {
366 for cpu in cpus.iter().skip(1) {
367 if !self.local.contains_key(cpu) {
368 siblings.entry(*cpu).or_default().push(idx);
369 }
370 }
371 }
372 self.local.extend(siblings);
373 }
374
375 /// Returns the least loaded worker for the incoming `cpu`, unless it is
376 /// busier than `other`, the least loaded choice.
377 fn local_worker(
378 &self,
379 cpu: usize,
380 other: usize,
381 load: impl Fn(usize) -> usize,
382 ) -> Option<usize> {
383 let util = |idx: usize| self.states[idx].util;
384 let best = self
385 .local
386 .get(&cpu)?
387 .iter()
388 .copied()
389 .filter(|&idx| !self.states[idx].blocked)
390 .min_by(|&a, &b| {
391 util(a)
392 .total_cmp(&util(b))
393 .then_with(|| load(a).cmp(&load(b)))
394 })?;
395 let max_load = load(other) + load(other) / 2 + LOCAL_LOAD_SLACK;
396 (best == other || (util(best) <= util(other) + LOCAL_UTIL_SLACK && load(best) <= max_load))
397 .then_some(best)
398 }
399
400 #[allow(clippy::cast_possible_truncation)]
401 /// Returns a random number in `0..n`.
402 fn random(&mut self, n: usize) -> usize {
403 // xorshift64
404 let mut x = self.rng;
405 x ^= x << 13;
406 x ^= x >> 7;
407 x ^= x << 17;
408 self.rng = x;
409 (x % n as u64) as usize
410 }
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 const MS: Duration = Duration::from_millis(1);
418
419 fn balancer(n: usize) -> Balancer {
420 let mut b = Balancer::new(LoadBalancing::LeastLoaded);
421 for i in 0..n {
422 b.insert(i);
423 }
424 b
425 }
426
427 fn sample(busy_ms: u32, blocked: bool) -> Sample {
428 turn(busy_ms, 0, blocked)
429 }
430
431 /// Sample taken `turn_ms` into the current runtime turn.
432 fn turn(busy_ms: u32, turn_ms: u32, blocked: bool) -> Sample {
433 Sample {
434 busy: Some(MS * busy_ms),
435 turn: MS * turn_ms,
436 blocked,
437 }
438 }
439
440 /// STATEMENT: Worker utilization is an exponential average of busy time that ignores
441 /// samples without busy time or elapsed time.
442 ///
443 /// HOW:
444 /// - Start at 0 and sample 250 ms fully busy; expect 0.5 after one time constant.
445 /// - Sample 250 ms idle; expect 0.25.
446 /// - Sample without busy time, then twice at one instant; expect 0.25 to stay.
447 #[test]
448 fn utilization_average() {
449 let t = Instant::now();
450 let mut st = State::default();
451 st.update(sample(0, false), t);
452 assert!(st.util.abs() < f64::EPSILON);
453
454 // fully busy for one time constant
455 st.update(sample(250, false), t + MS * 250);
456 assert!((st.util - 0.5).abs() < 1e-9, "{}", st.util);
457
458 // idle
459 st.update(sample(250, false), t + MS * 500);
460 assert!((st.util - 0.25).abs() < 1e-9, "{}", st.util);
461
462 // busy time is not available, or there is no time between samples
463 st.update(Sample::default(), t + MS * 600);
464 assert!((st.util - 0.25).abs() < 1e-9, "{}", st.util);
465 st.update(sample(0, false), t + MS * 700);
466 st.update(sample(0, false), t + MS * 700);
467 assert!((st.util - 0.25).abs() < 1e-9, "{}", st.util);
468 }
469
470 /// STATEMENT: The time a worker's runtime is blocked does not count
471 /// towards its utilization, and a long turn counts once it ends.
472 ///
473 /// HOW:
474 /// - Bring the utilization to 0.5, then sample a turn that starts at
475 /// 250 ms, at 50 ms into it, when it is blocked at 150 ms, and 10 ms
476 /// after it ended at 300 ms; the utilization stays 0.5.
477 /// - Sample an idle period and confirm the utilization decays from 0.5.
478 /// - Sample a 50 ms turn that does not block, while it runs and after it
479 /// ended, and confirm it counts as fully busy once it ends.
480 #[test]
481 fn blocked_time_is_not_utilization() {
482 let t = Instant::now();
483 let mut st = State::default();
484 st.update(sample(0, false), t);
485 st.update(sample(250, false), t + MS * 250);
486 assert!((st.util - 0.5).abs() < 1e-9, "{}", st.util);
487
488 st.update(turn(300, 50, false), t + MS * 300);
489 assert!((st.util - 0.5).abs() < 1e-9, "{}", st.util);
490 st.update(turn(400, 150, true), t + MS * 400);
491 assert!(st.blocked);
492 assert!((st.util - 0.5).abs() < 1e-9, "{}", st.util);
493 st.update(sample(550, false), t + MS * 560);
494 assert!(!st.blocked);
495 assert!((st.util - 0.5).abs() < 1e-9, "{}", st.util);
496
497 // idle for one time constant
498 st.update(sample(550, false), t + MS * 810);
499 assert!((st.util - 0.25).abs() < 1e-9, "{}", st.util);
500
501 // a turn from 810 ms to 860 ms
502 st.update(turn(570, 20, false), t + MS * 830);
503 assert!((st.util - 0.25).abs() < 1e-9, "{}", st.util);
504 st.update(sample(600, false), t + MS * 860);
505 let alpha = 50.0 / 300.0;
506 assert!(
507 (st.util - (0.25 + alpha * 0.75)).abs() < 1e-9,
508 "{}",
509 st.util
510 );
511 }
512
513 /// STATEMENT: The balancer samples workers at most every `REFRESH`, unless the worker list
514 /// changes.
515 ///
516 /// HOW:
517 /// - Refresh with idle workers; expect both ready.
518 /// - Refresh with blocked samples before `REFRESH`; expect no change, then at `REFRESH`
519 /// expect blocked worker 0 dropped from ready.
520 /// - Insert a worker and refresh at the same time; expect all 3 ready.
521 #[test]
522 fn refresh_interval() {
523 let t = Instant::now();
524 let mut b = balancer(2);
525 b.refresh(t, |_| sample(0, false));
526 assert_eq!(b.ready, [0, 1]);
527
528 // samples are taken at most every `REFRESH`
529 b.refresh(t + MS, |_| sample(0, true));
530 assert_eq!(b.ready, [0, 1]);
531 b.refresh(t + REFRESH, |i| sample(0, i == 0));
532 assert_eq!(b.ready, [1]);
533
534 // worker list changes force a refresh
535 b.insert(2);
536 b.refresh(t + REFRESH, |_| sample(0, false));
537 assert_eq!(b.ready, [0, 1, 2]);
538 }
539
540 /// STATEMENT: Least-loaded selection avoids blocked workers, and uses all workers when
541 /// every one is blocked.
542 ///
543 /// HOW:
544 /// - Block workers 0 and 1; expect worker 2 in 100 picks.
545 /// - Block all workers; expect each one picked in 100 picks.
546 #[test]
547 fn skips_blocked_workers() {
548 let t = Instant::now();
549 let mut b = balancer(3);
550 b.refresh(t, |i| sample(0, i != 2));
551 for _ in 0..100 {
552 assert_eq!(b.least_loaded(|_| 0), 2);
553 }
554
555 // all workers are blocked
556 b.refresh(t + REFRESH, |_| sample(0, true));
557 let mut seen = [false; 3];
558 for _ in 0..100 {
559 seen[b.least_loaded(|_| 0)] = true;
560 }
561 assert_eq!(seen, [true; 3]);
562 }
563
564 /// STATEMENT: Round robin skips blocked workers, and still picks a worker when all are
565 /// blocked.
566 ///
567 /// HOW:
568 /// - Block worker 1 and send 4 items; expect workers `[0, 2, 0, 2]`.
569 /// - Block all workers; expect the next turn, worker 0.
570 #[test]
571 fn round_robin_skips_blocked_workers() {
572 let t = Instant::now();
573 let mut b = balancer(3);
574 b.refresh(t, |i| sample(0, i == 1));
575 let mut seen = Vec::new();
576 for _ in 0..4 {
577 let idx = b.round_robin(3);
578 b.sent(idx, 3);
579 seen.push(idx);
580 }
581 assert_eq!(seen, [0, 2, 0, 2]);
582
583 // all workers are blocked
584 b.refresh(t + REFRESH, |_| sample(0, true));
585 assert_eq!(b.round_robin(3), 0);
586 }
587
588 /// STATEMENT: Least-loaded selection prefers a less utilized worker even with a higher
589 /// load.
590 ///
591 /// HOW:
592 /// - Make worker 0 more utilized than worker 1 by more than `UTIL_SLACK`.
593 /// - Give worker 1 a load of 100 and worker 0 none; expect worker 1 in 100 picks.
594 #[test]
595 fn prefers_less_utilized_workers() {
596 let t = Instant::now();
597 let mut b = balancer(2);
598 b.refresh(t, |_| sample(0, false));
599 b.refresh(t + MS * 100, |i| {
600 sample(if i == 0 { 100 } else { 10 }, false)
601 });
602 assert!(b.states[0].util > b.states[1].util + UTIL_SLACK);
603 for _ in 0..100 {
604 // utilization wins over load
605 assert_eq!(b.least_loaded(|i| if i == 0 { 0 } else { 100 }), 1);
606 }
607 }
608
609 /// STATEMENT: Among workers with similar utilization, least-loaded selection favors lower
610 /// load.
611 ///
612 /// HOW:
613 /// - Give 4 workers utilization within the slack and loads `[5, 1, 2, 3]`.
614 /// - Pick 1000 times; expect worker 0 never picked, and the others picked more often the
615 /// lower their load.
616 #[test]
617 fn compares_load_of_similar_workers() {
618 let t = Instant::now();
619 let mut b = balancer(4);
620 b.refresh(t, |_| sample(0, false));
621 b.refresh(t + MS * 100, |i| sample([10, 11, 12, 13][i], false));
622 let mut seen = [0; 4];
623 for _ in 0..1000 {
624 seen[b.least_loaded(|i| [5, 1, 2, 3][i])] += 1;
625 }
626 // the most loaded worker never wins a comparison
627 assert_eq!(seen[0], 0);
628 assert!(
629 seen[1] > seen[2] && seen[2] > seen[3] && seen[3] > 0,
630 "{seen:?}"
631 );
632 }
633
634 /// STATEMENT: With a single worker, least-loaded selection returns it even when blocked.
635 ///
636 /// HOW:
637 /// - Refresh one blocked worker.
638 /// - Expect worker 0.
639 #[test]
640 fn single_worker() {
641 let mut b = balancer(1);
642 b.refresh(Instant::now(), |_| sample(0, true));
643 assert_eq!(b.least_loaded(|_| 0), 0);
644 }
645
646 /// STATEMENT: A replaced worker starts with a fresh load state and the
647 /// next sample is taken at once.
648 ///
649 /// HOW:
650 /// - Make worker 0 busy and blocked, while worker 1 is idle.
651 /// - Reset worker 0 and check its utilization and blocked flag are
652 /// cleared, while worker 1 keeps its state.
653 /// - Refresh within `REFRESH` of the last sample and check both workers
654 /// are sampled again.
655 #[test]
656 fn reset_clears_worker_state() {
657 let t = Instant::now();
658 let mut b = balancer(2);
659 b.refresh(t, |_| sample(0, false));
660 b.refresh(t + REFRESH, |i| sample(if i == 0 { 100 } else { 0 }, false));
661 b.refresh(t + REFRESH * 2, |i| sample(100, i == 0));
662 assert!(b.states[0].util > 0.0 && b.is_blocked(0));
663 assert_eq!(b.ready, [1]);
664
665 b.reset(0);
666 assert!(b.states[0].util.abs() < f64::EPSILON);
667 assert!(!b.is_blocked(0));
668 assert!(b.states[0].at.is_none());
669 assert_eq!(b.states[1].busy, Some(MS * 100));
670
671 b.refresh(t + REFRESH * 2 + MS, |_| sample(100, false));
672 assert_eq!(b.ready, [0, 1]);
673 }
674
675 /// STATEMENT: Round robin stays within the worker list after workers are
676 /// removed.
677 ///
678 /// HOW:
679 /// - Send an item to the second of three workers, so the next turn is
680 /// the third one.
681 /// - Remove a worker and check the next turn is the last remaining
682 /// worker, then the turns wrap around to the first one.
683 #[test]
684 fn round_robin_after_removal() {
685 let mut b = balancer(3);
686 b.sent(1, 3);
687 b.remove(2);
688 assert_eq!(b.round_robin(2), 1);
689 b.sent(1, 2);
690 assert_eq!(b.round_robin(2), 0);
691 }
692
693 /// STATEMENT: A worker parked and unparked on the same arbiter keeps its load state; on a
694 /// new arbiter it starts over.
695 ///
696 /// HOW:
697 /// - Make worker 0 busier than worker 1 by more than `UTIL_SLACK`.
698 /// - Park and unpark it on the same arbiter; expect the same utilization and worker 1
699 /// still picked.
700 /// - Park it and unpark on another arbiter; expect zero utilization and no parked state.
701 #[ntex::test]
702 async fn keeps_state_of_unavailable_workers() {
703 let (a1, a2) = (ntex_rt::Arbiter::new(), ntex_rt::Arbiter::new());
704 let t = Instant::now();
705 let mut b = balancer(2);
706 b.refresh(t, |_| sample(0, false));
707 b.refresh(t + MS * 100, |i| {
708 sample(if i == 0 { 100 } else { 10 }, false)
709 });
710 let util = b.states[0].util;
711 assert!(util > b.states[1].util + UTIL_SLACK);
712
713 // the busy worker becomes unavailable and available again
714 b.park(0, "w0", a1.id());
715 b.unpark(0, "w0", a1.id());
716 assert!((b.states[0].util - util).abs() < f64::EPSILON);
717 for _ in 0..100 {
718 assert_eq!(b.least_loaded(|i| [1, 100][i]), 1);
719 }
720
721 // a restarted worker starts over
722 b.park(0, "w0", a1.id());
723 b.unpark(0, "w0", a2.id());
724 assert!(b.states[0].util.abs() < f64::EPSILON);
725 assert!(b.parked.is_empty());
726 a1.stop();
727 a2.stop();
728 }
729
730 /// STATEMENT: CPU mapping assigns each CPU to the workers placed on it, and sibling CPUs
731 /// only when no worker is placed on them.
732 ///
733 /// HOW:
734 /// - Map 5 workers: two on one core, two on other cores, one not placed.
735 /// - Expect each placement CPU mapped to its worker and free siblings to their core's
736 /// worker.
737 /// - Remap 2 workers on CPU 0; expect both on CPU 0 and the old entries gone.
738 #[test]
739 fn map_cpus() {
740 let mut b = balancer(5);
741 // workers 0 and 1 on the two CPUs of core (0, 1), workers 2 and 3
742 // on CPU 2 and 4 of cores (2, 3) and (4, 5), worker 4 not placed
743 b.map_cpus([&[0, 1][..], &[1, 0], &[2, 3], &[4, 5], &[]].into_iter());
744 let mut local: Vec<_> = b.local.iter().map(|(c, w)| (*c, w.clone())).collect();
745 local.sort();
746 assert_eq!(
747 local,
748 [
749 (0, vec![0]),
750 (1, vec![1]),
751 (2, vec![2]),
752 (3, vec![2]),
753 (4, vec![3]),
754 (5, vec![3])
755 ]
756 );
757
758 // several workers on one CPU
759 b.map_cpus([&[0][..], &[0]].into_iter());
760 assert_eq!(b.local.get(&0), Some(&vec![0, 1]));
761 assert_eq!(b.local.len(), 1);
762 }
763
764 /// STATEMENT: The worker on the incoming CPU is used unless it is blocked or much busier
765 /// than the least-loaded choice.
766 ///
767 /// HOW:
768 /// - Expect the worker on the CPU, the less utilized of two on a CPU, and none for an
769 /// unmapped CPU.
770 /// - Expect none when utilization exceeds the other choice by more than
771 /// `LOCAL_UTIL_SLACK`, unless the local worker is that choice.
772 /// - Expect none when its load exceeds the other choice's by more than half plus a slack,
773 /// and the local worker otherwise.
774 /// - Expect none when the local worker is blocked.
775 #[test]
776 fn local_worker() {
777 let t = Instant::now();
778 let mut b = balancer(4);
779 b.map_cpus([&[0][..], &[1], &[2], &[2]].into_iter());
780 b.refresh(t, |_| sample(0, false));
781 b.refresh(t + MS * 100, |i| sample([10, 0, 100, 90][i], false));
782 let load = |_| 10;
783
784 // the worker on the incoming CPU is preferred
785 assert_eq!(b.local_worker(0, 1, load), Some(0));
786 // the least utilized of the workers on the CPU
787 assert_eq!(b.local_worker(2, 2, load), Some(3));
788 // no worker on the CPU
789 assert_eq!(b.local_worker(7, 1, load), None);
790 // utilization exceeds the other choice by more than the slack
791 assert!(b.states[3].util > b.states[1].util + LOCAL_UTIL_SLACK);
792 assert_eq!(b.local_worker(2, 1, load), None);
793 b.map_cpus([&[0][..], &[1], &[2], &[3]].into_iter());
794 assert_eq!(b.local_worker(2, 1, load), None);
795 assert_eq!(b.local_worker(2, 2, load), Some(2));
796
797 // load exceeds the other choice by more than half plus the slack
798 let load = |i: usize| [100, 10, 0, 0][i];
799 assert_eq!(b.local_worker(0, 1, load), None);
800 let load = |i: usize| [100, 56, 0, 0][i];
801 assert_eq!(b.local_worker(0, 1, load), Some(0));
802
803 // blocked worker
804 b.refresh(t + MS * 200, |i| sample([10, 0, 100, 90][i], i == 0));
805 assert_eq!(b.local_worker(0, 1, |_| 0), None);
806 }
807
808 /// STATEMENT: The balancer's random generator covers the whole range below `n`.
809 ///
810 /// HOW:
811 /// - Draw 1000 numbers below 5 as array indexes.
812 /// - Expect every value from 0 to 4 seen.
813 #[test]
814 fn random_range() {
815 let mut b = balancer(0);
816 let mut seen = [false; 5];
817 for _ in 0..1000 {
818 seen[b.random(5)] = true;
819 }
820 assert_eq!(seen, [true; 5]);
821 }
822}