diff --git a/Cargo.lock b/Cargo.lock index 4cdcc47f6..8aedb8103 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -833,6 +833,29 @@ dependencies = [ "syn 1.0.74", ] +[[package]] +name = "deadpool" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef82259c587bceda08349f28ff00f69ae4c897898f254140af6021eb218e8232" +dependencies = [ + "async-trait", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-diesel" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc59b1d25a4c207b321398ab9c3e3651a6e726731ca8b0a4f07e1d4b22f44a40" +dependencies = [ + "async-trait", + "deadpool", + "diesel", + "tokio", +] + [[package]] name = "deflate" version = "0.8.6" @@ -901,7 +924,6 @@ dependencies = [ "chrono", "diesel_derives", "pq-sys", - "r2d2", "serde_json", ] @@ -1403,9 +1425,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.4.1" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a87b616e37e93c22fb19bcd386f02f3af5ea98a25670ad0fce773de23c5e68" +checksum = "acd94fdbe1d4ff688b67b04eee2e17bd50995534a61539e45adfefb45e5e5503" [[package]] name = "httpdate" @@ -1543,9 +1565,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.52" +version = "0.3.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce791b7ca6638aae45be056e068fc756d871eb3b3b10b8efa62d1c9cec616752" +checksum = "e4bf49d50e2961077d9c99f4b7997d770a1114f087c3c2e0069b36c13fc2979d" dependencies = [ "wasm-bindgen", ] @@ -1761,6 +1783,7 @@ version = "0.11.3" dependencies = [ "bcrypt", "chrono", + "deadpool-diesel", "diesel", "diesel_migrations", "lazy_static", @@ -1862,6 +1885,7 @@ dependencies = [ "cargo-husky", "chrono", "clokwerk", + "deadpool-diesel", "diesel", "diesel_migrations", "env_logger", @@ -3798,9 +3822,9 @@ checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" [[package]] name = "wasm-bindgen" -version = "0.2.75" +version = "0.2.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b608ecc8f4198fe8680e2ed18eccab5f0cd4caaf3d83516fa5fb2e927fda2586" +checksum = "8ce9b1b516211d33767048e5d47fa2a381ed8b76fc48d2ce4aa39877f9f183e0" dependencies = [ "cfg-if", "serde", @@ -3810,9 +3834,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.75" +version = "0.2.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580aa3a91a63d23aac5b6b267e2d13cb4f363e31dce6c352fca4752ae12e479f" +checksum = "cfe8dc78e2326ba5f845f4b5bf548401604fa20b1dd1d365fb73b6c1d6364041" dependencies = [ "bumpalo", "lazy_static", @@ -3825,9 +3849,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.25" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16646b21c3add8e13fdb8f20172f8a28c3dbf62f45406bcff0233188226cfe0c" +checksum = "95fded345a6559c2cfee778d562300c581f7d4ff3edb9b0d230d69800d213972" dependencies = [ "cfg-if", "js-sys", @@ -3837,9 +3861,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.75" +version = "0.2.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "171ebf0ed9e1458810dfcb31f2e766ad6b3a89dbda42d8901f2b268277e5f09c" +checksum = "44468aa53335841d9d6b6c023eaab07c0cd4bddbcfdee3e2bb1e8d2cb8069fef" dependencies = [ "quote 1.0.9", "wasm-bindgen-macro-support", @@ -3847,9 +3871,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.75" +version = "0.2.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c2657dd393f03aa2a659c25c6ae18a13a4048cebd220e147933ea837efc589f" +checksum = "0195807922713af1e67dc66132c7328206ed9766af3858164fb583eedc25fbad" dependencies = [ "proc-macro2 1.0.28", "quote 1.0.9", @@ -3860,15 +3884,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.75" +version = "0.2.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e0c4a743a309662d45f4ede961d7afa4ba4131a59a639f29b0069c3798bbcc2" +checksum = "acdb075a845574a1fa5f09fd77e43f7747599301ea3417a9fbffdeedfc1f4a29" [[package]] name = "web-sys" -version = "0.3.52" +version = "0.3.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c70a82d842c9979078c772d4a1344685045f1a5628f677c2b2eab4dd7d2696" +checksum = "224b2f6b67919060055ef1a67807367c2066ed520c3862cc013d26cf893a783c" dependencies = [ "js-sys", "wasm-bindgen", diff --git a/Cargo.toml b/Cargo.toml index be1fd4128..0db917ef7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,6 +63,7 @@ activitystreams = "0.7.0-alpha.11" actix-rt = { version = "2.2.0", default-features = false } serde_json = { version = "1.0.66", features = ["preserve_order"] } clokwerk = "0.3.5" +deadpool-diesel = { version = "0.1.2", features = ["postgres"] } [dev-dependencies.cargo-husky] version = "1.5.0" diff --git a/crates/api/src/comment.rs b/crates/api/src/comment.rs index 00e136adb..1b28988b8 100644 --- a/crates/api/src/comment.rs +++ b/crates/api/src/comment.rs @@ -1,7 +1,6 @@ use crate::Perform; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, check_downvotes_enabled, check_person_block, @@ -35,10 +34,7 @@ impl Perform for MarkCommentAsRead { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let comment_id = data.comment_id; - let orig_comment = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, None) - }) - .await??; + let orig_comment = CommentView::read(&&context.pool.get().await?, comment_id, None)?; check_community_ban( local_user_view.person.id, @@ -54,19 +50,13 @@ impl Perform for MarkCommentAsRead { // Do the mark as read let read = data.read; - blocking(context.pool(), move |conn| { - Comment::update_read(conn, comment_id, read) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_comment"))?; + Comment::update_read(&&context.pool.get().await?, comment_id, read) + .map_err(|_| ApiError::err("couldnt_update_comment"))?; // Refetch it let comment_id = data.comment_id; let person_id = local_user_view.person.id; - let comment_view = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, Some(person_id)) - }) - .await??; + let comment_view = CommentView::read(&&context.pool.get().await?, comment_id, Some(person_id))?; let res = CommentResponse { comment_view, @@ -96,23 +86,20 @@ impl Perform for SaveComment { }; if data.save { - let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form); - if blocking(context.pool(), save_comment).await?.is_err() { + let save_comment = CommentSaved::save(&&context.pool.get().await?, &comment_saved_form); + if save_comment.is_err() { return Err(ApiError::err("couldnt_save_comment").into()); } } else { - let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form); - if blocking(context.pool(), unsave_comment).await?.is_err() { + let unsave_comment = CommentSaved::unsave(&&context.pool.get().await?, &comment_saved_form); + if unsave_comment.is_err() { return Err(ApiError::err("couldnt_save_comment").into()); } } let comment_id = data.comment_id; let person_id = local_user_view.person.id; - let comment_view = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, Some(person_id)) - }) - .await??; + let comment_view = CommentView::read(&&context.pool.get().await?, comment_id, Some(person_id))?; Ok(CommentResponse { comment_view, @@ -140,10 +127,7 @@ impl Perform for CreateCommentLike { check_downvotes_enabled(data.score, context.pool()).await?; let comment_id = data.comment_id; - let orig_comment = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, None) - }) - .await??; + let orig_comment = CommentView::read(&&context.pool.get().await?, comment_id, None)?; check_community_ban( local_user_view.person.id, @@ -161,10 +145,8 @@ impl Perform for CreateCommentLike { // Add parent user to recipients let recipient_id = orig_comment.get_recipient_id(); - if let Ok(local_recipient) = blocking(context.pool(), move |conn| { - LocalUserView::read_person(conn, recipient_id) - }) - .await? + if let Ok(local_recipient) = + LocalUserView::read_person(&&context.pool.get().await?, recipient_id) { recipient_ids.push(local_recipient.local_user.id); } @@ -178,10 +160,7 @@ impl Perform for CreateCommentLike { // Remove any likes first let person_id = local_user_view.person.id; - blocking(context.pool(), move |conn| { - CommentLike::remove(conn, person_id, comment_id) - }) - .await??; + CommentLike::remove(&&context.pool.get().await?, person_id, comment_id)?; // Only add the like if the score isnt 0 let comment = orig_comment.comment; @@ -189,8 +168,8 @@ impl Perform for CreateCommentLike { let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); if do_add { let like_form2 = like_form.clone(); - let like = move |conn: &'_ _| CommentLike::like(conn, &like_form2); - if blocking(context.pool(), like).await?.is_err() { + let like = CommentLike::like(&&context.pool.get().await?, &like_form2); + if like.is_err() { return Err(ApiError::err("couldnt_like_comment").into()); } diff --git a/crates/api/src/comment_report.rs b/crates/api/src/comment_report.rs index 83aebfc52..178c48568 100644 --- a/crates/api/src/comment_report.rs +++ b/crates/api/src/comment_report.rs @@ -1,7 +1,6 @@ use crate::Perform; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, collect_moderated_communities, comment::*, @@ -45,10 +44,7 @@ impl Perform for CreateCommentReport { let person_id = local_user_view.person.id; let comment_id = data.comment_id; - let comment_view = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, None) - }) - .await??; + let comment_view = CommentView::read(&&context.pool.get().await?, comment_id, None)?; check_community_ban(person_id, comment_view.community.id, context.pool()).await?; @@ -59,11 +55,8 @@ impl Perform for CreateCommentReport { reason: data.reason.to_owned(), }; - let report = blocking(context.pool(), move |conn| { - CommentReport::report(conn, &report_form) - }) - .await? - .map_err(|_| ApiError::err("couldnt_create_report"))?; + let report = CommentReport::report(&&context.pool.get().await?, &report_form) + .map_err(|_| ApiError::err("couldnt_create_report"))?; let res = CreateCommentReportResponse { success: true }; @@ -99,24 +92,19 @@ impl Perform for ResolveCommentReport { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let report_id = data.report_id; - let report = blocking(context.pool(), move |conn| { - CommentReportView::read(conn, report_id) - }) - .await??; + let report = CommentReportView::read(&&context.pool.get().await?, report_id)?; let person_id = local_user_view.person.id; is_mod_or_admin(context.pool(), person_id, report.community.id).await?; let resolved = data.resolved; - let resolve_fun = move |conn: &'_ _| { - if resolved { - CommentReport::resolve(conn, report_id, person_id) - } else { - CommentReport::unresolve(conn, report_id, person_id) - } + let resolve_fun = if resolved { + CommentReport::resolve(&&context.pool.get().await?, report_id, person_id) + } else { + CommentReport::unresolve(&&context.pool.get().await?, report_id, person_id) }; - if blocking(context.pool(), resolve_fun).await?.is_err() { + if resolve_fun.is_err() { return Err(ApiError::err("couldnt_resolve_report").into()); }; @@ -158,14 +146,11 @@ impl Perform for ListCommentReports { let page = data.page; let limit = data.limit; - let comments = blocking(context.pool(), move |conn| { - CommentReportQueryBuilder::create(conn) - .community_ids(community_ids) - .page(page) - .limit(limit) - .list() - }) - .await??; + let comments = CommentReportQueryBuilder::create(&&context.pool.get().await?) + .community_ids(community_ids) + .page(page) + .limit(limit) + .list()?; let res = ListCommentReportsResponse { comments }; diff --git a/crates/api/src/community.rs b/crates/api/src/community.rs index d68d27c2f..773bae23c 100644 --- a/crates/api/src/community.rs +++ b/crates/api/src/community.rs @@ -2,7 +2,6 @@ use crate::Perform; use actix_web::web::Data; use anyhow::Context; use lemmy_api_common::{ - blocking, check_community_ban, community::*, get_local_user_view_from_jwt, @@ -56,10 +55,7 @@ impl Perform for FollowCommunity { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let community_id = data.community_id; - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; let community_follower_form = CommunityFollowerForm { community_id: data.community_id, person_id: local_user_view.person.id, @@ -70,14 +66,15 @@ impl Perform for FollowCommunity { if data.follow { check_community_ban(local_user_view.person.id, community_id, context.pool()).await?; - let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); - if blocking(context.pool(), follow).await?.is_err() { + let follow = + CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form); + if follow.is_err() { return Err(ApiError::err("community_follower_already_exists").into()); } } else { let unfollow = - move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); - if blocking(context.pool(), unfollow).await?.is_err() { + CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form); + if unfollow.is_err() { return Err(ApiError::err("community_follower_already_exists").into()); } } @@ -87,18 +84,17 @@ impl Perform for FollowCommunity { FollowCommunityApub::send(&local_user_view.person, &community, context).await?; } else { UndoFollowCommunity::send(&local_user_view.person, &community, context).await?; - let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); - if blocking(context.pool(), unfollow).await?.is_err() { + let unfollow = + CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form); + if unfollow.is_err() { return Err(ApiError::err("community_follower_already_exists").into()); } } let community_id = data.community_id; let person_id = local_user_view.person.id; - let mut community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, community_id, Some(person_id)) - }) - .await??; + let mut community_view = + CommunityView::read(&&context.pool.get().await?, community_id, Some(person_id))?; // TODO: this needs to return a "pending" state, until Accept is received from the remote server // For now, just assume that remote follows are accepted. @@ -131,8 +127,8 @@ impl Perform for BlockCommunity { }; if data.block { - let block = move |conn: &'_ _| CommunityBlock::block(conn, &community_block_form); - if blocking(context.pool(), block).await?.is_err() { + let block = CommunityBlock::block(&&context.pool.get().await?, &community_block_form); + if block.is_err() { return Err(ApiError::err("community_block_already_exists").into()); } @@ -142,27 +138,18 @@ impl Perform for BlockCommunity { person_id, pending: false, }; - blocking(context.pool(), move |conn: &'_ _| { - CommunityFollower::unfollow(conn, &community_follower_form) - }) - .await? - .ok(); - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok(); + let community = Community::read(&&context.pool.get().await?, community_id)?; UndoFollowCommunity::send(&local_user_view.person, &community, context).await?; } else { - let unblock = move |conn: &'_ _| CommunityBlock::unblock(conn, &community_block_form); - if blocking(context.pool(), unblock).await?.is_err() { + let unblock = CommunityBlock::unblock(&&context.pool.get().await?, &community_block_form); + if unblock.is_err() { return Err(ApiError::err("community_block_already_exists").into()); } } - let community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, community_id, Some(person_id)) - }) - .await??; + let community_view = + CommunityView::read(&&context.pool.get().await?, community_id, Some(person_id))?; Ok(BlockCommunityResponse { blocked: data.block, @@ -194,18 +181,12 @@ impl Perform for BanFromCommunity { person_id: data.person_id, }; - let community = blocking(context.pool(), move |conn: &'_ _| { - Community::read(conn, community_id) - }) - .await??; - let banned_person = blocking(context.pool(), move |conn: &'_ _| { - Person::read(conn, banned_person_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; + let banned_person = Person::read(&&context.pool.get().await?, banned_person_id)?; if data.ban { - let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form); - if blocking(context.pool(), ban).await?.is_err() { + let ban = CommunityPersonBan::ban(&&context.pool.get().await?, &community_user_ban_form); + if ban.is_err() { return Err(ApiError::err("community_user_already_banned").into()); } @@ -215,17 +196,13 @@ impl Perform for BanFromCommunity { person_id: banned_person_id, pending: false, }; - blocking(context.pool(), move |conn: &'_ _| { - CommunityFollower::unfollow(conn, &community_follower_form) - }) - .await? - .ok(); + CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok(); BlockUserFromCommunity::send(&community, &banned_person, &local_user_view.person, context) .await?; } else { - let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form); - if blocking(context.pool(), unban).await?.is_err() { + let unban = CommunityPersonBan::unban(&&context.pool.get().await?, &community_user_ban_form); + if unban.is_err() { return Err(ApiError::err("community_user_already_banned").into()); } UndoBlockUserFromCommunity::send( @@ -240,28 +217,24 @@ impl Perform for BanFromCommunity { // Remove/Restore their data if that's desired if data.remove_data.unwrap_or(false) { // Posts - blocking(context.pool(), move |conn: &'_ _| { - Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true) - }) - .await??; + Post::update_removed_for_creator( + &&context.pool.get().await?, + banned_person_id, + Some(community_id), + true, + )?; // Comments // TODO Diesel doesn't allow updates with joins, so this has to be a loop - let comments = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .creator_id(banned_person_id) - .community_id(community_id) - .limit(std::i64::MAX) - .list() - }) - .await??; + let comments = CommentQueryBuilder::create(&&context.pool.get().await?) + .creator_id(banned_person_id) + .community_id(community_id) + .limit(std::i64::MAX) + .list()?; for comment_view in &comments { let comment_id = comment_view.comment.id; - blocking(context.pool(), move |conn: &'_ _| { - Comment::update_removed(conn, comment_id, true) - }) - .await??; + Comment::update_removed(&&context.pool.get().await?, comment_id, true)?; } } @@ -277,16 +250,10 @@ impl Perform for BanFromCommunity { banned: Some(data.ban), expires, }; - blocking(context.pool(), move |conn| { - ModBanFromCommunity::create(conn, &form) - }) - .await??; + ModBanFromCommunity::create(&&context.pool.get().await?, &form)?; let person_id = data.person_id; - let person_view = blocking(context.pool(), move |conn| { - PersonViewSafe::read(conn, person_id) - }) - .await??; + let person_view = PersonViewSafe::read(&&context.pool.get().await?, person_id)?; let res = BanFromCommunityResponse { person_view, @@ -327,13 +294,13 @@ impl Perform for AddModToCommunity { person_id: data.person_id, }; if data.added { - let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); - if blocking(context.pool(), join).await?.is_err() { + let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form); + if join.is_err() { return Err(ApiError::err("community_moderator_already_exists").into()); } } else { - let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form); - if blocking(context.pool(), leave).await?.is_err() { + let leave = CommunityModerator::leave(&&context.pool.get().await?, &community_moderator_form); + if leave.is_err() { return Err(ApiError::err("community_moderator_already_exists").into()); } } @@ -345,21 +312,12 @@ impl Perform for AddModToCommunity { community_id: data.community_id, removed: Some(!data.added), }; - blocking(context.pool(), move |conn| { - ModAddCommunity::create(conn, &form) - }) - .await??; + ModAddCommunity::create(&&context.pool.get().await?, &form)?; // Send to federated instances let updated_mod_id = data.person_id; - let updated_mod = blocking(context.pool(), move |conn| { - Person::read(conn, updated_mod_id) - }) - .await??; - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let updated_mod = Person::read(&&context.pool.get().await?, updated_mod_id)?; + let community = Community::read(&&context.pool.get().await?, community_id)?; if data.added { AddMod::send(&community, &updated_mod, &local_user_view.person, context).await?; } else { @@ -369,10 +327,8 @@ impl Perform for AddModToCommunity { // Note: in case a remote mod is added, this returns the old moderators list, it will only get // updated once we receive an activity from the community (like `Announce/Add/Moderator`) let community_id = data.community_id; - let moderators = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await??; + let moderators = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?; let res = AddModToCommunityResponse { moderators }; context.chat_server().do_send(SendCommunityRoomMessage { @@ -399,12 +355,9 @@ impl Perform for TransferCommunity { let data: &TransferCommunity = self; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let site_creator_id = blocking(context.pool(), move |conn| { - Site::read(conn, 1).map(|s| s.creator_id) - }) - .await??; + let site_creator_id = Site::read(&&context.pool.get().await?, 1).map(|s| s.creator_id)?; - let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; + let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?; // Making sure the site creator, if an admin, is at the top let creator_index = admins @@ -416,10 +369,8 @@ impl Perform for TransferCommunity { // Fetch the community mods let community_id = data.community_id; - let mut community_mods = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await??; + let mut community_mods = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?; // Make sure transferrer is either the top community mod, or an admin if local_user_view.person.id != community_mods[0].moderator.id @@ -442,10 +393,7 @@ impl Perform for TransferCommunity { // Delete all the mods let community_id = data.community_id; - blocking(context.pool(), move |conn| { - CommunityModerator::delete_for_community(conn, community_id) - }) - .await??; + CommunityModerator::delete_for_community(&&context.pool.get().await?, community_id)?; // TODO: this should probably be a bulk operation // Re-add the mods, in the new order @@ -455,8 +403,8 @@ impl Perform for TransferCommunity { person_id: cmod.moderator.id, }; - let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); - if blocking(context.pool(), join).await?.is_err() { + let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form); + if join.is_err() { return Err(ApiError::err("community_moderator_already_exists").into()); } } @@ -468,25 +416,18 @@ impl Perform for TransferCommunity { community_id: data.community_id, removed: Some(false), }; - blocking(context.pool(), move |conn| { - ModTransferCommunity::create(conn, &form) - }) - .await??; + ModTransferCommunity::create(&&context.pool.get().await?, &form)?; let community_id = data.community_id; let person_id = local_user_view.person.id; - let community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, community_id, Some(person_id)) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_community"))?; + let community_view = + CommunityView::read(&&context.pool.get().await?, community_id, Some(person_id)) + .map_err(|_| ApiError::err("couldnt_find_community"))?; let community_id = data.community_id; - let moderators = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_community"))?; + let moderators = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id) + .map_err(|_| ApiError::err("couldnt_find_community"))?; // Return the jwt Ok(GetCommunityResponse { diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index bf3a813b3..7dad46fe9 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -1,3 +1,8 @@ +// Clippy needless_borrow linting is broken currently. Example: +// PersonViewSafe::read(&&context.pool.get().await?, person_details_id)?; +// change this to: `&&context.pool.get().await?` +#![allow(clippy::needless_borrow)] + use actix_web::{web, web::Data}; use captcha::Captcha; use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*, websocket::*}; diff --git a/crates/api/src/local_user.rs b/crates/api/src/local_user.rs index 510ef5adb..ffae88ba1 100644 --- a/crates/api/src/local_user.rs +++ b/crates/api/src/local_user.rs @@ -5,7 +5,6 @@ use bcrypt::verify; use captcha::{gen, Difficulty}; use chrono::Duration; use lemmy_api_common::{ - blocking, collect_moderated_communities, get_local_user_view_from_jwt, is_admin, @@ -86,11 +85,9 @@ impl Perform for Login { // Fetch that username / email let username_or_email = data.username_or_email.clone(); - let local_user_view = blocking(context.pool(), move |conn| { - LocalUserView::find_by_email_or_name(conn, &username_or_email) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?; + let local_user_view = + LocalUserView::find_by_email_or_name(&&context.pool.get().await?, &username_or_email) + .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?; // Verify the password let valid: bool = verify( @@ -220,16 +217,8 @@ impl Perform for SaveUserSettings { bot_account, }; - let person_res = blocking(context.pool(), move |conn| { - Person::update(conn, person_id, &person_form) - }) - .await?; - let _updated_person: Person = match person_res { - Ok(p) => p, - Err(_) => { - return Err(ApiError::err("user_already_exists").into()); - } - }; + Person::update(&&context.pool.get().await?, person_id, &person_form) + .map_err(|_| ApiError::err("user_already_exists"))?; let local_user_form = LocalUserForm { person_id, @@ -248,24 +237,20 @@ impl Perform for SaveUserSettings { send_notifications_to_email: data.send_notifications_to_email, }; - let local_user_res = blocking(context.pool(), move |conn| { - LocalUser::update(conn, local_user_id, &local_user_form) - }) - .await?; - let updated_local_user = match local_user_res { - Ok(u) => u, - Err(e) => { - let err_type = if e.to_string() - == "duplicate key value violates unique constraint \"local_user_email_key\"" - { - "email_already_exists" - } else { - "user_already_exists" - }; + let updated_local_user = + LocalUser::update(&&context.pool.get().await?, local_user_id, &local_user_form).map_err( + |e| { + let err_type = if e.to_string() + == "duplicate key value violates unique constraint \"local_user_email_key\"" + { + "email_already_exists" + } else { + "user_already_exists" + }; - return Err(ApiError::err(err_type).into()); - } - }; + ApiError::err(err_type) + }, + )?; // Return the jwt Ok(LoginResponse { @@ -305,10 +290,8 @@ impl Perform for ChangePassword { let local_user_id = local_user_view.local_user.id; let new_password = data.new_password.to_owned(); - let updated_local_user = blocking(context.pool(), move |conn| { - LocalUser::update_password(conn, local_user_id, &new_password) - }) - .await??; + let updated_local_user = + LocalUser::update_password(&&context.pool.get().await?, local_user_id, &new_password)?; // Return the jwt Ok(LoginResponse { @@ -334,16 +317,8 @@ impl Perform for AddAdmin { let added = data.added; let added_person_id = data.person_id; - let added_admin = match blocking(context.pool(), move |conn| { - Person::add_admin(conn, added_person_id, added) - }) - .await? - { - Ok(a) => a, - Err(_) => { - return Err(ApiError::err("couldnt_update_user").into()); - } - }; + let added_admin = Person::add_admin(&&context.pool.get().await?, added_person_id, added) + .map_err(|_| ApiError::err("couldnt_update_user"))?; // Mod tables let form = ModAddForm { @@ -352,14 +327,11 @@ impl Perform for AddAdmin { removed: Some(!data.added), }; - blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; + ModAdd::create(&&context.pool.get().await?, &form)?; - let site_creator_id = blocking(context.pool(), move |conn| { - Site::read(conn, 1).map(|s| s.creator_id) - }) - .await??; + let site_creator_id = Site::read(&&context.pool.get().await?, 1).map(|s| s.creator_id)?; - let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; + let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?; let creator_index = admins .iter() .position(|r| r.person.id == site_creator_id) @@ -396,26 +368,21 @@ impl Perform for BanPerson { let ban = data.ban; let banned_person_id = data.person_id; - let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban); - if blocking(context.pool(), ban_person).await?.is_err() { + let ban_person = Person::ban_person(&&context.pool.get().await?, banned_person_id, ban); + if ban_person.is_err() { return Err(ApiError::err("couldnt_update_user").into()); } // Remove their data if that's desired if data.remove_data.unwrap_or(false) { // Posts - blocking(context.pool(), move |conn: &'_ _| { - Post::update_removed_for_creator(conn, banned_person_id, None, true) - }) - .await??; + Post::update_removed_for_creator(&&context.pool.get().await?, banned_person_id, None, true)?; // Communities // Remove all communities where they're the top mod // for now, remove the communities manually - let first_mod_communities = blocking(context.pool(), move |conn: &'_ _| { - CommunityModeratorView::get_community_first_mods(conn) - }) - .await??; + let first_mod_communities = + CommunityModeratorView::get_community_first_mods(&&context.pool.get().await?)?; // Filter to only this banned users top communities let banned_user_first_communities: Vec = first_mod_communities @@ -424,17 +391,15 @@ impl Perform for BanPerson { .collect(); for first_mod_community in banned_user_first_communities { - blocking(context.pool(), move |conn: &'_ _| { - Community::update_removed(conn, first_mod_community.community.id, true) - }) - .await??; + Community::update_removed( + &&context.pool.get().await?, + first_mod_community.community.id, + true, + )?; } // Comments - blocking(context.pool(), move |conn: &'_ _| { - Comment::update_removed_for_creator(conn, banned_person_id, true) - }) - .await??; + Comment::update_removed_for_creator(&&context.pool.get().await?, banned_person_id, true)?; } // Mod tables @@ -448,13 +413,10 @@ impl Perform for BanPerson { expires, }; - blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; + ModBan::create(&&context.pool.get().await?, &form)?; let person_id = data.person_id; - let person_view = blocking(context.pool(), move |conn| { - PersonViewSafe::read(conn, person_id) - }) - .await??; + let person_view = PersonViewSafe::read(&&context.pool.get().await?, person_id)?; let res = BanPersonResponse { person_view, @@ -497,23 +459,18 @@ impl Perform for BlockPerson { }; if data.block { - let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form); - if blocking(context.pool(), block).await?.is_err() { + let block = PersonBlock::block(&&context.pool.get().await?, &person_block_form); + if block.is_err() { return Err(ApiError::err("person_block_already_exists").into()); } } else { - let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form); - if blocking(context.pool(), unblock).await?.is_err() { + let unblock = PersonBlock::unblock(&&context.pool.get().await?, &person_block_form); + if unblock.is_err() { return Err(ApiError::err("person_block_already_exists").into()); } } - // TODO does any federated stuff need to be done here? - - let person_view = blocking(context.pool(), move |conn| { - PersonViewSafe::read(conn, target_id) - }) - .await??; + let person_view = PersonViewSafe::read(&&context.pool.get().await?, target_id)?; let res = BlockPersonResponse { person_view, @@ -544,18 +501,15 @@ impl Perform for GetReplies { let person_id = local_user_view.person.id; let show_bot_accounts = local_user_view.local_user.show_bot_accounts; - let replies = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .sort(sort) - .unread_only(unread_only) - .recipient_id(person_id) - .show_bot_accounts(show_bot_accounts) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await??; + let replies = CommentQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .unread_only(unread_only) + .recipient_id(person_id) + .show_bot_accounts(show_bot_accounts) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list()?; Ok(GetRepliesResponse { replies }) } @@ -579,17 +533,14 @@ impl Perform for GetPersonMentions { let limit = data.limit; let unread_only = data.unread_only; let person_id = local_user_view.person.id; - let mentions = blocking(context.pool(), move |conn| { - PersonMentionQueryBuilder::create(conn) - .recipient_id(person_id) - .my_person_id(person_id) - .sort(sort) - .unread_only(unread_only) - .page(page) - .limit(limit) - .list() - }) - .await??; + let mentions = PersonMentionQueryBuilder::create(&&context.pool.get().await?) + .recipient_id(person_id) + .my_person_id(person_id) + .sort(sort) + .unread_only(unread_only) + .page(page) + .limit(limit) + .list()?; Ok(GetPersonMentionsResponse { mentions }) } @@ -608,10 +559,7 @@ impl Perform for MarkPersonMentionAsRead { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let person_mention_id = data.person_mention_id; - let read_person_mention = blocking(context.pool(), move |conn| { - PersonMention::read(conn, person_mention_id) - }) - .await??; + let read_person_mention = PersonMention::read(&&context.pool.get().await?, person_mention_id)?; if local_user_view.person.id != read_person_mention.recipient_id { return Err(ApiError::err("couldnt_update_comment").into()); @@ -620,17 +568,18 @@ impl Perform for MarkPersonMentionAsRead { let person_mention_id = read_person_mention.id; let read = data.read; let update_mention = - move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read); - if blocking(context.pool(), update_mention).await?.is_err() { + PersonMention::update_read(&&context.pool.get().await?, person_mention_id, read); + if update_mention.is_err() { return Err(ApiError::err("couldnt_update_comment").into()); }; let person_mention_id = read_person_mention.id; let person_id = local_user_view.person.id; - let person_mention_view = blocking(context.pool(), move |conn| { - PersonMentionView::read(conn, person_mention_id, Some(person_id)) - }) - .await??; + let person_mention_view = PersonMentionView::read( + &&context.pool.get().await?, + person_mention_id, + Some(person_id), + )?; Ok(PersonMentionResponse { person_mention_view, @@ -651,41 +600,35 @@ impl Perform for MarkAllAsRead { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let person_id = local_user_view.person.id; - let replies = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .my_person_id(person_id) - .recipient_id(person_id) - .unread_only(true) - .page(1) - .limit(999) - .list() - }) - .await??; + let replies = CommentQueryBuilder::create(&&context.pool.get().await?) + .my_person_id(person_id) + .recipient_id(person_id) + .unread_only(true) + .page(1) + .limit(999) + .list()?; // TODO: this should probably be a bulk operation // Not easy to do as a bulk operation, // because recipient_id isn't in the comment table for comment_view in &replies { let reply_id = comment_view.comment.id; - let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true); - if blocking(context.pool(), mark_as_read).await?.is_err() { + let mark_as_read = Comment::update_read(&&context.pool.get().await?, reply_id, true); + if mark_as_read.is_err() { return Err(ApiError::err("couldnt_update_comment").into()); } } // Mark all user mentions as read let update_person_mentions = - move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id); - if blocking(context.pool(), update_person_mentions) - .await? - .is_err() - { + PersonMention::mark_all_as_read(&&context.pool.get().await?, person_id); + if update_person_mentions.is_err() { return Err(ApiError::err("couldnt_update_comment").into()); } // Mark all private_messages as read - let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id); - if blocking(context.pool(), update_pm).await?.is_err() { + let update_pm = PrivateMessage::mark_all_as_read(&&context.pool.get().await?, person_id); + if update_pm.is_err() { return Err(ApiError::err("couldnt_update_private_message").into()); } @@ -706,11 +649,8 @@ impl Perform for PasswordReset { // Fetch that email let email = data.email.clone(); - let local_user_view = blocking(context.pool(), move |conn| { - LocalUserView::find_by_email(conn, &email) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?; + let local_user_view = LocalUserView::find_by_email(&&context.pool.get().await?, &email) + .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?; // Generate a random token let token = generate_random_string(); @@ -718,10 +658,7 @@ impl Perform for PasswordReset { // Insert the row let token2 = token.clone(); let local_user_id = local_user_view.local_user.id; - blocking(context.pool(), move |conn| { - PasswordResetRequest::create_token(conn, local_user_id, &token2) - }) - .await??; + PasswordResetRequest::create_token(&&context.pool.get().await?, local_user_id, &token2)?; // Email the pure token to the user. // TODO no i18n support here. @@ -749,10 +686,8 @@ impl Perform for PasswordChange { // Fetch the user_id from the token let token = data.token.clone(); - let local_user_id = blocking(context.pool(), move |conn| { - PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) - }) - .await??; + let local_user_id = PasswordResetRequest::read_from_token(&&context.pool.get().await?, &token) + .map(|p| p.local_user_id)?; password_length_check(&data.password)?; @@ -763,11 +698,9 @@ impl Perform for PasswordChange { // Update the user with the new password let password = data.password.clone(); - let updated_local_user = blocking(context.pool(), move |conn| { - LocalUser::update_password(conn, local_user_id, &password) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_user"))?; + let updated_local_user = + LocalUser::update_password(&&context.pool.get().await?, local_user_id, &password) + .map_err(|_| ApiError::err("couldnt_update_user"))?; // Return the jwt Ok(LoginResponse { @@ -802,16 +735,11 @@ impl Perform for GetReportCount { } } else { let ids = community_ids.clone(); - let comment_reports = blocking(context.pool(), move |conn| { - CommentReportView::get_report_count(conn, &ids) - }) - .await??; + let comment_reports = + CommentReportView::get_report_count(&&context.pool.get().await?, &ids)?; let ids = community_ids.clone(); - let post_reports = blocking(context.pool(), move |conn| { - PostReportView::get_report_count(conn, &ids) - }) - .await??; + let post_reports = PostReportView::get_report_count(&&context.pool.get().await?, &ids)?; GetReportCountResponse { community: data.community, diff --git a/crates/api/src/post.rs b/crates/api/src/post.rs index f0f025e26..43c8626fb 100644 --- a/crates/api/src/post.rs +++ b/crates/api/src/post.rs @@ -1,7 +1,6 @@ use crate::Perform; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, check_downvotes_enabled, check_person_block, @@ -45,7 +44,7 @@ impl Perform for CreatePostLike { // Check for a community ban let post_id = data.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; check_community_ban(local_user_view.person.id, post.community_id, context.pool()).await?; @@ -59,10 +58,7 @@ impl Perform for CreatePostLike { // Remove any likes first let person_id = local_user_view.person.id; - blocking(context.pool(), move |conn| { - PostLike::remove(conn, person_id, post_id) - }) - .await??; + PostLike::remove(&&context.pool.get().await?, person_id, post_id)?; let community_id = post.community_id; let object = PostOrComment::Post(Box::new(post)); @@ -71,8 +67,8 @@ impl Perform for CreatePostLike { let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); if do_add { let like_form2 = like_form.clone(); - let like = move |conn: &'_ _| PostLike::like(conn, &like_form2); - if blocking(context.pool(), like).await?.is_err() { + let like = PostLike::like(&&context.pool.get().await?, &like_form2); + if like.is_err() { return Err(ApiError::err("couldnt_like_post").into()); } @@ -123,7 +119,7 @@ impl Perform for LockPost { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let post_id = data.post_id; - let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let orig_post = Post::read(&&context.pool.get().await?, post_id)?; check_community_ban( local_user_view.person.id, @@ -143,10 +139,7 @@ impl Perform for LockPost { // Update the post let post_id = data.post_id; let locked = data.locked; - let updated_post = blocking(context.pool(), move |conn| { - Post::update_locked(conn, post_id, locked) - }) - .await??; + let updated_post = Post::update_locked(&&context.pool.get().await?, post_id, locked)?; // Mod tables let form = ModLockPostForm { @@ -154,7 +147,7 @@ impl Perform for LockPost { post_id: data.post_id, locked: Some(locked), }; - blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??; + ModLockPost::create(&&context.pool.get().await?, &form)?; // apub updates CreateOrUpdatePost::send( @@ -189,7 +182,7 @@ impl Perform for StickyPost { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let post_id = data.post_id; - let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let orig_post = Post::read(&&context.pool.get().await?, post_id)?; check_community_ban( local_user_view.person.id, @@ -209,10 +202,7 @@ impl Perform for StickyPost { // Update the post let post_id = data.post_id; let stickied = data.stickied; - let updated_post = blocking(context.pool(), move |conn| { - Post::update_stickied(conn, post_id, stickied) - }) - .await??; + let updated_post = Post::update_stickied(&&context.pool.get().await?, post_id, stickied)?; // Mod tables let form = ModStickyPostForm { @@ -220,10 +210,7 @@ impl Perform for StickyPost { post_id: data.post_id, stickied: Some(stickied), }; - blocking(context.pool(), move |conn| { - ModStickyPost::create(conn, &form) - }) - .await??; + ModStickyPost::create(&&context.pool.get().await?, &form)?; // Apub updates // TODO stickied should pry work like locked for ease of use @@ -264,23 +251,20 @@ impl Perform for SavePost { }; if data.save { - let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form); - if blocking(context.pool(), save).await?.is_err() { + let save = PostSaved::save(&&context.pool.get().await?, &post_saved_form); + if save.is_err() { return Err(ApiError::err("couldnt_save_post").into()); } } else { - let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form); - if blocking(context.pool(), unsave).await?.is_err() { + let unsave = PostSaved::unsave(&&context.pool.get().await?, &post_saved_form); + if unsave.is_err() { return Err(ApiError::err("couldnt_save_post").into()); } } let post_id = data.post_id; let person_id = local_user_view.person.id; - let post_view = blocking(context.pool(), move |conn| { - PostView::read(conn, post_id, Some(person_id)) - }) - .await??; + let post_view = PostView::read(&&context.pool.get().await?, post_id, Some(person_id))?; // Mark the post as read mark_post_as_read(person_id, post_id, context.pool()).await?; diff --git a/crates/api/src/post_report.rs b/crates/api/src/post_report.rs index e718b775a..bccbc6a7d 100644 --- a/crates/api/src/post_report.rs +++ b/crates/api/src/post_report.rs @@ -1,7 +1,6 @@ use crate::Perform; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, collect_moderated_communities, get_local_user_view_from_jwt, @@ -52,10 +51,7 @@ impl Perform for CreatePostReport { let person_id = local_user_view.person.id; let post_id = data.post_id; - let post_view = blocking(context.pool(), move |conn| { - PostView::read(conn, post_id, None) - }) - .await??; + let post_view = PostView::read(&&context.pool.get().await?, post_id, None)?; check_community_ban(person_id, post_view.community.id, context.pool()).await?; @@ -68,11 +64,8 @@ impl Perform for CreatePostReport { reason: data.reason.to_owned(), }; - let report = blocking(context.pool(), move |conn| { - PostReport::report(conn, &report_form) - }) - .await? - .map_err(|_| ApiError::err("couldnt_create_report"))?; + let report = PostReport::report(&&context.pool.get().await?, &report_form) + .map_err(|_| ApiError::err("couldnt_create_report"))?; let res = CreatePostReportResponse { success: true }; @@ -108,21 +101,16 @@ impl Perform for ResolvePostReport { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let report_id = data.report_id; - let report = blocking(context.pool(), move |conn| { - PostReportView::read(conn, report_id) - }) - .await??; + let report = PostReportView::read(&&context.pool.get().await?, report_id)?; let person_id = local_user_view.person.id; is_mod_or_admin(context.pool(), person_id, report.community.id).await?; let resolved = data.resolved; - let resolve_fun = move |conn: &'_ _| { - if resolved { - PostReport::resolve(conn, report_id, person_id) - } else { - PostReport::unresolve(conn, report_id, person_id) - } + let resolve_fun = if resolved { + PostReport::resolve(&&context.pool.get().await?, report_id, person_id) + } else { + PostReport::unresolve(&&context.pool.get().await?, report_id, person_id) }; let res = ResolvePostReportResponse { @@ -130,7 +118,7 @@ impl Perform for ResolvePostReport { resolved: true, }; - if blocking(context.pool(), resolve_fun).await?.is_err() { + if resolve_fun.is_err() { return Err(ApiError::err("couldnt_resolve_report").into()); }; @@ -166,14 +154,11 @@ impl Perform for ListPostReports { let page = data.page; let limit = data.limit; - let posts = blocking(context.pool(), move |conn| { - PostReportQueryBuilder::create(conn) - .community_ids(community_ids) - .page(page) - .limit(limit) - .list() - }) - .await??; + let posts = PostReportQueryBuilder::create(&&context.pool.get().await?) + .community_ids(community_ids) + .page(page) + .limit(limit) + .list()?; let res = ListPostReportsResponse { posts }; diff --git a/crates/api/src/private_message.rs b/crates/api/src/private_message.rs index f23bf71cd..f8a86d4f3 100644 --- a/crates/api/src/private_message.rs +++ b/crates/api/src/private_message.rs @@ -1,7 +1,6 @@ use crate::Perform; use actix_web::web::Data; use lemmy_api_common::{ - blocking, get_local_user_view_from_jwt, person::{MarkPrivateMessageAsRead, PrivateMessageResponse}, }; @@ -24,10 +23,8 @@ impl Perform for MarkPrivateMessageAsRead { // Checking permissions let private_message_id = data.private_message_id; - let orig_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::read(conn, private_message_id) - }) - .await??; + let orig_private_message = + PrivateMessage::read(&&context.pool.get().await?, private_message_id)?; if local_user_view.person.id != orig_private_message.recipient_id { return Err(ApiError::err("couldnt_update_private_message").into()); } @@ -35,11 +32,8 @@ impl Perform for MarkPrivateMessageAsRead { // Doing the update let private_message_id = data.private_message_id; let read = data.read; - blocking(context.pool(), move |conn| { - PrivateMessage::update_read(conn, private_message_id, read) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_private_message"))?; + PrivateMessage::update_read(&&context.pool.get().await?, private_message_id, read) + .map_err(|_| ApiError::err("couldnt_update_private_message"))?; // No need to send an apub update let op = UserOperation::MarkPrivateMessageAsRead; diff --git a/crates/api/src/site.rs b/crates/api/src/site.rs index 221b9870f..fa8dd4d37 100644 --- a/crates/api/src/site.rs +++ b/crates/api/src/site.rs @@ -2,7 +2,6 @@ use crate::Perform; use actix_web::web::Data; use anyhow::Context; use lemmy_api_common::{ - blocking, build_federated_instances, get_local_user_view_from_jwt, get_local_user_view_from_jwt_opt, @@ -67,51 +66,69 @@ impl Perform for GetModlog { let mod_person_id = data.mod_person_id; let page = data.page; let limit = data.limit; - let removed_posts = blocking(context.pool(), move |conn| { - ModRemovePostView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let removed_posts = ModRemovePostView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; - let locked_posts = blocking(context.pool(), move |conn| { - ModLockPostView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let locked_posts = ModLockPostView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; - let stickied_posts = blocking(context.pool(), move |conn| { - ModStickyPostView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let stickied_posts = ModStickyPostView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; - let removed_comments = blocking(context.pool(), move |conn| { - ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let removed_comments = ModRemoveCommentView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; - let banned_from_community = blocking(context.pool(), move |conn| { - ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let banned_from_community = ModBanFromCommunityView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; - let added_to_community = blocking(context.pool(), move |conn| { - ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let added_to_community = ModAddCommunityView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; - let transferred_to_community = blocking(context.pool(), move |conn| { - ModTransferCommunityView::list(conn, community_id, mod_person_id, page, limit) - }) - .await??; + let transferred_to_community = ModTransferCommunityView::list( + &&context.pool.get().await?, + community_id, + mod_person_id, + page, + limit, + )?; // These arrays are only for the full modlog, when a community isn't given let (removed_communities, banned, added) = if data.community_id.is_none() { - blocking(context.pool(), move |conn| { - Ok(( - ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?, - ModBanView::list(conn, mod_person_id, page, limit)?, - ModAddView::list(conn, mod_person_id, page, limit)?, - )) as Result<_, LemmyError> - }) - .await?? + ( + ModRemoveCommunityView::list(&&context.pool.get().await?, mod_person_id, page, limit)?, + ModBanView::list(&&context.pool.get().await?, mod_person_id, page, limit)?, + ModAddView::list(&&context.pool.get().await?, mod_person_id, page, limit)?, + ) } else { (Vec::new(), Vec::new(), Vec::new()) }; @@ -182,64 +199,52 @@ impl Perform for Search { let creator_id = data.creator_id; match search_type { SearchType::Posts => { - posts = blocking(context.pool(), move |conn| { - PostQueryBuilder::create(conn) - .sort(sort) - .show_nsfw(show_nsfw) - .show_bot_accounts(show_bot_accounts) - .show_read_posts(show_read_posts) - .listing_type(listing_type) - .community_id(community_id) - .community_actor_id(community_actor_id) - .creator_id(creator_id) - .my_person_id(person_id) - .search_term(q) - .page(page) - .limit(limit) - .list() - }) - .await??; + posts = PostQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .show_nsfw(show_nsfw) + .show_bot_accounts(show_bot_accounts) + .show_read_posts(show_read_posts) + .listing_type(listing_type) + .community_id(community_id) + .community_actor_id(community_actor_id) + .creator_id(creator_id) + .my_person_id(person_id) + .search_term(q) + .page(page) + .limit(limit) + .list()?; } SearchType::Comments => { - comments = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .sort(sort) - .listing_type(listing_type) - .search_term(q) - .show_bot_accounts(show_bot_accounts) - .community_id(community_id) - .community_actor_id(community_actor_id) - .creator_id(creator_id) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await??; + comments = CommentQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .listing_type(listing_type) + .search_term(q) + .show_bot_accounts(show_bot_accounts) + .community_id(community_id) + .community_actor_id(community_actor_id) + .creator_id(creator_id) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list()?; } SearchType::Communities => { - communities = blocking(context.pool(), move |conn| { - CommunityQueryBuilder::create(conn) - .sort(sort) - .listing_type(listing_type) - .search_term(q) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await??; + communities = CommunityQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .listing_type(listing_type) + .search_term(q) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list()?; } SearchType::Users => { - users = blocking(context.pool(), move |conn| { - PersonQueryBuilder::create(conn) - .sort(sort) - .search_term(q) - .page(page) - .limit(limit) - .list() - }) - .await??; + users = PersonQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .search_term(q) + .page(page) + .limit(limit) + .list()?; } SearchType::All => { // If the community or creator is included, dont search communities or users @@ -247,59 +252,50 @@ impl Perform for Search { data.community_id.is_some() || data.community_name.is_some() || data.creator_id.is_some(); let community_actor_id_2 = community_actor_id.to_owned(); - posts = blocking(context.pool(), move |conn| { - PostQueryBuilder::create(conn) - .sort(sort) - .show_nsfw(show_nsfw) - .show_bot_accounts(show_bot_accounts) - .show_read_posts(show_read_posts) - .listing_type(listing_type) - .community_id(community_id) - .community_actor_id(community_actor_id_2) - .creator_id(creator_id) - .my_person_id(person_id) - .search_term(q) - .page(page) - .limit(limit) - .list() - }) - .await??; + posts = PostQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .show_nsfw(show_nsfw) + .show_bot_accounts(show_bot_accounts) + .show_read_posts(show_read_posts) + .listing_type(listing_type) + .community_id(community_id) + .community_actor_id(community_actor_id_2) + .creator_id(creator_id) + .my_person_id(person_id) + .search_term(q) + .page(page) + .limit(limit) + .list()?; let q = data.q.to_owned(); let community_actor_id = community_actor_id.to_owned(); - comments = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .sort(sort) - .listing_type(listing_type) - .search_term(q) - .show_bot_accounts(show_bot_accounts) - .community_id(community_id) - .community_actor_id(community_actor_id) - .creator_id(creator_id) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await??; + comments = CommentQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .listing_type(listing_type) + .search_term(q) + .show_bot_accounts(show_bot_accounts) + .community_id(community_id) + .community_actor_id(community_actor_id) + .creator_id(creator_id) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list()?; let q = data.q.to_owned(); communities = if community_or_creator_included { vec![] } else { - blocking(context.pool(), move |conn| { - CommunityQueryBuilder::create(conn) - .sort(sort) - .listing_type(listing_type) - .search_term(q) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await?? + CommunityQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .listing_type(listing_type) + .search_term(q) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list()? }; let q = data.q.to_owned(); @@ -307,35 +303,29 @@ impl Perform for Search { users = if community_or_creator_included { vec![] } else { - blocking(context.pool(), move |conn| { - PersonQueryBuilder::create(conn) - .sort(sort) - .search_term(q) - .page(page) - .limit(limit) - .list() - }) - .await?? + PersonQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .search_term(q) + .page(page) + .limit(limit) + .list()? }; } SearchType::Url => { - posts = blocking(context.pool(), move |conn| { - PostQueryBuilder::create(conn) - .sort(sort) - .show_nsfw(show_nsfw) - .show_bot_accounts(show_bot_accounts) - .show_read_posts(show_read_posts) - .listing_type(listing_type) - .my_person_id(person_id) - .community_id(community_id) - .community_actor_id(community_actor_id) - .creator_id(creator_id) - .url_search(q) - .page(page) - .limit(limit) - .list() - }) - .await??; + posts = PostQueryBuilder::create(&&context.pool.get().await?) + .sort(sort) + .show_nsfw(show_nsfw) + .show_bot_accounts(show_bot_accounts) + .show_read_posts(show_read_posts) + .listing_type(listing_type) + .my_person_id(person_id) + .community_id(community_id) + .community_actor_id(community_actor_id) + .creator_id(creator_id) + .url_search(q) + .page(page) + .limit(limit) + .list()?; } }; @@ -386,7 +376,7 @@ impl Perform for TransferSite { is_admin(&local_user_view)?; - let read_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??; + let read_site = Site::read_simple(&&context.pool.get().await?)?; // Make sure user is the creator if read_site.creator_id != local_user_view.person.id { @@ -394,8 +384,8 @@ impl Perform for TransferSite { } let new_creator_id = data.person_id; - let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id); - if blocking(context.pool(), transfer_site).await?.is_err() { + let transfer_site = Site::transfer(&&context.pool.get().await?, new_creator_id); + if transfer_site.is_err() { return Err(ApiError::err("couldnt_update_site").into()); }; @@ -406,11 +396,11 @@ impl Perform for TransferSite { removed: Some(false), }; - blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; + ModAdd::create(&&context.pool.get().await?, &form)?; - let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; + let site_view = SiteView::read(&&context.pool.get().await?)?; - let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; + let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?; let creator_index = admins .iter() .position(|r| r.person.id == site_view.creator.id) @@ -418,7 +408,7 @@ impl Perform for TransferSite { let creator_person = admins.remove(creator_index); admins.insert(0, creator_person); - let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??; + let banned = PersonViewSafe::banned(&&context.pool.get().await?)?; let federated_instances = build_federated_instances(context.pool()).await?; Ok(GetSiteResponse { diff --git a/crates/api_common/src/lib.rs b/crates/api_common/src/lib.rs index e7d5181bc..ccbd42418 100644 --- a/crates/api_common/src/lib.rs +++ b/crates/api_common/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::needless_borrow)] + pub mod comment; pub mod community; pub mod person; @@ -66,22 +68,6 @@ pub struct WebFingerResponse { pub links: Vec, } -pub async fn blocking(pool: &DbPool, f: F) -> Result -where - F: FnOnce(&diesel::PgConnection) -> T + Send + 'static, - T: Send + 'static, -{ - let pool = pool.clone(); - let res = actix_web::web::block(move || { - let conn = pool.get()?; - let res = (f)(&conn); - Ok(res) as Result - }) - .await?; - - res -} - pub async fn send_local_notifs( mentions: Vec, comment: Comment, @@ -90,10 +76,14 @@ pub async fn send_local_notifs( pool: &DbPool, do_send_email: bool, ) -> Result, LemmyError> { - let ids = blocking(pool, move |conn| { - do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email) - }) - .await?; + let ids = do_send_local_notifs( + &&pool.get().await?, + &mentions, + &comment, + &person, + &post, + do_send_email, + ); Ok(ids) } @@ -222,10 +212,8 @@ pub async fn is_mod_or_admin( person_id: PersonId, community_id: CommunityId, ) -> Result<(), LemmyError> { - let is_mod_or_admin = blocking(pool, move |conn| { - CommunityView::is_mod_or_admin(conn, person_id, community_id) - }) - .await?; + let is_mod_or_admin = + CommunityView::is_mod_or_admin(&&pool.get().await?, person_id, community_id); if !is_mod_or_admin { return Err(ApiError::err("not_a_mod_or_admin").into()); } @@ -240,9 +228,7 @@ pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> { } pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result { - blocking(pool, move |conn| Post::read(conn, post_id)) - .await? - .map_err(|_| ApiError::err("couldnt_find_post").into()) + Post::read(&&pool.get().await?, post_id).map_err(|_| ApiError::err("couldnt_find_post").into()) } pub async fn mark_post_as_read( @@ -251,12 +237,8 @@ pub async fn mark_post_as_read( pool: &DbPool, ) -> Result { let post_read_form = PostReadForm { post_id, person_id }; - - blocking(pool, move |conn| { - PostRead::mark_as_read(conn, &post_read_form) - }) - .await? - .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into()) + PostRead::mark_as_read(&&pool.get().await?, &post_read_form) + .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into()) } pub async fn get_local_user_view_from_jwt( @@ -267,8 +249,7 @@ pub async fn get_local_user_view_from_jwt( .map_err(|_| ApiError::err("not_logged_in"))? .claims; let local_user_id = LocalUserId(claims.sub); - let local_user_view = - blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??; + let local_user_view = LocalUserView::read(&&pool.get().await?, local_user_id)?; // Check for a site ban if local_user_view.person.banned { return Err(ApiError::err("site_ban").into()); @@ -315,10 +296,8 @@ pub async fn get_local_user_settings_view_from_jwt( .map_err(|_| ApiError::err("not_logged_in"))? .claims; let local_user_id = LocalUserId(claims.sub); - let local_user_view = blocking(pool, move |conn| { - LocalUserSettingsView::read(conn, local_user_id) - }) - .await??; + let local_user_view = LocalUserSettingsView::read(&&pool.get().await?, local_user_id)?; + // Check for a site ban if local_user_view.person.banned { return Err(ApiError::err("site_ban").into()); @@ -346,9 +325,8 @@ pub async fn check_community_ban( community_id: CommunityId, pool: &DbPool, ) -> Result<(), LemmyError> { - let is_banned = - move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); - if blocking(pool, is_banned).await? { + let is_banned = CommunityPersonBanView::get(&&pool.get().await?, person_id, community_id).is_ok(); + if is_banned { Err(ApiError::err("community_ban").into()) } else { Ok(()) @@ -360,8 +338,8 @@ pub async fn check_person_block( potential_blocker_id: PersonId, pool: &DbPool, ) -> Result<(), LemmyError> { - let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok(); - if blocking(pool, is_blocked).await? { + let is_blocked = PersonBlock::read(&&pool.get().await?, potential_blocker_id, my_id).is_ok(); + if is_blocked { Err(ApiError::err("person_block").into()) } else { Ok(()) @@ -370,7 +348,7 @@ pub async fn check_person_block( pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> { if score == -1 { - let site = blocking(pool, move |conn| Site::read_simple(conn)).await??; + let site = Site::read_simple(&&pool.get().await?)?; if !site.enable_downvotes { return Err(ApiError::err("downvotes_disabled").into()); } @@ -395,10 +373,7 @@ pub async fn collect_moderated_communities( is_mod_or_admin(pool, person_id, community_id).await?; Ok(vec![community_id]) } else { - let ids = blocking(pool, move |conn: &'_ _| { - CommunityModerator::get_person_moderated_communities(conn, person_id) - }) - .await??; + let ids = CommunityModerator::get_person_moderated_communities(&&pool.get().await?, person_id)?; Ok(ids) } } @@ -407,10 +382,7 @@ pub async fn build_federated_instances( pool: &DbPool, ) -> Result, LemmyError> { if Settings::get().federation.enabled { - let distinct_communities = blocking(pool, move |conn| { - Community::distinct_federated_communities(conn) - }) - .await??; + let distinct_communities = Community::distinct_federated_communities(&&pool.get().await?)?; let allowed = Settings::get().federation.allowed_instances; let blocked = Settings::get().federation.blocked_instances; diff --git a/crates/api_crud/src/comment/create.rs b/crates/api_crud/src/comment/create.rs index c25966c7d..596b947b3 100644 --- a/crates/api_crud/src/comment/create.rs +++ b/crates/api_crud/src/comment/create.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, check_person_block, comment::*, @@ -60,8 +59,7 @@ impl PerformCrud for CreateComment { // If there's a parent_id, check to make sure that comment is in that post if let Some(parent_id) = data.parent_id { // Make sure the parent comment exists - let parent = blocking(context.pool(), move |conn| Comment::read(conn, parent_id)) - .await? + let parent = Comment::read(&&context.pool.get().await?, parent_id) .map_err(|_| ApiError::err("couldnt_create_comment"))?; check_person_block(local_user_view.person.id, parent.creator_id, context.pool()).await?; @@ -82,22 +80,15 @@ impl PerformCrud for CreateComment { // Create the comment let comment_form2 = comment_form.clone(); - let inserted_comment = blocking(context.pool(), move |conn| { - Comment::create(conn, &comment_form2) - }) - .await? - .map_err(|_| ApiError::err("couldnt_create_comment"))?; + let inserted_comment = Comment::create(&&context.pool.get().await?, &comment_form2) + .map_err(|_| ApiError::err("couldnt_create_comment"))?; // Necessary to update the ap_id let inserted_comment_id = inserted_comment.id; - let updated_comment: Comment = - blocking(context.pool(), move |conn| -> Result { - let apub_id = - generate_apub_endpoint(EndpointType::Comment, &inserted_comment_id.to_string())?; - Ok(Comment::update_ap_id(conn, inserted_comment_id, apub_id)?) - }) - .await? - .map_err(|_| ApiError::err("couldnt_create_comment"))?; + let apub_id = generate_apub_endpoint(EndpointType::Comment, &inserted_comment_id.to_string())?; + let updated_comment = + Comment::update_ap_id(&&context.pool.get().await?, inserted_comment_id, apub_id) + .map_err(|_| ApiError::err("couldnt_create_comment"))?; CreateOrUpdateComment::send( &updated_comment, @@ -128,8 +119,8 @@ impl PerformCrud for CreateComment { score: 1, }; - let like = move |conn: &'_ _| CommentLike::like(conn, &like_form); - if blocking(context.pool(), like).await?.is_err() { + let like = CommentLike::like(&&context.pool.get().await?, &like_form); + if like.is_err() { return Err(ApiError::err("couldnt_like_comment").into()); } @@ -146,11 +137,8 @@ impl PerformCrud for CreateComment { // If its a comment to yourself, mark it as read if local_user_view.person.id == inserted_comment.creator_id { let comment_id = inserted_comment.id; - blocking(context.pool(), move |conn| { - Comment::update_read(conn, comment_id, true) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_comment"))?; + Comment::update_read(&&context.pool.get().await?, comment_id, true) + .map_err(|_| ApiError::err("couldnt_update_comment"))?; } send_comment_ws_message( diff --git a/crates/api_crud/src/comment/delete.rs b/crates/api_crud/src/comment/delete.rs index 85917846e..8af2bb2d7 100644 --- a/crates/api_crud/src/comment/delete.rs +++ b/crates/api_crud/src/comment/delete.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, comment::*, get_local_user_view_from_jwt, @@ -28,10 +27,7 @@ impl PerformCrud for DeleteComment { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let comment_id = data.comment_id; - let orig_comment = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, None) - }) - .await??; + let orig_comment = CommentView::read(&&context.pool.get().await?, comment_id, None)?; check_community_ban( local_user_view.person.id, @@ -47,17 +43,11 @@ impl PerformCrud for DeleteComment { // Do the delete let deleted = data.deleted; - let updated_comment = blocking(context.pool(), move |conn| { - Comment::update_deleted(conn, comment_id, deleted) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_comment"))?; + let updated_comment = Comment::update_deleted(&&context.pool.get().await?, comment_id, deleted) + .map_err(|_| ApiError::err("couldnt_update_comment"))?; // Send the apub message - let community = blocking(context.pool(), move |conn| { - Community::read(conn, orig_comment.post.community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, orig_comment.post.community_id)?; send_apub_delete( &local_user_view.person, &community, @@ -68,7 +58,7 @@ impl PerformCrud for DeleteComment { .await?; let post_id = updated_comment.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; let recipient_ids = send_local_notifs( vec![], updated_comment, @@ -105,10 +95,7 @@ impl PerformCrud for RemoveComment { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let comment_id = data.comment_id; - let orig_comment = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, None) - }) - .await??; + let orig_comment = CommentView::read(&&context.pool.get().await?, comment_id, None)?; check_community_ban( local_user_view.person.id, @@ -127,11 +114,8 @@ impl PerformCrud for RemoveComment { // Do the remove let removed = data.removed; - let updated_comment = blocking(context.pool(), move |conn| { - Comment::update_removed(conn, comment_id, removed) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_comment"))?; + let updated_comment = Comment::update_removed(&&context.pool.get().await?, comment_id, removed) + .map_err(|_| ApiError::err("couldnt_update_comment"))?; // Mod tables let form = ModRemoveCommentForm { @@ -140,16 +124,10 @@ impl PerformCrud for RemoveComment { removed: Some(removed), reason: data.reason.to_owned(), }; - blocking(context.pool(), move |conn| { - ModRemoveComment::create(conn, &form) - }) - .await??; + ModRemoveComment::create(&&context.pool.get().await?, &form)?; // Send the apub message - let community = blocking(context.pool(), move |conn| { - Community::read(conn, orig_comment.post.community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, orig_comment.post.community_id)?; send_apub_remove( &local_user_view.person, &community, @@ -161,7 +139,7 @@ impl PerformCrud for RemoveComment { .await?; let post_id = updated_comment.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; let recipient_ids = send_local_notifs( vec![], updated_comment, diff --git a/crates/api_crud/src/comment/read.rs b/crates/api_crud/src/comment/read.rs index fc4bd1e35..1ae7028a6 100644 --- a/crates/api_crud/src/comment/read.rs +++ b/crates/api_crud/src/comment/read.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, comment::*, get_local_user_view_from_jwt_opt}; +use lemmy_api_common::{comment::*, get_local_user_view_from_jwt_opt}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_db_queries::{from_opt_str_to_opt_enum, DeleteableOrRemoveable, ListingType, SortType}; use lemmy_db_views::comment_view::CommentQueryBuilder; @@ -36,21 +36,18 @@ impl PerformCrud for GetComments { let saved_only = data.saved_only; let page = data.page; let limit = data.limit; - let mut comments = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .listing_type(listing_type) - .sort(sort) - .saved_only(saved_only) - .community_id(community_id) - .community_actor_id(community_actor_id) - .my_person_id(person_id) - .show_bot_accounts(show_bot_accounts) - .page(page) - .limit(limit) - .list() - }) - .await? - .map_err(|_| ApiError::err("couldnt_get_comments"))?; + let mut comments = CommentQueryBuilder::create(&&context.pool.get().await?) + .listing_type(listing_type) + .sort(sort) + .saved_only(saved_only) + .community_id(community_id) + .community_actor_id(community_actor_id) + .my_person_id(person_id) + .show_bot_accounts(show_bot_accounts) + .page(page) + .limit(limit) + .list() + .map_err(|_| ApiError::err("couldnt_get_comments"))?; // Blank out deleted or removed info for cv in comments diff --git a/crates/api_crud/src/comment/update.rs b/crates/api_crud/src/comment/update.rs index 8a5e8f0ed..e123becf1 100644 --- a/crates/api_crud/src/comment/update.rs +++ b/crates/api_crud/src/comment/update.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, comment::*, get_local_user_view_from_jwt, @@ -35,10 +34,7 @@ impl PerformCrud for EditComment { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let comment_id = data.comment_id; - let orig_comment = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, None) - }) - .await??; + let orig_comment = CommentView::read(&&context.pool.get().await?, comment_id, None)?; // TODO is this necessary? It should really only need to check on create check_community_ban( @@ -56,10 +52,11 @@ impl PerformCrud for EditComment { // Do the update let content_slurs_removed = remove_slurs(&data.content.to_owned()); let comment_id = data.comment_id; - let updated_comment = blocking(context.pool(), move |conn| { - Comment::update_content(conn, comment_id, &content_slurs_removed) - }) - .await? + let updated_comment = Comment::update_content( + &&context.pool.get().await?, + comment_id, + &content_slurs_removed, + ) .map_err(|_| ApiError::err("couldnt_update_comment"))?; // Send the apub update diff --git a/crates/api_crud/src/community/create.rs b/crates/api_crud/src/community/create.rs index ecaa9058d..102d4123c 100644 --- a/crates/api_crud/src/community/create.rs +++ b/crates/api_crud/src/community/create.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, community::{CommunityResponse, CreateCommunity}, get_local_user_view_from_jwt, is_admin, @@ -47,7 +46,7 @@ impl PerformCrud for CreateCommunity { let data: &CreateCommunity = self; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; - let site = blocking(context.pool(), move |conn| Site::read(conn, 0)).await??; + let site = Site::read(&&context.pool.get().await?, 0)?; if site.community_creation_admin_only && is_admin(&local_user_view).is_err() { return Err(ApiError::err("only_admins_can_create_communities").into()); } @@ -63,10 +62,8 @@ impl PerformCrud for CreateCommunity { // Double check for duplicate community actor_ids let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?; let actor_id_cloned = community_actor_id.to_owned(); - let community_dupe = blocking(context.pool(), move |conn| { - Community::read_from_apub_id(conn, &actor_id_cloned) - }) - .await?; + let community_dupe = + Community::read_from_apub_id(&&context.pool.get().await?, &actor_id_cloned); if community_dupe.is_ok() { return Err(ApiError::err("community_already_exists").into()); } @@ -94,11 +91,8 @@ impl PerformCrud for CreateCommunity { ..CommunityForm::default() }; - let inserted_community = blocking(context.pool(), move |conn| { - Community::create(conn, &community_form) - }) - .await? - .map_err(|_| ApiError::err("community_already_exists"))?; + let inserted_community = Community::create(&&context.pool.get().await?, &community_form) + .map_err(|_| ApiError::err("community_already_exists"))?; // The community creator becomes a moderator let community_moderator_form = CommunityModeratorForm { @@ -106,8 +100,8 @@ impl PerformCrud for CreateCommunity { person_id: local_user_view.person.id, }; - let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); - if blocking(context.pool(), join).await?.is_err() { + let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form); + if join.is_err() { return Err(ApiError::err("community_moderator_already_exists").into()); } @@ -118,16 +112,17 @@ impl PerformCrud for CreateCommunity { pending: false, }; - let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); - if blocking(context.pool(), follow).await?.is_err() { + let follow = CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form); + if follow.is_err() { return Err(ApiError::err("community_follower_already_exists").into()); } let person_id = local_user_view.person.id; - let community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, inserted_community.id, Some(person_id)) - }) - .await??; + let community_view = CommunityView::read( + &&context.pool.get().await?, + inserted_community.id, + Some(person_id), + )?; Ok(CommunityResponse { community_view }) } diff --git a/crates/api_crud/src/community/delete.rs b/crates/api_crud/src/community/delete.rs index b957b7d6e..d0bee702b 100644 --- a/crates/api_crud/src/community/delete.rs +++ b/crates/api_crud/src/community/delete.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt, is_admin}; +use lemmy_api_common::{community::*, get_local_user_view_from_jwt, is_admin}; use lemmy_apub::activities::deletion::{send_apub_delete, send_apub_remove}; use lemmy_db_queries::{source::community::Community_, Crud}; use lemmy_db_schema::source::{ @@ -25,10 +25,8 @@ impl PerformCrud for DeleteCommunity { // Fetch the community mods let community_id = data.community_id; - let community_mods = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await??; + let community_mods = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?; // Make sure deleter is the top mod if local_user_view.person.id != community_mods[0].moderator.id { @@ -38,11 +36,9 @@ impl PerformCrud for DeleteCommunity { // Do the delete let community_id = data.community_id; let deleted = data.deleted; - let updated_community = blocking(context.pool(), move |conn| { - Community::update_deleted(conn, community_id, deleted) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_community"))?; + let updated_community = + Community::update_deleted(&&context.pool.get().await?, community_id, deleted) + .map_err(|_| ApiError::err("couldnt_update_community"))?; // Send apub messages send_apub_delete( @@ -83,11 +79,9 @@ impl PerformCrud for RemoveCommunity { // Do the remove let community_id = data.community_id; let removed = data.removed; - let updated_community = blocking(context.pool(), move |conn| { - Community::update_removed(conn, community_id, removed) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_community"))?; + let updated_community = + Community::update_removed(&&context.pool.get().await?, community_id, removed) + .map_err(|_| ApiError::err("couldnt_update_community"))?; // Mod tables let expires = data.expires.map(naive_from_unix); @@ -98,10 +92,7 @@ impl PerformCrud for RemoveCommunity { reason: data.reason.to_owned(), expires, }; - blocking(context.pool(), move |conn| { - ModRemoveCommunity::create(conn, &form) - }) - .await??; + ModRemoveCommunity::create(&&context.pool.get().await?, &form)?; // Apub messages send_apub_remove( diff --git a/crates/api_crud/src/community/read.rs b/crates/api_crud/src/community/read.rs index 94e4ce7f4..ffda0ce4b 100644 --- a/crates/api_crud/src/community/read.rs +++ b/crates/api_crud/src/community/read.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt_opt}; +use lemmy_api_common::{community::*, get_local_user_view_from_jwt_opt}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_db_queries::{ from_opt_str_to_opt_enum, @@ -36,31 +36,24 @@ impl PerformCrud for GetCommunity { let name = data.name.to_owned().unwrap_or_else(|| "main".to_string()); let community_actor_id = build_actor_id_from_shortname(EndpointType::Community, &name)?; - blocking(context.pool(), move |conn| { - Community::read_from_apub_id(conn, &community_actor_id) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_community"))? - .id + Community::read_from_apub_id(&&context.pool.get().await?, &community_actor_id) + .map_err(|_| ApiError::err("couldnt_find_community"))? + .id } }; - let mut community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, community_id, person_id) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_community"))?; + let mut community_view = + CommunityView::read(&&context.pool.get().await?, community_id, person_id) + .map_err(|_| ApiError::err("couldnt_find_community"))?; // Blank out deleted or removed info if community_view.community.deleted || community_view.community.removed { community_view.community = community_view.community.blank_out_deleted_or_removed_info(); } - let moderators: Vec = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_community"))?; + let moderators: Vec = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id) + .map_err(|_| ApiError::err("couldnt_find_community"))?; let online = context .chat_server() @@ -104,17 +97,14 @@ impl PerformCrud for ListCommunities { let page = data.page; let limit = data.limit; - let mut communities = blocking(context.pool(), move |conn| { - CommunityQueryBuilder::create(conn) - .listing_type(listing_type) - .sort(sort) - .show_nsfw(show_nsfw) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await??; + let mut communities = CommunityQueryBuilder::create(&&context.pool.get().await?) + .listing_type(listing_type) + .sort(sort) + .show_nsfw(show_nsfw) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list()?; // Blank out deleted or removed info for cv in communities diff --git a/crates/api_crud/src/community/update.rs b/crates/api_crud/src/community/update.rs index 2196c57b7..1e783da14 100644 --- a/crates/api_crud/src/community/update.rs +++ b/crates/api_crud/src/community/update.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, community::{CommunityResponse, EditCommunity}, get_local_user_view_from_jwt, }; @@ -33,20 +32,15 @@ impl PerformCrud for EditCommunity { // Verify its a mod (only mods can edit it) let community_id = data.community_id; - let mods: Vec = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - .map(|v| v.into_iter().map(|m| m.moderator.id).collect()) - }) - .await??; + let mods: Vec = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id) + .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?; if !mods.contains(&local_user_view.person.id) { return Err(ApiError::err("not_a_moderator").into()); } let community_id = data.community_id; - let read_community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let read_community = Community::read(&&context.pool.get().await?, community_id)?; let icon = diesel_option_overwrite_to_url(&data.icon)?; let banner = diesel_option_overwrite_to_url(&data.banner)?; @@ -63,11 +57,9 @@ impl PerformCrud for EditCommunity { }; let community_id = data.community_id; - let updated_community = blocking(context.pool(), move |conn| { - Community::update(conn, community_id, &community_form) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_community"))?; + let updated_community = + Community::update(&&context.pool.get().await?, community_id, &community_form) + .map_err(|_| ApiError::err("couldnt_update_community"))?; UpdateCommunity::send(&updated_community, &local_user_view.person, context).await?; diff --git a/crates/api_crud/src/lib.rs b/crates/api_crud/src/lib.rs index f77632f90..6017955f7 100644 --- a/crates/api_crud/src/lib.rs +++ b/crates/api_crud/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::needless_borrow)] + use actix_web::{web, web::Data}; use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*}; use lemmy_utils::{ConnectionId, LemmyError}; diff --git a/crates/api_crud/src/post/create.rs b/crates/api_crud/src/post/create.rs index 547c657cf..a7547ff4c 100644 --- a/crates/api_crud/src/post/create.rs +++ b/crates/api_crud/src/post/create.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, get_local_user_view_from_jwt, mark_post_as_read, @@ -70,27 +69,20 @@ impl PerformCrud for CreatePost { ..PostForm::default() }; - let inserted_post = - match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? { - Ok(post) => post, - Err(e) => { - let err_type = if e.to_string() == "value too long for type character varying(200)" { - "post_title_too_long" - } else { - "couldnt_create_post" - }; - - return Err(ApiError::err(err_type).into()); - } + let inserted_post = Post::create(&&context.pool.get().await?, &post_form).map_err(|e| { + let err_type = if e.to_string() == "value too long for type character varying(200)" { + "post_title_too_long" + } else { + "couldnt_create_post" }; + ApiError::err(err_type) + })?; + let inserted_post_id = inserted_post.id; - let updated_post = blocking(context.pool(), move |conn| -> Result { - let apub_id = generate_apub_endpoint(EndpointType::Post, &inserted_post_id.to_string())?; - Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?) - }) - .await? - .map_err(|_| ApiError::err("couldnt_create_post"))?; + let apub_id = generate_apub_endpoint(EndpointType::Post, &inserted_post_id.to_string())?; + let updated_post = Post::update_ap_id(&&context.pool.get().await?, inserted_post_id, apub_id) + .map_err(|_| ApiError::err("couldnt_create_post"))?; CreateOrUpdatePost::send( &updated_post, @@ -109,8 +101,8 @@ impl PerformCrud for CreatePost { score: 1, }; - let like = move |conn: &'_ _| PostLike::like(conn, &like_form); - if blocking(context.pool(), like).await?.is_err() { + let like = PostLike::like(&&context.pool.get().await?, &like_form); + if like.is_err() { return Err(ApiError::err("couldnt_like_post").into()); } diff --git a/crates/api_crud/src/post/delete.rs b/crates/api_crud/src/post/delete.rs index c0ef35122..e2d84f122 100644 --- a/crates/api_crud/src/post/delete.rs +++ b/crates/api_crud/src/post/delete.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_community_ban, get_local_user_view_from_jwt, is_mod_or_admin, @@ -26,7 +25,7 @@ impl PerformCrud for DeletePost { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let post_id = data.post_id; - let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let orig_post = Post::read(&&context.pool.get().await?, post_id)?; check_community_ban( local_user_view.person.id, @@ -43,16 +42,10 @@ impl PerformCrud for DeletePost { // Update the post let post_id = data.post_id; let deleted = data.deleted; - let updated_post = blocking(context.pool(), move |conn| { - Post::update_deleted(conn, post_id, deleted) - }) - .await??; + let updated_post = Post::update_deleted(&&context.pool.get().await?, post_id, deleted)?; // apub updates - let community = blocking(context.pool(), move |conn| { - Community::read(conn, orig_post.community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, orig_post.community_id)?; send_apub_delete( &local_user_view.person, &community, @@ -86,7 +79,7 @@ impl PerformCrud for RemovePost { let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let post_id = data.post_id; - let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let orig_post = Post::read(&&context.pool.get().await?, post_id)?; check_community_ban( local_user_view.person.id, @@ -106,10 +99,7 @@ impl PerformCrud for RemovePost { // Update the post let post_id = data.post_id; let removed = data.removed; - let updated_post = blocking(context.pool(), move |conn| { - Post::update_removed(conn, post_id, removed) - }) - .await??; + let updated_post = Post::update_removed(&&context.pool.get().await?, post_id, removed)?; // Mod tables let form = ModRemovePostForm { @@ -118,16 +108,10 @@ impl PerformCrud for RemovePost { removed: Some(removed), reason: data.reason.to_owned(), }; - blocking(context.pool(), move |conn| { - ModRemovePost::create(conn, &form) - }) - .await??; + ModRemovePost::create(&&context.pool.get().await?, &form)?; // apub updates - let community = blocking(context.pool(), move |conn| { - Community::read(conn, orig_post.community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, orig_post.community_id)?; send_apub_remove( &local_user_view.person, &community, diff --git a/crates/api_crud/src/post/read.rs b/crates/api_crud/src/post/read.rs index d651a0577..3d4dd68d9 100644 --- a/crates/api_crud/src/post/read.rs +++ b/crates/api_crud/src/post/read.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, get_local_user_view_from_jwt_opt, mark_post_as_read, post::*}; +use lemmy_api_common::{get_local_user_view_from_jwt_opt, mark_post_as_read, post::*}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_db_queries::{from_opt_str_to_opt_enum, DeleteableOrRemoveable, ListingType, SortType}; use lemmy_db_views::{ @@ -32,11 +32,8 @@ impl PerformCrud for GetPost { let person_id = local_user_view.map(|u| u.person.id); let id = data.id; - let mut post_view = blocking(context.pool(), move |conn| { - PostView::read(conn, id, person_id) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_post"))?; + let mut post_view = PostView::read(&&context.pool.get().await?, id, person_id) + .map_err(|_| ApiError::err("couldnt_find_post"))?; // Blank out deleted info if post_view.post.deleted || post_view.post.removed { @@ -49,15 +46,12 @@ impl PerformCrud for GetPost { } let id = data.id; - let mut comments = blocking(context.pool(), move |conn| { - CommentQueryBuilder::create(conn) - .my_person_id(person_id) - .show_bot_accounts(show_bot_accounts) - .post_id(id) - .limit(9999) - .list() - }) - .await??; + let mut comments = CommentQueryBuilder::create(&&context.pool.get().await?) + .my_person_id(person_id) + .show_bot_accounts(show_bot_accounts) + .post_id(id) + .limit(9999) + .list()?; // Blank out deleted or removed info for cv in comments @@ -68,17 +62,13 @@ impl PerformCrud for GetPost { } let community_id = post_view.community.id; - let moderators = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await??; + let moderators = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?; // Necessary for the sidebar - let mut community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, community_id, person_id) - }) - .await? - .map_err(|_| ApiError::err("couldnt_find_community"))?; + let mut community_view = + CommunityView::read(&&context.pool.get().await?, community_id, person_id) + .map_err(|_| ApiError::err("couldnt_find_community"))?; // Blank out deleted or removed info if community_view.community.deleted || community_view.community.removed { @@ -137,23 +127,20 @@ impl PerformCrud for GetPosts { .unwrap_or(None); let saved_only = data.saved_only; - let mut posts = blocking(context.pool(), move |conn| { - PostQueryBuilder::create(conn) - .listing_type(listing_type) - .sort(sort) - .show_nsfw(show_nsfw) - .show_bot_accounts(show_bot_accounts) - .show_read_posts(show_read_posts) - .community_id(community_id) - .community_actor_id(community_actor_id) - .saved_only(saved_only) - .my_person_id(person_id) - .page(page) - .limit(limit) - .list() - }) - .await? - .map_err(|_| ApiError::err("couldnt_get_posts"))?; + let mut posts = PostQueryBuilder::create(&&context.pool.get().await?) + .listing_type(listing_type) + .sort(sort) + .show_nsfw(show_nsfw) + .show_bot_accounts(show_bot_accounts) + .show_read_posts(show_read_posts) + .community_id(community_id) + .community_actor_id(community_actor_id) + .saved_only(saved_only) + .my_person_id(person_id) + .page(page) + .limit(limit) + .list() + .map_err(|_| ApiError::err("couldnt_get_posts"))?; // Blank out deleted or removed info for pv in posts diff --git a/crates/api_crud/src/post/update.rs b/crates/api_crud/src/post/update.rs index d52538e06..e58d3e624 100644 --- a/crates/api_crud/src/post/update.rs +++ b/crates/api_crud/src/post/update.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, check_community_ban, get_local_user_view_from_jwt, post::*}; +use lemmy_api_common::{check_community_ban, get_local_user_view_from_jwt, post::*}; use lemmy_apub::activities::{post::create_or_update::CreateOrUpdatePost, CreateOrUpdateType}; use lemmy_db_queries::{source::post::Post_, Crud}; use lemmy_db_schema::{naive_now, source::post::*}; @@ -35,7 +35,7 @@ impl PerformCrud for EditPost { } let post_id = data.post_id; - let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let orig_post = Post::read(&&context.pool.get().await?, post_id)?; check_community_ban( local_user_view.person.id, @@ -72,22 +72,16 @@ impl PerformCrud for EditPost { }; let post_id = data.post_id; - let res = blocking(context.pool(), move |conn| { - Post::update(conn, post_id, &post_form) - }) - .await?; - let updated_post: Post = match res { - Ok(post) => post, - Err(e) => { + let updated_post = + Post::update(&&context.pool.get().await?, post_id, &post_form).map_err(|e| { let err_type = if e.to_string() == "value too long for type character varying(200)" { "post_title_too_long" } else { "couldnt_update_post" }; - return Err(ApiError::err(err_type).into()); - } - }; + ApiError::err(err_type) + })?; // Send apub update CreateOrUpdatePost::send( diff --git a/crates/api_crud/src/private_message/create.rs b/crates/api_crud/src/private_message/create.rs index 18ef3835d..4afbe24e2 100644 --- a/crates/api_crud/src/private_message/create.rs +++ b/crates/api_crud/src/private_message/create.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, check_person_block, get_local_user_view_from_jwt, person::{CreatePrivateMessage, PrivateMessageResponse}, @@ -44,33 +43,21 @@ impl PerformCrud for CreatePrivateMessage { ..PrivateMessageForm::default() }; - let inserted_private_message = match blocking(context.pool(), move |conn| { - PrivateMessage::create(conn, &private_message_form) - }) - .await? - { - Ok(private_message) => private_message, - Err(_e) => { - return Err(ApiError::err("couldnt_create_private_message").into()); - } - }; + let inserted_private_message = + PrivateMessage::create(&&context.pool.get().await?, &private_message_form) + .map_err(|_| ApiError::err("couldnt_create_private_message"))?; let inserted_private_message_id = inserted_private_message.id; - let updated_private_message = blocking( - context.pool(), - move |conn| -> Result { - let apub_id = generate_apub_endpoint( - EndpointType::PrivateMessage, - &inserted_private_message_id.to_string(), - )?; - Ok(PrivateMessage::update_ap_id( - conn, - inserted_private_message_id, - apub_id, - )?) - }, + let apub_id = generate_apub_endpoint( + EndpointType::PrivateMessage, + &inserted_private_message_id.to_string(), + )?; + + let updated_private_message = PrivateMessage::update_ap_id( + &&context.pool.get().await?, + inserted_private_message_id, + apub_id, ) - .await? .map_err(|_| ApiError::err("couldnt_create_private_message"))?; CreateOrUpdatePrivateMessage::send( @@ -92,10 +79,7 @@ impl PerformCrud for CreatePrivateMessage { // Send email to the local recipient, if one exists if res.private_message_view.recipient.local { let recipient_id = data.recipient_id; - let local_recipient = blocking(context.pool(), move |conn| { - LocalUserView::read_person(conn, recipient_id) - }) - .await??; + let local_recipient = LocalUserView::read_person(&&context.pool.get().await?, recipient_id)?; send_email_to_user( &local_recipient, "Private Message from", diff --git a/crates/api_crud/src/private_message/delete.rs b/crates/api_crud/src/private_message/delete.rs index 6cd2b44f2..58c3a98f8 100644 --- a/crates/api_crud/src/private_message/delete.rs +++ b/crates/api_crud/src/private_message/delete.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, get_local_user_view_from_jwt, person::{DeletePrivateMessage, PrivateMessageResponse}, }; @@ -28,10 +27,8 @@ impl PerformCrud for DeletePrivateMessage { // Checking permissions let private_message_id = data.private_message_id; - let orig_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::read(conn, private_message_id) - }) - .await??; + let orig_private_message = + PrivateMessage::read(&&context.pool.get().await?, private_message_id)?; if local_user_view.person.id != orig_private_message.creator_id { return Err(ApiError::err("no_private_message_edit_allowed").into()); } @@ -39,11 +36,9 @@ impl PerformCrud for DeletePrivateMessage { // Doing the update let private_message_id = data.private_message_id; let deleted = data.deleted; - let updated_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::update_deleted(conn, private_message_id, deleted) - }) - .await? - .map_err(|_| ApiError::err("couldnt_update_private_message"))?; + let updated_private_message = + PrivateMessage::update_deleted(&&context.pool.get().await?, private_message_id, deleted) + .map_err(|_| ApiError::err("couldnt_update_private_message"))?; // Send the apub update if data.deleted { diff --git a/crates/api_crud/src/private_message/read.rs b/crates/api_crud/src/private_message/read.rs index 3acbaa392..55bc77bc1 100644 --- a/crates/api_crud/src/private_message/read.rs +++ b/crates/api_crud/src/private_message/read.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, get_local_user_view_from_jwt, person::{GetPrivateMessages, PrivateMessagesResponse}, }; @@ -26,14 +25,11 @@ impl PerformCrud for GetPrivateMessages { let page = data.page; let limit = data.limit; let unread_only = data.unread_only; - let mut messages = blocking(context.pool(), move |conn| { - PrivateMessageQueryBuilder::create(conn, person_id) - .page(page) - .limit(limit) - .unread_only(unread_only) - .list() - }) - .await??; + let mut messages = PrivateMessageQueryBuilder::create(&&context.pool.get().await?, person_id) + .page(page) + .limit(limit) + .unread_only(unread_only) + .list()?; // Blank out deleted or removed info for pmv in messages diff --git a/crates/api_crud/src/private_message/update.rs b/crates/api_crud/src/private_message/update.rs index 72ca4fbbf..12f127f7f 100644 --- a/crates/api_crud/src/private_message/update.rs +++ b/crates/api_crud/src/private_message/update.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, get_local_user_view_from_jwt, person::{EditPrivateMessage, PrivateMessageResponse}, }; @@ -28,10 +27,8 @@ impl PerformCrud for EditPrivateMessage { // Checking permissions let private_message_id = data.private_message_id; - let orig_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::read(conn, private_message_id) - }) - .await??; + let orig_private_message = + PrivateMessage::read(&&context.pool.get().await?, private_message_id)?; if local_user_view.person.id != orig_private_message.creator_id { return Err(ApiError::err("no_private_message_edit_allowed").into()); } @@ -39,10 +36,11 @@ impl PerformCrud for EditPrivateMessage { // Doing the update let content_slurs_removed = remove_slurs(&data.content); let private_message_id = data.private_message_id; - let updated_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed) - }) - .await? + let updated_private_message = PrivateMessage::update_content( + &&context.pool.get().await?, + private_message_id, + &content_slurs_removed, + ) .map_err(|_| ApiError::err("couldnt_update_private_message"))?; // Send the apub update diff --git a/crates/api_crud/src/site/create.rs b/crates/api_crud/src/site/create.rs index b84adcdb4..015068752 100644 --- a/crates/api_crud/src/site/create.rs +++ b/crates/api_crud/src/site/create.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, get_local_user_view_from_jwt, is_admin, site::*, @@ -34,8 +33,8 @@ impl PerformCrud for CreateSite { ) -> Result { let data: &CreateSite = self; - let read_site = move |conn: &'_ _| Site::read_simple(conn); - if blocking(context.pool(), read_site).await?.is_ok() { + let read_site = Site::read_simple(&&context.pool.get().await?); + if read_site.is_ok() { return Err(ApiError::err("site_already_exists").into()); }; @@ -70,12 +69,12 @@ impl PerformCrud for CreateSite { community_creation_admin_only: data.community_creation_admin_only, }; - let create_site = move |conn: &'_ _| Site::create(conn, &site_form); - if blocking(context.pool(), create_site).await?.is_err() { + let create_site = Site::create(&&context.pool.get().await?, &site_form); + if create_site.is_err() { return Err(ApiError::err("site_already_exists").into()); } - let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; + let site_view = SiteView::read(&&context.pool.get().await?)?; Ok(SiteResponse { site_view }) } diff --git a/crates/api_crud/src/site/read.rs b/crates/api_crud/src/site/read.rs index cfbaf07a5..876311825 100644 --- a/crates/api_crud/src/site/read.rs +++ b/crates/api_crud/src/site/read.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, build_federated_instances, get_local_user_settings_view_from_jwt_opt, person::Register, @@ -30,7 +29,7 @@ impl PerformCrud for GetSite { ) -> Result { let data: &GetSite = self; - let site_view = match blocking(context.pool(), move |conn| SiteView::read(conn)).await? { + let site_view = match SiteView::read(&&context.pool.get().await?) { Ok(site_view) => Some(site_view), // If the site isn't created yet, check the setup Err(_) => { @@ -61,14 +60,14 @@ impl PerformCrud for GetSite { }; create_site.perform(context, websocket_id).await?; info!("Site {} created", setup.site_name); - Some(blocking(context.pool(), move |conn| SiteView::read(conn)).await??) + Some(SiteView::read(&&context.pool.get().await?)?) } else { None } } }; - let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; + let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?; // Make sure the site creator is the top admin if let Some(site_view) = site_view.to_owned() { @@ -81,7 +80,7 @@ impl PerformCrud for GetSite { } } - let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??; + let banned = PersonViewSafe::banned(&&context.pool.get().await?)?; let online = context .chat_server() @@ -94,31 +93,19 @@ impl PerformCrud for GetSite { get_local_user_settings_view_from_jwt_opt(&data.auth, context.pool()).await? { let person_id = local_user_view.person.id; - let follows = blocking(context.pool(), move |conn| { - CommunityFollowerView::for_person(conn, person_id) - }) - .await? - .map_err(|_| ApiError::err("system_err_login"))?; + let follows = CommunityFollowerView::for_person(&&context.pool.get().await?, person_id) + .map_err(|_| ApiError::err("system_err_login"))?; let person_id = local_user_view.person.id; - let community_blocks = blocking(context.pool(), move |conn| { - CommunityBlockView::for_person(conn, person_id) - }) - .await? - .map_err(|_| ApiError::err("system_err_login"))?; + let community_blocks = CommunityBlockView::for_person(&&context.pool.get().await?, person_id) + .map_err(|_| ApiError::err("system_err_login"))?; let person_id = local_user_view.person.id; - let person_blocks = blocking(context.pool(), move |conn| { - PersonBlockView::for_person(conn, person_id) - }) - .await? - .map_err(|_| ApiError::err("system_err_login"))?; + let person_blocks = PersonBlockView::for_person(&&context.pool.get().await?, person_id) + .map_err(|_| ApiError::err("system_err_login"))?; - let moderates = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_person(conn, person_id) - }) - .await? - .map_err(|_| ApiError::err("system_err_login"))?; + let moderates = CommunityModeratorView::for_person(&&context.pool.get().await?, person_id) + .map_err(|_| ApiError::err("system_err_login"))?; Some(MyUserInfo { local_user_view, diff --git a/crates/api_crud/src/site/update.rs b/crates/api_crud/src/site/update.rs index 781ea0081..a1d3f79c0 100644 --- a/crates/api_crud/src/site/update.rs +++ b/crates/api_crud/src/site/update.rs @@ -1,7 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; use lemmy_api_common::{ - blocking, get_local_user_view_from_jwt, is_admin, site::{EditSite, SiteResponse}, @@ -38,7 +37,7 @@ impl PerformCrud for EditSite { // Make sure user is an admin is_admin(&local_user_view)?; - let found_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??; + let found_site = Site::read_simple(&&context.pool.get().await?)?; let sidebar = diesel_option_overwrite(&data.sidebar); let description = diesel_option_overwrite(&data.description); @@ -63,12 +62,12 @@ impl PerformCrud for EditSite { community_creation_admin_only: data.community_creation_admin_only, }; - let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form); - if blocking(context.pool(), update_site).await?.is_err() { + let update_site = Site::update(&&context.pool.get().await?, 1, &site_form); + if update_site.is_err() { return Err(ApiError::err("couldnt_update_site").into()); } - let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; + let site_view = SiteView::read(&&context.pool.get().await?)?; let res = SiteResponse { site_view }; diff --git a/crates/api_crud/src/user/create.rs b/crates/api_crud/src/user/create.rs index 6f9216b36..12aed9947 100644 --- a/crates/api_crud/src/user/create.rs +++ b/crates/api_crud/src/user/create.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, password_length_check, person::*}; +use lemmy_api_common::{password_length_check, person::*}; use lemmy_apub::{ generate_apub_endpoint, generate_followers_url, @@ -49,7 +49,7 @@ impl PerformCrud for Register { let data: &Register = self; // Make sure site has open registration - if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? { + if let Ok(site) = Site::read_simple(&&context.pool.get().await?) { if !site.open_registration { return Err(ApiError::err("registration_closed").into()); } @@ -63,10 +63,7 @@ impl PerformCrud for Register { } // Check if there are admins. False if admins exist - let no_admins = blocking(context.pool(), move |conn| { - PersonViewSafe::admins(conn).map(|a| a.is_empty()) - }) - .await??; + let no_admins = PersonViewSafe::admins(&&context.pool.get().await?).map(|a| a.is_empty())?; // If its not the admin, check the captcha if !no_admins && Settings::get().captcha.enabled { @@ -111,11 +108,8 @@ impl PerformCrud for Register { }; // insert the person - let inserted_person = blocking(context.pool(), move |conn| { - Person::create(conn, &person_form) - }) - .await? - .map_err(|_| ApiError::err("user_already_exists"))?; + let inserted_person = Person::create(&&context.pool.get().await?, &person_form) + .map_err(|_| ApiError::err("user_already_exists"))?; // Create the local user // TODO some of these could probably use the DB defaults @@ -136,39 +130,29 @@ impl PerformCrud for Register { send_notifications_to_email: Some(false), }; - let inserted_local_user = match blocking(context.pool(), move |conn| { - LocalUser::register(conn, &local_user_form) - }) - .await? - { - Ok(lu) => lu, - Err(e) => { - let err_type = if e.to_string() - == "duplicate key value violates unique constraint \"local_user_email_key\"" - { - "email_already_exists" - } else { - "user_already_exists" - }; + let inserted_local_user = + match LocalUser::register(&&context.pool.get().await?, &local_user_form) { + Ok(lu) => lu, + Err(e) => { + let err_type = if e.to_string() + == "duplicate key value violates unique constraint \"local_user_email_key\"" + { + "email_already_exists" + } else { + "user_already_exists" + }; - // If the local user creation errored, then delete that person - blocking(context.pool(), move |conn| { - Person::delete(conn, inserted_person.id) - }) - .await??; + // If the local user creation errored, then delete that person + Person::delete(&&context.pool.get().await?, inserted_person.id)?; - return Err(ApiError::err(err_type).into()); - } - }; + return Err(ApiError::err(err_type).into()); + } + }; let main_community_keypair = generate_actor_keypair()?; // Create the main community if it doesn't exist - let main_community = match blocking(context.pool(), move |conn| { - Community::read(conn, CommunityId(2)) - }) - .await? - { + let main_community = match Community::read(&&context.pool.get().await?, CommunityId(2)) { Ok(c) => c, Err(_e) => { let default_community_name = "main"; @@ -185,10 +169,7 @@ impl PerformCrud for Register { shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)), ..CommunityForm::default() }; - blocking(context.pool(), move |conn| { - Community::create(conn, &community_form) - }) - .await?? + Community::create(&&context.pool.get().await?, &community_form)? } }; @@ -199,8 +180,8 @@ impl PerformCrud for Register { pending: false, }; - let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); - if blocking(context.pool(), follow).await?.is_err() { + let follow = CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form); + if follow.is_err() { return Err(ApiError::err("community_follower_already_exists").into()); }; @@ -211,8 +192,8 @@ impl PerformCrud for Register { person_id: inserted_person.id, }; - let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); - if blocking(context.pool(), join).await?.is_err() { + let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form); + if join.is_err() { return Err(ApiError::err("community_moderator_already_exists").into()); } } diff --git a/crates/api_crud/src/user/delete.rs b/crates/api_crud/src/user/delete.rs index fb9480dc7..238995d14 100644 --- a/crates/api_crud/src/user/delete.rs +++ b/crates/api_crud/src/user/delete.rs @@ -1,7 +1,7 @@ use crate::PerformCrud; use actix_web::web::Data; use bcrypt::verify; -use lemmy_api_common::{blocking, get_local_user_view_from_jwt, person::*}; +use lemmy_api_common::{get_local_user_view_from_jwt, person::*}; use lemmy_db_queries::source::{comment::Comment_, person::Person_, post::Post_}; use lemmy_db_schema::source::{comment::Comment, person::*, post::Post}; use lemmy_utils::{ApiError, ConnectionId, LemmyError}; @@ -31,21 +31,18 @@ impl PerformCrud for DeleteAccount { // Comments let person_id = local_user_view.person.id; - let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id); - if blocking(context.pool(), permadelete).await?.is_err() { + let permadelete = Comment::permadelete_for_creator(&&context.pool.get().await?, person_id); + if permadelete.is_err() { return Err(ApiError::err("couldnt_update_comment").into()); } // Posts - let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id); - if blocking(context.pool(), permadelete).await?.is_err() { + let permadelete = Post::permadelete_for_creator(&&context.pool.get().await?, person_id); + if permadelete.is_err() { return Err(ApiError::err("couldnt_update_post").into()); } - blocking(context.pool(), move |conn| { - Person::delete_account(conn, person_id) - }) - .await??; + Person::delete_account(&&context.pool.get().await?, person_id)?; Ok(LoginResponse { jwt: data.auth.to_owned(), diff --git a/crates/api_crud/src/user/read.rs b/crates/api_crud/src/user/read.rs index 4cfd90ab5..673b89e42 100644 --- a/crates/api_crud/src/user/read.rs +++ b/crates/api_crud/src/user/read.rs @@ -1,6 +1,6 @@ use crate::PerformCrud; use actix_web::web::Data; -use lemmy_api_common::{blocking, get_local_user_view_from_jwt_opt, person::*}; +use lemmy_api_common::{get_local_user_view_from_jwt_opt, person::*}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_db_queries::{from_opt_str_to_opt_enum, ApubObject, SortType}; use lemmy_db_schema::source::person::*; @@ -43,31 +43,24 @@ impl PerformCrud for GetPersonDetails { .unwrap_or_else(|| "admin".to_string()); let actor_id = build_actor_id_from_shortname(EndpointType::Person, &name)?; - let person = blocking(context.pool(), move |conn| { - Person::read_from_apub_id(conn, &actor_id) - }) - .await?; - person - .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))? - .id + let person = Person::read_from_apub_id(&&context.pool.get().await?, &actor_id) + .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?; + person.id } }; let person_id = local_user_view.map(|uv| uv.person.id); // You don't need to return settings for the user, since this comes back with GetSite - // `my_user` - let person_view = blocking(context.pool(), move |conn| { - PersonViewSafe::read(conn, person_details_id) - }) - .await??; + let person_view = PersonViewSafe::read(&&context.pool.get().await?, person_details_id)?; let page = data.page; let limit = data.limit; let saved_only = data.saved_only; let community_id = data.community_id; - let (posts, comments) = blocking(context.pool(), move |conn| { + let (posts, comments) = { + let conn = &&context.pool.get().await?; let mut posts_query = PostQueryBuilder::create(conn) .sort(sort) .show_nsfw(show_nsfw) @@ -79,7 +72,8 @@ impl PerformCrud for GetPersonDetails { .page(page) .limit(limit); - let mut comments_query = CommentQueryBuilder::create(conn) + let conn2 = &&context.pool.get().await?; + let mut comments_query = CommentQueryBuilder::create(conn2) .my_person_id(person_id) .show_bot_accounts(show_bot_accounts) .sort(sort) @@ -98,14 +92,11 @@ impl PerformCrud for GetPersonDetails { let posts = posts_query.list()?; let comments = comments_query.list()?; - Ok((posts, comments)) as Result<_, LemmyError> - }) - .await??; + (posts, comments) + }; - let moderates = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_person(conn, person_details_id) - }) - .await??; + let moderates = + CommunityModeratorView::for_person(&&context.pool.get().await?, person_details_id)?; // Return the jwt Ok(GetPersonDetailsResponse { diff --git a/crates/apub/src/activities/comment/create_or_update.rs b/crates/apub/src/activities/comment/create_or_update.rs index 7f83d78fa..54fceddbe 100644 --- a/crates/apub/src/activities/comment/create_or_update.rs +++ b/crates/apub/src/activities/comment/create_or_update.rs @@ -14,7 +14,6 @@ use crate::{ ActorType, }; use activitystreams::{base::AnyBase, link::Mention, primitives::OneOrMany, unparsed::Unparsed}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, verify_domains_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::Crud; use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post}; @@ -49,12 +48,9 @@ impl CreateOrUpdateComment { ) -> Result<(), LemmyError> { // TODO: might be helpful to add a comment method to retrieve community directly let post_id = comment.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; let community_id = post.community_id; - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; let id = generate_activity_id(kind.clone())?; let maa = collect_non_local_mentions(comment, &community, context).await?; diff --git a/crates/apub/src/activities/comment/mod.rs b/crates/apub/src/activities/comment/mod.rs index 228a5f804..4323262ad 100644 --- a/crates/apub/src/activities/comment/mod.rs +++ b/crates/apub/src/activities/comment/mod.rs @@ -5,7 +5,7 @@ use activitystreams::{ }; use anyhow::anyhow; use itertools::Itertools; -use lemmy_api_common::{blocking, send_local_notifs, WebFingerResponse}; +use lemmy_api_common::{send_local_notifs, WebFingerResponse}; use lemmy_db_queries::{Crud, DbPool}; use lemmy_db_schema::{ source::{comment::Comment, community::Community, person::Person, post::Post}, @@ -31,7 +31,7 @@ async fn get_notif_recipients( request_counter: &mut i32, ) -> Result, LemmyError> { let post_id = comment.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; let actor = get_or_fetch_and_upsert_person(actor, context, request_counter).await?; // Note: @@ -103,15 +103,14 @@ async fn get_comment_parent_creator( comment: &Comment, ) -> Result { let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id { - let parent_comment = - blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??; + let parent_comment = Comment::read(&&pool.get().await?, parent_comment_id)?; parent_comment.creator_id } else { let parent_post_id = comment.post_id; - let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??; + let parent_post = Post::read(&&pool.get().await?, parent_post_id)?; parent_post.creator_id }; - Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??) + Ok(Person::read(&&pool.get().await?, parent_creator_id)?) } /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`, diff --git a/crates/apub/src/activities/community/add_mod.rs b/crates/apub/src/activities/community/add_mod.rs index f83f14630..19eebb96d 100644 --- a/crates/apub/src/activities/community/add_mod.rs +++ b/crates/apub/src/activities/community/add_mod.rs @@ -19,7 +19,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::{source::community::CommunityModerator_, Joinable}; use lemmy_db_schema::source::{ @@ -100,19 +99,16 @@ impl ActivityHandler for AddMod { // If we had to refetch the community while parsing the activity, then the new mod has already // been added. Skip it here as it would result in a duplicate key error. let new_mod_id = new_mod.id; - let moderated_communities = blocking(context.pool(), move |conn| { - CommunityModerator::get_person_moderated_communities(conn, new_mod_id) - }) - .await??; + let moderated_communities = CommunityModerator::get_person_moderated_communities( + &&context.pool.get().await?, + new_mod_id, + )?; if !moderated_communities.contains(&community.id) { let form = CommunityModeratorForm { community_id: community.id, person_id: new_mod.id, }; - blocking(context.pool(), move |conn| { - CommunityModerator::join(conn, &form) - }) - .await??; + CommunityModerator::join(&&context.pool.get().await?, &form)?; } // TODO: send websocket notification about added mod Ok(()) diff --git a/crates/apub/src/activities/community/block_user.rs b/crates/apub/src/activities/community/block_user.rs index d31077dfa..e36c0d4e0 100644 --- a/crates/apub/src/activities/community/block_user.rs +++ b/crates/apub/src/activities/community/block_user.rs @@ -17,7 +17,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::{Bannable, Followable}; use lemmy_db_schema::source::{ @@ -112,10 +111,7 @@ impl ActivityHandler for BlockUserFromCommunity { person_id: blocked_user.id, }; - blocking(context.pool(), move |conn: &'_ _| { - CommunityPersonBan::ban(conn, &community_user_ban_form) - }) - .await??; + CommunityPersonBan::ban(&&context.pool.get().await?, &community_user_ban_form)?; // Also unsubscribe them from the community, if they are subscribed let community_follower_form = CommunityFollowerForm { @@ -123,11 +119,7 @@ impl ActivityHandler for BlockUserFromCommunity { person_id: blocked_user.id, pending: false, }; - blocking(context.pool(), move |conn: &'_ _| { - CommunityFollower::unfollow(conn, &community_follower_form) - }) - .await? - .ok(); + CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok(); Ok(()) } diff --git a/crates/apub/src/activities/community/remove_mod.rs b/crates/apub/src/activities/community/remove_mod.rs index 2d4eba56a..a89fe01e2 100644 --- a/crates/apub/src/activities/community/remove_mod.rs +++ b/crates/apub/src/activities/community/remove_mod.rs @@ -20,7 +20,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::Joinable; use lemmy_db_schema::source::{ @@ -117,10 +116,7 @@ impl ActivityHandler for RemoveMod { community_id: community.id, person_id: remove_mod.id, }; - blocking(context.pool(), move |conn| { - CommunityModerator::leave(conn, &form) - }) - .await??; + CommunityModerator::leave(&&context.pool.get().await?, &form)?; // TODO: send websocket notification about removed mod Ok(()) } else { diff --git a/crates/apub/src/activities/community/undo_block_user.rs b/crates/apub/src/activities/community/undo_block_user.rs index 0a9665af5..237e34968 100644 --- a/crates/apub/src/activities/community/undo_block_user.rs +++ b/crates/apub/src/activities/community/undo_block_user.rs @@ -17,7 +17,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::Bannable; use lemmy_db_schema::source::{ @@ -101,10 +100,7 @@ impl ActivityHandler for UndoBlockUserFromCommunity { person_id: blocked_user.id, }; - blocking(context.pool(), move |conn: &'_ _| { - CommunityPersonBan::unban(conn, &community_user_ban_form) - }) - .await??; + CommunityPersonBan::unban(&&context.pool.get().await?, &community_user_ban_form)?; Ok(()) } diff --git a/crates/apub/src/activities/community/update.rs b/crates/apub/src/activities/community/update.rs index 7539464da..2d778b18a 100644 --- a/crates/apub/src/activities/community/update.rs +++ b/crates/apub/src/activities/community/update.rs @@ -17,7 +17,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::{ApubObject, Crud}; use lemmy_db_schema::source::{ @@ -90,10 +89,7 @@ impl ActivityHandler for UpdateCommunity { _request_counter: &mut i32, ) -> Result<(), LemmyError> { let cc = self.cc[0].clone().into(); - let community = blocking(context.pool(), move |conn| { - Community::read_from_apub_id(conn, &cc) - }) - .await??; + let community = Community::read_from_apub_id(&&context.pool.get().await?, &cc)?; let updated_community = Group::from_apub_to_form(&self.object, &community.actor_id.clone().into()).await?; @@ -107,10 +103,7 @@ impl ActivityHandler for UpdateCommunity { banner: updated_community.banner, ..CommunityForm::default() }; - let updated_community = blocking(context.pool(), move |conn| { - Community::update(conn, community.id, &cf) - }) - .await??; + let updated_community = Community::update(&&context.pool.get().await?, community.id, &cf)?; send_community_ws_message( updated_community.id, diff --git a/crates/apub/src/activities/deletion/delete.rs b/crates/apub/src/activities/deletion/delete.rs index 455672882..fb3c9eb6c 100644 --- a/crates/apub/src/activities/deletion/delete.rs +++ b/crates/apub/src/activities/deletion/delete.rs @@ -22,7 +22,6 @@ use activitystreams::{ unparsed::Unparsed, }; use anyhow::anyhow; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::{ source::{comment::Comment_, community::Community_, post::Post_}, @@ -185,14 +184,9 @@ pub(in crate::activities) async fn receive_remove_action( reason, expires: None, }; - blocking(context.pool(), move |conn| { - ModRemoveCommunity::create(conn, &form) - }) - .await??; - let deleted_community = blocking(context.pool(), move |conn| { - Community::update_removed(conn, community.id, true) - }) - .await??; + ModRemoveCommunity::create(&&context.pool.get().await?, &form)?; + let deleted_community = + Community::update_removed(&&context.pool.get().await?, community.id, true)?; send_community_ws_message(deleted_community.id, RemoveCommunity, None, None, context).await?; } @@ -203,14 +197,8 @@ pub(in crate::activities) async fn receive_remove_action( removed: Some(true), reason, }; - blocking(context.pool(), move |conn| { - ModRemovePost::create(conn, &form) - }) - .await??; - let removed_post = blocking(context.pool(), move |conn| { - Post::update_removed(conn, post.id, true) - }) - .await??; + ModRemovePost::create(&&context.pool.get().await?, &form)?; + let removed_post = Post::update_removed(&&context.pool.get().await?, post.id, true)?; send_post_ws_message(removed_post.id, RemovePost, None, None, context).await?; } @@ -221,14 +209,8 @@ pub(in crate::activities) async fn receive_remove_action( removed: Some(true), reason, }; - blocking(context.pool(), move |conn| { - ModRemoveComment::create(conn, &form) - }) - .await??; - let removed_comment = blocking(context.pool(), move |conn| { - Comment::update_removed(conn, comment.id, true) - }) - .await??; + ModRemoveComment::create(&&context.pool.get().await?, &form)?; + let removed_comment = Comment::update_removed(&&context.pool.get().await?, comment.id, true)?; send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?; } diff --git a/crates/apub/src/activities/deletion/mod.rs b/crates/apub/src/activities/deletion/mod.rs index 350773f42..24462819f 100644 --- a/crates/apub/src/activities/deletion/mod.rs +++ b/crates/apub/src/activities/deletion/mod.rs @@ -7,7 +7,6 @@ use crate::{ fetcher::person::get_or_fetch_and_upsert_person, ActorType, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_domains_match, ActivityFields}; use lemmy_db_queries::{ source::{comment::Comment_, community::Community_, post::Post_}, @@ -89,10 +88,7 @@ impl DeletableObjects { ap_id: DbUrl, context: &LemmyContext, ) -> Result, LemmyError> { - blocking(context.pool(), move |conn| { - Type::read_from_apub_id(conn, &ap_id).ok() - }) - .await + Ok(Type::read_from_apub_id(&&context.pool.get().await?, &ap_id).ok()) } } @@ -185,24 +181,17 @@ async fn receive_delete_action( send_apub_delete(&mod_, &community.clone(), object, true, context).await?; } - let community = blocking(context.pool(), move |conn| { - Community::update_deleted(conn, community.id, deleted) - }) - .await??; + let community = + Community::update_deleted(&&context.pool.get().await?, community.id, deleted)?; send_community_ws_message(community.id, ws_messages.community, None, None, context).await?; } DeletableObjects::Post(post) => { - let deleted_post = blocking(context.pool(), move |conn| { - Post::update_deleted(conn, post.id, deleted) - }) - .await??; + let deleted_post = Post::update_deleted(&&context.pool.get().await?, post.id, deleted)?; send_post_ws_message(deleted_post.id, ws_messages.post, None, None, context).await?; } DeletableObjects::Comment(comment) => { - let deleted_comment = blocking(context.pool(), move |conn| { - Comment::update_deleted(conn, comment.id, deleted) - }) - .await??; + let deleted_comment = + Comment::update_deleted(&&context.pool.get().await?, comment.id, deleted)?; send_comment_ws_message_simple(deleted_comment.id, ws_messages.comment, context).await?; } } diff --git a/crates/apub/src/activities/deletion/undo_delete.rs b/crates/apub/src/activities/deletion/undo_delete.rs index 35369d441..e7964da34 100644 --- a/crates/apub/src/activities/deletion/undo_delete.rs +++ b/crates/apub/src/activities/deletion/undo_delete.rs @@ -22,7 +22,6 @@ use activitystreams::{ unparsed::Unparsed, }; use anyhow::anyhow; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::source::{comment::Comment_, community::Community_, post::Post_}; use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post}; @@ -133,24 +132,17 @@ impl UndoDelete { if community.local { return Err(anyhow!("Only local admin can restore community").into()); } - let deleted_community = blocking(context.pool(), move |conn| { - Community::update_removed(conn, community.id, false) - }) - .await??; + let deleted_community = + Community::update_removed(&&context.pool.get().await?, community.id, false)?; send_community_ws_message(deleted_community.id, EditCommunity, None, None, context).await?; } DeletableObjects::Post(post) => { - let removed_post = blocking(context.pool(), move |conn| { - Post::update_removed(conn, post.id, false) - }) - .await??; + let removed_post = Post::update_removed(&&context.pool.get().await?, post.id, false)?; send_post_ws_message(removed_post.id, EditPost, None, None, context).await?; } DeletableObjects::Comment(comment) => { - let removed_comment = blocking(context.pool(), move |conn| { - Comment::update_removed(conn, comment.id, false) - }) - .await??; + let removed_comment = + Comment::update_removed(&&context.pool.get().await?, comment.id, false)?; send_comment_ws_message_simple(removed_comment.id, EditComment, context).await?; } } diff --git a/crates/apub/src/activities/following/accept.rs b/crates/apub/src/activities/following/accept.rs index c76263cc0..8cfffee8a 100644 --- a/crates/apub/src/activities/following/accept.rs +++ b/crates/apub/src/activities/following/accept.rs @@ -16,7 +16,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::{ApubObject, Followable}; use lemmy_db_schema::source::{ @@ -46,15 +45,10 @@ pub struct AcceptFollowCommunity { impl AcceptFollowCommunity { pub async fn send(follow: FollowCommunity, context: &LemmyContext) -> Result<(), LemmyError> { let community_id = follow.object.clone(); - let community = blocking(context.pool(), move |conn| { - Community::read_from_apub_id(conn, &community_id.into()) - }) - .await??; + let community = + Community::read_from_apub_id(&&context.pool.get().await?, &community_id.into())?; let person_id = follow.actor().clone(); - let person = blocking(context.pool(), move |conn| { - Person::read_from_apub_id(conn, &person_id.into()) - }) - .await??; + let person = Person::read_from_apub_id(&&context.pool.get().await?, &person_id.into())?; let accept = AcceptFollowCommunity { actor: community.actor_id(), @@ -93,10 +87,7 @@ impl ActivityHandler for AcceptFollowCommunity { let actor = get_or_fetch_and_upsert_community(&self.actor, context, request_counter).await?; let to = get_or_fetch_and_upsert_person(&self.to, context, request_counter).await?; // This will throw an error if no follow was requested - blocking(context.pool(), move |conn| { - CommunityFollower::follow_accepted(conn, actor.id, to.id) - }) - .await??; + CommunityFollower::follow_accepted(&&context.pool.get().await?, actor.id, to.id)?; Ok(()) } diff --git a/crates/apub/src/activities/following/follow.rs b/crates/apub/src/activities/following/follow.rs index e6ca747a0..b956708a7 100644 --- a/crates/apub/src/activities/following/follow.rs +++ b/crates/apub/src/activities/following/follow.rs @@ -16,7 +16,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::Followable; use lemmy_db_schema::source::{ @@ -68,10 +67,7 @@ impl FollowCommunity { person_id: actor.id, pending: true, }; - blocking(context.pool(), move |conn| { - CommunityFollower::follow(conn, &community_follower_form).ok() - }) - .await?; + CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form).ok(); let follow = FollowCommunity::new(actor, community)?; let inbox = vec![community.inbox_url.clone().into()]; @@ -107,10 +103,7 @@ impl ActivityHandler for FollowCommunity { }; // This will fail if they're already a follower, but ignore the error. - blocking(context.pool(), move |conn| { - CommunityFollower::follow(conn, &community_follower_form).ok() - }) - .await?; + CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form).ok(); AcceptFollowCommunity::send(self, context).await } diff --git a/crates/apub/src/activities/following/undo.rs b/crates/apub/src/activities/following/undo.rs index 092036bb4..94f53f52c 100644 --- a/crates/apub/src/activities/following/undo.rs +++ b/crates/apub/src/activities/following/undo.rs @@ -16,7 +16,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::Followable; use lemmy_db_schema::source::{ @@ -94,10 +93,7 @@ impl ActivityHandler for UndoFollowCommunity { }; // This will fail if they aren't a follower, but ignore the error. - blocking(context.pool(), move |conn| { - CommunityFollower::unfollow(conn, &community_follower_form).ok() - }) - .await?; + CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok(); Ok(()) } } diff --git a/crates/apub/src/activities/mod.rs b/crates/apub/src/activities/mod.rs index a846a0e70..c0c467bb3 100644 --- a/crates/apub/src/activities/mod.rs +++ b/crates/apub/src/activities/mod.rs @@ -5,7 +5,6 @@ use crate::{ generate_moderators_url, }; use anyhow::anyhow; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_domains_match, ActivityFields}; use lemmy_db_queries::ApubObject; use lemmy_db_schema::{ @@ -104,26 +103,18 @@ pub(crate) async fn verify_mod_action( community: Url, context: &LemmyContext, ) -> Result<(), LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read_from_apub_id(conn, &community.into()) - }) - .await??; + let community = Community::read_from_apub_id(&&context.pool.get().await?, &community.into())?; if community.local { let actor_id: DbUrl = actor_id.clone().into(); - let actor = blocking(context.pool(), move |conn| { - Person::read_from_apub_id(conn, &actor_id) - }) - .await??; + let actor = Person::read_from_apub_id(&&context.pool.get().await?, &actor_id)?; // Note: this will also return true for admins in addition to mods, but as we dont know about // remote admins, it doesnt make any difference. let community_id = community.id; let actor_id = actor.id; - let is_mod_or_admin = blocking(context.pool(), move |conn| { - CommunityView::is_mod_or_admin(conn, actor_id, community_id) - }) - .await?; + let is_mod_or_admin = + CommunityView::is_mod_or_admin(&&context.pool.get().await?, actor_id, community_id); if !is_mod_or_admin { return Err(anyhow!("Not a mod").into()); } diff --git a/crates/apub/src/activities/post/create_or_update.rs b/crates/apub/src/activities/post/create_or_update.rs index c1b0703db..b953749d8 100644 --- a/crates/apub/src/activities/post/create_or_update.rs +++ b/crates/apub/src/activities/post/create_or_update.rs @@ -16,7 +16,6 @@ use crate::{ }; use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed}; use anyhow::anyhow; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ values::PublicUrl, verify_domains_match, @@ -55,10 +54,7 @@ impl CreateOrUpdatePost { context: &LemmyContext, ) -> Result<(), LemmyError> { let community_id = post.community_id; - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; let id = generate_activity_id(kind.clone())?; let create_or_update = CreateOrUpdatePost { diff --git a/crates/apub/src/activities/private_message/create_or_update.rs b/crates/apub/src/activities/private_message/create_or_update.rs index 98a26d806..4b64151cd 100644 --- a/crates/apub/src/activities/private_message/create_or_update.rs +++ b/crates/apub/src/activities/private_message/create_or_update.rs @@ -6,7 +6,6 @@ use crate::{ ActorType, }; use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_domains_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::Crud; use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; @@ -39,8 +38,7 @@ impl CreateOrUpdatePrivateMessage { context: &LemmyContext, ) -> Result<(), LemmyError> { let recipient_id = private_message.recipient_id; - let recipient = - blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = Person::read(&&context.pool.get().await?, recipient_id)?; let id = generate_activity_id(kind.clone())?; let create_or_update = CreateOrUpdatePrivateMessage { diff --git a/crates/apub/src/activities/private_message/delete.rs b/crates/apub/src/activities/private_message/delete.rs index 47e1a71a1..ff9475bc9 100644 --- a/crates/apub/src/activities/private_message/delete.rs +++ b/crates/apub/src/activities/private_message/delete.rs @@ -10,7 +10,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_domains_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::{source::private_message::PrivateMessage_, ApubObject, Crud}; use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; @@ -58,8 +57,7 @@ impl DeletePrivateMessage { let delete_id = delete.id.clone(); let recipient_id = pm.recipient_id; - let recipient = - blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = Person::read(&&context.pool.get().await?, recipient_id)?; let inbox = vec![recipient.get_shared_inbox_or_inbox_url()]; send_activity_new(context, &delete, &delete_id, actor, inbox, true).await } @@ -84,14 +82,10 @@ impl ActivityHandler for DeletePrivateMessage { _request_counter: &mut i32, ) -> Result<(), LemmyError> { let ap_id = self.object.clone(); - let private_message = blocking(context.pool(), move |conn| { - PrivateMessage::read_from_apub_id(conn, &ap_id.into()) - }) - .await??; - let deleted_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::update_deleted(conn, private_message.id, true) - }) - .await??; + let private_message = + PrivateMessage::read_from_apub_id(&&context.pool.get().await?, &ap_id.into())?; + let deleted_private_message = + PrivateMessage::update_deleted(&&context.pool.get().await?, private_message.id, true)?; send_pm_ws_message( deleted_private_message.id, diff --git a/crates/apub/src/activities/private_message/undo_delete.rs b/crates/apub/src/activities/private_message/undo_delete.rs index 911a17c79..0e741991d 100644 --- a/crates/apub/src/activities/private_message/undo_delete.rs +++ b/crates/apub/src/activities/private_message/undo_delete.rs @@ -15,7 +15,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{verify_domains_match, verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::{source::private_message::PrivateMessage_, ApubObject, Crud}; use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; @@ -46,8 +45,7 @@ impl UndoDeletePrivateMessage { context: &LemmyContext, ) -> Result<(), LemmyError> { let recipient_id = pm.recipient_id; - let recipient = - blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; + let recipient = Person::read(&&context.pool.get().await?, recipient_id)?; let object = DeletePrivateMessage::new(actor, pm)?; let id = generate_activity_id(UndoType::Undo)?; @@ -86,15 +84,11 @@ impl ActivityHandler for UndoDeletePrivateMessage { _request_counter: &mut i32, ) -> Result<(), LemmyError> { let ap_id = self.object.object.clone(); - let private_message = blocking(context.pool(), move |conn| { - PrivateMessage::read_from_apub_id(conn, &ap_id.into()) - }) - .await??; + let private_message = + PrivateMessage::read_from_apub_id(&&context.pool.get().await?, &ap_id.into())?; - let deleted_private_message = blocking(context.pool(), move |conn| { - PrivateMessage::update_deleted(conn, private_message.id, false) - }) - .await??; + let deleted_private_message = + PrivateMessage::update_deleted(&&context.pool.get().await?, private_message.id, false)?; send_pm_ws_message( deleted_private_message.id, diff --git a/crates/apub/src/activities/send/community.rs b/crates/apub/src/activities/send/community.rs index 29aa9dba8..8d0a8bb94 100644 --- a/crates/apub/src/activities/send/community.rs +++ b/crates/apub/src/activities/send/community.rs @@ -1,6 +1,5 @@ use crate::{check_is_apub_id_valid, ActorType, CommunityType}; use itertools::Itertools; -use lemmy_api_common::blocking; use lemmy_db_queries::DbPool; use lemmy_db_schema::source::community::Community; use lemmy_db_views_actor::community_follower_view::CommunityFollowerView; @@ -43,10 +42,7 @@ impl CommunityType for Community { async fn get_follower_inboxes(&self, pool: &DbPool) -> Result, LemmyError> { let id = self.id; - let follows = blocking(pool, move |conn| { - CommunityFollowerView::for_community(conn, id) - }) - .await??; + let follows = CommunityFollowerView::for_community(&&pool.get().await?, id)?; let inboxes = follows .into_iter() .filter(|f| !f.follower.local) diff --git a/crates/apub/src/activities/voting/mod.rs b/crates/apub/src/activities/voting/mod.rs index 48d44c0ee..71b338553 100644 --- a/crates/apub/src/activities/voting/mod.rs +++ b/crates/apub/src/activities/voting/mod.rs @@ -1,5 +1,4 @@ use crate::activities::voting::vote::VoteType; -use lemmy_api_common::blocking; use lemmy_db_queries::Likeable; use lemmy_db_schema::source::{ comment::{Comment, CommentLike, CommentLikeForm}, @@ -30,11 +29,8 @@ async fn vote_comment( score: vote_type.into(), }; let person_id = actor.id; - blocking(context.pool(), move |conn| { - CommentLike::remove(conn, person_id, comment_id)?; - CommentLike::like(conn, &like_form) - }) - .await??; + CommentLike::remove(&&context.pool.get().await?, person_id, comment_id)?; + CommentLike::like(&&context.pool.get().await?, &like_form)?; send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?; Ok(()) @@ -53,11 +49,8 @@ async fn vote_post( score: vote_type.into(), }; let person_id = actor.id; - blocking(context.pool(), move |conn| { - PostLike::remove(conn, person_id, post_id)?; - PostLike::like(conn, &like_form) - }) - .await??; + PostLike::remove(&&context.pool.get().await?, person_id, post_id)?; + PostLike::like(&&context.pool.get().await?, &like_form)?; send_post_ws_message(post.id, UserOperation::CreatePostLike, None, None, context).await?; Ok(()) @@ -70,10 +63,7 @@ async fn undo_vote_comment( ) -> Result<(), LemmyError> { let comment_id = comment.id; let person_id = actor.id; - blocking(context.pool(), move |conn| { - CommentLike::remove(conn, person_id, comment_id) - }) - .await??; + CommentLike::remove(&&context.pool.get().await?, person_id, comment_id)?; send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?; Ok(()) @@ -86,10 +76,7 @@ async fn undo_vote_post( ) -> Result<(), LemmyError> { let post_id = post.id; let person_id = actor.id; - blocking(context.pool(), move |conn| { - PostLike::remove(conn, person_id, post_id) - }) - .await??; + PostLike::remove(&&context.pool.get().await?, person_id, post_id)?; send_post_ws_message(post_id, UserOperation::CreatePostLike, None, None, context).await?; Ok(()) diff --git a/crates/apub/src/activities/voting/undo_vote.rs b/crates/apub/src/activities/voting/undo_vote.rs index 6e18b3cb6..b5c6eefe1 100644 --- a/crates/apub/src/activities/voting/undo_vote.rs +++ b/crates/apub/src/activities/voting/undo_vote.rs @@ -25,7 +25,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_db_queries::Crud; use lemmy_db_schema::{ @@ -62,10 +61,7 @@ impl UndoVote { kind: VoteType, context: &LemmyContext, ) -> Result<(), LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; let object = Vote::new(object, actor, &community, kind.clone())?; let id = generate_activity_id(UndoType::Undo)?; diff --git a/crates/apub/src/activities/voting/vote.rs b/crates/apub/src/activities/voting/vote.rs index cd7d04c54..95bad9aff 100644 --- a/crates/apub/src/activities/voting/vote.rs +++ b/crates/apub/src/activities/voting/vote.rs @@ -17,7 +17,6 @@ use crate::{ }; use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed}; use anyhow::anyhow; -use lemmy_api_common::blocking; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_db_queries::Crud; use lemmy_db_schema::{ @@ -100,10 +99,7 @@ impl Vote { kind: VoteType, context: &LemmyContext, ) -> Result<(), LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; let vote = Vote::new(object, actor, &community, kind)?; let vote_id = vote.id.clone(); diff --git a/crates/apub/src/fetcher/community.rs b/crates/apub/src/fetcher/community.rs index 83aa7b51e..3d66d19ec 100644 --- a/crates/apub/src/fetcher/community.rs +++ b/crates/apub/src/fetcher/community.rs @@ -11,7 +11,6 @@ use crate::{ use activitystreams::collection::{CollectionExt, OrderedCollection}; use anyhow::Context; use diesel::result::Error::NotFound; -use lemmy_api_common::blocking; use lemmy_apub_lib::ActivityHandler; use lemmy_db_queries::{source::community::Community_, ApubObject, Joinable}; use lemmy_db_schema::source::community::{Community, CommunityModerator, CommunityModeratorForm}; @@ -31,10 +30,7 @@ pub(crate) async fn get_or_fetch_and_upsert_community( recursion_counter: &mut i32, ) -> Result { let apub_id_owned = apub_id.to_owned(); - let community = blocking(context.pool(), move |conn| { - Community::read_from_apub_id(conn, &apub_id_owned.into()) - }) - .await?; + let community = Community::read_from_apub_id(&&context.pool.get().await?, &apub_id_owned.into()); match community { Ok(c) if !c.local && should_refetch_actor(c.last_refreshed_at) => { @@ -63,10 +59,7 @@ async fn fetch_remote_community( if let Some(c) = old_community.to_owned() { if is_deleted(&group) { - blocking(context.pool(), move |conn| { - Community::update_deleted(conn, c.id, true) - }) - .await??; + Community::update_deleted(&&context.pool.get().await?, c.id, true)?; } else if group.is_err() { // If fetching failed, return the existing data. return Ok(c); @@ -94,10 +87,8 @@ async fn update_community_mods( ) -> Result<(), LemmyError> { let new_moderators = fetch_community_mods(context, group, request_counter).await?; let community_id = community.id; - let current_moderators = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, community_id) - }) - .await??; + let current_moderators = + CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?; // Remove old mods from database which arent in the moderators collection anymore for mod_user in ¤t_moderators { if !new_moderators.contains(&mod_user.moderator.actor_id.clone().into()) { @@ -105,10 +96,7 @@ async fn update_community_mods( community_id: mod_user.community.id, person_id: mod_user.moderator.id, }; - blocking(context.pool(), move |conn| { - CommunityModerator::leave(conn, &community_moderator_form) - }) - .await??; + CommunityModerator::leave(&&context.pool.get().await?, &community_moderator_form)?; } } @@ -126,10 +114,7 @@ async fn update_community_mods( community_id: community.id, person_id: mod_user.id, }; - blocking(context.pool(), move |conn| { - CommunityModerator::join(conn, &community_moderator_form) - }) - .await??; + CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form)?; } } diff --git a/crates/apub/src/fetcher/objects.rs b/crates/apub/src/fetcher/objects.rs index e538982db..1a8abc8bb 100644 --- a/crates/apub/src/fetcher/objects.rs +++ b/crates/apub/src/fetcher/objects.rs @@ -5,7 +5,6 @@ use crate::{ }; use anyhow::anyhow; use diesel::result::Error::NotFound; -use lemmy_api_common::blocking; use lemmy_db_queries::{ApubObject, Crud}; use lemmy_db_schema::source::{comment::Comment, post::Post}; use lemmy_utils::LemmyError; @@ -23,10 +22,7 @@ pub(crate) async fn get_or_fetch_and_insert_post( recursion_counter: &mut i32, ) -> Result { let post_ap_id_owned = post_ap_id.to_owned(); - let post = blocking(context.pool(), move |conn| { - Post::read_from_apub_id(conn, &post_ap_id_owned.into()) - }) - .await?; + let post = Post::read_from_apub_id(&&context.pool.get().await?, &post_ap_id_owned.into()); match post { Ok(p) => Ok(p), @@ -52,10 +48,8 @@ pub(crate) async fn get_or_fetch_and_insert_comment( recursion_counter: &mut i32, ) -> Result { let comment_ap_id_owned = comment_ap_id.to_owned(); - let comment = blocking(context.pool(), move |conn| { - Comment::read_from_apub_id(conn, &comment_ap_id_owned.into()) - }) - .await?; + let comment = + Comment::read_from_apub_id(&&context.pool.get().await?, &comment_ap_id_owned.into()); match comment { Ok(p) => Ok(p), @@ -69,7 +63,7 @@ pub(crate) async fn get_or_fetch_and_insert_comment( let comment = Comment::from_apub(&comment, context, comment_ap_id, recursion_counter).await?; let post_id = comment.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; if post.locked { return Err(anyhow!("Post is locked").into()); } diff --git a/crates/apub/src/fetcher/person.rs b/crates/apub/src/fetcher/person.rs index ed3ca057f..81d2326e3 100644 --- a/crates/apub/src/fetcher/person.rs +++ b/crates/apub/src/fetcher/person.rs @@ -4,7 +4,6 @@ use crate::{ }; use anyhow::anyhow; use diesel::result::Error::NotFound; -use lemmy_api_common::blocking; use lemmy_db_queries::{source::person::Person_, ApubObject}; use lemmy_db_schema::source::person::Person; use lemmy_utils::LemmyError; @@ -22,10 +21,7 @@ pub(crate) async fn get_or_fetch_and_upsert_person( recursion_counter: &mut i32, ) -> Result { let apub_id_owned = apub_id.to_owned(); - let person = blocking(context.pool(), move |conn| { - Person::read_from_apub_id(conn, &apub_id_owned.into()) - }) - .await?; + let person = Person::read_from_apub_id(&&context.pool.get().await?, &apub_id_owned.into()); match person { // If its older than a day, re-fetch it @@ -36,10 +32,7 @@ pub(crate) async fn get_or_fetch_and_upsert_person( if is_deleted(&person) { // TODO: use Person::update_deleted() once implemented - blocking(context.pool(), move |conn| { - Person::delete_account(conn, u.id) - }) - .await??; + Person::delete_account(&&context.pool.get().await?, u.id)?; return Err(anyhow!("Person was deleted by remote instance").into()); } else if person.is_err() { return Ok(u); @@ -48,10 +41,7 @@ pub(crate) async fn get_or_fetch_and_upsert_person( let person = Person::from_apub(&person?, context, apub_id, recursion_counter).await?; let person_id = person.id; - blocking(context.pool(), move |conn| { - Person::mark_as_updated(conn, person_id) - }) - .await??; + Person::mark_as_updated(&&context.pool.get().await?, person_id)?; Ok(person) } diff --git a/crates/apub/src/fetcher/search.rs b/crates/apub/src/fetcher/search.rs index 2c9bebb02..d6bf85229 100644 --- a/crates/apub/src/fetcher/search.rs +++ b/crates/apub/src/fetcher/search.rs @@ -10,7 +10,7 @@ use crate::{ Object, }; use anyhow::anyhow; -use lemmy_api_common::{blocking, site::SearchResponse}; +use lemmy_api_common::site::SearchResponse; use lemmy_db_queries::{ source::{ comment::Comment_, @@ -119,40 +119,31 @@ async fn build_response( let person_id = p.id(&query_url)?; let person = get_or_fetch_and_upsert_person(person_id, context, recursion_counter).await?; - response.users = vec![ - blocking(context.pool(), move |conn| { - PersonViewSafe::read(conn, person.id) - }) - .await??, - ]; + response.users = vec![PersonViewSafe::read( + &&context.pool.get().await?, + person.id, + )?]; } SearchAcceptedObjects::Group(g) => { let community_uri = g.id(&query_url)?; let community = get_or_fetch_and_upsert_community(community_uri, context, recursion_counter).await?; - response.communities = vec![ - blocking(context.pool(), move |conn| { - CommunityView::read(conn, community.id, None) - }) - .await??, - ]; + response.communities = vec![CommunityView::read( + &&context.pool.get().await?, + community.id, + None, + )?]; } SearchAcceptedObjects::Page(p) => { let p = Post::from_apub(&p, context, &query_url, recursion_counter).await?; - response.posts = - vec![blocking(context.pool(), move |conn| PostView::read(conn, p.id, None)).await??]; + response.posts = vec![PostView::read(&&context.pool.get().await?, p.id, None)?]; } SearchAcceptedObjects::Comment(c) => { let c = Comment::from_apub(&c, context, &query_url, recursion_counter).await?; - response.comments = vec![ - blocking(context.pool(), move |conn| { - CommentView::read(conn, c.id, None) - }) - .await??, - ]; + response.comments = vec![CommentView::read(&&context.pool.get().await?, c.id, None)?]; } }; @@ -163,35 +154,20 @@ async fn delete_object_locally(query_url: &Url, context: &LemmyContext) -> Resul let res = find_object_by_id(context, query_url.to_owned()).await?; match res { Object::Comment(c) => { - blocking(context.pool(), move |conn| { - Comment::update_deleted(conn, c.id, true) - }) - .await??; + Comment::update_deleted(&&context.pool.get().await?, c.id, true)?; } Object::Post(p) => { - blocking(context.pool(), move |conn| { - Post::update_deleted(conn, p.id, true) - }) - .await??; + Post::update_deleted(&&context.pool.get().await?, p.id, true)?; } Object::Person(u) => { // TODO: implement update_deleted() for user, move it to ApubObject trait - blocking(context.pool(), move |conn| { - Person::delete_account(conn, u.id) - }) - .await??; + Person::delete_account(&&context.pool.get().await?, u.id)?; } Object::Community(c) => { - blocking(context.pool(), move |conn| { - Community::update_deleted(conn, c.id, true) - }) - .await??; + Community::update_deleted(&&context.pool.get().await?, c.id, true)?; } Object::PrivateMessage(pm) => { - blocking(context.pool(), move |conn| { - PrivateMessage::update_deleted(conn, pm.id, true) - }) - .await??; + PrivateMessage::update_deleted(&&context.pool.get().await?, pm.id, true)?; } } Err(anyhow!("Object was deleted").into()) diff --git a/crates/apub/src/http/comment.rs b/crates/apub/src/http/comment.rs index 4f63d89d3..7f4f37cae 100644 --- a/crates/apub/src/http/comment.rs +++ b/crates/apub/src/http/comment.rs @@ -4,7 +4,6 @@ use crate::{ }; use actix_web::{body::Body, web, web::Path, HttpResponse}; use diesel::result::Error::NotFound; -use lemmy_api_common::blocking; use lemmy_db_queries::Crud; use lemmy_db_schema::{source::comment::Comment, CommentId}; use lemmy_utils::LemmyError; @@ -22,7 +21,7 @@ pub(crate) async fn get_apub_comment( context: web::Data, ) -> Result, LemmyError> { let id = CommentId(info.comment_id.parse::()?); - let comment = blocking(context.pool(), move |conn| Comment::read(conn, id)).await??; + let comment = Comment::read(&&context.pool.get().await?, id)?; if !comment.local { return Err(NotFound.into()); } diff --git a/crates/apub/src/http/community.rs b/crates/apub/src/http/community.rs index cd75031dc..31d1a125c 100644 --- a/crates/apub/src/http/community.rs +++ b/crates/apub/src/http/community.rs @@ -21,7 +21,6 @@ use activitystreams::{ url::Url, }; use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ActivityFields, ActivityHandler}; use lemmy_db_queries::source::{activity::Activity_, community::Community_}; use lemmy_db_schema::source::{activity::Activity, community::Community}; @@ -44,10 +43,7 @@ pub(crate) async fn get_apub_community_http( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read_from_name(conn, &info.community_name) - }) - .await??; + let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?; if !community.deleted { let apub = community.to_apub(context.pool()).await?; @@ -101,16 +97,11 @@ pub(crate) async fn get_apub_community_followers( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read_from_name(conn, &info.community_name) - }) - .await??; + let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?; let community_id = community.id; - let community_followers = blocking(context.pool(), move |conn| { - CommunityFollowerView::for_community(conn, community_id) - }) - .await??; + let community_followers = + CommunityFollowerView::for_community(&&context.pool.get().await?, community_id)?; let mut collection = UnorderedCollection::new(); collection @@ -126,16 +117,11 @@ pub(crate) async fn get_apub_community_outbox( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read_from_name(conn, &info.community_name) - }) - .await??; + let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?; let community_actor_id = community.actor_id.to_owned(); - let activities = blocking(context.pool(), move |conn| { - Activity::read_community_outbox(conn, &community_actor_id) - }) - .await??; + let activities = + Activity::read_community_outbox(&&context.pool.get().await?, &community_actor_id)?; let activities = activities .iter() @@ -155,10 +141,7 @@ pub(crate) async fn get_apub_community_inbox( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read_from_name(conn, &info.community_name) - }) - .await??; + let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?; let mut collection = OrderedCollection::new(); collection @@ -171,20 +154,14 @@ pub(crate) async fn get_apub_community_moderators( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let community = blocking(context.pool(), move |conn| { - Community::read_from_name(conn, &info.community_name) - }) - .await??; + let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?; // The attributed to, is an ordered vector with the creator actor_ids first, // then the rest of the moderators // TODO Technically the instance admins can mod the community, but lets // ignore that for now let cid = community.id; - let moderators = blocking(context.pool(), move |conn| { - CommunityModeratorView::for_community(conn, cid) - }) - .await??; + let moderators = CommunityModeratorView::for_community(&&context.pool.get().await?, cid)?; let moderators: Vec = moderators .into_iter() diff --git a/crates/apub/src/http/mod.rs b/crates/apub/src/http/mod.rs index 6fe8d182e..d3bb7be90 100644 --- a/crates/apub/src/http/mod.rs +++ b/crates/apub/src/http/mod.rs @@ -19,7 +19,6 @@ use actix_web::{ use anyhow::{anyhow, Context}; use futures::StreamExt; use http::StatusCode; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ActivityFields, ActivityHandler}; use lemmy_db_queries::{source::activity::Activity_, DbPool}; use lemmy_db_schema::source::activity::Activity; @@ -158,10 +157,7 @@ pub(crate) async fn get_activity( info.id ))? .into(); - let activity = blocking(context.pool(), move |conn| { - Activity::read_from_apub_id(conn, &activity_id) - }) - .await??; + let activity = Activity::read_from_apub_id(&&context.pool.get().await?, &activity_id)?; let sensitive = activity.sensitive.unwrap_or(true); if !activity.local || sensitive { @@ -176,10 +172,7 @@ pub(crate) async fn is_activity_already_known( activity_id: &Url, ) -> Result { let activity_id = activity_id.to_owned().into(); - let existing = blocking(pool, move |conn| { - Activity::read_from_apub_id(conn, &activity_id) - }) - .await?; + let existing = Activity::read_from_apub_id(&&pool.get().await?, &activity_id); match existing { Ok(_) => Ok(true), Err(_) => Ok(false), diff --git a/crates/apub/src/http/person.rs b/crates/apub/src/http/person.rs index dcab60017..c176533ab 100644 --- a/crates/apub/src/http/person.rs +++ b/crates/apub/src/http/person.rs @@ -23,7 +23,6 @@ use activitystreams::{ collection::{CollectionExt, OrderedCollection}, }; use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ActivityFields, ActivityHandler}; use lemmy_db_queries::source::person::Person_; use lemmy_db_schema::source::person::Person; @@ -45,10 +44,7 @@ pub(crate) async fn get_apub_person_http( ) -> Result, LemmyError> { let user_name = info.into_inner().user_name; // TODO: this needs to be able to read deleted persons, so that it can send tombstones - let person = blocking(context.pool(), move |conn| { - Person::find_by_name(conn, &user_name) - }) - .await??; + let person = Person::find_by_name(&&context.pool.get().await?, &user_name)?; if !person.deleted { let apub = person.to_apub(context.pool()).await?; @@ -95,10 +91,7 @@ pub(crate) async fn get_apub_person_outbox( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let person = blocking(context.pool(), move |conn| { - Person::find_by_name(conn, &info.user_name) - }) - .await??; + let person = Person::find_by_name(&&context.pool.get().await?, &info.user_name)?; // TODO: populate the person outbox let mut collection = OrderedCollection::new(); collection @@ -113,10 +106,7 @@ pub(crate) async fn get_apub_person_inbox( info: web::Path, context: web::Data, ) -> Result, LemmyError> { - let person = blocking(context.pool(), move |conn| { - Person::find_by_name(conn, &info.user_name) - }) - .await??; + let person = Person::find_by_name(&&context.pool.get().await?, &info.user_name)?; let mut collection = OrderedCollection::new(); collection diff --git a/crates/apub/src/http/post.rs b/crates/apub/src/http/post.rs index 324bb7da9..667cd7a48 100644 --- a/crates/apub/src/http/post.rs +++ b/crates/apub/src/http/post.rs @@ -4,7 +4,6 @@ use crate::{ }; use actix_web::{body::Body, web, HttpResponse}; use diesel::result::Error::NotFound; -use lemmy_api_common::blocking; use lemmy_db_queries::Crud; use lemmy_db_schema::{source::post::Post, PostId}; use lemmy_utils::LemmyError; @@ -22,7 +21,7 @@ pub(crate) async fn get_apub_post( context: web::Data, ) -> Result, LemmyError> { let id = PostId(info.post_id.parse::()?); - let post = blocking(context.pool(), move |conn| Post::read(conn, id)).await??; + let post = Post::read(&&context.pool.get().await?, id)?; if !post.local { return Err(NotFound.into()); } diff --git a/crates/apub/src/lib.rs b/crates/apub/src/lib.rs index 839e7d148..f882b9e4f 100644 --- a/crates/apub/src/lib.rs +++ b/crates/apub/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::needless_borrow)] + #[macro_use] extern crate lazy_static; @@ -12,7 +14,6 @@ pub mod objects; use crate::extensions::signatures::PublicKey; use anyhow::{anyhow, Context}; use diesel::NotFound; -use lemmy_api_common::blocking; use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool}; use lemmy_db_schema::{ source::{ @@ -237,10 +238,7 @@ where T: Serialize + std::fmt::Debug + Send + 'static, { let ap_id = ap_id.to_owned().into(); - blocking(pool, move |conn| { - Activity::insert(conn, ap_id, &activity, local, sensitive) - }) - .await??; + Activity::insert(&&pool.get().await?, ap_id, &activity, local, sensitive)?; Ok(()) } @@ -267,19 +265,13 @@ pub(crate) async fn find_post_or_comment_by_id( apub_id: Url, ) -> Result { let ap_id = apub_id.clone(); - let post = blocking(context.pool(), move |conn| { - Post::read_from_apub_id(conn, &ap_id.into()) - }) - .await?; + let post = Post::read_from_apub_id(&&context.pool.get().await?, &ap_id.into()); if let Ok(p) = post { return Ok(PostOrComment::Post(Box::new(p))); } let ap_id = apub_id.clone(); - let comment = blocking(context.pool(), move |conn| { - Comment::read_from_apub_id(conn, &ap_id.into()) - }) - .await?; + let comment = Comment::read_from_apub_id(&&context.pool.get().await?, &ap_id.into()); if let Ok(c) = comment { return Ok(PostOrComment::Comment(Box::new(c))); } @@ -306,27 +298,19 @@ async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result { let post_id = c.post_id; - let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&context.pool.get().await?, post_id)?; Ok((post, Some(c.id))) } } @@ -140,10 +139,7 @@ impl Note { ) -> Result<(), LemmyError> { let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?; let community_id = post.community_id; - let community = blocking(context.pool(), move |conn| { - Community::read(conn, community_id) - }) - .await??; + let community = Community::read(&&context.pool.get().await?, community_id)?; if post.locked { return Err(anyhow!("Post is locked").into()); @@ -166,17 +162,17 @@ impl ToApub for Comment { async fn to_apub(&self, pool: &DbPool) -> Result { let creator_id = self.creator_id; - let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??; + let creator = Person::read(&&pool.get().await?, creator_id)?; let post_id = self.post_id; - let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??; + let post = Post::read(&&pool.get().await?, post_id)?; // Add a vector containing some important info to the "in_reply_to" field // [post_ap_id, Option(parent_comment_ap_id)] let mut in_reply_to_vec = vec![post.ap_id.into_inner()]; if let Some(parent_id) = self.parent_id { - let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_id)).await??; + let parent_comment = Comment::read(&&pool.get().await?, parent_id)?; in_reply_to_vec.push(parent_comment.ap_id.into_inner()); } @@ -246,6 +242,6 @@ impl FromApub for Comment { ap_id, local: Some(false), }; - Ok(blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??) + Ok(Comment::upsert(&&context.pool.get().await?, &form)?) } } diff --git a/crates/apub/src/objects/community.rs b/crates/apub/src/objects/community.rs index 5269d7663..e540cedae 100644 --- a/crates/apub/src/objects/community.rs +++ b/crates/apub/src/objects/community.rs @@ -13,7 +13,6 @@ use activitystreams::{ unparsed::Unparsed, }; use chrono::{DateTime, FixedOffset}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ values::{MediaTypeHtml, MediaTypeMarkdown}, verify_domains_match, @@ -178,7 +177,7 @@ impl FromApub for Community { fetch_community_mods(context, group, request_counter).await?; let form = Group::from_apub_to_form(group, expected_domain).await?; - let community = blocking(context.pool(), move |conn| Community::upsert(conn, &form)).await??; + let community = Community::upsert(&&context.pool.get().await?, &form)?; Ok(community) } } diff --git a/crates/apub/src/objects/person.rs b/crates/apub/src/objects/person.rs index ec14a943e..46645e160 100644 --- a/crates/apub/src/objects/person.rs +++ b/crates/apub/src/objects/person.rs @@ -12,7 +12,6 @@ use activitystreams::{ primitives::OneOrMany, unparsed::Unparsed, }; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ values::{MediaTypeHtml, MediaTypeMarkdown}, verify_domains_match, @@ -176,10 +175,7 @@ impl FromApub for DbPerson { shared_inbox_url: Some(shared_inbox), matrix_user_id: Some(person.matrix_user_id.clone()), }; - let person = blocking(context.pool(), move |conn| { - DbPerson::upsert(conn, &person_form) - }) - .await??; + let person = DbPerson::upsert(&&context.pool.get().await?, &person_form)?; Ok(person) } } diff --git a/crates/apub/src/objects/post.rs b/crates/apub/src/objects/post.rs index 4773f8c56..0537c0bc5 100644 --- a/crates/apub/src/objects/post.rs +++ b/crates/apub/src/objects/post.rs @@ -16,7 +16,6 @@ use activitystreams::{ unparsed::Unparsed, }; use chrono::{DateTime, FixedOffset}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ values::{MediaTypeHtml, MediaTypeMarkdown}, verify_domains_match, @@ -80,10 +79,7 @@ impl Page { /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]]. pub(crate) async fn is_mod_action(&self, pool: &DbPool) -> Result { let post_id = self.id.clone(); - let old_post = blocking(pool, move |conn| { - Post::read_from_apub_id(conn, &post_id.into()) - }) - .await?; + let old_post = Post::read_from_apub_id(&&pool.get().await?, &post_id.into()); let is_mod_action = if let Ok(old_post) = old_post { self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked) @@ -120,9 +116,9 @@ impl ToApub for Post { // Turn a Lemmy post into an ActivityPub page that can be sent out over the network. async fn to_apub(&self, pool: &DbPool) -> Result { let creator_id = self.creator_id; - let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??; + let creator = Person::read(&&pool.get().await?, creator_id)?; let community_id = self.community_id; - let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??; + let community = Community::read(&&pool.get().await?, community_id)?; let source = self.body.clone().map(|body| Source { content: body, @@ -218,6 +214,6 @@ impl FromApub for Post { ap_id, local: Some(false), }; - Ok(blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??) + Ok(Post::upsert(&&context.pool.get().await?, &form)?) } } diff --git a/crates/apub/src/objects/private_message.rs b/crates/apub/src/objects/private_message.rs index 02cf12eba..eda38912f 100644 --- a/crates/apub/src/objects/private_message.rs +++ b/crates/apub/src/objects/private_message.rs @@ -11,7 +11,6 @@ use activitystreams::{ }; use anyhow::anyhow; use chrono::{DateTime, FixedOffset}; -use lemmy_api_common::blocking; use lemmy_apub_lib::{ values::{MediaTypeHtml, MediaTypeMarkdown}, verify_domains_match, @@ -76,10 +75,10 @@ impl ToApub for PrivateMessage { async fn to_apub(&self, pool: &DbPool) -> Result { let creator_id = self.creator_id; - let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??; + let creator = Person::read(&&pool.get().await?, creator_id)?; let recipient_id = self.recipient_id; - let recipient = blocking(pool, move |conn| Person::read(conn, recipient_id)).await??; + let recipient = Person::read(&&pool.get().await?, recipient_id)?; let note = Note { context: lemmy_context(), @@ -136,11 +135,6 @@ impl FromApub for PrivateMessage { ap_id, local: Some(false), }; - Ok( - blocking(context.pool(), move |conn| { - PrivateMessage::upsert(conn, &form) - }) - .await??, - ) + Ok(PrivateMessage::upsert(&&context.pool.get().await?, &form)?) } } diff --git a/crates/db_queries/Cargo.toml b/crates/db_queries/Cargo.toml index 50199ea3e..b676d7931 100644 --- a/crates/db_queries/Cargo.toml +++ b/crates/db_queries/Cargo.toml @@ -13,7 +13,7 @@ doctest = false [dependencies] lemmy_utils = { version = "=0.11.3", path = "../utils" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } -diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } +diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] } diesel_migrations = "1.4.0" chrono = { version = "0.4.19", features = ["serde"] } serde = { version = "1.0.127", features = ["derive"] } @@ -26,6 +26,7 @@ url = { version = "2.2.2", features = ["serde"] } lazy_static = "1.4.0" regex = "1.5.4" bcrypt = "0.10.1" +deadpool-diesel = { version = "0.1.2", features = ["postgres"] } [dev-dependencies] serial_test = "0.5.1" diff --git a/crates/db_queries/src/lib.rs b/crates/db_queries/src/lib.rs index e62124b18..8e73ee812 100644 --- a/crates/db_queries/src/lib.rs +++ b/crates/db_queries/src/lib.rs @@ -12,6 +12,7 @@ extern crate diesel_migrations; #[cfg(test)] extern crate serial_test; +use deadpool_diesel::postgres::Pool; use diesel::{result::Error, *}; use lemmy_db_schema::{CommunityId, DbUrl, PersonId}; use lemmy_utils::ApiError; @@ -23,7 +24,7 @@ use url::Url; pub mod aggregates; pub mod source; -pub type DbPool = diesel::r2d2::Pool>; +pub type DbPool = Pool; pub trait Crud { type Form; diff --git a/crates/db_schema/Cargo.toml b/crates/db_schema/Cargo.toml index 969382b84..ae40168c6 100644 --- a/crates/db_schema/Cargo.toml +++ b/crates/db_schema/Cargo.toml @@ -9,7 +9,7 @@ license = "AGPL-3.0" doctest = false [dependencies] -diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } +diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] } chrono = { version = "0.4.19", features = ["serde"] } serde = { version = "1.0.127", features = ["derive"] } serde_json = { version = "1.0.66", features = ["preserve_order"] } diff --git a/crates/db_views/Cargo.toml b/crates/db_views/Cargo.toml index 7044b6659..60203b51f 100644 --- a/crates/db_views/Cargo.toml +++ b/crates/db_views/Cargo.toml @@ -11,7 +11,7 @@ doctest = false [dependencies] lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } -diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } +diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] } serde = { version = "1.0.127", features = ["derive"] } log = "0.4.14" url = "2.2.2" diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index 2183fa31e..f682a232c 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -708,7 +708,7 @@ mod tests { ); // Make sure block set the creator blocked - assert_eq!(true, read_comment_from_blocked_person.creator_blocked); + assert!(read_comment_from_blocked_person.creator_blocked); assert_eq!(1, num_deleted); assert_eq!(1, like_removed); diff --git a/crates/db_views_actor/Cargo.toml b/crates/db_views_actor/Cargo.toml index 14741e408..ebbef1521 100644 --- a/crates/db_views_actor/Cargo.toml +++ b/crates/db_views_actor/Cargo.toml @@ -11,5 +11,5 @@ doctest = false [dependencies] lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } -diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } +diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] } serde = { version = "1.0.127", features = ["derive"] } diff --git a/crates/db_views_moderator/Cargo.toml b/crates/db_views_moderator/Cargo.toml index ba80dc0d4..2c3aed9a5 100644 --- a/crates/db_views_moderator/Cargo.toml +++ b/crates/db_views_moderator/Cargo.toml @@ -11,5 +11,5 @@ doctest = false [dependencies] lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } -diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } +diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] } serde = { version = "1.0.127", features = ["derive"] } diff --git a/crates/routes/src/feeds.rs b/crates/routes/src/feeds.rs index 75542e740..47bc3cfe0 100644 --- a/crates/routes/src/feeds.rs +++ b/crates/routes/src/feeds.rs @@ -2,7 +2,6 @@ use actix_web::{error::ErrorBadRequest, *}; use anyhow::anyhow; use chrono::{DateTime, NaiveDateTime, Utc}; use diesel::PgConnection; -use lemmy_api_common::blocking; use lemmy_db_queries::{ source::{community::Community_, person::Person_}, Crud, @@ -88,15 +87,12 @@ async fn get_feed_data( listing_type: ListingType, sort_type: SortType, ) -> Result { - let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; + let site_view = SiteView::read(&&context.pool.get().await?)?; - let posts = blocking(context.pool(), move |conn| { - PostQueryBuilder::create(conn) - .listing_type(listing_type) - .sort(sort_type) - .list() - }) - .await??; + let posts = PostQueryBuilder::create(&&context.pool.get().await?) + .listing_type(listing_type) + .sort(sort_type) + .list()?; let items = create_post_items(posts)?; @@ -141,13 +137,13 @@ async fn get_feed( _ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))), }; - let builder = blocking(context.pool(), move |conn| match request_type { + let conn = &&context.pool.get().await.map_err(ErrorBadRequest)?; + let builder = match request_type { RequestType::User => get_feed_user(conn, &sort_type, param), RequestType::Community => get_feed_community(conn, &sort_type, param), RequestType::Front => get_feed_front(conn, &sort_type, param), RequestType::Inbox => get_feed_inbox(conn, param), - }) - .await? + } .map_err(ErrorBadRequest)?; let rss = builder.build().map_err(ErrorBadRequest)?.to_string(); diff --git a/crates/routes/src/lib.rs b/crates/routes/src/lib.rs index b966b766a..8cd6869e9 100644 --- a/crates/routes/src/lib.rs +++ b/crates/routes/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::needless_borrow)] + #[macro_use] extern crate lazy_static; diff --git a/crates/routes/src/nodeinfo.rs b/crates/routes/src/nodeinfo.rs index 86d625900..200c95603 100644 --- a/crates/routes/src/nodeinfo.rs +++ b/crates/routes/src/nodeinfo.rs @@ -1,6 +1,5 @@ use actix_web::{body::Body, error::ErrorBadRequest, *}; use anyhow::anyhow; -use lemmy_api_common::blocking; use lemmy_db_views::site_view::SiteView; use lemmy_utils::{settings::structs::Settings, version, LemmyError}; use lemmy_websocket::LemmyContext; @@ -27,8 +26,7 @@ async fn node_info_well_known() -> Result, LemmyError> { } async fn node_info(context: web::Data) -> Result { - let site_view = blocking(context.pool(), SiteView::read) - .await? + let site_view = SiteView::read(&&context.pool.get().await.map_err(ErrorBadRequest)?) .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?; let protocols = if Settings::get().federation.enabled { diff --git a/crates/routes/src/webfinger.rs b/crates/routes/src/webfinger.rs index 5d4be74c4..48d65fa71 100644 --- a/crates/routes/src/webfinger.rs +++ b/crates/routes/src/webfinger.rs @@ -1,6 +1,6 @@ use actix_web::{error::ErrorBadRequest, web::Query, *}; use anyhow::anyhow; -use lemmy_api_common::{blocking, WebFingerLink, WebFingerResponse}; +use lemmy_api_common::{WebFingerLink, WebFingerResponse}; use lemmy_db_queries::source::{community::Community_, person::Person_}; use lemmy_db_schema::source::{community::Community, person::Person}; use lemmy_utils::{ @@ -46,24 +46,19 @@ async fn get_webfinger_response( .map(|c| c.get(1)) .flatten(); + let conn = &&context.pool.get().await.map_err(ErrorBadRequest)?; let url = if let Some(community_name) = community_regex_parsed { let community_name = community_name.as_str().to_owned(); // Make sure the requested community exists. - blocking(context.pool(), move |conn| { - Community::read_from_name(conn, &community_name) - }) - .await? - .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? - .actor_id + Community::read_from_name(conn, &community_name) + .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? + .actor_id } else if let Some(person_name) = username_regex_parsed { let person_name = person_name.as_str().to_owned(); // Make sure the requested person exists. - blocking(context.pool(), move |conn| { - Person::find_by_name(conn, &person_name) - }) - .await? - .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? - .actor_id + Person::find_by_name(conn, &person_name) + .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? + .actor_id } else { return Err(ErrorBadRequest(LemmyError::from(anyhow!("not_found")))); }; diff --git a/crates/utils/src/settings/structs.rs b/crates/utils/src/settings/structs.rs index c9537fe36..614af8d3f 100644 --- a/crates/utils/src/settings/structs.rs +++ b/crates/utils/src/settings/structs.rs @@ -57,7 +57,7 @@ pub struct DatabaseConfig { #[default("lemmy")] pub(super) database: String, #[default(5)] - pub pool_size: u32, + pub pool_size: usize, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/websocket/src/chat_server.rs b/crates/websocket/src/chat_server.rs index 2e4fda2e4..e25fe6253 100644 --- a/crates/websocket/src/chat_server.rs +++ b/crates/websocket/src/chat_server.rs @@ -9,11 +9,8 @@ use crate::{ use actix::prelude::*; use anyhow::Context as acontext; use background_jobs::QueueHandle; -use diesel::{ - r2d2::{ConnectionManager, Pool}, - PgConnection, -}; use lemmy_api_common::{comment::*, post::*}; +use lemmy_db_queries::DbPool; use lemmy_db_schema::{CommunityId, LocalUserId, PostId}; use lemmy_utils::{ location_info, @@ -69,7 +66,7 @@ pub struct ChatServer { pub(super) rng: ThreadRng, /// The DB Pool - pub(super) pool: Pool>, + pub(super) pool: DbPool, /// Rate limiting based on rate type and IP addr pub(super) rate_limiter: RateLimit, @@ -96,7 +93,7 @@ pub struct SessionInfo { /// room through `ChatServer`. impl ChatServer { pub fn startup( - pool: Pool>, + pool: DbPool, rate_limiter: RateLimit, message_handler: MessageHandlerType, message_handler_crud: MessageHandlerCrudType, diff --git a/crates/websocket/src/lib.rs b/crates/websocket/src/lib.rs index fbb2bb512..657f84573 100644 --- a/crates/websocket/src/lib.rs +++ b/crates/websocket/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::needless_borrow)] + #[macro_use] extern crate strum_macros; diff --git a/crates/websocket/src/send.rs b/crates/websocket/src/send.rs index 130d94a48..bc64c7a72 100644 --- a/crates/websocket/src/send.rs +++ b/crates/websocket/src/send.rs @@ -4,7 +4,6 @@ use crate::{ OperationType, }; use lemmy_api_common::{ - blocking, comment::CommentResponse, community::CommunityResponse, person::PrivateMessageResponse, @@ -28,10 +27,7 @@ pub async fn send_post_ws_message person_id: Option, context: &LemmyContext, ) -> Result { - let mut post_view = blocking(context.pool(), move |conn| { - PostView::read(conn, post_id, person_id) - }) - .await??; + let mut post_view = PostView::read(&&context.pool.get().await?, post_id, person_id)?; if post_view.post.deleted || post_view.post.removed { post_view.post = post_view.post.blank_out_deleted_or_removed_info(); @@ -67,10 +63,7 @@ pub async fn send_comment_ws_message, context: &LemmyContext, ) -> Result { - let mut view = blocking(context.pool(), move |conn| { - CommentView::read(conn, comment_id, person_id) - }) - .await??; + let mut view = CommentView::read(&&context.pool.get().await?, comment_id, person_id)?; if view.comment.deleted || view.comment.removed { view.comment = view.comment.blank_out_deleted_or_removed_info(); @@ -98,10 +91,9 @@ pub async fn send_community_ws_message, context: &LemmyContext, ) -> Result { - let mut community_view = blocking(context.pool(), move |conn| { - CommunityView::read(conn, community_id, person_id) - }) - .await??; + let mut community_view = + CommunityView::read(&&context.pool.get().await?, community_id, person_id)?; + // Blank out deleted or removed info if community_view.community.deleted || community_view.community.removed { community_view.community = community_view.community.blank_out_deleted_or_removed_info(); @@ -129,10 +121,7 @@ pub async fn send_pm_ws_message( websocket_id: Option, context: &LemmyContext, ) -> Result { - let mut view = blocking(context.pool(), move |conn| { - PrivateMessageView::read(conn, private_message_id) - }) - .await??; + let mut view = PrivateMessageView::read(&&context.pool.get().await?, private_message_id)?; // Blank out deleted or removed info if view.private_message.deleted { @@ -146,10 +135,7 @@ pub async fn send_pm_ws_message( // Send notifications to the local recipient, if one exists if res.private_message_view.recipient.local { let recipient_id = res.private_message_view.recipient.id; - let local_recipient = blocking(context.pool(), move |conn| { - LocalUserView::read_person(conn, recipient_id) - }) - .await??; + let local_recipient = LocalUserView::read_person(&&context.pool.get().await?, recipient_id)?; context.chat_server().do_send(SendUserRoomMessage { op, response: res.clone(), diff --git a/src/main.rs b/src/main.rs index 504ccc80e..16df7fa36 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,12 +3,8 @@ extern crate diesel_migrations; use actix::prelude::*; use actix_web::{web::Data, *}; -use diesel::{ - r2d2::{ConnectionManager, Pool}, - PgConnection, -}; +use deadpool_diesel::postgres::{Manager, Pool}; use lemmy_api::match_websocket_operation; -use lemmy_api_common::blocking; use lemmy_api_crud::match_websocket_operation_crud; use lemmy_apub::activity_queue::create_activity_queue; use lemmy_db_queries::get_database_url_from_env; @@ -31,28 +27,26 @@ async fn main() -> Result<(), LemmyError> { env_logger::init(); let settings = Settings::get(); - // Set up the r2d2 connection pool + // Set up the deadpool connection pool let db_url = match get_database_url_from_env() { Ok(url) => url, Err(_) => settings.get_database_url(), }; - let manager = ConnectionManager::::new(&db_url); - let pool = Pool::builder() - .max_size(settings.database.pool_size) - .build(manager) - .unwrap_or_else(|_| panic!("Error connecting to {}", db_url)); + + let manager = Manager::new(db_url); + let pool = Pool::new(manager, settings.database.pool_size); + let conn = &pool.get().await?; // Run the migrations from code - blocking(&pool, move |conn| { - embedded_migrations::run(conn)?; - run_advanced_migrations(conn)?; - Ok(()) as Result<(), LemmyError> - }) - .await??; + embedded_migrations::run(conn)?; + run_advanced_migrations(conn)?; - let pool2 = pool.clone(); + // TODO can't move the pool into clokwerk, it doesn't yet support async + let c1 = pool.get().await?; + let c2 = pool.get().await?; + let c3 = pool.get().await?; thread::spawn(move || { - scheduled_tasks::setup(pool2); + scheduled_tasks::setup(c1, c2, c3); }); // Set up the rate limiter diff --git a/src/scheduled_tasks.rs b/src/scheduled_tasks.rs index a3b5f75db..089bd2356 100644 --- a/src/scheduled_tasks.rs +++ b/src/scheduled_tasks.rs @@ -2,27 +2,28 @@ use clokwerk::{Scheduler, TimeUnits}; // Import week days and WeekDay use diesel::{sql_query, PgConnection, RunQueryDsl}; -use lemmy_db_queries::{source::activity::Activity_, DbPool}; +use lemmy_db_queries::source::activity::Activity_; use lemmy_db_schema::source::activity::Activity; use log::info; use std::{thread, time::Duration}; +type DeadpoolPgConnection = deadpool_diesel::Connection; + /// Schedules various cleanup tasks for lemmy in a background thread -pub fn setup(pool: DbPool) { +pub fn setup(c1: DeadpoolPgConnection, c2: DeadpoolPgConnection, c3: DeadpoolPgConnection) { let mut scheduler = Scheduler::new(); - let conn = pool.get().unwrap(); - active_counts(&conn); - reindex_aggregates_tables(&conn); + active_counts(&c1); + reindex_aggregates_tables(&c1); + clear_old_activities(&c1); + scheduler.every(1.hour()).run(move || { - active_counts(&conn); - reindex_aggregates_tables(&conn); + active_counts(&c2); + reindex_aggregates_tables(&c2); }); - let conn = pool.get().unwrap(); - clear_old_activities(&conn); scheduler.every(1.weeks()).run(move || { - clear_old_activities(&conn); + clear_old_activities(&c3); }); // Manually run the scheduler in an event loop