From 3a0576ba482190d4cda8d12e9edf94ca2c80ac04 Mon Sep 17 00:00:00 2001 From: minhtrannhat Date: Wed, 8 May 2024 17:27:05 -0400 Subject: [PATCH] feat(log): database operations and API logs split --- src/routes/subscriptions.rs | 59 +++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index b68f7e9..38da4f9 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -1,7 +1,6 @@ use actix_web::{web, HttpResponse}; use chrono::Utc; use sqlx::PgPool; -use tracing::Instrument; use uuid::Uuid; #[derive(serde::Deserialize)] @@ -10,45 +9,49 @@ pub struct FormData { name: String, } +#[tracing::instrument( + name = "Adding a new subscriber", + // functions args isn't really relevant to the span + skip(form, db_conn_pool), + fields( + request_id = %Uuid::new_v4(), + subscriber_email = %form.email, + subscriber_name = %form.name + ) +)] pub async fn subscribe_route( form: web::Form, db_conn_pool: web::Data, ) -> HttpResponse { - let request_id = Uuid::new_v4(); + match insert_subscriber(&db_conn_pool, &form).await { + Ok(_) => HttpResponse::Ok().finish(), + Err(_) => HttpResponse::InternalServerError().finish(), + } +} - let request_span = tracing::info_span!( - "Adding new subscriber", - %request_id, - subscriber_email = %form.email, - subscriber_name = %form.name - ); - - let _request_span_guard = request_span.enter(); - - let query_span = tracing::info_span!("Adding new subscriber in PostgreSQL"); - - match sqlx::query!( +#[tracing::instrument( + name = "Saving new subscriber details in the database", + skip(form, pool) +)] +pub async fn insert_subscriber(pool: &PgPool, form: &FormData) -> Result<(), sqlx::Error> { + sqlx::query!( r#" INSERT INTO subscriptions (id, email, name, subscribed_at) VALUES ($1, $2, $3, $4) - "#, + "#, Uuid::new_v4(), form.email, form.name, Utc::now() ) - .execute(db_conn_pool.get_ref()) - .instrument(query_span) + .execute(pool) .await - { - Ok(_) => HttpResponse::Ok().finish(), - Err(err) => { - tracing::error!( - "request_id {} - Failed to execute query: {:?}", - request_id, - err - ); - HttpResponse::InternalServerError().finish() - } - } + .map_err(|e| { + tracing::error!("Failed to execute query: {:?}", e); + e + // Using the `?` operator to return early + // if the function failed, returning a sqlx::Error + // We will talk about error handling in depth later! + })?; + Ok(()) }