AppFlowy/backend/src/application.rs

78 lines
2.4 KiB
Rust
Raw Normal View History

2021-08-21 22:02:05 +08:00
use crate::{
config::{get_configuration, DatabaseSettings, Settings},
context::AppContext,
routers::*,
ws_service::WSServer,
};
use actix::Actor;
use actix_web::{dev::Server, middleware, web, web::Data, App, HttpServer, Scope};
use sqlx::{postgres::PgPoolOptions, PgPool};
use std::{net::TcpListener, sync::Arc};
pub struct Application {
port: u16,
server: Server,
}
impl Application {
pub async fn build(configuration: Settings) -> Result<Self, std::io::Error> {
let address = format!(
"{}:{}",
configuration.application.host, configuration.application.port
);
let listener = TcpListener::bind(&address)?;
let port = listener.local_addr().unwrap().port();
2021-08-22 22:16:03 +08:00
let app_ctx = init_app_context(&configuration).await;
let server = run(listener, app_ctx)?;
Ok(Self { port, server })
2021-08-21 22:02:05 +08:00
}
pub async fn run_until_stopped(self) -> Result<(), std::io::Error> { self.server.await }
}
2021-08-22 22:16:03 +08:00
pub fn run(listener: TcpListener, app_ctx: AppContext) -> Result<Server, std::io::Error> {
let AppContext { ws_server, pg_pool } = app_ctx;
let ws_server = Data::new(ws_server);
let pg_pool = Data::new(pg_pool);
2021-08-21 22:02:05 +08:00
let server = HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.app_data(web::JsonConfig::default().limit(4096))
.service(ws_scope())
.service(user_scope())
2021-08-22 22:16:03 +08:00
.app_data(ws_server.clone())
.app_data(pg_pool.clone())
2021-08-21 22:02:05 +08:00
})
.listen(listener)?
.run();
Ok(server)
}
fn ws_scope() -> Scope { web::scope("/ws").service(ws::start_connection) }
fn user_scope() -> Scope {
web::scope("/user").service(web::resource("/register").route(web::post().to(user::register)))
}
2021-08-22 22:16:03 +08:00
async fn init_app_context(configuration: &Settings) -> AppContext {
2021-08-21 22:02:05 +08:00
let _ = flowy_log::Builder::new("flowy").env_filter("Debug").build();
2021-08-22 22:16:03 +08:00
let pg_pool = get_connection_pool(&configuration.database)
.await
.expect(&format!(
"Failed to connect to Postgres at {:?}.",
configuration.database
));
2021-08-21 22:02:05 +08:00
let ws_server = WSServer::new().start();
2021-08-22 22:16:03 +08:00
AppContext::new(ws_server, pg_pool)
2021-08-21 22:02:05 +08:00
}
pub async fn get_connection_pool(configuration: &DatabaseSettings) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new()
.connect_timeout(std::time::Duration::from_secs(5))
2021-08-21 22:02:05 +08:00
.connect_with(configuration.with_db())
.await
}