Skip to content

Commit

Permalink
Added helper functions to clean up main.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
Blckbrry-Pi committed Sep 10, 2023
1 parent 7df7184 commit d5beade
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 46 deletions.
10 changes: 10 additions & 0 deletions src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ pub async fn connect_as(connection_name: &str) -> Result<PgPool, sqlx::Error> {
Ok(client)
}

pub fn unwrap_connection(connection_result: Result<PgPool, sqlx::Error>) -> PgPool {
match connection_result {
Ok(client) => client,
Err(e) => {
crate::logging::error!("Failed to connect to eureka db: {e}");
crate::logging::debug!("Eureka db error: {e:#?}");
panic!("Failed to connect to eureka db: {e}");
}
}
}

pub type Ctx = sqlx::pool::PoolConnection<sqlx::Postgres>;

Expand Down
8 changes: 8 additions & 0 deletions src/graphql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,11 @@ pub fn schema(app_state: AppState) -> Schema {
.data(app_state)
.finish()
}

pub fn save_schema(schema: &Schema, path: &str) {
if let Err(err) = std::fs::write(path, schema.sdl()) {
crate::logging::warn!("Schema failed to save to {path}: {err}");
} else {
crate::logging::info!("Schema saved to {path}");
}
}
12 changes: 11 additions & 1 deletion src/logs_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub mod logging {
//!
//! Usually you should just import all of it with
//! ```no_run
//! use crate::log_env::logging::*;
//! use crate::logging::*;
//! ```
use arcs_logging_rs::with_target;
Expand Down Expand Up @@ -65,6 +65,16 @@ pub mod env {
use arcs_env_rs::*;

env_var_req!(PORT);

pub fn port_u16_panic() -> u16 {
let port = port();
let Ok(port) = port.parse() else {
crate::logging::error!("Failed to parse port as u16");
crate::logging::debug!("Port: {:#?}", port);
panic!("Failed to parse port as u16");
};
port
}

assert_req_env!(
check_env_vars:
Expand Down
84 changes: 41 additions & 43 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,47 @@ use arcs_logging_rs::set_up_logging;



use improved_eureka::env::port_u16_panic;
use improved_eureka::{state::AppState, graphql::Schema};
use improved_eureka::graphql::schema;
use improved_eureka::graphql::{schema, save_schema};

use improved_eureka::database::connect_as;
use improved_eureka::database::{connect_as, unwrap_connection};
use improved_eureka::logging::*;





#[actix_web::main]
async fn main() -> std::io::Result<()> {
info!("Server process started");

let (schema, bind_to) = get_setup().await;

let server = HttpServer::new(move || {
debug!("Server thread spun up");
App::new()
.app_data(schema.clone())
.service(graphql_handler)
.service(interactive)
})
.bind(bind_to)?
.run();

let (result, _) = tokio::join!(
server,
async { info!("Server bound to {}:{}", bind_to.0, bind_to.1); },
);

result
}

/// This function does most of the "dirty work" of setting up the server.
///
/// It's here to keep the main function clean, and it also represents a
/// separation of concerns in that it will reduce the data needed to run the
/// server down to just 2 values.
async fn get_setup() -> (actix_web::web::Data<Schema>, (&'static str, u16)) {
dotenvy::dotenv().unwrap();
set_up_logging(&arcs_logging_rs::DEFAULT_LOGGGING_TARGETS, "TableJet Improved Eureka").unwrap();

Expand All @@ -23,55 +55,21 @@ async fn main() -> std::io::Result<()> {
}


let postgres_connect_result = connect_as("TableJet Improved Eureka").await;

let db = match postgres_connect_result {
Ok(client) => client,
Err(e) => {
error!("failed to connect to eureka db: {e}");
debug!("Eureka db error: {e:#?}");
panic!("Failed to connect to eureka db: {e}");
}
};
info!("Connected to db");
let db = connect_as("TableJet Improved Eureka").await;
let db = unwrap_connection(db);
let ctx: AppState = AppState::new(db);
info!("Connected to db");

let schema = schema(ctx); // (true, Some(std::path::Path::new("./schema.graphql"))).unwrap();
let schema = schema(ctx);
info!("Created schema");

if let Err(err) = std::fs::write("./schema.graphql", schema.sdl()) {
warn!("Schema failed to save: {err}");
} else {
info!("Schema saved");
}
save_schema(&schema, "./schema.graphql");


let ip = "0.0.0.0";
let port = port_u16_panic();

let port = improved_eureka::env::port();

let Ok(port) = port.parse() else {
error!("Failed to parse port as u16");
debug!("Port: {:#?}", port);
panic!("Failed to parse port as u16");
};

let server = HttpServer::new(move || {
debug!("Server thread spun up");
App::new()
.app_data(actix_web::web::Data::new(schema.clone()))
.service(graphql_handler)
.service(interactive)
})
.bind((ip, port))?
.run();

let (result, _) = tokio::join!(
server,
async { info!("Server started bound to {ip}:{port}"); },
);

result
(actix_web::web::Data::new(schema), (ip, port))
}


Expand Down
10 changes: 8 additions & 2 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
use sqlx::PgPool;

#[derive(Debug, Clone)]
pub struct WebContext {
pub db: PgPool,
db: PgPool,
}
impl WebContext {
pub fn new(db: PgPool) -> Self {
Self { db }
}
}

#[derive(Clone)]
pub struct AppState(std::sync::Arc<WebContext>);
impl AppState {
pub fn new(db: PgPool) -> Self {
Self(std::sync::Arc::new(WebContext { db }))
Self(std::sync::Arc::new(WebContext::new(db)))
}

pub fn db(&self) -> &PgPool {
Expand Down

0 comments on commit d5beade

Please sign in to comment.