Skip to content

Commit

Permalink
Configure docker-compose for local development
Browse files Browse the repository at this point in the history
  • Loading branch information
SpartanPlume committed Feb 20, 2024
1 parent 8747703 commit ad01251
Show file tree
Hide file tree
Showing 20 changed files with 355 additions and 44 deletions.
6 changes: 6 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.env
target/
tests/
Dockerfile
scripts/
migrations/
4 changes: 4 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# For sqlx build
DATABASE_URL="postgres://postgres:password@localhost:5432/tosurnament"
# For docker-compose
DB_USERNAME="tosurnament"
DB_NAME="tosurnament"
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/target
secrets/

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ tracing-bunyan-formatter = "0.3"
tracing-log = "0.2"
secrecy = { version = "0.8", features = ["serde"] }
tracing-actix-web = "0.7"
serde-aux = "4"
config-secret = "0.1"

[dependencies.sqlx]
version = "0.7"
Expand Down
27 changes: 27 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
FROM lukemathwalker/cargo-chef:latest-rust-1 AS chef
WORKDIR /app

FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Build dependencies - this is the caching Docker layer!
RUN cargo chef cook --release --recipe-path recipe.json
# Build application
COPY . .
ENV SQLX_OFFLINE true
RUN cargo build --release --bin tosurnament

FROM debian:bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update -y \
&& apt-get install -y --no-install-recommends openssl ca-certificates \
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/tosurnament tosurnament
COPY configuration configuration
ENV APP_ENVIRONMENT production
ENTRYPOINT ["./tosurnament"]
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Tosurnament

## Setup

### Secrets

Create a `secrets` folder and add the following files in it:
- `db_password.txt`: Password for your db
5 changes: 5 additions & 0 deletions configuration/base.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
application:
port: 8080
database:
host: "127.0.0.1"
port: 5432
4 changes: 4 additions & 0 deletions configuration/development.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
application:
host: 0.0.0.0
database:
require_ssl: false
14 changes: 7 additions & 7 deletions configuration.yaml → configuration/local.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
application_port: 8080
database:
host: "127.0.0.1"
port: 5432
username: "postgres"
password: "password"
database_name: "tosurnament"
application:
host: "127.0.0.1"
database:
username: "postgres"
password: "password"
database_name: "tosurnament"
require_ssl: false
4 changes: 4 additions & 0 deletions configuration/production.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
application:
host: 0.0.0.0
database:
require_ssl: true
4 changes: 4 additions & 0 deletions configuration/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
application:
host: 0.0.0.0
database:
require_ssl: true
41 changes: 41 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
services:
db:
image: postgres:16
restart: always
ports:
- 5432:5432
secrets:
- db_password
environment:
- POSTGRES_USER=${DB_USERNAME}
- PGUSER=${DB_USERNAME}
- POSTGRES_PASSWORD_FILE=/run/secrets/db_password
- POSTGRES_DB=${DB_NAME}
healthcheck:
test: [ "CMD-SHELL", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
- ./migrations/20240215193936_create_tournaments_table.sql:/docker-entrypoint-initdb.d/create_tournaments_table.tosurnament.sql
server:
build:
context: .
dockerfile: Dockerfile
ports:
- 8080:8080
depends_on:
db:
condition: service_healthy
secrets:
- db_password
environment:
- APP_ENVIRONMENT=development
- APP_DATABASE__USERNAME=${DB_USERNAME}
- APP_DATABASE__PASSWORD_FILE=/run/secrets/db_password
- APP_DATABASE__DATABASE_NAME=${DB_NAME}
- APP_DATABASE__HOST=db

secrets:
db_password:
file: secrets/db_password.txt
107 changes: 85 additions & 22 deletions src/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,49 +1,112 @@
use crate::secret_env::SecretFileEnvironment;
use secrecy::{ExposeSecret, Secret};
use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::{
postgres::{PgConnectOptions, PgSslMode},
ConnectOptions,
};

#[derive(serde::Deserialize)]
pub struct Settings {
pub database: DatabaseSettings,
pub application_port: u16,
pub application: ApplicationSettings,
}

#[derive(serde::Deserialize)]
pub struct ApplicationSettings {
pub host: String,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
}

#[derive(serde::Deserialize)]
pub struct DatabaseSettings {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: String,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub database_name: String,
pub require_ssl: bool,
}

impl DatabaseSettings {
pub fn connection_string(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}/{}",
self.username,
self.password.expose_secret(),
self.host,
self.port,
self.database_name
))
pub fn without_db(&self) -> PgConnectOptions {
let ssl_mode = if self.require_ssl {
PgSslMode::Require
} else {
PgSslMode::Prefer
};
PgConnectOptions::new()
.host(&self.host)
.port(self.port)
.username(&self.username)
.password(self.password.expose_secret())
.ssl_mode(ssl_mode)
}

pub fn connection_string_without_db(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}",
self.username,
self.password.expose_secret(),
self.host,
self.port
))
pub fn with_db(&self) -> PgConnectOptions {
let options = self.without_db().database(&self.database_name);
options.log_statements(tracing_log::log::LevelFilter::Trace)
}
}

pub fn get_configuration() -> Result<Settings, config::ConfigError> {
let base_path = std::env::current_dir().expect("Failed to determine the current directory");
let configuration_dir = base_path.join("configuration");
let environment: Environment = std::env::var("APP_ENVIRONMENT")
.unwrap_or_else(|_| "local".into())
.try_into()
.expect("Failed to parse APP_ENVIRONMENT");
let environment_filename = format!("{}.yaml", environment.as_str());

let settings = config::Config::builder()
.add_source(config::File::new(
"configuration.yaml",
config::FileFormat::Yaml,
.add_source(config::File::from(configuration_dir.join("base.yaml")))
.add_source(config::File::from(
configuration_dir.join(environment_filename),
))
.add_source(
config::Environment::with_prefix("APP")
.prefix_separator("_")
.separator("__"),
)
.add_source(
SecretFileEnvironment::with_prefix("APP")
.prefix_separator("_")
.separator("__"),
)
.build()?;
settings.try_deserialize::<Settings>()
}

pub enum Environment {
Local,
Development,
Test,
Production,
}

impl Environment {
pub fn as_str(&self) -> &'static str {
match self {
Environment::Local => "local",
Environment::Development => "development",
Environment::Test => "test",
Environment::Production => "production",
}
}
}

impl TryFrom<String> for Environment {
type Error = String;

fn try_from(s: String) -> Result<Self, Self::Error> {
match s.to_lowercase().as_str() {
"local" => Ok(Self::Local),
"development" => Ok(Self::Development),
"test" => Ok(Self::Test),
"production" => Ok(Self::Production),
other => Err(format!("{} is not a supported environment", other)),
}
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod configuration;
pub mod routes;
pub mod secret_env;
pub mod startup;
pub mod telemetry;
14 changes: 8 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::net::TcpListener;

use secrecy::ExposeSecret;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;

use tosurnament::configuration::get_configuration;
use tosurnament::startup::run;
Expand All @@ -13,10 +12,13 @@ async fn main() -> Result<(), std::io::Error> {
init_subscriber(subscriber);

let configuration = get_configuration().expect("Failed to read configuration");
let db_pool = PgPool::connect(configuration.database.connection_string().expose_secret())
.await
.expect("Failed to connect to Postgres");
let address = format!("127.0.0.1:{}", configuration.application_port);
let db_pool = PgPoolOptions::new()
.acquire_timeout(std::time::Duration::from_secs(2))
.connect_lazy_with(configuration.database.with_db());
let address = format!(
"{}:{}",
configuration.application.host, configuration.application.port
);
let listener = TcpListener::bind(address).expect("Failed to bind port");
run(listener, db_pool)?.await
}
2 changes: 1 addition & 1 deletion src/routes/tournaments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ struct Tournament {
}

#[allow(clippy::async_yields_async)]
#[post("/tournament")]
#[post("/tournaments")]
#[tracing::instrument(skip_all, fields(%tournament.name))]
async fn create_tournament(
tournament: web::Json<Tournament>,
Expand Down
Loading

0 comments on commit ad01251

Please sign in to comment.