restructured, added db connection pool

This commit is contained in:
Andre Heber
2024-02-15 13:00:04 +01:00
parent b6679e2436
commit bb94bde843
14 changed files with 1400 additions and 38 deletions

1
.env Normal file
View File

@ -0,0 +1 @@
DATABASE_URL="postgres://postgres:password@localhost:5432/newsletter"

1139
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -15,5 +15,19 @@ name = "zero2prod"
[dependencies] [dependencies]
actix-web = "4" actix-web = "4"
tokio = { version="1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
reqwest = "0.11" reqwest = "0.11"
serde = { version = "1", features = ["derive"] }
config = "0.14"
[dependencies.sqlx]
version = "0.7.3"
default-features = false
features = [
"runtime-tokio-rustls",
"macros",
"postgres",
"uuid",
"chrono",
"migrate",
]

7
configuration.yaml Normal file
View File

@ -0,0 +1,7 @@
application_port: 8000
database:
host: "127.0.0.1"
port: 5432
username: "postgres"
password: "password"
database_name: "newsletter"

View File

@ -0,0 +1,8 @@
-- Add migration script here
CREATE TABLE subscriptions(
id uuid NOT NULL,
PRIMARY KEY (id),
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
subscribed_at timestamptz NOT NULL
);

52
scripts/init_db.sh Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env bash
set -x
set -eo pipefail
if ! [ -x "$(command -v psql)" ]; then
echo >&2 "Error: psql is not installed."
exit 1
fi
if ! [ -x "$(command -v sqlx)" ]; then
echo >&2 "Error: sqlx is not installed."
echo >&2 "Use:"
echo >&2 " cargo install --version=0.5.7 sqlx-cli --no-default-features --features postgres"
echo >&2 "to install it."
exit 1
fi
# Check if a custom user has been set, otherwise default to 'postgres'
DB_USER=${POSTGRES_USER:=postgres}
# Check if a custom password has been set, otherwise default to 'password'
DB_PASSWORD="${POSTGRES_PASSWORD:=password}"
# Check if a custom database name has been set, otherwise default to 'newsletter'
DB_NAME="${POSTGRES_DB:=newsletter}"
# Check if a custom port has been set, otherwise default to '5432'
DB_PORT="${POSTGRES_PORT:=5432}"
# Launch postgres using Docker
if [[ -z "${SKIP_DOCKER}" ]]
then
docker run \
-e POSTGRES_USER=${DB_USER} \
-e POSTGRES_PASSWORD=${DB_PASSWORD} \
-e POSTGRES_DB=${DB_NAME} \
-p "${DB_PORT}":5432 \
-d postgres \
postgres -N 1000
# ^ Increased maximum number of connections for testing purposes
fi
# Keep pinging Postgres until it's ready to accept commands
export PGPASSWORD="${DB_PASSWORD}"
until psql -h "localhost" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do
>&2 echo "Postgres is still unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up and running on port ${DB_PORT}!"
export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME}
sqlx database create
sqlx migrate run
>&2 echo "Postgres has been migrated, ready to go!"

38
src/configuration.rs Normal file
View File

@ -0,0 +1,38 @@
use config::Config;
#[derive(serde::Deserialize)]
pub struct Settings {
pub database: DatabaseSettings,
pub application_port: u16,
}
#[derive(serde::Deserialize)]
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub port: u16,
pub host: String,
pub database_name: String,
}
impl DatabaseSettings {
pub fn connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database_name
)
}
}
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// let mut settings = config::Config::default();
// settings.merge(config::File::with_name("configuration"))?;
// settings.try_into()
let settings = Config::builder()
.add_source(config::File::with_name("configuration"))
.build()?;
Ok(settings.try_deserialize()?)
}

View File

@ -1,18 +1,3 @@
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder}; pub mod configuration;
use actix_web::dev::Server; pub mod routes;
use std::net::TcpListener; pub mod startup;
async fn health_check() -> HttpResponse {
HttpResponse::Ok().into()
}
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let server = HttpServer::new(|| {
App::new()
.route("/health_check", web::get().to(health_check))
})
.listen(listener)?
.run();
Ok(server)
}

View File

@ -1,9 +1,15 @@
use std::net::TcpListener; use std::net::TcpListener;
use sqlx::postgres::PgPoolOptions;
use zero2prod::run; use zero2prod::configuration::get_configuration;
use zero2prod::startup::run;
#[tokio::main] #[tokio::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8000").expect("Failed to bind random port"); let config = get_configuration().expect("Failed to read configuration");
run(listener)?.await let connection = PgPoolOptions::new()
.max_connections(10).connect(&config.database.connection_string()).await.expect("Failed to connect to Postgres.");
let address = format!("127.0.0.1:{}", config.application_port);
let listener = TcpListener::bind(address).expect("Failed to bind random port");
run(listener, connection)?.await
} }

View File

@ -0,0 +1,5 @@
use actix_web::HttpResponse;
pub async fn health_check() -> HttpResponse {
HttpResponse::Ok().into()
}

5
src/routes/mod.rs Normal file
View File

@ -0,0 +1,5 @@
mod health_check;
mod subscriptions;
pub use health_check::*;
pub use subscriptions::*;

View File

@ -0,0 +1,12 @@
use actix_web::{web, HttpResponse};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct FormData {
pub email: String,
pub name: String,
}
pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse {
HttpResponse::Ok().finish()
}

20
src/startup.rs Normal file
View File

@ -0,0 +1,20 @@
use actix_web::dev::Server;
use actix_web::{web, App, HttpServer};
use sqlx::{Pool, Postgres};
use std::net::TcpListener;
use crate::routes::{health_check, subscribe};
pub fn run(listener: TcpListener, connection: Pool<Postgres>) -> Result<Server, std::io::Error> {
let connection = web::Data::new(connection);
let server = HttpServer::new(move || {
App::new()
.route("/health_check", web::get().to(health_check))
.route("/subscriptions", web::post().to(subscribe))
.app_data(connection.clone())
})
.listen(listener)?
.run();
Ok(server)
}

View File

@ -1,23 +1,97 @@
use sqlx::{postgres::PgPoolOptions, query, Connection, PgConnection, Pool, Postgres};
use std::net::TcpListener; use std::net::TcpListener;
use zero2prod::configuration::get_configuration;
fn spawn_app(connection: Pool<Postgres>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = zero2prod::startup::run(listener, connection).expect("Failed to bind address");
tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}
#[tokio::test] #[tokio::test]
async fn health_check_works() { async fn health_check_works() {
let address = spawn_app(); let config = get_configuration().expect("Failed to read configuration");
let health_check_endpoint = format!("{}/health_check", address); let connection = PgPoolOptions::new()
let client = reqwest::Client::new(); .max_connections(10).connect(&config.database.connection_string()).await.expect("Failed to connect to Postgres.");
let response = client.get(health_check_endpoint)
.send().await.expect("Failed to execute request.");
assert!(response.status().is_success()); let address = spawn_app(connection);
assert_eq!(Some(0), response.content_length()); let health_check_endpoint = format!("{}/health_check", address);
let client = reqwest::Client::new();
let response = client
.get(health_check_endpoint)
.send()
.await
.expect("Failed to execute request.");
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
} }
fn spawn_app() -> String { #[tokio::test]
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port"); async fn subscribe_returns_a_200_for_valid_form_data() {
let port = listener.local_addr().unwrap().port(); let config = get_configuration().expect("Failed to read configuration");
let connection = PgPoolOptions::new()
.max_connections(10).connect(&config.database.connection_string()).await.expect("Failed to connect to Postgres.");
let server = zero2prod::run(listener).expect("Failed to bind address"); let app_address = spawn_app(connection);
tokio::spawn(server);
format!("http://127.0.0.1:{}", port) let mut connection = PgConnection::connect(&config.database.connection_string()).await.expect("Failed to connect to Postgres.");
let client = reqwest::Client::new();
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
let response = client
.post(&format!("{}/subscriptions", &app_address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request.");
assert_eq!(200, response.status().as_u16());
let saved = query!("SELECT email, name FROM subscriptions",)
.fetch_one(&mut connection)
.await
.expect("Failed to fetch saved subscription.");
assert_eq!(saved.email, "ursula_le_guin@gmail.com");
assert_eq!(saved.name, "le guin");
}
#[tokio::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
let config = get_configuration().expect("Failed to read configuration");
let connection = PgPoolOptions::new()
.max_connections(10).connect(&config.database.connection_string()).await.expect("Failed to connect to Postgres.");
let app_address = spawn_app(connection);
let client = reqwest::Client::new();
let test_cases = vec![
("name=le%20guin", "missing the email"),
("email=ursula_le_guin%40gmail.com", "missing the name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
let response = client
.post(&format!("{}/subscriptions", &app_address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
.await
.expect("Failed to execute request.");
assert_eq!(
400,
response.status().as_u16(),
"The API did not fail with 400 Bad Request when the payload was {}.",
error_message
);
}
} }