From c2e3b2d52ec8cbb23408e646dd2418dab4d07eed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 23 Nov 2026 20:29:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20simplify=20eve?= =?UTF-8?q?ry=20crate=20and=20move=20the=20server=20to=20turso?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collapse request/response wrappers into enum variants, give models pub fields, merge errors and validation into single sources, and replace SurrealDB with turso. Forbid unsafe and use line-tables-only debug info workspace-wide. --- Cargo.toml | 11 +- configs/server_config.example.toml | 7 +- crates/client/Cargo.toml | 7 +- crates/client/src/event.rs | 39 -- crates/client/src/gui.rs | 158 +++-- crates/client/src/gui/auth.rs | 91 +++ crates/client/src/gui/chat.rs | 702 +++++++++---------- crates/client/src/gui/login.rs | 100 --- crates/client/src/gui/register.rs | 99 --- crates/client/src/lib.rs | 13 +- crates/client/src/main.rs | 8 +- crates/client/src/network.rs | 412 +++++++---- crates/client/src/request.rs | 297 -------- crates/common/Cargo.toml | 7 +- crates/common/src/community.rs | 28 - crates/common/src/config.rs | 20 + crates/common/src/error.rs | 131 +++- crates/common/src/error/community.rs | 32 - crates/common/src/error/decode.rs | 24 - crates/common/src/error/file_operation.rs | 24 - crates/common/src/error/macro_.rs | 56 -- crates/common/src/error/message.rs | 32 - crates/common/src/error/network.rs | 58 -- crates/common/src/error/user.rs | 32 - crates/common/src/event.rs | 14 - crates/common/src/lib.rs | 7 +- crates/common/src/message.rs | 42 -- crates/common/src/model.rs | 21 + crates/common/src/network.rs | 111 ++- crates/common/src/request.rs | 85 +-- crates/common/src/request/community.rs | 100 --- crates/common/src/request/message.rs | 130 ---- crates/common/src/request/user.rs | 79 --- crates/common/src/request/user_community.rs | 113 --- crates/common/src/response.rs | 13 +- crates/common/src/response/community.rs | 0 crates/common/src/response/message.rs | 0 crates/common/src/response/user.rs | 0 crates/common/src/user.rs | 25 - crates/common/src/utils.rs | 57 -- crates/common/src/validate.rs | 86 ++- crates/server/Cargo.toml | 16 +- crates/server/src/authentication.rs | 34 +- crates/server/src/community.rs | 297 +++----- crates/server/src/community/database.rs | 67 -- crates/server/src/database.rs | 57 ++ crates/server/src/database_.rs | 81 --- crates/server/src/error.rs | 46 +- crates/server/src/error/database.rs | 30 - crates/server/src/lib.rs | 38 +- crates/server/src/main.rs | 2 - crates/server/src/message.rs | 528 ++++---------- crates/server/src/message/database.rs | 104 --- crates/server/src/network.rs | 219 +++--- crates/server/src/request.rs | 341 +++------ crates/server/src/test.rs | 27 +- crates/server/src/user.rs | 277 +++----- crates/server/src/user/database.rs | 61 -- crates/server/src/user_community.rs | 295 +++----- crates/server/src/user_community/database.rs | 105 --- 60 files changed, 1745 insertions(+), 4151 deletions(-) delete mode 100644 crates/client/src/event.rs create mode 100644 crates/client/src/gui/auth.rs delete mode 100644 crates/client/src/gui/login.rs delete mode 100644 crates/client/src/gui/register.rs delete mode 100644 crates/client/src/request.rs delete mode 100644 crates/common/src/community.rs create mode 100644 crates/common/src/config.rs delete mode 100644 crates/common/src/error/community.rs delete mode 100644 crates/common/src/error/decode.rs delete mode 100644 crates/common/src/error/file_operation.rs delete mode 100644 crates/common/src/error/macro_.rs delete mode 100644 crates/common/src/error/message.rs delete mode 100644 crates/common/src/error/network.rs delete mode 100644 crates/common/src/error/user.rs delete mode 100644 crates/common/src/event.rs delete mode 100644 crates/common/src/message.rs create mode 100644 crates/common/src/model.rs delete mode 100644 crates/common/src/request/community.rs delete mode 100644 crates/common/src/request/message.rs delete mode 100644 crates/common/src/request/user.rs delete mode 100644 crates/common/src/request/user_community.rs delete mode 100644 crates/common/src/response/community.rs delete mode 100644 crates/common/src/response/message.rs delete mode 100644 crates/common/src/response/user.rs delete mode 100644 crates/common/src/user.rs delete mode 100644 crates/common/src/utils.rs delete mode 100644 crates/server/src/community/database.rs create mode 100644 crates/server/src/database.rs delete mode 100644 crates/server/src/database_.rs delete mode 100644 crates/server/src/error/database.rs delete mode 100644 crates/server/src/message/database.rs delete mode 100644 crates/server/src/user/database.rs delete mode 100644 crates/server/src/user_community/database.rs diff --git a/Cargo.toml b/Cargo.toml index c1cc5b5..5960ca9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,19 +2,24 @@ resolver = "2" members = ["crates/client", "crates/common", "crates/server"] +[profile.dev] +debug = "line-tables-only" + [profile.release] opt-level = 3 lto = "fat" codegen-units = 1 panic = "abort" -strip = "symbols" -debug = false +debug = "line-tables-only" overflow-checks = false incremental = false +[workspace.lints.rust] +unsafe_code = "forbid" + [workspace.dependencies] common = { path = "crates/common" } -tokio = { version = "1.53.1", features = ["full"] } +tokio = { version = "1.54.1", features = ["full"] } bitcode = "0.6.9" quinn = { version = "0.11.12", default-features = false, features = [ "runtime-tokio", diff --git a/configs/server_config.example.toml b/configs/server_config.example.toml index 0c7cbf4..179d6e5 100644 --- a/configs/server_config.example.toml +++ b/configs/server_config.example.toml @@ -1,8 +1,3 @@ [server_config] -database_prefix = "wss" -database_address = "127.0.0.1:8000" -namespace = "yumush" -database = "yumush" -username = "yumush" -password = "yumush" +database_path = "yumush.db" server_address = "127.0.0.1:2026" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 0b1c317..e95c430 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -4,8 +4,11 @@ version = "0.1.0" edition = "2024" [dependencies] -common = { workspace = true, features = ["client"] } +common.workspace = true tokio.workspace = true -quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } +quinn = { workspace = true, features = ["rustls-ring"] } gpui-kit = "0.7.0" + +[lints] +workspace = true diff --git a/crates/client/src/event.rs b/crates/client/src/event.rs deleted file mode 100644 index 334cc01..0000000 --- a/crates/client/src/event.rs +++ /dev/null @@ -1,39 +0,0 @@ -use std::time::Duration; - -use gpui_kit::{Context, Window}; - -use crate::gui::Yumush; - -const CHECK_INTERVAL: Duration = Duration::from_secs(3); - -impl Yumush { - pub fn time_based_repetitive_checks_after_login( - &self, - window: &mut Window, - cx: &mut Context, - ) { - cx.spawn_in(window, async move |this, cx| { - loop { - cx.background_executor().timer(CHECK_INTERVAL).await; - - let keep_going = this.update_in(cx, |yumush, window, cx| { - if !yumush.is_logged_in() { - return false; - } - - if yumush.is_connected() { - yumush.get_chat_users(window, cx); - yumush.get_communities(window, cx); - } - - true - }); - - if !matches!(keep_going, Ok(true)) { - break; - } - } - }) - .detach(); - } -} diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 9073a22..6885e1e 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1,31 +1,38 @@ -use common::user::User; +use std::fmt::Display; +use std::time::Duration; + +use common::model::User; use gpui_kit::{ - Context, IntoElement, ParentElement, Render, Styled, Window, - component::{ActiveTheme, WindowExt, button::Button, notification::Notification}, + AppContext, AsyncWindowContext, Context, Entity, IntoElement, ParentElement, Render, Styled, + WeakEntity, Window, + component::{ + ActiveTheme, WindowExt, button::Button, input::InputState, notification::Notification, + }, div, rgb, }; use tokio::sync::mpsc; -use crate::{ - gui::{chat::Chat, login::Login, register::Register}, - network::{NetworkEvent, NetworkHandle}, -}; +use crate::network::{NetworkEvent, NetworkHandle}; + +mod auth; mod chat; -mod login; -mod register; -#[derive(Debug, PartialEq, Eq)] +use auth::Auth; +use chat::Chat; + +const CHECK_INTERVAL: Duration = Duration::from_secs(3); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Route { - Register, Login, + Register, Chat, } pub struct Yumush { user: Option, current_route: Route, - register: Register, - login: Login, + auth: Auth, chat: Chat, network: NetworkHandle, connected: bool, @@ -54,65 +61,62 @@ impl Yumush { Self { user: None, current_route: Route::Login, - register: Register::new(window, cx), - login: Login::new(window, cx), + auth: Auth::new(window, cx), chat: Chat::new(window, cx), network, connected: false, } } - fn set_user(&mut self, user: User) { - self.user = Some(user); - } - - fn get_user(&self) -> Option { - self.user.clone() - } + fn start_polling(&self, window: &mut Window, cx: &mut Context) { + cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(CHECK_INTERVAL).await; - fn reset_user(&mut self) { - self.user = None; - } + let keep_going = this.update_in(cx, |yumush, window, cx| { + if yumush.user.is_none() { + return false; + } - pub fn is_connected(&self) -> bool { - self.connected - } + if yumush.connected { + yumush.get_chat_users(window, cx); + yumush.get_communities(window, cx); + } - pub fn is_logged_in(&self) -> bool { - self.user.is_some() - } + true + }); - fn get_username(&self) -> Option<&str> { - self.user.as_ref().map(|user| user.get_username()) + if !matches!(keep_going, Ok(true)) { + break; + } + } + }) + .detach(); } fn logout(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user) = self.get_user() else { + let Some(user) = self.user.take() else { return; }; let network = self.network.clone(); - self.reset_user(); self.chat.reset(); self.change_page(Route::Login, window, cx); cx.spawn_in(window, async move |this, cx| { - if let Err(error_value) = network.deauthenticate(user.get_username()).await { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); + if let Err(error) = network.deauthenticate(&user.username).await { + notify_error(&this, cx, error); } }) .detach(); } - fn change_page(&mut self, new_route: Route, window: &mut Window, cx: &mut Context) { - self.current_route = new_route; + fn change_page(&mut self, route: Route, window: &mut Window, cx: &mut Context) { + self.current_route = route; cx.notify(); - match self.current_route { - Route::Register => self.register.focus(window, cx), - Route::Login => self.login.focus(window, cx), + match route { + Route::Login | Route::Register => self.auth.focus(window, cx), Route::Chat => self.chat.focus(window, cx), } } @@ -127,9 +131,9 @@ impl Yumush { NetworkEvent::Connected(user) => { self.connected = true; match user { - Some(user) => self.set_user(user), - None if self.is_logged_in() => { - self.reset_user(); + Some(user) => self.user = Some(user), + None if self.user.is_some() => { + self.user = None; self.change_page(Route::Login, window, cx); } None => {} @@ -138,15 +142,49 @@ impl Yumush { NetworkEvent::ConnectionFailed(_) | NetworkEvent::Disconnected(_) => { self.connected = false; } - NetworkEvent::MessageReceived(message) => self.chat.push_message(message), + NetworkEvent::MessageReceived(message) => self.chat.merge_messages(vec![message]), } cx.notify(); } } +pub fn notify_error( + this: &WeakEntity, + cx: &mut AsyncWindowContext, + error: impl Display, +) { + let _ = this.update_in(cx, |_, window, cx| { + window.push_notification(Notification::error(error.to_string()), cx); + }); +} + +fn new_input( + placeholder: &'static str, + window: &mut Window, + cx: &mut Context, +) -> Entity { + cx.new(|cx| { + let mut input_state = InputState::new(window, cx); + input_state.set_placeholder(placeholder, window, cx); + + input_state + }) +} + impl Render for Yumush { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let route = self.current_route; + let page = match route { + Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(), + Route::Chat => self.chat_page(cx).into_any_element(), + }; + let status_color = if self.connected { + rgb(0x22c55e) + } else { + rgb(0xef4444) + }; + div() .size_full() .relative() @@ -159,11 +197,7 @@ impl Render for Yumush { .size_full() .bg(rgb(0x1e1e1e)) .text_color(cx.theme().foreground) - .child(match self.current_route { - Route::Register => self.register_page(cx).into_any_element(), - Route::Login => self.login_page(cx).into_any_element(), - Route::Chat => self.chat_page(cx).into_any_element(), - }), + .child(page), ) .child( div() @@ -174,20 +208,12 @@ impl Render for Yumush { .flex_row() .items_center() .gap_2() - .child( - div() - .text_color(if self.connected { - rgb(0x22c55e) - } else { - rgb(0xef4444) - }) - .child(format!( - "{:?} is {}", - self.get_username(), - if self.connected { "online" } else { "offline" } - )), + .children( + self.user.as_ref().map(|user| { + div().text_color(status_color).child(user.username.clone()) + }), ) - .children(self.is_logged_in().then(|| { + .children(self.user.is_some().then(|| { let entity = cx.entity(); Button::new("logout_button").label("Logout").on_click( diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs new file mode 100644 index 0000000..55a6b10 --- /dev/null +++ b/crates/client/src/gui/auth.rs @@ -0,0 +1,91 @@ +use gpui_kit::{ + Context, Entity, IntoElement, ParentElement, Styled, Window, + component::{ + button::Button, + input::{Input, InputEvent, InputState}, + }, + div, +}; + +use crate::gui::{Route, Yumush, new_input, notify_error}; + +pub struct Auth { + username_input: Entity, +} + +impl Auth { + pub fn new(window: &mut Window, cx: &mut Context) -> Self { + let username_input = new_input("Username...", window, cx); + username_input.update(cx, |input, cx| input.focus(window, cx)); + + cx.subscribe_in(&username_input, window, |this, _, event, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + submit(this, window, cx); + } + }) + .detach(); + + Self { username_input } + } + + pub fn focus(&self, window: &mut Window, cx: &mut Context) { + self.username_input + .update(cx, |input, cx| input.focus(window, cx)); + } +} + +fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { + let username = this.auth.username_input.read(cx).text().to_string(); + let route = this.current_route; + let network = this.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let result = match route { + Route::Register => network.create_user(&username).await, + _ => network.authenticate(&username).await, + }; + + match result { + Ok(user) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.user = Some(user); + yumush.change_page(Route::Chat, window, cx); + yumush.start_polling(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); +} + +impl Yumush { + pub(super) fn auth_page(&self, route: Route, cx: &mut Context) -> impl IntoElement { + let (action_label, switch_route, switch_label) = match route { + Route::Register => ("Register", Route::Login, "Go to Login Page"), + _ => ("Login", Route::Register, "Go to Register Page"), + }; + + let entity = cx.entity(); + let action_button = + Button::new("auth_button") + .label(action_label) + .on_click(move |_, window, cx| { + entity.update(cx, |this, cx| submit(this, window, cx)); + }); + + let entity = cx.entity(); + let switch_button = Button::new("auth_switch_button") + .label(switch_label) + .on_click(move |_, window, cx| { + entity.update(cx, |this, cx| this.change_page(switch_route, window, cx)); + }); + + div() + .w_1_5() + .child("Username") + .child(Input::new(&self.auth.username_input)) + .child(action_button) + .child(switch_button) + } +} diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index abb29f4..3d4763f 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,12 +1,10 @@ use common::{ - community::Community, constant::NEWEST_MESSAGE_MARKER, - message::Message, - user::User, + model::{Community, Message, User}, validate::{validate_community_name, validate_message_body}, }; use gpui_kit::{ - AppContext, Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, + Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Window, component::{ WindowExt, @@ -17,103 +15,56 @@ use gpui_kit::{ div, rgb, }; -use crate::gui::Yumush; +use crate::gui::{Yumush, new_input, notify_error}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Panel { + None, + Create, + Join, +} pub struct Chat { communities: Vec, selected_community_id: Option, users: Vec, - chat_messages: Vec, + messages: Vec, + panel: Panel, message_input: Entity, community_name_input: Entity, - creating_community: bool, community_search_input: Entity, - community_search_results: Vec, - joining_community: bool, + search_results: Vec, } impl Chat { pub fn new(window: &mut Window, cx: &mut Context) -> Self { - let message_input = cx.new(|cx| { - let mut input_state = InputState::new(window, cx); - input_state.set_placeholder("", window, cx); - - input_state - }); - + let message_input = new_input("", window, cx); cx.subscribe_in(&message_input, window, |this, input, event, window, cx| { if matches!(event, InputEvent::PressEnter { .. }) { - let message_body = input.read(cx).text().to_string(); - - if let Err(error_value) = validate_message_body(&message_body) { - window.push_notification(Notification::error(error_value.to_string()), cx); - - return; - } - - let Some(user) = this.get_user() else { - return; - }; - - let network = this.network.clone(); - let Some(community_id) = this.chat.selected_community_id.clone() else { - window.push_notification(Notification::error("No Community Selected"), cx); - return; - }; - - cx.spawn_in(window, async move |this, cx| { - if let Err(error_value) = network - .create_message(user.get_user_id(), &community_id, &message_body) - .await - { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification( - Notification::error(error_value.to_string()), - cx, - ); - }); - } - }) - .detach(); - - input.update(cx, |input_state, cx| { - input_state.set_value("", window, cx); - }); + send_message(this, input, window, cx); } }) .detach(); - let community_name_input = cx.new(|cx| { - let mut input_state = InputState::new(window, cx); - input_state.set_placeholder("Community Name...", window, cx); - - input_state - }); - + let community_name_input = new_input("Community Name...", window, cx); cx.subscribe_in( &community_name_input, window, |this, input, event, window, cx| { if matches!(event, InputEvent::PressEnter { .. }) { - create_community_action(this, input, window, cx); + create_community(this, input, window, cx); } }, ) .detach(); - let community_search_input = cx.new(|cx| { - let mut input_state = InputState::new(window, cx); - input_state.set_placeholder("Community Name...", window, cx); - - input_state - }); - + let community_search_input = new_input("Community Name...", window, cx); cx.subscribe_in( &community_search_input, window, |this, input, event, window, cx| { if matches!(event, InputEvent::PressEnter { .. }) { - search_community_action(this, input, window, cx); + search_community(this, input, window, cx); } }, ) @@ -123,152 +74,134 @@ impl Chat { communities: vec![], selected_community_id: None, users: vec![], - chat_messages: vec![], + messages: vec![], + panel: Panel::None, message_input, community_name_input, - creating_community: false, community_search_input, - community_search_results: vec![], - joining_community: false, + search_results: vec![], } } - pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) { - self.message_input.update(cx, |input, cx| { - input.focus(window, cx); - }); + pub fn focus(&self, window: &mut Window, cx: &mut Context) { + self.message_input + .update(cx, |input, cx| input.focus(window, cx)); } - pub fn push_message(&mut self, message: Message) { - self.merge_messages(vec![message]); + pub fn merge_messages(&mut self, messages: Vec) { + self.messages.extend(messages); + self.messages.sort_by(|left, right| left.id.cmp(&right.id)); + self.messages.dedup_by(|left, right| left.id == right.id); } - fn merge_messages(&mut self, messages: Vec) { - self.chat_messages.extend(messages); - self.chat_messages - .sort_by(|left, right| left.get_id().cmp(right.get_id())); - self.chat_messages - .dedup_by(|left, right| left.get_id() == right.get_id()); - } - - pub fn update_user_list(&mut self, users: Vec) { - self.users = users; - } - - pub fn update_community_list(&mut self, communities: Vec) { - if self.selected_community_id.is_none() { - self.selected_community_id = communities - .first() - .map(|community| community.get_community_id().to_string()); + fn set_panel(&mut self, panel: Panel) { + if panel != Panel::Join { + self.search_results.clear(); } - - self.communities = communities; - } - - pub fn get_selected_community_id(&self) -> Option { - self.selected_community_id.to_owned() - } - - pub fn set_selected_community_id(&mut self, selected_community_id: Option) { - self.selected_community_id = selected_community_id - } - - pub fn update_searched_community_list(&mut self, communities: Vec) { - self.community_search_results = communities; - } - - pub fn set_joining_community(&mut self, joining_community: bool) { - self.joining_community = joining_community + self.panel = panel; } pub fn reset(&mut self) { self.communities.clear(); self.selected_community_id = None; self.users.clear(); - self.chat_messages.clear(); - self.creating_community = false; - self.community_search_results.clear(); - self.joining_community = false; + self.messages.clear(); + self.set_panel(Panel::None); } } -fn create_community_action( +fn send_message( this: &mut Yumush, input: &Entity, window: &mut Window, - cx: &mut Context<'_, Yumush>, + cx: &mut Context, ) { - let community_name = input.read(cx).text().to_string(); - - if let Err(error_value) = validate_community_name(&community_name) { - window.push_notification(Notification::error(error_value.to_string()), cx); + let body = input.read(cx).text().to_string(); + if let Err(error) = validate_message_body(&body) { + window.push_notification(Notification::error(error.to_string()), cx); return; } + let Some(user_id) = this.user.as_ref().map(|user| user.id.clone()) else { + return; + }; + let Some(community_id) = this.chat.selected_community_id.clone() else { + window.push_notification(Notification::error("No Community Selected"), cx); + return; + }; let network = this.network.clone(); - input.update(cx, |input_state, cx| { - input_state.set_value("", window, cx); - }); - this.chat.creating_community = false; + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.create_message(&user_id, &community_id, &body).await { + notify_error(&this, cx, error); + } + }) + .detach(); + + input.update(cx, |state, cx| state.set_value("", window, cx)); +} + +fn create_community( + this: &mut Yumush, + input: &Entity, + window: &mut Window, + cx: &mut Context, +) { + let name = input.read(cx).text().to_string(); + + if let Err(error) = validate_community_name(&name) { + window.push_notification(Notification::error(error.to_string()), cx); + return; + } + + let network = this.network.clone(); + input.update(cx, |state, cx| state.set_value("", window, cx)); + this.chat.set_panel(Panel::None); cx.spawn_in(window, async move |this, cx| { - let community = match network.create_community(&community_name).await { + let community = match network.create_community(&name).await { Ok(community) => community, - Err(error_value) => { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); - + Err(error) => { + notify_error(&this, cx, error); return; } }; let _ = this.update_in(cx, |yumush, window, cx| { - yumush - .chat - .set_selected_community_id(Some(community.get_community_id().to_string())); - yumush.chat.update_user_list(vec![]); yumush.get_communities(window, cx); - yumush.get_chat_users(window, cx); - yumush.get_chat_messages(window, cx); - cx.notify(); + yumush.select_community(community.id, window, cx); }); }) .detach(); } -fn search_community_action( +fn search_community( this: &mut Yumush, input: &Entity, window: &mut Window, - cx: &mut Context<'_, Yumush>, + cx: &mut Context, ) { - let community_name = input.read(cx).text().to_string(); - - if let Err(error_value) = validate_community_name(&community_name) { - window.push_notification(Notification::error(error_value.to_string()), cx); + let name = input.read(cx).text().to_string(); + if let Err(error) = validate_community_name(&name) { + window.push_notification(Notification::error(error.to_string()), cx); return; } let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { - let communities = match network.search_community(&community_name).await { + let communities = match network.search_community(&name).await { Ok(communities) => communities, - Err(error_value) => { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); - + Err(error) => { + notify_error(&this, cx, error); return; } }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.update_searched_community_list(communities); + yumush.chat.search_results = communities; cx.notify(); }); }) @@ -276,182 +209,21 @@ fn search_community_action( } impl Yumush { - pub fn chat_page(&self, cx: &mut Context) -> impl IntoElement { + pub(super) fn chat_page(&self, cx: &mut Context) -> impl IntoElement { let entity = cx.entity(); + div() .flex() .flex_row() .size_full() - .child( - div() - .id("community_list") - .h_full() - .flex() - .flex_col() - .flex_shrink_0() - .w_1_5() - .border_r_1() - .border_color(rgb(0x2f3136)) - .bg(rgb(0x2b2d31)) - .p_2() - .gap_1() - .child( - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .child( - div() - .text_color(rgb(0x949ba4)) - .font_weight(FontWeight::SEMIBOLD) - .child("Communities"), - ) - .child({ - let entity = entity.clone(); - - Button::new("create_community_button").label("+").on_click( - move |_, window, cx| { - entity.update(cx, |yumush, cx| { - yumush.chat.creating_community = - !yumush.chat.creating_community; - - if yumush.chat.creating_community { - yumush.chat.community_name_input.update( - cx, - |input_state, cx| { - input_state.focus(window, cx); - }, - ); - } - - cx.notify(); - }); - }, - ) - }) - .child({ - let entity = entity.clone(); - - Button::new("join_community_button").label("Join").on_click( - move |_, window, cx| { - entity.update(cx, |yumush, cx| { - yumush.chat.joining_community = - !yumush.chat.joining_community; - - if yumush.chat.joining_community { - yumush.chat.community_search_input.update( - cx, - |input_state, cx| { - input_state.focus(window, cx); - }, - ); - } else { - yumush.chat.update_searched_community_list(vec![]); - } - - cx.notify(); - }); - }, - ) - }), - ) - .children( - self.chat - .creating_community - .then(|| Input::new(&self.chat.community_name_input)), - ) - .children( - self.chat - .joining_community - .then(|| Input::new(&self.chat.community_search_input)), - ) - .children( - self.chat - .community_search_results - .iter() - .filter(|result| { - !self.chat.communities.iter().any(|community| { - community.get_community_id() == result.get_community_id() - }) - }) - .enumerate() - .map(|(index, result)| { - let community_id = result.get_community_id().to_string(); - let entity = entity.clone(); - - div() - .id(("community_search_result", index)) - .p_1() - .cursor_pointer() - .bg(rgb(0x1e1f22)) - .text_color(rgb(0x949ba4)) - .child(result.get_community_name().to_string()) - .on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| { - yumush.join_community(&community_id, window, cx); - }) - }) - }), - ) - .children(self.chat.communities.iter().enumerate().map( - |(index, community)| { - let community_id = community.get_community_id().to_string(); - let selected = self.chat.get_selected_community_id().as_deref() - == Some(&community_id); - let entity = entity.clone(); - - div() - .id(("community", index)) - .p_1() - .cursor_pointer() - .bg(if selected { - rgb(0x404249) - } else { - rgb(0x2b2d31) - }) - .child(community.get_community_name().to_string()) - .on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| { - yumush.chat.set_selected_community_id(Some( - community_id.to_owned(), - )); - yumush.chat.update_user_list(vec![]); - yumush.get_chat_users(window, cx); - yumush.get_chat_messages(window, cx); - cx.notify(); - }) - }) - }, - )), - ) + .child(self.community_list(&entity)) .child( div() .flex() .flex_col() .flex_1() .min_w_0() - .child( - div() - .id("chat_messages") - .flex() - .flex_col() - .flex_1() - .min_w_0() - .overflow_y_scroll() - .p_2() - .gap_1() - .children( - self.chat - .chat_messages - .iter() - .filter(|message| { - Some(message.get_community_id()) - == self.chat.get_selected_community_id().as_deref() - }) - .map(|message| render_message(message, &self.chat.users)), - ), - ) + .child(self.message_list()) .child( div() .p_2() @@ -460,49 +232,207 @@ impl Yumush { .child(Input::new(&self.chat.message_input)), ), ) + .child(self.user_list()) + } + + fn community_list(&self, entity: &Entity) -> impl IntoElement { + div() + .id("community_list") + .h_full() + .flex() + .flex_col() + .flex_shrink_0() + .w_1_5() + .border_r_1() + .border_color(rgb(0x2f3136)) + .bg(rgb(0x2b2d31)) + .p_2() + .gap_1() .child( div() - .id("user_list") - .h_full() .flex() - .flex_col() - .flex_shrink_0() - .w_1_5() - .border_l_1() - .border_color(rgb(0x2f3136)) - .bg(rgb(0x2b2d31)) - .p_2() - .gap_1() + .flex_row() + .items_center() + .justify_between() .child( div() .text_color(rgb(0x949ba4)) .font_weight(FontWeight::SEMIBOLD) - .child(format!("Online - {}", self.chat.users.len())), + .child("Communities"), ) - .children( - self.chat - .users + .child(panel_button( + entity, + "create_community_button", + "+", + Panel::Create, + )) + .child(panel_button( + entity, + "join_community_button", + "Join", + Panel::Join, + )), + ) + .children( + (self.chat.panel == Panel::Create) + .then(|| Input::new(&self.chat.community_name_input)), + ) + .children( + (self.chat.panel == Panel::Join) + .then(|| Input::new(&self.chat.community_search_input)), + ) + .children( + self.chat + .search_results + .iter() + .filter(|result| { + !self + .chat + .communities .iter() - .map(|user| div().p_1().child(user.get_username().to_string())), - ), + .any(|community| community.id == result.id) + }) + .enumerate() + .map(|(index, result)| { + let community_id = result.id.clone(); + let entity = entity.clone(); + + div() + .id(("community_search_result", index)) + .p_1() + .cursor_pointer() + .bg(rgb(0x1e1f22)) + .text_color(rgb(0x949ba4)) + .child(result.name.clone()) + .on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| { + yumush.join_community(&community_id, window, cx) + }) + }) + }), + ) + .children( + self.chat + .communities + .iter() + .enumerate() + .map(|(index, community)| { + let community_id = community.id.clone(); + let selected = self.chat.selected_community_id.as_deref() + == Some(community.id.as_str()); + let entity = entity.clone(); + + div() + .id(("community", index)) + .p_1() + .cursor_pointer() + .bg(if selected { + rgb(0x404249) + } else { + rgb(0x2b2d31) + }) + .child(community.name.clone()) + .on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| { + yumush.select_community(community_id.clone(), window, cx) + }) + }) + }), ) } - pub fn get_chat_users(&self, window: &mut Window, cx: &mut Context) { - let network = self.network.clone(); + fn message_list(&self) -> impl IntoElement { + div() + .id("chat_messages") + .flex() + .flex_col() + .flex_1() + .min_w_0() + .overflow_y_scroll() + .p_2() + .gap_1() + .children( + self.chat + .messages + .iter() + .filter(|message| { + Some(&message.community_id) == self.chat.selected_community_id.as_ref() + }) + .map(|message| render_message(message, &self.chat.users)), + ) + } - let Some(community_id) = self.chat.get_selected_community_id().to_owned() else { + fn user_list(&self) -> impl IntoElement { + div() + .id("user_list") + .h_full() + .flex() + .flex_col() + .flex_shrink_0() + .w_1_5() + .border_l_1() + .border_color(rgb(0x2f3136)) + .bg(rgb(0x2b2d31)) + .p_2() + .gap_1() + .child( + div() + .text_color(rgb(0x949ba4)) + .font_weight(FontWeight::SEMIBOLD) + .child(format!("Online - {}", self.chat.users.len())), + ) + .children( + self.chat + .users + .iter() + .map(|user| div().p_1().child(user.username.clone())), + ) + } + + fn toggle_panel(&mut self, panel: Panel, window: &mut Window, cx: &mut Context) { + let panel = if self.chat.panel == panel { + Panel::None + } else { + panel + }; + self.chat.set_panel(panel); + + let input = match panel { + Panel::None => None, + Panel::Create => Some(&self.chat.community_name_input), + Panel::Join => Some(&self.chat.community_search_input), + }; + if let Some(input) = input { + input.update(cx, |state, cx| state.focus(window, cx)); + } + + cx.notify(); + } + + fn select_community( + &mut self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.selected_community_id = Some(community_id); + self.chat.users.clear(); + self.get_chat_users(window, cx); + self.get_chat_messages(window, cx); + cx.notify(); + } + + pub(super) fn get_chat_users(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; + let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let user_ids = match network.users_in(&community_id).await { Ok(user_ids) => user_ids, - Err(error_value) => { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); - + Err(error) => { + notify_error(&this, cx, error); return; } }; @@ -515,34 +445,27 @@ impl Yumush { } let _ = this.update(cx, |yumush, cx| { - yumush.chat.update_user_list(users); + yumush.chat.users = users; cx.notify(); }); }) .detach(); } - pub fn get_chat_messages(&self, window: &mut Window, cx: &mut Context) { - let network = self.network.clone(); - - let Some(community_id) = self.chat.get_selected_community_id() else { + pub(super) fn get_chat_messages(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; + let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let messages = match network - .read_message_by_community_id_with_marker_and_limit( - community_id.as_str(), - NEWEST_MESSAGE_MARKER, - ) + .read_messages(&community_id, NEWEST_MESSAGE_MARKER) .await { Ok(messages) => messages, - Err(error_value) => { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); - + Err(error) => { + notify_error(&this, cx, error); return; } }; @@ -555,21 +478,17 @@ impl Yumush { .detach(); } - pub fn get_communities(&self, window: &mut Window, cx: &mut Context) { - let Some(user) = self.get_user() else { + pub(super) fn get_communities(&self, window: &mut Window, cx: &mut Context) { + let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { return; }; - let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let community_ids = match network.community_of(user.get_user_id()).await { + let community_ids = match network.communities_of(&user_id).await { Ok(community_ids) => community_ids, - Err(error_value) => { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); - + Err(error) => { + notify_error(&this, cx, error); return; } }; @@ -582,55 +501,60 @@ impl Yumush { } let _ = this.update(cx, |yumush, cx| { - yumush.chat.update_community_list(communities); + if yumush.chat.selected_community_id.is_none() { + yumush.chat.selected_community_id = + communities.first().map(|community| community.id.clone()); + } + yumush.chat.communities = communities; cx.notify(); }); }) .detach(); } - pub fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context) { - let Some(user) = self.get_user() else { + fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context) { + let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { return; }; - let network = self.network.clone(); let community_id = community_id.to_string(); cx.spawn_in(window, async move |this, cx| { - if let Err(error_value) = network - .join_community(user.get_user_id(), &community_id) - .await - { - let _ = this.update_in(cx, |_, window, cx| { - window.push_notification(Notification::error(error_value.to_string()), cx); - }); - + if let Err(error) = network.join_community(&user_id, &community_id).await { + notify_error(&this, cx, error); return; } let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.set_joining_community(false); - yumush.chat.update_searched_community_list(vec![]); - yumush.chat.set_selected_community_id(Some(community_id)); - yumush.chat.update_user_list(vec![]); + yumush.chat.set_panel(Panel::None); yumush.get_communities(window, cx); - yumush.get_chat_users(window, cx); - yumush.get_chat_messages(window, cx); - - cx.notify(); + yumush.select_community(community_id, window, cx); }); }) .detach(); } } +fn panel_button( + entity: &Entity, + id: &'static str, + label: &'static str, + panel: Panel, +) -> impl IntoElement { + let entity = entity.clone(); + + Button::new(id).label(label).on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| yumush.toggle_panel(panel, window, cx)); + }) +} + fn render_message(message: &Message, users: &[User]) -> impl IntoElement { let username = users .iter() - .find(|user| user.get_user_id() == message.get_user_id()) - .map(User::get_username) - .unwrap_or(message.get_user_id()); + .find(|user| user.id == message.user_id) + .map(|user| user.username.as_str()) + .unwrap_or(message.user_id.as_str()); + div() .flex() .flex_col() @@ -641,5 +565,5 @@ fn render_message(message: &Message, users: &[User]) -> impl IntoElement { .font_weight(FontWeight::BOLD) .child(username.to_string()), ) - .child(div().pl_2().child(message.get_message_body().to_string())) + .child(div().pl_2().child(message.body.clone())) } diff --git a/crates/client/src/gui/login.rs b/crates/client/src/gui/login.rs deleted file mode 100644 index b5a5607..0000000 --- a/crates/client/src/gui/login.rs +++ /dev/null @@ -1,100 +0,0 @@ -use gpui_kit::{ - AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window, - component::{ - WindowExt, - button::Button, - input::{Input, InputEvent, InputState}, - notification::Notification, - }, - div, -}; - -use crate::gui::{Route, Yumush}; - -pub struct Login { - username_input: Entity, -} - -impl Login { - pub fn new(window: &mut Window, cx: &mut Context) -> Self { - let username_input = cx.new(|cx| { - let mut input_state = InputState::new(window, cx); - input_state.set_placeholder("Username...", window, cx); - input_state.focus(window, cx); - - input_state - }); - - cx.subscribe_in(&username_input, window, |this, input, event, window, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - login_action(this, input, window, cx); - } - }) - .detach(); - - Self { username_input } - } - - pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) { - self.username_input.update(cx, |input, cx| { - input.focus(window, cx); - }); - } -} - -fn login_action( - this: &mut Yumush, - input: &Entity, - window: &mut Window, - cx: &mut Context<'_, Yumush>, -) { - let username = input.read(cx).text().to_string(); - let network = this.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let result = network.authenticate(&username).await; - - let _ = this.update_in(cx, |yumush, window, cx| match result { - Ok(user) => { - yumush.set_user(user); - yumush.change_page(Route::Chat, window, cx); - yumush.time_based_repetitive_checks_after_login(window, cx); - } - Err(error_value) => { - window.push_notification(Notification::error(error_value.to_string()), cx); - } - }); - }) - .detach(); -} - -impl Yumush { - pub fn login_page(&mut self, cx: &mut Context) -> impl IntoElement { - let entity = cx.entity(); - let username_input = self.login.username_input.clone(); - let login_button = Button::new("login_button") - .on_click(move |_, window, cx| { - entity.update(cx, |this, cx| { - login_action(this, &username_input, window, cx); - }) - }) - .label("Login"); - - let entity = cx.entity(); - let register_page_switch_button = Button::new("register_page_switch_button") - .on_click(move |_, window, cx| { - entity.update(cx, |this, cx| { - this.change_page(Route::Register, window, cx); - }) - }) - .label("Go to Register Page"); - - div() - .w_1_5() - .child("Username") - .child(Input::new(&self.login.username_input)) - .child(login_button) - .child(register_page_switch_button) - .into_element() - } -} diff --git a/crates/client/src/gui/register.rs b/crates/client/src/gui/register.rs deleted file mode 100644 index 349116e..0000000 --- a/crates/client/src/gui/register.rs +++ /dev/null @@ -1,99 +0,0 @@ -use gpui_kit::{ - AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window, - component::{ - WindowExt, - button::Button, - input::{Input, InputEvent, InputState}, - notification::Notification, - }, - div, -}; - -use crate::gui::{Route, Yumush}; - -pub struct Register { - username_input: Entity, -} - -impl Register { - pub fn new(window: &mut Window, cx: &mut Context) -> Self { - let username_input = cx.new(|cx| { - let mut input_state = InputState::new(window, cx); - input_state.set_placeholder("Username...", window, cx); - input_state.focus(window, cx); - - input_state - }); - - cx.subscribe_in(&username_input, window, |this, input, event, window, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - register_action(this, input, window, cx); - } - }) - .detach(); - - Self { username_input } - } - - pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) { - self.username_input.update(cx, |input, cx| { - input.focus(window, cx); - }); - } -} - -fn register_action( - this: &mut Yumush, - input: &Entity, - window: &mut Window, - cx: &mut Context<'_, Yumush>, -) { - let username = input.read(cx).text().to_string(); - let network = this.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let result = network.create_user(&username).await; - - let _ = this.update_in(cx, |yumush, window, cx| match result { - Ok(user) => { - yumush.set_user(user); - yumush.change_page(Route::Chat, window, cx); - } - Err(error_value) => { - window.push_notification(Notification::error(error_value.to_string()), cx); - } - }); - }) - .detach(); -} - -impl Yumush { - pub fn register_page(&mut self, cx: &mut Context) -> impl IntoElement { - let entity = cx.entity(); - let username_input = self.register.username_input.clone(); - let register_button = Button::new("register_button") - .on_click(move |_, window, cx| { - entity.update(cx, |this, cx| { - register_action(this, &username_input, window, cx); - }) - }) - .label("Register"); - - let entity = cx.entity(); - let login_page_switch_button = Button::new("login_page_switch_button") - .on_click(move |_, window, cx| { - entity.update(cx, |this, cx| { - this.change_page(Route::Login, window, cx); - }) - }) - .label("Go to Login Page"); - - div() - .w_1_5() - .child("Username") - .child(Input::new(&self.register.username_input)) - .child(register_button) - .child(login_page_switch_button) - .into_element() - } -} diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 5f916fe..abf8dca 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -1,9 +1,7 @@ -use common::utils::TOML; +use common::config::parse; -pub mod event; pub mod gui; pub mod network; -mod request; pub const NAME: &str = "Yumush"; @@ -19,14 +17,11 @@ pub struct ClientConfig { impl Default for ClientConfig { fn default() -> Self { - let toml = TOML::naive_toml_parser_from_content(CLIENT_CONFIG_FILE_CONTENT).unwrap(); - - let server_address = toml.fields.get("server_address").unwrap().to_owned(); - let server_name = toml.fields.get("server_name").unwrap().to_owned(); + let fields = parse(CLIENT_CONFIG_FILE_CONTENT).expect("client config"); Self { - server_address, - server_name, + server_address: fields["server_address"].clone(), + server_name: fields["server_name"].clone(), } } } diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 03e6aeb..c8704c9 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -1,12 +1,10 @@ -use client::{gui::Yumush, network, ClientConfig, NAME}; +use client::{ClientConfig, NAME, gui::Yumush, network}; use gpui_kit::{ - application, component::Root, init, px, size, App, AppContext, Bounds, TitlebarOptions, - WindowBounds, WindowOptions, + App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application, + component::Root, init, px, size, }; fn main() { - println!("Hello, world!"); - let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); application().run(|cx: &mut App| { diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index 341274f..630ef27 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -1,9 +1,15 @@ use std::sync::Arc; use std::time::Duration; -use common::error::Error; -use common::network::Network; -use common::{community::Community, error::network, message::Message, user::User}; +use common::{ + constant::MESSAGE_PAGE_LIMIT, + error::Error, + model::{Community, Message, User}, + network::{receive_message, send_request}, + request::Request, + response::Response, + validate::{validate_community_name, validate_message_body, validate_username}, +}; use quinn::{ Endpoint, crypto::rustls::QuicClientConfig, @@ -14,7 +20,7 @@ use quinn::{ }; use tokio::sync::{mpsc, oneshot}; -use crate::{ClientConfig, request::ClientRequest}; +use crate::ClientConfig; const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1); const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3); @@ -22,112 +28,204 @@ const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3); const CHANNEL_SIZE: usize = 32; const RECONNECT_DELAY: Duration = Duration::from_secs(1); -pub async fn connect(server_address: &str, server_name: &str) -> Result { - let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; - endpoint.set_default_client_config(config()); +#[derive(Debug)] +pub enum NetworkEvent { + Connected(Option), + ConnectionFailed(Error), + Disconnected(Error), + MessageReceived(Message), +} - let connection = endpoint - .connect(server_address.parse().unwrap(), server_name)? - .await?; +#[derive(Debug)] +struct Command { + request: Request, + reply: oneshot::Sender>, +} - Ok(ClientRequest::new(connection)) +#[derive(Debug, Clone)] +pub struct NetworkHandle { + command_sender: mpsc::Sender, } -fn config() -> quinn::ClientConfig { - let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); - let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) - .with_protocol_versions(&[&rustls::version::TLS13]) - .unwrap() - .dangerous() - .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider))) - .with_no_client_auth(); +impl NetworkHandle { + pub async fn request(&self, request: Request) -> Result { + let (reply, response) = oneshot::channel(); - let mut client_config = - quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap())); + self.command_sender + .send(Command { request, reply }) + .await + .map_err(|_| Error::ChannelClosed)?; - let mut transport_config = quinn::TransportConfig::default(); - transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL)); - transport_config.max_idle_timeout(Some(MAX_IDLE_TIMEOUT.try_into().unwrap())); + match response.await.map_err(|_| Error::ChannelClosed)?? { + Response::Error(error) => Err(error), + response => Ok(response), + } + } - client_config.transport_config(Arc::new(transport_config)); + pub async fn authenticate(&self, token: &str) -> Result { + match self + .request(Request::Authentication { + token: token.to_string(), + }) + .await? + { + Response::Authentication(user) => Ok(user), + _ => Err(Error::Server), + } + } - client_config -} + pub async fn deauthenticate(&self, token: &str) -> Result { + match self + .request(Request::Deauthentication { + token: token.to_string(), + }) + .await? + { + Response::Deauthentication(user) => Ok(user), + _ => Err(Error::Server), + } + } + + pub async fn create_user(&self, username: &str) -> Result { + validate_username(username)?; -macro_rules! network_commands { - ($($variant:ident => $method:ident($($arg:ident), *) -> $ret:ty),* $(,)?) => { - #[derive(Debug)] - pub enum NetworkCommand { - $($variant{ - $($arg: String, )* - reply: oneshot::Sender>, - },)* + match self + .request(Request::CreateUser { + username: username.to_string(), + }) + .await? + { + Response::CreateUser(user) => Ok(user), + _ => Err(Error::Server), } + } - impl NetworkHandle { - $(pub async fn $method(&self, $($arg: &str),*) -> Result<$ret, Error> { - let (reply, response) = oneshot::channel(); - let command = NetworkCommand::$variant { - $($arg: $arg.to_string(),)* - reply, - }; + pub async fn read_user(&self, user_id: &str) -> Result { + match self + .request(Request::ReadUser { + user_id: user_id.to_string(), + }) + .await? + { + Response::ReadUser(user) => Ok(user), + _ => Err(Error::Server), + } + } - self.command_sender.send(command).await.map_err(|_| network::Error::ChannelClosed)?; + pub async fn create_community(&self, name: &str) -> Result { + validate_community_name(name)?; - response.await.map_err(|_| network::Error::ChannelClosed)? - })* + match self + .request(Request::CreateCommunity { + name: name.to_string(), + }) + .await? + { + Response::CreateCommunity(community) => Ok(community), + _ => Err(Error::Server), } + } - async fn dispatch(client_request: ClientRequest, command: NetworkCommand) { - match command { - $(NetworkCommand::$variant { $($arg,)* reply} => { - let _ = reply.send(client_request.$method($(&$arg),*).await); - })* - } + pub async fn read_community(&self, community_id: &str) -> Result { + match self + .request(Request::ReadCommunity { + community_id: community_id.to_string(), + }) + .await? + { + Response::ReadCommunity(community) => Ok(community), + _ => Err(Error::Server), } - }; -} + } -network_commands! { - Authenticate => authenticate(authentication_token) -> User, - Deauthenticate => deauthenticate(authentication_token) -> User, - CreateUser => create_user(username) -> User, - ReadUser => read_user(user_id) -> User, - UpdateUser => update_user(user_id, username) -> User, - DeleteUser => delete_user(user_id) -> User, - CreateCommunity => create_community(community_name) -> Community, - ReadCommunity => read_community(community_id) -> Community, - UpdateCommunity => update_community(community_id, community_name) -> Community, - DeleteCommunity => delete_community(community_id) -> Community, - CreateMessage => create_message(user_id, community_id, message_body) -> Message, - ReadMessage => read_message(message_id) -> Message, - UpdateMessage => update_message(message_id, message_body) -> Message, - DeleteMessage => delete_message(message_id) -> Message, - ReadMessageByCommunityIDWithMarkerAndLimit => read_message_by_community_id_with_marker_and_limit(community_id, marker) -> Vec, - JoinCommunity => join_community(user_id, community_id) -> (), - LeaveCommunity => leave_community(user_id, community_id) -> (), - IsUserIn => is_user_in(user_id, community_id) -> bool, - UsersIn => users_in(community_id) -> Vec, - CommunityOf => community_of(user_id) -> Vec, - SearchCommunity => search_community(community_name) -> Vec, -} + pub async fn create_message( + &self, + user_id: &str, + community_id: &str, + body: &str, + ) -> Result { + validate_message_body(body)?; + + match self + .request(Request::CreateMessage { + user_id: user_id.to_string(), + community_id: community_id.to_string(), + body: body.to_string(), + }) + .await? + { + Response::CreateMessage(message) => Ok(message), + _ => Err(Error::Server), + } + } -#[derive(Debug)] -pub enum NetworkEvent { - Connected(Option), - ConnectionFailed(Error), - Disconnected(Error), - MessageReceived(Message), -} + pub async fn read_messages( + &self, + community_id: &str, + marker: &str, + ) -> Result, Error> { + match self + .request(Request::ReadMessages { + community_id: community_id.to_string(), + marker: marker.to_string(), + limit: MESSAGE_PAGE_LIMIT, + }) + .await? + { + Response::ReadMessages(messages) => Ok(messages), + _ => Err(Error::Server), + } + } -#[derive(Debug, Clone)] -pub struct NetworkHandle { - command_sender: mpsc::Sender, -} + pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { + match self + .request(Request::JoinCommunity { + user_id: user_id.to_string(), + community_id: community_id.to_string(), + }) + .await? + { + Response::JoinCommunity => Ok(()), + _ => Err(Error::Server), + } + } -impl NetworkHandle { - fn new(command_sender: mpsc::Sender) -> Self { - Self { command_sender } + pub async fn users_in(&self, community_id: &str) -> Result, Error> { + match self + .request(Request::UsersIn { + community_id: community_id.to_string(), + }) + .await? + { + Response::UsersIn(user_ids) => Ok(user_ids), + _ => Err(Error::Server), + } + } + + pub async fn communities_of(&self, user_id: &str) -> Result, Error> { + match self + .request(Request::CommunitiesOf { + user_id: user_id.to_string(), + }) + .await? + { + Response::CommunitiesOf(community_ids) => Ok(community_ids), + _ => Err(Error::Server), + } + } + + pub async fn search_community(&self, name: &str) -> Result, Error> { + validate_community_name(name)?; + + match self + .request(Request::SearchCommunity { + name: name.to_string(), + }) + .await? + { + Response::SearchCommunity(communities) => Ok(communities), + _ => Err(Error::Server), + } } } @@ -146,24 +244,69 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver Result { + let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; + endpoint.set_default_client_config(config()); + + let connection = endpoint + .connect(server_address.parse()?, server_name)? + .await?; + + Ok(connection) +} + +fn config() -> quinn::ClientConfig { + let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); + let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .dangerous() + .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider))) + .with_no_client_auth(); + + let mut client_config = + quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap())); + + let mut transport_config = quinn::TransportConfig::default(); + transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL)); + transport_config.max_idle_timeout(Some(MAX_IDLE_TIMEOUT.try_into().unwrap())); + + client_config.transport_config(Arc::new(transport_config)); + + client_config +} + +async fn send(connection: &quinn::Connection, request: &Request) -> Result { + let (send_stream, receive_stream) = connection.open_bi().await?; + send_request(request, send_stream, receive_stream).await +} + +async fn dispatch( + connection: quinn::Connection, + request: Request, + reply: oneshot::Sender>, +) { + let _ = reply.send(send(&connection, &request).await); } async fn actor( client_config: ClientConfig, - mut command_receiver: mpsc::Receiver, + mut command_receiver: mpsc::Receiver, event_sender: mpsc::Sender, ) { let mut authentication_token: Option = None; let mut authentication_epoch = 0; let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE); 'session: loop { - let client_request = loop { + let connection = loop { match connect(&client_config.server_address, &client_config.server_name).await { - Ok(client_request) => break client_request, - Err(error_value) => { + Ok(connection) => break connection, + Err(error) => { if event_sender - .send(NetworkEvent::ConnectionFailed(error_value)) + .send(NetworkEvent::ConnectionFailed(error)) .await .is_err() { @@ -176,10 +319,13 @@ async fn actor( }; let mut user = None; - if let Some(authentication_token_) = &authentication_token { - match client_request.authenticate(authentication_token_).await { - Ok(user_) => user = Some(user_), - Err(_) => authentication_token = None, + if let Some(token) = &authentication_token { + let request = Request::Authentication { + token: token.clone(), + }; + match send(&connection, &request).await { + Ok(Response::Authentication(user_)) => user = Some(user_), + _ => authentication_token = None, } } @@ -192,48 +338,50 @@ async fn actor( } tokio::spawn(message_receive_loop( - client_request.clone(), + connection.clone(), event_sender.clone(), )); loop { tokio::select! { command = command_receiver.recv() => match command { - Some(NetworkCommand::Authenticate {authentication_token: authentication_token_, reply}) => { - let client_request = client_request.clone(); - let token_sender = token_sender.clone(); - let epoch = authentication_epoch; - - tokio::spawn(async move { - let result = client_request.authenticate(&authentication_token_).await; - if result.is_ok() { - let _ = token_sender.send((epoch, authentication_token_)).await; - } - - let _ = reply.send(result); - }); - } - Some(command) => { - match &command { - NetworkCommand::Deauthenticate { .. } => { - authentication_token = None; - authentication_epoch += 1; - } - _ => {} + Some(Command { request, reply }) => match &request { + Request::Authentication { token } => { + let token = token.clone(); + let token_sender = token_sender.clone(); + let epoch = authentication_epoch; + let connection = connection.clone(); + + tokio::spawn(async move { + let response = send(&connection, &request).await; + if let Ok(Response::Authentication(_)) = &response { + let _ = token_sender.send((epoch, token)).await; + } + + let _ = reply.send(response); + }); } - tokio::spawn(dispatch(client_request.clone(), command)); - } + Request::Deauthentication { .. } => { + authentication_token = None; + authentication_epoch += 1; + + tokio::spawn(dispatch(connection.clone(), request, reply)); + } + _ => { + tokio::spawn(dispatch(connection.clone(), request, reply)); + } + }, None => break 'session, }, - Some((epoch, authentication_token_)) = token_receiver.recv() => { + Some((epoch, token)) = token_receiver.recv() => { if epoch == authentication_epoch { - authentication_token = Some(authentication_token_) + authentication_token = Some(token); } } - error_value = client_request.closed() => { - if event_sender.send(NetworkEvent::Disconnected(error_value.into())).await.is_err() { - return ; + error = connection.closed() => { + if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { + return; } break; @@ -244,14 +392,14 @@ async fn actor( } async fn message_receive_loop( - client_request: ClientRequest, + connection: quinn::Connection, event_sender: mpsc::Sender, ) { - let Ok(mut receive_stream) = client_request.accept_unidirectional_stream().await else { + let Ok(mut receive_stream) = connection.accept_uni().await else { return; }; - while let Ok(message) = Network::receive_message(&mut receive_stream).await { + while let Ok(message) = receive_message(&mut receive_stream).await { if event_sender .send(NetworkEvent::MessageReceived(message)) .await diff --git a/crates/client/src/request.rs b/crates/client/src/request.rs deleted file mode 100644 index 174e279..0000000 --- a/crates/client/src/request.rs +++ /dev/null @@ -1,297 +0,0 @@ -use common::{ - community::Community, - constant::MESSAGE_PAGE_LIMIT, - error::Error, - message::Message, - network::Network, - request::{ - Authentication, Deauthentication, Request, - community::{ - CreateCommunity, DeleteCommunity, ReadCommunity, SearchCommunity, UpdateCommunity, - }, - message::{ - CreateMessage, DeleteMessage, ReadMessage, ReadMessageByCommunityIDWithMarkerAndLimit, - UpdateMessage, - }, - user::{CreateUser, DeleteUser, ReadUser, UpdateUser}, - user_community::{CommunityOf, IsUserIn, JoinCommunity, LeaveCommunity, UsersIn}, - }, - response::Response, - user::User, -}; - -macro_rules! send_request_receive_response_then_classify { - ($request:expr, $variant:path, $connection:expr) => {{ - let (send_stream, receive_stream) = $connection.open_bi().await?; - let response = - Network::send_request_and_receive_response(&$request, send_stream, receive_stream) - .await?; - match response { - $variant(inner) => Ok(inner), - Response::Error(error) => Err(error), - _ => Err(Error::Server), - } - }}; - - (@unit $request:expr, $variant:path, $connection:expr) => {{ - let (send_stream, receive_stream) = $connection.open_bi().await?; - let response = - Network::send_request_and_receive_response(&$request, send_stream, receive_stream) - .await?; - match response { - $variant => Ok(()), - Response::Error(error_value) => Err(error_value), - _ => Err(Error::Server), - } - }}; -} - -#[derive(Debug, Clone)] -pub struct ClientRequest { - connection: quinn::Connection, -} - -impl ClientRequest { - pub fn new(connection: quinn::Connection) -> Self { - Self { connection } - } - - pub async fn closed(&self) -> Error { - self.connection.closed().await.into() - } - - pub async fn accept_unidirectional_stream(&self) -> Result { - Ok(self.connection.accept_uni().await?) - } - - pub async fn authenticate(&self, authentication_token: &str) -> Result { - let authentication = Authentication::new(authentication_token); - let request = Request::Authentication(authentication); - - send_request_receive_response_then_classify!( - request, - Response::Authentication, - self.connection - ) - } - - pub async fn deauthenticate(&self, authentication_token: &str) -> Result { - let deauthentication = Deauthentication::new(authentication_token); - let request = Request::Deauthentication(deauthentication); - - send_request_receive_response_then_classify!( - request, - Response::Deauthentication, - self.connection - ) - } - - pub async fn create_user(&self, username: &str) -> Result { - let create_user = CreateUser::new(username)?; - let request = Request::CreateUser(create_user); - - send_request_receive_response_then_classify!(request, Response::CreateUser, self.connection) - } - - pub async fn read_user(&self, user_id: &str) -> Result { - let read_user = ReadUser::new(user_id); - let request = Request::ReadUser(read_user); - - send_request_receive_response_then_classify!(request, Response::ReadUser, self.connection) - } - - pub async fn update_user(&self, user_id: &str, username: &str) -> Result { - let update_user = UpdateUser::new(user_id, username)?; - let request = Request::UpdateUser(update_user); - - send_request_receive_response_then_classify!(request, Response::UpdateUser, self.connection) - } - - pub async fn delete_user(&self, user_id: &str) -> Result { - let delete_user = DeleteUser::new(user_id); - let request = Request::DeleteUser(delete_user); - - send_request_receive_response_then_classify!(request, Response::DeleteUser, self.connection) - } - - pub async fn create_community(&self, community_name: &str) -> Result { - let create_community = CreateCommunity::new(community_name)?; - let request = Request::CreateCommunity(create_community); - - send_request_receive_response_then_classify!( - request, - Response::CreateCommunity, - self.connection - ) - } - - pub async fn read_community(&self, community_id: &str) -> Result { - let read_community = ReadCommunity::new(community_id); - let request = Request::ReadCommunity(read_community); - - send_request_receive_response_then_classify!( - request, - Response::ReadCommunity, - self.connection - ) - } - - pub async fn update_community( - &self, - community_id: &str, - community_name: &str, - ) -> Result { - let update_community = UpdateCommunity::new(community_id, community_name)?; - let request = Request::UpdateCommunity(update_community); - - send_request_receive_response_then_classify!( - request, - Response::UpdateCommunity, - self.connection - ) - } - - pub async fn delete_community(&self, community_id: &str) -> Result { - let delete_community = DeleteCommunity::new(community_id); - let request = Request::DeleteCommunity(delete_community); - - send_request_receive_response_then_classify!( - request, - Response::DeleteCommunity, - self.connection - ) - } - - pub async fn create_message( - &self, - user_id: &str, - community_id: &str, - message_body: &str, - ) -> Result { - let create_message = CreateMessage::new(user_id, community_id, message_body)?; - let request = Request::CreateMessage(create_message); - - send_request_receive_response_then_classify!( - request, - Response::CreateMessage, - self.connection - ) - } - - pub async fn read_message(&self, message_id: &str) -> Result { - let read_message = ReadMessage::new(message_id); - let request = Request::ReadMessage(read_message); - - send_request_receive_response_then_classify!( - request, - Response::ReadMessage, - self.connection - ) - } - - pub async fn update_message( - &self, - message_id: &str, - message_body: &str, - ) -> Result { - let update_message = UpdateMessage::new(message_id, message_body)?; - let request = Request::UpdateMessage(update_message); - - send_request_receive_response_then_classify!( - request, - Response::UpdateMessage, - self.connection - ) - } - - pub async fn delete_message(&self, message_id: &str) -> Result { - let delete_message = DeleteMessage::new(message_id); - let request = Request::DeleteMessage(delete_message); - - send_request_receive_response_then_classify!( - request, - Response::DeleteMessage, - self.connection - ) - } - - pub async fn read_message_by_community_id_with_marker_and_limit( - &self, - community_id: &str, - marker: &str, - ) -> Result, Error> { - let read_message_by_community_id_with_marker_and_limit = - ReadMessageByCommunityIDWithMarkerAndLimit::new( - community_id, - marker, - MESSAGE_PAGE_LIMIT, - ); - let request = Request::ReadMessageByCommunityIDWithMarkerAndLimit( - read_message_by_community_id_with_marker_and_limit, - ); - - send_request_receive_response_then_classify!( - request, - Response::ReadMessageByCommunityIDWithMarkerAndLimit, - self.connection - ) - } - - pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { - let join_community = JoinCommunity::new(user_id, community_id); - let request = Request::JoinCommunity(join_community); - - send_request_receive_response_then_classify!( - @unit request, - Response::JoinCommunity, - self.connection - ) - } - - pub async fn leave_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { - let leave_community = LeaveCommunity::new(user_id, community_id); - let request = Request::LeaveCommunity(leave_community); - - send_request_receive_response_then_classify!( - @unit request, - Response::LeaveCommunity, - self.connection - ) - } - - pub async fn is_user_in(&self, user_id: &str, community_id: &str) -> Result { - let is_user_in = IsUserIn::new(user_id, community_id); - let request = Request::IsUserIn(is_user_in); - - send_request_receive_response_then_classify!(request, Response::IsUserIn, self.connection) - } - - pub async fn users_in(&self, community_id: &str) -> Result, Error> { - let users_in = UsersIn::new(community_id); - let request = Request::UsersIn(users_in); - - send_request_receive_response_then_classify!(request, Response::UsersIn, self.connection) - } - - pub async fn community_of(&self, user_id: &str) -> Result, Error> { - let community_of = CommunityOf::new(user_id); - let request = Request::CommunityOf(community_of); - - send_request_receive_response_then_classify!( - request, - Response::CommunityOf, - self.connection - ) - } - - pub async fn search_community(&self, community_name: &str) -> Result, Error> { - let search_community = SearchCommunity::new(community_name)?; - let request = Request::SearchCommunity(search_community); - - send_request_receive_response_then_classify!( - request, - Response::SearchCommunity, - self.connection - ) - } -} diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index d8efe64..c015136 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -3,10 +3,9 @@ name = "common" version = "0.1.0" edition = "2024" -[features] -client = [] -server = [] - [dependencies] bitcode.workspace = true quinn.workspace = true + +[lints] +workspace = true diff --git a/crates/common/src/community.rs b/crates/common/src/community.rs deleted file mode 100644 index a8eb893..0000000 --- a/crates/common/src/community.rs +++ /dev/null @@ -1,28 +0,0 @@ -use bitcode::{Decode, Encode}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Community { - community_id: String, - community_name: String, -} - -impl Community { - #[cfg(feature = "server")] - pub fn new(community_id: &str, community_name: &str) -> Self { - let community_id = community_id.to_string(); - let community_name = community_name.to_string(); - - Self { - community_id, - community_name, - } - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } - - pub fn get_community_name(&self) -> &str { - &self.community_name - } -} diff --git a/crates/common/src/config.rs b/crates/common/src/config.rs new file mode 100644 index 0000000..59795b1 --- /dev/null +++ b/crates/common/src/config.rs @@ -0,0 +1,20 @@ +use std::collections::HashMap; + +use crate::error::Error; + +pub fn parse(content: &str) -> Result, Error> { + content + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('[') && !line.starts_with('#')) + .map(|line| { + let (key, value) = line + .split_once('=') + .ok_or_else(|| Error::Config(format!("Invalid line: {line}")))?; + Ok(( + key.replace('"', "").trim().to_string(), + value.replace('"', "").trim().to_string(), + )) + }) + .collect() +} diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index a917f9b..4d3c309 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -1,50 +1,111 @@ +use std::fmt::Display; + use bitcode::{Decode, Encode}; -use crate::{error_display, error_from}; +#[macro_export] +macro_rules! error_from { + ($target:ty { $($rest:tt)* }) => { + $crate::error_from!(@arm $target, $($rest)*); + }; + + (@arm $target:ty, $source:ty => $variant:path as $middle:ty, $($rest:tt)*) => { + impl From<$source> for $target { + fn from(value: $source) -> Self { + $variant(<$middle>::from(value).into()) + } + } + $crate::error_from!(@arm $target, $($rest)*); + }; + + (@arm $target:ty, $source:ty => $variant:path, $($rest:tt)*) => { + impl From<$source> for $target { + fn from(value: $source) -> Self { + $variant(value) + } + } + $crate::error_from!(@arm $target, $($rest)*); + }; -pub mod community; -pub mod decode; -pub mod file_operation; -pub mod macro_; -pub mod message; -pub mod network; -pub mod user; + (@arm $target:ty,) => {}; +} + +macro_rules! from_display { + ($target:ty { $($source:ty => $variant:path),+ $(,)? }) => { + $( + impl From<$source> for $target { + fn from(value: $source) -> Self { + $variant(value.to_string()) + } + } + )+ + }; +} + +#[derive(Debug, Clone, Encode, Decode)] +pub enum InvalidInput { + TooShort { minimum: usize, actual: usize }, + TooLong { maximum: usize, actual: usize }, + NotASCII, +} + +impl Display for InvalidInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + InvalidInput::TooShort { minimum, actual } => { + write!(f, "too short ({actual} < {minimum})") + } + InvalidInput::TooLong { maximum, actual } => { + write!(f, "too long ({actual} > {maximum})") + } + InvalidInput::NotASCII => write!(f, "not ASCII"), + } + } +} #[derive(Debug, Clone, Encode, Decode)] pub enum Error { Authenticate, - User(user::Error), - Community(community::Error), - Message(message::Error), - FileOperation(file_operation::Error), - Network(network::Error), - Decode(decode::Error), Server, + ChannelClosed, + Config(String), + Network(String), + Decode(String), + ReadBoundExceed { actual: usize, maximum: usize }, + User(InvalidInput), + Community(InvalidInput), + Message(InvalidInput), } impl std::error::Error for Error {} -error_display! { Error, - delegate = [Error::User, Error::Message, Error::Community, Error::FileOperation, Error::Network, Error::Decode], - unit = [Error::Authenticate => "Authenticate", Error::Server => "Server"], +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Authenticate => write!(f, "Authenticate"), + Error::Server => write!(f, "Server"), + Error::ChannelClosed => write!(f, "Channel closed"), + Error::Config(message) => write!(f, "Config: {message}"), + Error::Network(message) => write!(f, "Network: {message}"), + Error::Decode(message) => write!(f, "Decode: {message}"), + Error::ReadBoundExceed { actual, maximum } => { + write!(f, "Read bound exceeded ({actual} > {maximum})") + } + Error::User(e) => write!(f, "Username: {e}"), + Error::Community(e) => write!(f, "Community name: {e}"), + Error::Message(e) => write!(f, "Message: {e}"), + } + } } -error_from! { Error { - user::Error => Error::User, - community::Error => Error::Community, - message::Error => Error::Message, - file_operation::Error => Error::FileOperation, - network::Error => Error::Network, - decode::Error => Error::Decode, - - std::net::AddrParseError => Error::Network as network::Error, - std::io::Error => Error::Network as network::Error, - quinn::ConnectionError => Error::Network as network::Error, - quinn::ConnectError => Error::Network as network::Error, - quinn::ReadError => Error::Network as network::Error, - quinn::ReadToEndError => Error::Network as network::Error, - quinn::ReadExactError => Error::Network as network::Error, - quinn::WriteError => Error::Network as network::Error, - quinn::ClosedStream => Error::Network as network::Error, - bitcode::Error => Error::Decode as decode::Error, +from_display! { Error { + std::net::AddrParseError => Error::Network, + std::io::Error => Error::Network, + quinn::ConnectionError => Error::Network, + quinn::ConnectError => Error::Network, + quinn::ReadError => Error::Network, + quinn::ReadToEndError => Error::Network, + quinn::ReadExactError => Error::Network, + quinn::WriteError => Error::Network, + quinn::ClosedStream => Error::Network, + bitcode::Error => Error::Decode, } } diff --git a/crates/common/src/error/community.rs b/crates/common/src/error/community.rs deleted file mode 100644 index af37050..0000000 --- a/crates/common/src/error/community.rs +++ /dev/null @@ -1,32 +0,0 @@ -use std::fmt::Display; - -use bitcode::{Decode, Encode}; - -use crate::constant::{MAXIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_COMMUNITY_NAME_LENGTH}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Error { - MaximumLength(usize), - MinimumLength(usize), - ASCII, -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::MaximumLength(length) => write!( - f, - "More than maximum length({}) is provided({})", - MAXIMUM_COMMUNITY_NAME_LENGTH, length - ), - Error::MinimumLength(length) => write!( - f, - "Less than minimum length({}) is provided({})", - MINIMUM_COMMUNITY_NAME_LENGTH, length - ), - Error::ASCII => write!(f, "Given input is not ASCII compatible"), - } - } -} diff --git a/crates/common/src/error/decode.rs b/crates/common/src/error/decode.rs deleted file mode 100644 index afe3812..0000000 --- a/crates/common/src/error/decode.rs +++ /dev/null @@ -1,24 +0,0 @@ -use std::fmt::Display; - -use bitcode::{Decode, Encode}; - -use crate::error_from_display; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Error { - Inner(String), -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Inner(error_value) => error_value.fmt(f), - } - } -} - -error_from_display! { Error { - bitcode::Error => Error::Inner, -} } diff --git a/crates/common/src/error/file_operation.rs b/crates/common/src/error/file_operation.rs deleted file mode 100644 index 2ab073c..0000000 --- a/crates/common/src/error/file_operation.rs +++ /dev/null @@ -1,24 +0,0 @@ -use std::fmt::Display; - -use bitcode::{Decode, Encode}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Error { - FileOpen(String), - Read, - Empty, - Split, -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::FileOpen(error_value) => write!(f, "File open is failed| {}", error_value), - Error::Read => write!(f, "Read file context is failed"), - Error::Empty => write!(f, "File is empty"), - Error::Split => write!(f, "Splitting context is failed"), - } - } -} diff --git a/crates/common/src/error/macro_.rs b/crates/common/src/error/macro_.rs deleted file mode 100644 index a58cd78..0000000 --- a/crates/common/src/error/macro_.rs +++ /dev/null @@ -1,56 +0,0 @@ -#[macro_export] -macro_rules! error_from { - ($target:ty { $($rest:tt)* }) => { - $crate::error_from!(@arm $target, $($rest)*); - }; - - (@arm $target:ty, $source:ty => $variant:path as $middle:ty, $($rest:tt)*) => { - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(<$middle>::from(value).into()) - } - } - $crate::error_from!(@arm $target, $($rest)*); - }; - - (@arm $target:ty, $source:ty => $variant:path, $($rest:tt)*) => { - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(value) - } - } - $crate::error_from!(@arm $target, $($rest)*); - }; - - (@arm $target:ty,) => {}; -} - -#[macro_export] -macro_rules! error_from_display { - ($target:ty { $($source:ty => $variant:path),+ $(,)? }) => { - $( - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(value.to_string()) - } - } - )+ - }; -} - -#[macro_export] -macro_rules! error_display { - ($target:ty, - delegate = [$($variant:path),* $(,)?], - unit = [$($unit:path => $message:literal),* $(,)?] $(,)? - ) => { - impl std::fmt::Display for $target { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - $($variant(error_value) => std::fmt::Display::fmt(error_value, formatter),)* - $($unit => formatter.write_str($message),)* - } - } - } - }; -} diff --git a/crates/common/src/error/message.rs b/crates/common/src/error/message.rs deleted file mode 100644 index 0776644..0000000 --- a/crates/common/src/error/message.rs +++ /dev/null @@ -1,32 +0,0 @@ -use std::fmt::Display; - -use bitcode::{Decode, Encode}; - -use crate::constant::{MAXIMUM_MESSAGE_LENGTH, MINIMUM_MESSAGE_LENGTH}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Error { - MaximumLength(usize), - MinimumLength(usize), - ASCII, -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::MaximumLength(length) => write!( - f, - "More than maximum length({}) is provided({})", - MAXIMUM_MESSAGE_LENGTH, length - ), - Error::MinimumLength(length) => write!( - f, - "Less than minimum length({}) is provided({})", - MINIMUM_MESSAGE_LENGTH, length - ), - Error::ASCII => write!(f, "Given input is not ASCII compatible"), - } - } -} diff --git a/crates/common/src/error/network.rs b/crates/common/src/error/network.rs deleted file mode 100644 index 6aaa574..0000000 --- a/crates/common/src/error/network.rs +++ /dev/null @@ -1,58 +0,0 @@ -use std::fmt::Display; - -use bitcode::{Decode, Encode}; - -use crate::error_from_display; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Error { - AddressParse(String), - InputOutput(String), - Connect(String), - Connection(String), - Read(String), - ReadToEnd(String), - ReadExact(String), - Write(String), - ClosedStream(String), - ConnectionError(String), - ChannelClosed, - ReadBoundExceed(usize, usize), -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::AddressParse(error_value) => error_value.fmt(f), - Error::InputOutput(error_value) => error_value.fmt(f), - Error::Connect(error_value) => error_value.fmt(f), - Error::Connection(error_value) => error_value.fmt(f), - Error::Read(error_value) => error_value.fmt(f), - Error::ReadToEnd(error_value) => error_value.fmt(f), - Error::ReadExact(error_value) => error_value.fmt(f), - Error::Write(error_value) => error_value.fmt(f), - Error::ClosedStream(error_value) => error_value.fmt(f), - Error::ConnectionError(error_value) => error_value.fmt(f), - Error::ChannelClosed => write!(f, "Channel Closed"), - Error::ReadBoundExceed(actual, expected) => write!( - f, - "Read Bound Exceed | Actual = {} | Expected = {}", - actual, expected - ), - } - } -} - -error_from_display! { Error { - std::net::AddrParseError => Error::AddressParse, - std::io::Error => Error::InputOutput, - quinn::ConnectionError => Error::Connection, - quinn::ConnectError => Error::Connect, - quinn::ReadError => Error::Read, - quinn::ReadToEndError => Error::ReadToEnd, - quinn::ReadExactError => Error::ReadExact, - quinn::WriteError => Error::Write, - quinn::ClosedStream => Error::ClosedStream, -} } diff --git a/crates/common/src/error/user.rs b/crates/common/src/error/user.rs deleted file mode 100644 index b3a8832..0000000 --- a/crates/common/src/error/user.rs +++ /dev/null @@ -1,32 +0,0 @@ -use std::fmt::Display; - -use bitcode::{Decode, Encode}; - -use crate::constant::{MAXIMUM_USERNAME_LENGTH, MINIMUM_USERNAME_LENGTH}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Error { - MaximumLength(usize), - MinimumLength(usize), - ASCII, -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::MaximumLength(length) => write!( - f, - "More than maximum length({}) is provided({})", - MAXIMUM_USERNAME_LENGTH, length - ), - Error::MinimumLength(length) => write!( - f, - "Less than minimum length({}) is provided({})", - MINIMUM_USERNAME_LENGTH, length - ), - Error::ASCII => write!(f, "Given input is not ASCII compatible"), - } - } -} diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs deleted file mode 100644 index b4388ee..0000000 --- a/crates/common/src/event.rs +++ /dev/null @@ -1,14 +0,0 @@ -use bitcode::{Decode, Encode}; - -use crate::{community::Community, message::Message, user::User}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Event { - MessageCreate(Message), - MessageUpdate(Message), - MessageDelete(Message), - UserJoin(Community, User), - UserLeave(Community, User), - CommunityUpdate(Community), - CommunityDelete(Community), -} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 4f15998..c7569ef 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -1,11 +1,8 @@ -pub mod community; +pub mod config; pub mod constant; pub mod error; -pub mod event; -pub mod message; +pub mod model; pub mod network; pub mod request; pub mod response; -pub mod user; -pub mod utils; pub mod validate; diff --git a/crates/common/src/message.rs b/crates/common/src/message.rs deleted file mode 100644 index f79000f..0000000 --- a/crates/common/src/message.rs +++ /dev/null @@ -1,42 +0,0 @@ -use bitcode::{Decode, Encode}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Message { - message_id: String, - user_id: String, - community_id: String, - message_body: String, -} - -impl Message { - #[cfg(feature = "server")] - pub fn new(message_id: &str, user_id: &str, community_id: &str, message_body: &str) -> Self { - let message_id = message_id.to_string(); - let user_id = user_id.to_string(); - let community_id = community_id.to_string(); - let message_body = message_body.to_string(); - - Self { - message_id, - user_id, - community_id, - message_body, - } - } - - pub fn get_id(&self) -> &str { - &self.message_id - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_message_body(&self) -> &str { - &self.message_body - } -} diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs new file mode 100644 index 0000000..0677994 --- /dev/null +++ b/crates/common/src/model.rs @@ -0,0 +1,21 @@ +use bitcode::{Decode, Encode}; + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct User { + pub id: String, + pub username: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct Community { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct Message { + pub id: String, + pub user_id: String, + pub community_id: String, + pub body: String, +} diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs index 8b06f7c..becd478 100644 --- a/crates/common/src/network.rs +++ b/crates/common/src/network.rs @@ -3,83 +3,64 @@ use quinn::{RecvStream, SendStream}; use crate::{ constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT}, error::Error, - message::Message, + model::Message, request::Request, response::Response, }; -pub const AUTHENTICATION_MAX_READ_LENGHT: usize = 64; -pub const REQUEST_MAX_READ_LENGHT: usize = MAXIMUM_MESSAGE_LENGTH * 2; +pub const AUTHENTICATION_MAX_READ_LENGTH: usize = 64; +pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; pub const MESSAGE_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; -pub const RESPONSE_MAX_READ_LENGHT: usize = MESSAGE_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; +pub const RESPONSE_MAX_READ_LENGTH: usize = MESSAGE_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; -pub struct Network; - -impl Network { - pub async fn send_response( - response: &Response, - mut send_stream: SendStream, - ) -> Result<(), Error> { - Ok({ - send_stream.write_all(&bitcode::encode(response)).await?; - send_stream.finish()?; - }) - } - - pub async fn receive_request( - mut receive_stream: RecvStream, - size_limit: Option, - ) -> Result { - let request = match size_limit { - Some(size_limit) => receive_stream.read_to_end(size_limit).await?, - None => receive_stream.read_to_end(REQUEST_MAX_READ_LENGHT).await?, - }; +pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> { + send_stream.write_all(&bitcode::encode(response)).await?; + send_stream.finish()?; + Ok(()) +} - Ok(bitcode::decode::(&request)?) - } +pub async fn receive_request( + mut receive_stream: RecvStream, + limit: usize, +) -> Result { + let bytes = receive_stream.read_to_end(limit).await?; + Ok(bitcode::decode(&bytes)?) +} - pub async fn send_request_and_receive_response( - request: &Request, - mut send_stream: SendStream, - mut receive_stream: RecvStream, - ) -> Result { - send_stream.write_all(&bitcode::encode(request)).await?; - send_stream.finish()?; +pub async fn send_request( + request: &Request, + mut send_stream: SendStream, + mut receive_stream: RecvStream, +) -> Result { + send_stream.write_all(&bitcode::encode(request)).await?; + send_stream.finish()?; - let response = receive_stream.read_to_end(RESPONSE_MAX_READ_LENGHT).await?; + let bytes = receive_stream.read_to_end(RESPONSE_MAX_READ_LENGTH).await?; + Ok(bitcode::decode(&bytes)?) +} - Ok(bitcode::decode::(&response)?) - } +pub async fn send_message(message: &Message, send_stream: &mut SendStream) -> Result<(), Error> { + let payload = bitcode::encode(message); + send_stream + .write_all(&(payload.len() as u32).to_le_bytes()) + .await?; + send_stream.write_all(&payload).await?; + Ok(()) +} - pub async fn send_message( - message: &Message, - send_stream: &mut SendStream, - ) -> Result<(), Error> { - let payload = bitcode::encode(message); - send_stream - .write_all(&(payload.len() as u32).to_le_bytes()) - .await?; - send_stream.write_all(&payload).await?; +pub async fn receive_message(receive_stream: &mut RecvStream) -> Result { + let mut length_bytes = [0u8; 4]; + receive_stream.read_exact(&mut length_bytes).await?; - Ok(()) + let length = u32::from_le_bytes(length_bytes) as usize; + if length > MESSAGE_MAX_ENCODED_LENGTH { + return Err(Error::ReadBoundExceed { + actual: length, + maximum: MESSAGE_MAX_ENCODED_LENGTH, + }); } - pub async fn receive_message(receive_stream: &mut RecvStream) -> Result { - let mut length_bytes = [0u8; 4]; - receive_stream.read_exact(&mut length_bytes).await?; - - let length = u32::from_le_bytes(length_bytes) as usize; - if length > MESSAGE_MAX_ENCODED_LENGTH { - return Err(crate::error::network::Error::ReadBoundExceed( - length, - RESPONSE_MAX_READ_LENGHT, - ) - .into()); - } - - let mut payload = vec![0u8; length]; - receive_stream.read_exact(&mut payload).await?; - - Ok(bitcode::decode(&payload)?) - } + let mut payload = vec![0u8; length]; + receive_stream.read_exact(&mut payload).await?; + Ok(bitcode::decode(&payload)?) } diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index 884c8a7..4a015aa 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -1,69 +1,26 @@ use bitcode::{Decode, Encode}; -use crate::request::{ - community::{ - CreateCommunity, DeleteCommunity, ReadCommunity, SearchCommunity, UpdateCommunity, - }, - message::{ - CreateMessage, DeleteMessage, ReadMessage, ReadMessageByCommunityIDWithMarkerAndLimit, - UpdateMessage, - }, - user::{CreateUser, DeleteUser, ReadUser, UpdateUser}, - user_community::{CommunityOf, IsUserIn, JoinCommunity, LeaveCommunity, UsersIn}, -}; - -pub mod community; -pub mod message; -pub mod user; -pub mod user_community; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Authentication(String); - -impl Authentication { - pub fn new(authentication_token: &str) -> Self { - Self(authentication_token.to_string()) - } - - pub fn get_authentication_token(&self) -> &str { - &self.0 - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Deauthentication(String); - -impl Deauthentication { - pub fn new(authentication_token: &str) -> Self { - Self(authentication_token.to_string()) - } - - pub fn get_authentication_token(&self) -> &str { - &self.0 - } -} - #[derive(Debug, Clone, Encode, Decode)] pub enum Request { - Authentication(Authentication), - Deauthentication(Deauthentication), - CreateUser(CreateUser), - ReadUser(ReadUser), - UpdateUser(UpdateUser), - DeleteUser(DeleteUser), - CreateCommunity(CreateCommunity), - ReadCommunity(ReadCommunity), - UpdateCommunity(UpdateCommunity), - DeleteCommunity(DeleteCommunity), - CreateMessage(CreateMessage), - ReadMessage(ReadMessage), - UpdateMessage(UpdateMessage), - DeleteMessage(DeleteMessage), - ReadMessageByCommunityIDWithMarkerAndLimit(ReadMessageByCommunityIDWithMarkerAndLimit), - JoinCommunity(JoinCommunity), - LeaveCommunity(LeaveCommunity), - IsUserIn(IsUserIn), - UsersIn(UsersIn), - CommunityOf(CommunityOf), - SearchCommunity(SearchCommunity), + Authentication { token: String }, + Deauthentication { token: String }, + CreateUser { username: String }, + ReadUser { user_id: String }, + UpdateUser { user_id: String, username: String }, + DeleteUser { user_id: String }, + CreateCommunity { name: String }, + ReadCommunity { community_id: String }, + UpdateCommunity { community_id: String, name: String }, + DeleteCommunity { community_id: String }, + CreateMessage { user_id: String, community_id: String, body: String }, + ReadMessage { message_id: String }, + UpdateMessage { message_id: String, body: String }, + DeleteMessage { message_id: String }, + ReadMessages { community_id: String, marker: String, limit: usize }, + JoinCommunity { user_id: String, community_id: String }, + LeaveCommunity { user_id: String, community_id: String }, + IsUserIn { user_id: String, community_id: String }, + UsersIn { community_id: String }, + CommunitiesOf { user_id: String }, + SearchCommunity { name: String }, } diff --git a/crates/common/src/request/community.rs b/crates/common/src/request/community.rs deleted file mode 100644 index b6dda00..0000000 --- a/crates/common/src/request/community.rs +++ /dev/null @@ -1,100 +0,0 @@ -use bitcode::{Decode, Encode}; - -use crate::{error::Error, validate::validate_community_name}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct CreateCommunity { - community_name: String, -} - -impl CreateCommunity { - pub fn new(community_name: &str) -> Result { - let community_name = community_name.to_string(); - validate_community_name(&community_name)?; - - Ok(Self { community_name }) - } - - pub fn get_community_name(&self) -> &str { - &self.community_name - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct ReadCommunity { - community_id: String, -} - -impl ReadCommunity { - pub fn new(community_id: &str) -> Self { - let community_id = community_id.to_string(); - - Self { community_id } - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct UpdateCommunity { - community_id: String, - community_name: String, -} - -impl UpdateCommunity { - pub fn new(community_id: &str, community_name: &str) -> Result { - let community_id = community_id.to_string(); - let community_name = community_name.to_string(); - validate_community_name(&community_name)?; - - Ok(Self { - community_id, - community_name, - }) - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } - - pub fn get_community_name(&self) -> &str { - &self.community_name - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct DeleteCommunity { - community_id: String, -} - -impl DeleteCommunity { - pub fn new(community_id: &str) -> Self { - let community_id = community_id.to_string(); - - Self { community_id } - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct SearchCommunity { - community_name: String, -} - -impl SearchCommunity { - pub fn new(community_name: &str) -> Result { - let community_name = community_name.to_string(); - validate_community_name(&community_name)?; - - Ok(Self { community_name }) - } - - pub fn get_community_name(&self) -> &str { - &self.community_name - } -} diff --git a/crates/common/src/request/message.rs b/crates/common/src/request/message.rs deleted file mode 100644 index e0936b1..0000000 --- a/crates/common/src/request/message.rs +++ /dev/null @@ -1,130 +0,0 @@ -use bitcode::{Decode, Encode}; - -use crate::{error::Error, validate::validate_message_body}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct CreateMessage { - community_id: String, - user_id: String, - message_body: String, -} - -impl CreateMessage { - pub fn new(user_id: &str, community_id: &str, message_body: &str) -> Result { - let user_id = user_id.to_string(); - let community_id = community_id.to_string(); - let message_body = message_body.to_string(); - validate_message_body(&message_body)?; - - Ok(Self { - community_id, - user_id, - message_body, - }) - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_message_body(&self) -> &str { - &self.message_body - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct ReadMessage { - message_id: String, -} - -impl ReadMessage { - pub fn new(message_id: &str) -> Self { - let message_id = message_id.to_string(); - - Self { message_id } - } - - pub fn get_message_id(&self) -> &str { - &self.message_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct UpdateMessage { - message_id: String, - message_body: String, -} - -impl UpdateMessage { - pub fn new(message_id: &str, message_body: &str) -> Result { - let message_id = message_id.to_string(); - let message_body = message_body.to_string(); - validate_message_body(&message_body)?; - - Ok(Self { - message_id, - message_body, - }) - } - - pub fn get_message_id(&self) -> &str { - &self.message_id - } - - pub fn get_message_body(&self) -> &str { - &self.message_body - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct DeleteMessage { - message_id: String, -} - -impl DeleteMessage { - pub fn new(message_id: &str) -> Self { - let message_id = message_id.to_string(); - - Self { message_id } - } - - pub fn get_message_id(&self) -> &str { - &self.message_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct ReadMessageByCommunityIDWithMarkerAndLimit { - community_id: String, - marker: String, - limit: usize, -} - -impl ReadMessageByCommunityIDWithMarkerAndLimit { - pub fn new(community_id: &str, marker: &str, limit: usize) -> Self { - let community_id = community_id.to_string(); - let marker = marker.to_string(); - - Self { - community_id, - marker, - limit, - } - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } - - pub fn get_marker(&self) -> &str { - self.marker.as_str() - } - - pub fn get_limit(&self) -> usize { - self.limit - } -} diff --git a/crates/common/src/request/user.rs b/crates/common/src/request/user.rs deleted file mode 100644 index 44274ed..0000000 --- a/crates/common/src/request/user.rs +++ /dev/null @@ -1,79 +0,0 @@ -use bitcode::{Decode, Encode}; - -use crate::{error::Error, validate::validate_username}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct CreateUser { - username: String, -} - -impl CreateUser { - pub fn new(username: &str) -> Result { - let username = username.to_string(); - validate_username(&username)?; - - Ok(Self { username }) - } - - pub fn get_username(&self) -> &str { - &self.username - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct ReadUser { - user_id: String, -} - -impl ReadUser { - pub fn new(user_id: &str) -> Self { - let user_id = user_id.to_string(); - - Self { user_id } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct UpdateUser { - user_id: String, - username: String, -} - -impl UpdateUser { - pub fn new(user_id: &str, username: &str) -> Result { - let user_id = user_id.to_string(); - let username = username.to_string(); - validate_username(&username)?; - - Ok(Self { user_id, username }) - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_username(&self) -> &str { - &self.username - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct DeleteUser { - user_id: String, -} - -impl DeleteUser { - pub fn new(user_id: &str) -> Self { - let user_id = user_id.to_string(); - - Self { user_id } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } -} diff --git a/crates/common/src/request/user_community.rs b/crates/common/src/request/user_community.rs deleted file mode 100644 index 011b942..0000000 --- a/crates/common/src/request/user_community.rs +++ /dev/null @@ -1,113 +0,0 @@ -use bitcode::{Decode, Encode}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct JoinCommunity { - user_id: String, - community_id: String, -} - -impl JoinCommunity { - pub fn new(user_id: &str, community_id: &str) -> Self { - let user_id = user_id.to_string(); - let community_id = community_id.to_string(); - - Self { - user_id, - community_id, - } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct LeaveCommunity { - user_id: String, - community_id: String, -} - -impl LeaveCommunity { - pub fn new(user_id: &str, community_id: &str) -> Self { - let user_id = user_id.to_string(); - let community_id = community_id.to_string(); - - Self { - user_id, - community_id, - } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct IsUserIn { - user_id: String, - community_id: String, -} - -impl IsUserIn { - pub fn new(user_id: &str, community_id: &str) -> Self { - let user_id = user_id.to_string(); - let community_id = community_id.to_string(); - - Self { - user_id, - community_id, - } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct UsersIn { - community_id: String, -} - -impl UsersIn { - pub fn new(community_id: &str) -> Self { - let community_id = community_id.to_string(); - - Self { community_id } - } - - pub fn get_community_id(&self) -> &str { - &self.community_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct CommunityOf { - user_id: String, -} - -impl CommunityOf { - pub fn new(user_id: &str) -> Self { - let user_id = user_id.to_string(); - - Self { user_id } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } -} diff --git a/crates/common/src/response.rs b/crates/common/src/response.rs index 6f15cdf..627c7d7 100644 --- a/crates/common/src/response.rs +++ b/crates/common/src/response.rs @@ -1,10 +1,9 @@ use bitcode::{Decode, Encode}; -use crate::{community::Community, error::Error, message::Message, user::User}; - -pub mod community; -pub mod message; -pub mod user; +use crate::{ + error::Error, + model::{Community, Message, User}, +}; #[derive(Debug, Clone, Encode, Decode)] pub enum Response { @@ -22,12 +21,12 @@ pub enum Response { ReadMessage(Message), UpdateMessage(Message), DeleteMessage(Message), - ReadMessageByCommunityIDWithMarkerAndLimit(Vec), + ReadMessages(Vec), JoinCommunity, LeaveCommunity, IsUserIn(bool), UsersIn(Vec), - CommunityOf(Vec), + CommunitiesOf(Vec), SearchCommunity(Vec), Error(Error), } diff --git a/crates/common/src/response/community.rs b/crates/common/src/response/community.rs deleted file mode 100644 index e69de29..0000000 diff --git a/crates/common/src/response/message.rs b/crates/common/src/response/message.rs deleted file mode 100644 index e69de29..0000000 diff --git a/crates/common/src/response/user.rs b/crates/common/src/response/user.rs deleted file mode 100644 index e69de29..0000000 diff --git a/crates/common/src/user.rs b/crates/common/src/user.rs deleted file mode 100644 index 034fd44..0000000 --- a/crates/common/src/user.rs +++ /dev/null @@ -1,25 +0,0 @@ -use bitcode::{Decode, Encode}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct User { - user_id: String, - username: String, -} - -impl User { - #[cfg(feature = "server")] - pub fn new(user_id: &str, username: &str) -> Self { - let user_id = user_id.to_string(); - let username = username.to_string(); - - Self { user_id, username } - } - - pub fn get_user_id(&self) -> &str { - &self.user_id - } - - pub fn get_username(&self) -> &str { - &self.username - } -} diff --git a/crates/common/src/utils.rs b/crates/common/src/utils.rs deleted file mode 100644 index f65524f..0000000 --- a/crates/common/src/utils.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::{ - collections::{HashMap, VecDeque}, - fs::File, - io::Read, - path::Path, -}; - -use crate::error::{Error, file_operation}; - -#[derive(Debug, Clone)] -pub struct TOML { - pub header: String, - pub fields: HashMap, -} - -impl TOML { - pub fn naive_toml_parser_from_file(file_location: impl AsRef) -> Result { - let mut toml_file = File::open(file_location) - .map_err(|error_value| file_operation::Error::FileOpen(error_value.to_string()))?; - let mut toml_ingredients = String::default(); - toml_file - .read_to_string(&mut toml_ingredients) - .map_err(|_| file_operation::Error::Read)?; - - Self::naive_toml_parser_from_content(&toml_ingredients) - } - - pub fn naive_toml_parser_from_content(toml_ingredients: &str) -> Result { - let mut toml_ingredients = toml_ingredients.lines().collect::>(); - - let header = toml_ingredients - .pop_front() - .ok_or(file_operation::Error::Empty)? - .replace('[', "") - .replace(']', "") - .trim_end() - .to_string(); - - let mut fields = HashMap::new(); - - toml_ingredients - .iter() - .try_for_each(|ingredient| -> Result<(), Error> { - let key_and_value = ingredient - .split_once('=') - .ok_or(file_operation::Error::Split)?; - - let key = key_and_value.0.replace('"', "").trim().to_string(); - let value = key_and_value.1.replace('"', "").trim().to_string(); - - fields.insert(key, value); - Ok(()) - })?; - - Ok(TOML { header, fields }) - } -} diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index 98f02b5..a1c10a0 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -1,52 +1,64 @@ -use crate::constant::{ - MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_USERNAME_LENGTH, - MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_USERNAME_LENGTH, +use crate::{ + constant::{ + MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_USERNAME_LENGTH, + MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_USERNAME_LENGTH, + }, + error::{Error, InvalidInput}, }; -type UserError = crate::error::user::Error; -type MessageError = crate::error::message::Error; -type CommunityError = crate::error::community::Error; - -pub fn validate_username(username: &str) -> Result<(), UserError> { - if !username.is_ascii() { - return Err(UserError::ASCII); +fn check( + input: &str, + minimum: usize, + maximum: usize, + ascii_only: bool, +) -> Result<(), InvalidInput> { + if ascii_only && !input.is_ascii() { + return Err(InvalidInput::NotASCII); } - if username.len() < MINIMUM_USERNAME_LENGTH { - return Err(UserError::MinimumLength(username.len())); + if input.len() < minimum { + return Err(InvalidInput::TooShort { + minimum, + actual: input.len(), + }); } - if username.len() > MAXIMUM_USERNAME_LENGTH { - return Err(UserError::MaximumLength(username.len())); + if input.len() > maximum { + return Err(InvalidInput::TooLong { + maximum, + actual: input.len(), + }); } Ok(()) } -pub fn validate_message_body(message: &str) -> Result<(), MessageError> { - if message.len() < MINIMUM_MESSAGE_LENGTH { - return Err(MessageError::MinimumLength(message.len())); - } - - if message.len() > MAXIMUM_MESSAGE_LENGTH { - return Err(MessageError::MaximumLength(message.len())); - } - - Ok(()) +pub fn validate_username(username: &str) -> Result<(), Error> { + check( + username, + MINIMUM_USERNAME_LENGTH, + MAXIMUM_USERNAME_LENGTH, + true, + ) + .map_err(Error::User) } -pub fn validate_community_name(community_name: &str) -> Result<(), CommunityError> { - if !community_name.is_ascii() { - return Err(CommunityError::ASCII); - } - - if community_name.len() < MINIMUM_COMMUNITY_NAME_LENGTH { - return Err(CommunityError::MinimumLength(community_name.len())); - } - - if community_name.len() > MAXIMUM_COMMUNITY_NAME_LENGTH { - return Err(CommunityError::MaximumLength(community_name.len())); - } +pub fn validate_community_name(name: &str) -> Result<(), Error> { + check( + name, + MINIMUM_COMMUNITY_NAME_LENGTH, + MAXIMUM_COMMUNITY_NAME_LENGTH, + true, + ) + .map_err(Error::Community) +} - Ok(()) +pub fn validate_message_body(body: &str) -> Result<(), Error> { + check( + body, + MINIMUM_MESSAGE_LENGTH, + MAXIMUM_MESSAGE_LENGTH, + false, + ) + .map_err(Error::Message) } diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 04e468b..c37fab2 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -7,21 +7,15 @@ edition = "2024" default = ["rcgen"] rcgen = ["dep:rcgen"] -[dev-dependencies] -tempfile = "3.27.0" - [dependencies] -common = { workspace = true, features = ["server"] } +common.workspace = true rcgen = { version = "0.14.10", optional = true } tokio.workspace = true -tokio-stream = { version = "0.1.19", features = ["sync"] } quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } bitcode.workspace = true rustls.workspace = true - -surrealdb = { version = "3.3.0", default-features = false, features = [ - "protocol-ws", - "rustls", - "kv-surrealkv", -] } +turso = "0.9.0-pre.6" ulid = "3.0.0" + +[lints] +workspace = true diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 8cf7370..5f48b14 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -1,33 +1,11 @@ -use crate::{database_::DB, error::Error, user::User}; +use common::{error::Error as CommonError, model::User}; -pub(crate) async fn authenticate( - authentication_token: &str, - database_connection: &DB, -) -> Result { - println!("{}", authentication_token); +use crate::{database::DB, error::Error, user}; - //todo - //Err(Error::Common(common::error::Error::Authenticate)) - let users = User::read_by_username(authentication_token, database_connection).await?; - let user = users +pub async fn authenticate(token: &str, db: &DB) -> Result { + user::read_by_username(token, db) + .await? .into_iter() .next() - .ok_or(Error::Common(common::error::Error::Authenticate))?; - Ok(user) -} - -pub(crate) async fn deauthenticate( - authentication_token: &str, - database_connection: &DB, -) -> Result { - println!("{}", authentication_token); - - //todo - //Err(Error::Common(common::error::Error::Authenticate)) - let users = User::read_by_username(authentication_token, database_connection).await?; - let user = users - .into_iter() - .next() - .ok_or(Error::Common(common::error::Error::Authenticate))?; - Ok(user) + .ok_or(Error::Common(CommonError::Authenticate)) } diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs index e4b788e..2037517 100644 --- a/crates/server/src/community.rs +++ b/crates/server/src/community.rs @@ -1,282 +1,153 @@ -use std::sync::LazyLock; - -use common::validate::validate_community_name; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; -use ulid::Generator; +use common::{model::Community, validate::validate_community_name}; +use turso::Row; use crate::{ - database_::{COMMUNITY_TABLE, DB}, + database::{DB, new_id}, error::Error, }; -mod database; - -static ULID: LazyLock> = LazyLock::new(|| Generator::new().into()); - -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)] -pub struct CommunityID(RecordId); - -impl CommunityID { - async fn new() -> Self { - loop { - match ULID.lock().await.generate() { - Ok(ulid) => return Self(RecordId::new(COMMUNITY_TABLE, ulid.to_string())), - Err(_) => continue, - } - } - } - - pub(crate) fn as_record_id(&self) -> RecordId { - self.0.clone() - } - - pub(crate) fn as_str(&self) -> &str { - match &self.0.key { - RecordIdKey::String(user_id) => user_id, - _ => unreachable!("We shouldn't be here"), - } - } +fn from_row(row: &Row) -> Result { + Ok(Community { + id: row.get(0)?, + name: row.get(1)?, + }) } -impl ToOwned for CommunityID { - type Owned = CommunityID; +pub async fn create(name: &str, db: &DB) -> Result { + validate_community_name(name)?; - fn to_owned(&self) -> Self::Owned { - Self(self.0.clone()) - } -} + let mut rows = db + .query( + "INSERT INTO community (id, name) VALUES (?1, ?2) RETURNING id, name", + (new_id(), name), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; -impl From<&str> for CommunityID { - fn from(value: &str) -> Self { - Self(RecordId::new(COMMUNITY_TABLE, value)) - } + from_row(&row) } -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)] -pub struct CommunityName(String); - -impl CommunityName { - pub fn try_new(community_name: &str) -> Result { - let community_name = community_name.to_string(); - validate_community_name(&community_name)?; - - Ok(Self(community_name)) - } +pub async fn read(community_id: &str, db: &DB) -> Result { + let mut rows = db + .query( + "SELECT id, name FROM community WHERE id = ?1", + (community_id,), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - pub fn as_str(&self) -> &str { - &self.0 - } + from_row(&row) } -impl ToOwned for CommunityName { - type Owned = CommunityName; +pub async fn read_by_name(name: &str, db: &DB) -> Result, Error> { + let mut rows = db + .query( + "SELECT id, name FROM community WHERE name = ?1 ORDER BY id", + (name,), + ) + .await?; - fn to_owned(&self) -> Self::Owned { - Self(self.0.clone()) + let mut communities = Vec::new(); + while let Some(row) = rows.next().await? { + communities.push(from_row(&row)?); } -} -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)] -pub struct Community { - id: CommunityID, - community_name: CommunityName, + Ok(communities) } -impl Community { - async fn new(community_name: &str) -> Result { - let community_name = CommunityName::try_new(community_name)?; - - let id = CommunityID::new().await; - - Ok(Self { id, community_name }) - } - - pub fn get_id(&self) -> &CommunityID { - &self.id - } - - pub fn get_community_name(&self) -> &CommunityName { - &self.community_name - } - - fn update_name(mut self, community_name: &str) -> Result { - self.community_name = CommunityName::try_new(community_name)?; - - Ok(self) - } - - pub async fn create(name: &str, database_connection: &DB) -> Result { - let community = Self::new(name).await?; - - database::create(community, database_connection).await - } - - pub async fn read(id: &CommunityID, database_connection: &DB) -> Result { - database::read(id, database_connection).await - } +pub async fn update(community_id: &str, name: &str, db: &DB) -> Result { + validate_community_name(name)?; - pub async fn read_by_name( - name: &str, - database_connection: &DB, - ) -> Result, Error> { - database::read_by_name(name, database_connection).await - } - - pub async fn read_all(database_connection: &DB) -> Result, Error> { - database::read_all(database_connection).await - } - - pub async fn update(self, name: &str, database_connection: &DB) -> Result { - let user = self.update_name(name)?; - database::update(user, database_connection).await - } + let mut rows = db + .query( + "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name", + (community_id, name), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - pub async fn delete(self, database_connection: &DB) -> Result { - database::delete(self.id, database_connection).await - } + from_row(&row) } -impl Into for Community { - fn into(self) -> common::community::Community { - common::community::Community::new( - self.get_id().as_str(), - self.get_community_name().as_str(), +pub async fn delete(community_id: &str, db: &DB) -> Result { + let mut rows = db + .query( + "DELETE FROM community WHERE id = ?1 RETURNING id, name", + (community_id,), ) - } + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; + + from_row(&row) } #[cfg(test)] mod tests { - use crate::{ - community::Community, - error::{Error, database}, - test, - }; + use crate::{community, error::Error, test}; #[tokio::test] async fn create() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let name = "Tahinli"; - let community = Community::create(name, &database_connection).await; + let community = community::create("Tahinli", &db).await.unwrap(); - assert_eq!(name, community.unwrap().get_community_name().as_str()); + assert_eq!("Tahinli", community.name); } #[tokio::test] async fn read() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let name = "Tahinli"; - let created_community = Community::create(name, &database_connection).await.unwrap(); - - let searched_community = Community::read(&created_community.get_id(), &database_connection) - .await - .unwrap(); + let created_community = community::create("Tahinli", &db).await.unwrap(); + let searched_community = community::read(&created_community.id, &db).await.unwrap(); assert_eq!(created_community, searched_community); } #[tokio::test] async fn read_by_name() { - let (database_connection, _temp_directory) = test::get_database().await; - - let name = "Tahinli"; - let community_1 = Community::create(name, &database_connection).await.unwrap(); - let community_2 = Community::create(name, &database_connection).await.unwrap(); - let _community_3 = Community::create("Not Tahinli", &database_connection) - .await - .unwrap(); - - let expected_result = vec![community_1, community_2]; - - let searched_communitys = Community::read_by_name(name, &database_connection) - .await - .unwrap(); - - assert_eq!(expected_result, searched_communitys); - } - - #[tokio::test] - async fn read_all() { - let (database_connection, _temp_directory) = test::get_database().await; - - let name = "Tahinli"; - let community_1 = Community::create(name, &database_connection).await.unwrap(); - let community_2 = Community::create(name, &database_connection).await.unwrap(); - let community_3 = Community::create("Not Tahinli", &database_connection) - .await - .unwrap(); + let db = test::get_database().await; - let expected_result = vec![community_1, community_2, community_3]; + let community_1 = community::create("Tahinli", &db).await.unwrap(); + let community_2 = community::create("Tahinli", &db).await.unwrap(); + let _community_3 = community::create("Not Tahinli", &db).await.unwrap(); - let searched_communitys = Community::read_all(&database_connection).await.unwrap(); + let searched_communities = community::read_by_name("Tahinli", &db).await.unwrap(); - assert_eq!(expected_result, searched_communitys); + assert_eq!(vec![community_1, community_2], searched_communities); } #[tokio::test] async fn update() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let name = "Tahinli"; - let created_community = Community::create(name, &database_connection).await.unwrap(); - let created_id = created_community.get_id().to_owned(); - let created_community_name = created_community.get_community_name().to_owned(); - - let updated_community = created_community - .update("Not Tahinli", &database_connection) - .await - .unwrap(); - - let searched_community = Community::read(updated_community.get_id(), &database_connection) + let created_community = community::create("Tahinli", &db).await.unwrap(); + let updated_community = community::update(&created_community.id, "Not Tahinli", &db) .await .unwrap(); + let searched_community = community::read(&created_community.id, &db).await.unwrap(); - assert_eq!(&created_id, searched_community.get_id()); - assert_ne!( - &created_community_name, - searched_community.get_community_name() - ); + assert_eq!(created_community.id, searched_community.id); assert_eq!(updated_community, searched_community); + assert_eq!("Not Tahinli", searched_community.name); } #[tokio::test] - async fn update_on_unpersistent_community() { - let (database_connection, _temp_directory) = test::get_database().await; + async fn update_on_missing_community() { + let db = test::get_database().await; - let name = "Tahinli"; - let unpersistent_community = Community::new(name).await.unwrap(); + let updated_community = community::update("missing", "Not Tahinli", &db).await; - let updated_community = unpersistent_community - .update("Not Tahinli", &database_connection) - .await; - - assert!(matches!( - updated_community, - Err(Error::Database(database::Error::Update)), - )); + assert!(matches!(updated_community, Err(Error::NotFound))); } #[tokio::test] async fn delete() { - let (database_connection, _temp_directory) = test::get_database().await; - - let name = "Tahinli"; - let created_community = Community::create(name, &database_connection).await.unwrap(); - let created_id = created_community.get_id().to_owned(); - let created_community_name = created_community.get_community_name().to_owned(); + let db = test::get_database().await; - let deleted_community = created_community - .delete(&database_connection) - .await - .unwrap(); + let created_community = community::create("Tahinli", &db).await.unwrap(); + let deleted_community = community::delete(&created_community.id, &db).await.unwrap(); - assert_eq!(&created_id, deleted_community.get_id()); - assert_eq!( - &created_community_name, - deleted_community.get_community_name() - ); + assert_eq!(created_community, deleted_community); } } diff --git a/crates/server/src/community/database.rs b/crates/server/src/community/database.rs deleted file mode 100644 index 0f013b1..0000000 --- a/crates/server/src/community/database.rs +++ /dev/null @@ -1,67 +0,0 @@ -use crate::{ - community::{Community, CommunityID}, - database_::{COMMUNITY_TABLE, DB}, - error::{self, Error}, -}; - -pub(super) async fn create( - community: Community, - database_connection: &DB, -) -> Result { - let result = database_connection - .create(community.get_id().as_record_id()) - .content(community) - .await?; - - result.ok_or_else(|| error::database::Error::Create.into()) -} - -pub(super) async fn read(id: &CommunityID, database_connection: &DB) -> Result { - let result = database_connection.select(id.as_record_id()).await?; - - result.ok_or_else(|| error::database::Error::Read.into()) -} - -pub(super) async fn read_by_name( - name: &str, - database_connection: &DB, -) -> Result, Error> { - let mut result = database_connection - .query( - " - SELECT * FROM type::table($table) WHERE community_name = $community_name; - ", - ) - .bind(("table", COMMUNITY_TABLE)) - .bind(("community_name", name.to_string())) - .await? - .check()?; - - let result = result.take::>(0)?; - - Ok(result) -} - -pub(super) async fn read_all(database_connection: &DB) -> Result, Error> { - let result = database_connection.select(COMMUNITY_TABLE).await?; - - Ok(result) -} - -pub(super) async fn update( - community: Community, - database_connection: &DB, -) -> Result { - let result = database_connection - .update(community.get_id().as_record_id()) - .content(community) - .await?; - - result.ok_or_else(|| error::database::Error::Update.into()) -} - -pub(super) async fn delete(id: CommunityID, database_connection: &DB) -> Result { - let result = database_connection.delete(id.as_record_id()).await?; - - result.ok_or_else(|| error::database::Error::Delete.into()) -} diff --git a/crates/server/src/database.rs b/crates/server/src/database.rs new file mode 100644 index 0000000..339761c --- /dev/null +++ b/crates/server/src/database.rs @@ -0,0 +1,57 @@ +use std::sync::{LazyLock, Mutex}; + +use ulid::Generator; + +use crate::error::Error; + +pub type DB = turso::Connection; + +static ULID: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); + +pub async fn connect(path: &str) -> Result { + let database = turso::Builder::new_local(path).build().await?; + + Ok(database.connect()?) +} + +pub async fn migrate(db: &DB) -> Result<(), Error> { + db.execute_batch( + " + CREATE TABLE IF NOT EXISTS user ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS community ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS message ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + community_id TEXT NOT NULL, + body TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS message_community_id ON message (community_id); + + CREATE TABLE IF NOT EXISTS user_community ( + user_id TEXT NOT NULL, + community_id TEXT NOT NULL, + PRIMARY KEY (user_id, community_id) + ); + ", + ) + .await?; + + Ok(()) +} + +pub fn new_id() -> String { + loop { + match ULID.lock().unwrap().generate() { + Ok(ulid) => return ulid.to_string(), + Err(_) => continue, + } + } +} diff --git a/crates/server/src/database_.rs b/crates/server/src/database_.rs deleted file mode 100644 index 843aa32..0000000 --- a/crates/server/src/database_.rs +++ /dev/null @@ -1,81 +0,0 @@ -use surrealdb::{ - Surreal, - engine::any::{self, Any}, - opt::auth::Root, -}; - -use crate::{ServerConfig, error::Error}; - -pub type DB = Surreal; - -pub const USER_TABLE: &str = "user"; -pub const COMMUNITY_TABLE: &str = "community"; -pub const MESSAGE_TABLE: &str = "message"; -pub const USER_COMMUNITY_TABLE: &str = "user_community"; - -pub async fn connect(server_config: &ServerConfig) -> Result { - let address = format!( - "{}://{}", - server_config.database_prefix, server_config.database_address - ); - let database_connection = any::connect(address).await?; - - database_connection - .use_ns(server_config.namespace.clone()) - .use_db(server_config.database.clone()) - .await?; - - if !server_config.username.is_empty() && !server_config.password.is_empty() { - database_connection - .signin(Root { - username: server_config.username.clone(), - password: server_config.password.clone(), - }) - .await?; - } - - Ok(database_connection) -} - -pub async fn migrate(database_connection: &DB) -> Result<(), Error> { - database_connection - .query(format!( - " - DEFINE TABLE IF NOT EXISTS {USER_TABLE} SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS username ON {USER_TABLE} TYPE string; - - DEFINE TABLE IF NOT EXISTS {COMMUNITY_TABLE} SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS community_name ON {COMMUNITY_TABLE} TYPE string; - - DEFINE TABLE IF NOT EXISTS {MESSAGE_TABLE} SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS community_id ON {MESSAGE_TABLE} TYPE record<{COMMUNITY_TABLE}>; - DEFINE FIELD IF NOT EXISTS user_id ON {MESSAGE_TABLE} TYPE record<{USER_TABLE}>; - DEFINE FIELD IF NOT EXISTS message_body ON {MESSAGE_TABLE} TYPE string; - DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_community_id ON {MESSAGE_TABLE} FIELDS community_id; - DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_user_id ON {MESSAGE_TABLE} FIELDS user_id; - - DEFINE TABLE IF NOT EXISTS {USER_COMMUNITY_TABLE} TYPE RELATION FROM {USER_TABLE} TO {COMMUNITY_TABLE} ENFORCED SCHEMAFULL; - DEFINE INDEX IF NOT EXISTS {USER_COMMUNITY_TABLE}_unique ON {USER_COMMUNITY_TABLE} FIELDS in, out UNIQUE - " - )) - .await? - .check()?; - - Ok(()) -} - -pub async fn health(database_connection: &DB) -> Result<(), Error> { - Ok(database_connection.health().await?) -} - -// pub fn user_record_id(key: impl Into) -> RecordId { -// RecordId::new(USER_TABLE, key) -// } - -// pub fn community_record_id(key: impl Into) -> RecordId { -// RecordId::new(COMMUNITY_TABLE, key) -// } - -// pub fn message_record_id(key: impl Into) -> RecordId { -// RecordId::new(MESSAGE_TABLE, key) -// } diff --git a/crates/server/src/error.rs b/crates/server/src/error.rs index 1148950..06db31a 100644 --- a/crates/server/src/error.rs +++ b/crates/server/src/error.rs @@ -2,12 +2,11 @@ use std::fmt::Display; use common::error_from; -pub mod database; - #[derive(Debug)] pub enum Error { Common(common::error::Error), - Database(database::Error), + Database(turso::Error), + NotFound, } impl std::error::Error for Error {} @@ -15,8 +14,9 @@ impl std::error::Error for Error {} impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Error::Common(error_value) => error_value.fmt(f), - Error::Database(error_value) => error_value.fmt(f), + Error::Common(error) => write!(f, "{error}"), + Error::Database(error) => write!(f, "Database: {error}"), + Error::NotFound => write!(f, "Not found"), } } } @@ -24,9 +24,9 @@ impl Display for Error { impl From for common::error::Error { fn from(value: Error) -> Self { match value { - Error::Common(error_value) => error_value, - Error::Database(error_value) => { - eprintln!("Error: Database | {}", error_value); + Error::Common(error) => error, + error => { + eprintln!("Error: {error}"); common::error::Error::Server } @@ -36,22 +36,16 @@ impl From for common::error::Error { error_from! { Error { common::error::Error => Error::Common, - database::Error => Error::Database, - - common::error::user::Error => Error::Common as common::error::Error, - common::error::community::Error => Error::Common as common::error::Error, - common::error::message::Error => Error::Common as common::error::Error, - - surrealdb::Error => Error::Database as database::Error, - - std::net::AddrParseError => Error::Common as common::error::network::Error, - std::io::Error => Error::Common as common::error::network::Error, - quinn::ConnectionError => Error::Common as common::error::network::Error, - quinn::ConnectError => Error::Common as common::error::network::Error, - quinn::ReadError => Error::Common as common::error::network::Error, - quinn::ReadToEndError => Error::Common as common::error::network::Error, - quinn::ReadExactError => Error::Common as common::error::network::Error, - quinn::WriteError => Error::Common as common::error::network::Error, - quinn::ClosedStream => Error::Common as common::error::network::Error, - bitcode::Error => Error::Common as common::error::decode::Error, + turso::Error => Error::Database, + + std::net::AddrParseError => Error::Common as common::error::Error, + std::io::Error => Error::Common as common::error::Error, + quinn::ConnectionError => Error::Common as common::error::Error, + quinn::ConnectError => Error::Common as common::error::Error, + quinn::ReadError => Error::Common as common::error::Error, + quinn::ReadToEndError => Error::Common as common::error::Error, + quinn::ReadExactError => Error::Common as common::error::Error, + quinn::WriteError => Error::Common as common::error::Error, + quinn::ClosedStream => Error::Common as common::error::Error, + bitcode::Error => Error::Common as common::error::Error, } } diff --git a/crates/server/src/error/database.rs b/crates/server/src/error/database.rs deleted file mode 100644 index 5cee5cc..0000000 --- a/crates/server/src/error/database.rs +++ /dev/null @@ -1,30 +0,0 @@ -use std::fmt::Display; - -use common::error_from; - -#[derive(Debug)] -pub enum Error { - Inner(surrealdb::Error), - Create, - Read, - Update, - Delete, -} - -impl std::error::Error for Error {} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Inner(error) => write!(f, "{}", error), - Error::Create => write!(f, "Creating a record failed"), - Error::Read => write!(f, "Reading a record failed"), - Error::Update => write!(f, "Updating a record failed"), - Error::Delete => write!(f, "Deleting a record failed"), - } - } -} - -error_from! { Error { - surrealdb::Error => Error::Inner, -} } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index cc64c9c..3e0f5c3 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -1,11 +1,7 @@ -use common::utils::TOML; - -use crate::network::serve; - pub mod authentication; pub mod community; -pub(crate) mod database_; -pub(crate) mod error; +pub mod database; +pub mod error; pub mod message; pub mod network; pub mod request; @@ -21,27 +17,18 @@ const SERVER_CONFIG_FILE_PATH: &str = concat!( ); pub struct ServerConfig { - database_prefix: String, - database_address: String, - namespace: String, - database: String, - username: String, - password: String, - server_address: String, + pub database_path: String, + pub server_address: String, } impl Default for ServerConfig { fn default() -> Self { - let mut toml = TOML::naive_toml_parser_from_file(SERVER_CONFIG_FILE_PATH).unwrap(); + let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH).unwrap(); + let mut fields = common::config::parse(&content).unwrap(); Self { - database_prefix: toml.fields.remove("database_prefix").unwrap(), - database_address: toml.fields.remove("database_address").unwrap(), - namespace: toml.fields.remove("namespace").unwrap(), - database: toml.fields.remove("database").unwrap(), - username: toml.fields.remove("username").unwrap(), - password: toml.fields.remove("password").unwrap(), - server_address: toml.fields.remove("server_address").unwrap(), + database_path: fields.remove("database_path").unwrap(), + server_address: fields.remove("server_address").unwrap(), } } } @@ -52,11 +39,12 @@ pub async fn showtime() { .unwrap(); let server_config = ServerConfig::default(); - let database_connection = database_::connect(&server_config).await.unwrap(); - database_::migrate(&database_connection).await.unwrap(); - database_::health(&database_connection).await.unwrap(); + let database = database::connect(&server_config.database_path) + .await + .unwrap(); + database::migrate(&database).await.unwrap(); - serve(&server_config.server_address, &database_connection) + network::serve(&server_config.server_address, &database) .await .unwrap(); } diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index a5fb7a5..44a1a95 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -2,7 +2,5 @@ use server::showtime; #[tokio::main] async fn main() { - println!("Hello, world!"); - showtime().await; } diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index 31b7140..b5e3f81 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -1,501 +1,209 @@ -use std::sync::LazyLock; - -use common::validate::validate_message_body; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; -use ulid::Generator; +use common::{model::Message, validate::validate_message_body}; +use turso::Row; use crate::{ - community::{Community, CommunityID}, - database_::{DB, MESSAGE_TABLE}, + database::{DB, new_id}, error::Error, - user::{User, UserID}, }; -mod database; - -static ULID: LazyLock> = LazyLock::new(|| Generator::new().into()); - -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)] -pub struct MessageID(RecordId); - -impl MessageID { - async fn new() -> Self { - loop { - match ULID.lock().await.generate() { - Ok(ulid) => return Self(RecordId::new(MESSAGE_TABLE, ulid.to_string())), - Err(_) => continue, - } - } - } - - pub(crate) fn as_record_id(&self) -> RecordId { - self.0.clone() - } - - pub fn as_str(&self) -> &str { - match &self.0.key { - RecordIdKey::String(user_id) => user_id, - _ => unreachable!("We shouldn't be here"), - } - } +fn from_row(row: &Row) -> Result { + Ok(Message { + id: row.get(0)?, + user_id: row.get(1)?, + community_id: row.get(2)?, + body: row.get(3)?, + }) } -impl ToOwned for MessageID { - type Owned = MessageID; - - fn to_owned(&self) -> Self::Owned { - Self(self.0.clone()) - } -} +pub async fn create( + user_id: &str, + community_id: &str, + body: &str, + db: &DB, +) -> Result { + validate_message_body(body)?; + + let mut rows = db + .query( + "INSERT INTO message (id, user_id, community_id, body) VALUES (?1, ?2, ?3, ?4) RETURNING id, user_id, community_id, body", + (new_id(), user_id, community_id, body), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; -impl From<&str> for MessageID { - fn from(value: &str) -> Self { - Self(RecordId::new(MESSAGE_TABLE, value)) - } + from_row(&row) } -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)] -pub struct MessageBody(String); - -impl MessageBody { - pub fn try_new(message_body: &str) -> Result { - let message_body = message_body.to_string(); - validate_message_body(&message_body)?; - - Ok(Self(message_body)) - } +pub async fn read(message_id: &str, db: &DB) -> Result { + let mut rows = db + .query( + "SELECT id, user_id, community_id, body FROM message WHERE id = ?1", + (message_id,), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - pub(crate) fn as_str(&self) -> &str { - &self.0 - } + from_row(&row) } -impl ToOwned for MessageBody { - type Owned = MessageBody; +pub async fn read_page( + community_id: &str, + marker: &str, + limit: usize, + db: &DB, +) -> Result, Error> { + let mut rows = db + .query( + "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND id <= ?2 ORDER BY id DESC LIMIT ?3", + (community_id, marker, limit as i64), + ) + .await?; - fn to_owned(&self) -> Self::Owned { - Self(self.0.clone()) + let mut messages = Vec::new(); + while let Some(row) = rows.next().await? { + messages.push(from_row(&row)?); } -} + messages.reverse(); -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)] -pub struct Message { - id: MessageID, - user_id: UserID, - community_id: CommunityID, - message_body: MessageBody, + Ok(messages) } -impl Message { - async fn new(user: &User, community: &Community, message_body: &str) -> Result { - let message_body = MessageBody::try_new(message_body)?; - - let id = MessageID::new().await; - let user_id = user.get_id().to_owned(); - let community_id = community.get_id().to_owned(); - //todo RecordID olan yerleri düzeltiyoruz - Ok(Self { - id, - user_id, - community_id, - message_body, - }) - } - - pub fn get_user_id(&self) -> &UserID { - &self.user_id - } - - pub fn get_community_id(&self) -> &CommunityID { - &self.community_id - } - - pub fn get_message_body(&self) -> &MessageBody { - &self.message_body - } - - pub fn get_id(&self) -> &MessageID { - &self.id - } - - fn set_message_body(mut self, message_body: &str) -> Result { - self.message_body = MessageBody::try_new(message_body)?; - - Ok(self) - } - - pub async fn create( - user: &User, - community: &Community, - message: &str, - database_connection: &DB, - ) -> Result { - let message = Self::new(user, community, message).await?; - database::create(message, database_connection).await - } - - pub async fn read(id: &MessageID, database_connection: &DB) -> Result { - database::read(id, database_connection).await - } - - pub async fn read_by_community_id( - community_id: &CommunityID, - database_connection: &DB, - ) -> Result, Error> { - database::read_by_community_id(community_id, database_connection).await - } +pub async fn update(message_id: &str, body: &str, db: &DB) -> Result { + validate_message_body(body)?; - pub async fn read_by_community_id_with_marker_and_limit( - community_id: &CommunityID, - marker: &MessageID, - limit: usize, - database_connection: &DB, - ) -> Result, Error> { - database::read_by_community_id_with_marker_and_limit( - community_id, - marker, - limit, - database_connection, + let mut rows = db + .query( + "UPDATE message SET body = ?2 WHERE id = ?1 RETURNING id, user_id, community_id, body", + (message_id, body), ) - .await - } - - pub async fn read_by_user_id( - user_id: &UserID, - database_connection: &DB, - ) -> Result, Error> { - database::read_by_user_id(user_id, database_connection).await - } - - pub async fn update( - self, - message_body: &str, - database_connection: &DB, - ) -> Result { - let message_body = self.set_message_body(message_body)?; - database::update(message_body, database_connection).await - } - - pub async fn delete(self, database_connection: &DB) -> Result { - database::delete(self.id, database_connection).await - } -} - -impl ToOwned for Message { - type Owned = Self; + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - fn to_owned(&self) -> Self::Owned { - Self { - id: self.id.to_owned(), - user_id: self.user_id.to_owned(), - community_id: self.community_id.to_owned(), - message_body: self.message_body.to_owned(), - } - } + from_row(&row) } -impl Into for Message { - fn into(self) -> common::message::Message { - common::message::Message::new( - self.get_id().as_str(), - self.get_user_id().as_str(), - self.get_community_id().as_str(), - self.message_body.as_str(), +pub async fn delete(message_id: &str, db: &DB) -> Result { + let mut rows = db + .query( + "DELETE FROM message WHERE id = ?1 RETURNING id, user_id, community_id, body", + (message_id,), ) - } + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; + + from_row(&row) } #[cfg(test)] mod tests { - use crate::{ - community::Community, - error::{Error, database}, - message::Message, - test, - user::User, - }; + use crate::{community, error::Error, message, test, user}; #[tokio::test] async fn create() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let username = "Tahinli"; - let name = username; - - let user = User::create(username, &database_connection).await.unwrap(); - let community = Community::create(name, &database_connection).await.unwrap(); - - let message_ = name; - let message = Message::create(&user, &community, message_, &database_connection) + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("Tahinli", &db).await.unwrap(); + let message = message::create(&user.id, &community.id, "Tahinli", &db) .await .unwrap(); - assert_eq!(community.get_id(), message.get_community_id()); - assert_eq!(user.get_id(), message.get_user_id()); - assert_eq!(message_, message.get_message_body().as_str()); + assert_eq!(community.id, message.community_id); + assert_eq!(user.id, message.user_id); + assert_eq!("Tahinli", message.body); } #[tokio::test] async fn read() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let name = username; + let db = test::get_database().await; - let user = User::create(username, &database_connection).await.unwrap(); - let community = Community::create(name, &database_connection).await.unwrap(); - - let message_ = name; - let created_message = Message::create(&user, &community, message_, &database_connection) + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("Tahinli", &db).await.unwrap(); + let created_message = message::create(&user.id, &community.id, "Tahinli", &db) .await .unwrap(); - let searched_message = Message::read(created_message.get_id(), &database_connection) - .await - .unwrap(); + let searched_message = message::read(&created_message.id, &db).await.unwrap(); assert_eq!(created_message, searched_message); } #[tokio::test] - async fn read_by_community_id() { - let (database_connection, _temp_directory) = test::get_database().await; + async fn read_page() { + let db = test::get_database().await; - let username = "Tahinli"; - let name = username; + let user_1 = user::create("Tahinli", &db).await.unwrap(); + let user_2 = user::create("Not Tahinli", &db).await.unwrap(); + let community = community::create("Tahinli", &db).await.unwrap(); - let user_1 = User::create(username, &database_connection).await.unwrap(); - let user_2 = User::create("Not Tahinli", &database_connection) + let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &db) .await .unwrap(); - let community_1 = Community::create(name, &database_connection).await.unwrap(); - let community_2 = Community::create("Not Tahinli", &database_connection) + let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &db) .await .unwrap(); - - let message_ = name; - let created_message_1 = - Message::create(&user_1, &community_1, message_, &database_connection) - .await - .unwrap(); - let created_message_2 = - Message::create(&user_2, &community_1, message_, &database_connection) - .await - .unwrap(); - let _created_message_3 = - Message::create(&user_1, &community_2, message_, &database_connection) - .await - .unwrap(); - - let expected_result = vec![created_message_1, created_message_2]; - - let searched_messages = - Message::read_by_community_id(community_1.get_id(), &database_connection) - .await - .unwrap(); - - assert_eq!(expected_result, searched_messages); - } - - #[tokio::test] - async fn read_by_community_id_with_marker_and_limit() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let name = username; - - let user_1 = User::create(username, &database_connection).await.unwrap(); - let user_2 = User::create("Not Tahinli", &database_connection) + let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &db) .await .unwrap(); - let community = Community::create(name, &database_connection).await.unwrap(); - - let message_ = name; - let created_message_1 = - Message::create(&user_1, &community, message_, &database_connection) - .await - .unwrap(); - let created_message_2 = - Message::create(&user_2, &community, message_, &database_connection) - .await - .unwrap(); - - let created_message_3 = - Message::create(&user_2, &community, message_, &database_connection) - .await - .unwrap(); - - let created_message_2_id = created_message_2.get_id().to_owned(); - let created_message_3_id = created_message_3.get_id().to_owned(); - - let mut expected_result = vec![created_message_1, created_message_2, created_message_3]; - - let searched_messages = Message::read_by_community_id_with_marker_and_limit( - community.get_id(), - &created_message_3_id, - 3, - &database_connection, - ) - .await - .unwrap(); - - assert_eq!(expected_result, searched_messages); - - expected_result.remove(0); - - let searched_messages = Message::read_by_community_id_with_marker_and_limit( - community.get_id(), - &created_message_3_id, - 2, - &database_connection, - ) - .await - .unwrap(); - - assert_eq!(expected_result, searched_messages); - - expected_result.pop(); - - let searched_messages = Message::read_by_community_id_with_marker_and_limit( - community.get_id(), - &created_message_2_id, - 1, - &database_connection, - ) - .await - .unwrap(); - assert_eq!(expected_result, searched_messages); - } - - #[tokio::test] - async fn read_by_user_id() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let name = username; - - let user_1 = User::create(username, &database_connection).await.unwrap(); - let user_2 = User::create("Not Tahinli", &database_connection) - .await - .unwrap(); - let community_1 = Community::create(name, &database_connection).await.unwrap(); - let community_2 = Community::create("Not Tahinli", &database_connection) + let searched_messages = message::read_page(&community.id, &message_3.id, 3, &db) .await .unwrap(); - let message_ = name; - let created_message_1 = - Message::create(&user_1, &community_1, message_, &database_connection) - .await - .unwrap(); - let created_message_2 = - Message::create(&user_1, &community_2, message_, &database_connection) - .await - .unwrap(); - let _created_message_3 = - Message::create(&user_2, &community_1, message_, &database_connection) - .await - .unwrap(); - - let expected_result = vec![created_message_1, created_message_2]; - - let searched_messages = Message::read_by_user_id(user_1.get_id(), &database_connection) + assert_eq!( + vec![message_1, message_2, message_3.clone()], + searched_messages + ); + + let searched_messages = message::read_page(&community.id, &message_3.id, 1, &db) .await .unwrap(); - assert_eq!(expected_result, searched_messages); + assert_eq!(vec![message_3], searched_messages); } #[tokio::test] async fn update() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let name = username; - - let user = User::create(username, &database_connection).await.unwrap(); - let community = Community::create(name, &database_connection).await.unwrap(); + let db = test::get_database().await; - let message_ = name; - let created_message = Message::create(&user, &community, message_, &database_connection) + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("Tahinli", &db).await.unwrap(); + let created_message = message::create(&user.id, &community.id, "Tahinli", &db) .await .unwrap(); - let created_message_id = created_message.get_id().to_owned(); - let created_message_user_id = created_message.get_user_id().to_owned(); - let created_message_community_id = created_message.get_community_id().to_owned(); - let created_message_message = created_message.get_message_body().to_owned(); - - let updated_message = created_message - .update("Not Tahinli", &database_connection) - .await - .unwrap(); - - let searched_message = Message::read(updated_message.get_id(), &database_connection) + let updated_message = message::update(&created_message.id, "Not Tahinli", &db) .await .unwrap(); + let searched_message = message::read(&created_message.id, &db).await.unwrap(); - assert_eq!(&created_message_id, updated_message.get_id()); - assert_eq!( - &created_message_community_id, - updated_message.get_community_id() - ); - assert_eq!(&created_message_user_id, updated_message.get_user_id()); - assert_ne!(&created_message_message, updated_message.get_message_body()); + assert_eq!(created_message.user_id, updated_message.user_id); + assert_eq!(created_message.community_id, updated_message.community_id); assert_eq!(updated_message, searched_message); + assert_eq!("Not Tahinli", searched_message.body); } #[tokio::test] - async fn update_on_unpersistent_message() { - let (database_connection, _temp_directory) = test::get_database().await; + async fn update_on_missing_message() { + let db = test::get_database().await; - let username = "Tahinli"; - let name = username; + let updated_message = message::update("missing", "Tahinli", &db).await; - let user = User::create(username, &database_connection).await.unwrap(); - let community = Community::create(name, &database_connection).await.unwrap(); - - let message_ = name; - let unpersistent_message = Message::new(&user, &community, message_).await.unwrap(); - let updated_message = unpersistent_message - .update(message_, &database_connection) - .await; - - assert!(matches!( - updated_message, - Err(Error::Database(database::Error::Update)), - )); + assert!(matches!(updated_message, Err(Error::NotFound))); } #[tokio::test] async fn delete() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let name = username; + let db = test::get_database().await; - let user = User::create(username, &database_connection).await.unwrap(); - let community = Community::create(name, &database_connection).await.unwrap(); - - let message_ = name; - let created_message = Message::create(&user, &community, message_, &database_connection) + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("Tahinli", &db).await.unwrap(); + let created_message = message::create(&user.id, &community.id, "Tahinli", &db) .await .unwrap(); - let created_message_id = created_message.get_id().to_owned(); - let created_message_user_id = created_message.get_user_id().to_owned(); - let created_message_community_id = created_message.get_community_id().to_owned(); - let created_message_message = created_message.get_message_body().to_owned(); - let deleted_message = created_message.delete(&database_connection).await.unwrap(); + let deleted_message = message::delete(&created_message.id, &db).await.unwrap(); - assert_eq!(&created_message_id, deleted_message.get_id()); - assert_eq!( - &created_message_community_id, - deleted_message.get_community_id() - ); - assert_eq!(&created_message_user_id, deleted_message.get_user_id()); - assert_eq!(&created_message_message, deleted_message.get_message_body()); + assert_eq!(created_message, deleted_message); } } diff --git a/crates/server/src/message/database.rs b/crates/server/src/message/database.rs deleted file mode 100644 index c347417..0000000 --- a/crates/server/src/message/database.rs +++ /dev/null @@ -1,104 +0,0 @@ -use crate::{ - community::CommunityID, - database_::{DB, MESSAGE_TABLE}, - error::{self, Error}, - message::{Message, MessageID}, - user::UserID, -}; - -pub(super) async fn create(message: Message, database_connection: &DB) -> Result { - let result = database_connection - .create(message.get_id().as_record_id()) - .content(message) - .await?; - - result.ok_or_else(|| error::database::Error::Create.into()) -} - -pub(super) async fn read(id: &MessageID, database_connection: &DB) -> Result { - let result = database_connection.select(id.as_record_id()).await?; - - result.ok_or_else(|| error::database::Error::Read.into()) -} - -pub(super) async fn read_by_community_id( - community_id: &CommunityID, - database_connection: &DB, -) -> Result, Error> { - let mut result = database_connection - .query( - " - SELECT * FROM type::table($table) WHERE community_id = $community_id; - ", - ) - .bind(("table", MESSAGE_TABLE)) - .bind(("community_id", community_id.as_record_id())) - .await? - .check()?; - - let result = result.take::>(0)?; - - Ok(result) -} - -pub(super) async fn read_by_community_id_with_marker_and_limit( - community_id: &CommunityID, - marker: &MessageID, - limit: usize, - database_connection: &DB, -) -> Result, Error> { - let query = " - SELECT * FROM type::table($table) - WHERE community_id = $community_id AND id <= $before - ORDER BY id DESC LIMIT $limit; - "; - - let mut result = database_connection - .query(query) - .bind(("table", MESSAGE_TABLE)) - .bind(("community_id", community_id.as_record_id())) - .bind(("limit", limit)) - .bind(("before", marker.as_record_id())) - .await? - .check()?; - - let mut result = result.take::>(0)?; - result.reverse(); - - Ok(result) -} - -pub(super) async fn read_by_user_id( - user_id: &UserID, - database_connection: &DB, -) -> Result, Error> { - let mut result = database_connection - .query( - " - SELECT * FROM type::table($table) WHERE user_id = $user_id; - ", - ) - .bind(("table", MESSAGE_TABLE)) - .bind(("user_id", user_id.as_record_id())) - .await? - .check()?; - - let result = result.take::>(0)?; - - Ok(result) -} - -pub(super) async fn update(message: Message, database_connection: &DB) -> Result { - let result = database_connection - .update(message.get_id().as_record_id()) - .content(message) - .await?; - - result.ok_or_else(|| error::database::Error::Update.into()) -} - -pub(super) async fn delete(id: MessageID, database_connection: &DB) -> Result { - let result = database_connection.delete(id.as_record_id()).await?; - - result.ok_or_else(|| error::database::Error::Delete.into()) -} diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index b7eab28..c2fba0f 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -1,35 +1,25 @@ -use std::{ - collections::HashMap, - sync::{ - Arc, - atomic::{AtomicU64, Ordering}, - }, -}; +use std::sync::Arc; use common::{ - network::{AUTHENTICATION_MAX_READ_LENGHT, Network}, + model::Message, + network::{ + AUTHENTICATION_MAX_READ_LENGTH, REQUEST_MAX_READ_LENGTH, receive_request, send_message, + send_response, + }, request::Request, response::Response, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; use tokio::{sync::mpsc, task::JoinHandle}; -use tokio_stream::{StreamExt, wrappers::ReceiverStream}; use crate::{ - authentication::authenticate, - community::{Community, CommunityID}, - database_::DB, - error::Error, - request::handle_request, - user::UserID, - user_community::users_in, + authentication::authenticate, database::DB, error::Error, request::handle_request, + user_community, }; const CHANNEL_LENGTH: usize = 2048; const SESSION_LENGTH: usize = 64; -static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(0); - #[cfg(feature = "rcgen")] fn config() -> quinn::ServerConfig { use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer}; @@ -40,81 +30,64 @@ fn config() -> quinn::ServerConfig { quinn::ServerConfig::with_single_cert(vec![certificate_der], certificate_key.into()).unwrap() } -pub async fn serve(server_address: &str, database_connection: &DB) -> Result<(), Error> { +pub async fn serve(server_address: &str, db: &DB) -> Result<(), Error> { let endpoint = Endpoint::server(config(), server_address.parse()?)?; let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); - let database_connection_clone = || -> DB { database_connection.clone() }; - - tokio::spawn(the_actor(event_receiver, database_connection_clone())); + tokio::spawn(the_actor(event_receiver, db.clone())); while let Some(incoming) = endpoint.accept().await { - let database_connection = database_connection.clone(); - let event_sender = event_sender.clone(); - tokio::spawn(handle_connection( incoming, - event_sender, - database_connection, + event_sender.clone(), + db.clone(), )); } Ok(()) } -async fn handle_connection( - incoming: Incoming, - event_sender: mpsc::Sender, - database_connection: DB, -) { +async fn handle_connection(incoming: Incoming, event_sender: mpsc::Sender, db: DB) { match incoming.await { Ok(connection) => { - if let Err(error_value) = - establish_connection(&connection, event_sender, &database_connection).await - { - eprintln!("Error = Endpoint Accept | {}", error_value.to_string()); + if let Err(error) = establish_connection(&connection, event_sender, &db).await { + eprintln!("Error = Endpoint Accept | {error}"); connection.close(0u8.into(), b"kendine iyi bak"); } } - Err(error_value) => eprintln!("Error = Connection | {}", error_value.to_string()), + Err(error) => eprintln!("Error = Connection | {error}"), } } async fn establish_connection( connection: &Connection, event_sender: mpsc::Sender, - database_connection: &DB, + db: &DB, ) -> Result<(), Error> { let (send_stream, receive_stream) = connection.accept_bi().await?; - let first_request = - Network::receive_request(receive_stream, Some(AUTHENTICATION_MAX_READ_LENGHT)).await?; + let first_request = receive_request(receive_stream, AUTHENTICATION_MAX_READ_LENGTH).await?; - if let Request::Authentication(authentication) = first_request { - let authentication_token = authentication.get_authentication_token(); - let user = authenticate(authentication_token, database_connection).await?; - let response = Response::Authentication(common::user::User::new( - user.get_id().as_str(), - user.get_username().as_str(), - )); + if let Request::Authentication { token } = first_request { + let user = authenticate(&token, db).await?; + let response = Response::Authentication(user.clone()); - let user_id = user.get_id().to_owned(); tokio::spawn(listen( - user_id, + user.id.clone(), connection.clone(), event_sender.clone(), - database_connection.clone(), + db.clone(), )); - Network::send_response(&response, send_stream).await?; + send_response(&response, send_stream).await?; let send_stream = connection.open_uni().await?; let _ = event_sender - .send(Event::Joined( - user.get_id().to_owned(), + .send(Event::Joined { + user_id: user.id, send_stream, - connection.clone(), - )) + connection: connection.clone(), + }) .await; Ok(()) @@ -124,130 +97,105 @@ async fn establish_connection( } async fn listen( - user_id: UserID, + user_id: String, connection: Connection, event_sender: mpsc::Sender, - database_connection: DB, + db: DB, ) { - let read_and_answer = async |user_id: UserID, - send_stream: SendStream, - receive_stream: RecvStream, - event_sender: mpsc::Sender, - database_connection: DB| - -> Result<(), Error> { - let request = Network::receive_request(receive_stream, None).await?; - let response = handle_request(user_id, request, &database_connection).await; - - if let Response::CreateMessage(message) = &response { - let _ = event_sender.send(Event::Sent(message.to_owned())).await; - } - - Network::send_response(&response, send_stream).await?; - - Ok(()) - }; - while let Ok((send_stream, receive_stream)) = connection.accept_bi().await { - let database_connection = database_connection.clone(); - let user_id = user_id.clone(); - tokio::spawn(read_and_answer( - user_id, + user_id.clone(), send_stream, receive_stream, event_sender.clone(), - database_connection, + db.clone(), )); } } -enum Event { - Joined(UserID, SendStream, Connection), - Sent(common::message::Message), -} +async fn read_and_answer( + user_id: String, + send_stream: SendStream, + receive_stream: RecvStream, + event_sender: mpsc::Sender, + db: DB, +) -> Result<(), Error> { + let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?; + let response = handle_request(&user_id, request, &db).await; -type SessionID = u64; + if let Response::CreateMessage(message) = &response { + let _ = event_sender.send(Event::Sent(message.clone())).await; + } -struct Session { - user_id: UserID, - connection: Connection, - message_sender: mpsc::Sender>, - writer: JoinHandle<()>, + send_response(&response, send_stream).await?; + + Ok(()) } -impl Session { - fn new( - user_id: UserID, +enum Event { + Joined { + user_id: String, + send_stream: SendStream, connection: Connection, - message_sender: mpsc::Sender>, - writer: JoinHandle<()>, - ) -> Self { - Self { - user_id, - connection, - message_sender, - writer, - } - } + }, + Sent(Message), +} + +struct Session { + pub user_id: String, + pub connection: Connection, + pub message_sender: mpsc::Sender>, + pub writer: JoinHandle<()>, } async fn write_session( - mut message_receiver: mpsc::Receiver>, + mut message_receiver: mpsc::Receiver>, mut send_stream: SendStream, ) { while let Some(message) = message_receiver.recv().await { - if let Err(error_value) = Network::send_message(&message, &mut send_stream).await { - eprintln!("Error = Message | Session Write | {}", error_value); + if let Err(error) = send_message(&message, &mut send_stream).await { + eprintln!("Error = Message | Session Write | {error}"); break; } } } -async fn the_actor(event_receiver: mpsc::Receiver, database_connection: DB) { - let mut sessions: HashMap = HashMap::new(); - - let mut events = ReceiverStream::new(event_receiver); +async fn the_actor(mut event_receiver: mpsc::Receiver, db: DB) { + let mut sessions: Vec = Vec::new(); - while let Some(event) = events.next().await { - sessions.retain(|_, session| { + while let Some(event) = event_receiver.recv().await { + sessions.retain(|session| { !session.writer.is_finished() && session.connection.close_reason().is_none() }); match event { - Event::Joined(user_id, send_stream, connection) => { + Event::Joined { + user_id, + send_stream, + connection, + } => { let (message_sender, message_receiver) = mpsc::channel(SESSION_LENGTH); let writer = tokio::spawn(write_session(message_receiver, send_stream)); - sessions.insert( - NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed), - Session::new(user_id, connection, message_sender, writer), - ); + sessions.push(Session { + user_id, + connection, + message_sender, + writer, + }); } Event::Sent(message) => { - let Ok(community) = Community::read( - &CommunityID::from(message.get_community_id()), - &database_connection, - ) - .await - else { - eprintln!( - "Error = Message | Community Read | {}", - message.get_community_id() - ); - continue; - }; - - let Ok(users) = users_in(&community, &database_connection).await else { + let Ok(users) = user_community::users_in(&message.community_id, &db).await else { eprintln!( "Error = Message | Community Member Read | {}", - message.get_community_id() + message.community_id ); continue; }; let message = Arc::new(message); - sessions.retain(|session_id, session| { + sessions.retain(|session| { if !users.contains(&session.user_id) { return true; } @@ -256,9 +204,8 @@ async fn the_actor(event_receiver: mpsc::Receiver, database_connection: D Ok(()) => true, Err(mpsc::error::TrySendError::Full(_)) => { eprintln!( - "Error = Message | Session Buffer is Full | {} | {}", - session_id, - session.user_id.as_str() + "Error = Message | Session Buffer is Full | {}", + session.user_id ); session.writer.abort(); false diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 7132274..da32c33 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -1,251 +1,110 @@ use common::{request::Request, response::Response}; use crate::{ - authentication::{authenticate, deauthenticate}, - community::Community, - database_::DB, - error::Error, - message::Message, - user::{User, UserID}, - user_community::{JoinCommunity, LeaveCommunity, communitys_of, is_user_in, users_in}, + authentication::authenticate, community, database::DB, error::Error, message, user, + user_community, }; -pub async fn handle_request( - user_id: UserID, - request: Request, - database_connection: &DB, -) -> Response { - let request_matcher = async || -> Result { - match request { - Request::Authentication(authentication) => { - let user = authenticate( - authentication.get_authentication_token(), - database_connection, - ) - .await?; - - Ok(Response::Authentication(user.into())) - } - Request::Deauthentication(deauthentication) => { - let user = deauthenticate( - deauthentication.get_authentication_token(), - database_connection, - ) - .await?; - - Ok(Response::Deauthentication(user.into())) - } - Request::CreateUser(create_user) => { - let user = User::create(create_user.get_username(), database_connection).await?; - - Ok(Response::CreateUser(user.into())) - } - Request::ReadUser(read_user) => { - let user = User::read(&read_user.get_user_id().into(), database_connection).await?; - - Ok(Response::ReadUser(user.into())) - } - Request::UpdateUser(update_user) => { - let user = - User::read(&update_user.get_user_id().into(), database_connection).await?; - let user = user - .update(update_user.get_username(), database_connection) - .await?; - - Ok(Response::UpdateUser(user.into())) - } - Request::DeleteUser(delete_user) => { - let user = - User::read(&delete_user.get_user_id().into(), database_connection).await?; - let user = user.delete(database_connection).await?; - - Ok(Response::DeleteUser(user.into())) - } - Request::CreateCommunity(create_community) => { - let community = - Community::create(create_community.get_community_name(), database_connection) - .await?; - - JoinCommunity::apply(&user_id, community.get_id(), database_connection).await?; - Ok(Response::CreateCommunity(community.into())) - } - Request::ReadCommunity(read_community) => { - let community = Community::read( - &read_community.get_community_id().into(), - database_connection, - ) - .await?; - - Ok(Response::ReadCommunity(community.into())) - } - Request::UpdateCommunity(update_community) => { - let community = Community::read( - &update_community.get_community_id().into(), - database_connection, - ) - .await?; - - let community = community - .update(update_community.get_community_name(), database_connection) - .await?; - - Ok(Response::UpdateCommunity(community.into())) - } - Request::DeleteCommunity(delete_community) => { - let community = Community::read( - &delete_community.get_community_id().into(), - database_connection, - ) - .await?; - - let community = community.delete(database_connection).await?; - - Ok(Response::DeleteCommunity(community.into())) - } - Request::CreateMessage(create_message) => { - let user = - User::read(&create_message.get_user_id().into(), database_connection).await?; - let community = Community::read( - &create_message.get_community_id().into(), - database_connection, - ) - .await?; - let message = create_message.get_message_body(); - let message = - Message::create(&user, &community, &message, database_connection).await?; - - Ok(Response::CreateMessage(message.into())) - } - Request::ReadMessage(read_message) => { - let message = - Message::read(&read_message.get_message_id().into(), database_connection) - .await?; - - Ok(Response::ReadMessage(message.into())) - } - Request::UpdateMessage(update_message) => { - let message = - Message::read(&update_message.get_message_id().into(), database_connection) - .await?; - - let message = message - .update(update_message.get_message_body(), database_connection) - .await?; - - Ok(Response::UpdateMessage(message.into())) - } - Request::DeleteMessage(delete_message) => { - let message = - Message::read(&delete_message.get_message_id().into(), database_connection) - .await?; - - let message = message.delete(database_connection).await?; - - Ok(Response::DeleteMessage(message.into())) - } - Request::ReadMessageByCommunityIDWithMarkerAndLimit( - read_message_by_community_id_with_marker_and_limit, - ) => { - let messages = Message::read_by_community_id_with_marker_and_limit( - &read_message_by_community_id_with_marker_and_limit - .get_community_id() - .into(), - &read_message_by_community_id_with_marker_and_limit - .get_marker() - .into(), - read_message_by_community_id_with_marker_and_limit.get_limit(), - database_connection, - ) - .await?; - - Ok(Response::ReadMessageByCommunityIDWithMarkerAndLimit( - messages.into_iter().map(Into::into).collect(), - )) - } - Request::JoinCommunity(join_community) => { - JoinCommunity::apply( - &join_community.get_user_id().into(), - &join_community.get_community_id().into(), - database_connection, - ) - .await?; - - Ok(Response::JoinCommunity) - } - Request::LeaveCommunity(leave_community) => { - LeaveCommunity::apply( - &leave_community.get_user_id().into(), - &leave_community.get_community_id().into(), - database_connection, - ) - .await?; - - let community = Community::read( - &leave_community.get_community_id().into(), - database_connection, - ) - .await?; - - if users_in(&community, database_connection).await?.is_empty() { - community.delete(database_connection).await?; - } - - Ok(Response::LeaveCommunity) - } - Request::IsUserIn(is_user_in_) => { - let user = - User::read(&is_user_in_.get_user_id().into(), database_connection).await?; - let community = - Community::read(&is_user_in_.get_community_id().into(), database_connection) - .await?; - - let is_user_in = is_user_in(&user, &community, database_connection).await?; - - Ok(Response::IsUserIn(is_user_in)) - } - Request::UsersIn(users_in_) => { - let community = - Community::read(&users_in_.get_community_id().into(), database_connection) - .await?; - - let users_in = users_in(&community, database_connection).await?; - - Ok(Response::UsersIn( - users_in - .iter() - .map(|user_id| user_id.as_str().to_string()) - .collect(), - )) - } - Request::CommunityOf(community_of_) => { - let user = - User::read(&community_of_.get_user_id().into(), database_connection).await?; - - let community_of = communitys_of(&user, database_connection).await?; - - Ok(Response::CommunityOf( - community_of - .iter() - .map(|community_id| community_id.as_str().to_string()) - .collect(), - )) - } - Request::SearchCommunity(search_community) => { - let communities = Community::read_by_name( - search_community.get_community_name(), - database_connection, - ) - .await?; +pub async fn handle_request(session_user_id: &str, request: Request, db: &DB) -> Response { + match handle(session_user_id, request, db).await { + Ok(response) => response, + Err(error) => Response::Error(error.into()), + } +} - Ok(Response::SearchCommunity( - communities.into_iter().map(Into::into).collect(), - )) - } +async fn handle(session_user_id: &str, request: Request, db: &DB) -> Result { + let response = match request { + Request::Authentication { token } => { + Response::Authentication(authenticate(&token, db).await?) + } + Request::Deauthentication { token } => { + Response::Deauthentication(authenticate(&token, db).await?) + } + Request::CreateUser { username } => { + Response::CreateUser(user::create(&username, db).await?) + } + Request::ReadUser { user_id } => Response::ReadUser(user::read(&user_id, db).await?), + Request::UpdateUser { user_id, username } => { + Response::UpdateUser(user::update(&user_id, &username, db).await?) + } + Request::DeleteUser { user_id } => Response::DeleteUser(user::delete(&user_id, db).await?), + Request::CreateCommunity { name } => { + let community = community::create(&name, db).await?; + user_community::join(session_user_id, &community.id, db).await?; + Response::CreateCommunity(community) + } + Request::ReadCommunity { community_id } => { + Response::ReadCommunity(community::read(&community_id, db).await?) + } + Request::UpdateCommunity { community_id, name } => { + Response::UpdateCommunity(community::update(&community_id, &name, db).await?) + } + Request::DeleteCommunity { community_id } => { + Response::DeleteCommunity(community::delete(&community_id, db).await?) + } + Request::CreateMessage { + user_id, + community_id, + body, + } => { + user::read(&user_id, db).await?; + community::read(&community_id, db).await?; + Response::CreateMessage(message::create(&user_id, &community_id, &body, db).await?) + } + Request::ReadMessage { message_id } => { + Response::ReadMessage(message::read(&message_id, db).await?) + } + Request::UpdateMessage { message_id, body } => { + Response::UpdateMessage(message::update(&message_id, &body, db).await?) + } + Request::DeleteMessage { message_id } => { + Response::DeleteMessage(message::delete(&message_id, db).await?) + } + Request::ReadMessages { + community_id, + marker, + limit, + } => Response::ReadMessages(message::read_page(&community_id, &marker, limit, db).await?), + Request::JoinCommunity { + user_id, + community_id, + } => { + user_community::join(&user_id, &community_id, db).await?; + Response::JoinCommunity + } + Request::LeaveCommunity { + user_id, + community_id, + } => { + user_community::leave(&user_id, &community_id, db).await?; + if user_community::users_in(&community_id, db) + .await? + .is_empty() + { + community::delete(&community_id, db).await?; + } + Response::LeaveCommunity + } + Request::IsUserIn { + user_id, + community_id, + } => { + user::read(&user_id, db).await?; + community::read(&community_id, db).await?; + Response::IsUserIn(user_community::is_user_in(&user_id, &community_id, db).await?) + } + Request::UsersIn { community_id } => { + community::read(&community_id, db).await?; + Response::UsersIn(user_community::users_in(&community_id, db).await?) + } + Request::CommunitiesOf { user_id } => { + user::read(&user_id, db).await?; + Response::CommunitiesOf(user_community::communities_of(&user_id, db).await?) + } + Request::SearchCommunity { name } => { + Response::SearchCommunity(community::read_by_name(&name, db).await?) } }; - match request_matcher().await { - Ok(response) => response, - Err(error_value) => Response::Error(error_value.into()), - } + Ok(response) } diff --git a/crates/server/src/test.rs b/crates/server/src/test.rs index 38e67f9..165619e 100644 --- a/crates/server/src/test.rs +++ b/crates/server/src/test.rs @@ -1,25 +1,8 @@ -#[cfg(test)] -use crate::{ - ServerConfig, - database_::{self, DB}, -}; -use tempfile::TempDir; +use crate::database::{self, DB}; -pub async fn get_database() -> (DB, TempDir) { - let temp_directory = TempDir::new().unwrap(); +pub async fn get_database() -> DB { + let database = database::connect(":memory:").await.unwrap(); + database::migrate(&database).await.unwrap(); - let server_config = ServerConfig { - database_prefix: "surrealkv".to_string(), - database_address: temp_directory.path().display().to_string(), - namespace: "yumush".to_string(), - database: "yumush".to_string(), - username: "".to_string(), - password: "".to_string(), - server_address: "127.0.0.1:2026".to_string(), - }; - - let database_connection = database_::connect(&server_config).await.unwrap(); - database_::migrate(&database_connection).await.unwrap(); - - (database_connection, temp_directory) + database } diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index 95a587e..0932eee 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -1,261 +1,150 @@ -use std::sync::LazyLock; - -use common::validate::validate_username; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; -use ulid::Generator; +use common::{model::User, validate::validate_username}; +use turso::Row; use crate::{ - database_::{DB, USER_TABLE}, + database::{DB, new_id}, error::Error, }; -mod database; - -static ULID: LazyLock> = LazyLock::new(|| Generator::new().into()); - -#[derive(Debug, Clone, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)] -pub struct UserID(RecordId); - -impl UserID { - async fn new() -> Self { - loop { - match ULID.lock().await.generate() { - Ok(ulid) => return Self(RecordId::new(USER_TABLE, ulid.to_string())), - Err(_) => continue, - } - } - } - - pub(crate) fn as_record_id(&self) -> RecordId { - self.0.clone() - } - - pub(crate) fn as_str(&self) -> &str { - match &self.0.key { - RecordIdKey::String(user_id) => user_id, - _ => unreachable!("We shouldn't be here"), - } - } -} - -impl From<&str> for UserID { - fn from(value: &str) -> Self { - Self(RecordId::new(USER_TABLE, value)) - } +fn from_row(row: &Row) -> Result { + Ok(User { + id: row.get(0)?, + username: row.get(1)?, + }) } -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)] -pub struct Username(String); +pub async fn create(username: &str, db: &DB) -> Result { + validate_username(username)?; -impl Username { - pub fn try_new(username: &str) -> Result { - let username = username.to_string(); - validate_username(&username)?; + let mut rows = db + .query( + "INSERT INTO user (id, username) VALUES (?1, ?2) RETURNING id, username", + (new_id(), username), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - Ok(Self(username)) - } - - pub fn as_str(&self) -> &str { - &self.0 - } + from_row(&row) } -impl ToOwned for Username { - type Owned = Username; +pub async fn read(user_id: &str, db: &DB) -> Result { + let mut rows = db + .query("SELECT id, username FROM user WHERE id = ?1", (user_id,)) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - fn to_owned(&self) -> Self::Owned { - Self(self.0.clone()) - } -} - -#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)] -pub struct User { - id: UserID, - username: Username, + from_row(&row) } -impl User { - pub fn get_id(&self) -> &UserID { - &self.id - } - - pub fn get_username(&self) -> &Username { - &self.username - } - - async fn new(username: &str) -> Result { - let username = Username::try_new(username)?; - let id = UserID::new().await; - - Ok(Self { id, username }) - } - - fn update_username(mut self, username: &str) -> Result { - self.username = Username::try_new(username)?; - - Ok(self) - } - - pub async fn create(username: &str, database_connection: &DB) -> Result { - let user = Self::new(username).await?; - - database::create(user, database_connection).await - } +pub async fn read_by_username(username: &str, db: &DB) -> Result, Error> { + let mut rows = db + .query( + "SELECT id, username FROM user WHERE username = ?1 ORDER BY id", + (username,), + ) + .await?; - pub async fn read(id: &UserID, database_connection: &DB) -> Result { - database::read(id, database_connection).await + let mut users = Vec::new(); + while let Some(row) = rows.next().await? { + users.push(from_row(&row)?); } - pub async fn read_by_username( - username: &str, - database_connection: &DB, - ) -> Result, Error> { - database::read_by_username(username, database_connection).await - } + Ok(users) +} - pub async fn read_all(database_connection: &DB) -> Result, Error> { - database::read_all(database_connection).await - } +pub async fn update(user_id: &str, username: &str, db: &DB) -> Result { + validate_username(username)?; - pub async fn update(self, username: &str, database_connection: &DB) -> Result { - let user = self.update_username(username)?; - database::update(user, database_connection).await - } + let mut rows = db + .query( + "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username", + (user_id, username), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; - pub async fn delete(self, database_connection: &DB) -> Result { - database::delete(self.id, database_connection).await - } + from_row(&row) } -impl Into for User { - fn into(self) -> common::user::User { - common::user::User::new(self.get_id().as_str(), self.get_username().as_str()) - } +pub async fn delete(user_id: &str, db: &DB) -> Result { + let mut rows = db + .query( + "DELETE FROM user WHERE id = ?1 RETURNING id, username", + (user_id,), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; + + from_row(&row) } #[cfg(test)] mod tests { - use crate::{ - error::{Error, database}, - test, - user::User, - }; + use crate::{error::Error, test, user}; #[tokio::test] async fn create() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let username = "Tahinli"; - let user = User::create(username, &database_connection).await; + let user = user::create("Tahinli", &db).await.unwrap(); - assert_eq!(username, user.unwrap().get_username().as_str()); + assert_eq!("Tahinli", user.username); } #[tokio::test] async fn read() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let username = "Tahinli"; - let created_user = User::create(username, &database_connection).await.unwrap(); - - let searched_user = User::read(&created_user.get_id(), &database_connection) - .await - .unwrap(); + let created_user = user::create("Tahinli", &db).await.unwrap(); + let searched_user = user::read(&created_user.id, &db).await.unwrap(); assert_eq!(created_user, searched_user); } #[tokio::test] async fn read_by_username() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let user_1 = User::create(username, &database_connection).await.unwrap(); - let user_2 = User::create(username, &database_connection).await.unwrap(); - let _user_3 = User::create("Not Tahinli", &database_connection) - .await - .unwrap(); - - let expected_result = vec![user_1, user_2]; - - let searched_users = User::read_by_username(username, &database_connection) - .await - .unwrap(); - - assert_eq!(expected_result, searched_users); - } + let db = test::get_database().await; - #[tokio::test] - async fn read_all() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let user_1 = User::create(username, &database_connection).await.unwrap(); - let user_2 = User::create(username, &database_connection).await.unwrap(); - let user_3 = User::create("Not Tahinli", &database_connection) - .await - .unwrap(); + let user_1 = user::create("Tahinli", &db).await.unwrap(); + let user_2 = user::create("Tahinli", &db).await.unwrap(); + let _user_3 = user::create("Not Tahinli", &db).await.unwrap(); - let expected_result = vec![user_1, user_2, user_3]; + let searched_users = user::read_by_username("Tahinli", &db).await.unwrap(); - let searched_users = User::read_all(&database_connection).await.unwrap(); - - assert_eq!(expected_result, searched_users); + assert_eq!(vec![user_1, user_2], searched_users); } #[tokio::test] async fn update() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let created_user = User::create(username, &database_connection).await.unwrap(); - let created_id = created_user.get_id().to_owned(); - let created_user_username = created_user.get_username().to_owned(); + let db = test::get_database().await; - let updated_user = created_user - .update("Not Tahinli", &database_connection) + let created_user = user::create("Tahinli", &db).await.unwrap(); + let updated_user = user::update(&created_user.id, "Not Tahinli", &db) .await .unwrap(); + let searched_user = user::read(&created_user.id, &db).await.unwrap(); - let searched_user = User::read(updated_user.get_id(), &database_connection) - .await - .unwrap(); - - assert_eq!(&created_id, searched_user.get_id()); - assert_ne!(&created_user_username, searched_user.get_username()); + assert_eq!(created_user.id, searched_user.id); assert_eq!(updated_user, searched_user); + assert_eq!("Not Tahinli", searched_user.username); } #[tokio::test] - async fn update_on_unpersistent_user() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let unperistent_user = User::new(username).await.unwrap(); + async fn update_on_missing_user() { + let db = test::get_database().await; - let updated_user = unperistent_user - .update("Not Tahinli", &database_connection) - .await; + let updated_user = user::update("missing", "Not Tahinli", &db).await; - assert!(matches!( - updated_user, - Err(Error::Database(database::Error::Update)), - )); + assert!(matches!(updated_user, Err(Error::NotFound))); } #[tokio::test] async fn delete() { - let (database_connection, _temp_directory) = test::get_database().await; - - let username = "Tahinli"; - let created_user = User::create(username, &database_connection).await.unwrap(); - let created_id = created_user.get_id().to_owned(); - let created_user_username = created_user.get_username().to_owned(); + let db = test::get_database().await; - let deleted_user = created_user.delete(&database_connection).await.unwrap(); + let created_user = user::create("Tahinli", &db).await.unwrap(); + let deleted_user = user::delete(&created_user.id, &db).await.unwrap(); - assert_eq!(&created_id, deleted_user.get_id()); - assert_eq!(&created_user_username, deleted_user.get_username()); + assert_eq!(created_user, deleted_user); } } diff --git a/crates/server/src/user/database.rs b/crates/server/src/user/database.rs deleted file mode 100644 index d2144a1..0000000 --- a/crates/server/src/user/database.rs +++ /dev/null @@ -1,61 +0,0 @@ -use crate::{ - database_::{DB, USER_TABLE}, - error::{self, Error}, - user::{User, UserID}, -}; - -pub(super) async fn create(user: User, database_connection: &DB) -> Result { - let result = database_connection - .create(user.get_id().as_record_id()) - .content(user) - .await?; - - result.ok_or_else(|| error::database::Error::Create.into()) -} - -pub(super) async fn read(id: &UserID, database_connection: &DB) -> Result { - let result = database_connection.select(id.as_record_id()).await?; - - result.ok_or_else(|| error::database::Error::Read.into()) -} - -pub(super) async fn read_by_username( - username: &str, - database_connection: &DB, -) -> Result, Error> { - let mut result = database_connection - .query( - " - SELECT * FROM type::table($table) WHERE username = $username; - ", - ) - .bind(("table", USER_TABLE)) - .bind(("username", username.to_string())) - .await? - .check()?; - - let result = result.take::>(0)?; - - Ok(result) -} - -pub(super) async fn read_all(database_connection: &DB) -> Result, Error> { - let result = database_connection.select(USER_TABLE).await?; - - Ok(result) -} - -pub(super) async fn update(user: User, database_connection: &DB) -> Result { - let result = database_connection - .update(user.get_id().as_record_id()) - .content(user) - .await?; - - result.ok_or_else(|| error::database::Error::Update.into()) -} - -pub(super) async fn delete(id: UserID, database_connection: &DB) -> Result { - let result = database_connection.delete(id.as_record_id()).await?; - - result.ok_or_else(|| error::database::Error::Delete.into()) -} diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index 44a54f4..df8277c 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -1,268 +1,193 @@ -use crate::{ - community::{Community, CommunityID}, - database_::DB, - error::Error, - user::{User, UserID}, -}; - -mod database; - -#[derive(Debug)] -pub enum CommunityEvent { - JoinCommunity(JoinCommunity), - LeaveCommunity(LeaveCommunity), -} - -#[derive(Debug)] -pub struct JoinCommunity { - user_id: UserID, - community_id: CommunityID, -} +use crate::{database::DB, error::Error}; -impl JoinCommunity { - fn new(user_id: &UserID, community_id: &CommunityID) -> Self { - let user_id = user_id.to_owned(); - let community_id = community_id.to_owned(); +pub async fn join(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> { + db.execute( + "INSERT INTO user_community (user_id, community_id) VALUES (?1, ?2)", + (user_id, community_id), + ) + .await?; - Self { - user_id, - community_id, - } - } + Ok(()) +} - pub fn get_user_id(&self) -> &UserID { - &self.user_id - } +pub async fn leave(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> { + let deleted = db + .execute( + "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", + (user_id, community_id), + ) + .await?; - pub fn get_community_id(&self) -> &CommunityID { - &self.community_id + if deleted == 0 { + return Err(Error::NotFound); } - pub async fn apply( - user_id: &UserID, - community_id: &CommunityID, - database_connection: &DB, - ) -> Result<(), Error> { - let join_community = Self::new(user_id, community_id); - - database::join(&join_community, database_connection).await - } + Ok(()) } -#[derive(Debug)] -pub struct LeaveCommunity { - user_id: UserID, - community_id: CommunityID, +pub async fn is_user_in(user_id: &str, community_id: &str, db: &DB) -> Result { + let mut rows = db + .query( + "SELECT COUNT(*) FROM user_community WHERE user_id = ?1 AND community_id = ?2", + (user_id, community_id), + ) + .await?; + let row = rows.next().await?.ok_or(Error::NotFound)?; + let count: i64 = row.get(0)?; + + Ok(count > 0) } -impl LeaveCommunity { - fn new(user_id: &UserID, community_id: &CommunityID) -> Self { - let user_id = user_id.to_owned(); - let community_id = community_id.to_owned(); - - Self { - user_id, - community_id, - } +pub async fn users_in(community_id: &str, db: &DB) -> Result, Error> { + let mut rows = db + .query( + "SELECT user_id FROM user_community WHERE community_id = ?1 ORDER BY user_id", + (community_id,), + ) + .await?; + + let mut user_ids = Vec::new(); + while let Some(row) = rows.next().await? { + user_ids.push(row.get(0)?); } - pub fn get_user_id(&self) -> &UserID { - &self.user_id - } - - pub fn get_community_id(&self) -> &CommunityID { - &self.community_id - } - - pub async fn apply( - user_id: &UserID, - community_id: &CommunityID, - database_connection: &DB, - ) -> Result<(), Error> { - let leave_community = Self::new(user_id, community_id); - - database::leave(&leave_community, database_connection).await - } + Ok(user_ids) } -pub async fn is_user_in( - user: &User, - community: &Community, - database_connection: &DB, -) -> Result { - database::is_user_in(user, community, database_connection).await -} +pub async fn communities_of(user_id: &str, db: &DB) -> Result, Error> { + let mut rows = db + .query( + "SELECT community_id FROM user_community WHERE user_id = ?1 ORDER BY community_id", + (user_id,), + ) + .await?; + + let mut community_ids = Vec::new(); + while let Some(row) = rows.next().await? { + community_ids.push(row.get(0)?); + } -pub async fn users_in( - community: &Community, - database_connection: &DB, -) -> Result, Error> { - database::users_in(community, database_connection).await -} -pub async fn communitys_of( - user: &User, - database_connection: &DB, -) -> Result, Error> { - database::communitys_of(user, database_connection).await + Ok(community_ids) } #[cfg(test)] mod tests { - use crate::{ - community::Community, - error::{Error, database}, - test, - user::User, - user_community::{self, JoinCommunity, LeaveCommunity, is_user_in}, - }; + use crate::{community, error::Error, test, user, user_community}; #[tokio::test] async fn join() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let user = User::create("Tahinli", &database_connection).await.unwrap(); - let community = Community::create("The Community", &database_connection) - .await - .unwrap(); - - let join = - JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection).await; + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("The Community", &db).await.unwrap(); - assert_eq!(true, join.is_ok()); - - let is_user_in = is_user_in(&user, &community, &database_connection) + user_community::join(&user.id, &community.id, &db) .await .unwrap(); - assert!(is_user_in); + assert!( + user_community::is_user_in(&user.id, &community.id, &db) + .await + .unwrap() + ); } #[tokio::test] async fn join_again() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let user = User::create("Tahinli", &database_connection).await.unwrap(); - let community = Community::create("The Community", &database_connection) - .await - .unwrap(); + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("The Community", &db).await.unwrap(); - JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection) + user_community::join(&user.id, &community.id, &db) .await .unwrap(); - let join = - JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection).await; - - assert!(join.is_err()); + assert!( + user_community::join(&user.id, &community.id, &db) + .await + .is_err() + ); } #[tokio::test] async fn leave() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let user = User::create("Tahinli", &database_connection).await.unwrap(); - let community = Community::create("The Community", &database_connection) - .await - .unwrap(); - JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection) + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("The Community", &db).await.unwrap(); + user_community::join(&user.id, &community.id, &db) .await .unwrap(); - let leave = - LeaveCommunity::apply(user.get_id(), community.get_id(), &database_connection).await; - - assert!(leave.is_ok()); - - let is_user_in = is_user_in(&user, &community, &database_connection) + user_community::leave(&user.id, &community.id, &db) .await .unwrap(); - assert!(!is_user_in); + assert!( + !user_community::is_user_in(&user.id, &community.id, &db) + .await + .unwrap() + ); } #[tokio::test] async fn leave_again() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let user = User::create("Tahinli", &database_connection).await.unwrap(); - let community = Community::create("The Community", &database_connection) + let user = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("The Community", &db).await.unwrap(); + user_community::join(&user.id, &community.id, &db) .await .unwrap(); - JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection) + user_community::leave(&user.id, &community.id, &db) .await .unwrap(); - LeaveCommunity::apply(user.get_id(), community.get_id(), &database_connection) - .await - .unwrap(); - - let leave = - LeaveCommunity::apply(user.get_id(), community.get_id(), &database_connection).await; + let leave = user_community::leave(&user.id, &community.id, &db).await; - assert!(matches!( - leave, - Err(Error::Database(database::Error::Delete)) - )); + assert!(matches!(leave, Err(Error::NotFound))); } #[tokio::test] async fn users_in() { - let (database_connection, _temp_directory) = test::get_database().await; + let db = test::get_database().await; - let user_1 = User::create("Tahinli", &database_connection).await.unwrap(); - let user_2 = User::create("Tahinli", &database_connection).await.unwrap(); - let _user_3 = User::create("Tahinli", &database_connection).await.unwrap(); - let community = Community::create("The Community", &database_connection) - .await - .unwrap(); + let user_1 = user::create("Tahinli", &db).await.unwrap(); + let user_2 = user::create("Tahinli", &db).await.unwrap(); + let _user_3 = user::create("Tahinli", &db).await.unwrap(); + let community = community::create("The Community", &db).await.unwrap(); - JoinCommunity::apply(user_1.get_id(), community.get_id(), &database_connection) + user_community::join(&user_1.id, &community.id, &db) .await .unwrap(); - - JoinCommunity::apply(user_2.get_id(), community.get_id(), &database_connection) + user_community::join(&user_2.id, &community.id, &db) .await .unwrap(); - let users_in = user_community::users_in(&community, &database_connection) - .await - .unwrap(); - let expected_result = vec![user_1.get_id().to_owned(), user_2.get_id().to_owned()]; + let users_in = user_community::users_in(&community.id, &db).await.unwrap(); - assert_eq!(users_in, expected_result) + assert_eq!(vec![user_1.id, user_2.id], users_in); } #[tokio::test] - async fn communitys_of() { - let (database_connection, _temp_directory) = test::get_database().await; + async fn communities_of() { + let db = test::get_database().await; - let user = User::create("Tahinli", &database_connection).await.unwrap(); - let community_1 = Community::create("The Community", &database_connection) - .await - .unwrap(); - let community_2 = Community::create("The Community", &database_connection) - .await - .unwrap(); - let _community_3 = Community::create("The Community", &database_connection) - .await - .unwrap(); + let user = user::create("Tahinli", &db).await.unwrap(); + let community_1 = community::create("The Community", &db).await.unwrap(); + let community_2 = community::create("The Community", &db).await.unwrap(); + let _community_3 = community::create("The Community", &db).await.unwrap(); - JoinCommunity::apply(user.get_id(), community_1.get_id(), &database_connection) + user_community::join(&user.id, &community_1.id, &db) .await .unwrap(); - - JoinCommunity::apply(user.get_id(), community_2.get_id(), &database_connection) + user_community::join(&user.id, &community_2.id, &db) .await .unwrap(); - let communitys_of = user_community::communitys_of(&user, &database_connection) - .await - .unwrap(); - let expected_result = vec![ - community_1.get_id().to_owned(), - community_2.get_id().to_owned(), - ]; + let communities_of = user_community::communities_of(&user.id, &db).await.unwrap(); - assert_eq!(communitys_of, expected_result) + assert_eq!(vec![community_1.id, community_2.id], communities_of); } } diff --git a/crates/server/src/user_community/database.rs b/crates/server/src/user_community/database.rs deleted file mode 100644 index 0da00f4..0000000 --- a/crates/server/src/user_community/database.rs +++ /dev/null @@ -1,105 +0,0 @@ -use surrealdb::types::Value; - -use crate::{ - community::{Community, CommunityID}, - database_::{COMMUNITY_TABLE, DB, USER_COMMUNITY_TABLE, USER_TABLE}, - error::{Error, database}, - user::{User, UserID}, - user_community::{JoinCommunity, LeaveCommunity}, -}; - -pub(super) async fn join( - join_community: &JoinCommunity, - database_connection: &DB, -) -> Result<(), Error> { - let query = format!("RELATE $user_id->{USER_COMMUNITY_TABLE}-> $community_id;"); - database_connection - .query(query) - .bind(("user_id", join_community.get_user_id().as_record_id())) - .bind(( - "community_id", - join_community.get_community_id().as_record_id(), - )) - .await? - .check()?; - - Ok(()) -} - -pub(super) async fn leave( - leave_community: &LeaveCommunity, - database_connection: &DB, -) -> Result<(), Error> { - let query = - format!("DELETE $user_id->{USER_COMMUNITY_TABLE} WHERE out = $community_id RETURN BEFORE;"); - let mut result = database_connection - .query(query) - .bind(("user_id", leave_community.get_user_id().as_record_id())) - .bind(( - "community_id", - leave_community.get_community_id().as_record_id(), - )) - .await? - .check()?; - - let deleted = result.take::>(0)?; - if deleted.is_empty() { - return Err(database::Error::Delete.into()); - } else { - Ok(()) - } -} - -pub(super) async fn is_user_in( - user: &User, - community: &Community, - database_connection: &DB, -) -> Result { - let query = format!( - "RETURN count(SELECT 1 FROM {USER_COMMUNITY_TABLE} WHERE in = $user_id AND out = $community_id) > 0;" - ); - let mut result = database_connection - .query(query) - .bind(("user_id", user.get_id().as_record_id())) - .bind(("community_id", community.get_id().as_record_id())) - .await? - .check()?; - - let result = result.take::>(0)?; - - Ok(result.unwrap_or(false)) -} - -pub(super) async fn users_in( - community: &Community, - database_connection: &DB, -) -> Result, Error> { - let query = format!("RETURN $community_id<-{USER_COMMUNITY_TABLE}<-{USER_TABLE};"); - let mut result = database_connection - .query(query) - .bind(("community_id", community.get_id().as_record_id())) - .await? - .check()?; - - let mut result = result.take::>(0)?; - result.sort(); - - Ok(result) -} - -pub(super) async fn communitys_of( - user: &User, - database_connection: &DB, -) -> Result, Error> { - let query = format!("RETURN $user_id->{USER_COMMUNITY_TABLE}->{COMMUNITY_TABLE};"); - let mut result = database_connection - .query(query) - .bind(("user_id", user.get_id().as_record_id())) - .await? - .check()?; - - let mut result = result.take::>(0)?; - result.sort(); - - Ok(result) -}