Skip to content

Commit

Permalink
Handle graceful server shutdown form C++
Browse files Browse the repository at this point in the history
  • Loading branch information
alaarihan committed Oct 13, 2024
1 parent ec11a2b commit 1eb0f80
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
16 changes: 15 additions & 1 deletion api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::panic;
use utils::copy_database_if_not_exists;
use utils::{copy_database_if_not_exists, SHUTDOWN_CHANNEL};

pub mod app_state;
pub mod auth;
Expand All @@ -18,6 +18,20 @@ pub enum RustError {
Error = 1,
}

// Externally callable function to shut down the server for using from C++.
#[no_mangle]
pub extern "C" fn shutdown_server() {
// Send a shutdown signal to the server
let _ = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
let sender = SHUTDOWN_CHANNEL.lock().await;
sender.send(()).await.ok();
});
}

// Externally callable function to run the server for using from C++, returning a RustError.
#[no_mangle]
pub extern "C" fn run_server() -> RustError {
Expand Down
14 changes: 11 additions & 3 deletions api/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use axum::{
Router,
};

use tokio::{net::TcpListener, signal};
use tokio::{net::TcpListener, signal, sync::mpsc};
use tower_http::{
cors::{Any, CorsLayer},
services::ServeDir,
Expand All @@ -15,7 +15,7 @@ use tower_http::{
use crate::{
app_state::{self, AppState},
file::routes::file_routes,
utils::{run_migrations, SPA_DIR},
utils::{run_migrations, SHUTDOWN_CHANNEL, SPA_DIR},
};

use super::modbus_register::routes::modbus_register_routes;
Expand Down Expand Up @@ -57,7 +57,9 @@ pub async fn create_app(app_state: AppState) -> Result<Router, Box<dyn Error>> {

pub async fn server_start() -> Result<(), Box<dyn Error>> {
// Initialize tracing
tracing_subscriber::fmt::init();
if let Err(_) = tracing_subscriber::fmt().try_init() {
// Handle the error or ignore it if reinitialization is not needed
}

// Load environment variables from .env file
dotenvy::dotenv().ok();
Expand Down Expand Up @@ -89,6 +91,11 @@ pub async fn server_start() -> Result<(), Box<dyn Error>> {
}

async fn shutdown_signal(state: AppState) {
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);

// Store the sender in the SHUTDOWN_CHANNEL
*SHUTDOWN_CHANNEL.lock().await = shutdown_tx;

let ctrl_c = async {
signal::ctrl_c()
.await
Expand All @@ -109,6 +116,7 @@ async fn shutdown_signal(state: AppState) {
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
_ = shutdown_rx.recv() => {}, // Listen for the shutdown signal
}

// Drop the database connection gracefully
Expand Down
5 changes: 4 additions & 1 deletion api/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use lazy_static::lazy_static;
use migration::{Migrator, MigratorTrait};
use std::{env, fs, path::Path};
use std::{env, fs, path::Path, sync::Arc};
use tokio::sync::{mpsc, Mutex};

use crate::db_connection::establish_connection;

Expand All @@ -15,6 +16,8 @@ lazy_static! {
// SPA_DIR is set from environment variable or defaults to a local directory.
pub static ref SPA_DIR: String =
env::var("SPA_DIR").unwrap_or_else(|_| "./ResourceFile/webview/www".to_string());

pub static ref SHUTDOWN_CHANNEL: Arc<Mutex<mpsc::Sender<()>>> = Arc::new(Mutex::new(mpsc::channel(1).0));
}

// Copies the database file to the destination if it does not already exist.
Expand Down

0 comments on commit 1eb0f80

Please sign in to comment.