diff --git a/.env b/.env index c226415..1b358ca 100644 --- a/.env +++ b/.env @@ -1,6 +1,11 @@ -BLOG_ENDPOINT=git@github.com:Lumither/blog-posts.git +# General GIT_WORK_DIR=/home/lumither/dev/blog/blog_posts_git +BLOG_ENDPOINT=git@github.com:Lumither/blog-posts.git +LOG_ROOT_DIR=/var/log/nocturne +# Backend BACKEND_URL=https://lumither.com/api BACKEND_PORT=3001 + +## Database related DB_CONNECTION=postgresql://localhost:5432/blog diff --git a/backend/.env b/backend/.env index c226415..1b358ca 100644 --- a/backend/.env +++ b/backend/.env @@ -1,6 +1,11 @@ -BLOG_ENDPOINT=git@github.com:Lumither/blog-posts.git +# General GIT_WORK_DIR=/home/lumither/dev/blog/blog_posts_git +BLOG_ENDPOINT=git@github.com:Lumither/blog-posts.git +LOG_ROOT_DIR=/var/log/nocturne +# Backend BACKEND_URL=https://lumither.com/api BACKEND_PORT=3001 + +## Database related DB_CONNECTION=postgresql://localhost:5432/blog diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 6831286..22d1a90 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -16,3 +16,7 @@ sqlx = { version = "0.7.4", features = ["runtime-tokio", "tls-native-tls", "post chrono = { version = "0.4.38", features = ["serde", "alloc"] } regex = "1.10.4" futures = { version = "0.3.30", features = ["executor"] } +tracing = "0.1.40" +tracing-subscriber = "0.3.18" +tracing-appender = "0.2.3" +log = "0.4.21" diff --git a/backend/src/logger.rs b/backend/src/logger.rs new file mode 100644 index 0000000..f5c4421 --- /dev/null +++ b/backend/src/logger.rs @@ -0,0 +1,72 @@ +use std::{env, io}; + +use chrono::Local; +use tracing::{error, info, Level}; +use tracing_appender::{non_blocking, rolling}; +use tracing_appender::non_blocking::WorkerGuard; +use tracing_subscriber::{fmt, Registry}; +use tracing_subscriber::fmt::format::Writer; +use tracing_subscriber::fmt::MakeWriter; +use tracing_subscriber::fmt::time::FormatTime; +use tracing_subscriber::fmt::writer::MakeWriterExt; +use tracing_subscriber::layer::SubscriberExt; + +use crate::constants::GLOBAL_TIME_FORMAT; + +struct LocalTimer; + +impl FormatTime for LocalTimer { + fn format_time(&self, w: &mut Writer<'_>) -> std::fmt::Result { + write!(w, "{}", Local::now().format(GLOBAL_TIME_FORMAT)) + } +} + +type LogWriter = dyn for<'writer> MakeWriter<'writer, Writer = dyn io::Write + 'static> + 'static; + +pub fn init() -> (WorkerGuard, WorkerGuard) { + let log_path = env::var("LOG_ROOT_DIR").unwrap_or_else(|e| { + panic!("[Fatal] failed to load LOG_ROOT_DIR: {}", e); + }); + + let log_path = format!("{}/backend", log_path); + + let (info_log_writer, info_guard) = non_blocking(rolling::never(&log_path, "info.log")); + // let info_log = info_log.with_max_level(Level::TRACE); + + let (err_log_writer, error_guard) = non_blocking(rolling::never(&log_path, "error.log")); + // let error_log = error_logging_handle.with_filter(|log| log.level().eq(&Level::ERROR)); + + let log_format = tracing_subscriber::fmt::format() + .with_level(true) + .with_target(true) + .with_source_location(true) + .with_timer(LocalTimer); + + // todo: separate errors/warnings/info logs + let subscribers = Registry::default() + .with( + fmt::Layer::default() + .with_writer(info_log_writer) + // .with_max_level(Level::TRACE) + .with_ansi(false), + ) + .with( + fmt::Layer::default() + .with_writer(err_log_writer) + .with_ansi(false), + ) + .with( + fmt::Layer::default() + .with_writer(io::stdout) + .with_ansi(true) + .event_format(log_format), + ); + + tracing::subscriber::set_global_default(subscribers) + .expect("[Fatal] Failed to setup logging system"); + + info!("Module Started: Logger"); + + // error!("test"); + (info_guard, error_guard) +} diff --git a/backend/src/main.rs b/backend/src/main.rs index 7f97b02..f641aa4 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1,10 +1,15 @@ use std::env; use std::error::Error; +use std::num::ParseIntError; +use std::process::exit; +use std::str::FromStr; use axum::Router; use axum::routing::{get, post}; use dotenv::dotenv; -use sqlx::postgres::PgPoolOptions; +use sqlx::ConnectOptions; +use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; +use tracing::{error, warn}; use crate::api::get::get_post::get_post; use crate::api::get::get_post_list::get_post_list; @@ -12,24 +17,49 @@ use crate::api::post::refresh::refresh; mod api; mod constants; +mod logger; mod markdown; mod model; #[tokio::main] async fn main() -> Result<(), Box> { - dotenv()?; + match dotenv() { + Ok(_) => { + println!("[Info] env loaded, starting up...") + } + Err(e) => { + panic!("[Fatal] failed to load env var: {}", e) + } + }; + + let _guards = logger::init(); let port: u32 = match env::var("BACKEND_PORT") { - Ok(value) => value.parse().unwrap(), + Ok(value) => value.parse().unwrap_or_else(|e: ParseIntError| { + warn!("Failed to parse BACKEND_PORT: {}", e.to_string()); + 3001 + }), Err(_) => 3001, }; - let db_connection: String = env::var("DB_CONNECTION")?; + let db_uri: String = env::var("DB_CONNECTION").unwrap_or_else(|e| { + error!( + "Invalid or missing env var: DB_CONNECTION: {}", + e.to_string() + ); + exit(1); + }); + let db_connect_option = PgConnectOptions::from_str(&db_uri) + .unwrap() + .disable_statement_logging(); let db_pool = PgPoolOptions::new() - .connect(&db_connection) + .connect_with(db_connect_option) .await - .expect("failed to load database"); + .unwrap_or_else(|e| { + error!("Failed to load database: {}", e.to_string()); + exit(1); + }); let app = Router::new() .route("/refresh_posts", post(refresh)) @@ -37,9 +67,17 @@ async fn main() -> Result<(), Box> { .route("/get_post/:post_id", get(get_post)) .with_state(db_pool); - let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)).await?; + let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)) + .await + .unwrap_or_else(|e| { + error!("Failed to build TCP listener: {}", e.to_string()); + exit(1); + }); - axum::serve(listener, app).await?; + axum::serve(listener, app).await.unwrap_or_else(|e| { + error!("Failed to start axum: {}", e.to_string()); + exit(1); + }); Ok(()) } diff --git a/frontend/.env b/frontend/.env index c226415..1b358ca 100644 --- a/frontend/.env +++ b/frontend/.env @@ -1,6 +1,11 @@ -BLOG_ENDPOINT=git@github.com:Lumither/blog-posts.git +# General GIT_WORK_DIR=/home/lumither/dev/blog/blog_posts_git +BLOG_ENDPOINT=git@github.com:Lumither/blog-posts.git +LOG_ROOT_DIR=/var/log/nocturne +# Backend BACKEND_URL=https://lumither.com/api BACKEND_PORT=3001 + +## Database related DB_CONNECTION=postgresql://localhost:5432/blog diff --git a/openresty/conf/blog_backend.conf b/openresty/conf/blog_backend.conf deleted file mode 100644 index 4d297fd..0000000 --- a/openresty/conf/blog_backend.conf +++ /dev/null @@ -1,16 +0,0 @@ - -location / { - default_type text/html; - proxy_pass http://localhost:3000; - proxy_redirect off; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; -} - -location /api/ { - rewrite ^/api(/.*)$ $1 break; - proxy_pass http://localhost:3001; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; -} diff --git a/openresty/conf/nocturne.conf b/openresty/conf/nocturne.conf new file mode 100644 index 0000000..787c98f --- /dev/null +++ b/openresty/conf/nocturne.conf @@ -0,0 +1,39 @@ +# server { +# listen 80; +# server_name lumither.com; + +# return 301 https://$host$request_uri; +# } + + +server { + listen 80; + # listen 443 ssl; + # server_name lumither.com; + + # ssl_certificate certs/cert.pem; + # ssl_certificate_key certs/key.pem; + + # ssl_session_cache shared:SSL:1m; + # ssl_session_timeout 5m; + + # ssl_ciphers HIGH:!aNULL:!MD5; + # ssl_prefer_server_ciphers on; + + location / { + default_type text/html; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_pass http://127.0.0.1:3000; + proxy_redirect off; + } + + location /api/ { + rewrite ^/api(/.*)$ $1 break; + proxy_pass http://127.0.0.1:3001; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } + +} \ No newline at end of file diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..2efab7c --- /dev/null +++ b/setup.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +. "$DIR/.env" + +sudo groupadd nocturne +USERNAME="$(whoami)" +echo "$USERNAME" +sudo usermod -aG nocturne "$USERNAME" + +sudo mkdir -p "$LOG_ROOT_DIR/backend" "$LOG_ROOT_DIR/frontend" +sudo chown -R :nocturne "$LOG_ROOT_DIR" +sudo chmod -R 775 "$LOG_ROOT_DIR" +