From dff8b947bb779d27d4b5953fe1f34166ac5c4104 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Sun, 12 Jan 2020 10:31:51 -0500 Subject: [PATCH] Trying to add r2d2 connection pooling to websockets. --- server/src/api/comment.rs | 13 ++- server/src/api/community.rs | 29 +++--- server/src/api/mod.rs | 3 +- server/src/api/post.rs | 20 ++--- server/src/api/site.rs | 22 ++--- server/src/api/user.rs | 40 +++------ server/src/apub/community.rs | 8 +- server/src/apub/user.rs | 4 +- server/src/db/category.rs | 2 +- server/src/db/comment.rs | 2 +- server/src/db/comment_view.rs | 2 +- server/src/db/community.rs | 2 +- server/src/db/mod.rs | 17 +--- server/src/db/moderator.rs | 2 +- server/src/db/password_reset_request.rs | 2 +- server/src/db/post.rs | 2 +- server/src/db/post_view.rs | 2 +- server/src/db/user.rs | 2 +- server/src/db/user_mention.rs | 2 +- server/src/main.rs | 21 ++++- server/src/routes/feeds.rs | 112 +++++++++++++----------- server/src/routes/nodeinfo.rs | 64 ++++++++------ server/src/routes/webfinger.rs | 93 +++++++++++--------- server/src/routes/websocket.rs | 20 ++++- server/src/websocket/server.rs | 109 +++++++++++++---------- 25 files changed, 308 insertions(+), 287 deletions(-) diff --git a/server/src/api/comment.rs b/server/src/api/comment.rs index 62759578b..61cc95063 100644 --- a/server/src/api/comment.rs +++ b/server/src/api/comment.rs @@ -1,6 +1,7 @@ use super::*; use crate::send_email; use crate::settings::Settings; +use diesel::PgConnection; #[derive(Serialize, Deserialize)] pub struct CreateComment { @@ -47,9 +48,8 @@ pub struct CreateCommentLike { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &CreateComment = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -206,9 +206,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &EditComment = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -318,9 +317,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &SaveComment = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -356,9 +354,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &CreateCommentLike = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, diff --git a/server/src/api/community.rs b/server/src/api/community.rs index a1109c03c..0bf846c3d 100644 --- a/server/src/api/community.rs +++ b/server/src/api/community.rs @@ -1,4 +1,5 @@ use super::*; +use diesel::PgConnection; use std::str::FromStr; #[derive(Serialize, Deserialize)] @@ -118,9 +119,8 @@ pub struct TransferCommunity { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetCommunity = &self.data; - let conn = establish_connection(); let user_id: Option = match &data.auth { Some(auth) => match Claims::decode(&auth) { @@ -173,9 +173,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &CreateCommunity = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -248,15 +247,13 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &EditCommunity = &self.data; if has_slurs(&data.name) || has_slurs(&data.title) { return Err(APIError::err(&self.op, "no_slurs").into()); } - let conn = establish_connection(); - let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, Err(_e) => return Err(APIError::err(&self.op, "not_logged_in").into()), @@ -325,9 +322,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &ListCommunities = &self.data; - let conn = establish_connection(); let user_claims: Option = match &data.auth { Some(auth) => match Claims::decode(&auth) { @@ -366,9 +362,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &FollowCommunity = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -404,9 +399,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetFollowedCommunities = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -430,9 +424,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &BanFromCommunity = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -485,9 +478,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &AddModToCommunity = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -536,9 +528,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &TransferCommunity = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index 07712e874..e35804476 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -16,6 +16,7 @@ use crate::db::user_mention_view::*; use crate::db::user_view::*; use crate::db::*; use crate::{extract_usernames, has_slurs, naive_from_unix, naive_now, remove_slurs}; +use diesel::PgConnection; use failure::Error; use serde::{Deserialize, Serialize}; @@ -96,7 +97,7 @@ impl Oper { } pub trait Perform { - fn perform(&self) -> Result + fn perform(&self, conn: &PgConnection) -> Result where T: Sized; } diff --git a/server/src/api/post.rs b/server/src/api/post.rs index 5bc31defe..b0fcdd0c1 100644 --- a/server/src/api/post.rs +++ b/server/src/api/post.rs @@ -1,4 +1,5 @@ use super::*; +use diesel::PgConnection; use std::str::FromStr; #[derive(Serialize, Deserialize)] @@ -87,9 +88,8 @@ pub struct SavePost { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &CreatePost = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -158,9 +158,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetPost = &self.data; - let conn = establish_connection(); let user_id: Option = match &data.auth { Some(auth) => match Claims::decode(&auth) { @@ -207,9 +206,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetPosts = &self.data; - let conn = establish_connection(); let user_claims: Option = match &data.auth { Some(auth) => match Claims::decode(&auth) { @@ -254,9 +252,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &CreatePostLike = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -316,14 +313,12 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &EditPost = &self.data; if has_slurs(&data.name) || (data.body.is_some() && has_slurs(&data.body.to_owned().unwrap())) { return Err(APIError::err(&self.op, "no_slurs").into()); } - let conn = establish_connection(); - let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, Err(_e) => return Err(APIError::err(&self.op, "not_logged_in").into()), @@ -412,9 +407,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &SavePost = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, diff --git a/server/src/api/site.rs b/server/src/api/site.rs index 58c34e8fa..a189a0308 100644 --- a/server/src/api/site.rs +++ b/server/src/api/site.rs @@ -1,4 +1,5 @@ use super::*; +use diesel::PgConnection; use std::str::FromStr; #[derive(Serialize, Deserialize)] @@ -97,9 +98,8 @@ pub struct TransferSite { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let _data: &ListCategories = &self.data; - let conn = establish_connection(); let categories: Vec = Category::list_all(&conn)?; @@ -112,9 +112,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetModlog = &self.data; - let conn = establish_connection(); let removed_posts = ModRemovePostView::list( &conn, @@ -187,9 +186,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &CreateSite = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -234,9 +232,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &EditSite = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -283,9 +280,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let _data: &GetSite = &self.data; - let conn = establish_connection(); // It can return a null site in order to redirect let site_view = match Site::read(&conn, 1) { @@ -314,9 +310,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &Search = &self.data; - let conn = establish_connection(); let sort = SortType::from_str(&data.sort)?; let type_ = SearchType::from_str(&data.type_)?; @@ -419,9 +414,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &TransferSite = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, diff --git a/server/src/api/user.rs b/server/src/api/user.rs index 41729eb75..20eb09c19 100644 --- a/server/src/api/user.rs +++ b/server/src/api/user.rs @@ -2,6 +2,7 @@ use super::*; use crate::settings::Settings; use crate::{generate_random_string, send_email}; use bcrypt::verify; +use diesel::PgConnection; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug)] @@ -167,9 +168,8 @@ pub struct PasswordChange { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &Login = &self.data; - let conn = establish_connection(); // Fetch that username / email let user: User_ = match User_::find_by_email_or_username(&conn, &data.username_or_email) { @@ -192,9 +192,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &Register = &self.data; - let conn = establish_connection(); // Make sure site has open registration if let Ok(site) = SiteView::read(&conn) { @@ -299,9 +298,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &SaveUserSettings = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -378,9 +376,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetUserDetails = &self.data; - let conn = establish_connection(); let user_claims: Option = match &data.auth { Some(auth) => match Claims::decode(&auth) { @@ -470,9 +467,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &AddAdmin = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -535,9 +531,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &BanUser = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -604,9 +599,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetReplies = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -632,9 +626,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &GetUserMentions = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -660,9 +653,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &EditUserMention = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -695,9 +687,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &MarkAllAsRead = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -759,9 +750,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &DeleteAccount = &self.data; - let conn = establish_connection(); let claims = match Claims::decode(&data.auth) { Ok(claims) => claims.claims, @@ -838,9 +828,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &PasswordReset = &self.data; - let conn = establish_connection(); // Fetch that email let user: User_ = match User_::find_by_email(&conn, &data.email) { @@ -872,9 +861,8 @@ impl Perform for Oper { } impl Perform for Oper { - fn perform(&self) -> Result { + fn perform(&self, conn: &PgConnection) -> Result { let data: &PasswordChange = &self.data; - let conn = establish_connection(); // Fetch the user_id from the token let user_id = PasswordResetRequest::read_from_token(&conn, &data.token)?.user_id; diff --git a/server/src/apub/community.rs b/server/src/apub/community.rs index fac6088e4..32f14eeb2 100644 --- a/server/src/apub/community.rs +++ b/server/src/apub/community.rs @@ -1,7 +1,7 @@ use crate::apub::make_apub_endpoint; use crate::db::community::Community; use crate::db::community_view::CommunityFollowerView; -use crate::db::establish_connection; +use crate::db::establish_unpooled_connection; use crate::to_datetime_utc; use activitypub::{actor::Group, collection::UnorderedCollection, context}; use actix_web::body::Body; @@ -62,7 +62,7 @@ impl Community { collection.object_props.set_context_object(context()).ok(); collection.object_props.set_id_string(base_url).ok(); - let connection = establish_connection(); + let connection = establish_unpooled_connection(); //As we are an object, we validated that the community id was valid let community_followers = CommunityFollowerView::for_community(&connection, self.id).unwrap(); @@ -85,7 +85,7 @@ pub struct CommunityQuery { } pub async fn get_apub_community(info: Path) -> HttpResponse { - let connection = establish_connection(); + let connection = establish_unpooled_connection(); if let Ok(community) = Community::read_from_name(&connection, info.community_name.to_owned()) { HttpResponse::Ok() @@ -97,7 +97,7 @@ pub async fn get_apub_community(info: Path) -> HttpResponse) -> HttpResponse { - let connection = establish_connection(); + let connection = establish_unpooled_connection(); if let Ok(community) = Community::read_from_name(&connection, info.community_name.to_owned()) { HttpResponse::Ok() diff --git a/server/src/apub/user.rs b/server/src/apub/user.rs index cf9a9797c..5f2421f11 100644 --- a/server/src/apub/user.rs +++ b/server/src/apub/user.rs @@ -1,5 +1,5 @@ use crate::apub::make_apub_endpoint; -use crate::db::establish_connection; +use crate::db::establish_unpooled_connection; use crate::db::user::User_; use crate::to_datetime_utc; use activitypub::{actor::Person, context}; @@ -62,7 +62,7 @@ pub struct UserQuery { } pub async fn get_apub_user(info: Path) -> HttpResponse { - let connection = establish_connection(); + let connection = establish_unpooled_connection(); if let Ok(user) = User_::find_by_email_or_username(&connection, &info.user_name) { HttpResponse::Ok() diff --git a/server/src/db/category.rs b/server/src/db/category.rs index 6e483ce08..408c8231b 100644 --- a/server/src/db/category.rs +++ b/server/src/db/category.rs @@ -52,7 +52,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let categories = Category::list_all(&conn).unwrap(); let expected_first_category = Category { diff --git a/server/src/db/comment.rs b/server/src/db/comment.rs index b31980522..a9c7d81dd 100644 --- a/server/src/db/comment.rs +++ b/server/src/db/comment.rs @@ -166,7 +166,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "terry".into(), diff --git a/server/src/db/comment_view.rs b/server/src/db/comment_view.rs index 2942bbe74..ba085af64 100644 --- a/server/src/db/comment_view.rs +++ b/server/src/db/comment_view.rs @@ -364,7 +364,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "timmy".into(), diff --git a/server/src/db/community.rs b/server/src/db/community.rs index 09c3ddc4f..b482ca4a9 100644 --- a/server/src/db/community.rs +++ b/server/src/db/community.rs @@ -212,7 +212,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "bobbee".into(), diff --git a/server/src/db/mod.rs b/server/src/db/mod.rs index fe6cb3ce4..c25a64560 100644 --- a/server/src/db/mod.rs +++ b/server/src/db/mod.rs @@ -1,7 +1,6 @@ extern crate lazy_static; use crate::settings::Settings; use diesel::dsl::*; -use diesel::r2d2::*; use diesel::result::Error; use diesel::*; use serde::{Deserialize, Serialize}; @@ -111,19 +110,9 @@ impl MaybeOptional for Option { } } -lazy_static! { - static ref PG_POOL: Pool> = { - let db_url = Settings::get().get_database_url(); - let manager = ConnectionManager::::new(&db_url); - Pool::builder() - .max_size(Settings::get().database.pool_size) - .build(manager) - .unwrap_or_else(|_| panic!("Error connecting to {}", db_url)) - }; -} - -pub fn establish_connection() -> PooledConnection> { - PG_POOL.get().unwrap() +pub fn establish_unpooled_connection() -> PgConnection { + let db_url = Settings::get().get_database_url(); + PgConnection::establish(&db_url).expect(&format!("Error connecting to {}", db_url)) } #[derive(EnumString, ToString, Debug, Serialize, Deserialize)] diff --git a/server/src/db/moderator.rs b/server/src/db/moderator.rs index dc018bd93..3c6233cb9 100644 --- a/server/src/db/moderator.rs +++ b/server/src/db/moderator.rs @@ -434,7 +434,7 @@ mod tests { // use Crud; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_mod = UserForm { name: "the mod".into(), diff --git a/server/src/db/password_reset_request.rs b/server/src/db/password_reset_request.rs index 1664516b3..fa060a591 100644 --- a/server/src/db/password_reset_request.rs +++ b/server/src/db/password_reset_request.rs @@ -84,7 +84,7 @@ mod tests { #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "thommy prw".into(), diff --git a/server/src/db/post.rs b/server/src/db/post.rs index 084edc9bf..d3fba4dad 100644 --- a/server/src/db/post.rs +++ b/server/src/db/post.rs @@ -179,7 +179,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "jim".into(), diff --git a/server/src/db/post_view.rs b/server/src/db/post_view.rs index 0efcab43e..5217e73a7 100644 --- a/server/src/db/post_view.rs +++ b/server/src/db/post_view.rs @@ -290,7 +290,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let user_name = "tegan".to_string(); let community_name = "test_community_3".to_string(); diff --git a/server/src/db/user.rs b/server/src/db/user.rs index b04012974..71b63d742 100644 --- a/server/src/db/user.rs +++ b/server/src/db/user.rs @@ -176,7 +176,7 @@ mod tests { #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "thommy".into(), diff --git a/server/src/db/user_mention.rs b/server/src/db/user_mention.rs index 672867797..21dd1675d 100644 --- a/server/src/db/user_mention.rs +++ b/server/src/db/user_mention.rs @@ -60,7 +60,7 @@ mod tests { use super::*; #[test] fn test_crud() { - let conn = establish_connection(); + let conn = establish_unpooled_connection(); let new_user = UserForm { name: "terrylake".into(), diff --git a/server/src/main.rs b/server/src/main.rs index 763f540fb..ea49cd133 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -3,7 +3,8 @@ extern crate lemmy_server; extern crate diesel_migrations; use actix_web::*; -use lemmy_server::db::establish_connection; +use diesel::r2d2::{ConnectionManager, Pool}; +use diesel::PgConnection; use lemmy_server::routes::{federation, feeds, index, nodeinfo, webfinger, websocket}; use lemmy_server::settings::Settings; use std::io; @@ -13,13 +14,19 @@ embed_migrations!(); #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init(); + let settings = Settings::get(); + + // Set up the r2d2 connection pool + let manager = ConnectionManager::::new(&settings.get_database_url()); + let pool = Pool::builder() + .max_size(settings.database.pool_size) + .build(manager) + .unwrap_or_else(|_| panic!("Error connecting to {}", settings.get_database_url())); // Run the migrations from code - let conn = establish_connection(); + let conn = pool.get().unwrap(); embedded_migrations::run(&conn).unwrap(); - let settings = Settings::get(); - println!( "Starting http server at {}:{}", settings.bind, settings.port @@ -28,12 +35,18 @@ async fn main() -> io::Result<()> { // Create Http server with websocket support HttpServer::new(move || { App::new() + .wrap(middleware::Logger::default()) + .data(pool.clone()) + // The routes .configure(federation::config) .configure(feeds::config) .configure(index::config) .configure(nodeinfo::config) .configure(webfinger::config) .configure(websocket::config) + // .configure(websocket.config(pool)) + // .configure(websocket. + // static files .service(actix_files::Files::new( "/static", settings.front_end_dir.to_owned(), diff --git a/server/src/routes/feeds.rs b/server/src/routes/feeds.rs index ae1631e2d..ad0f28d5a 100644 --- a/server/src/routes/feeds.rs +++ b/server/src/routes/feeds.rs @@ -7,11 +7,12 @@ use crate::db::post_view::{PostQueryBuilder, PostView}; use crate::db::site_view::SiteView; use crate::db::user::{Claims, User_}; use crate::db::user_mention_view::{UserMentionQueryBuilder, UserMentionView}; -use crate::db::{establish_connection, ListingType, SortType}; +use crate::db::{ListingType, SortType}; use crate::Settings; -use actix_web::body::Body; use actix_web::{web, HttpResponse, Result}; use chrono::{DateTime, Utc}; +use diesel::r2d2::{ConnectionManager, Pool}; +use diesel::PgConnection; use failure::Error; use rss::{CategoryBuilder, ChannelBuilder, GuidBuilder, Item, ItemBuilder}; use serde::Deserialize; @@ -37,54 +38,61 @@ pub fn config(cfg: &mut web::ServiceConfig) { .route("/feeds/all.xml", web::get().to(feeds::get_all_feed)); } -async fn get_all_feed(info: web::Query) -> HttpResponse { - let sort_type = match get_sort_type(info) { - Ok(sort_type) => sort_type, - Err(_) => return HttpResponse::BadRequest().finish(), - }; +async fn get_all_feed( + info: web::Query, + db: web::Data>>, +) -> Result { + let res = web::block(move || { + let conn = db.get()?; - let feed_result = get_feed_all_data(&sort_type); - - match feed_result { - Ok(rss) => HttpResponse::Ok() + let sort_type = get_sort_type(info)?; + get_feed_all_data(&conn, &sort_type) + }) + .await + .map(|rss| { + HttpResponse::Ok() .content_type("application/rss+xml") - .body(rss), - Err(_) => HttpResponse::NotFound().finish(), - } + .body(rss) + }) + .map_err(|_| HttpResponse::InternalServerError())?; + Ok(res) } async fn get_feed( path: web::Path<(String, String)>, info: web::Query, -) -> HttpResponse { - let sort_type = match get_sort_type(info) { - Ok(sort_type) => sort_type, - Err(_) => return HttpResponse::BadRequest().finish(), - }; + db: web::Data>>, +) -> Result { + let res = web::block(move || { + let conn = db.get()?; - let request_type = match path.0.as_ref() { - "u" => RequestType::User, - "c" => RequestType::Community, - "front" => RequestType::Front, - "inbox" => RequestType::Inbox, - _ => return HttpResponse::NotFound().finish(), - }; + let sort_type = get_sort_type(info)?; - let param = path.1.to_owned(); + let request_type = match path.0.as_ref() { + "u" => RequestType::User, + "c" => RequestType::Community, + "front" => RequestType::Front, + "inbox" => RequestType::Inbox, + _ => return Err(format_err!("wrong_type")), + }; - let feed_result = match request_type { - RequestType::User => get_feed_user(&sort_type, param), - RequestType::Community => get_feed_community(&sort_type, param), - RequestType::Front => get_feed_front(&sort_type, param), - RequestType::Inbox => get_feed_inbox(param), - }; + let param = path.1.to_owned(); - match feed_result { - Ok(rss) => HttpResponse::Ok() + 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(|rss| { + HttpResponse::Ok() .content_type("application/rss+xml") - .body(rss), - Err(_) => HttpResponse::NotFound().finish(), - } + .body(rss) + }) + .map_err(|_| HttpResponse::InternalServerError())?; + Ok(res) } fn get_sort_type(info: web::Query) -> Result { @@ -95,9 +103,7 @@ fn get_sort_type(info: web::Query) -> Result { SortType::from_str(&sort_query) } -fn get_feed_all_data(sort_type: &SortType) -> Result { - let conn = establish_connection(); - +fn get_feed_all_data(conn: &PgConnection, sort_type: &SortType) -> Result { let site_view = SiteView::read(&conn)?; let posts = PostQueryBuilder::create(&conn) @@ -120,9 +126,11 @@ fn get_feed_all_data(sort_type: &SortType) -> Result { Ok(channel_builder.build().unwrap().to_string()) } -fn get_feed_user(sort_type: &SortType, user_name: String) -> Result { - let conn = establish_connection(); - +fn get_feed_user( + conn: &PgConnection, + sort_type: &SortType, + user_name: String, +) -> Result { let site_view = SiteView::read(&conn)?; let user = User_::find_by_username(&conn, &user_name)?; let user_url = user.get_profile_url(); @@ -144,9 +152,11 @@ fn get_feed_user(sort_type: &SortType, user_name: String) -> Result Result { - let conn = establish_connection(); - +fn get_feed_community( + conn: &PgConnection, + sort_type: &SortType, + community_name: String, +) -> Result { let site_view = SiteView::read(&conn)?; let community = Community::read_from_name(&conn, community_name)?; let community_url = community.get_url(); @@ -172,9 +182,7 @@ fn get_feed_community(sort_type: &SortType, community_name: String) -> Result Result { - let conn = establish_connection(); - +fn get_feed_front(conn: &PgConnection, sort_type: &SortType, jwt: String) -> Result { let site_view = SiteView::read(&conn)?; let user_id = Claims::decode(&jwt)?.claims.id; @@ -199,9 +207,7 @@ fn get_feed_front(sort_type: &SortType, jwt: String) -> Result { Ok(channel_builder.build().unwrap().to_string()) } -fn get_feed_inbox(jwt: String) -> Result { - let conn = establish_connection(); - +fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result { let site_view = SiteView::read(&conn)?; let user_id = Claims::decode(&jwt)?.claims.id; diff --git a/server/src/routes/nodeinfo.rs b/server/src/routes/nodeinfo.rs index 2b7135fba..6ab540f9e 100644 --- a/server/src/routes/nodeinfo.rs +++ b/server/src/routes/nodeinfo.rs @@ -1,10 +1,11 @@ -use crate::db::establish_connection; use crate::db::site_view::SiteView; use crate::version; use crate::Settings; use actix_web::body::Body; use actix_web::web; use actix_web::HttpResponse; +use diesel::r2d2::{ConnectionManager, Pool}; +use diesel::PgConnection; use serde_json::json; pub fn config(cfg: &mut web::ServiceConfig) { @@ -26,34 +27,39 @@ async fn node_info_well_known() -> HttpResponse { .body(json.to_string()) } -async fn node_info() -> HttpResponse { - let conn = establish_connection(); - let site_view = match SiteView::read(&conn) { - Ok(site_view) => site_view, - Err(_e) => return HttpResponse::InternalServerError().finish(), - }; - let protocols = if Settings::get().federation_enabled { - vec!["activitypub"] - } else { - vec![] - }; - let json = json!({ - "version": "2.0", - "software": { - "name": "lemmy", - "version": version::VERSION, - }, - "protocols": protocols, - "usage": { - "users": { - "total": site_view.number_of_users +async fn node_info( + db: web::Data>>, +) -> Result { + let res = web::block(move || { + let conn = db.get()?; + let site_view = match SiteView::read(&conn) { + Ok(site_view) => site_view, + Err(_) => return Err(format_err!("not_found")), + }; + let protocols = if Settings::get().federation_enabled { + vec!["activitypub"] + } else { + vec![] + }; + Ok(json!({ + "version": "2.0", + "software": { + "name": "lemmy", + "version": version::VERSION, }, - "localPosts": site_view.number_of_posts, - "localComments": site_view.number_of_comments, - "openRegistrations": site_view.open_registration, + "protocols": protocols, + "usage": { + "users": { + "total": site_view.number_of_users + }, + "localPosts": site_view.number_of_posts, + "localComments": site_view.number_of_comments, + "openRegistrations": site_view.open_registration, } - }); - HttpResponse::Ok() - .content_type("application/json") - .body(json.to_string()) + })) + }) + .await + .map(|json| HttpResponse::Ok().json(json)) + .map_err(|_| HttpResponse::InternalServerError())?; + Ok(res) } diff --git a/server/src/routes/webfinger.rs b/server/src/routes/webfinger.rs index c538f5b1d..20f76a9ad 100644 --- a/server/src/routes/webfinger.rs +++ b/server/src/routes/webfinger.rs @@ -1,10 +1,10 @@ use crate::db::community::Community; -use crate::db::establish_connection; use crate::Settings; -use actix_web::body::Body; use actix_web::web; use actix_web::web::Query; use actix_web::HttpResponse; +use diesel::r2d2::{ConnectionManager, Pool}; +use diesel::PgConnection; use regex::Regex; use serde::Deserialize; use serde_json::json; @@ -37,54 +37,61 @@ lazy_static! { /// /// You can also view the webfinger response that Mastodon sends: /// https://radical.town/.well-known/webfinger?resource=acct:felix@radical.town -async fn get_webfinger_response(info: Query) -> HttpResponse { - let regex_parsed = WEBFINGER_COMMUNITY_REGEX - .captures(&info.resource) - .map(|c| c.get(1)); - // TODO: replace this with .flatten() once we are running rust 1.40 - let regex_parsed_flattened = match regex_parsed { - Some(s) => s, - None => None, - }; - let community_name = match regex_parsed_flattened { - Some(c) => c.as_str(), - None => return HttpResponse::NotFound().finish(), - }; +async fn get_webfinger_response( + info: Query, + db: web::Data>>, +) -> Result { + let res = web::block(move || { + let conn = db.get()?; - // Make sure the requested community exists. - let conn = establish_connection(); - let community = match Community::read_from_name(&conn, community_name.to_string()) { - Ok(o) => o, - Err(_) => return HttpResponse::NotFound().finish(), - }; + let regex_parsed = WEBFINGER_COMMUNITY_REGEX + .captures(&info.resource) + .map(|c| c.get(1)); + // TODO: replace this with .flatten() once we are running rust 1.40 + let regex_parsed_flattened = match regex_parsed { + Some(s) => s, + None => None, + }; + let community_name = match regex_parsed_flattened { + Some(c) => c.as_str(), + None => return Err(format_err!("not_found")), + }; - let community_url = community.get_url(); + // Make sure the requested community exists. + let community = match Community::read_from_name(&conn, community_name.to_string()) { + Ok(o) => o, + Err(_) => return Err(format_err!("not_found")), + }; - let json = json!({ + let community_url = community.get_url(); + + Ok(json!({ "subject": info.resource, "aliases": [ community_url, ], "links": [ - { - "rel": "http://webfinger.net/rel/profile-page", - "type": "text/html", - "href": community_url - }, - { - "rel": "self", - "type": "application/activity+json", - // Yes this is correct, this link doesn't include the `.json` extension - "href": community_url - } - // TODO: this also needs to return the subscribe link once that's implemented - //{ - // "rel": "http://ostatus.org/schema/1.0/subscribe", - // "template": "https://my_instance.com/authorize_interaction?uri={uri}" - //} + { + "rel": "http://webfinger.net/rel/profile-page", + "type": "text/html", + "href": community_url + }, + { + "rel": "self", + "type": "application/activity+json", + // Yes this is correct, this link doesn't include the `.json` extension + "href": community_url + } + // TODO: this also needs to return the subscribe link once that's implemented + //{ + // "rel": "http://ostatus.org/schema/1.0/subscribe", + // "template": "https://my_instance.com/authorize_interaction?uri={uri}" + //} ] - }); - HttpResponse::Ok() - .content_type("application/activity+json") - .body(json.to_string()) + })) + }) + .await + .map(|json| HttpResponse::Ok().json(json)) + .map_err(|_| HttpResponse::InternalServerError())?; + Ok(res) } diff --git a/server/src/routes/websocket.rs b/server/src/routes/websocket.rs index 8113a613e..0d953d243 100644 --- a/server/src/routes/websocket.rs +++ b/server/src/routes/websocket.rs @@ -1,13 +1,24 @@ use crate::websocket::server::*; +use crate::Settings; use actix::prelude::*; use actix_web::web; use actix_web::*; use actix_web_actors::ws; +use diesel::r2d2::{ConnectionManager, Pool}; +use diesel::PgConnection; use std::time::{Duration, Instant}; pub fn config(cfg: &mut web::ServiceConfig) { + // TODO couldn't figure out how to get this method to recieve the other pool + let settings = Settings::get(); + let manager = ConnectionManager::::new(&settings.get_database_url()); + let pool = Pool::builder() + .max_size(settings.database.pool_size) + .build(manager) + .unwrap_or_else(|_| panic!("Error connecting to {}", settings.get_database_url())); + // Start chat server actor in separate thread - let server = ChatServer::default().start(); + let server = ChatServer::startup(pool).start(); cfg .data(server) .service(web::resource("/api/v1/ws").to(chat_route)); @@ -24,9 +35,11 @@ async fn chat_route( stream: web::Payload, chat_server: web::Data>, ) -> Result { + // TODO not sure if the blocking should be here or not ws::start( WSSession { - cs_addr: chat_server.get_ref().to_owned(), + // db: db.get_ref().clone(), + cs_addr: chat_server.get_ref().clone(), id: 0, hb: Instant::now(), ip: req @@ -51,6 +64,7 @@ struct WSSession { /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT), /// otherwise we drop connection. hb: Instant, + // db: Pool>, } impl Actor for WSSession { @@ -127,7 +141,7 @@ impl StreamHandler> for WSSession { } ws::Message::Text(text) => { let m = text.trim().to_owned(); - println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id); + // println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id); self .cs_addr diff --git a/server/src/websocket/server.rs b/server/src/websocket/server.rs index b9dad9a4b..006169dfb 100644 --- a/server/src/websocket/server.rs +++ b/server/src/websocket/server.rs @@ -3,6 +3,8 @@ //! room through `ChatServer`. use actix::prelude::*; +use diesel::r2d2::{ConnectionManager, Pool}; +use diesel::PgConnection; use failure::Error; use rand::{rngs::ThreadRng, Rng}; use serde::{Deserialize, Serialize}; @@ -42,6 +44,7 @@ pub struct Disconnect { pub ip: String, } +// TODO this is unused rn /// Send message to specific room #[derive(Message)] #[rtype(result = "()")] @@ -81,10 +84,26 @@ pub struct ChatServer { rate_limits: HashMap, rooms: HashMap>, // A map from room / post name to set of connectionIDs rng: ThreadRng, + db: Pool>, } -impl Default for ChatServer { - fn default() -> ChatServer { +// impl Default for ChatServer { +// fn default(nah: String) -> ChatServer { +// // default room +// let rooms = HashMap::new(); + +// ChatServer { +// sessions: HashMap::new(), +// rate_limits: HashMap::new(), +// rooms, +// rng: rand::thread_rng(), +// nah: nah, +// } +// } +// } + +impl ChatServer { + pub fn startup(db: Pool>) -> ChatServer { // default room let rooms = HashMap::new(); @@ -93,11 +112,10 @@ impl Default for ChatServer { rate_limits: HashMap::new(), rooms, rng: rand::thread_rng(), + db, } } -} -impl ChatServer { /// Send message to all users in the room fn send_room_message(&self, room: i32, message: &str, skip_id: usize) { if let Some(sessions) = self.rooms.get(&room) { @@ -133,7 +151,8 @@ impl ChatServer { ) -> Result<(), Error> { use crate::db::post_view::*; use crate::db::*; - let conn = establish_connection(); + + let conn = self.db.get()?; let posts = PostQueryBuilder::create(&conn) .listing_type(ListingType::Community) @@ -299,17 +318,19 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let login: Login = serde_json::from_str(data)?; - let res = Oper::new(user_operation, login).perform()?; + let res = Oper::new(user_operation, login).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::Register => { let register: Register = serde_json::from_str(data)?; - let res = Oper::new(user_operation, register).perform(); + let res = Oper::new(user_operation, register).perform(&conn); if res.is_ok() { chat.check_rate_limit_register(msg.id)?; } @@ -317,63 +338,63 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let get_user_details: GetUserDetails = serde_json::from_str(data)?; - let res = Oper::new(user_operation, get_user_details).perform()?; + let res = Oper::new(user_operation, get_user_details).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::SaveUserSettings => { let save_user_settings: SaveUserSettings = serde_json::from_str(data)?; - let res = Oper::new(user_operation, save_user_settings).perform()?; + let res = Oper::new(user_operation, save_user_settings).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::AddAdmin => { let add_admin: AddAdmin = serde_json::from_str(data)?; - let res = Oper::new(user_operation, add_admin).perform()?; + let res = Oper::new(user_operation, add_admin).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::BanUser => { let ban_user: BanUser = serde_json::from_str(data)?; - let res = Oper::new(user_operation, ban_user).perform()?; + let res = Oper::new(user_operation, ban_user).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetReplies => { let get_replies: GetReplies = serde_json::from_str(data)?; - let res = Oper::new(user_operation, get_replies).perform()?; + let res = Oper::new(user_operation, get_replies).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetUserMentions => { let get_user_mentions: GetUserMentions = serde_json::from_str(data)?; - let res = Oper::new(user_operation, get_user_mentions).perform()?; + let res = Oper::new(user_operation, get_user_mentions).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::EditUserMention => { let edit_user_mention: EditUserMention = serde_json::from_str(data)?; - let res = Oper::new(user_operation, edit_user_mention).perform()?; + let res = Oper::new(user_operation, edit_user_mention).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::MarkAllAsRead => { let mark_all_as_read: MarkAllAsRead = serde_json::from_str(data)?; - let res = Oper::new(user_operation, mark_all_as_read).perform()?; + let res = Oper::new(user_operation, mark_all_as_read).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetCommunity => { let get_community: GetCommunity = serde_json::from_str(data)?; - let res = Oper::new(user_operation, get_community).perform()?; + let res = Oper::new(user_operation, get_community).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::ListCommunities => { let list_communities: ListCommunities = serde_json::from_str(data)?; - let res = Oper::new(user_operation, list_communities).perform()?; + let res = Oper::new(user_operation, list_communities).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::CreateCommunity => { chat.check_rate_limit_register(msg.id)?; let create_community: CreateCommunity = serde_json::from_str(data)?; - let res = Oper::new(user_operation, create_community).perform()?; + let res = Oper::new(user_operation, create_community).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::EditCommunity => { let edit_community: EditCommunity = serde_json::from_str(data)?; - let res = Oper::new(user_operation, edit_community).perform()?; + let res = Oper::new(user_operation, edit_community).perform(&conn)?; let mut community_sent: CommunityResponse = res.clone(); community_sent.community.user_id = None; community_sent.community.subscribed = None; @@ -383,18 +404,18 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let follow_community: FollowCommunity = serde_json::from_str(data)?; - let res = Oper::new(user_operation, follow_community).perform()?; + let res = Oper::new(user_operation, follow_community).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetFollowedCommunities => { let followed_communities: GetFollowedCommunities = serde_json::from_str(data)?; - let res = Oper::new(user_operation, followed_communities).perform()?; + let res = Oper::new(user_operation, followed_communities).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::BanFromCommunity => { let ban_from_community: BanFromCommunity = serde_json::from_str(data)?; let community_id = ban_from_community.community_id; - let res = Oper::new(user_operation, ban_from_community).perform()?; + let res = Oper::new(user_operation, ban_from_community).perform(&conn)?; let res_str = serde_json::to_string(&res)?; chat.send_community_message(community_id, &res_str, msg.id)?; Ok(res_str) @@ -402,42 +423,42 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let mod_add_to_community: AddModToCommunity = serde_json::from_str(data)?; let community_id = mod_add_to_community.community_id; - let res = Oper::new(user_operation, mod_add_to_community).perform()?; + let res = Oper::new(user_operation, mod_add_to_community).perform(&conn)?; let res_str = serde_json::to_string(&res)?; chat.send_community_message(community_id, &res_str, msg.id)?; Ok(res_str) } UserOperation::ListCategories => { let list_categories: ListCategories = ListCategories; - let res = Oper::new(user_operation, list_categories).perform()?; + let res = Oper::new(user_operation, list_categories).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::CreatePost => { chat.check_rate_limit_post(msg.id)?; let create_post: CreatePost = serde_json::from_str(data)?; - let res = Oper::new(user_operation, create_post).perform()?; + let res = Oper::new(user_operation, create_post).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetPost => { let get_post: GetPost = serde_json::from_str(data)?; chat.join_room(get_post.id, msg.id); - let res = Oper::new(user_operation, get_post).perform()?; + let res = Oper::new(user_operation, get_post).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetPosts => { let get_posts: GetPosts = serde_json::from_str(data)?; - let res = Oper::new(user_operation, get_posts).perform()?; + let res = Oper::new(user_operation, get_posts).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::CreatePostLike => { chat.check_rate_limit_message(msg.id)?; let create_post_like: CreatePostLike = serde_json::from_str(data)?; - let res = Oper::new(user_operation, create_post_like).perform()?; + let res = Oper::new(user_operation, create_post_like).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::EditPost => { let edit_post: EditPost = serde_json::from_str(data)?; - let res = Oper::new(user_operation, edit_post).perform()?; + let res = Oper::new(user_operation, edit_post).perform(&conn)?; let mut post_sent = res.clone(); post_sent.post.my_vote = None; let post_sent_str = serde_json::to_string(&post_sent)?; @@ -446,14 +467,14 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let save_post: SavePost = serde_json::from_str(data)?; - let res = Oper::new(user_operation, save_post).perform()?; + let res = Oper::new(user_operation, save_post).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::CreateComment => { chat.check_rate_limit_message(msg.id)?; let create_comment: CreateComment = serde_json::from_str(data)?; let post_id = create_comment.post_id; - let res = Oper::new(user_operation, create_comment).perform()?; + let res = Oper::new(user_operation, create_comment).perform(&conn)?; let mut comment_sent = res.clone(); comment_sent.comment.my_vote = None; comment_sent.comment.user_id = None; @@ -464,7 +485,7 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let edit_comment: EditComment = serde_json::from_str(data)?; let post_id = edit_comment.post_id; - let res = Oper::new(user_operation, edit_comment).perform()?; + let res = Oper::new(user_operation, edit_comment).perform(&conn)?; let mut comment_sent = res.clone(); comment_sent.comment.my_vote = None; comment_sent.comment.user_id = None; @@ -474,14 +495,14 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let save_comment: SaveComment = serde_json::from_str(data)?; - let res = Oper::new(user_operation, save_comment).perform()?; + let res = Oper::new(user_operation, save_comment).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::CreateCommentLike => { chat.check_rate_limit_message(msg.id)?; let create_comment_like: CreateCommentLike = serde_json::from_str(data)?; let post_id = create_comment_like.post_id; - let res = Oper::new(user_operation, create_comment_like).perform()?; + let res = Oper::new(user_operation, create_comment_like).perform(&conn)?; let mut comment_sent = res.clone(); comment_sent.comment.my_vote = None; comment_sent.comment.user_id = None; @@ -491,54 +512,54 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { let get_modlog: GetModlog = serde_json::from_str(data)?; - let res = Oper::new(user_operation, get_modlog).perform()?; + let res = Oper::new(user_operation, get_modlog).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::CreateSite => { let create_site: CreateSite = serde_json::from_str(data)?; - let res = Oper::new(user_operation, create_site).perform()?; + let res = Oper::new(user_operation, create_site).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::EditSite => { let edit_site: EditSite = serde_json::from_str(data)?; - let res = Oper::new(user_operation, edit_site).perform()?; + let res = Oper::new(user_operation, edit_site).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::GetSite => { let online: usize = chat.sessions.len(); let get_site: GetSite = serde_json::from_str(data)?; - let mut res = Oper::new(user_operation, get_site).perform()?; + let mut res = Oper::new(user_operation, get_site).perform(&conn)?; res.online = online; Ok(serde_json::to_string(&res)?) } UserOperation::Search => { let search: Search = serde_json::from_str(data)?; - let res = Oper::new(user_operation, search).perform()?; + let res = Oper::new(user_operation, search).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::TransferCommunity => { let transfer_community: TransferCommunity = serde_json::from_str(data)?; - let res = Oper::new(user_operation, transfer_community).perform()?; + let res = Oper::new(user_operation, transfer_community).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::TransferSite => { let transfer_site: TransferSite = serde_json::from_str(data)?; - let res = Oper::new(user_operation, transfer_site).perform()?; + let res = Oper::new(user_operation, transfer_site).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::DeleteAccount => { let delete_account: DeleteAccount = serde_json::from_str(data)?; - let res = Oper::new(user_operation, delete_account).perform()?; + let res = Oper::new(user_operation, delete_account).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::PasswordReset => { let password_reset: PasswordReset = serde_json::from_str(data)?; - let res = Oper::new(user_operation, password_reset).perform()?; + let res = Oper::new(user_operation, password_reset).perform(&conn)?; Ok(serde_json::to_string(&res)?) } UserOperation::PasswordChange => { let password_change: PasswordChange = serde_json::from_str(data)?; - let res = Oper::new(user_operation, password_change).perform()?; + let res = Oper::new(user_operation, password_change).perform(&conn)?; Ok(serde_json::to_string(&res)?) } }