Skip to content

Commit

Permalink
finished: Part IV: Basic Server & log tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonkayZK committed Dec 8, 2021
1 parent 51120a3 commit 7526728
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 99 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Expand Up @@ -17,3 +17,7 @@ serde = { version = "1.0.126", features = ["derive"] }
sqlx = { version = "0.5.5", features = ["runtime-tokio-rustls", "postgres", "migrate"] }
tokio = { version = "1.6.2", features = ["full"] }
async-trait = { version = "0.1.51" }
hyper = "0.14.9"
routerify = "2.1.0"
tracing = "0.1.26"
tracing-subscriber = "0.2.18"
3 changes: 2 additions & 1 deletion src/dao/base_mapper.rs
Expand Up @@ -8,6 +8,7 @@ type Responder<T> = Sender<Result<T, sqlx::Error>>;
pub type BaseConnection = PoolConnection<Postgres>;

#[derive(Debug)]
#[allow(dead_code)]
pub enum BaseMapperEnum<I, T> {
ReadDataList { resp: Responder<Vec<T>> },
ReadDataById { id: I, resp: Responder<T> },
Expand All @@ -21,7 +22,7 @@ macro_rules! resp_failed {
($m: expr, $f: tt) => {
match $m {
Ok(_) => {}
Err(e) => eprintln!("Resp failed for {}, error: {:?}", $f, e),
Err(e) => tracing::error!("Resp failed for {}, error: {:?}", $f, e),
}
};
}
Expand Down
110 changes: 12 additions & 98 deletions src/main.rs
@@ -1,20 +1,28 @@
use crate::configs::conf::CONFIG;
use crate::configs::database::DbHandle;
use crate::dao::base_mapper::BaseMapperEnum;
use crate::dao::url_map_dao::{UrlMap, UrlMapDao};
use crate::dao::url_map_dao::UrlMapDao;
use anyhow::Result;
use std::sync::Arc;
use tracing::info;
use tracing::subscriber::set_global_default;
use tracing_subscriber::FmtSubscriber;

mod configs;
mod dao;
mod server;

#[tokio::main]
async fn main() -> Result<()> {
println!("{:?}", CONFIG);
let subscriber = FmtSubscriber::new();
let _ = set_global_default(subscriber);

info! {
"{:?}", CONFIG
}

let db = DbHandle::new().await.unwrap();
let db = Arc::new(db);

let (db_tx, db_rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
let mut manager = UrlMapDao::new(db, db_rx);
Expand All @@ -33,101 +41,7 @@ async fn main() -> Result<()> {
Err(e) => eprintln!("Unable to get url_maps: {}", e),
}

// Create
let (tx, rx) = tokio::sync::oneshot::channel();
match db_tx
.send(BaseMapperEnum::CreateData {
data: UrlMap {
key: String::from("linkedin"),
url: String::from("linkedin.com"),
},
resp: tx,
})
.await
{
Ok(_) => {}
Err(e) => eprintln!("Failed to send to database manager: {}", e),
}
let url_maps = rx.await.unwrap();
match url_maps {
Ok(ums) => println!("url_maps: {:?}", ums),
Err(e) => eprintln!("Unable to get url_maps: {}", e),
}

// Read
let (tx, rx) = tokio::sync::oneshot::channel();
match db_tx
.send(BaseMapperEnum::ReadDataById {
id: "linkedin".into(),
resp: tx,
})
.await
{
Ok(_) => {}
Err(e) => eprintln!("Failed to send to database manager: {}", e),
}
let url_maps = rx.await.unwrap();
match url_maps {
Ok(ums) => println!("url_maps: {:?}", ums),
Err(e) => eprintln!("Unable to get url_maps: {}", e),
}

// Update
let (tx, rx) = tokio::sync::oneshot::channel();
match db_tx
.send(BaseMapperEnum::UpdateData {
data: UrlMap {
key: String::from("linkedin"),
url: String::from("linkedin.com2"),
},
resp: tx,
})
.await
{
Ok(_) => {}
Err(e) => eprintln!("Failed to send to database manager: {}", e),
}
let url_maps = rx.await.unwrap();
match url_maps {
Ok(ums) => println!("url_maps: {:?}", ums),
Err(e) => eprintln!("Unable to get url_maps: {}", e),
}

// Read Again
let (tx, rx) = tokio::sync::oneshot::channel();
match db_tx
.send(BaseMapperEnum::ReadDataById {
id: "linkedin".into(),
resp: tx,
})
.await
{
Ok(_) => {}
Err(e) => eprintln!("Failed to send to database manager: {}", e),
}
let url_maps = rx.await.unwrap();
match url_maps {
Ok(ums) => println!("url_maps: {:?}", ums),
Err(e) => eprintln!("Unable to get url_maps: {}", e),
}

// Delete
let (tx, rx) = tokio::sync::oneshot::channel();
match db_tx
.send(BaseMapperEnum::DeleteDataById {
id: "linkedin".into(),
resp: tx,
})
.await
{
Ok(_) => {}
Err(e) => eprintln!("Failed to send to database manager: {}", e),
}
let url_maps = rx.await.unwrap();
match url_maps {
Ok(ums) => println!("url_maps: {:?}", ums),
Err(e) => eprintln!("Unable to get url_maps: {}", e),
}
server::listen().await?;

Ok(())
}
4 changes: 4 additions & 0 deletions src/server/mod.rs
@@ -0,0 +1,4 @@
mod router;
mod serve;

pub use serve::listen;
34 changes: 34 additions & 0 deletions src/server/router.rs
@@ -0,0 +1,34 @@
use hyper::{Body, Request, Response, StatusCode};
use routerify::{ext::RequestExt, Error, Middleware, RequestInfo, Router};
use tracing::{error, info};

async fn logger(req: Request<Body>) -> Result<Request<Body>, Error> {
info!(
"{} {} {}",
req.remote_addr(),
req.method(),
req.uri().path()
);
Ok(req)
}

async fn error_handler(err: routerify::RouteError, _: RequestInfo) -> Response<Body> {
error!("{}", err);
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from(format!("Something went wrong: {}", err)))
.unwrap()
}

async fn home_handler(_: Request<Body>) -> Result<Response<Body>, Error> {
Ok(Response::new(Body::from("Url Mapper in Rust!")))
}

pub fn router() -> Router<Body, Error> {
Router::builder()
.middleware(Middleware::pre(logger))
.get("/", home_handler)
.err_handler_with_info(error_handler)
.build()
.unwrap()
}
17 changes: 17 additions & 0 deletions src/server/serve.rs
@@ -0,0 +1,17 @@
use crate::server::router::router;
use crate::CONFIG;
use anyhow::Result;
use hyper::Server;
use routerify::RouterService;
use tracing::info;

pub async fn listen() -> Result<()> {
let router = router();
let service = RouterService::new(router).unwrap();
let address = format!("{}:{}", CONFIG.host, CONFIG.port).parse()?;

let server = Server::bind(&address).serve(service);
info!("Server started listening on {}", address);
server.await?;
Ok(())
}

0 comments on commit 7526728

Please sign in to comment.