Big changes, up to 3.8.5.5

This commit is contained in:
Nick Bland 2023-08-31 23:57:30 +10:00
parent bd9f5a7819
commit 679e257f7b
15 changed files with 1021 additions and 39 deletions

1
.env Normal file
View File

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

2
.gitignore vendored
View File

@ -1,6 +1,6 @@
/target
.vscode
.env
#.env
.gitlab-ci-local
# Added by cargo

795
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,20 @@ name = "mail_app"
[dependencies]
actix-web = "4"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }
config = "0.13"
[dependencies.sqlx]
version = "0.6"
default-features = false
features = [
"runtime-tokio-rustls",
"macros",
"postgres",
"uuid",
"chrono",
"migrate"
]
[dev-dependencies]
reqwest = "0.11"

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,9 @@
-- migrations/{timestamp}_create_subscriptions_table.sql
-- Create Subscriptions Table
CREATE TABLE subscriptions(
id uuid NOT NULL,
PRIMARY KEY (id),
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
subscribed_at timestamptz NOT NULL
);

51
scripts/init_db.sh Executable file
View File

@ -0,0 +1,51 @@
#!/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.6" sqlx-cli"
echo >&2 " --no-default-features --feature rustls,postgres"
echo >&2 "to install."
exit 1
fi
DB_USER="${POSTGRES_USER:=postgres}"
DB_PASSWORD="${POSTGRES_PASSWORD:=password}"
DB_NAME="${POSTGRES_DB:=newsletter}"
DB_PORT="${POSTGRES_PORT:=5432}"
DB_HOST="${POSTGRES_HOST:=localhost}"
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 \
--name "mailAppDB" \
-d postgres:alpine \
postgres -N 1000
fi
# Ping until ready to accept commands
export PGPASSWORD="${DB_PASSWORD}"
until psql -h "${DB_HOST}" -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 running on port ${DB_PORT}, and ready to accept commands!"
DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}
export DATABASE_URL
sqlx database create
sqlx migrate run
>&2 echo "Postgres has been migrated, ready for queries!"

34
src/configuration.rs Normal file
View File

@ -0,0 +1,34 @@
#[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,
}
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// initialise config reader
let settings = config::Config::builder()
.add_source(
config::File::new("configuration.yaml", config::FileFormat::Yaml)
)
.build()?;
settings.try_deserialize::<Settings>()
}
impl DatabaseSettings {
pub fn connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database_name
)
}
}

View File

@ -1,17 +1,3 @@
use actix_web::{web, App, HttpResponse, HttpServer};
use actix_web::dev::Server;
use std::net::TcpListener;
async fn health_check() -> HttpResponse {
HttpResponse::Ok().finish()
}
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)
}
pub mod configuration;
pub mod routes;
pub mod startup;

View File

@ -1,10 +1,11 @@
use mail_app::run;
use std::net::TcpListener;
use mail_app::startup::run;
use mail_app::configuration::get_configuration;
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let listener = TcpListener::bind("127.0.0.1:8000")
.expect("Failed to bind to port 8000");
let configuration = get_configuration().expect("Failed to read config");
let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(address)?;
run(listener)?.await
}

View File

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

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,11 @@
use actix_web::{web, HttpResponse};
#[derive(serde::Deserialize)]
pub struct FormData {
email: String,
name: String,
}
pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse {
HttpResponse::Ok().finish()
}

15
src/startup.rs Normal file
View File

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

View File

@ -1,4 +1,17 @@
use std::net::TcpListener;
use sqlx::{PgConnection, Connection};
use mail_app::startup::run;
use mail_app::configuration::get_configuration;
fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port.");
let port = listener.local_addr().unwrap().port();
let server = run(listener).expect("Failed to bind address");
// Launch in background
let _spawn = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}
#[tokio::test]
async fn health_check_works() {
@ -18,13 +31,66 @@ async fn health_check_works() {
assert_eq!(Some(0), response.content_length());
}
fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0")
.expect("Failed to bind to random port.");
let port = listener.local_addr().unwrap().port();
let server = mail_app::run(listener).expect("Failed to bind address");
// Launch in background
let _spawn = tokio::spawn(server);
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
// Arrange
let app_address = spawn_app();
let configuration = get_configuration().expect("Failed to get config");
let connection_string = configuration.database.connection_string();
let mut connection = PgConnection::connect(&connection_string)
.await
.expect("Failed to connect to Postgres Database.");
let client = reqwest::Client::new();
format!("http://127.0.0.1:{}", port)
// Act
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
assert_eq!(200, response.status().as_u16());
let saved = sqlx::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() {
// Arrange
let app_address = spawn_app();
let client = reqwest::Client::new();
let test_cases = vec![
("name=le%20guin", "missing email"),
("email=ursula_le_guin%40gmail.com", "missing name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
// Act
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
assert_eq!(
400,
response.status().as_u16(),
"The API id not fail wth 400 Bad Request when the payload was {}.",
error_message
);
}
}