1#[cfg(feature = "tcp-binder")]
11pub mod tcp;
12
13use async_trait::async_trait;
14use log::{debug, trace};
15use std::{
16 fmt::Debug,
17 future::Future,
18 io::{Error, ErrorKind, Result},
19 ops::{Deref, DerefMut},
20 sync::Arc,
21 time::Duration,
22};
23use tokio::{sync::Mutex, task, time};
24
25use crate::{
26 handler::{self, Handler},
27 request::{Request, RequestReader},
28 response::{Response, ResponseWriter},
29 timer::{ThreadSafeTimer, TimerConfig, TimerCycle, TimerEvent, TimerLoop},
30};
31
32#[derive(Clone, Debug, Default, Eq, PartialEq)]
36pub enum ServerState {
37 Running,
39
40 Stopping,
42
43 #[default]
45 Stopped,
46}
47
48pub struct ServerConfig {
50 handler: Arc<Handler<ServerEvent>>,
52
53 binders: Vec<Box<dyn ServerBind>>,
55}
56
57impl Default for ServerConfig {
58 fn default() -> Self {
59 Self {
60 handler: handler::default(),
61 binders: Vec::new(),
62 }
63 }
64}
65
66#[derive(Clone, Debug, Eq, PartialEq)]
68pub enum ServerEvent {
69 Started,
71
72 Stopping,
74
75 Stopped,
77}
78
79#[derive(Clone, Debug, Default)]
81pub struct ThreadSafeState(Arc<Mutex<ServerState>>);
82
83impl ThreadSafeState {
84 pub fn new() -> Self {
86 Self::default()
87 }
88
89 async fn set(&self, next_state: ServerState) {
91 let mut state = self.lock().await;
92 *state = next_state;
93 }
94
95 pub async fn set_running(&self) {
97 self.set(ServerState::Running).await
98 }
99
100 pub async fn set_stopping(&self) {
102 self.set(ServerState::Stopping).await
103 }
104
105 pub async fn set_stopped(&self) {
107 self.set(ServerState::Stopped).await
108 }
109}
110
111impl Deref for ThreadSafeState {
112 type Target = Arc<Mutex<ServerState>>;
113
114 fn deref(&self) -> &Self::Target {
115 &self.0
116 }
117}
118
119impl DerefMut for ThreadSafeState {
120 fn deref_mut(&mut self) -> &mut Self::Target {
121 &mut self.0
122 }
123}
124
125#[async_trait]
129pub trait ServerBind: Debug + Send + Sync {
130 async fn bind(&self, timer: ThreadSafeTimer) -> Result<()>;
133}
134
135#[async_trait]
139pub trait ServerStream: RequestReader + ResponseWriter {
140 async fn handle(&mut self, timer: ThreadSafeTimer) -> Result<()> {
142 let req = self.read().await?;
143 let res = match req {
144 Request::Start => {
145 debug!("starting timer");
146 timer.start().await?;
147 Response::Ok
148 }
149 Request::Get => {
150 debug!("getting timer");
151 let timer = timer.get().await;
152 trace!("{timer:#?}");
153 Response::Timer(timer)
154 }
155 Request::Set(duration) => {
156 debug!("setting timer");
157 timer.set(duration).await?;
158 Response::Ok
159 }
160 Request::Pause => {
161 debug!("pausing timer");
162 timer.pause().await?;
163 Response::Ok
164 }
165 Request::Resume => {
166 debug!("resuming timer");
167 timer.resume().await?;
168 Response::Ok
169 }
170 Request::Stop => {
171 debug!("stopping timer");
172 timer.stop().await?;
173 Response::Ok
174 }
175 };
176 self.write(res).await?;
177 Ok(())
178 }
179}
180
181impl<T: RequestReader + ResponseWriter> ServerStream for T {}
182
183#[derive(Default)]
185pub struct Server {
186 config: ServerConfig,
188
189 state: ThreadSafeState,
191
192 timer: ThreadSafeTimer,
194}
195
196impl Server {
197 pub async fn bind_with<F: Future<Output = Result<()>>>(
202 self,
203 wait: impl FnOnce() -> F + Send + Sync + 'static,
204 ) -> Result<()> {
205 debug!("starting server");
206
207 let handler = &self.config.handler;
208 let fire_event = |event: ServerEvent| async move {
209 debug!("firing server event {event:?}");
210 if let Err(err) = handler(event.clone()).await {
211 debug!("error while firing server event, skipping it");
212 debug!("{err:?}");
213 }
214 };
215
216 self.state.set_running().await;
217 fire_event(ServerEvent::Started).await;
218
219 let state = self.state.clone();
221 let timer = self.timer.clone();
222 let tick = task::spawn(async move {
223 loop {
224 let mut state = state.lock().await;
225 match *state {
226 ServerState::Stopping => {
227 *state = ServerState::Stopped;
228 break;
229 }
230 ServerState::Stopped => {
231 break;
232 }
233 ServerState::Running => {
234 timer.update().await;
235 }
236 };
237 drop(state);
238
239 time::sleep(Duration::from_secs(1)).await;
240 }
241 });
242
243 for binder in self.config.binders {
246 let timer = self.timer.clone();
247 task::spawn(async move {
248 debug!("binding {binder:?}");
249 if let Err(err) = binder.bind(timer).await {
250 debug!("error while binding, skipping it");
251 debug!("{err:?}");
252 }
253 });
254 }
255
256 debug!("main loop started");
257 wait().await?;
258 debug!("main loop stopped");
259
260 self.state.set_stopping().await;
261 fire_event(ServerEvent::Stopping).await;
262
263 tick.await
265 .map_err(|_| Error::new(ErrorKind::Other, "cannot wait for timer thread"))?;
266 fire_event(ServerEvent::Stopped).await;
267
268 Ok(())
269 }
270
271 pub async fn bind(self) -> Result<()> {
274 self.bind_with(|| async {
275 loop {
276 time::sleep(Duration::from_secs(1)).await;
277 }
278 })
279 .await
280 }
281}
282
283#[derive(Default)]
287pub struct ServerBuilder {
288 server_config: ServerConfig,
290
291 timer_config: TimerConfig,
293}
294
295impl ServerBuilder {
296 pub fn new() -> Self {
298 Self::default()
299 }
300
301 pub fn with_server_config(mut self, config: ServerConfig) -> Self {
303 self.server_config = config;
304 self
305 }
306
307 pub fn with_timer_config(mut self, config: TimerConfig) -> Self {
309 self.timer_config = config;
310 self
311 }
312
313 pub fn with_pomodoro_config(mut self) -> Self {
319 let work = TimerCycle::new("Work", 25 * 60);
320 let short_break = TimerCycle::new("Short break", 5 * 60);
321 let long_break = TimerCycle::new("Long break", 15 * 60);
322
323 *self.timer_config.cycles = vec![
324 work.clone(),
325 short_break.clone(),
326 work.clone(),
327 short_break.clone(),
328 work.clone(),
329 short_break.clone(),
330 work.clone(),
331 short_break.clone(),
332 long_break,
333 ];
334 self
335 }
336
337 pub fn with_52_17_config(mut self) -> Self {
342 let work = TimerCycle::new("Work", 52 * 60);
343 let rest = TimerCycle::new("Rest", 17 * 60);
344
345 *self.timer_config.cycles = vec![work, rest];
346 self
347 }
348
349 pub fn with_server_handler<F: Future<Output = Result<()>> + Send + 'static>(
351 mut self,
352 handler: impl Fn(ServerEvent) -> F + Send + Sync + 'static,
353 ) -> Self {
354 self.server_config.handler = Arc::new(move |evt| Box::pin(handler(evt)));
355 self
356 }
357
358 pub fn with_binder(mut self, binder: Box<dyn ServerBind>) -> Self {
360 self.server_config.binders.push(binder);
361 self
362 }
363
364 pub fn with_timer_handler<F: Future<Output = Result<()>> + Send + 'static>(
366 mut self,
367 handler: impl Fn(TimerEvent) -> F + Sync + Send + 'static,
368 ) -> Self {
369 self.timer_config.handler = Arc::new(move |evt| Box::pin(handler(evt)));
370 self
371 }
372
373 pub fn with_cycle<C>(mut self, cycle: C) -> Self
375 where
376 C: Into<TimerCycle>,
377 {
378 self.timer_config.cycles.push(cycle.into());
379 self
380 }
381
382 pub fn with_cycles<C, I>(mut self, cycles: I) -> Self
384 where
385 C: Into<TimerCycle>,
386 I: IntoIterator<Item = C>,
387 {
388 for cycle in cycles {
389 self.timer_config.cycles.push(cycle.into());
390 }
391 self
392 }
393
394 pub fn with_cycles_count(mut self, count: impl Into<TimerLoop>) -> Self {
396 self.timer_config.cycles_count = count.into();
397 self
398 }
399
400 pub fn build(self) -> Result<Server> {
402 Ok(Server {
403 config: self.server_config,
404 state: ThreadSafeState::new(),
405 timer: ThreadSafeTimer::new(self.timer_config)?,
406 })
407 }
408}