Echo Writes Code

state.rs

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
use crate::content::{ ContentDatabase };
use crate::errors::{ Result };
use crate::renderer::{ Renderer };
use std::path::{ PathBuf };
use std::sync::{ RwLock, RwLockReadGuard, RwLockWriteGuard };

#[derive(Debug)]
pub struct ServerConfiguration {
  pub site_title: String,
  pub content_path: PathBuf,
  pub metadata_path: PathBuf,
  pub theme_path: PathBuf,
  pub theme_static_path: PathBuf,
  pub host: String,
  pub port: u16,
}

#[derive(Debug)]
pub struct ServerState {
  database: RwLock<ContentDatabase>,
  renderer: Renderer,
}

impl ServerState {
  pub fn new(configuration: &ServerConfiguration) -> Result<ServerState> {
    let database = ContentDatabase::open(&configuration.content_path, &configuration.metadata_path)?;
    let server_state = ServerState {
      database: RwLock::new(database),
      renderer: Renderer::new(&configuration.site_title, &configuration.theme_path),
    };

    Ok(server_state)
  }

  pub fn database(&self) -> RwLockReadGuard<'_, ContentDatabase> {
    self.database
      .read()
      .expect("Database lock should not be poisoned")
  }

  pub fn database_mut(&self) -> RwLockWriteGuard<'_, ContentDatabase> {
    self.database
      .write()
      .expect("Database lock should not be poisoned")
  }

  pub fn renderer(&self) -> &Renderer {
    &self.renderer
  }
}