pavex/server/configuration.rs
1use std::num::NonZeroUsize;
2
3use tracing_log_error::log_error;
4
5#[derive(Debug, Clone)]
6/// All the available options for customizing the behaviour of a [`Server`](super::Server).
7///
8/// Refer to [`Server::set_config`](super::Server::set_config) for applying the configuration
9/// you assembled.
10pub struct ServerConfiguration {
11 /// Number of worker threads to spawn.
12 pub(crate) n_workers: NonZeroUsize,
13}
14
15impl Default for ServerConfiguration {
16 fn default() -> Self {
17 Self::new()
18 }
19}
20
21impl ServerConfiguration {
22 /// Initialize a new [`ServerConfiguration`] using its default settings.
23 pub fn new() -> Self {
24 let n_workers = match std::thread::available_parallelism() {
25 Ok(n) => n,
26 Err(e) => {
27 let fallback = NonZeroUsize::new(2).unwrap();
28 log_error!(
29 e,
30 level: tracing::Level::WARN,
31 "Failed to determine the amount of available parallelism. \
32 Setting the number of worker threads to a fallback value of {}",
33 fallback);
34 fallback
35 }
36 };
37 Self { n_workers }
38 }
39
40 /// Set the number of worker threads to be spawned.
41 /// It must be greater than 0.
42 ///
43 /// # Default
44 ///
45 /// It relies on [`std::thread::available_parallelism`] to determine the available parallelism.
46 /// On most platforms, this is the number of physical CPU cores available. If the available
47 /// parallelism cannot be determined, it defaults to 2.
48 ///
49 /// ## Logical vs physical Cores
50 ///
51 /// If you'd prefer to match the number of _logical_ cores instead, you can use the [`num_cpus`]
52 /// crate to acquire the logical core count instead.
53 ///
54 /// [`num_cpus`]: https://docs.rs/num_cpus
55 #[track_caller]
56 pub fn set_n_workers(mut self, n: usize) -> Self {
57 assert!(n > 0, "The number of workers must be greater than 0");
58 self.n_workers = NonZeroUsize::new(n).unwrap();
59 self
60 }
61
62 /// Get the number of worker threads to be spawned.
63 pub fn get_n_workers(&self) -> NonZeroUsize {
64 self.n_workers
65 }
66}