implemented foundational API routes (/articles, /summaries) using Axum, added graceful shutdown handling, improved database initialization with connection pooling and directory creation, and integrated tracing for logging

This commit is contained in:
2025-08-05 08:59:01 +02:00
parent 79e4d7f1de
commit a30f8467bc
9 changed files with 326 additions and 38 deletions

View File

@@ -1,3 +1,3 @@
mod handlers;
mod middleware;
mod routes;
pub mod handlers;
pub mod middleware;
pub mod routes;

View File

@@ -0,0 +1,39 @@
use axum::Json;
use axum::extract::State;
use serde_json::Value;
use sqlx::SqlitePool;
pub async fn get_articles(State(pool): State<SqlitePool>) -> Result<Json<Value>, AppError> {
// TODO: Article logic
Ok(Json(serde_json::json!({"articles": []})))
}
pub async fn get_summaries(State(pool): State<SqlitePool>) -> Result<Json<Value>, AppError> {
// TODO: Summaries logic
Ok(Json(serde_json::json!({"summaries": []})))
}
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
pub struct AppError(anyhow::Error);
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>, {
fn from(err: E) -> Self {
Self(err.into())
}
}

View File

@@ -0,0 +1,11 @@
use axum::Router;
use axum::routing::get;
use sqlx::SqlitePool;
use crate::api::handlers;
pub fn routes() -> Router<SqlitePool> {
Router::new()
.route("/articles", get(handlers::get_articles))
.route("/summaries", get(handlers::get_summaries))
// Add more routes as needed
}

View File

@@ -1,21 +1,53 @@
use std::env;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct Config {
pub db_path: String,
pub migration_path: String,
pub host: String,
pub port: u16,
}
impl Config {
pub fn from_env() -> Self {
Self {
db_path: env::var("DB_URL").unwrap_or_else(|_| "owlynews.sqlite3".to_string()),
db_path: Self::get_db_path(),
migration_path: std::env::var("MIGRATION_PATH")
.unwrap_or_else(|_| "./migrations".to_string()),
host: env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
port: env::var("PORT")
.unwrap_or_else(|_| "1337".to_string())
.parse()
.expect("PORT must be a number"),
}
}
fn get_db_path() -> String {
if let Ok(db_path) = env::var("DATABASE_PATH") {
return db_path;
}
if cfg!(debug_assertions) {
// Development: Use backend-rust directory
// TODO: Change later
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("owlynews.sqlite3");
path.to_str().unwrap().to_string()
} else {
// Production: Use standard Linux applications data directory
"/var/lib/owly-news-summariser/owlynews.sqlite3".to_string()
}
}
pub fn database_url(&self) -> String {
format!("sqlite:{}", self.db_path)
}
pub fn ensure_db_directory(&self) -> Result<(), std::io::Error> {
if let Some(parent) = std::path::Path::new(&self.db_path).parent() {
std::fs::create_dir_all(parent)?;
}
Ok(())
}
}

View File

@@ -1,23 +1,31 @@
use crate::config::Config;
use anyhow::Result;
use sqlx::migrate::Migrator;
use sqlx::sqlite::{SqliteConnectOptions, SqliteConnection};
use sqlx::{Connection, SqlitePool};
use sqlx::{Pool, Sqlite, SqlitePool};
use std::str::FromStr;
use tracing::info;
pub const MIGRATOR: Migrator = sqlx::migrate!("./migrations");
pub async fn initialize_db(db_path: &str, _migrations_dir: &str) -> Result<SqliteConnection> {
let options =
SqliteConnectOptions::from_str(&format!("sqlite:{}", db_path))?.create_if_missing(true);
let mut conn = SqliteConnection::connect_with(&options).await?;
pub async fn initialize_db(config: &Config) -> Result<Pool<Sqlite>> {
config.ensure_db_directory()?;
MIGRATOR.run(&mut conn).await?;
let options = SqliteConnectOptions::from_str(&config.database_url())?
.create_if_missing(true)
.journal_mode(sqlx::sqlite::SqliteJournalMode::Wal)
.foreign_keys(true);
Ok(conn)
}
let pool = SqlitePool::connect_with(options).await?;
pub async fn create_pool(opts: SqliteConnectOptions) -> Result<SqlitePool> {
let pool = SqlitePool::connect_with(opts).await?;
MIGRATOR.run(&pool).await?;
info!("Database migrations completed successfully");
Ok(pool)
}
pub async fn create_pool(opts: SqliteConnectOptions) -> Result<SqlitePool> {
let pool = SqlitePool::connect_with(opts).await?;
Ok(pool)
}

View File

@@ -5,35 +5,74 @@ mod models;
mod services;
use crate::config::Config;
use anyhow::Result;
use axum::Router;
use axum::routing::get;
use sqlx::sqlite::SqliteConnectOptions;
use std::str::FromStr;
use tokio::signal;
use tokio::signal::ctrl_c;
use tokio::signal::unix::signal;
use tracing::{error, info};
use tracing_subscriber;
#[tokio::main]
async fn main() {
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_target(false)
.compact()
.init();
let config = Config::from_env();
match db::initialize_db(&config.db_path, &config.migration_path).await {
Ok(_conn) => {
println!("Database initialized successfully");
let pool = db::initialize_db(&config).await?;
let options = SqliteConnectOptions::from_str(&config.database_url())
.expect("Invalid database URL")
.create_if_missing(true);
let app = create_app(pool);
match db::create_pool(options).await {
Ok(_pool) => {
println!("Database pool created successfully")
// App logic here
}
Err(e) => {
println!("Error creating database pool: {:?}", e);
std::process::exit(1);
}
}
}
Err(e) => {
println!("Error initializing database: {:?}", e);
std::process::exit(1);
}
}
let listener =
tokio::net::TcpListener::bind(format!("{}:{}", config.host, config.port)).await?;
info!("Server starting on {}:{}", config.host, config.port);
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
Ok(())
}
fn create_app(pool: sqlx::SqlitePool) -> Router {
Router::new()
.route("/health", get(health_check))
.nest("/api", api::routes::routes())
.with_state(pool)
}
async fn health_check() -> &'static str {
"OK"
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install CTRL+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install terminate handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
info!("Signal received, shutting down");
}