Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Database and redis configurations added #3

Merged
merged 1 commit into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
873 changes: 859 additions & 14 deletions backend/Cargo.lock

Large diffs are not rendered by default.

20 changes: 14 additions & 6 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,20 @@ name = "backend"

[dependencies]
actix-web = "4"
config = { version = "0.13.3", features = ["yaml"] }
dotenv = "0.15.0"
serde = "1.0.160"
tokio = { version = "1.27.0", features = ["macros", "rt-multi-thread"] }
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.17", features = [
config = { version = "0.13", features = ["yaml"] }
deadpool-redis = "0.11"
dotenv = "0.15"
serde = "1"
sqlx = { version = "0.6", features = [
"runtime-actix-rustls",
"postgres",
"uuid",
"chrono",
"migrate",
] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = [
"fmt",
"std",
"env-filter",
Expand Down
3 changes: 3 additions & 0 deletions backend/migrations/20230423180653_users_table.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Add down migration script here
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS user_profile;
34 changes: 34 additions & 0 deletions backend/migrations/20230423180653_users_table.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
-- Add up migration script here
-- User table
CREATE TABLE IF NOT EXISTS users(
id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
is_active BOOLEAN DEFAULT FALSE,
is_staff BOOLEAN DEFAULT FALSE,
is_superuser BOOLEAN DEFAULT FALSE,
thumbnail TEXT NULL,
date_joined TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS users_id_email_is_active_indx ON users (id, email, is_active);
-- Create a domain for phone data type
CREATE DOMAIN phone AS TEXT CHECK(
octet_length(VALUE) BETWEEN 1
/*+*/
+ 8 AND 1
/*+*/
+ 15 + 3
AND VALUE ~ '^\+\d+$'
);
-- User details table (One-to-one relationship)
CREATE TABLE user_profile (
id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL UNIQUE,
phone_number phone NULL,
birth_date DATE NULL,
github_link TEXT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS users_detail_id_user_id ON user_profile (id, user_id);
15 changes: 15 additions & 0 deletions backend/settings/base.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
application:
port: 5000

database:
username: "quickcheck"
password: "password"
port: 5432
host: "localhost"
database_name: "rust_auth_db_dev"
require_ssl: false

redis:
uri: "redis://127.0.0.1:6379"
pool_max_open: 16
pool_max_idle: 8
pool_timeout_seconds: 1
pool_expire_seconds: 60
2 changes: 1 addition & 1 deletion backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ async fn main() -> std::io::Result<()> {
let subscriber = backend::telemetry::get_subscriber(settings.clone().debug);
backend::telemetry::init_subscriber(subscriber);

let application = backend::startup::Application::build(settings).await?;
let application = backend::startup::Application::build(settings, None).await?;

tracing::event!(target: "backend", tracing::Level::INFO, "Listening on http://127.0.0.1:{}/", application.port());

Expand Down
1 change: 1 addition & 0 deletions backend/src/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod health;
mod users;

pub use health::health_check;
1 change: 1 addition & 0 deletions backend/src/routes/users/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mod register;
Empty file.
44 changes: 44 additions & 0 deletions backend/src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use sqlx::ConnectOptions;

/// Global settings for the exposing all preconfigured variables
#[derive(serde::Deserialize, Clone)]
pub struct Settings {
pub application: ApplicationSettings,
pub debug: bool,
pub database: DatabaseSettings,
pub redis: RedisSettings,
}

/// Application's specific settings to expose `port`,
Expand All @@ -16,6 +20,46 @@ pub struct ApplicationSettings {
pub protocol: String,
}

/// Redis settings for the entire app
#[derive(serde::Deserialize, Clone, Debug)]
pub struct RedisSettings {
pub uri: String,
pub pool_max_open: u64,
pub pool_max_idle: u64,
pub pool_timeout_seconds: u64,
pub pool_expire_seconds: u64,
}

/// Database settings for the entire app
#[derive(serde::Deserialize, Clone)]
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub port: u16,
pub host: String,
pub database_name: String,
pub require_ssl: bool,
}

impl DatabaseSettings {
pub fn connect_to_db(&self) -> sqlx::postgres::PgConnectOptions {
let ssl_mode = if self.require_ssl {
sqlx::postgres::PgSslMode::Require
} else {
sqlx::postgres::PgSslMode::Prefer
};
let mut options = sqlx::postgres::PgConnectOptions::new()
.host(&self.host)
.username(&self.username)
.password(&self.password)
.port(self.port)
.ssl_mode(ssl_mode)
.database(&self.database_name);
options.log_statements(tracing::log::LevelFilter::Trace);
options
}
}

/// The possible runtime environment for our application.
pub enum Environment {
Development,
Expand Down
49 changes: 45 additions & 4 deletions backend/src/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,29 @@ pub struct Application {
}

impl Application {
pub async fn build(settings: crate::settings::Settings) -> Result<Self, std::io::Error> {
pub async fn build(
settings: crate::settings::Settings,
test_pool: Option<sqlx::postgres::PgPool>,
) -> Result<Self, std::io::Error> {
let connection_pool = if let Some(pool) = test_pool {
pool
} else {
get_connection_pool(&settings.database).await
};

sqlx::migrate!()
.run(&connection_pool)
.await
.expect("Failed to migrate the database.");

let address = format!(
"{}:{}",
settings.application.host, settings.application.port
);

let listener = std::net::TcpListener::bind(&address)?;
let port = listener.local_addr().unwrap().port();
let server = run(listener).await?;
let server = run(listener, connection_pool, settings).await?;

Ok(Self { port, server })
}
Expand All @@ -26,9 +40,36 @@ impl Application {
}
}

async fn run(listener: std::net::TcpListener) -> Result<actix_web::dev::Server, std::io::Error> {
pub async fn get_connection_pool(
settings: &crate::settings::DatabaseSettings,
) -> sqlx::postgres::PgPool {
sqlx::postgres::PgPoolOptions::new()
.acquire_timeout(std::time::Duration::from_secs(2))
.connect_lazy_with(settings.connect_to_db())
}

async fn run(
listener: std::net::TcpListener,
db_pool: sqlx::postgres::PgPool,
settings: crate::settings::Settings,
) -> Result<actix_web::dev::Server, std::io::Error> {
// Database connection pool application state
let pool = actix_web::web::Data::new(db_pool);

// Redis connection pool
let cfg = deadpool_redis::Config::from_url(settings.clone().redis.uri);
let redis_pool = cfg
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
.expect("Cannot create deadpool redis.");
let redis_pool_data = actix_web::web::Data::new(redis_pool);

let server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(crate::routes::health_check)
actix_web::App::new()
.service(crate::routes::health_check)
// Add database pool to application state
.app_data(pool.clone())
// Add redis pool to application state
.app_data(redis_pool_data.clone())
})
.listen(listener)?
.run();
Expand Down