Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
filiptronicek committed Apr 4, 2024
1 parent 718e3f6 commit a12ad57
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 29 deletions.
6 changes: 4 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ fn main() {
.output()
.expect("Failed to execute git command");

let git_hash = String::from_utf8_lossy(&git_output.stdout).trim().to_string();
let git_hash = String::from_utf8_lossy(&git_output.stdout)
.trim()
.to_string();

// Write the git hash to a file as a constant.
writeln!(f, "pub const GIT_COMMIT: &str = \"{}\";", git_hash).unwrap();
println!("cargo:rerun-if-changed=.git/HEAD");
println!("cargo:rerun-if-changed=.git/index");
}
}
21 changes: 10 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,9 @@ struct StatsResponse {
}

#[get("/stats")]
fn get_service_stats(_rate_limiter: RateLimiter) -> Result<Custom<Json<StatsResponse>>, Custom<Json<APIResponse>>> {
fn get_service_stats(
_rate_limiter: RateLimiter,
) -> Result<Custom<Json<StatsResponse>>, Custom<Json<APIResponse>>> {
let mut db_connection = match db::initialize() {
Ok(conn) => conn,
Err(err) => {
Expand All @@ -345,7 +347,7 @@ fn get_service_stats(_rate_limiter: RateLimiter) -> Result<Custom<Json<StatsResp
match stats {
Ok(stats) => {
let response = StatsResponse {
total_clips: serde_json::to_value(stats).unwrap()
total_clips: serde_json::to_value(stats).unwrap(),
};
Ok(Custom(Status::Ok, Json(response)))
}
Expand Down Expand Up @@ -428,14 +430,11 @@ async fn rocket() -> _ {
)
.register("/", catchers![too_many_requests, not_found])
.manage(rate_limiter)
.attach(rocket::fairing::AdHoc::on_response(
"Headers",
|_, res| {
Box::pin(async move {
// CORS headers
res.set_header(Header::new("Access-Control-Allow-Origin", "*"));
})
},
))
.attach(rocket::fairing::AdHoc::on_response("Headers", |_, res| {
Box::pin(async move {
// CORS headers
res.set_header(Header::new("Access-Control-Allow-Origin", "*"));
})
}))
.manage(s3_client)
}
42 changes: 26 additions & 16 deletions src/utils/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,16 @@ impl fmt::Display for InsertClipError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InsertClipError::DieselError(e) => write!(f, "Database error: {}", e),
InsertClipError::MaxAttemptsExceeded => write!(f, "Exceeded maximum attempts to generate a unique code."),
InsertClipError::MaxAttemptsExceeded => {
write!(f, "Exceeded maximum attempts to generate a unique code.")
}
}
}
}

/// Inserts a clip into the database
/// Returns the inserted clip
pub fn insert_clip(
connection: &mut PgConnection,
url: String,
) -> Result<Clip, InsertClipError> {
pub fn insert_clip(connection: &mut PgConnection, url: String) -> Result<Clip, InsertClipError> {
let expiry_date = chrono::Local::now().naive_local() + chrono::Duration::days(7);
let mut attempts = 0;
const MAX_ATTEMPTS: usize = 10; // Maximum attempts to generate a unique code
Expand All @@ -95,21 +94,26 @@ pub fn insert_clip(

match diesel::insert_into(clips::table)
.values(&new_clip)
.get_result::<Clip>(connection).map_err(InsertClipError::from) {
Ok(clip) => return Ok(clip),
Err(InsertClipError::DieselError(Error::DatabaseError(DatabaseErrorKind::UniqueViolation, _))) => {
attempts += 1;
continue;
},
Err(e) => return Err(e), // For any other diesel error, return immediately
.get_result::<Clip>(connection)
.map_err(InsertClipError::from)
{
Ok(clip) => return Ok(clip),
Err(InsertClipError::DieselError(Error::DatabaseError(
DatabaseErrorKind::UniqueViolation,
_,
))) => {
attempts += 1;
continue;
}
Err(e) => return Err(e), // For any other diesel error, return immediately
}
}

Err(InsertClipError::MaxAttemptsExceeded)
}

/// Returns the highest ID in the clips table
pub fn get_total_clip_count (connection: &mut PgConnection) -> Result<i32, diesel::result::Error> {
pub fn get_total_clip_count(connection: &mut PgConnection) -> Result<i32, diesel::result::Error> {
use crate::schema::clips::dsl::*;

clips
Expand All @@ -119,10 +123,16 @@ pub fn get_total_clip_count (connection: &mut PgConnection) -> Result<i32, diese
.ok_or(diesel::result::Error::NotFound)
}


/// Deletes expired clips from the database
pub fn collect_garbage(connection: &mut PgConnection) -> Result<usize, diesel::result::Error> {
use crate::schema::clips::dsl::*;

diesel::delete(clips.filter(expires_at.is_not_null().and(expires_at.lt(chrono::Local::now().naive_local())))).execute(connection)
}
diesel::delete(
clips.filter(
expires_at
.is_not_null()
.and(expires_at.lt(chrono::Local::now().naive_local())),
),
)
.execute(connection)
}

0 comments on commit a12ad57

Please sign in to comment.