Skip to content

Commit

Permalink
fix: fixes warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
jaypalmudaliyar24 committed Jun 26, 2024
1 parent 522db52 commit 3cb4b49
Show file tree
Hide file tree
Showing 19 changed files with 121 additions and 127 deletions.
2 changes: 1 addition & 1 deletion crates/url_shortner/src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod types;
pub mod utils;
pub mod utils;
2 changes: 1 addition & 1 deletion crates/url_shortner/src/common/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
pub struct TimeStamp(pub DateTime<Utc>);
#[derive(Serialize, Deserialize, Clone, Debug, Eq, Hash, PartialEq)]
pub struct UrlShortCode (pub String);
pub struct UrlShortCode(pub String);
2 changes: 1 addition & 1 deletion crates/url_shortner/src/common/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ pub fn from_maybe<T>(maybe_value: Option<T>, default: T) -> T {
Some(value) => value,
None => default,
}
}
}
99 changes: 54 additions & 45 deletions crates/url_shortner/src/domain/action/internal/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ the GNU Affero General Public License along with this program. If not, see <http

use crate::{
common::{
types::{TimeStamp, UrlShortCode},
utils::from_maybe
},
domain::types::internal::crud::*,
environment::AppState,
redis::commands::set_base_url_for_short_code,
tools::error::AppError
types::{TimeStamp, UrlShortCode},
utils::from_maybe,
},
domain::types::internal::crud::*,
environment::AppState,
redis::commands::set_base_url_for_short_code,
tools::error::AppError,
};
use actix_web::web::Data;
use chrono::{Utc, Duration};
use chrono::{Duration, Utc};
use rand::{
distributions::{Alphanumeric, DistString},
thread_rng,
Expand All @@ -29,65 +29,74 @@ pub async fn generate_url(
app_state: Data<AppState>,
req: GenerateShortUrlRequest,
) -> Result<GenerateShortUrlResponse, AppError> {

println!("Generate short url req: {:?}", req);

let base_url = Url::parse(&req.base_url).map_err(|error| {
AppError::InvalidRequest(format!("URL parsing failed: {}", error))
})?;
let base_url = Url::parse(&req.base_url)
.map_err(|error| AppError::InvalidRequest(format!("URL parsing failed: {}", error)))?;

println!("Parsed URL: {:?}", base_url);

let expiry_seconds: Option<u32> = req.expiry_in_hours.and_then(|hours| Some(3600 * Into::<u32>::into(hours)));

let expiry_seconds: Option<u32> = req
.expiry_in_hours
.map(|hours| 3600 * Into::<u32>::into(hours));
let redis_expiry_in_s = from_maybe(expiry_seconds, app_state.redis_expiry);

let UrlShortCode(final_short_code) =
match req.custom_short_code {
Some(custom_short_code) => {
set_custom_code(&base_url, &custom_short_code, redis_expiry_in_s, &app_state.redis_pool).await?;
custom_short_code
},
None => {
let final_short_code = set_base_url(&base_url, redis_expiry_in_s, &app_state).await?;
final_short_code.ok_or_else(|| {
AppError::InternalError(format!("Failed to generate unique short code after {} retries", app_state.max_retries_for_shortening))
})?
}
};
let UrlShortCode(final_short_code) = match req.custom_short_code {
Some(custom_short_code) => {
set_custom_code(
&base_url,
&custom_short_code,
redis_expiry_in_s,
&app_state.redis_pool,
)
.await?;
custom_short_code
}
None => {
let final_short_code = set_base_url(&base_url, redis_expiry_in_s, &app_state).await?;
final_short_code.ok_or_else(|| {
AppError::InternalError(format!(
"Failed to generate unique short code after {} retries",
app_state.max_retries_for_shortening
))
})?
}
};

let url_expiry = TimeStamp(Utc::now() + Duration::seconds(redis_expiry_in_s.into()));
let short_url = format!("{}/{}", app_state.shortened_base_url, final_short_code);
println!("Generated short url: {} with expiry ts: {:?}", short_url, url_expiry.0);
println!(
"Generated short url: {} with expiry ts: {:?}",
short_url, url_expiry.0
);

Ok(GenerateShortUrlResponse {
short_url,
url_expiry,
})
}

async fn set_custom_code (
async fn set_custom_code(
base_url: &Url,
short_code: &UrlShortCode,
redis_expiry: u32,
persistent_redis: &RedisConnectionPool,
) -> Result<(), AppError> {
let is_key_set = set_base_url_for_short_code(
base_url,
&short_code,
persistent_redis,
redis_expiry
).await?;
let is_key_set =
set_base_url_for_short_code(base_url, short_code.clone(), persistent_redis, redis_expiry)
.await?;

if ! is_key_set {
if !is_key_set {
let UrlShortCode(code) = short_code;
Err(AppError::InvalidRequest(format!("Short code: {code} already exists")))
}
else {
Err(AppError::InvalidRequest(format!(
"Short code: {code} already exists"
)))
} else {
Ok(())
}
}

async fn set_base_url (
async fn set_base_url(
base_url: &Url,
redis_expiry: u32,
app_state: &Data<AppState>,
Expand All @@ -100,19 +109,19 @@ async fn set_base_url (
let short_code = UrlShortCode(Alphanumeric.sample_string(&mut rng, short_code_len));
let is_key_set = set_base_url_for_short_code(
base_url,
&short_code,
short_code.clone(),
&app_state.redis_pool,
redis_expiry,
).await?;
)
.await?;

if is_key_set {
final_short_code = Some(short_code);
break;
}
else {
} else {
retries_rem -= 1;
}
};
}

Ok(final_short_code)
}
2 changes: 1 addition & 1 deletion crates/url_shortner/src/domain/action/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod crud;
pub mod crud;
2 changes: 1 addition & 1 deletion crates/url_shortner/src/domain/action/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod public_api;
pub mod internal;
pub mod public_api;
23 changes: 13 additions & 10 deletions crates/url_shortner/src/domain/action/public_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,31 @@ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; wit
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_web::web::{Data, Redirect};
use crate::{
common::types::UrlShortCode, environment::AppState,
redis::commands::*,
tools::error::AppError
common::types::UrlShortCode, environment::AppState, redis::commands::*, tools::error::AppError,
};
use actix_web::web::{Data, Redirect};

pub async fn redirect_to_url(
app_state: Data<AppState>,
url_short_code: UrlShortCode,
) -> Result<Redirect, AppError> {
println!("redirect request to url with short code: {:?}", url_short_code);
println!(
"redirect request to url with short code: {:?}",
url_short_code
);

let mb_base_url = get_base_url_by_short_code(&url_short_code, &app_state.redis_pool).await?;
let mb_base_url =
get_base_url_by_short_code(url_short_code.clone(), &app_state.redis_pool).await?;

match mb_base_url {
Some(base_url) => {
println!("redirecting to: {}", base_url);
Ok(Redirect::to(base_url.to_string()))
},
None => Err(AppError::
InvalidRequest(format!("No URL found for short code: {}", url_short_code.0))
)
}
None => Err(AppError::InvalidRequest(format!(
"No URL found for short code: {}",
url_short_code.0
))),
}
}
17 changes: 7 additions & 10 deletions crates/url_shortner/src/domain/api/internal/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,26 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{
domain::{action::internal::crud, types::internal::crud::*},
environment::AppState,
tools::{auth::authenticate, error::AppError},
};
use actix_web::{
post,
web::{Data, Json},
HttpRequest,
};
use crate::{
domain::{
action::internal::crud,
types::internal::crud::*
},
environment::AppState, tools::{auth::authenticate, error::AppError}
};

#[post("/internal/generateShortUrl")]
async fn generate_url(
data: Data<AppState>,
req: HttpRequest,
param_obj: Json<GenerateShortUrlRequest>,
) -> Result<Json<GenerateShortUrlResponse>, AppError> {

authenticate(&data.internal_auth_api_key, req)?;

let req_body = param_obj.into_inner();

Ok(Json(crud::generate_url(data, req_body).await?))
}
}
2 changes: 1 addition & 1 deletion crates/url_shortner/src/domain/api/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod crud;
pub mod crud;
9 changes: 3 additions & 6 deletions crates/url_shortner/src/domain/api/public_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ use actix_web::{
};

use crate::{
common::types::*,
domain::action::public_api,
environment::AppState,
tools::error::AppError,
common::types::*, domain::action::public_api, environment::AppState, tools::error::AppError,
};

#[get("/{urlShortCode}")]
Expand All @@ -23,5 +20,5 @@ async fn redirect_to_url(
path: Path<String>,
) -> Result<Redirect, AppError> {
let url_short_code = UrlShortCode(path.into_inner());
Ok(public_api::redirect_to_url(app_state, url_short_code).await?)
}
public_api::redirect_to_url(app_state, url_short_code).await
}
4 changes: 2 additions & 2 deletions crates/url_shortner/src/domain/types/internal/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use serde::{Deserialize, Serialize};
use crate::common::types::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
Expand All @@ -22,4 +22,4 @@ pub struct GenerateShortUrlRequest {
pub struct GenerateShortUrlResponse {
pub short_url: String,
pub url_expiry: TimeStamp,
}
}
2 changes: 1 addition & 1 deletion crates/url_shortner/src/domain/types/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod crud;
pub mod crud;
2 changes: 1 addition & 1 deletion crates/url_shortner/src/domain/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod internal;
pub mod internal;
3 changes: 1 addition & 2 deletions crates/url_shortner/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use crate::tools::logger::LoggerConfig;
use serde::Deserialize;
use shared::redis::types::{RedisConnectionPool, RedisSettings};
use std::sync::Arc;

use crate::tools::logger::LoggerConfig;

#[derive(Debug, Deserialize, Clone)]
pub struct AppConfig {
pub port: u16,
Expand Down
Loading

0 comments on commit 3cb4b49

Please sign in to comment.