Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ jobs:
- name: Check Formatting
run: cargo fmt --all -- --check

- name: Run Clippy
run: cargo clippy --all-targets --all-features -- -D warnings

# Run tests (Non-chain only, as requested)
- name: Run Tests
run: cargo test -- --skip chain_ --test-threads=1 --nocapture
2 changes: 1 addition & 1 deletion src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ fn map_db_error(err: DbError) -> (StatusCode, String) {
if msg.contains("duplicate key value violates unique constraint") {
(
StatusCode::CONFLICT,
format!("The given value is conflicting with existing record"),
"The given value is conflicting with existing record".to_string(),
)
} else {
(
Expand Down
24 changes: 12 additions & 12 deletions src/handlers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,28 +85,28 @@ pub async fn verify_login(
warn!(error = %e, "verify_login: verify_address error");
}
let addr_ok = addr_res.map_err(|_| {
AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(format!(
"address verification failed"
))))
AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(
"address verification failed".to_string(),
)))
})?;
if !addr_ok {
return Err(AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(
format!("address verification failed"),
"address verification failed".to_string(),
))));
}
let sig_res = SignatureService::verify_message(message.as_bytes(), &body.signature, &body.public_key);
if let Err(e) = &sig_res {
warn!(error = %e, "verify_login: verify_message error");
}
let sig_ok = sig_res.map_err(|_| {
AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(format!(
"message verification failed"
))))
AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(
"message verification failed".to_string(),
)))
})?;
debug!(addr_ok = addr_ok, sig_ok = sig_ok, "verify_login: verification results");
if !sig_ok {
return Err(AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(
format!("message verification failed"),
"message verification failed".to_string(),
))));
}

Expand Down Expand Up @@ -168,7 +168,7 @@ pub async fn handle_x_oauth(
tracing::info!("Quan address from token: {}", quan_address);

let (auth_url, verifier) = state.twitter_gateway.generate_auth_url();
let session_id = format!("{}|{}", quan_address, uuid::Uuid::new_v4().to_string());
let session_id = format!("{}|{}", quan_address, uuid::Uuid::new_v4());

tracing::info!("Session id in cookies: {}", session_id);

Expand Down Expand Up @@ -254,9 +254,9 @@ pub async fn handle_x_oauth_callback(
tracing::debug!("Do X association...");
let quan_address = {
let Some(address) = session_id.split_once('|').map(|(left, _)| left) else {
return Err(AppError::Handler(HandlerError::Auth(AuthHandlerError::OAuth(format!(
"Session id malformed",
)))));
return Err(AppError::Handler(HandlerError::Auth(AuthHandlerError::OAuth(
"Session id malformed".to_string(),
))));
};

address.to_string()
Expand Down
4 changes: 1 addition & 3 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,5 @@ pub fn validate_pagination_query(page: u32, page_size: u32) -> Result<(), AppErr
}

fn calculate_total_pages(page_size: u32, total_items: u32) -> u32 {
let total_pages = ((total_items as f64) / (page_size as f64)).ceil() as u32;

total_pages
((total_items as f64) / (page_size as f64)).ceil() as u32
}
40 changes: 20 additions & 20 deletions src/handlers/raid_quest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub async fn handle_get_raid_leaderboard(
meta: PaginationMetadata {
page: params.page,
page_size: params.page_size,
total_items: total_items as u32,
total_items,
total_pages,
},
};
Expand All @@ -151,9 +151,9 @@ pub async fn handle_get_specific_raider_raid_leaderboard(
Path((raider_id, raid_id)): Path<(String, i32)>,
) -> Result<Json<SuccessResponse<RaidLeaderboard>>, AppError> {
let Some(raider_leaderboard) = state.db.raid_leaderboards.get_raider_entry(raid_id, &raider_id).await? else {
return Err(AppError::Database(DbError::RecordNotFound(format!(
"No raider leaderboard is found"
))));
return Err(AppError::Database(DbError::RecordNotFound(
"No raider leaderboard is found".to_string(),
)));
};

Ok(SuccessResponse::new(raider_leaderboard))
Expand Down Expand Up @@ -189,13 +189,13 @@ pub async fn handle_create_raid_submission(
let (current_active_raid, user_x) = get_active_raid_and_x_association(&state, &user).await?;

let Some((reply_username, reply_id)) = parse_x_status_url(&payload.tweet_reply_link) else {
return Err(AppError::Handler(HandlerError::InvalidBody(format!(
"Couldn't parse tweet reply link"
))));
return Err(AppError::Handler(HandlerError::InvalidBody(
"Couldn't parse tweet reply link".to_string(),
)));
};
if user_x.username != reply_username {
return Err(AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(
format!("Only tweet reply author is eligible to submit"),
"Only tweet reply author is eligible to submit".to_string(),
))));
}

Expand Down Expand Up @@ -224,7 +224,7 @@ pub async fn handle_delete_raid_submission(

if raid_submission.raider_id != user.quan_address.0 {
return Err(AppError::Handler(HandlerError::Auth(AuthHandlerError::Unauthorized(
format!("Only raid submission owner can delete"),
"Only raid submission owner can delete".to_string(),
))));
}

Expand All @@ -238,14 +238,14 @@ async fn get_active_raid_and_x_association(
user: &Address,
) -> Result<(RaidQuest, XAssociation), AppError> {
let Some(current_active_raid) = state.db.raid_quests.find_active().await? else {
return Err(AppError::Database(DbError::RecordNotFound(format!(
"No active raid is found"
))));
return Err(AppError::Database(DbError::RecordNotFound(
"No active raid is found".to_string(),
)));
};
let Some(user_x) = state.db.x_associations.find_by_address(&user.quan_address).await? else {
return Err(AppError::Database(DbError::RecordNotFound(format!(
"User doesn't have X association"
))));
return Err(AppError::Database(DbError::RecordNotFound(
"User doesn't have X association".to_string(),
)));
};
Ok((current_active_raid, user_x))
}
Expand Down Expand Up @@ -369,7 +369,7 @@ mod tests {
.oneshot(
Request::builder()
.method("PUT")
.uri(&format!("/raids/{}/finish", raid_id))
.uri(format!("/raids/{}/finish", raid_id))
.body(Body::empty())
.unwrap(),
)
Expand Down Expand Up @@ -405,7 +405,7 @@ mod tests {
.oneshot(
Request::builder()
.method("PUT")
.uri(&format!("/raids/{}/activate", raid_id))
.uri(format!("/raids/{}/activate", raid_id))
.body(Body::empty())
.unwrap(),
)
Expand Down Expand Up @@ -514,7 +514,7 @@ mod tests {
.oneshot(
Request::builder()
.method("GET")
.uri(&format!("/raiders/{}/leaderboard/{}", user.quan_address.0, raid_id,))
.uri(format!("/raiders/{}/leaderboard/{}", user.quan_address.0, raid_id,))
.body(Body::empty())
.unwrap(),
)
Expand Down Expand Up @@ -707,7 +707,7 @@ mod tests {
.oneshot(
Request::builder()
.method("DELETE")
.uri(&format!("/submissions/{}", submission_id))
.uri(format!("/submissions/{}", submission_id))
.body(Body::empty())
.unwrap(),
)
Expand Down Expand Up @@ -756,7 +756,7 @@ mod tests {
.oneshot(
Request::builder()
.method("DELETE")
.uri(&format!("/submissions/{}", submission_id))
.uri(format!("/submissions/{}", submission_id))
.body(Body::empty())
.unwrap(),
)
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/referral.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ pub async fn handle_add_referral(

Ok(SuccessResponse::new(referrer.referral_code))
} else {
return Err(AppError::Handler(HandlerError::Referral(
Err(AppError::Handler(HandlerError::Referral(
ReferralHandlerError::ReferralNotFound(format!("Referrer not found for code '{}'", submitted_code)),
)));
)))
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/handlers/tweet_author.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ mod tests {

let author = state.db.tweet_authors.find_by_id("hello").await.unwrap().unwrap();

assert_eq!(author.is_ignored, true);
assert!(author.is_ignored);
}

#[tokio::test]
Expand Down
6 changes: 6 additions & 0 deletions src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ pub struct Metrics {
pub registry: Arc<Registry>,
}

impl Default for Metrics {
fn default() -> Self {
Self::new()
}
}

impl Metrics {
pub fn new() -> Self {
let registry = Registry::new();
Expand Down
6 changes: 2 additions & 4 deletions src/models/raid_submission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,13 @@ impl From<&TwitterTweet> for UpdateRaidSubmissionStats {
let default_metrics = TweetPublicMetrics::default();
let public_metrics = tweet.public_metrics.as_ref().unwrap_or(&default_metrics);

let update_payload = UpdateRaidSubmissionStats {
UpdateRaidSubmissionStats {
id: tweet.id.clone(),
impression_count: public_metrics.impression_count as i32,
like_count: public_metrics.like_count as i32,
retweet_count: public_metrics.retweet_count as i32,
reply_count: public_metrics.reply_count as i32,
};

update_payload
}
}
}

Expand Down
6 changes: 2 additions & 4 deletions src/models/relevant_tweet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl NewTweetPayload {
.unwrap();
let created_at = tweet.created_at.ok_or_else(|| chrono::Utc::now().to_rfc3339()).unwrap();

let new_tweet = NewTweetPayload {
NewTweetPayload {
id: tweet.id,
author_id: tweet.author_id.unwrap(),
text: tweet.text,
Expand All @@ -106,8 +106,6 @@ impl NewTweetPayload {
retweet_count: public_metrics.retweet_count as i32,
reply_count: public_metrics.reply_count as i32,
created_at: DateTime::parse_from_rfc3339(&created_at).unwrap().with_timezone(&Utc),
};

new_tweet
}
}
}
6 changes: 2 additions & 4 deletions src/models/tweet_author.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl NewAuthorPayload {
pub fn new(author: TwitterUser) -> Self {
let public_metrics = author.public_metrics.unwrap_or_default();

let new_author = NewAuthorPayload {
NewAuthorPayload {
id: author.id,
name: author.name,
username: author.username,
Expand All @@ -97,9 +97,7 @@ impl NewAuthorPayload {
media_count: public_metrics.media_count.unwrap_or(0) as i32,
like_count: public_metrics.like_count.unwrap_or(0) as i32,
is_ignored: Some(true),
};

new_author
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/repositories/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl AddressRepository {
.build_query_scalar()
.fetch_one(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(count)
}
Expand Down Expand Up @@ -291,7 +291,7 @@ impl AddressRepository {
.build_query_as::<AddressWithOptInAndAssociations>()
.fetch_all(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(addresses)
}
Expand Down
4 changes: 2 additions & 2 deletions src/repositories/raid_quest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl RaidQuestRepository {
.build_query_as::<RaidQuest>()
.fetch_all(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(tweets)
}
Expand Down Expand Up @@ -218,7 +218,7 @@ impl RaidQuestRepository {
.build_query_scalar()
.fetch_one(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(count)
}
Expand Down
2 changes: 1 addition & 1 deletion src/repositories/raid_submission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ mod tests {
// 3. Verify Update in DB
let updated = repo.find_by_id(&input.id).await.unwrap().unwrap();

assert_eq!(updated.is_invalid, true);
assert!(updated.is_invalid);

// 4. Verify `updated_at` trigger worked
assert!(
Expand Down
4 changes: 2 additions & 2 deletions src/repositories/relevant_tweet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl RelevantTweetRepository {
.build_query_scalar()
.fetch_one(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(count)
}
Expand Down Expand Up @@ -141,7 +141,7 @@ impl RelevantTweetRepository {
.build_query_as::<TweetWithAuthor>()
.fetch_all(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(tweets)
}
Expand Down
6 changes: 3 additions & 3 deletions src/repositories/tweet_author.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl TweetAuthorRepository {
.build_query_scalar()
.fetch_one(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(count)
}
Expand Down Expand Up @@ -102,7 +102,7 @@ impl TweetAuthorRepository {
.build_query_as::<TweetAuthor>()
.fetch_all(&self.pool)
.await
.map_err(|e| DbError::Database(e))?;
.map_err(DbError::Database)?;

Ok(authors)
}
Expand Down Expand Up @@ -150,7 +150,7 @@ impl TweetAuthorRepository {
.bind(&payload.id)
.bind(&payload.name)
.bind(&payload.username)
.bind(&payload.is_ignored)
.bind(payload.is_ignored)
.bind(payload.followers_count)
.bind(payload.following_count)
.bind(payload.tweet_count)
Expand Down
Loading