Skip to content

Commit

Permalink
refactor: improve and update comments for better clarity
Browse files Browse the repository at this point in the history
  • Loading branch information
koskeller committed Jun 4, 2024
1 parent 5798476 commit 7ce4657
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 26 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ chrono = { version = "0.4.38", features = ["serde"] }
serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.117"
uuid = { version = "1.8.0", features = ["v7", "serde"] }

dotenvy = "0.15.7"

anyhow = "1.0.86"
thiserror = "1.0.61"
6 changes: 3 additions & 3 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ pub type Config = Arc<Configuration>;

#[derive(Deserialize)]
pub struct Configuration {
/// The environment to run the application in.
/// The environment in which to run the application.
pub env: Environment,

/// The address to listen on.
pub listen_address: SocketAddr,
/// The port to listen on.
pub app_port: u16,

/// The DSN for the database. Only postgres is currently supported.
/// The DSN for the database. Currently, only PostgreSQL is supported.
pub db_dsn: String,
/// The maximum number of connections for the PostgreSQL pool.
pub db_pool_max_size: u32,
Expand Down Expand Up @@ -58,7 +58,7 @@ impl Configuration {
}

/// Sets the database DSN.
/// This method is used from the tests to override the database DSN.
/// This method is used in tests to override the database DSN.
pub fn set_dsn(&mut self, db_dsn: String) {
self.db_dsn = db_dsn
}
Expand Down
12 changes: 5 additions & 7 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ pub struct Db {
}

impl Db {
// We create a single connection pool for SQLx that's shared across the whole application.
// This saves us from opening a new connection for every API call, which is wasteful.
// We create a single connection pool for SQLx that is shared across the entire application.
// This prevents the need to open a new connection for every API call, which would be wasteful.
pub async fn new(dsn: &str, pool_max_size: u32) -> Result<Self> {
let pool = PgPoolOptions::new()
// The default connection limit for a Postgres server is 100 connections, minus 3 for superusers.
// Since we're using the default superuser we don't have to worry about this too much,
// although we should leave some connections available for manual access.
// The default connection limit for a Postgres server is 100 connections, with 3 reserved for superusers.
//
// If you're deploying your application with multiple replicas, then the total
// across all replicas should not exceed the Postgres connection limit.
Expand All @@ -24,8 +22,8 @@ impl Db {
}

pub async fn migrate(&self) -> Result<()> {
// This embeds database migrations in the application binary so we can ensure the database
// is migrated correctly on startup.
// This integrates database migrations into the application binary to ensure the database
// is properly migrated during startup.
sqlx::migrate!("./migrations").run(&self.pool).await?;
Ok(())
}
Expand Down
16 changes: 10 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use axum::Router;
use std::sync::Arc;

pub mod api_error;
pub mod cfg;
Expand All @@ -14,7 +13,7 @@ pub use db::*;
#[derive(Clone)]
pub struct AppState {
pub db: Db,
pub cfg: Arc<Configuration>,
pub cfg: Config,
}

pub fn router(cfg: Config, db: Db) -> Router {
Expand All @@ -34,16 +33,21 @@ pub fn router(cfg: Config, db: Db) -> Router {
// Layer that applies the Cors middleware which adds headers for CORS.
let cors_layer = middleware::cors_layer();

// Layer that applies the Timeout middleware which apply a timeout to requests.
// Default value is 15 seconds.
// Layer that applies the Timeout middleware, which sets a timeout for requests.
// The default value is 15 seconds.
let timeout_layer = middleware::timeout_layer();

// Any trailing slashes from request paths will be removed. For example, a request with `/foo/`
// will be changed to `/foo` before reaching the inner service.
// will be changed to `/foo` before reaching the internal service.
let normalize_path_layer = middleware::normalize_path_layer();

// Create the router with the routes.
let router = routes::router();

// Combine all the routes and apply the middleware layers.
// The order of the layers is important. The first layer is the outermost layer.
Router::new()
.merge(routes::router())
.merge(router)
.layer(normalize_path_layer)
.layer(cors_layer)
.layer(timeout_layer)
Expand Down
8 changes: 6 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ async fn main() {

// Spin up our server.
tracing::info!("Starting server on {}", cfg.listen_address);
let listener = TcpListener::bind(&cfg.listen_address).await.unwrap();
let listener = TcpListener::bind(&cfg.listen_address)
.await
.expect("Failed to bind address");
let router = server::router(cfg, db);
axum::serve(listener, router).await.unwrap()
axum::serve(listener, router)
.await
.expect("Failed to start server")
}
4 changes: 2 additions & 2 deletions src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ impl MakeRequestId for Id {
}
}

/// Sets 'x-request-id' header with randomly generated uuid v4.
/// Sets the 'x-request-id' header with a randomly generated UUID v7.
///
/// SetRequestId wont override request ids if its already present
/// SetRequestId will not override request IDs if they are already present
/// on requests or responses.
pub fn request_id_layer() -> SetRequestIdLayer<Id> {
let x_request_id = HeaderName::from_static("x-request-id");
Expand Down
10 changes: 5 additions & 5 deletions src/telemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ use tower_http::{
use tracing::Level;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

// The `EnvFilter` type is used to filter log events based on the value of an environment variable.
// In this case, we are using the `try_from_default_env` method to attempt to read the `RUST_LOG` environment variable,
// which is used to set the log level for the application.
// If the environment variable is not set, we fall back to the default log level of `debug`.
/// The `EnvFilter` type is used to filter log events based on the value of an environment variable.
/// In this case, we are using the `try_from_default_env` method to attempt to read the `RUST_LOG` environment variable,
/// which is used to set the log level for the application.
/// If the environment variable is not set, we default to the log level of `debug`.
/// The `RUST_LOG` environment variable is set in the Dockerfile and .env files.
pub fn setup_tracing() {
let env_filter_layer = EnvFilter::try_from_default_env().unwrap_or_else(|_| "debug".into());
let formatting_layer = fmt::layer().json();
Expand All @@ -20,7 +21,6 @@ pub fn setup_tracing() {

/// Returns a `TraceLayer` for HTTP requests and responses.
/// The `TraceLayer` is used to trace requests and responses in the application.
/// It includes headers and sets the log level to `INFO`.
pub fn trace_layer() -> TraceLayer<SharedClassifier<ServerErrorsAsFailures>> {
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
Expand Down

0 comments on commit 7ce4657

Please sign in to comment.