Echo/Scheduler/SchedulerBuilder.rs
1//! # SchedulerBuilder
2//!
3//! Defines the fluent builder for creating and configuring a `Scheduler`.
4
5use std::collections::HashMap;
6
7use log::warn;
8
9use crate::Scheduler::Scheduler::Scheduler;
10
11/// Defines concurrency limits for named queues (for future use).
12#[derive(Debug, Clone, Copy)]
13pub enum Concurrency {
14 /// Specifies a maximum number of concurrent tasks for a queue.
15 Limit(usize),
16
17 /// Allows an unlimited number of concurrent tasks for a queue.
18 Unlimited,
19}
20
21/// A fluent builder for creating a `Scheduler` instance.
22///
23/// This pattern provides a clear and readable API for configuring the scheduler
24/// before it is constructed. It is the primary entry point for using the `Echo`
25/// library.
26pub struct SchedulerBuilder {
27 /// The number of worker threads to be spawned in the scheduler's pool.
28 Count:usize,
29
30 /// Configuration for named queues with concurrency limits (for future
31 /// use).
32 Configuration:HashMap<String, Concurrency>,
33}
34
35impl SchedulerBuilder {
36 /// Creates a new `SchedulerBuilder` with default settings.
37 ///
38 /// By default, the worker count is set to the number of logical CPUs on the
39 /// system, with a minimum of two workers to ensure work-stealing is
40 /// viable.
41 pub fn Create() -> Self {
42 let Default = num_cpus::get().max(2);
43
44 Self { Count:Default, Configuration:HashMap::new() }
45 }
46
47 /// Sets the total number of worker threads for the scheduler pool.
48 ///
49 /// If `Count` is `0`, it defaults to the number of logical CPUs.
50 pub fn WithWorkerCount(mut self, Count:usize) -> Self {
51 if Count == 0 {
52 warn!("[SchedulerBuilder] Worker count of 0 is invalid. Defaulting to logical CPUs.");
53
54 self.Count = num_cpus::get().max(2);
55 } else {
56 self.Count = Count;
57 }
58
59 self
60 }
61
62 /// Configures a named queue with a specific concurrency limit (for future
63 /// use).
64 pub fn WithQueue(mut self, Name:&str, Limit:Concurrency) -> Self {
65 self.Configuration.insert(Name.to_string(), Limit);
66
67 self
68 }
69
70 /// Builds and starts the `Scheduler` with the specified configuration.
71 ///
72 /// This method consumes the builder and returns a new, running `Scheduler`.
73 pub fn Build(self) -> Scheduler { Scheduler::Create(self.Count, self.Configuration) }
74}
75
76impl Default for SchedulerBuilder {
77 /// Provides a default `SchedulerBuilder` instance.
78 fn default() -> Self { Self::Create() }
79}