Skip to content

Commit

Permalink
fix(test): adding shutdown test plus reformating
Browse files Browse the repository at this point in the history
  • Loading branch information
Christiantyemele committed Jul 2, 2024
1 parent 5f9800f commit 4161afb
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 21 deletions.
4 changes: 3 additions & 1 deletion generic-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ chrono = { version = "0.4.26", optional = true }
did-endpoint = { path = "../did-endpoint", optional = true }
oob-messages = { path = "../oob-messages", optional = true }
tokio-util = {version = "0.7.11", features = ["rt"] }
once_cell = "1.19.0"

[dev-dependencies]
tower = { version = "0.4.13", features = ["util"] }

assert_cmd = "2.0"
predicates = "3.0.4"
[features]
default = ["plugin-index", "plugin-did_endpoint", "plugin-oob_messages"]

Expand Down
72 changes: 52 additions & 20 deletions generic-server/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,49 +1,53 @@
use generic_server::app;

use axum::Server;
use std::net::SocketAddr;
use generic_server::app;
use once_cell::sync::Lazy;
use std::{net::SocketAddr, sync::Arc};
use tokio::sync::{mpsc::Sender, Mutex};
use tokio_util::sync::CancellationToken;

// create a global signal shutdown signal transmitter
static SHUTDOWN: Lazy<Arc<Mutex<Option<Sender<String>>>>> = Lazy::new(|| Arc::new(Mutex::new(None)));
#[tokio::main]
async fn main() {

//creating cancellation token which can be cloned and closed to tell server and process to finish
// Start server
let port = std::env::var("SERVER_LOCAL_PORT").unwrap_or("3000".to_owned());
let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
tracing::info!("listening on {addr}");
run_and_shutdown_server(addr).await
}

async fn run_and_shutdown_server(add: SocketAddr) {
//creating cancellation token which can be cloned and closed to tell server and process to finish
let token = CancellationToken::new();

// Load dotenv-flow variables
dotenv_flow::dotenv_flow().ok();

// Enable logging
config_tracing();

// Start server
let port = std::env::var("SERVER_LOCAL_PORT").unwrap_or("3000".to_owned());
let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
tracing::info!("listening on {addr}");

// create a messager which will send the shutdown message to the server and its processes
// any process which wishes to stop the server can send a shutdown message to the shutdown transmitter
let (_shutdown_tx, mut shutdown_rx) = tokio::sync::mpsc::channel::<String>(2);
let (shutdown_tx, mut shutdown_rx) = tokio::sync::mpsc::channel::<String>(2);

// spawn task for server
tokio::spawn(async move {
Server::bind(&addr)
tokio::spawn(async move {
Server::bind(&add)
.serve(app().into_make_service())
.await
.unwrap();
});
// watching on shutdown events/signals to gracefully shutdown servers
let mut lock = SHUTDOWN.lock().await;
lock.replace(shutdown_tx);

// watching on shutdown events/signals to gracefully shutdown servers
tokio::select! {
_msg = shutdown_rx.recv() => {eprintln!("\nshutting down gracefully:{}", _msg.unwrap()); token.cancel()}
_msg = shutdown_rx.recv() => {eprintln!("\nshutting down gracefully:{:?}", _msg); token.cancel()}
_ = tokio::signal::ctrl_c() => {eprintln!("\nshutting down gracefully"); token.cancel()}
}
};
}

fn config_tracing() {
use tracing::Level;
use tracing_subscriber::{filter, layer::SubscriberExt, util::SubscriberInitExt};

let tracing_layer = tracing_subscriber::fmt::layer();
let filter = filter::Targets::new()
.with_target("hyper::proto", Level::INFO)
Expand All @@ -55,3 +59,31 @@ fn config_tracing() {
.with(filter)
.init();
}

#[cfg(test)]
mod tests {
use super::*;
use std::net::SocketAddr;

#[tokio::test]
async fn test_server_shutdown() {
let port = std::env::var("SERVER_LOCAL_PORT").unwrap_or("3000".to_owned());
let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
tracing::info!("listening on {addr}");

// run server in background
tokio::spawn(run_and_shutdown_server(addr));

// send shutdown signal
let mut lock = SHUTDOWN.lock().await;
let sender = lock.as_mut();
match sender {
Some(sender) => {
sender.send("value".to_owned()).await.unwrap();

}
None => {}
}

}
}

0 comments on commit 4161afb

Please sign in to comment.