main.rs

  1mod admin;
  2mod assets;
  3mod auth;
  4mod db;
  5mod env;
  6mod errors;
  7mod expiring;
  8mod github;
  9mod home;
 10mod rpc;
 11mod team;
 12#[cfg(test)]
 13mod tests;
 14
 15use self::errors::TideResultExt as _;
 16use anyhow::{Context, Result};
 17use async_std::net::TcpListener;
 18use async_trait::async_trait;
 19use auth::RequestExt as _;
 20use db::{Db, DbOptions};
 21use handlebars::{Handlebars, TemplateRenderError};
 22use parking_lot::RwLock;
 23use rust_embed::RustEmbed;
 24use serde::{Deserialize, Serialize};
 25use std::sync::Arc;
 26use surf::http::cookies::SameSite;
 27use tide::{log, sessions::SessionMiddleware};
 28use tide_compress::CompressMiddleware;
 29use zrpc::Peer;
 30
 31type Request = tide::Request<Arc<AppState>>;
 32
 33#[derive(RustEmbed)]
 34#[folder = "templates"]
 35struct Templates;
 36
 37#[derive(Default, Deserialize)]
 38pub struct Config {
 39    pub http_port: u16,
 40    pub database_url: String,
 41    pub session_secret: String,
 42    pub github_app_id: usize,
 43    pub github_client_id: String,
 44    pub github_client_secret: String,
 45    pub github_private_key: String,
 46}
 47
 48pub struct AppState {
 49    db: Db,
 50    handlebars: RwLock<Handlebars<'static>>,
 51    auth_client: auth::Client,
 52    github_client: Arc<github::AppClient>,
 53    repo_client: github::RepoClient,
 54    config: Config,
 55}
 56
 57impl AppState {
 58    async fn new(config: Config) -> tide::Result<Arc<Self>> {
 59        let db = Db(DbOptions::new()
 60            .max_connections(5)
 61            .connect(&config.database_url)
 62            .await
 63            .context("failed to connect to postgres database")?);
 64
 65        let github_client =
 66            github::AppClient::new(config.github_app_id, config.github_private_key.clone());
 67        let repo_client = github_client
 68            .repo("zed-industries/zed".into())
 69            .await
 70            .context("failed to initialize github client")?;
 71
 72        let this = Self {
 73            db,
 74            handlebars: Default::default(),
 75            auth_client: auth::build_client(&config.github_client_id, &config.github_client_secret),
 76            github_client,
 77            repo_client,
 78            config,
 79        };
 80        this.register_partials();
 81        Ok(Arc::new(this))
 82    }
 83
 84    fn register_partials(&self) {
 85        for path in Templates::iter() {
 86            if let Some(partial_name) = path
 87                .strip_prefix("partials/")
 88                .and_then(|path| path.strip_suffix(".hbs"))
 89            {
 90                let partial = Templates::get(path.as_ref()).unwrap();
 91                self.handlebars
 92                    .write()
 93                    .register_partial(partial_name, std::str::from_utf8(partial.as_ref()).unwrap())
 94                    .unwrap()
 95            }
 96        }
 97    }
 98
 99    fn render_template(
100        &self,
101        path: &'static str,
102        data: &impl Serialize,
103    ) -> Result<String, TemplateRenderError> {
104        #[cfg(debug_assertions)]
105        self.register_partials();
106
107        self.handlebars.read().render_template(
108            std::str::from_utf8(Templates::get(path).unwrap().as_ref()).unwrap(),
109            data,
110        )
111    }
112}
113
114#[async_trait]
115trait RequestExt {
116    async fn layout_data(&mut self) -> tide::Result<Arc<LayoutData>>;
117    fn db(&self) -> &Db;
118}
119
120#[async_trait]
121impl RequestExt for Request {
122    async fn layout_data(&mut self) -> tide::Result<Arc<LayoutData>> {
123        if self.ext::<Arc<LayoutData>>().is_none() {
124            self.set_ext(Arc::new(LayoutData {
125                current_user: self.current_user().await?,
126            }));
127        }
128        Ok(self.ext::<Arc<LayoutData>>().unwrap().clone())
129    }
130
131    fn db(&self) -> &Db {
132        &self.state().db
133    }
134}
135
136#[derive(Serialize)]
137struct LayoutData {
138    current_user: Option<auth::User>,
139}
140
141#[async_std::main]
142async fn main() -> tide::Result<()> {
143    log::start();
144
145    if let Err(error) = env::load_dotenv() {
146        log::error!(
147            "error loading .env.toml (this is expected in production): {}",
148            error
149        );
150    }
151
152    let config = envy::from_env::<Config>().expect("error loading config");
153    let state = AppState::new(config).await?;
154    let rpc = Peer::new();
155    run_server(
156        state.clone(),
157        rpc,
158        TcpListener::bind(&format!("0.0.0.0:{}", state.config.http_port)).await?,
159    )
160    .await?;
161    Ok(())
162}
163
164pub async fn run_server(
165    state: Arc<AppState>,
166    rpc: Arc<Peer>,
167    listener: TcpListener,
168) -> tide::Result<()> {
169    let mut web = tide::with_state(state.clone());
170    web.with(CompressMiddleware::new());
171    web.with(
172        SessionMiddleware::new(
173            db::SessionStore::new_with_table_name(&state.config.database_url, "sessions")
174                .await
175                .unwrap(),
176            state.config.session_secret.as_bytes(),
177        )
178        .with_same_site_policy(SameSite::Lax), // Required obtain our session in /auth_callback
179    );
180    web.with(errors::Middleware);
181    home::add_routes(&mut web);
182    team::add_routes(&mut web);
183    admin::add_routes(&mut web);
184    auth::add_routes(&mut web);
185    assets::add_routes(&mut web);
186
187    let mut app = tide::with_state(state.clone());
188    rpc::add_routes(&mut app, &rpc);
189    app.at("/").nest(web);
190
191    app.listen(listener).await?;
192
193    Ok(())
194}