1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
//! # Server module.
//!
//! The [`Server`] runs the timer, accepts connections from clients
//! and sends responses. The [`Server`] accepts connections using
//! [`ServerBind`]ers. The [`Server`] should have at least one
//! [`ServerBind`], otherwise it stops by itself.
#[cfg(feature = "tcp-binder")]
mod tcp;
#[cfg(feature = "tcp-binder")]
pub use tcp::*;
use log::{debug, error, trace, warn};
use std::{
io,
ops::{Deref, DerefMut},
sync::{Arc, Mutex},
thread,
time::Duration,
};
use crate::{TimerCycle, TimerLoop};
use super::{Request, Response, ThreadSafeTimer, TimerConfig, TimerEvent};
/// The server state enum.
///
/// This enum represents the different states the server can be in.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum ServerState {
/// The server is in running mode, which blocks the main process.
Running,
/// The server received the order to stop.
Stopping,
/// The server is stopped and will free the main process.
#[default]
Stopped,
}
/// The server configuration.
pub struct ServerConfig {
/// The server state change handler.
handler: ServerStateChangedHandler,
/// The binders list the server should use when starting up.
binders: Vec<Box<dyn ServerBind>>,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
handler: Arc::new(|_| Ok(())),
binders: Vec::new(),
}
}
}
/// The server state changed event.
///
/// Event triggered by [`ServerStateChangedHandler`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ServerEvent {
Started,
Stopping,
Stopped,
}
/// The server state changed handler alias.
pub type ServerStateChangedHandler = Arc<dyn Fn(ServerEvent) -> io::Result<()> + Sync + Send>;
/// Thread safe version of the [`ServerState`].
///
/// It allows the [`Server`] to mutate its state even from a
/// [`std::thread::spawn`]).
#[derive(Clone, Debug, Default)]
pub struct ThreadSafeState(Arc<Mutex<ServerState>>);
impl ThreadSafeState {
/// Create a new server thread safe state using defaults.
pub fn new() -> Self {
Self::default()
}
/// Change the inner server state with the given one.
fn set(&self, next_state: ServerState) -> io::Result<()> {
match self.lock() {
Ok(mut state) => {
*state = next_state;
Ok(())
}
Err(err) => Err(io::Error::new(
io::ErrorKind::Other,
format!("cannot lock server state: {err}"),
)),
}
}
/// Change the inner server state to running.
pub fn set_running(&self) -> io::Result<()> {
self.set(ServerState::Running)
}
/// Change the inner server state to stopping.
pub fn set_stopping(&self) -> io::Result<()> {
self.set(ServerState::Stopping)
}
/// Change the inner server state to stopped.
pub fn set_stopped(&self) -> io::Result<()> {
self.set(ServerState::Stopped)
}
}
impl Deref for ThreadSafeState {
type Target = Arc<Mutex<ServerState>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ThreadSafeState {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// The server bind trait.
///
/// [`ServerBind`]ers must implement this trait.
pub trait ServerBind: Sync + Send {
/// Describe how the server should bind to accept connections from
/// clients.
fn bind(&self, timer: ThreadSafeTimer) -> io::Result<()>;
}
/// The server stream trait.
///
/// [`ServerBind`]ers may implement this trait, but it is not
/// mandatory. It can be seen as a helper: by implementing the
/// [`ServerStream::read`] and the [`ServerStream::write`] functions,
/// the trait can deduce how to handle a request.
pub trait ServerStream<T> {
fn read(&self, stream: &T) -> io::Result<Request>;
fn write(&self, stream: &mut T, res: Response) -> io::Result<()>;
fn handle(&self, timer: ThreadSafeTimer, stream: &mut T) -> io::Result<()> {
let req = self.read(stream)?;
let res = match req {
Request::Start => {
debug!("starting timer");
timer.start()?;
Response::Ok
}
Request::Get => {
debug!("getting timer");
let timer = timer.get()?;
trace!("{timer:#?}");
Response::Timer(timer)
}
Request::Set(duration) => {
debug!("setting timer");
timer.set(duration)?;
Response::Ok
}
Request::Pause => {
debug!("pausing timer");
timer.pause()?;
Response::Ok
}
Request::Resume => {
debug!("resuming timer");
timer.resume()?;
Response::Ok
}
Request::Stop => {
debug!("stopping timer");
timer.stop()?;
Response::Ok
}
};
self.write(stream, res)?;
Ok(())
}
}
/// The server struct.
#[derive(Default)]
pub struct Server {
/// The server configuration.
config: ServerConfig,
/// The current server state.
state: ThreadSafeState,
/// The current server timer.
timer: ThreadSafeTimer,
}
impl Server {
/// Start the server by running the timer in a dedicated thread as
/// well as all the binders in dedicated threads.
///
/// The main thread is then blocked by the given `wait` closure.
pub fn bind_with(self, wait: impl Fn() -> io::Result<()>) -> io::Result<()> {
debug!("starting server");
let fire_event = |event: ServerEvent| {
if let Err(err) = (self.config.handler)(event.clone()) {
warn!("cannot fire event {event:?}, skipping it");
error!("{err}");
}
};
self.state.set_running()?;
fire_event(ServerEvent::Started);
// the tick represents the timer running in a separated thread
let state = self.state.clone();
let timer = self.timer.clone();
let tick = thread::spawn(move || loop {
match state.lock() {
Ok(mut state) => match *state {
ServerState::Stopping => {
*state = ServerState::Stopped;
break;
}
ServerState::Stopped => {
break;
}
ServerState::Running => {
if let Err(err) = timer.update() {
warn!("cannot update timer, exiting: {err}");
debug!("cannot update timer: {err:?}");
*state = ServerState::Stopping;
break;
}
}
},
Err(err) => {
warn!("cannot determine if server should stop, exiting: {err}");
debug!("cannot determine if server should stop: {err:?}");
break;
}
}
trace!("timer tick: {timer:#?}");
thread::sleep(Duration::from_secs(1));
});
// start all binders in dedicated threads in order not to
// block the main thread
for binder in self.config.binders {
let timer = self.timer.clone();
thread::spawn(move || {
if let Err(err) = binder.bind(timer) {
warn!("cannot bind, exiting: {err}");
debug!("cannot bind: {err:?}");
}
});
}
wait()?;
self.state.set_stopping()?;
fire_event(ServerEvent::Stopping);
// wait for the timer thread to stop before exiting
tick.join()
.map_err(|_| io::Error::new(io::ErrorKind::Other, "cannot wait for timer thread"))?;
fire_event(ServerEvent::Stopped);
Ok(())
}
/// Wrapper around [`Server::bind_with`] where the `wait` closure
/// sleeps every second in an infinite loop.
pub fn bind(self) -> io::Result<()> {
self.bind_with(|| loop {
thread::sleep(Duration::from_secs(1));
})
}
}
/// The server builder.
///
/// Convenient builder to help building a final [`Server`].
#[derive(Default)]
pub struct ServerBuilder {
/// The server configuration.
server_config: ServerConfig,
/// The timer configuration.
timer_config: TimerConfig,
}
impl ServerBuilder {
/// Create a new server builder using defaults.
pub fn new() -> Self {
Self::default()
}
/// Set the server configuration.
pub fn with_server_config(mut self, config: ServerConfig) -> Self {
self.server_config = config;
self
}
/// Set the timer configuration.
pub fn with_timer_config(mut self, config: TimerConfig) -> Self {
self.timer_config = config;
self
}
/// Configure the timer to follow the Pomodoro time management
/// method, which alternates 25 min of work and 5 min of breaks 4
/// times, then ends with a long break of 15 min.
///
/// See <https://en.wikipedia.org/wiki/Pomodoro_Technique>.
pub fn with_pomodoro_config(mut self) -> Self {
let work = TimerCycle::new("Work", 25 * 60);
let short_break = TimerCycle::new("Short break", 5 * 60);
let long_break = TimerCycle::new("Long break", 15 * 60);
*self.timer_config.cycles = vec![
work.clone(),
short_break.clone(),
work.clone(),
short_break.clone(),
work.clone(),
short_break.clone(),
work.clone(),
short_break.clone(),
long_break,
];
self
}
/// Configure the timer to follow the 52/17 time management
/// method, which alternates 52 min of work and 17 min of resting.
///
/// See <https://en.wikipedia.org/wiki/52/17_rule>.
pub fn with_52_17_config(mut self) -> Self {
let work = TimerCycle::new("Work", 52 * 60);
let rest = TimerCycle::new("Rest", 17 * 60);
*self.timer_config.cycles = vec![work, rest];
self
}
/// Set the server handler.
pub fn with_server_handler<H>(mut self, handler: H) -> Self
where
H: Fn(ServerEvent) -> io::Result<()> + Sync + Send + 'static,
{
self.server_config.handler = Arc::new(handler);
self
}
/// Push the given server binder.
pub fn with_binder(mut self, binder: Box<dyn ServerBind>) -> Self {
self.server_config.binders.push(binder);
self
}
/// Set the timer handler.
pub fn with_timer_handler<H>(mut self, handler: H) -> Self
where
H: Fn(TimerEvent) -> io::Result<()> + Sync + Send + 'static,
{
self.timer_config.handler = Arc::new(handler);
self
}
/// Push the given timer cycle.
pub fn with_cycle<C>(mut self, cycle: C) -> Self
where
C: Into<TimerCycle>,
{
self.timer_config.cycles.push(cycle.into());
self
}
/// Set the timer cycles.
pub fn with_cycles<C, I>(mut self, cycles: I) -> Self
where
C: Into<TimerCycle>,
I: IntoIterator<Item = C>,
{
for cycle in cycles {
self.timer_config.cycles.push(cycle.into());
}
self
}
/// Set the timer cycles count.
pub fn with_cycles_count(mut self, count: impl Into<TimerLoop>) -> Self {
self.timer_config.cycles_count = count.into();
self
}
/// Build the final server.
pub fn build(self) -> io::Result<Server> {
Ok(Server {
config: self.server_config,
state: ThreadSafeState::new(),
timer: ThreadSafeTimer::new(self.timer_config)?,
})
}
}