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