li7y/src/main.rs
Simon Bruder 21c99a1677
Use diesel-async
This simplifies running queries, as it avoids having to use web::block
for everything.
2024-07-11 01:16:39 +02:00

64 lines
2.3 KiB
Rust

// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use std::env;
use actix_web::{web, App, HttpServer};
use diesel::pg::Pg;
use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
use diesel_async::pg::AsyncPgConnection;
use diesel_async::pooled_connection::deadpool::Pool;
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::AsyncConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use log::{debug, info};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
// adapted from https://github.com/weiznich/diesel_async/blob/002c67e4d09acd9b38d0fb08ff0efc24954b2558/examples/sync-wrapper/src/main.rs#L36-L48
async fn run_migrations<A: AsyncConnection<Backend = Pg> + 'static>(async_connection: A) {
let mut async_wrapper: AsyncConnectionWrapper<A> =
AsyncConnectionWrapper::from(async_connection);
web::block(move || {
async_wrapper.run_pending_migrations(MIGRATIONS).unwrap();
})
.await
.expect("failed to run migrations");
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new(
env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
);
let pool: Pool<AsyncPgConnection> = Pool::builder(manager)
.build()
.expect("database URL must be valid");
run_migrations(pool.get().await.unwrap()).await;
let address = env::var("LISTEN_ADDRESS").unwrap_or("::1".to_string());
let port = env::var("LISTEN_PORT").map_or(8080, |s| {
s.parse::<u16>().expect("failed to parse LISTEN_PORT")
});
let static_root = env::var("STATIC_ROOT").unwrap_or("static".to_string());
info!("Starting on {address}:{port} with static files from {static_root}");
debug!("Serving static files from {static_root}");
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.service(web::scope("/api/v1").configure(li7y::api::v1::config))
.service(actix_files::Files::new("/static", &static_root))
.configure(li7y::frontend::config)
})
.bind((address, port))?
.run()
.await
}