forge
Explore
Log in

Don't you dare go Hollow

Simplify every crate and move the server to turso

Browse files at this commit

c2e3b2d52ec8cbb23408e646dd2418dab4d07eedAhmet Kaan GümüşParent: 6306f14
  • refactor
    • simplify every crate and move the server to turso
Show full message
♻️ refactor: simplify every crate and move the server to turso

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.

60 changed files +1745 -4151

Cargo.tomlmodified+8 -3
@@ -2,19 +2,24 @@
2 resolver = "2"2 resolver = "2"
3 members = ["crates/client", "crates/common", "crates/server"]3 members = ["crates/client", "crates/common", "crates/server"]
4 4
5+[profile.dev]
6+debug = "line-tables-only"
7+
5 [profile.release]8 [profile.release]
6 opt-level = 39 opt-level = 3
7 lto = "fat"10 lto = "fat"
8 codegen-units = 111 codegen-units = 1
9 panic = "abort"12 panic = "abort"
10-strip = "symbols"13+debug = "line-tables-only"
11-debug = false
12 overflow-checks = false14 overflow-checks = false
13 incremental = false15 incremental = false
14 16
17+[workspace.lints.rust]
18+unsafe_code = "forbid"
19+
15 [workspace.dependencies]20 [workspace.dependencies]
16 common = { path = "crates/common" }21 common = { path = "crates/common" }
17-tokio = { version = "1.53.1", features = ["full"] }22+tokio = { version = "1.54.1", features = ["full"] }
18 bitcode = "0.6.9"23 bitcode = "0.6.9"
19 quinn = { version = "0.11.12", default-features = false, features = [24 quinn = { version = "0.11.12", default-features = false, features = [
20 "runtime-tokio",25 "runtime-tokio",
configs/server_config.example.tomlmodified+1 -6
@@ -1,8 +1,3 @@
1 [server_config]1 [server_config]
2-database_prefix = "wss"2+database_path = "yumush.db"
3-database_address = "127.0.0.1:8000"
4-namespace = "yumush"
5-database = "yumush"
6-username = "yumush"
7-password = "yumush"
8 server_address = "127.0.0.1:2026"3 server_address = "127.0.0.1:2026"
crates/client/Cargo.tomlmodified+5 -2
@@ -4,8 +4,11 @@ version = "0.1.0"
4 edition = "2024"4 edition = "2024"
5 5
6 [dependencies]6 [dependencies]
7-common = { workspace = true, features = ["client"] }7+common.workspace = true
8 tokio.workspace = true8 tokio.workspace = true
9-quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }9+quinn = { workspace = true, features = ["rustls-ring"] }
10 10
11 gpui-kit = "0.7.0"11 gpui-kit = "0.7.0"
12+
13+[lints]
14+workspace = true
crates/client/src/event.rsdeleted+0 -39
@@ -1,39 +0,0 @@
1-use std::time::Duration;
2-
3-use gpui_kit::{Context, Window};
4-
5-use crate::gui::Yumush;
6-
7-const CHECK_INTERVAL: Duration = Duration::from_secs(3);
8-
9-impl Yumush {
10- pub fn time_based_repetitive_checks_after_login(
11- &self,
12- window: &mut Window,
13- cx: &mut Context<Self>,
14- ) {
15- cx.spawn_in(window, async move |this, cx| {
16- loop {
17- cx.background_executor().timer(CHECK_INTERVAL).await;
18-
19- let keep_going = this.update_in(cx, |yumush, window, cx| {
20- if !yumush.is_logged_in() {
21- return false;
22- }
23-
24- if yumush.is_connected() {
25- yumush.get_chat_users(window, cx);
26- yumush.get_communities(window, cx);
27- }
28-
29- true
30- });
31-
32- if !matches!(keep_going, Ok(true)) {
33- break;
34- }
35- }
36- })
37- .detach();
38- }
39-}
crates/client/src/gui.rsmodified+92 -66
@@ -1,31 +1,38 @@
1-use common::user::User;1+use std::fmt::Display;
2+use std::time::Duration;
3+
4+use common::model::User;
2 use gpui_kit::{5 use gpui_kit::{
3- Context, IntoElement, ParentElement, Render, Styled, Window,6+ AppContext, AsyncWindowContext, Context, Entity, IntoElement, ParentElement, Render, Styled,
4- component::{ActiveTheme, WindowExt, button::Button, notification::Notification},7+ WeakEntity, Window,
8+ component::{
9+ ActiveTheme, WindowExt, button::Button, input::InputState, notification::Notification,
10+ },
5 div, rgb,11 div, rgb,
6 };12 };
7 use tokio::sync::mpsc;13 use tokio::sync::mpsc;
8 14
9-use crate::{15+use crate::network::{NetworkEvent, NetworkHandle};
10- gui::{chat::Chat, login::Login, register::Register},16+
11- network::{NetworkEvent, NetworkHandle},17+mod auth;
12-};
13 mod chat;18 mod chat;
14-mod login;
15-mod register;
16 19
17-#[derive(Debug, PartialEq, Eq)]20+use auth::Auth;
21+use chat::Chat;
22+
23+const CHECK_INTERVAL: Duration = Duration::from_secs(3);
24+
25+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18 enum Route {26 enum Route {
19- Register,
20 Login,27 Login,
28+ Register,
21 Chat,29 Chat,
22 }30 }
23 31
24 pub struct Yumush {32 pub struct Yumush {
25 user: Option<User>,33 user: Option<User>,
26 current_route: Route,34 current_route: Route,
27- register: Register,35+ auth: Auth,
28- login: Login,
29 chat: Chat,36 chat: Chat,
30 network: NetworkHandle,37 network: NetworkHandle,
31 connected: bool,38 connected: bool,
@@ -54,65 +61,62 @@ impl Yumush {
54 Self {61 Self {
55 user: None,62 user: None,
56 current_route: Route::Login,63 current_route: Route::Login,
57- register: Register::new(window, cx),64+ auth: Auth::new(window, cx),
58- login: Login::new(window, cx),
59 chat: Chat::new(window, cx),65 chat: Chat::new(window, cx),
60 network,66 network,
61 connected: false,67 connected: false,
62 }68 }
63 }69 }
64 70
65- fn set_user(&mut self, user: User) {71+ fn start_polling(&self, window: &mut Window, cx: &mut Context<Self>) {
66- self.user = Some(user);72+ cx.spawn_in(window, async move |this, cx| {
67- }73+ loop {
68-74+ cx.background_executor().timer(CHECK_INTERVAL).await;
69- fn get_user(&self) -> Option<User> {
70- self.user.clone()
71- }
72 75
73- fn reset_user(&mut self) {76+ let keep_going = this.update_in(cx, |yumush, window, cx| {
74- self.user = None;77+ if yumush.user.is_none() {
75- }78+ return false;
79+ }
76 80
77- pub fn is_connected(&self) -> bool {81+ if yumush.connected {
78- self.connected82+ yumush.get_chat_users(window, cx);
79- }83+ yumush.get_communities(window, cx);
84+ }
80 85
81- pub fn is_logged_in(&self) -> bool {86+ true
82- self.user.is_some()87+ });
83- }
84 88
85- fn get_username(&self) -> Option<&str> {89+ if !matches!(keep_going, Ok(true)) {
86- self.user.as_ref().map(|user| user.get_username())90+ break;
91+ }
92+ }
93+ })
94+ .detach();
87 }95 }
88 96
89 fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {97 fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
90- let Some(user) = self.get_user() else {98+ let Some(user) = self.user.take() else {
91 return;99 return;
92 };100 };
93 let network = self.network.clone();101 let network = self.network.clone();
94 102
95- self.reset_user();
96 self.chat.reset();103 self.chat.reset();
97 self.change_page(Route::Login, window, cx);104 self.change_page(Route::Login, window, cx);
98 105
99 cx.spawn_in(window, async move |this, cx| {106 cx.spawn_in(window, async move |this, cx| {
100- if let Err(error_value) = network.deauthenticate(user.get_username()).await {107+ if let Err(error) = network.deauthenticate(&user.username).await {
101- let _ = this.update_in(cx, |_, window, cx| {108+ notify_error(&this, cx, error);
102- window.push_notification(Notification::error(error_value.to_string()), cx);
103- });
104 }109 }
105 })110 })
106 .detach();111 .detach();
107 }112 }
108 113
109- fn change_page(&mut self, new_route: Route, window: &mut Window, cx: &mut Context<Self>) {114+ fn change_page(&mut self, route: Route, window: &mut Window, cx: &mut Context<Self>) {
110- self.current_route = new_route;115+ self.current_route = route;
111 cx.notify();116 cx.notify();
112 117
113- match self.current_route {118+ match route {
114- Route::Register => self.register.focus(window, cx),119+ Route::Login | Route::Register => self.auth.focus(window, cx),
115- Route::Login => self.login.focus(window, cx),
116 Route::Chat => self.chat.focus(window, cx),120 Route::Chat => self.chat.focus(window, cx),
117 }121 }
118 }122 }
@@ -127,9 +131,9 @@ impl Yumush {
127 NetworkEvent::Connected(user) => {131 NetworkEvent::Connected(user) => {
128 self.connected = true;132 self.connected = true;
129 match user {133 match user {
130- Some(user) => self.set_user(user),134+ Some(user) => self.user = Some(user),
131- None if self.is_logged_in() => {135+ None if self.user.is_some() => {
132- self.reset_user();136+ self.user = None;
133 self.change_page(Route::Login, window, cx);137 self.change_page(Route::Login, window, cx);
134 }138 }
135 None => {}139 None => {}
@@ -138,15 +142,49 @@ impl Yumush {
138 NetworkEvent::ConnectionFailed(_) | NetworkEvent::Disconnected(_) => {142 NetworkEvent::ConnectionFailed(_) | NetworkEvent::Disconnected(_) => {
139 self.connected = false;143 self.connected = false;
140 }144 }
141- NetworkEvent::MessageReceived(message) => self.chat.push_message(message),145+ NetworkEvent::MessageReceived(message) => self.chat.merge_messages(vec![message]),
142 }146 }
143 147
144 cx.notify();148 cx.notify();
145 }149 }
146 }150 }
147 151
152+pub fn notify_error<T: 'static>(
153+ this: &WeakEntity<T>,
154+ cx: &mut AsyncWindowContext,
155+ error: impl Display,
156+) {
157+ let _ = this.update_in(cx, |_, window, cx| {
158+ window.push_notification(Notification::error(error.to_string()), cx);
159+ });
160+}
161+
162+fn new_input(
163+ placeholder: &'static str,
164+ window: &mut Window,
165+ cx: &mut Context<Yumush>,
166+) -> Entity<InputState> {
167+ cx.new(|cx| {
168+ let mut input_state = InputState::new(window, cx);
169+ input_state.set_placeholder(placeholder, window, cx);
170+
171+ input_state
172+ })
173+}
174+
148 impl Render for Yumush {175 impl Render for Yumush {
149 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {176 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
177+ let route = self.current_route;
178+ let page = match route {
179+ Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(),
180+ Route::Chat => self.chat_page(cx).into_any_element(),
181+ };
182+ let status_color = if self.connected {
183+ rgb(0x22c55e)
184+ } else {
185+ rgb(0xef4444)
186+ };
187+
150 div()188 div()
151 .size_full()189 .size_full()
152 .relative()190 .relative()
@@ -159,11 +197,7 @@ impl Render for Yumush {
159 .size_full()197 .size_full()
160 .bg(rgb(0x1e1e1e))198 .bg(rgb(0x1e1e1e))
161 .text_color(cx.theme().foreground)199 .text_color(cx.theme().foreground)
162- .child(match self.current_route {200+ .child(page),
163- Route::Register => self.register_page(cx).into_any_element(),
164- Route::Login => self.login_page(cx).into_any_element(),
165- Route::Chat => self.chat_page(cx).into_any_element(),
166- }),
167 )201 )
168 .child(202 .child(
169 div()203 div()
@@ -174,20 +208,12 @@ impl Render for Yumush {
174 .flex_row()208 .flex_row()
175 .items_center()209 .items_center()
176 .gap_2()210 .gap_2()
177- .child(211+ .children(
178- div()212+ self.user.as_ref().map(|user| {
179- .text_color(if self.connected {213+ div().text_color(status_color).child(user.username.clone())
180- rgb(0x22c55e)214+ }),
181- } else {
182- rgb(0xef4444)
183- })
184- .child(format!(
185- "{:?} is {}",
186- self.get_username(),
187- if self.connected { "online" } else { "offline" }
188- )),
189 )215 )
190- .children(self.is_logged_in().then(|| {216+ .children(self.user.is_some().then(|| {
191 let entity = cx.entity();217 let entity = cx.entity();
192 218
193 Button::new("logout_button").label("Logout").on_click(219 Button::new("logout_button").label("Logout").on_click(
crates/client/src/gui/auth.rsadded+91 -0
@@ -0,0 +1,91 @@
1+use gpui_kit::{
2+ Context, Entity, IntoElement, ParentElement, Styled, Window,
3+ component::{
4+ button::Button,
5+ input::{Input, InputEvent, InputState},
6+ },
7+ div,
8+};
9+
10+use crate::gui::{Route, Yumush, new_input, notify_error};
11+
12+pub struct Auth {
13+ username_input: Entity<InputState>,
14+}
15+
16+impl Auth {
17+ pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {
18+ let username_input = new_input("Username...", window, cx);
19+ username_input.update(cx, |input, cx| input.focus(window, cx));
20+
21+ cx.subscribe_in(&username_input, window, |this, _, event, window, cx| {
22+ if matches!(event, InputEvent::PressEnter { .. }) {
23+ submit(this, window, cx);
24+ }
25+ })
26+ .detach();
27+
28+ Self { username_input }
29+ }
30+
31+ pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {
32+ self.username_input
33+ .update(cx, |input, cx| input.focus(window, cx));
34+ }
35+}
36+
37+fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) {
38+ let username = this.auth.username_input.read(cx).text().to_string();
39+ let route = this.current_route;
40+ let network = this.network.clone();
41+
42+ cx.spawn_in(window, async move |this, cx| {
43+ let result = match route {
44+ Route::Register => network.create_user(&username).await,
45+ _ => network.authenticate(&username).await,
46+ };
47+
48+ match result {
49+ Ok(user) => {
50+ let _ = this.update_in(cx, |yumush, window, cx| {
51+ yumush.user = Some(user);
52+ yumush.change_page(Route::Chat, window, cx);
53+ yumush.start_polling(window, cx);
54+ });
55+ }
56+ Err(error) => notify_error(&this, cx, error),
57+ }
58+ })
59+ .detach();
60+}
61+
62+impl Yumush {
63+ pub(super) fn auth_page(&self, route: Route, cx: &mut Context<Self>) -> impl IntoElement {
64+ let (action_label, switch_route, switch_label) = match route {
65+ Route::Register => ("Register", Route::Login, "Go to Login Page"),
66+ _ => ("Login", Route::Register, "Go to Register Page"),
67+ };
68+
69+ let entity = cx.entity();
70+ let action_button =
71+ Button::new("auth_button")
72+ .label(action_label)
73+ .on_click(move |_, window, cx| {
74+ entity.update(cx, |this, cx| submit(this, window, cx));
75+ });
76+
77+ let entity = cx.entity();
78+ let switch_button = Button::new("auth_switch_button")
79+ .label(switch_label)
80+ .on_click(move |_, window, cx| {
81+ entity.update(cx, |this, cx| this.change_page(switch_route, window, cx));
82+ });
83+
84+ div()
85+ .w_1_5()
86+ .child("Username")
87+ .child(Input::new(&self.auth.username_input))
88+ .child(action_button)
89+ .child(switch_button)
90+ }
91+}
crates/client/src/gui/chat.rsmodified+313 -389
@@ -1,12 +1,10 @@
1 use common::{1 use common::{
2- community::Community,
3 constant::NEWEST_MESSAGE_MARKER,2 constant::NEWEST_MESSAGE_MARKER,
4- message::Message,3+ model::{Community, Message, User},
5- user::User,
6 validate::{validate_community_name, validate_message_body},4 validate::{validate_community_name, validate_message_body},
7 };5 };
8 use gpui_kit::{6 use gpui_kit::{
9- AppContext, Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement,7+ Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement,
10 StatefulInteractiveElement, Styled, Window,8 StatefulInteractiveElement, Styled, Window,
11 component::{9 component::{
12 WindowExt,10 WindowExt,
@@ -17,103 +15,56 @@ use gpui_kit::{
17 div, rgb,15 div, rgb,
18 };16 };
19 17
20-use crate::gui::Yumush;18+use crate::gui::{Yumush, new_input, notify_error};
19+
20+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21+enum Panel {
22+ None,
23+ Create,
24+ Join,
25+}
21 26
22 pub struct Chat {27 pub struct Chat {
23 communities: Vec<Community>,28 communities: Vec<Community>,
24 selected_community_id: Option<String>,29 selected_community_id: Option<String>,
25 users: Vec<User>,30 users: Vec<User>,
26- chat_messages: Vec<Message>,31+ messages: Vec<Message>,
32+ panel: Panel,
27 message_input: Entity<InputState>,33 message_input: Entity<InputState>,
28 community_name_input: Entity<InputState>,34 community_name_input: Entity<InputState>,
29- creating_community: bool,
30 community_search_input: Entity<InputState>,35 community_search_input: Entity<InputState>,
31- community_search_results: Vec<Community>,36+ search_results: Vec<Community>,
32- joining_community: bool,
33 }37 }
34 38
35 impl Chat {39 impl Chat {
36 pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {40 pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {
37- let message_input = cx.new(|cx| {41+ let message_input = new_input("", window, cx);
38- let mut input_state = InputState::new(window, cx);
39- input_state.set_placeholder("", window, cx);
40-
41- input_state
42- });
43-
44 cx.subscribe_in(&message_input, window, |this, input, event, window, cx| {42 cx.subscribe_in(&message_input, window, |this, input, event, window, cx| {
45 if matches!(event, InputEvent::PressEnter { .. }) {43 if matches!(event, InputEvent::PressEnter { .. }) {
46- let message_body = input.read(cx).text().to_string();44+ send_message(this, input, window, cx);
47-
48- if let Err(error_value) = validate_message_body(&message_body) {
49- window.push_notification(Notification::error(error_value.to_string()), cx);
50-
51- return;
52- }
53-
54- let Some(user) = this.get_user() else {
55- return;
56- };
57-
58- let network = this.network.clone();
59- let Some(community_id) = this.chat.selected_community_id.clone() else {
60- window.push_notification(Notification::error("No Community Selected"), cx);
61- return;
62- };
63-
64- cx.spawn_in(window, async move |this, cx| {
65- if let Err(error_value) = network
66- .create_message(user.get_user_id(), &community_id, &message_body)
67- .await
68- {
69- let _ = this.update_in(cx, |_, window, cx| {
70- window.push_notification(
71- Notification::error(error_value.to_string()),
72- cx,
73- );
74- });
75- }
76- })
77- .detach();
78-
79- input.update(cx, |input_state, cx| {
80- input_state.set_value("", window, cx);
81- });
82 }45 }
83 })46 })
84 .detach();47 .detach();
85 48
86- let community_name_input = cx.new(|cx| {49+ let community_name_input = new_input("Community Name...", window, cx);
87- let mut input_state = InputState::new(window, cx);
88- input_state.set_placeholder("Community Name...", window, cx);
89-
90- input_state
91- });
92-
93 cx.subscribe_in(50 cx.subscribe_in(
94 &community_name_input,51 &community_name_input,
95 window,52 window,
96 |this, input, event, window, cx| {53 |this, input, event, window, cx| {
97 if matches!(event, InputEvent::PressEnter { .. }) {54 if matches!(event, InputEvent::PressEnter { .. }) {
98- create_community_action(this, input, window, cx);55+ create_community(this, input, window, cx);
99 }56 }
100 },57 },
101 )58 )
102 .detach();59 .detach();
103 60
104- let community_search_input = cx.new(|cx| {61+ let community_search_input = new_input("Community Name...", window, cx);
105- let mut input_state = InputState::new(window, cx);
106- input_state.set_placeholder("Community Name...", window, cx);
107-
108- input_state
109- });
110-
111 cx.subscribe_in(62 cx.subscribe_in(
112 &community_search_input,63 &community_search_input,
113 window,64 window,
114 |this, input, event, window, cx| {65 |this, input, event, window, cx| {
115 if matches!(event, InputEvent::PressEnter { .. }) {66 if matches!(event, InputEvent::PressEnter { .. }) {
116- search_community_action(this, input, window, cx);67+ search_community(this, input, window, cx);
117 }68 }
118 },69 },
119 )70 )
@@ -123,152 +74,134 @@ impl Chat {
123 communities: vec![],74 communities: vec![],
124 selected_community_id: None,75 selected_community_id: None,
125 users: vec![],76 users: vec![],
126- chat_messages: vec![],77+ messages: vec![],
78+ panel: Panel::None,
127 message_input,79 message_input,
128 community_name_input,80 community_name_input,
129- creating_community: false,
130 community_search_input,81 community_search_input,
131- community_search_results: vec![],82+ search_results: vec![],
132- joining_community: false,
133 }83 }
134 }84 }
135 85
136- pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) {86+ pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {
137- self.message_input.update(cx, |input, cx| {87+ self.message_input
138- input.focus(window, cx);88+ .update(cx, |input, cx| input.focus(window, cx));
139- });
140 }89 }
141 90
142- pub fn push_message(&mut self, message: Message) {91+ pub fn merge_messages(&mut self, messages: Vec<Message>) {
143- self.merge_messages(vec![message]);92+ self.messages.extend(messages);
93+ self.messages.sort_by(|left, right| left.id.cmp(&right.id));
94+ self.messages.dedup_by(|left, right| left.id == right.id);
144 }95 }
145 96
146- fn merge_messages(&mut self, messages: Vec<Message>) {97+ fn set_panel(&mut self, panel: Panel) {
147- self.chat_messages.extend(messages);98+ if panel != Panel::Join {
148- self.chat_messages99+ self.search_results.clear();
149- .sort_by(|left, right| left.get_id().cmp(right.get_id()));
150- self.chat_messages
151- .dedup_by(|left, right| left.get_id() == right.get_id());
152- }
153-
154- pub fn update_user_list(&mut self, users: Vec<User>) {
155- self.users = users;
156- }
157-
158- pub fn update_community_list(&mut self, communities: Vec<Community>) {
159- if self.selected_community_id.is_none() {
160- self.selected_community_id = communities
161- .first()
162- .map(|community| community.get_community_id().to_string());
163 }100 }
164-101+ self.panel = panel;
165- self.communities = communities;
166- }
167-
168- pub fn get_selected_community_id(&self) -> Option<String> {
169- self.selected_community_id.to_owned()
170- }
171-
172- pub fn set_selected_community_id(&mut self, selected_community_id: Option<String>) {
173- self.selected_community_id = selected_community_id
174- }
175-
176- pub fn update_searched_community_list(&mut self, communities: Vec<Community>) {
177- self.community_search_results = communities;
178- }
179-
180- pub fn set_joining_community(&mut self, joining_community: bool) {
181- self.joining_community = joining_community
182 }102 }
183 103
184 pub fn reset(&mut self) {104 pub fn reset(&mut self) {
185 self.communities.clear();105 self.communities.clear();
186 self.selected_community_id = None;106 self.selected_community_id = None;
187 self.users.clear();107 self.users.clear();
188- self.chat_messages.clear();108+ self.messages.clear();
189- self.creating_community = false;109+ self.set_panel(Panel::None);
190- self.community_search_results.clear();
191- self.joining_community = false;
192 }110 }
193 }111 }
194 112
195-fn create_community_action(113+fn send_message(
196 this: &mut Yumush,114 this: &mut Yumush,
197 input: &Entity<InputState>,115 input: &Entity<InputState>,
198 window: &mut Window,116 window: &mut Window,
199- cx: &mut Context<'_, Yumush>,117+ cx: &mut Context<Yumush>,
200 ) {118 ) {
201- let community_name = input.read(cx).text().to_string();119+ let body = input.read(cx).text().to_string();
202-
203- if let Err(error_value) = validate_community_name(&community_name) {
204- window.push_notification(Notification::error(error_value.to_string()), cx);
205 120
121+ if let Err(error) = validate_message_body(&body) {
122+ window.push_notification(Notification::error(error.to_string()), cx);
206 return;123 return;
207 }124 }
208 125
126+ let Some(user_id) = this.user.as_ref().map(|user| user.id.clone()) else {
127+ return;
128+ };
129+ let Some(community_id) = this.chat.selected_community_id.clone() else {
130+ window.push_notification(Notification::error("No Community Selected"), cx);
131+ return;
132+ };
209 let network = this.network.clone();133 let network = this.network.clone();
210 134
211- input.update(cx, |input_state, cx| {135+ cx.spawn_in(window, async move |this, cx| {
212- input_state.set_value("", window, cx);136+ if let Err(error) = network.create_message(&user_id, &community_id, &body).await {
213- });137+ notify_error(&this, cx, error);
214- this.chat.creating_community = false;138+ }
139+ })
140+ .detach();
141+
142+ input.update(cx, |state, cx| state.set_value("", window, cx));
143+}
144+
145+fn create_community(
146+ this: &mut Yumush,
147+ input: &Entity<InputState>,
148+ window: &mut Window,
149+ cx: &mut Context<Yumush>,
150+) {
151+ let name = input.read(cx).text().to_string();
152+
153+ if let Err(error) = validate_community_name(&name) {
154+ window.push_notification(Notification::error(error.to_string()), cx);
155+ return;
156+ }
157+
158+ let network = this.network.clone();
159+ input.update(cx, |state, cx| state.set_value("", window, cx));
160+ this.chat.set_panel(Panel::None);
215 161
216 cx.spawn_in(window, async move |this, cx| {162 cx.spawn_in(window, async move |this, cx| {
217- let community = match network.create_community(&community_name).await {163+ let community = match network.create_community(&name).await {
218 Ok(community) => community,164 Ok(community) => community,
219- Err(error_value) => {165+ Err(error) => {
220- let _ = this.update_in(cx, |_, window, cx| {166+ notify_error(&this, cx, error);
221- window.push_notification(Notification::error(error_value.to_string()), cx);
222- });
223-
224 return;167 return;
225 }168 }
226 };169 };
227 170
228 let _ = this.update_in(cx, |yumush, window, cx| {171 let _ = this.update_in(cx, |yumush, window, cx| {
229- yumush
230- .chat
231- .set_selected_community_id(Some(community.get_community_id().to_string()));
232- yumush.chat.update_user_list(vec![]);
233 yumush.get_communities(window, cx);172 yumush.get_communities(window, cx);
234- yumush.get_chat_users(window, cx);173+ yumush.select_community(community.id, window, cx);
235- yumush.get_chat_messages(window, cx);
236- cx.notify();
237 });174 });
238 })175 })
239 .detach();176 .detach();
240 }177 }
241 178
242-fn search_community_action(179+fn search_community(
243 this: &mut Yumush,180 this: &mut Yumush,
244 input: &Entity<InputState>,181 input: &Entity<InputState>,
245 window: &mut Window,182 window: &mut Window,
246- cx: &mut Context<'_, Yumush>,183+ cx: &mut Context<Yumush>,
247 ) {184 ) {
248- let community_name = input.read(cx).text().to_string();185+ let name = input.read(cx).text().to_string();
249-
250- if let Err(error_value) = validate_community_name(&community_name) {
251- window.push_notification(Notification::error(error_value.to_string()), cx);
252 186
187+ if let Err(error) = validate_community_name(&name) {
188+ window.push_notification(Notification::error(error.to_string()), cx);
253 return;189 return;
254 }190 }
255 191
256 let network = this.network.clone();192 let network = this.network.clone();
257 193
258 cx.spawn_in(window, async move |this, cx| {194 cx.spawn_in(window, async move |this, cx| {
259- let communities = match network.search_community(&community_name).await {195+ let communities = match network.search_community(&name).await {
260 Ok(communities) => communities,196 Ok(communities) => communities,
261- Err(error_value) => {197+ Err(error) => {
262- let _ = this.update_in(cx, |_, window, cx| {198+ notify_error(&this, cx, error);
263- window.push_notification(Notification::error(error_value.to_string()), cx);
264- });
265-
266 return;199 return;
267 }200 }
268 };201 };
269 202
270 let _ = this.update(cx, |yumush, cx| {203 let _ = this.update(cx, |yumush, cx| {
271- yumush.chat.update_searched_community_list(communities);204+ yumush.chat.search_results = communities;
272 cx.notify();205 cx.notify();
273 });206 });
274 })207 })
@@ -276,182 +209,21 @@ fn search_community_action(
276 }209 }
277 210
278 impl Yumush {211 impl Yumush {
279- pub fn chat_page(&self, cx: &mut Context<Self>) -> impl IntoElement {212+ pub(super) fn chat_page(&self, cx: &mut Context<Self>) -> impl IntoElement {
280 let entity = cx.entity();213 let entity = cx.entity();
214+
281 div()215 div()
282 .flex()216 .flex()
283 .flex_row()217 .flex_row()
284 .size_full()218 .size_full()
285- .child(219+ .child(self.community_list(&entity))
286- div()
287- .id("community_list")
288- .h_full()
289- .flex()
290- .flex_col()
291- .flex_shrink_0()
292- .w_1_5()
293- .border_r_1()
294- .border_color(rgb(0x2f3136))
295- .bg(rgb(0x2b2d31))
296- .p_2()
297- .gap_1()
298- .child(
299- div()
300- .flex()
301- .flex_row()
302- .items_center()
303- .justify_between()
304- .child(
305- div()
306- .text_color(rgb(0x949ba4))
307- .font_weight(FontWeight::SEMIBOLD)
308- .child("Communities"),
309- )
310- .child({
311- let entity = entity.clone();
312-
313- Button::new("create_community_button").label("+").on_click(
314- move |_, window, cx| {
315- entity.update(cx, |yumush, cx| {
316- yumush.chat.creating_community =
317- !yumush.chat.creating_community;
318-
319- if yumush.chat.creating_community {
320- yumush.chat.community_name_input.update(
321- cx,
322- |input_state, cx| {
323- input_state.focus(window, cx);
324- },
325- );
326- }
327-
328- cx.notify();
329- });
330- },
331- )
332- })
333- .child({
334- let entity = entity.clone();
335-
336- Button::new("join_community_button").label("Join").on_click(
337- move |_, window, cx| {
338- entity.update(cx, |yumush, cx| {
339- yumush.chat.joining_community =
340- !yumush.chat.joining_community;
341-
342- if yumush.chat.joining_community {
343- yumush.chat.community_search_input.update(
344- cx,
345- |input_state, cx| {
346- input_state.focus(window, cx);
347- },
348- );
349- } else {
350- yumush.chat.update_searched_community_list(vec![]);
351- }
352-
353- cx.notify();
354- });
355- },
356- )
357- }),
358- )
359- .children(
360- self.chat
361- .creating_community
362- .then(|| Input::new(&self.chat.community_name_input)),
363- )
364- .children(
365- self.chat
366- .joining_community
367- .then(|| Input::new(&self.chat.community_search_input)),
368- )
369- .children(
370- self.chat
371- .community_search_results
372- .iter()
373- .filter(|result| {
374- !self.chat.communities.iter().any(|community| {
375- community.get_community_id() == result.get_community_id()
376- })
377- })
378- .enumerate()
379- .map(|(index, result)| {
380- let community_id = result.get_community_id().to_string();
381- let entity = entity.clone();
382-
383- div()
384- .id(("community_search_result", index))
385- .p_1()
386- .cursor_pointer()
387- .bg(rgb(0x1e1f22))
388- .text_color(rgb(0x949ba4))
389- .child(result.get_community_name().to_string())
390- .on_click(move |_, window, cx| {
391- entity.update(cx, |yumush, cx| {
392- yumush.join_community(&community_id, window, cx);
393- })
394- })
395- }),
396- )
397- .children(self.chat.communities.iter().enumerate().map(
398- |(index, community)| {
399- let community_id = community.get_community_id().to_string();
400- let selected = self.chat.get_selected_community_id().as_deref()
401- == Some(&community_id);
402- let entity = entity.clone();
403-
404- div()
405- .id(("community", index))
406- .p_1()
407- .cursor_pointer()
408- .bg(if selected {
409- rgb(0x404249)
410- } else {
411- rgb(0x2b2d31)
412- })
413- .child(community.get_community_name().to_string())
414- .on_click(move |_, window, cx| {
415- entity.update(cx, |yumush, cx| {
416- yumush.chat.set_selected_community_id(Some(
417- community_id.to_owned(),
418- ));
419- yumush.chat.update_user_list(vec![]);
420- yumush.get_chat_users(window, cx);
421- yumush.get_chat_messages(window, cx);
422- cx.notify();
423- })
424- })
425- },
426- )),
427- )
428 .child(220 .child(
429 div()221 div()
430 .flex()222 .flex()
431 .flex_col()223 .flex_col()
432 .flex_1()224 .flex_1()
433 .min_w_0()225 .min_w_0()
434- .child(226+ .child(self.message_list())
435- div()
436- .id("chat_messages")
437- .flex()
438- .flex_col()
439- .flex_1()
440- .min_w_0()
441- .overflow_y_scroll()
442- .p_2()
443- .gap_1()
444- .children(
445- self.chat
446- .chat_messages
447- .iter()
448- .filter(|message| {
449- Some(message.get_community_id())
450- == self.chat.get_selected_community_id().as_deref()
451- })
452- .map(|message| render_message(message, &self.chat.users)),
453- ),
454- )
455 .child(227 .child(
456 div()228 div()
457 .p_2()229 .p_2()
@@ -460,49 +232,207 @@ impl Yumush {
460 .child(Input::new(&self.chat.message_input)),232 .child(Input::new(&self.chat.message_input)),
461 ),233 ),
462 )234 )
235+ .child(self.user_list())
236+ }
237+
238+ fn community_list(&self, entity: &Entity<Self>) -> impl IntoElement {
239+ div()
240+ .id("community_list")
241+ .h_full()
242+ .flex()
243+ .flex_col()
244+ .flex_shrink_0()
245+ .w_1_5()
246+ .border_r_1()
247+ .border_color(rgb(0x2f3136))
248+ .bg(rgb(0x2b2d31))
249+ .p_2()
250+ .gap_1()
463 .child(251 .child(
464 div()252 div()
465- .id("user_list")
466- .h_full()
467 .flex()253 .flex()
468- .flex_col()254+ .flex_row()
469- .flex_shrink_0()255+ .items_center()
470- .w_1_5()256+ .justify_between()
471- .border_l_1()
472- .border_color(rgb(0x2f3136))
473- .bg(rgb(0x2b2d31))
474- .p_2()
475- .gap_1()
476 .child(257 .child(
477 div()258 div()
478 .text_color(rgb(0x949ba4))259 .text_color(rgb(0x949ba4))
479 .font_weight(FontWeight::SEMIBOLD)260 .font_weight(FontWeight::SEMIBOLD)
480- .child(format!("Online - {}", self.chat.users.len())),261+ .child("Communities"),
481 )262 )
482- .children(263+ .child(panel_button(
483- self.chat264+ entity,
484- .users265+ "create_community_button",
266+ "+",
267+ Panel::Create,
268+ ))
269+ .child(panel_button(
270+ entity,
271+ "join_community_button",
272+ "Join",
273+ Panel::Join,
274+ )),
275+ )
276+ .children(
277+ (self.chat.panel == Panel::Create)
278+ .then(|| Input::new(&self.chat.community_name_input)),
279+ )
280+ .children(
281+ (self.chat.panel == Panel::Join)
282+ .then(|| Input::new(&self.chat.community_search_input)),
283+ )
284+ .children(
285+ self.chat
286+ .search_results
287+ .iter()
288+ .filter(|result| {
289+ !self
290+ .chat
291+ .communities
485 .iter()292 .iter()
486- .map(|user| div().p_1().child(user.get_username().to_string())),293+ .any(|community| community.id == result.id)
487- ),294+ })
295+ .enumerate()
296+ .map(|(index, result)| {
297+ let community_id = result.id.clone();
298+ let entity = entity.clone();
299+
300+ div()
301+ .id(("community_search_result", index))
302+ .p_1()
303+ .cursor_pointer()
304+ .bg(rgb(0x1e1f22))
305+ .text_color(rgb(0x949ba4))
306+ .child(result.name.clone())
307+ .on_click(move |_, window, cx| {
308+ entity.update(cx, |yumush, cx| {
309+ yumush.join_community(&community_id, window, cx)
310+ })
311+ })
312+ }),
313+ )
314+ .children(
315+ self.chat
316+ .communities
317+ .iter()
318+ .enumerate()
319+ .map(|(index, community)| {
320+ let community_id = community.id.clone();
321+ let selected = self.chat.selected_community_id.as_deref()
322+ == Some(community.id.as_str());
323+ let entity = entity.clone();
324+
325+ div()
326+ .id(("community", index))
327+ .p_1()
328+ .cursor_pointer()
329+ .bg(if selected {
330+ rgb(0x404249)
331+ } else {
332+ rgb(0x2b2d31)
333+ })
334+ .child(community.name.clone())
335+ .on_click(move |_, window, cx| {
336+ entity.update(cx, |yumush, cx| {
337+ yumush.select_community(community_id.clone(), window, cx)
338+ })
339+ })
340+ }),
488 )341 )
489 }342 }
490 343
491- pub fn get_chat_users(&self, window: &mut Window, cx: &mut Context<Self>) {344+ fn message_list(&self) -> impl IntoElement {
492- let network = self.network.clone();345+ div()
346+ .id("chat_messages")
347+ .flex()
348+ .flex_col()
349+ .flex_1()
350+ .min_w_0()
351+ .overflow_y_scroll()
352+ .p_2()
353+ .gap_1()
354+ .children(
355+ self.chat
356+ .messages
357+ .iter()
358+ .filter(|message| {
359+ Some(&message.community_id) == self.chat.selected_community_id.as_ref()
360+ })
361+ .map(|message| render_message(message, &self.chat.users)),
362+ )
363+ }
493 364
494- let Some(community_id) = self.chat.get_selected_community_id().to_owned() else {365+ fn user_list(&self) -> impl IntoElement {
366+ div()
367+ .id("user_list")
368+ .h_full()
369+ .flex()
370+ .flex_col()
371+ .flex_shrink_0()
372+ .w_1_5()
373+ .border_l_1()
374+ .border_color(rgb(0x2f3136))
375+ .bg(rgb(0x2b2d31))
376+ .p_2()
377+ .gap_1()
378+ .child(
379+ div()
380+ .text_color(rgb(0x949ba4))
381+ .font_weight(FontWeight::SEMIBOLD)
382+ .child(format!("Online - {}", self.chat.users.len())),
383+ )
384+ .children(
385+ self.chat
386+ .users
387+ .iter()
388+ .map(|user| div().p_1().child(user.username.clone())),
389+ )
390+ }
391+
392+ fn toggle_panel(&mut self, panel: Panel, window: &mut Window, cx: &mut Context<Self>) {
393+ let panel = if self.chat.panel == panel {
394+ Panel::None
395+ } else {
396+ panel
397+ };
398+ self.chat.set_panel(panel);
399+
400+ let input = match panel {
401+ Panel::None => None,
402+ Panel::Create => Some(&self.chat.community_name_input),
403+ Panel::Join => Some(&self.chat.community_search_input),
404+ };
405+ if let Some(input) = input {
406+ input.update(cx, |state, cx| state.focus(window, cx));
407+ }
408+
409+ cx.notify();
410+ }
411+
412+ fn select_community(
413+ &mut self,
414+ community_id: String,
415+ window: &mut Window,
416+ cx: &mut Context<Self>,
417+ ) {
418+ self.chat.selected_community_id = Some(community_id);
419+ self.chat.users.clear();
420+ self.get_chat_users(window, cx);
421+ self.get_chat_messages(window, cx);
422+ cx.notify();
423+ }
424+
425+ pub(super) fn get_chat_users(&self, window: &mut Window, cx: &mut Context<Self>) {
426+ let Some(community_id) = self.chat.selected_community_id.clone() else {
495 return;427 return;
496 };428 };
429+ let network = self.network.clone();
497 430
498 cx.spawn_in(window, async move |this, cx| {431 cx.spawn_in(window, async move |this, cx| {
499 let user_ids = match network.users_in(&community_id).await {432 let user_ids = match network.users_in(&community_id).await {
500 Ok(user_ids) => user_ids,433 Ok(user_ids) => user_ids,
501- Err(error_value) => {434+ Err(error) => {
502- let _ = this.update_in(cx, |_, window, cx| {435+ notify_error(&this, cx, error);
503- window.push_notification(Notification::error(error_value.to_string()), cx);
504- });
505-
506 return;436 return;
507 }437 }
508 };438 };
@@ -515,34 +445,27 @@ impl Yumush {
515 }445 }
516 446
517 let _ = this.update(cx, |yumush, cx| {447 let _ = this.update(cx, |yumush, cx| {
518- yumush.chat.update_user_list(users);448+ yumush.chat.users = users;
519 cx.notify();449 cx.notify();
520 });450 });
521 })451 })
522 .detach();452 .detach();
523 }453 }
524 454
525- pub fn get_chat_messages(&self, window: &mut Window, cx: &mut Context<Self>) {455+ pub(super) fn get_chat_messages(&self, window: &mut Window, cx: &mut Context<Self>) {
526- let network = self.network.clone();456+ let Some(community_id) = self.chat.selected_community_id.clone() else {
527-
528- let Some(community_id) = self.chat.get_selected_community_id() else {
529 return;457 return;
530 };458 };
459+ let network = self.network.clone();
531 460
532 cx.spawn_in(window, async move |this, cx| {461 cx.spawn_in(window, async move |this, cx| {
533 let messages = match network462 let messages = match network
534- .read_message_by_community_id_with_marker_and_limit(463+ .read_messages(&community_id, NEWEST_MESSAGE_MARKER)
535- community_id.as_str(),
536- NEWEST_MESSAGE_MARKER,
537- )
538 .await464 .await
539 {465 {
540 Ok(messages) => messages,466 Ok(messages) => messages,
541- Err(error_value) => {467+ Err(error) => {
542- let _ = this.update_in(cx, |_, window, cx| {468+ notify_error(&this, cx, error);
543- window.push_notification(Notification::error(error_value.to_string()), cx);
544- });
545-
546 return;469 return;
547 }470 }
548 };471 };
@@ -555,21 +478,17 @@ impl Yumush {
555 .detach();478 .detach();
556 }479 }
557 480
558- pub fn get_communities(&self, window: &mut Window, cx: &mut Context<Self>) {481+ pub(super) fn get_communities(&self, window: &mut Window, cx: &mut Context<Self>) {
559- let Some(user) = self.get_user() else {482+ let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else {
560 return;483 return;
561 };484 };
562-
563 let network = self.network.clone();485 let network = self.network.clone();
564 486
565 cx.spawn_in(window, async move |this, cx| {487 cx.spawn_in(window, async move |this, cx| {
566- let community_ids = match network.community_of(user.get_user_id()).await {488+ let community_ids = match network.communities_of(&user_id).await {
567 Ok(community_ids) => community_ids,489 Ok(community_ids) => community_ids,
568- Err(error_value) => {490+ Err(error) => {
569- let _ = this.update_in(cx, |_, window, cx| {491+ notify_error(&this, cx, error);
570- window.push_notification(Notification::error(error_value.to_string()), cx);
571- });
572-
573 return;492 return;
574 }493 }
575 };494 };
@@ -582,55 +501,60 @@ impl Yumush {
582 }501 }
583 502
584 let _ = this.update(cx, |yumush, cx| {503 let _ = this.update(cx, |yumush, cx| {
585- yumush.chat.update_community_list(communities);504+ if yumush.chat.selected_community_id.is_none() {
505+ yumush.chat.selected_community_id =
506+ communities.first().map(|community| community.id.clone());
507+ }
508+ yumush.chat.communities = communities;
586 cx.notify();509 cx.notify();
587 });510 });
588 })511 })
589 .detach();512 .detach();
590 }513 }
591 514
592- pub fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context<Self>) {515+ fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context<Self>) {
593- let Some(user) = self.get_user() else {516+ let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else {
594 return;517 return;
595 };518 };
596-
597 let network = self.network.clone();519 let network = self.network.clone();
598 let community_id = community_id.to_string();520 let community_id = community_id.to_string();
599 521
600 cx.spawn_in(window, async move |this, cx| {522 cx.spawn_in(window, async move |this, cx| {
601- if let Err(error_value) = network523+ if let Err(error) = network.join_community(&user_id, &community_id).await {
602- .join_community(user.get_user_id(), &community_id)524+ notify_error(&this, cx, error);
603- .await
604- {
605- let _ = this.update_in(cx, |_, window, cx| {
606- window.push_notification(Notification::error(error_value.to_string()), cx);
607- });
608-
609 return;525 return;
610 }526 }
611 527
612 let _ = this.update_in(cx, |yumush, window, cx| {528 let _ = this.update_in(cx, |yumush, window, cx| {
613- yumush.chat.set_joining_community(false);529+ yumush.chat.set_panel(Panel::None);
614- yumush.chat.update_searched_community_list(vec![]);
615- yumush.chat.set_selected_community_id(Some(community_id));
616- yumush.chat.update_user_list(vec![]);
617 yumush.get_communities(window, cx);530 yumush.get_communities(window, cx);
618- yumush.get_chat_users(window, cx);531+ yumush.select_community(community_id, window, cx);
619- yumush.get_chat_messages(window, cx);
620-
621- cx.notify();
622 });532 });
623 })533 })
624 .detach();534 .detach();
625 }535 }
626 }536 }
627 537
538+fn panel_button(
539+ entity: &Entity<Yumush>,
540+ id: &'static str,
541+ label: &'static str,
542+ panel: Panel,
543+) -> impl IntoElement {
544+ let entity = entity.clone();
545+
546+ Button::new(id).label(label).on_click(move |_, window, cx| {
547+ entity.update(cx, |yumush, cx| yumush.toggle_panel(panel, window, cx));
548+ })
549+}
550+
628 fn render_message(message: &Message, users: &[User]) -> impl IntoElement {551 fn render_message(message: &Message, users: &[User]) -> impl IntoElement {
629 let username = users552 let username = users
630 .iter()553 .iter()
631- .find(|user| user.get_user_id() == message.get_user_id())554+ .find(|user| user.id == message.user_id)
632- .map(User::get_username)555+ .map(|user| user.username.as_str())
633- .unwrap_or(message.get_user_id());556+ .unwrap_or(message.user_id.as_str());
557+
634 div()558 div()
635 .flex()559 .flex()
636 .flex_col()560 .flex_col()
@@ -641,5 +565,5 @@ fn render_message(message: &Message, users: &[User]) -> impl IntoElement {
641 .font_weight(FontWeight::BOLD)565 .font_weight(FontWeight::BOLD)
642 .child(username.to_string()),566 .child(username.to_string()),
643 )567 )
644- .child(div().pl_2().child(message.get_message_body().to_string()))568+ .child(div().pl_2().child(message.body.clone()))
645 }569 }
crates/client/src/gui/login.rsdeleted+0 -100
@@ -1,100 +0,0 @@
1-use gpui_kit::{
2- AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window,
3- component::{
4- WindowExt,
5- button::Button,
6- input::{Input, InputEvent, InputState},
7- notification::Notification,
8- },
9- div,
10-};
11-
12-use crate::gui::{Route, Yumush};
13-
14-pub struct Login {
15- username_input: Entity<InputState>,
16-}
17-
18-impl Login {
19- pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {
20- let username_input = cx.new(|cx| {
21- let mut input_state = InputState::new(window, cx);
22- input_state.set_placeholder("Username...", window, cx);
23- input_state.focus(window, cx);
24-
25- input_state
26- });
27-
28- cx.subscribe_in(&username_input, window, |this, input, event, window, cx| {
29- if matches!(event, InputEvent::PressEnter { .. }) {
30- login_action(this, input, window, cx);
31- }
32- })
33- .detach();
34-
35- Self { username_input }
36- }
37-
38- pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) {
39- self.username_input.update(cx, |input, cx| {
40- input.focus(window, cx);
41- });
42- }
43-}
44-
45-fn login_action(
46- this: &mut Yumush,
47- input: &Entity<InputState>,
48- window: &mut Window,
49- cx: &mut Context<'_, Yumush>,
50-) {
51- let username = input.read(cx).text().to_string();
52- let network = this.network.clone();
53-
54- cx.spawn_in(window, async move |this, cx| {
55- let result = network.authenticate(&username).await;
56-
57- let _ = this.update_in(cx, |yumush, window, cx| match result {
58- Ok(user) => {
59- yumush.set_user(user);
60- yumush.change_page(Route::Chat, window, cx);
61- yumush.time_based_repetitive_checks_after_login(window, cx);
62- }
63- Err(error_value) => {
64- window.push_notification(Notification::error(error_value.to_string()), cx);
65- }
66- });
67- })
68- .detach();
69-}
70-
71-impl Yumush {
72- pub fn login_page(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
73- let entity = cx.entity();
74- let username_input = self.login.username_input.clone();
75- let login_button = Button::new("login_button")
76- .on_click(move |_, window, cx| {
77- entity.update(cx, |this, cx| {
78- login_action(this, &username_input, window, cx);
79- })
80- })
81- .label("Login");
82-
83- let entity = cx.entity();
84- let register_page_switch_button = Button::new("register_page_switch_button")
85- .on_click(move |_, window, cx| {
86- entity.update(cx, |this, cx| {
87- this.change_page(Route::Register, window, cx);
88- })
89- })
90- .label("Go to Register Page");
91-
92- div()
93- .w_1_5()
94- .child("Username")
95- .child(Input::new(&self.login.username_input))
96- .child(login_button)
97- .child(register_page_switch_button)
98- .into_element()
99- }
100-}
crates/client/src/gui/register.rsdeleted+0 -99
@@ -1,99 +0,0 @@
1-use gpui_kit::{
2- AppContext, Context, Entity, IntoElement, ParentElement, Styled, Window,
3- component::{
4- WindowExt,
5- button::Button,
6- input::{Input, InputEvent, InputState},
7- notification::Notification,
8- },
9- div,
10-};
11-
12-use crate::gui::{Route, Yumush};
13-
14-pub struct Register {
15- username_input: Entity<InputState>,
16-}
17-
18-impl Register {
19- pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {
20- let username_input = cx.new(|cx| {
21- let mut input_state = InputState::new(window, cx);
22- input_state.set_placeholder("Username...", window, cx);
23- input_state.focus(window, cx);
24-
25- input_state
26- });
27-
28- cx.subscribe_in(&username_input, window, |this, input, event, window, cx| {
29- if matches!(event, InputEvent::PressEnter { .. }) {
30- register_action(this, input, window, cx);
31- }
32- })
33- .detach();
34-
35- Self { username_input }
36- }
37-
38- pub fn focus(&self, window: &mut Window, cx: &mut Context<'_, Yumush>) {
39- self.username_input.update(cx, |input, cx| {
40- input.focus(window, cx);
41- });
42- }
43-}
44-
45-fn register_action(
46- this: &mut Yumush,
47- input: &Entity<InputState>,
48- window: &mut Window,
49- cx: &mut Context<'_, Yumush>,
50-) {
51- let username = input.read(cx).text().to_string();
52- let network = this.network.clone();
53-
54- cx.spawn_in(window, async move |this, cx| {
55- let result = network.create_user(&username).await;
56-
57- let _ = this.update_in(cx, |yumush, window, cx| match result {
58- Ok(user) => {
59- yumush.set_user(user);
60- yumush.change_page(Route::Chat, window, cx);
61- }
62- Err(error_value) => {
63- window.push_notification(Notification::error(error_value.to_string()), cx);
64- }
65- });
66- })
67- .detach();
68-}
69-
70-impl Yumush {
71- pub fn register_page(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
72- let entity = cx.entity();
73- let username_input = self.register.username_input.clone();
74- let register_button = Button::new("register_button")
75- .on_click(move |_, window, cx| {
76- entity.update(cx, |this, cx| {
77- register_action(this, &username_input, window, cx);
78- })
79- })
80- .label("Register");
81-
82- let entity = cx.entity();
83- let login_page_switch_button = Button::new("login_page_switch_button")
84- .on_click(move |_, window, cx| {
85- entity.update(cx, |this, cx| {
86- this.change_page(Route::Login, window, cx);
87- })
88- })
89- .label("Go to Login Page");
90-
91- div()
92- .w_1_5()
93- .child("Username")
94- .child(Input::new(&self.register.username_input))
95- .child(register_button)
96- .child(login_page_switch_button)
97- .into_element()
98- }
99-}
crates/client/src/lib.rsmodified+4 -9
@@ -1,9 +1,7 @@
1-use common::utils::TOML;1+use common::config::parse;
2 2
3-pub mod event;
4 pub mod gui;3 pub mod gui;
5 pub mod network;4 pub mod network;
6-mod request;
7 5
8 pub const NAME: &str = "Yumush";6 pub const NAME: &str = "Yumush";
9 7
@@ -19,14 +17,11 @@ pub struct ClientConfig {
19 17
20 impl Default for ClientConfig {18 impl Default for ClientConfig {
21 fn default() -> Self {19 fn default() -> Self {
22- let toml = TOML::naive_toml_parser_from_content(CLIENT_CONFIG_FILE_CONTENT).unwrap();20+ let fields = parse(CLIENT_CONFIG_FILE_CONTENT).expect("client config");
23-
24- let server_address = toml.fields.get("server_address").unwrap().to_owned();
25- let server_name = toml.fields.get("server_name").unwrap().to_owned();
26 21
27 Self {22 Self {
28- server_address,23+ server_address: fields["server_address"].clone(),
29- server_name,24+ server_name: fields["server_name"].clone(),
30 }25 }
31 }26 }
32 }27 }
crates/client/src/main.rsmodified+3 -5
@@ -1,12 +1,10 @@
1-use client::{gui::Yumush, network, ClientConfig, NAME};1+use client::{ClientConfig, NAME, gui::Yumush, network};
2 use gpui_kit::{2 use gpui_kit::{
3- application, component::Root, init, px, size, App, AppContext, Bounds, TitlebarOptions,3+ App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application,
4- WindowBounds, WindowOptions,4+ component::Root, init, px, size,
5 };5 };
6 6
7 fn main() {7 fn main() {
8- println!("Hello, world!");
9-
10 let (network_handle, network_event_receiver) = network::start(ClientConfig::default());8 let (network_handle, network_event_receiver) = network::start(ClientConfig::default());
11 9
12 application().run(|cx: &mut App| {10 application().run(|cx: &mut App| {
crates/client/src/network.rsmodified+280 -132
@@ -1,9 +1,15 @@
1 use std::sync::Arc;1 use std::sync::Arc;
2 use std::time::Duration;2 use std::time::Duration;
3 3
4-use common::error::Error;4+use common::{
5-use common::network::Network;5+ constant::MESSAGE_PAGE_LIMIT,
6-use common::{community::Community, error::network, message::Message, user::User};6+ error::Error,
7+ model::{Community, Message, User},
8+ network::{receive_message, send_request},
9+ request::Request,
10+ response::Response,
11+ validate::{validate_community_name, validate_message_body, validate_username},
12+};
7 use quinn::{13 use quinn::{
8 Endpoint,14 Endpoint,
9 crypto::rustls::QuicClientConfig,15 crypto::rustls::QuicClientConfig,
@@ -14,7 +20,7 @@ use quinn::{
14 };20 };
15 use tokio::sync::{mpsc, oneshot};21 use tokio::sync::{mpsc, oneshot};
16 22
17-use crate::{ClientConfig, request::ClientRequest};23+use crate::ClientConfig;
18 24
19 const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1);25 const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1);
20 const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);26 const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);
@@ -22,112 +28,204 @@ const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);
22 const CHANNEL_SIZE: usize = 32;28 const CHANNEL_SIZE: usize = 32;
23 const RECONNECT_DELAY: Duration = Duration::from_secs(1);29 const RECONNECT_DELAY: Duration = Duration::from_secs(1);
24 30
25-pub async fn connect(server_address: &str, server_name: &str) -> Result<ClientRequest, Error> {31+#[derive(Debug)]
26- let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?;32+pub enum NetworkEvent {
27- endpoint.set_default_client_config(config());33+ Connected(Option<User>),
34+ ConnectionFailed(Error),
35+ Disconnected(Error),
36+ MessageReceived(Message),
37+}
28 38
29- let connection = endpoint39+#[derive(Debug)]
30- .connect(server_address.parse().unwrap(), server_name)?40+struct Command {
31- .await?;41+ request: Request,
42+ reply: oneshot::Sender<Result<Response, Error>>,
43+}
32 44
33- Ok(ClientRequest::new(connection))45+#[derive(Debug, Clone)]
46+pub struct NetworkHandle {
47+ command_sender: mpsc::Sender<Command>,
34 }48 }
35 49
36-fn config() -> quinn::ClientConfig {50+impl NetworkHandle {
37- let crypto_provider = Arc::new(rustls::crypto::ring::default_provider());51+ pub async fn request(&self, request: Request) -> Result<Response, Error> {
38- let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone())52+ let (reply, response) = oneshot::channel();
39- .with_protocol_versions(&[&rustls::version::TLS13])
40- .unwrap()
41- .dangerous()
42- .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider)))
43- .with_no_client_auth();
44 53
45- let mut client_config =54+ self.command_sender
46- quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap()));55+ .send(Command { request, reply })
56+ .await
57+ .map_err(|_| Error::ChannelClosed)?;
47 58
48- let mut transport_config = quinn::TransportConfig::default();59+ match response.await.map_err(|_| Error::ChannelClosed)?? {
49- transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL));60+ Response::Error(error) => Err(error),
50- transport_config.max_idle_timeout(Some(MAX_IDLE_TIMEOUT.try_into().unwrap()));61+ response => Ok(response),
62+ }
63+ }
51 64
52- client_config.transport_config(Arc::new(transport_config));65+ pub async fn authenticate(&self, token: &str) -> Result<User, Error> {
66+ match self
67+ .request(Request::Authentication {
68+ token: token.to_string(),
69+ })
70+ .await?
71+ {
72+ Response::Authentication(user) => Ok(user),
73+ _ => Err(Error::Server),
74+ }
75+ }
53 76
54- client_config77+ pub async fn deauthenticate(&self, token: &str) -> Result<User, Error> {
55-}78+ match self
79+ .request(Request::Deauthentication {
80+ token: token.to_string(),
81+ })
82+ .await?
83+ {
84+ Response::Deauthentication(user) => Ok(user),
85+ _ => Err(Error::Server),
86+ }
87+ }
88+
89+ pub async fn create_user(&self, username: &str) -> Result<User, Error> {
90+ validate_username(username)?;
56 91
57-macro_rules! network_commands {92+ match self
58- ($($variant:ident => $method:ident($($arg:ident), *) -> $ret:ty),* $(,)?) => {93+ .request(Request::CreateUser {
59- #[derive(Debug)]94+ username: username.to_string(),
60- pub enum NetworkCommand {95+ })
61- $($variant{96+ .await?
62- $($arg: String, )*97+ {
63- reply: oneshot::Sender<Result<$ret, Error>>,98+ Response::CreateUser(user) => Ok(user),
64- },)*99+ _ => Err(Error::Server),
65 }100 }
101+ }
66 102
67- impl NetworkHandle {103+ pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {
68- $(pub async fn $method(&self, $($arg: &str),*) -> Result<$ret, Error> {104+ match self
69- let (reply, response) = oneshot::channel();105+ .request(Request::ReadUser {
70- let command = NetworkCommand::$variant {106+ user_id: user_id.to_string(),
71- $($arg: $arg.to_string(),)*107+ })
72- reply,108+ .await?
73- };109+ {
110+ Response::ReadUser(user) => Ok(user),
111+ _ => Err(Error::Server),
112+ }
113+ }
74 114
75- self.command_sender.send(command).await.map_err(|_| network::Error::ChannelClosed)?;115+ pub async fn create_community(&self, name: &str) -> Result<Community, Error> {
116+ validate_community_name(name)?;
76 117
77- response.await.map_err(|_| network::Error::ChannelClosed)?118+ match self
78- })*119+ .request(Request::CreateCommunity {
120+ name: name.to_string(),
121+ })
122+ .await?
123+ {
124+ Response::CreateCommunity(community) => Ok(community),
125+ _ => Err(Error::Server),
79 }126 }
127+ }
80 128
81- async fn dispatch(client_request: ClientRequest, command: NetworkCommand) {129+ pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> {
82- match command {130+ match self
83- $(NetworkCommand::$variant { $($arg,)* reply} => {131+ .request(Request::ReadCommunity {
84- let _ = reply.send(client_request.$method($(&$arg),*).await);132+ community_id: community_id.to_string(),
85- })*133+ })
86- }134+ .await?
135+ {
136+ Response::ReadCommunity(community) => Ok(community),
137+ _ => Err(Error::Server),
87 }138 }
88- };139+ }
89-}
90 140
91-network_commands! {141+ pub async fn create_message(
92- Authenticate => authenticate(authentication_token) -> User,142+ &self,
93- Deauthenticate => deauthenticate(authentication_token) -> User,143+ user_id: &str,
94- CreateUser => create_user(username) -> User,144+ community_id: &str,
95- ReadUser => read_user(user_id) -> User,145+ body: &str,
96- UpdateUser => update_user(user_id, username) -> User,146+ ) -> Result<Message, Error> {
97- DeleteUser => delete_user(user_id) -> User,147+ validate_message_body(body)?;
98- CreateCommunity => create_community(community_name) -> Community,148+
99- ReadCommunity => read_community(community_id) -> Community,149+ match self
100- UpdateCommunity => update_community(community_id, community_name) -> Community,150+ .request(Request::CreateMessage {
101- DeleteCommunity => delete_community(community_id) -> Community,151+ user_id: user_id.to_string(),
102- CreateMessage => create_message(user_id, community_id, message_body) -> Message,152+ community_id: community_id.to_string(),
103- ReadMessage => read_message(message_id) -> Message,153+ body: body.to_string(),
104- UpdateMessage => update_message(message_id, message_body) -> Message,154+ })
105- DeleteMessage => delete_message(message_id) -> Message,155+ .await?
106- ReadMessageByCommunityIDWithMarkerAndLimit => read_message_by_community_id_with_marker_and_limit(community_id, marker) -> Vec<Message>,156+ {
107- JoinCommunity => join_community(user_id, community_id) -> (),157+ Response::CreateMessage(message) => Ok(message),
108- LeaveCommunity => leave_community(user_id, community_id) -> (),158+ _ => Err(Error::Server),
109- IsUserIn => is_user_in(user_id, community_id) -> bool,159+ }
110- UsersIn => users_in(community_id) -> Vec<String>,160+ }
111- CommunityOf => community_of(user_id) -> Vec<String>,
112- SearchCommunity => search_community(community_name) -> Vec<Community>,
113-}
114 161
115-#[derive(Debug)]162+ pub async fn read_messages(
116-pub enum NetworkEvent {163+ &self,
117- Connected(Option<User>),164+ community_id: &str,
118- ConnectionFailed(Error),165+ marker: &str,
119- Disconnected(Error),166+ ) -> Result<Vec<Message>, Error> {
120- MessageReceived(Message),167+ match self
121-}168+ .request(Request::ReadMessages {
169+ community_id: community_id.to_string(),
170+ marker: marker.to_string(),
171+ limit: MESSAGE_PAGE_LIMIT,
172+ })
173+ .await?
174+ {
175+ Response::ReadMessages(messages) => Ok(messages),
176+ _ => Err(Error::Server),
177+ }
178+ }
122 179
123-#[derive(Debug, Clone)]180+ pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> {
124-pub struct NetworkHandle {181+ match self
125- command_sender: mpsc::Sender<NetworkCommand>,182+ .request(Request::JoinCommunity {
126-}183+ user_id: user_id.to_string(),
184+ community_id: community_id.to_string(),
185+ })
186+ .await?
187+ {
188+ Response::JoinCommunity => Ok(()),
189+ _ => Err(Error::Server),
190+ }
191+ }
127 192
128-impl NetworkHandle {193+ pub async fn users_in(&self, community_id: &str) -> Result<Vec<String>, Error> {
129- fn new(command_sender: mpsc::Sender<NetworkCommand>) -> Self {194+ match self
130- Self { command_sender }195+ .request(Request::UsersIn {
196+ community_id: community_id.to_string(),
197+ })
198+ .await?
199+ {
200+ Response::UsersIn(user_ids) => Ok(user_ids),
201+ _ => Err(Error::Server),
202+ }
203+ }
204+
205+ pub async fn communities_of(&self, user_id: &str) -> Result<Vec<String>, Error> {
206+ match self
207+ .request(Request::CommunitiesOf {
208+ user_id: user_id.to_string(),
209+ })
210+ .await?
211+ {
212+ Response::CommunitiesOf(community_ids) => Ok(community_ids),
213+ _ => Err(Error::Server),
214+ }
215+ }
216+
217+ pub async fn search_community(&self, name: &str) -> Result<Vec<Community>, Error> {
218+ validate_community_name(name)?;
219+
220+ match self
221+ .request(Request::SearchCommunity {
222+ name: name.to_string(),
223+ })
224+ .await?
225+ {
226+ Response::SearchCommunity(communities) => Ok(communities),
227+ _ => Err(Error::Server),
228+ }
131 }229 }
132 }230 }
133 231
@@ -146,24 +244,69 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw
146 })244 })
147 .expect("network thread");245 .expect("network thread");
148 246
149- (NetworkHandle::new(command_sender), event_receiver)247+ (NetworkHandle { command_sender }, event_receiver)
248+}
249+
250+async fn connect(server_address: &str, server_name: &str) -> Result<quinn::Connection, Error> {
251+ let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?;
252+ endpoint.set_default_client_config(config());
253+
254+ let connection = endpoint
255+ .connect(server_address.parse()?, server_name)?
256+ .await?;
257+
258+ Ok(connection)
259+}
260+
261+fn config() -> quinn::ClientConfig {
262+ let crypto_provider = Arc::new(rustls::crypto::ring::default_provider());
263+ let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone())
264+ .with_protocol_versions(&[&rustls::version::TLS13])
265+ .unwrap()
266+ .dangerous()
267+ .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider)))
268+ .with_no_client_auth();
269+
270+ let mut client_config =
271+ quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap()));
272+
273+ let mut transport_config = quinn::TransportConfig::default();
274+ transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL));
275+ transport_config.max_idle_timeout(Some(MAX_IDLE_TIMEOUT.try_into().unwrap()));
276+
277+ client_config.transport_config(Arc::new(transport_config));
278+
279+ client_config
280+}
281+
282+async fn send(connection: &quinn::Connection, request: &Request) -> Result<Response, Error> {
283+ let (send_stream, receive_stream) = connection.open_bi().await?;
284+ send_request(request, send_stream, receive_stream).await
285+}
286+
287+async fn dispatch(
288+ connection: quinn::Connection,
289+ request: Request,
290+ reply: oneshot::Sender<Result<Response, Error>>,
291+) {
292+ let _ = reply.send(send(&connection, &request).await);
150 }293 }
151 294
152 async fn actor(295 async fn actor(
153 client_config: ClientConfig,296 client_config: ClientConfig,
154- mut command_receiver: mpsc::Receiver<NetworkCommand>,297+ mut command_receiver: mpsc::Receiver<Command>,
155 event_sender: mpsc::Sender<NetworkEvent>,298 event_sender: mpsc::Sender<NetworkEvent>,
156 ) {299 ) {
157 let mut authentication_token: Option<String> = None;300 let mut authentication_token: Option<String> = None;
158 let mut authentication_epoch = 0;301 let mut authentication_epoch = 0;
159 let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE);302 let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE);
160 'session: loop {303 'session: loop {
161- let client_request = loop {304+ let connection = loop {
162 match connect(&client_config.server_address, &client_config.server_name).await {305 match connect(&client_config.server_address, &client_config.server_name).await {
163- Ok(client_request) => break client_request,306+ Ok(connection) => break connection,
164- Err(error_value) => {307+ Err(error) => {
165 if event_sender308 if event_sender
166- .send(NetworkEvent::ConnectionFailed(error_value))309+ .send(NetworkEvent::ConnectionFailed(error))
167 .await310 .await
168 .is_err()311 .is_err()
169 {312 {
@@ -176,10 +319,13 @@ async fn actor(
176 };319 };
177 320
178 let mut user = None;321 let mut user = None;
179- if let Some(authentication_token_) = &authentication_token {322+ if let Some(token) = &authentication_token {
180- match client_request.authenticate(authentication_token_).await {323+ let request = Request::Authentication {
181- Ok(user_) => user = Some(user_),324+ token: token.clone(),
182- Err(_) => authentication_token = None,325+ };
326+ match send(&connection, &request).await {
327+ Ok(Response::Authentication(user_)) => user = Some(user_),
328+ _ => authentication_token = None,
183 }329 }
184 }330 }
185 331
@@ -192,48 +338,50 @@ async fn actor(
192 }338 }
193 339
194 tokio::spawn(message_receive_loop(340 tokio::spawn(message_receive_loop(
195- client_request.clone(),341+ connection.clone(),
196 event_sender.clone(),342 event_sender.clone(),
197 ));343 ));
198 344
199 loop {345 loop {
200 tokio::select! {346 tokio::select! {
201 command = command_receiver.recv() => match command {347 command = command_receiver.recv() => match command {
202- Some(NetworkCommand::Authenticate {authentication_token: authentication_token_, reply}) => {348+ Some(Command { request, reply }) => match &request {
203- let client_request = client_request.clone();349+ Request::Authentication { token } => {
204- let token_sender = token_sender.clone();350+ let token = token.clone();
205- let epoch = authentication_epoch;351+ let token_sender = token_sender.clone();
206-352+ let epoch = authentication_epoch;
207- tokio::spawn(async move {353+ let connection = connection.clone();
208- let result = client_request.authenticate(&authentication_token_).await;354+
209- if result.is_ok() {355+ tokio::spawn(async move {
210- let _ = token_sender.send((epoch, authentication_token_)).await;356+ let response = send(&connection, &request).await;
211- }357+ if let Ok(Response::Authentication(_)) = &response {
212-358+ let _ = token_sender.send((epoch, token)).await;
213- let _ = reply.send(result);359+ }
214- });360+
215- }361+ let _ = reply.send(response);
216- Some(command) => {362+ });
217- match &command {
218- NetworkCommand::Deauthenticate { .. } => {
219- authentication_token = None;
220- authentication_epoch += 1;
221- }
222- _ => {}
223 }363 }
224- tokio::spawn(dispatch(client_request.clone(), command));364+ Request::Deauthentication { .. } => {
225- }365+ authentication_token = None;
366+ authentication_epoch += 1;
367+
368+ tokio::spawn(dispatch(connection.clone(), request, reply));
369+ }
370+ _ => {
371+ tokio::spawn(dispatch(connection.clone(), request, reply));
372+ }
373+ },
226 None => break 'session,374 None => break 'session,
227 },375 },
228- Some((epoch, authentication_token_)) = token_receiver.recv() => {376+ Some((epoch, token)) = token_receiver.recv() => {
229 if epoch == authentication_epoch {377 if epoch == authentication_epoch {
230- authentication_token = Some(authentication_token_)378+ authentication_token = Some(token);
231 }379 }
232 }380 }
233 381
234- error_value = client_request.closed() => {382+ error = connection.closed() => {
235- if event_sender.send(NetworkEvent::Disconnected(error_value.into())).await.is_err() {383+ if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() {
236- return ;384+ return;
237 }385 }
238 386
239 break;387 break;
@@ -244,14 +392,14 @@ async fn actor(
244 }392 }
245 393
246 async fn message_receive_loop(394 async fn message_receive_loop(
247- client_request: ClientRequest,395+ connection: quinn::Connection,
248 event_sender: mpsc::Sender<NetworkEvent>,396 event_sender: mpsc::Sender<NetworkEvent>,
249 ) {397 ) {
250- let Ok(mut receive_stream) = client_request.accept_unidirectional_stream().await else {398+ let Ok(mut receive_stream) = connection.accept_uni().await else {
251 return;399 return;
252 };400 };
253 401
254- while let Ok(message) = Network::receive_message(&mut receive_stream).await {402+ while let Ok(message) = receive_message(&mut receive_stream).await {
255 if event_sender403 if event_sender
256 .send(NetworkEvent::MessageReceived(message))404 .send(NetworkEvent::MessageReceived(message))
257 .await405 .await
crates/client/src/request.rsdeleted+0 -297
@@ -1,297 +0,0 @@
1-use common::{
2- community::Community,
3- constant::MESSAGE_PAGE_LIMIT,
4- error::Error,
5- message::Message,
6- network::Network,
7- request::{
8- Authentication, Deauthentication, Request,
9- community::{
10- CreateCommunity, DeleteCommunity, ReadCommunity, SearchCommunity, UpdateCommunity,
11- },
12- message::{
13- CreateMessage, DeleteMessage, ReadMessage, ReadMessageByCommunityIDWithMarkerAndLimit,
14- UpdateMessage,
15- },
16- user::{CreateUser, DeleteUser, ReadUser, UpdateUser},
17- user_community::{CommunityOf, IsUserIn, JoinCommunity, LeaveCommunity, UsersIn},
18- },
19- response::Response,
20- user::User,
21-};
22-
23-macro_rules! send_request_receive_response_then_classify {
24- ($request:expr, $variant:path, $connection:expr) => {{
25- let (send_stream, receive_stream) = $connection.open_bi().await?;
26- let response =
27- Network::send_request_and_receive_response(&$request, send_stream, receive_stream)
28- .await?;
29- match response {
30- $variant(inner) => Ok(inner),
31- Response::Error(error) => Err(error),
32- _ => Err(Error::Server),
33- }
34- }};
35-
36- (@unit $request:expr, $variant:path, $connection:expr) => {{
37- let (send_stream, receive_stream) = $connection.open_bi().await?;
38- let response =
39- Network::send_request_and_receive_response(&$request, send_stream, receive_stream)
40- .await?;
41- match response {
42- $variant => Ok(()),
43- Response::Error(error_value) => Err(error_value),
44- _ => Err(Error::Server),
45- }
46- }};
47-}
48-
49-#[derive(Debug, Clone)]
50-pub struct ClientRequest {
51- connection: quinn::Connection,
52-}
53-
54-impl ClientRequest {
55- pub fn new(connection: quinn::Connection) -> Self {
56- Self { connection }
57- }
58-
59- pub async fn closed(&self) -> Error {
60- self.connection.closed().await.into()
61- }
62-
63- pub async fn accept_unidirectional_stream(&self) -> Result<quinn::RecvStream, Error> {
64- Ok(self.connection.accept_uni().await?)
65- }
66-
67- pub async fn authenticate(&self, authentication_token: &str) -> Result<User, Error> {
68- let authentication = Authentication::new(authentication_token);
69- let request = Request::Authentication(authentication);
70-
71- send_request_receive_response_then_classify!(
72- request,
73- Response::Authentication,
74- self.connection
75- )
76- }
77-
78- pub async fn deauthenticate(&self, authentication_token: &str) -> Result<User, Error> {
79- let deauthentication = Deauthentication::new(authentication_token);
80- let request = Request::Deauthentication(deauthentication);
81-
82- send_request_receive_response_then_classify!(
83- request,
84- Response::Deauthentication,
85- self.connection
86- )
87- }
88-
89- pub async fn create_user(&self, username: &str) -> Result<User, Error> {
90- let create_user = CreateUser::new(username)?;
91- let request = Request::CreateUser(create_user);
92-
93- send_request_receive_response_then_classify!(request, Response::CreateUser, self.connection)
94- }
95-
96- pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {
97- let read_user = ReadUser::new(user_id);
98- let request = Request::ReadUser(read_user);
99-
100- send_request_receive_response_then_classify!(request, Response::ReadUser, self.connection)
101- }
102-
103- pub async fn update_user(&self, user_id: &str, username: &str) -> Result<User, Error> {
104- let update_user = UpdateUser::new(user_id, username)?;
105- let request = Request::UpdateUser(update_user);
106-
107- send_request_receive_response_then_classify!(request, Response::UpdateUser, self.connection)
108- }
109-
110- pub async fn delete_user(&self, user_id: &str) -> Result<User, Error> {
111- let delete_user = DeleteUser::new(user_id);
112- let request = Request::DeleteUser(delete_user);
113-
114- send_request_receive_response_then_classify!(request, Response::DeleteUser, self.connection)
115- }
116-
117- pub async fn create_community(&self, community_name: &str) -> Result<Community, Error> {
118- let create_community = CreateCommunity::new(community_name)?;
119- let request = Request::CreateCommunity(create_community);
120-
121- send_request_receive_response_then_classify!(
122- request,
123- Response::CreateCommunity,
124- self.connection
125- )
126- }
127-
128- pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> {
129- let read_community = ReadCommunity::new(community_id);
130- let request = Request::ReadCommunity(read_community);
131-
132- send_request_receive_response_then_classify!(
133- request,
134- Response::ReadCommunity,
135- self.connection
136- )
137- }
138-
139- pub async fn update_community(
140- &self,
141- community_id: &str,
142- community_name: &str,
143- ) -> Result<Community, Error> {
144- let update_community = UpdateCommunity::new(community_id, community_name)?;
145- let request = Request::UpdateCommunity(update_community);
146-
147- send_request_receive_response_then_classify!(
148- request,
149- Response::UpdateCommunity,
150- self.connection
151- )
152- }
153-
154- pub async fn delete_community(&self, community_id: &str) -> Result<Community, Error> {
155- let delete_community = DeleteCommunity::new(community_id);
156- let request = Request::DeleteCommunity(delete_community);
157-
158- send_request_receive_response_then_classify!(
159- request,
160- Response::DeleteCommunity,
161- self.connection
162- )
163- }
164-
165- pub async fn create_message(
166- &self,
167- user_id: &str,
168- community_id: &str,
169- message_body: &str,
170- ) -> Result<Message, Error> {
171- let create_message = CreateMessage::new(user_id, community_id, message_body)?;
172- let request = Request::CreateMessage(create_message);
173-
174- send_request_receive_response_then_classify!(
175- request,
176- Response::CreateMessage,
177- self.connection
178- )
179- }
180-
181- pub async fn read_message(&self, message_id: &str) -> Result<Message, Error> {
182- let read_message = ReadMessage::new(message_id);
183- let request = Request::ReadMessage(read_message);
184-
185- send_request_receive_response_then_classify!(
186- request,
187- Response::ReadMessage,
188- self.connection
189- )
190- }
191-
192- pub async fn update_message(
193- &self,
194- message_id: &str,
195- message_body: &str,
196- ) -> Result<Message, Error> {
197- let update_message = UpdateMessage::new(message_id, message_body)?;
198- let request = Request::UpdateMessage(update_message);
199-
200- send_request_receive_response_then_classify!(
201- request,
202- Response::UpdateMessage,
203- self.connection
204- )
205- }
206-
207- pub async fn delete_message(&self, message_id: &str) -> Result<Message, Error> {
208- let delete_message = DeleteMessage::new(message_id);
209- let request = Request::DeleteMessage(delete_message);
210-
211- send_request_receive_response_then_classify!(
212- request,
213- Response::DeleteMessage,
214- self.connection
215- )
216- }
217-
218- pub async fn read_message_by_community_id_with_marker_and_limit(
219- &self,
220- community_id: &str,
221- marker: &str,
222- ) -> Result<Vec<Message>, Error> {
223- let read_message_by_community_id_with_marker_and_limit =
224- ReadMessageByCommunityIDWithMarkerAndLimit::new(
225- community_id,
226- marker,
227- MESSAGE_PAGE_LIMIT,
228- );
229- let request = Request::ReadMessageByCommunityIDWithMarkerAndLimit(
230- read_message_by_community_id_with_marker_and_limit,
231- );
232-
233- send_request_receive_response_then_classify!(
234- request,
235- Response::ReadMessageByCommunityIDWithMarkerAndLimit,
236- self.connection
237- )
238- }
239-
240- pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> {
241- let join_community = JoinCommunity::new(user_id, community_id);
242- let request = Request::JoinCommunity(join_community);
243-
244- send_request_receive_response_then_classify!(
245- @unit request,
246- Response::JoinCommunity,
247- self.connection
248- )
249- }
250-
251- pub async fn leave_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> {
252- let leave_community = LeaveCommunity::new(user_id, community_id);
253- let request = Request::LeaveCommunity(leave_community);
254-
255- send_request_receive_response_then_classify!(
256- @unit request,
257- Response::LeaveCommunity,
258- self.connection
259- )
260- }
261-
262- pub async fn is_user_in(&self, user_id: &str, community_id: &str) -> Result<bool, Error> {
263- let is_user_in = IsUserIn::new(user_id, community_id);
264- let request = Request::IsUserIn(is_user_in);
265-
266- send_request_receive_response_then_classify!(request, Response::IsUserIn, self.connection)
267- }
268-
269- pub async fn users_in(&self, community_id: &str) -> Result<Vec<String>, Error> {
270- let users_in = UsersIn::new(community_id);
271- let request = Request::UsersIn(users_in);
272-
273- send_request_receive_response_then_classify!(request, Response::UsersIn, self.connection)
274- }
275-
276- pub async fn community_of(&self, user_id: &str) -> Result<Vec<String>, Error> {
277- let community_of = CommunityOf::new(user_id);
278- let request = Request::CommunityOf(community_of);
279-
280- send_request_receive_response_then_classify!(
281- request,
282- Response::CommunityOf,
283- self.connection
284- )
285- }
286-
287- pub async fn search_community(&self, community_name: &str) -> Result<Vec<Community>, Error> {
288- let search_community = SearchCommunity::new(community_name)?;
289- let request = Request::SearchCommunity(search_community);
290-
291- send_request_receive_response_then_classify!(
292- request,
293- Response::SearchCommunity,
294- self.connection
295- )
296- }
297-}
crates/common/Cargo.tomlmodified+3 -4
@@ -3,10 +3,9 @@ name = "common"
3 version = "0.1.0"3 version = "0.1.0"
4 edition = "2024"4 edition = "2024"
5 5
6-[features]
7-client = []
8-server = []
9-
10 [dependencies]6 [dependencies]
11 bitcode.workspace = true7 bitcode.workspace = true
12 quinn.workspace = true8 quinn.workspace = true
9+
10+[lints]
11+workspace = true
crates/common/src/community.rsdeleted+0 -28
@@ -1,28 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-#[derive(Debug, Clone, Encode, Decode)]
4-pub struct Community {
5- community_id: String,
6- community_name: String,
7-}
8-
9-impl Community {
10- #[cfg(feature = "server")]
11- pub fn new(community_id: &str, community_name: &str) -> Self {
12- let community_id = community_id.to_string();
13- let community_name = community_name.to_string();
14-
15- Self {
16- community_id,
17- community_name,
18- }
19- }
20-
21- pub fn get_community_id(&self) -> &str {
22- &self.community_id
23- }
24-
25- pub fn get_community_name(&self) -> &str {
26- &self.community_name
27- }
28-}
crates/common/src/config.rsadded+20 -0
@@ -0,0 +1,20 @@
1+use std::collections::HashMap;
2+
3+use crate::error::Error;
4+
5+pub fn parse(content: &str) -> Result<HashMap<String, String>, Error> {
6+ content
7+ .lines()
8+ .map(str::trim)
9+ .filter(|line| !line.is_empty() && !line.starts_with('[') && !line.starts_with('#'))
10+ .map(|line| {
11+ let (key, value) = line
12+ .split_once('=')
13+ .ok_or_else(|| Error::Config(format!("Invalid line: {line}")))?;
14+ Ok((
15+ key.replace('"', "").trim().to_string(),
16+ value.replace('"', "").trim().to_string(),
17+ ))
18+ })
19+ .collect()
20+}
crates/common/src/error.rsmodified+96 -35
@@ -1,50 +1,111 @@
1+use std::fmt::Display;
2+
1 use bitcode::{Decode, Encode};3 use bitcode::{Decode, Encode};
2 4
3-use crate::{error_display, error_from};5+#[macro_export]
6+macro_rules! error_from {
7+ ($target:ty { $($rest:tt)* }) => {
8+ $crate::error_from!(@arm $target, $($rest)*);
9+ };
10+
11+ (@arm $target:ty, $source:ty => $variant:path as $middle:ty, $($rest:tt)*) => {
12+ impl From<$source> for $target {
13+ fn from(value: $source) -> Self {
14+ $variant(<$middle>::from(value).into())
15+ }
16+ }
17+ $crate::error_from!(@arm $target, $($rest)*);
18+ };
19+
20+ (@arm $target:ty, $source:ty => $variant:path, $($rest:tt)*) => {
21+ impl From<$source> for $target {
22+ fn from(value: $source) -> Self {
23+ $variant(value)
24+ }
25+ }
26+ $crate::error_from!(@arm $target, $($rest)*);
27+ };
4 28
5-pub mod community;29+ (@arm $target:ty,) => {};
6-pub mod decode;30+}
7-pub mod file_operation;31+
8-pub mod macro_;32+macro_rules! from_display {
9-pub mod message;33+ ($target:ty { $($source:ty => $variant:path),+ $(,)? }) => {
10-pub mod network;34+ $(
11-pub mod user;35+ impl From<$source> for $target {
36+ fn from(value: $source) -> Self {
37+ $variant(value.to_string())
38+ }
39+ }
40+ )+
41+ };
42+}
43+
44+#[derive(Debug, Clone, Encode, Decode)]
45+pub enum InvalidInput {
46+ TooShort { minimum: usize, actual: usize },
47+ TooLong { maximum: usize, actual: usize },
48+ NotASCII,
49+}
50+
51+impl Display for InvalidInput {
52+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53+ match self {
54+ InvalidInput::TooShort { minimum, actual } => {
55+ write!(f, "too short ({actual} < {minimum})")
56+ }
57+ InvalidInput::TooLong { maximum, actual } => {
58+ write!(f, "too long ({actual} > {maximum})")
59+ }
60+ InvalidInput::NotASCII => write!(f, "not ASCII"),
61+ }
62+ }
63+}
12 64
13 #[derive(Debug, Clone, Encode, Decode)]65 #[derive(Debug, Clone, Encode, Decode)]
14 pub enum Error {66 pub enum Error {
15 Authenticate,67 Authenticate,
16- User(user::Error),
17- Community(community::Error),
18- Message(message::Error),
19- FileOperation(file_operation::Error),
20- Network(network::Error),
21- Decode(decode::Error),
22 Server,68 Server,
69+ ChannelClosed,
70+ Config(String),
71+ Network(String),
72+ Decode(String),
73+ ReadBoundExceed { actual: usize, maximum: usize },
74+ User(InvalidInput),
75+ Community(InvalidInput),
76+ Message(InvalidInput),
23 }77 }
24 78
25 impl std::error::Error for Error {}79 impl std::error::Error for Error {}
26 80
27-error_display! { Error,81+impl Display for Error {
28- delegate = [Error::User, Error::Message, Error::Community, Error::FileOperation, Error::Network, Error::Decode],82+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29- unit = [Error::Authenticate => "Authenticate", Error::Server => "Server"],83+ match self {
84+ Error::Authenticate => write!(f, "Authenticate"),
85+ Error::Server => write!(f, "Server"),
86+ Error::ChannelClosed => write!(f, "Channel closed"),
87+ Error::Config(message) => write!(f, "Config: {message}"),
88+ Error::Network(message) => write!(f, "Network: {message}"),
89+ Error::Decode(message) => write!(f, "Decode: {message}"),
90+ Error::ReadBoundExceed { actual, maximum } => {
91+ write!(f, "Read bound exceeded ({actual} > {maximum})")
92+ }
93+ Error::User(e) => write!(f, "Username: {e}"),
94+ Error::Community(e) => write!(f, "Community name: {e}"),
95+ Error::Message(e) => write!(f, "Message: {e}"),
96+ }
97+ }
30 }98 }
31 99
32-error_from! { Error {100+from_display! { Error {
33- user::Error => Error::User,101+ std::net::AddrParseError => Error::Network,
34- community::Error => Error::Community,102+ std::io::Error => Error::Network,
35- message::Error => Error::Message,103+ quinn::ConnectionError => Error::Network,
36- file_operation::Error => Error::FileOperation,104+ quinn::ConnectError => Error::Network,
37- network::Error => Error::Network,105+ quinn::ReadError => Error::Network,
38- decode::Error => Error::Decode,106+ quinn::ReadToEndError => Error::Network,
39-107+ quinn::ReadExactError => Error::Network,
40- std::net::AddrParseError => Error::Network as network::Error,108+ quinn::WriteError => Error::Network,
41- std::io::Error => Error::Network as network::Error,109+ quinn::ClosedStream => Error::Network,
42- quinn::ConnectionError => Error::Network as network::Error,110+ bitcode::Error => Error::Decode,
43- quinn::ConnectError => Error::Network as network::Error,
44- quinn::ReadError => Error::Network as network::Error,
45- quinn::ReadToEndError => Error::Network as network::Error,
46- quinn::ReadExactError => Error::Network as network::Error,
47- quinn::WriteError => Error::Network as network::Error,
48- quinn::ClosedStream => Error::Network as network::Error,
49- bitcode::Error => Error::Decode as decode::Error,
50 } }111 } }
crates/common/src/error/community.rsdeleted+0 -32
@@ -1,32 +0,0 @@
1-use std::fmt::Display;
2-
3-use bitcode::{Decode, Encode};
4-
5-use crate::constant::{MAXIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_COMMUNITY_NAME_LENGTH};
6-
7-#[derive(Debug, Clone, Encode, Decode)]
8-pub enum Error {
9- MaximumLength(usize),
10- MinimumLength(usize),
11- ASCII,
12-}
13-
14-impl std::error::Error for Error {}
15-
16-impl Display for Error {
17- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18- match self {
19- Error::MaximumLength(length) => write!(
20- f,
21- "More than maximum length({}) is provided({})",
22- MAXIMUM_COMMUNITY_NAME_LENGTH, length
23- ),
24- Error::MinimumLength(length) => write!(
25- f,
26- "Less than minimum length({}) is provided({})",
27- MINIMUM_COMMUNITY_NAME_LENGTH, length
28- ),
29- Error::ASCII => write!(f, "Given input is not ASCII compatible"),
30- }
31- }
32-}
crates/common/src/error/decode.rsdeleted+0 -24
@@ -1,24 +0,0 @@
1-use std::fmt::Display;
2-
3-use bitcode::{Decode, Encode};
4-
5-use crate::error_from_display;
6-
7-#[derive(Debug, Clone, Encode, Decode)]
8-pub enum Error {
9- Inner(String),
10-}
11-
12-impl std::error::Error for Error {}
13-
14-impl Display for Error {
15- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16- match self {
17- Error::Inner(error_value) => error_value.fmt(f),
18- }
19- }
20-}
21-
22-error_from_display! { Error {
23- bitcode::Error => Error::Inner,
24-} }
crates/common/src/error/file_operation.rsdeleted+0 -24
@@ -1,24 +0,0 @@
1-use std::fmt::Display;
2-
3-use bitcode::{Decode, Encode};
4-
5-#[derive(Debug, Clone, Encode, Decode)]
6-pub enum Error {
7- FileOpen(String),
8- Read,
9- Empty,
10- Split,
11-}
12-
13-impl std::error::Error for Error {}
14-
15-impl Display for Error {
16- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17- match self {
18- Error::FileOpen(error_value) => write!(f, "File open is failed| {}", error_value),
19- Error::Read => write!(f, "Read file context is failed"),
20- Error::Empty => write!(f, "File is empty"),
21- Error::Split => write!(f, "Splitting context is failed"),
22- }
23- }
24-}
crates/common/src/error/macro_.rsdeleted+0 -56
@@ -1,56 +0,0 @@
1-#[macro_export]
2-macro_rules! error_from {
3- ($target:ty { $($rest:tt)* }) => {
4- $crate::error_from!(@arm $target, $($rest)*);
5- };
6-
7- (@arm $target:ty, $source:ty => $variant:path as $middle:ty, $($rest:tt)*) => {
8- impl From<$source> for $target {
9- fn from(value: $source) -> Self {
10- $variant(<$middle>::from(value).into())
11- }
12- }
13- $crate::error_from!(@arm $target, $($rest)*);
14- };
15-
16- (@arm $target:ty, $source:ty => $variant:path, $($rest:tt)*) => {
17- impl From<$source> for $target {
18- fn from(value: $source) -> Self {
19- $variant(value)
20- }
21- }
22- $crate::error_from!(@arm $target, $($rest)*);
23- };
24-
25- (@arm $target:ty,) => {};
26-}
27-
28-#[macro_export]
29-macro_rules! error_from_display {
30- ($target:ty { $($source:ty => $variant:path),+ $(,)? }) => {
31- $(
32- impl From<$source> for $target {
33- fn from(value: $source) -> Self {
34- $variant(value.to_string())
35- }
36- }
37- )+
38- };
39-}
40-
41-#[macro_export]
42-macro_rules! error_display {
43- ($target:ty,
44- delegate = [$($variant:path),* $(,)?],
45- unit = [$($unit:path => $message:literal),* $(,)?] $(,)?
46- ) => {
47- impl std::fmt::Display for $target {
48- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49- match self {
50- $($variant(error_value) => std::fmt::Display::fmt(error_value, formatter),)*
51- $($unit => formatter.write_str($message),)*
52- }
53- }
54- }
55- };
56-}
crates/common/src/error/message.rsdeleted+0 -32
@@ -1,32 +0,0 @@
1-use std::fmt::Display;
2-
3-use bitcode::{Decode, Encode};
4-
5-use crate::constant::{MAXIMUM_MESSAGE_LENGTH, MINIMUM_MESSAGE_LENGTH};
6-
7-#[derive(Debug, Clone, Encode, Decode)]
8-pub enum Error {
9- MaximumLength(usize),
10- MinimumLength(usize),
11- ASCII,
12-}
13-
14-impl std::error::Error for Error {}
15-
16-impl Display for Error {
17- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18- match self {
19- Error::MaximumLength(length) => write!(
20- f,
21- "More than maximum length({}) is provided({})",
22- MAXIMUM_MESSAGE_LENGTH, length
23- ),
24- Error::MinimumLength(length) => write!(
25- f,
26- "Less than minimum length({}) is provided({})",
27- MINIMUM_MESSAGE_LENGTH, length
28- ),
29- Error::ASCII => write!(f, "Given input is not ASCII compatible"),
30- }
31- }
32-}
crates/common/src/error/network.rsdeleted+0 -58
@@ -1,58 +0,0 @@
1-use std::fmt::Display;
2-
3-use bitcode::{Decode, Encode};
4-
5-use crate::error_from_display;
6-
7-#[derive(Debug, Clone, Encode, Decode)]
8-pub enum Error {
9- AddressParse(String),
10- InputOutput(String),
11- Connect(String),
12- Connection(String),
13- Read(String),
14- ReadToEnd(String),
15- ReadExact(String),
16- Write(String),
17- ClosedStream(String),
18- ConnectionError(String),
19- ChannelClosed,
20- ReadBoundExceed(usize, usize),
21-}
22-
23-impl std::error::Error for Error {}
24-
25-impl Display for Error {
26- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27- match self {
28- Error::AddressParse(error_value) => error_value.fmt(f),
29- Error::InputOutput(error_value) => error_value.fmt(f),
30- Error::Connect(error_value) => error_value.fmt(f),
31- Error::Connection(error_value) => error_value.fmt(f),
32- Error::Read(error_value) => error_value.fmt(f),
33- Error::ReadToEnd(error_value) => error_value.fmt(f),
34- Error::ReadExact(error_value) => error_value.fmt(f),
35- Error::Write(error_value) => error_value.fmt(f),
36- Error::ClosedStream(error_value) => error_value.fmt(f),
37- Error::ConnectionError(error_value) => error_value.fmt(f),
38- Error::ChannelClosed => write!(f, "Channel Closed"),
39- Error::ReadBoundExceed(actual, expected) => write!(
40- f,
41- "Read Bound Exceed | Actual = {} | Expected = {}",
42- actual, expected
43- ),
44- }
45- }
46-}
47-
48-error_from_display! { Error {
49- std::net::AddrParseError => Error::AddressParse,
50- std::io::Error => Error::InputOutput,
51- quinn::ConnectionError => Error::Connection,
52- quinn::ConnectError => Error::Connect,
53- quinn::ReadError => Error::Read,
54- quinn::ReadToEndError => Error::ReadToEnd,
55- quinn::ReadExactError => Error::ReadExact,
56- quinn::WriteError => Error::Write,
57- quinn::ClosedStream => Error::ClosedStream,
58-} }
crates/common/src/error/user.rsdeleted+0 -32
@@ -1,32 +0,0 @@
1-use std::fmt::Display;
2-
3-use bitcode::{Decode, Encode};
4-
5-use crate::constant::{MAXIMUM_USERNAME_LENGTH, MINIMUM_USERNAME_LENGTH};
6-
7-#[derive(Debug, Clone, Encode, Decode)]
8-pub enum Error {
9- MaximumLength(usize),
10- MinimumLength(usize),
11- ASCII,
12-}
13-
14-impl std::error::Error for Error {}
15-
16-impl Display for Error {
17- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18- match self {
19- Error::MaximumLength(length) => write!(
20- f,
21- "More than maximum length({}) is provided({})",
22- MAXIMUM_USERNAME_LENGTH, length
23- ),
24- Error::MinimumLength(length) => write!(
25- f,
26- "Less than minimum length({}) is provided({})",
27- MINIMUM_USERNAME_LENGTH, length
28- ),
29- Error::ASCII => write!(f, "Given input is not ASCII compatible"),
30- }
31- }
32-}
crates/common/src/event.rsdeleted+0 -14
@@ -1,14 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-use crate::{community::Community, message::Message, user::User};
4-
5-#[derive(Debug, Clone, Encode, Decode)]
6-pub enum Event {
7- MessageCreate(Message),
8- MessageUpdate(Message),
9- MessageDelete(Message),
10- UserJoin(Community, User),
11- UserLeave(Community, User),
12- CommunityUpdate(Community),
13- CommunityDelete(Community),
14-}
crates/common/src/lib.rsmodified+2 -5
@@ -1,11 +1,8 @@
1-pub mod community;1+pub mod config;
2 pub mod constant;2 pub mod constant;
3 pub mod error;3 pub mod error;
4-pub mod event;4+pub mod model;
5-pub mod message;
6 pub mod network;5 pub mod network;
7 pub mod request;6 pub mod request;
8 pub mod response;7 pub mod response;
9-pub mod user;
10-pub mod utils;
11 pub mod validate;8 pub mod validate;
crates/common/src/message.rsdeleted+0 -42
@@ -1,42 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-#[derive(Debug, Clone, Encode, Decode)]
4-pub struct Message {
5- message_id: String,
6- user_id: String,
7- community_id: String,
8- message_body: String,
9-}
10-
11-impl Message {
12- #[cfg(feature = "server")]
13- pub fn new(message_id: &str, user_id: &str, community_id: &str, message_body: &str) -> Self {
14- let message_id = message_id.to_string();
15- let user_id = user_id.to_string();
16- let community_id = community_id.to_string();
17- let message_body = message_body.to_string();
18-
19- Self {
20- message_id,
21- user_id,
22- community_id,
23- message_body,
24- }
25- }
26-
27- pub fn get_id(&self) -> &str {
28- &self.message_id
29- }
30-
31- pub fn get_community_id(&self) -> &str {
32- &self.community_id
33- }
34-
35- pub fn get_user_id(&self) -> &str {
36- &self.user_id
37- }
38-
39- pub fn get_message_body(&self) -> &str {
40- &self.message_body
41- }
42-}
crates/common/src/model.rsadded+21 -0
@@ -0,0 +1,21 @@
1+use bitcode::{Decode, Encode};
2+
3+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
4+pub struct User {
5+ pub id: String,
6+ pub username: String,
7+}
8+
9+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
10+pub struct Community {
11+ pub id: String,
12+ pub name: String,
13+}
14+
15+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
16+pub struct Message {
17+ pub id: String,
18+ pub user_id: String,
19+ pub community_id: String,
20+ pub body: String,
21+}
crates/common/src/network.rsmodified+46 -65
@@ -3,83 +3,64 @@ use quinn::{RecvStream, SendStream};
3 use crate::{3 use crate::{
4 constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT},4 constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT},
5 error::Error,5 error::Error,
6- message::Message,6+ model::Message,
7 request::Request,7 request::Request,
8 response::Response,8 response::Response,
9 };9 };
10 10
11-pub const AUTHENTICATION_MAX_READ_LENGHT: usize = 64;11+pub const AUTHENTICATION_MAX_READ_LENGTH: usize = 64;
12-pub const REQUEST_MAX_READ_LENGHT: usize = MAXIMUM_MESSAGE_LENGTH * 2;12+pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2;
13 pub const MESSAGE_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2;13 pub const MESSAGE_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2;
14-pub const RESPONSE_MAX_READ_LENGHT: usize = MESSAGE_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT;14+pub const RESPONSE_MAX_READ_LENGTH: usize = MESSAGE_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT;
15 15
16-pub struct Network;16+pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> {
17-17+ send_stream.write_all(&bitcode::encode(response)).await?;
18-impl Network {18+ send_stream.finish()?;
19- pub async fn send_response(19+ Ok(())
20- response: &Response,20+}
21- mut send_stream: SendStream,
22- ) -> Result<(), Error> {
23- Ok({
24- send_stream.write_all(&bitcode::encode(response)).await?;
25- send_stream.finish()?;
26- })
27- }
28-
29- pub async fn receive_request(
30- mut receive_stream: RecvStream,
31- size_limit: Option<usize>,
32- ) -> Result<Request, Error> {
33- let request = match size_limit {
34- Some(size_limit) => receive_stream.read_to_end(size_limit).await?,
35- None => receive_stream.read_to_end(REQUEST_MAX_READ_LENGHT).await?,
36- };
37 21
38- Ok(bitcode::decode::<Request>(&request)?)22+pub async fn receive_request(
39- }23+ mut receive_stream: RecvStream,
24+ limit: usize,
25+) -> Result<Request, Error> {
26+ let bytes = receive_stream.read_to_end(limit).await?;
27+ Ok(bitcode::decode(&bytes)?)
28+}
40 29
41- pub async fn send_request_and_receive_response(30+pub async fn send_request(
42- request: &Request,31+ request: &Request,
43- mut send_stream: SendStream,32+ mut send_stream: SendStream,
44- mut receive_stream: RecvStream,33+ mut receive_stream: RecvStream,
45- ) -> Result<Response, Error> {34+) -> Result<Response, Error> {
46- send_stream.write_all(&bitcode::encode(request)).await?;35+ send_stream.write_all(&bitcode::encode(request)).await?;
47- send_stream.finish()?;36+ send_stream.finish()?;
48 37
49- let response = receive_stream.read_to_end(RESPONSE_MAX_READ_LENGHT).await?;38+ let bytes = receive_stream.read_to_end(RESPONSE_MAX_READ_LENGTH).await?;
39+ Ok(bitcode::decode(&bytes)?)
40+}
50 41
51- Ok(bitcode::decode::<Response>(&response)?)42+pub async fn send_message(message: &Message, send_stream: &mut SendStream) -> Result<(), Error> {
52- }43+ let payload = bitcode::encode(message);
44+ send_stream
45+ .write_all(&(payload.len() as u32).to_le_bytes())
46+ .await?;
47+ send_stream.write_all(&payload).await?;
48+ Ok(())
49+}
53 50
54- pub async fn send_message(51+pub async fn receive_message(receive_stream: &mut RecvStream) -> Result<Message, Error> {
55- message: &Message,52+ let mut length_bytes = [0u8; 4];
56- send_stream: &mut SendStream,53+ receive_stream.read_exact(&mut length_bytes).await?;
57- ) -> Result<(), Error> {
58- let payload = bitcode::encode(message);
59- send_stream
60- .write_all(&(payload.len() as u32).to_le_bytes())
61- .await?;
62- send_stream.write_all(&payload).await?;
63 54
64- Ok(())55+ let length = u32::from_le_bytes(length_bytes) as usize;
56+ if length > MESSAGE_MAX_ENCODED_LENGTH {
57+ return Err(Error::ReadBoundExceed {
58+ actual: length,
59+ maximum: MESSAGE_MAX_ENCODED_LENGTH,
60+ });
65 }61 }
66 62
67- pub async fn receive_message(receive_stream: &mut RecvStream) -> Result<Message, Error> {63+ let mut payload = vec![0u8; length];
68- let mut length_bytes = [0u8; 4];64+ receive_stream.read_exact(&mut payload).await?;
69- receive_stream.read_exact(&mut length_bytes).await?;65+ Ok(bitcode::decode(&payload)?)
70-
71- let length = u32::from_le_bytes(length_bytes) as usize;
72- if length > MESSAGE_MAX_ENCODED_LENGTH {
73- return Err(crate::error::network::Error::ReadBoundExceed(
74- length,
75- RESPONSE_MAX_READ_LENGHT,
76- )
77- .into());
78- }
79-
80- let mut payload = vec![0u8; length];
81- receive_stream.read_exact(&mut payload).await?;
82-
83- Ok(bitcode::decode(&payload)?)
84- }
85 }66 }
crates/common/src/request.rsmodified+21 -64
@@ -1,69 +1,26 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::request::{
4- community::{
5- CreateCommunity, DeleteCommunity, ReadCommunity, SearchCommunity, UpdateCommunity,
6- },
7- message::{
8- CreateMessage, DeleteMessage, ReadMessage, ReadMessageByCommunityIDWithMarkerAndLimit,
9- UpdateMessage,
10- },
11- user::{CreateUser, DeleteUser, ReadUser, UpdateUser},
12- user_community::{CommunityOf, IsUserIn, JoinCommunity, LeaveCommunity, UsersIn},
13-};
14-
15-pub mod community;
16-pub mod message;
17-pub mod user;
18-pub mod user_community;
19-
20-#[derive(Debug, Clone, Encode, Decode)]
21-pub struct Authentication(String);
22-
23-impl Authentication {
24- pub fn new(authentication_token: &str) -> Self {
25- Self(authentication_token.to_string())
26- }
27-
28- pub fn get_authentication_token(&self) -> &str {
29- &self.0
30- }
31-}
32-
33-#[derive(Debug, Clone, Encode, Decode)]
34-pub struct Deauthentication(String);
35-
36-impl Deauthentication {
37- pub fn new(authentication_token: &str) -> Self {
38- Self(authentication_token.to_string())
39- }
40-
41- pub fn get_authentication_token(&self) -> &str {
42- &self.0
43- }
44-}
45-
46 #[derive(Debug, Clone, Encode, Decode)]3 #[derive(Debug, Clone, Encode, Decode)]
47 pub enum Request {4 pub enum Request {
48- Authentication(Authentication),5+ Authentication { token: String },
49- Deauthentication(Deauthentication),6+ Deauthentication { token: String },
50- CreateUser(CreateUser),7+ CreateUser { username: String },
51- ReadUser(ReadUser),8+ ReadUser { user_id: String },
52- UpdateUser(UpdateUser),9+ UpdateUser { user_id: String, username: String },
53- DeleteUser(DeleteUser),10+ DeleteUser { user_id: String },
54- CreateCommunity(CreateCommunity),11+ CreateCommunity { name: String },
55- ReadCommunity(ReadCommunity),12+ ReadCommunity { community_id: String },
56- UpdateCommunity(UpdateCommunity),13+ UpdateCommunity { community_id: String, name: String },
57- DeleteCommunity(DeleteCommunity),14+ DeleteCommunity { community_id: String },
58- CreateMessage(CreateMessage),15+ CreateMessage { user_id: String, community_id: String, body: String },
59- ReadMessage(ReadMessage),16+ ReadMessage { message_id: String },
60- UpdateMessage(UpdateMessage),17+ UpdateMessage { message_id: String, body: String },
61- DeleteMessage(DeleteMessage),18+ DeleteMessage { message_id: String },
62- ReadMessageByCommunityIDWithMarkerAndLimit(ReadMessageByCommunityIDWithMarkerAndLimit),19+ ReadMessages { community_id: String, marker: String, limit: usize },
63- JoinCommunity(JoinCommunity),20+ JoinCommunity { user_id: String, community_id: String },
64- LeaveCommunity(LeaveCommunity),21+ LeaveCommunity { user_id: String, community_id: String },
65- IsUserIn(IsUserIn),22+ IsUserIn { user_id: String, community_id: String },
66- UsersIn(UsersIn),23+ UsersIn { community_id: String },
67- CommunityOf(CommunityOf),24+ CommunitiesOf { user_id: String },
68- SearchCommunity(SearchCommunity),25+ SearchCommunity { name: String },
69 }26 }
crates/common/src/request/community.rsdeleted+0 -100
@@ -1,100 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-use crate::{error::Error, validate::validate_community_name};
4-
5-#[derive(Debug, Clone, Encode, Decode)]
6-pub struct CreateCommunity {
7- community_name: String,
8-}
9-
10-impl CreateCommunity {
11- pub fn new(community_name: &str) -> Result<Self, Error> {
12- let community_name = community_name.to_string();
13- validate_community_name(&community_name)?;
14-
15- Ok(Self { community_name })
16- }
17-
18- pub fn get_community_name(&self) -> &str {
19- &self.community_name
20- }
21-}
22-
23-#[derive(Debug, Clone, Encode, Decode)]
24-pub struct ReadCommunity {
25- community_id: String,
26-}
27-
28-impl ReadCommunity {
29- pub fn new(community_id: &str) -> Self {
30- let community_id = community_id.to_string();
31-
32- Self { community_id }
33- }
34-
35- pub fn get_community_id(&self) -> &str {
36- &self.community_id
37- }
38-}
39-
40-#[derive(Debug, Clone, Encode, Decode)]
41-pub struct UpdateCommunity {
42- community_id: String,
43- community_name: String,
44-}
45-
46-impl UpdateCommunity {
47- pub fn new(community_id: &str, community_name: &str) -> Result<Self, Error> {
48- let community_id = community_id.to_string();
49- let community_name = community_name.to_string();
50- validate_community_name(&community_name)?;
51-
52- Ok(Self {
53- community_id,
54- community_name,
55- })
56- }
57-
58- pub fn get_community_id(&self) -> &str {
59- &self.community_id
60- }
61-
62- pub fn get_community_name(&self) -> &str {
63- &self.community_name
64- }
65-}
66-
67-#[derive(Debug, Clone, Encode, Decode)]
68-pub struct DeleteCommunity {
69- community_id: String,
70-}
71-
72-impl DeleteCommunity {
73- pub fn new(community_id: &str) -> Self {
74- let community_id = community_id.to_string();
75-
76- Self { community_id }
77- }
78-
79- pub fn get_community_id(&self) -> &str {
80- &self.community_id
81- }
82-}
83-
84-#[derive(Debug, Clone, Encode, Decode)]
85-pub struct SearchCommunity {
86- community_name: String,
87-}
88-
89-impl SearchCommunity {
90- pub fn new(community_name: &str) -> Result<Self, Error> {
91- let community_name = community_name.to_string();
92- validate_community_name(&community_name)?;
93-
94- Ok(Self { community_name })
95- }
96-
97- pub fn get_community_name(&self) -> &str {
98- &self.community_name
99- }
100-}
crates/common/src/request/message.rsdeleted+0 -130
@@ -1,130 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-use crate::{error::Error, validate::validate_message_body};
4-
5-#[derive(Debug, Clone, Encode, Decode)]
6-pub struct CreateMessage {
7- community_id: String,
8- user_id: String,
9- message_body: String,
10-}
11-
12-impl CreateMessage {
13- pub fn new(user_id: &str, community_id: &str, message_body: &str) -> Result<Self, Error> {
14- let user_id = user_id.to_string();
15- let community_id = community_id.to_string();
16- let message_body = message_body.to_string();
17- validate_message_body(&message_body)?;
18-
19- Ok(Self {
20- community_id,
21- user_id,
22- message_body,
23- })
24- }
25-
26- pub fn get_community_id(&self) -> &str {
27- &self.community_id
28- }
29-
30- pub fn get_user_id(&self) -> &str {
31- &self.user_id
32- }
33-
34- pub fn get_message_body(&self) -> &str {
35- &self.message_body
36- }
37-}
38-
39-#[derive(Debug, Clone, Encode, Decode)]
40-pub struct ReadMessage {
41- message_id: String,
42-}
43-
44-impl ReadMessage {
45- pub fn new(message_id: &str) -> Self {
46- let message_id = message_id.to_string();
47-
48- Self { message_id }
49- }
50-
51- pub fn get_message_id(&self) -> &str {
52- &self.message_id
53- }
54-}
55-
56-#[derive(Debug, Clone, Encode, Decode)]
57-pub struct UpdateMessage {
58- message_id: String,
59- message_body: String,
60-}
61-
62-impl UpdateMessage {
63- pub fn new(message_id: &str, message_body: &str) -> Result<Self, Error> {
64- let message_id = message_id.to_string();
65- let message_body = message_body.to_string();
66- validate_message_body(&message_body)?;
67-
68- Ok(Self {
69- message_id,
70- message_body,
71- })
72- }
73-
74- pub fn get_message_id(&self) -> &str {
75- &self.message_id
76- }
77-
78- pub fn get_message_body(&self) -> &str {
79- &self.message_body
80- }
81-}
82-
83-#[derive(Debug, Clone, Encode, Decode)]
84-pub struct DeleteMessage {
85- message_id: String,
86-}
87-
88-impl DeleteMessage {
89- pub fn new(message_id: &str) -> Self {
90- let message_id = message_id.to_string();
91-
92- Self { message_id }
93- }
94-
95- pub fn get_message_id(&self) -> &str {
96- &self.message_id
97- }
98-}
99-
100-#[derive(Debug, Clone, Encode, Decode)]
101-pub struct ReadMessageByCommunityIDWithMarkerAndLimit {
102- community_id: String,
103- marker: String,
104- limit: usize,
105-}
106-
107-impl ReadMessageByCommunityIDWithMarkerAndLimit {
108- pub fn new(community_id: &str, marker: &str, limit: usize) -> Self {
109- let community_id = community_id.to_string();
110- let marker = marker.to_string();
111-
112- Self {
113- community_id,
114- marker,
115- limit,
116- }
117- }
118-
119- pub fn get_community_id(&self) -> &str {
120- &self.community_id
121- }
122-
123- pub fn get_marker(&self) -> &str {
124- self.marker.as_str()
125- }
126-
127- pub fn get_limit(&self) -> usize {
128- self.limit
129- }
130-}
crates/common/src/request/user.rsdeleted+0 -79
@@ -1,79 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-use crate::{error::Error, validate::validate_username};
4-
5-#[derive(Debug, Clone, Encode, Decode)]
6-pub struct CreateUser {
7- username: String,
8-}
9-
10-impl CreateUser {
11- pub fn new(username: &str) -> Result<Self, Error> {
12- let username = username.to_string();
13- validate_username(&username)?;
14-
15- Ok(Self { username })
16- }
17-
18- pub fn get_username(&self) -> &str {
19- &self.username
20- }
21-}
22-
23-#[derive(Debug, Clone, Encode, Decode)]
24-pub struct ReadUser {
25- user_id: String,
26-}
27-
28-impl ReadUser {
29- pub fn new(user_id: &str) -> Self {
30- let user_id = user_id.to_string();
31-
32- Self { user_id }
33- }
34-
35- pub fn get_user_id(&self) -> &str {
36- &self.user_id
37- }
38-}
39-
40-#[derive(Debug, Clone, Encode, Decode)]
41-pub struct UpdateUser {
42- user_id: String,
43- username: String,
44-}
45-
46-impl UpdateUser {
47- pub fn new(user_id: &str, username: &str) -> Result<Self, Error> {
48- let user_id = user_id.to_string();
49- let username = username.to_string();
50- validate_username(&username)?;
51-
52- Ok(Self { user_id, username })
53- }
54-
55- pub fn get_user_id(&self) -> &str {
56- &self.user_id
57- }
58-
59- pub fn get_username(&self) -> &str {
60- &self.username
61- }
62-}
63-
64-#[derive(Debug, Clone, Encode, Decode)]
65-pub struct DeleteUser {
66- user_id: String,
67-}
68-
69-impl DeleteUser {
70- pub fn new(user_id: &str) -> Self {
71- let user_id = user_id.to_string();
72-
73- Self { user_id }
74- }
75-
76- pub fn get_user_id(&self) -> &str {
77- &self.user_id
78- }
79-}
crates/common/src/request/user_community.rsdeleted+0 -113
@@ -1,113 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-#[derive(Debug, Clone, Encode, Decode)]
4-pub struct JoinCommunity {
5- user_id: String,
6- community_id: String,
7-}
8-
9-impl JoinCommunity {
10- pub fn new(user_id: &str, community_id: &str) -> Self {
11- let user_id = user_id.to_string();
12- let community_id = community_id.to_string();
13-
14- Self {
15- user_id,
16- community_id,
17- }
18- }
19-
20- pub fn get_user_id(&self) -> &str {
21- &self.user_id
22- }
23-
24- pub fn get_community_id(&self) -> &str {
25- &self.community_id
26- }
27-}
28-
29-#[derive(Debug, Clone, Encode, Decode)]
30-pub struct LeaveCommunity {
31- user_id: String,
32- community_id: String,
33-}
34-
35-impl LeaveCommunity {
36- pub fn new(user_id: &str, community_id: &str) -> Self {
37- let user_id = user_id.to_string();
38- let community_id = community_id.to_string();
39-
40- Self {
41- user_id,
42- community_id,
43- }
44- }
45-
46- pub fn get_user_id(&self) -> &str {
47- &self.user_id
48- }
49-
50- pub fn get_community_id(&self) -> &str {
51- &self.community_id
52- }
53-}
54-
55-#[derive(Debug, Clone, Encode, Decode)]
56-pub struct IsUserIn {
57- user_id: String,
58- community_id: String,
59-}
60-
61-impl IsUserIn {
62- pub fn new(user_id: &str, community_id: &str) -> Self {
63- let user_id = user_id.to_string();
64- let community_id = community_id.to_string();
65-
66- Self {
67- user_id,
68- community_id,
69- }
70- }
71-
72- pub fn get_user_id(&self) -> &str {
73- &self.user_id
74- }
75-
76- pub fn get_community_id(&self) -> &str {
77- &self.community_id
78- }
79-}
80-
81-#[derive(Debug, Clone, Encode, Decode)]
82-pub struct UsersIn {
83- community_id: String,
84-}
85-
86-impl UsersIn {
87- pub fn new(community_id: &str) -> Self {
88- let community_id = community_id.to_string();
89-
90- Self { community_id }
91- }
92-
93- pub fn get_community_id(&self) -> &str {
94- &self.community_id
95- }
96-}
97-
98-#[derive(Debug, Clone, Encode, Decode)]
99-pub struct CommunityOf {
100- user_id: String,
101-}
102-
103-impl CommunityOf {
104- pub fn new(user_id: &str) -> Self {
105- let user_id = user_id.to_string();
106-
107- Self { user_id }
108- }
109-
110- pub fn get_user_id(&self) -> &str {
111- &self.user_id
112- }
113-}
crates/common/src/response.rsmodified+6 -7
@@ -1,10 +1,9 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::{community::Community, error::Error, message::Message, user::User};3+use crate::{
4-4+ error::Error,
5-pub mod community;5+ model::{Community, Message, User},
6-pub mod message;6+};
7-pub mod user;
8 7
9 #[derive(Debug, Clone, Encode, Decode)]8 #[derive(Debug, Clone, Encode, Decode)]
10 pub enum Response {9 pub enum Response {
@@ -22,12 +21,12 @@ pub enum Response {
22 ReadMessage(Message),21 ReadMessage(Message),
23 UpdateMessage(Message),22 UpdateMessage(Message),
24 DeleteMessage(Message),23 DeleteMessage(Message),
25- ReadMessageByCommunityIDWithMarkerAndLimit(Vec<Message>),24+ ReadMessages(Vec<Message>),
26 JoinCommunity,25 JoinCommunity,
27 LeaveCommunity,26 LeaveCommunity,
28 IsUserIn(bool),27 IsUserIn(bool),
29 UsersIn(Vec<String>),28 UsersIn(Vec<String>),
30- CommunityOf(Vec<String>),29+ CommunitiesOf(Vec<String>),
31 SearchCommunity(Vec<Community>),30 SearchCommunity(Vec<Community>),
32 Error(Error),31 Error(Error),
33 }32 }
crates/common/src/response/community.rsdeleted+0 -0
crates/common/src/response/message.rsdeleted+0 -0
crates/common/src/response/user.rsdeleted+0 -0
crates/common/src/user.rsdeleted+0 -25
@@ -1,25 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-#[derive(Debug, Clone, Encode, Decode)]
4-pub struct User {
5- user_id: String,
6- username: String,
7-}
8-
9-impl User {
10- #[cfg(feature = "server")]
11- pub fn new(user_id: &str, username: &str) -> Self {
12- let user_id = user_id.to_string();
13- let username = username.to_string();
14-
15- Self { user_id, username }
16- }
17-
18- pub fn get_user_id(&self) -> &str {
19- &self.user_id
20- }
21-
22- pub fn get_username(&self) -> &str {
23- &self.username
24- }
25-}
crates/common/src/utils.rsdeleted+0 -57
@@ -1,57 +0,0 @@
1-use std::{
2- collections::{HashMap, VecDeque},
3- fs::File,
4- io::Read,
5- path::Path,
6-};
7-
8-use crate::error::{Error, file_operation};
9-
10-#[derive(Debug, Clone)]
11-pub struct TOML {
12- pub header: String,
13- pub fields: HashMap<String, String>,
14-}
15-
16-impl TOML {
17- pub fn naive_toml_parser_from_file(file_location: impl AsRef<Path>) -> Result<TOML, Error> {
18- let mut toml_file = File::open(file_location)
19- .map_err(|error_value| file_operation::Error::FileOpen(error_value.to_string()))?;
20- let mut toml_ingredients = String::default();
21- toml_file
22- .read_to_string(&mut toml_ingredients)
23- .map_err(|_| file_operation::Error::Read)?;
24-
25- Self::naive_toml_parser_from_content(&toml_ingredients)
26- }
27-
28- pub fn naive_toml_parser_from_content(toml_ingredients: &str) -> Result<TOML, Error> {
29- let mut toml_ingredients = toml_ingredients.lines().collect::<VecDeque<&str>>();
30-
31- let header = toml_ingredients
32- .pop_front()
33- .ok_or(file_operation::Error::Empty)?
34- .replace('[', "")
35- .replace(']', "")
36- .trim_end()
37- .to_string();
38-
39- let mut fields = HashMap::new();
40-
41- toml_ingredients
42- .iter()
43- .try_for_each(|ingredient| -> Result<(), Error> {
44- let key_and_value = ingredient
45- .split_once('=')
46- .ok_or(file_operation::Error::Split)?;
47-
48- let key = key_and_value.0.replace('"', "").trim().to_string();
49- let value = key_and_value.1.replace('"', "").trim().to_string();
50-
51- fields.insert(key, value);
52- Ok(())
53- })?;
54-
55- Ok(TOML { header, fields })
56- }
57-}
crates/common/src/validate.rsmodified+49 -37
@@ -1,52 +1,64 @@
1-use crate::constant::{1+use crate::{
2- MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_USERNAME_LENGTH,2+ constant::{
3- MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_USERNAME_LENGTH,3+ MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_USERNAME_LENGTH,
4+ MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_USERNAME_LENGTH,
5+ },
6+ error::{Error, InvalidInput},
4 };7 };
5 8
6-type UserError = crate::error::user::Error;9+fn check(
7-type MessageError = crate::error::message::Error;10+ input: &str,
8-type CommunityError = crate::error::community::Error;11+ minimum: usize,
9-12+ maximum: usize,
10-pub fn validate_username(username: &str) -> Result<(), UserError> {13+ ascii_only: bool,
11- if !username.is_ascii() {14+) -> Result<(), InvalidInput> {
12- return Err(UserError::ASCII);15+ if ascii_only && !input.is_ascii() {
16+ return Err(InvalidInput::NotASCII);
13 }17 }
14 18
15- if username.len() < MINIMUM_USERNAME_LENGTH {19+ if input.len() < minimum {
16- return Err(UserError::MinimumLength(username.len()));20+ return Err(InvalidInput::TooShort {
21+ minimum,
22+ actual: input.len(),
23+ });
17 }24 }
18 25
19- if username.len() > MAXIMUM_USERNAME_LENGTH {26+ if input.len() > maximum {
20- return Err(UserError::MaximumLength(username.len()));27+ return Err(InvalidInput::TooLong {
28+ maximum,
29+ actual: input.len(),
30+ });
21 }31 }
22 32
23 Ok(())33 Ok(())
24 }34 }
25 35
26-pub fn validate_message_body(message: &str) -> Result<(), MessageError> {36+pub fn validate_username(username: &str) -> Result<(), Error> {
27- if message.len() < MINIMUM_MESSAGE_LENGTH {37+ check(
28- return Err(MessageError::MinimumLength(message.len()));38+ username,
29- }39+ MINIMUM_USERNAME_LENGTH,
30-40+ MAXIMUM_USERNAME_LENGTH,
31- if message.len() > MAXIMUM_MESSAGE_LENGTH {41+ true,
32- return Err(MessageError::MaximumLength(message.len()));42+ )
33- }43+ .map_err(Error::User)
34-
35- Ok(())
36 }44 }
37 45
38-pub fn validate_community_name(community_name: &str) -> Result<(), CommunityError> {46+pub fn validate_community_name(name: &str) -> Result<(), Error> {
39- if !community_name.is_ascii() {47+ check(
40- return Err(CommunityError::ASCII);48+ name,
41- }49+ MINIMUM_COMMUNITY_NAME_LENGTH,
42-50+ MAXIMUM_COMMUNITY_NAME_LENGTH,
43- if community_name.len() < MINIMUM_COMMUNITY_NAME_LENGTH {51+ true,
44- return Err(CommunityError::MinimumLength(community_name.len()));52+ )
45- }53+ .map_err(Error::Community)
46-54+}
47- if community_name.len() > MAXIMUM_COMMUNITY_NAME_LENGTH {
48- return Err(CommunityError::MaximumLength(community_name.len()));
49- }
50 55
51- Ok(())56+pub fn validate_message_body(body: &str) -> Result<(), Error> {
57+ check(
58+ body,
59+ MINIMUM_MESSAGE_LENGTH,
60+ MAXIMUM_MESSAGE_LENGTH,
61+ false,
62+ )
63+ .map_err(Error::Message)
52 }64 }
crates/server/Cargo.tomlmodified+5 -11
@@ -7,21 +7,15 @@ edition = "2024"
7 default = ["rcgen"]7 default = ["rcgen"]
8 rcgen = ["dep:rcgen"]8 rcgen = ["dep:rcgen"]
9 9
10-[dev-dependencies]
11-tempfile = "3.27.0"
12-
13 [dependencies]10 [dependencies]
14-common = { workspace = true, features = ["server"] }11+common.workspace = true
15 rcgen = { version = "0.14.10", optional = true }12 rcgen = { version = "0.14.10", optional = true }
16 tokio.workspace = true13 tokio.workspace = true
17-tokio-stream = { version = "0.1.19", features = ["sync"] }
18 quinn = { workspace = true, features = ["rustls-aws-lc-rs"] }14 quinn = { workspace = true, features = ["rustls-aws-lc-rs"] }
19 bitcode.workspace = true15 bitcode.workspace = true
20 rustls.workspace = true16 rustls.workspace = true
21-17+turso = "0.9.0-pre.6"
22-surrealdb = { version = "3.3.0", default-features = false, features = [
23- "protocol-ws",
24- "rustls",
25- "kv-surrealkv",
26-] }
27 ulid = "3.0.0"18 ulid = "3.0.0"
19+
20+[lints]
21+workspace = true
crates/server/src/authentication.rsmodified+6 -28
@@ -1,33 +1,11 @@
1-use crate::{database_::DB, error::Error, user::User};1+use common::{error::Error as CommonError, model::User};
2 2
3-pub(crate) async fn authenticate(3+use crate::{database::DB, error::Error, user};
4- authentication_token: &str,
5- database_connection: &DB,
6-) -> Result<User, Error> {
7- println!("{}", authentication_token);
8 4
9- //todo5+pub async fn authenticate(token: &str, db: &DB) -> Result<User, Error> {
10- //Err(Error::Common(common::error::Error::Authenticate))6+ user::read_by_username(token, db)
11- let users = User::read_by_username(authentication_token, database_connection).await?;7+ .await?
12- let user = users
13 .into_iter()8 .into_iter()
14 .next()9 .next()
15- .ok_or(Error::Common(common::error::Error::Authenticate))?;10+ .ok_or(Error::Common(CommonError::Authenticate))
16- Ok(user)
17-}
18-
19-pub(crate) async fn deauthenticate(
20- authentication_token: &str,
21- database_connection: &DB,
22-) -> Result<User, Error> {
23- println!("{}", authentication_token);
24-
25- //todo
26- //Err(Error::Common(common::error::Error::Authenticate))
27- let users = User::read_by_username(authentication_token, database_connection).await?;
28- let user = users
29- .into_iter()
30- .next()
31- .ok_or(Error::Common(common::error::Error::Authenticate))?;
32- Ok(user)
33 }11 }
crates/server/src/community.rsmodified+84 -213
@@ -1,282 +1,153 @@
1-use std::sync::LazyLock;1+use common::{model::Community, validate::validate_community_name};
2-2+use turso::Row;
3-use common::validate::validate_community_name;
4-use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
5-use tokio::sync::Mutex;
6-use ulid::Generator;
7 3
8 use crate::{4 use crate::{
9- database_::{COMMUNITY_TABLE, DB},5+ database::{DB, new_id},
10 error::Error,6 error::Error,
11 };7 };
12 8
13-mod database;9+fn from_row(row: &Row) -> Result<Community, Error> {
14-10+ Ok(Community {
15-static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Generator::new().into());11+ id: row.get(0)?,
16-12+ name: row.get(1)?,
17-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)]13+ })
18-pub struct CommunityID(RecordId);
19-
20-impl CommunityID {
21- async fn new() -> Self {
22- loop {
23- match ULID.lock().await.generate() {
24- Ok(ulid) => return Self(RecordId::new(COMMUNITY_TABLE, ulid.to_string())),
25- Err(_) => continue,
26- }
27- }
28- }
29-
30- pub(crate) fn as_record_id(&self) -> RecordId {
31- self.0.clone()
32- }
33-
34- pub(crate) fn as_str(&self) -> &str {
35- match &self.0.key {
36- RecordIdKey::String(user_id) => user_id,
37- _ => unreachable!("We shouldn't be here"),
38- }
39- }
40 }14 }
41 15
42-impl ToOwned for CommunityID {16+pub async fn create(name: &str, db: &DB) -> Result<Community, Error> {
43- type Owned = CommunityID;17+ validate_community_name(name)?;
44 18
45- fn to_owned(&self) -> Self::Owned {19+ let mut rows = db
46- Self(self.0.clone())20+ .query(
47- }21+ "INSERT INTO community (id, name) VALUES (?1, ?2) RETURNING id, name",
48-}22+ (new_id(), name),
23+ )
24+ .await?;
25+ let row = rows.next().await?.ok_or(Error::NotFound)?;
49 26
50-impl From<&str> for CommunityID {27+ from_row(&row)
51- fn from(value: &str) -> Self {
52- Self(RecordId::new(COMMUNITY_TABLE, value))
53- }
54 }28 }
55 29
56-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)]30+pub async fn read(community_id: &str, db: &DB) -> Result<Community, Error> {
57-pub struct CommunityName(String);31+ let mut rows = db
58-32+ .query(
59-impl CommunityName {33+ "SELECT id, name FROM community WHERE id = ?1",
60- pub fn try_new(community_name: &str) -> Result<Self, Error> {34+ (community_id,),
61- let community_name = community_name.to_string();35+ )
62- validate_community_name(&community_name)?;36+ .await?;
63-37+ let row = rows.next().await?.ok_or(Error::NotFound)?;
64- Ok(Self(community_name))
65- }
66 38
67- pub fn as_str(&self) -> &str {39+ from_row(&row)
68- &self.0
69- }
70 }40 }
71 41
72-impl ToOwned for CommunityName {42+pub async fn read_by_name(name: &str, db: &DB) -> Result<Vec<Community>, Error> {
73- type Owned = CommunityName;43+ let mut rows = db
44+ .query(
45+ "SELECT id, name FROM community WHERE name = ?1 ORDER BY id",
46+ (name,),
47+ )
48+ .await?;
74 49
75- fn to_owned(&self) -> Self::Owned {50+ let mut communities = Vec::new();
76- Self(self.0.clone())51+ while let Some(row) = rows.next().await? {
52+ communities.push(from_row(&row)?);
77 }53 }
78-}
79 54
80-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)]55+ Ok(communities)
81-pub struct Community {
82- id: CommunityID,
83- community_name: CommunityName,
84 }56 }
85 57
86-impl Community {58+pub async fn update(community_id: &str, name: &str, db: &DB) -> Result<Community, Error> {
87- async fn new(community_name: &str) -> Result<Self, Error> {59+ validate_community_name(name)?;
88- let community_name = CommunityName::try_new(community_name)?;
89-
90- let id = CommunityID::new().await;
91-
92- Ok(Self { id, community_name })
93- }
94-
95- pub fn get_id(&self) -> &CommunityID {
96- &self.id
97- }
98-
99- pub fn get_community_name(&self) -> &CommunityName {
100- &self.community_name
101- }
102-
103- fn update_name(mut self, community_name: &str) -> Result<Community, Error> {
104- self.community_name = CommunityName::try_new(community_name)?;
105-
106- Ok(self)
107- }
108-
109- pub async fn create(name: &str, database_connection: &DB) -> Result<Community, Error> {
110- let community = Self::new(name).await?;
111-
112- database::create(community, database_connection).await
113- }
114-
115- pub async fn read(id: &CommunityID, database_connection: &DB) -> Result<Community, Error> {
116- database::read(id, database_connection).await
117- }
118 60
119- pub async fn read_by_name(61+ let mut rows = db
120- name: &str,62+ .query(
121- database_connection: &DB,63+ "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name",
122- ) -> Result<Vec<Community>, Error> {64+ (community_id, name),
123- database::read_by_name(name, database_connection).await65+ )
124- }66+ .await?;
125-67+ let row = rows.next().await?.ok_or(Error::NotFound)?;
126- pub async fn read_all(database_connection: &DB) -> Result<Vec<Community>, Error> {
127- database::read_all(database_connection).await
128- }
129-
130- pub async fn update(self, name: &str, database_connection: &DB) -> Result<Community, Error> {
131- let user = self.update_name(name)?;
132- database::update(user, database_connection).await
133- }
134 68
135- pub async fn delete(self, database_connection: &DB) -> Result<Community, Error> {69+ from_row(&row)
136- database::delete(self.id, database_connection).await
137- }
138 }70 }
139 71
140-impl Into<common::community::Community> for Community {72+pub async fn delete(community_id: &str, db: &DB) -> Result<Community, Error> {
141- fn into(self) -> common::community::Community {73+ let mut rows = db
142- common::community::Community::new(74+ .query(
143- self.get_id().as_str(),75+ "DELETE FROM community WHERE id = ?1 RETURNING id, name",
144- self.get_community_name().as_str(),76+ (community_id,),
145 )77 )
146- }78+ .await?;
79+ let row = rows.next().await?.ok_or(Error::NotFound)?;
80+
81+ from_row(&row)
147 }82 }
148 83
149 #[cfg(test)]84 #[cfg(test)]
150 mod tests {85 mod tests {
151- use crate::{86+ use crate::{community, error::Error, test};
152- community::Community,
153- error::{Error, database},
154- test,
155- };
156 87
157 #[tokio::test]88 #[tokio::test]
158 async fn create() {89 async fn create() {
159- let (database_connection, _temp_directory) = test::get_database().await;90+ let db = test::get_database().await;
160 91
161- let name = "Tahinli";92+ let community = community::create("Tahinli", &db).await.unwrap();
162- let community = Community::create(name, &database_connection).await;
163 93
164- assert_eq!(name, community.unwrap().get_community_name().as_str());94+ assert_eq!("Tahinli", community.name);
165 }95 }
166 96
167 #[tokio::test]97 #[tokio::test]
168 async fn read() {98 async fn read() {
169- let (database_connection, _temp_directory) = test::get_database().await;99+ let db = test::get_database().await;
170 100
171- let name = "Tahinli";101+ let created_community = community::create("Tahinli", &db).await.unwrap();
172- let created_community = Community::create(name, &database_connection).await.unwrap();102+ let searched_community = community::read(&created_community.id, &db).await.unwrap();
173-
174- let searched_community = Community::read(&created_community.get_id(), &database_connection)
175- .await
176- .unwrap();
177 103
178 assert_eq!(created_community, searched_community);104 assert_eq!(created_community, searched_community);
179 }105 }
180 106
181 #[tokio::test]107 #[tokio::test]
182 async fn read_by_name() {108 async fn read_by_name() {
183- let (database_connection, _temp_directory) = test::get_database().await;109+ let db = test::get_database().await;
184-
185- let name = "Tahinli";
186- let community_1 = Community::create(name, &database_connection).await.unwrap();
187- let community_2 = Community::create(name, &database_connection).await.unwrap();
188- let _community_3 = Community::create("Not Tahinli", &database_connection)
189- .await
190- .unwrap();
191-
192- let expected_result = vec![community_1, community_2];
193-
194- let searched_communitys = Community::read_by_name(name, &database_connection)
195- .await
196- .unwrap();
197-
198- assert_eq!(expected_result, searched_communitys);
199- }
200-
201- #[tokio::test]
202- async fn read_all() {
203- let (database_connection, _temp_directory) = test::get_database().await;
204-
205- let name = "Tahinli";
206- let community_1 = Community::create(name, &database_connection).await.unwrap();
207- let community_2 = Community::create(name, &database_connection).await.unwrap();
208- let community_3 = Community::create("Not Tahinli", &database_connection)
209- .await
210- .unwrap();
211 110
212- let expected_result = vec![community_1, community_2, community_3];111+ let community_1 = community::create("Tahinli", &db).await.unwrap();
112+ let community_2 = community::create("Tahinli", &db).await.unwrap();
113+ let _community_3 = community::create("Not Tahinli", &db).await.unwrap();
213 114
214- let searched_communitys = Community::read_all(&database_connection).await.unwrap();115+ let searched_communities = community::read_by_name("Tahinli", &db).await.unwrap();
215 116
216- assert_eq!(expected_result, searched_communitys);117+ assert_eq!(vec![community_1, community_2], searched_communities);
217 }118 }
218 119
219 #[tokio::test]120 #[tokio::test]
220 async fn update() {121 async fn update() {
221- let (database_connection, _temp_directory) = test::get_database().await;122+ let db = test::get_database().await;
222 123
223- let name = "Tahinli";124+ let created_community = community::create("Tahinli", &db).await.unwrap();
224- let created_community = Community::create(name, &database_connection).await.unwrap();125+ let updated_community = community::update(&created_community.id, "Not Tahinli", &db)
225- let created_id = created_community.get_id().to_owned();
226- let created_community_name = created_community.get_community_name().to_owned();
227-
228- let updated_community = created_community
229- .update("Not Tahinli", &database_connection)
230- .await
231- .unwrap();
232-
233- let searched_community = Community::read(updated_community.get_id(), &database_connection)
234 .await126 .await
235 .unwrap();127 .unwrap();
128+ let searched_community = community::read(&created_community.id, &db).await.unwrap();
236 129
237- assert_eq!(&created_id, searched_community.get_id());130+ assert_eq!(created_community.id, searched_community.id);
238- assert_ne!(
239- &created_community_name,
240- searched_community.get_community_name()
241- );
242 assert_eq!(updated_community, searched_community);131 assert_eq!(updated_community, searched_community);
132+ assert_eq!("Not Tahinli", searched_community.name);
243 }133 }
244 134
245 #[tokio::test]135 #[tokio::test]
246- async fn update_on_unpersistent_community() {136+ async fn update_on_missing_community() {
247- let (database_connection, _temp_directory) = test::get_database().await;137+ let db = test::get_database().await;
248 138
249- let name = "Tahinli";139+ let updated_community = community::update("missing", "Not Tahinli", &db).await;
250- let unpersistent_community = Community::new(name).await.unwrap();
251 140
252- let updated_community = unpersistent_community141+ assert!(matches!(updated_community, Err(Error::NotFound)));
253- .update("Not Tahinli", &database_connection)
254- .await;
255-
256- assert!(matches!(
257- updated_community,
258- Err(Error::Database(database::Error::Update)),
259- ));
260 }142 }
261 143
262 #[tokio::test]144 #[tokio::test]
263 async fn delete() {145 async fn delete() {
264- let (database_connection, _temp_directory) = test::get_database().await;146+ let db = test::get_database().await;
265-
266- let name = "Tahinli";
267- let created_community = Community::create(name, &database_connection).await.unwrap();
268- let created_id = created_community.get_id().to_owned();
269- let created_community_name = created_community.get_community_name().to_owned();
270 147
271- let deleted_community = created_community148+ let created_community = community::create("Tahinli", &db).await.unwrap();
272- .delete(&database_connection)149+ let deleted_community = community::delete(&created_community.id, &db).await.unwrap();
273- .await
274- .unwrap();
275 150
276- assert_eq!(&created_id, deleted_community.get_id());151+ assert_eq!(created_community, deleted_community);
277- assert_eq!(
278- &created_community_name,
279- deleted_community.get_community_name()
280- );
281 }152 }
282 }153 }
crates/server/src/community/database.rsdeleted+0 -67
@@ -1,67 +0,0 @@
1-use crate::{
2- community::{Community, CommunityID},
3- database_::{COMMUNITY_TABLE, DB},
4- error::{self, Error},
5-};
6-
7-pub(super) async fn create(
8- community: Community,
9- database_connection: &DB,
10-) -> Result<Community, Error> {
11- let result = database_connection
12- .create(community.get_id().as_record_id())
13- .content(community)
14- .await?;
15-
16- result.ok_or_else(|| error::database::Error::Create.into())
17-}
18-
19-pub(super) async fn read(id: &CommunityID, database_connection: &DB) -> Result<Community, Error> {
20- let result = database_connection.select(id.as_record_id()).await?;
21-
22- result.ok_or_else(|| error::database::Error::Read.into())
23-}
24-
25-pub(super) async fn read_by_name(
26- name: &str,
27- database_connection: &DB,
28-) -> Result<Vec<Community>, Error> {
29- let mut result = database_connection
30- .query(
31- "
32- SELECT * FROM type::table($table) WHERE community_name = $community_name;
33- ",
34- )
35- .bind(("table", COMMUNITY_TABLE))
36- .bind(("community_name", name.to_string()))
37- .await?
38- .check()?;
39-
40- let result = result.take::<Vec<Community>>(0)?;
41-
42- Ok(result)
43-}
44-
45-pub(super) async fn read_all(database_connection: &DB) -> Result<Vec<Community>, Error> {
46- let result = database_connection.select(COMMUNITY_TABLE).await?;
47-
48- Ok(result)
49-}
50-
51-pub(super) async fn update(
52- community: Community,
53- database_connection: &DB,
54-) -> Result<Community, Error> {
55- let result = database_connection
56- .update(community.get_id().as_record_id())
57- .content(community)
58- .await?;
59-
60- result.ok_or_else(|| error::database::Error::Update.into())
61-}
62-
63-pub(super) async fn delete(id: CommunityID, database_connection: &DB) -> Result<Community, Error> {
64- let result = database_connection.delete(id.as_record_id()).await?;
65-
66- result.ok_or_else(|| error::database::Error::Delete.into())
67-}
crates/server/src/database.rsadded+57 -0
@@ -0,0 +1,57 @@
1+use std::sync::{LazyLock, Mutex};
2+
3+use ulid::Generator;
4+
5+use crate::error::Error;
6+
7+pub type DB = turso::Connection;
8+
9+static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
10+
11+pub async fn connect(path: &str) -> Result<DB, Error> {
12+ let database = turso::Builder::new_local(path).build().await?;
13+
14+ Ok(database.connect()?)
15+}
16+
17+pub async fn migrate(db: &DB) -> Result<(), Error> {
18+ db.execute_batch(
19+ "
20+ CREATE TABLE IF NOT EXISTS user (
21+ id TEXT PRIMARY KEY,
22+ username TEXT NOT NULL
23+ );
24+
25+ CREATE TABLE IF NOT EXISTS community (
26+ id TEXT PRIMARY KEY,
27+ name TEXT NOT NULL
28+ );
29+
30+ CREATE TABLE IF NOT EXISTS message (
31+ id TEXT PRIMARY KEY,
32+ user_id TEXT NOT NULL,
33+ community_id TEXT NOT NULL,
34+ body TEXT NOT NULL
35+ );
36+ CREATE INDEX IF NOT EXISTS message_community_id ON message (community_id);
37+
38+ CREATE TABLE IF NOT EXISTS user_community (
39+ user_id TEXT NOT NULL,
40+ community_id TEXT NOT NULL,
41+ PRIMARY KEY (user_id, community_id)
42+ );
43+ ",
44+ )
45+ .await?;
46+
47+ Ok(())
48+}
49+
50+pub fn new_id() -> String {
51+ loop {
52+ match ULID.lock().unwrap().generate() {
53+ Ok(ulid) => return ulid.to_string(),
54+ Err(_) => continue,
55+ }
56+ }
57+}
crates/server/src/database_.rsdeleted+0 -81
@@ -1,81 +0,0 @@
1-use surrealdb::{
2- Surreal,
3- engine::any::{self, Any},
4- opt::auth::Root,
5-};
6-
7-use crate::{ServerConfig, error::Error};
8-
9-pub type DB = Surreal<Any>;
10-
11-pub const USER_TABLE: &str = "user";
12-pub const COMMUNITY_TABLE: &str = "community";
13-pub const MESSAGE_TABLE: &str = "message";
14-pub const USER_COMMUNITY_TABLE: &str = "user_community";
15-
16-pub async fn connect(server_config: &ServerConfig) -> Result<DB, Error> {
17- let address = format!(
18- "{}://{}",
19- server_config.database_prefix, server_config.database_address
20- );
21- let database_connection = any::connect(address).await?;
22-
23- database_connection
24- .use_ns(server_config.namespace.clone())
25- .use_db(server_config.database.clone())
26- .await?;
27-
28- if !server_config.username.is_empty() && !server_config.password.is_empty() {
29- database_connection
30- .signin(Root {
31- username: server_config.username.clone(),
32- password: server_config.password.clone(),
33- })
34- .await?;
35- }
36-
37- Ok(database_connection)
38-}
39-
40-pub async fn migrate(database_connection: &DB) -> Result<(), Error> {
41- database_connection
42- .query(format!(
43- "
44- DEFINE TABLE IF NOT EXISTS {USER_TABLE} SCHEMAFULL;
45- DEFINE FIELD IF NOT EXISTS username ON {USER_TABLE} TYPE string;
46-
47- DEFINE TABLE IF NOT EXISTS {COMMUNITY_TABLE} SCHEMAFULL;
48- DEFINE FIELD IF NOT EXISTS community_name ON {COMMUNITY_TABLE} TYPE string;
49-
50- DEFINE TABLE IF NOT EXISTS {MESSAGE_TABLE} SCHEMAFULL;
51- DEFINE FIELD IF NOT EXISTS community_id ON {MESSAGE_TABLE} TYPE record<{COMMUNITY_TABLE}>;
52- DEFINE FIELD IF NOT EXISTS user_id ON {MESSAGE_TABLE} TYPE record<{USER_TABLE}>;
53- DEFINE FIELD IF NOT EXISTS message_body ON {MESSAGE_TABLE} TYPE string;
54- DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_community_id ON {MESSAGE_TABLE} FIELDS community_id;
55- DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_user_id ON {MESSAGE_TABLE} FIELDS user_id;
56-
57- DEFINE TABLE IF NOT EXISTS {USER_COMMUNITY_TABLE} TYPE RELATION FROM {USER_TABLE} TO {COMMUNITY_TABLE} ENFORCED SCHEMAFULL;
58- DEFINE INDEX IF NOT EXISTS {USER_COMMUNITY_TABLE}_unique ON {USER_COMMUNITY_TABLE} FIELDS in, out UNIQUE
59- "
60- ))
61- .await?
62- .check()?;
63-
64- Ok(())
65-}
66-
67-pub async fn health(database_connection: &DB) -> Result<(), Error> {
68- Ok(database_connection.health().await?)
69-}
70-
71-// pub fn user_record_id(key: impl Into<RecordIdKey>) -> RecordId {
72-// RecordId::new(USER_TABLE, key)
73-// }
74-
75-// pub fn community_record_id(key: impl Into<RecordIdKey>) -> RecordId {
76-// RecordId::new(COMMUNITY_TABLE, key)
77-// }
78-
79-// pub fn message_record_id(key: impl Into<RecordIdKey>) -> RecordId {
80-// RecordId::new(MESSAGE_TABLE, key)
81-// }
crates/server/src/error.rsmodified+20 -26
@@ -2,12 +2,11 @@ use std::fmt::Display;
2 2
3 use common::error_from;3 use common::error_from;
4 4
5-pub mod database;
6-
7 #[derive(Debug)]5 #[derive(Debug)]
8 pub enum Error {6 pub enum Error {
9 Common(common::error::Error),7 Common(common::error::Error),
10- Database(database::Error),8+ Database(turso::Error),
9+ NotFound,
11 }10 }
12 11
13 impl std::error::Error for Error {}12 impl std::error::Error for Error {}
@@ -15,8 +14,9 @@ impl std::error::Error for Error {}
15 impl Display for Error {14 impl Display for Error {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {15 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 match self {16 match self {
18- Error::Common(error_value) => error_value.fmt(f),17+ Error::Common(error) => write!(f, "{error}"),
19- Error::Database(error_value) => error_value.fmt(f),18+ Error::Database(error) => write!(f, "Database: {error}"),
19+ Error::NotFound => write!(f, "Not found"),
20 }20 }
21 }21 }
22 }22 }
@@ -24,9 +24,9 @@ impl Display for Error {
24 impl From<Error> for common::error::Error {24 impl From<Error> for common::error::Error {
25 fn from(value: Error) -> Self {25 fn from(value: Error) -> Self {
26 match value {26 match value {
27- Error::Common(error_value) => error_value,27+ Error::Common(error) => error,
28- Error::Database(error_value) => {28+ error => {
29- eprintln!("Error: Database | {}", error_value);29+ eprintln!("Error: {error}");
30 30
31 common::error::Error::Server31 common::error::Error::Server
32 }32 }
@@ -36,22 +36,16 @@ impl From<Error> for common::error::Error {
36 36
37 error_from! { Error {37 error_from! { Error {
38 common::error::Error => Error::Common,38 common::error::Error => Error::Common,
39- database::Error => Error::Database,39+ turso::Error => Error::Database,
40-40+
41- common::error::user::Error => Error::Common as common::error::Error,41+ std::net::AddrParseError => Error::Common as common::error::Error,
42- common::error::community::Error => Error::Common as common::error::Error,42+ std::io::Error => Error::Common as common::error::Error,
43- common::error::message::Error => Error::Common as common::error::Error,43+ quinn::ConnectionError => Error::Common as common::error::Error,
44-44+ quinn::ConnectError => Error::Common as common::error::Error,
45- surrealdb::Error => Error::Database as database::Error,45+ quinn::ReadError => Error::Common as common::error::Error,
46-46+ quinn::ReadToEndError => Error::Common as common::error::Error,
47- std::net::AddrParseError => Error::Common as common::error::network::Error,47+ quinn::ReadExactError => Error::Common as common::error::Error,
48- std::io::Error => Error::Common as common::error::network::Error,48+ quinn::WriteError => Error::Common as common::error::Error,
49- quinn::ConnectionError => Error::Common as common::error::network::Error,49+ quinn::ClosedStream => Error::Common as common::error::Error,
50- quinn::ConnectError => Error::Common as common::error::network::Error,50+ bitcode::Error => Error::Common as common::error::Error,
51- quinn::ReadError => Error::Common as common::error::network::Error,
52- quinn::ReadToEndError => Error::Common as common::error::network::Error,
53- quinn::ReadExactError => Error::Common as common::error::network::Error,
54- quinn::WriteError => Error::Common as common::error::network::Error,
55- quinn::ClosedStream => Error::Common as common::error::network::Error,
56- bitcode::Error => Error::Common as common::error::decode::Error,
57 } }51 } }
crates/server/src/error/database.rsdeleted+0 -30
@@ -1,30 +0,0 @@
1-use std::fmt::Display;
2-
3-use common::error_from;
4-
5-#[derive(Debug)]
6-pub enum Error {
7- Inner(surrealdb::Error),
8- Create,
9- Read,
10- Update,
11- Delete,
12-}
13-
14-impl std::error::Error for Error {}
15-
16-impl Display for Error {
17- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18- match self {
19- Error::Inner(error) => write!(f, "{}", error),
20- Error::Create => write!(f, "Creating a record failed"),
21- Error::Read => write!(f, "Reading a record failed"),
22- Error::Update => write!(f, "Updating a record failed"),
23- Error::Delete => write!(f, "Deleting a record failed"),
24- }
25- }
26-}
27-
28-error_from! { Error {
29- surrealdb::Error => Error::Inner,
30-} }
crates/server/src/lib.rsmodified+13 -25
@@ -1,11 +1,7 @@
1-use common::utils::TOML;
2-
3-use crate::network::serve;
4-
5 pub mod authentication;1 pub mod authentication;
6 pub mod community;2 pub mod community;
7-pub(crate) mod database_;3+pub mod database;
8-pub(crate) mod error;4+pub mod error;
9 pub mod message;5 pub mod message;
10 pub mod network;6 pub mod network;
11 pub mod request;7 pub mod request;
@@ -21,27 +17,18 @@ const SERVER_CONFIG_FILE_PATH: &str = concat!(
21 );17 );
22 18
23 pub struct ServerConfig {19 pub struct ServerConfig {
24- database_prefix: String,20+ pub database_path: String,
25- database_address: String,21+ pub server_address: String,
26- namespace: String,
27- database: String,
28- username: String,
29- password: String,
30- server_address: String,
31 }22 }
32 23
33 impl Default for ServerConfig {24 impl Default for ServerConfig {
34 fn default() -> Self {25 fn default() -> Self {
35- let mut toml = TOML::naive_toml_parser_from_file(SERVER_CONFIG_FILE_PATH).unwrap();26+ let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH).unwrap();
27+ let mut fields = common::config::parse(&content).unwrap();
36 28
37 Self {29 Self {
38- database_prefix: toml.fields.remove("database_prefix").unwrap(),30+ database_path: fields.remove("database_path").unwrap(),
39- database_address: toml.fields.remove("database_address").unwrap(),31+ server_address: fields.remove("server_address").unwrap(),
40- namespace: toml.fields.remove("namespace").unwrap(),
41- database: toml.fields.remove("database").unwrap(),
42- username: toml.fields.remove("username").unwrap(),
43- password: toml.fields.remove("password").unwrap(),
44- server_address: toml.fields.remove("server_address").unwrap(),
45 }32 }
46 }33 }
47 }34 }
@@ -52,11 +39,12 @@ pub async fn showtime() {
52 .unwrap();39 .unwrap();
53 let server_config = ServerConfig::default();40 let server_config = ServerConfig::default();
54 41
55- let database_connection = database_::connect(&server_config).await.unwrap();42+ let database = database::connect(&server_config.database_path)
56- database_::migrate(&database_connection).await.unwrap();43+ .await
57- database_::health(&database_connection).await.unwrap();44+ .unwrap();
45+ database::migrate(&database).await.unwrap();
58 46
59- serve(&server_config.server_address, &database_connection)47+ network::serve(&server_config.server_address, &database)
60 .await48 .await
61 .unwrap();49 .unwrap();
62 }50 }
crates/server/src/main.rsmodified+0 -2
@@ -2,7 +2,5 @@ use server::showtime;
2 2
3 #[tokio::main]3 #[tokio::main]
4 async fn main() {4 async fn main() {
5- println!("Hello, world!");
6-
7 showtime().await;5 showtime().await;
8 }6 }
crates/server/src/message.rsmodified+118 -410
@@ -1,501 +1,209 @@
1-use std::sync::LazyLock;1+use common::{model::Message, validate::validate_message_body};
2-2+use turso::Row;
3-use common::validate::validate_message_body;
4-use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
5-use tokio::sync::Mutex;
6-use ulid::Generator;
7 3
8 use crate::{4 use crate::{
9- community::{Community, CommunityID},5+ database::{DB, new_id},
10- database_::{DB, MESSAGE_TABLE},
11 error::Error,6 error::Error,
12- user::{User, UserID},
13 };7 };
14 8
15-mod database;9+fn from_row(row: &Row) -> Result<Message, Error> {
16-10+ Ok(Message {
17-static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Generator::new().into());11+ id: row.get(0)?,
18-12+ user_id: row.get(1)?,
19-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)]13+ community_id: row.get(2)?,
20-pub struct MessageID(RecordId);14+ body: row.get(3)?,
21-15+ })
22-impl MessageID {
23- async fn new() -> Self {
24- loop {
25- match ULID.lock().await.generate() {
26- Ok(ulid) => return Self(RecordId::new(MESSAGE_TABLE, ulid.to_string())),
27- Err(_) => continue,
28- }
29- }
30- }
31-
32- pub(crate) fn as_record_id(&self) -> RecordId {
33- self.0.clone()
34- }
35-
36- pub fn as_str(&self) -> &str {
37- match &self.0.key {
38- RecordIdKey::String(user_id) => user_id,
39- _ => unreachable!("We shouldn't be here"),
40- }
41- }
42 }16 }
43 17
44-impl ToOwned for MessageID {18+pub async fn create(
45- type Owned = MessageID;19+ user_id: &str,
46-20+ community_id: &str,
47- fn to_owned(&self) -> Self::Owned {21+ body: &str,
48- Self(self.0.clone())22+ db: &DB,
49- }23+) -> Result<Message, Error> {
50-}24+ validate_message_body(body)?;
25+
26+ let mut rows = db
27+ .query(
28+ "INSERT INTO message (id, user_id, community_id, body) VALUES (?1, ?2, ?3, ?4) RETURNING id, user_id, community_id, body",
29+ (new_id(), user_id, community_id, body),
30+ )
31+ .await?;
32+ let row = rows.next().await?.ok_or(Error::NotFound)?;
51 33
52-impl From<&str> for MessageID {34+ from_row(&row)
53- fn from(value: &str) -> Self {
54- Self(RecordId::new(MESSAGE_TABLE, value))
55- }
56 }35 }
57 36
58-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)]37+pub async fn read(message_id: &str, db: &DB) -> Result<Message, Error> {
59-pub struct MessageBody(String);38+ let mut rows = db
60-39+ .query(
61-impl MessageBody {40+ "SELECT id, user_id, community_id, body FROM message WHERE id = ?1",
62- pub fn try_new(message_body: &str) -> Result<Self, Error> {41+ (message_id,),
63- let message_body = message_body.to_string();42+ )
64- validate_message_body(&message_body)?;43+ .await?;
65-44+ let row = rows.next().await?.ok_or(Error::NotFound)?;
66- Ok(Self(message_body))
67- }
68 45
69- pub(crate) fn as_str(&self) -> &str {46+ from_row(&row)
70- &self.0
71- }
72 }47 }
73 48
74-impl ToOwned for MessageBody {49+pub async fn read_page(
75- type Owned = MessageBody;50+ community_id: &str,
51+ marker: &str,
52+ limit: usize,
53+ db: &DB,
54+) -> Result<Vec<Message>, Error> {
55+ let mut rows = db
56+ .query(
57+ "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND id <= ?2 ORDER BY id DESC LIMIT ?3",
58+ (community_id, marker, limit as i64),
59+ )
60+ .await?;
76 61
77- fn to_owned(&self) -> Self::Owned {62+ let mut messages = Vec::new();
78- Self(self.0.clone())63+ while let Some(row) = rows.next().await? {
64+ messages.push(from_row(&row)?);
79 }65 }
80-}66+ messages.reverse();
81 67
82-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord)]68+ Ok(messages)
83-pub struct Message {
84- id: MessageID,
85- user_id: UserID,
86- community_id: CommunityID,
87- message_body: MessageBody,
88 }69 }
89 70
90-impl Message {71+pub async fn update(message_id: &str, body: &str, db: &DB) -> Result<Message, Error> {
91- async fn new(user: &User, community: &Community, message_body: &str) -> Result<Self, Error> {72+ validate_message_body(body)?;
92- let message_body = MessageBody::try_new(message_body)?;
93-
94- let id = MessageID::new().await;
95- let user_id = user.get_id().to_owned();
96- let community_id = community.get_id().to_owned();
97- //todo RecordID olan yerleri düzeltiyoruz
98- Ok(Self {
99- id,
100- user_id,
101- community_id,
102- message_body,
103- })
104- }
105-
106- pub fn get_user_id(&self) -> &UserID {
107- &self.user_id
108- }
109-
110- pub fn get_community_id(&self) -> &CommunityID {
111- &self.community_id
112- }
113-
114- pub fn get_message_body(&self) -> &MessageBody {
115- &self.message_body
116- }
117-
118- pub fn get_id(&self) -> &MessageID {
119- &self.id
120- }
121-
122- fn set_message_body(mut self, message_body: &str) -> Result<Message, Error> {
123- self.message_body = MessageBody::try_new(message_body)?;
124-
125- Ok(self)
126- }
127-
128- pub async fn create(
129- user: &User,
130- community: &Community,
131- message: &str,
132- database_connection: &DB,
133- ) -> Result<Self, Error> {
134- let message = Self::new(user, community, message).await?;
135- database::create(message, database_connection).await
136- }
137-
138- pub async fn read(id: &MessageID, database_connection: &DB) -> Result<Message, Error> {
139- database::read(id, database_connection).await
140- }
141-
142- pub async fn read_by_community_id(
143- community_id: &CommunityID,
144- database_connection: &DB,
145- ) -> Result<Vec<Message>, Error> {
146- database::read_by_community_id(community_id, database_connection).await
147- }
148 73
149- pub async fn read_by_community_id_with_marker_and_limit(74+ let mut rows = db
150- community_id: &CommunityID,75+ .query(
151- marker: &MessageID,76+ "UPDATE message SET body = ?2 WHERE id = ?1 RETURNING id, user_id, community_id, body",
152- limit: usize,77+ (message_id, body),
153- database_connection: &DB,
154- ) -> Result<Vec<Message>, Error> {
155- database::read_by_community_id_with_marker_and_limit(
156- community_id,
157- marker,
158- limit,
159- database_connection,
160 )78 )
161- .await79+ .await?;
162- }80+ let row = rows.next().await?.ok_or(Error::NotFound)?;
163-
164- pub async fn read_by_user_id(
165- user_id: &UserID,
166- database_connection: &DB,
167- ) -> Result<Vec<Message>, Error> {
168- database::read_by_user_id(user_id, database_connection).await
169- }
170-
171- pub async fn update(
172- self,
173- message_body: &str,
174- database_connection: &DB,
175- ) -> Result<Message, Error> {
176- let message_body = self.set_message_body(message_body)?;
177- database::update(message_body, database_connection).await
178- }
179-
180- pub async fn delete(self, database_connection: &DB) -> Result<Message, Error> {
181- database::delete(self.id, database_connection).await
182- }
183-}
184-
185-impl ToOwned for Message {
186- type Owned = Self;
187 81
188- fn to_owned(&self) -> Self::Owned {82+ from_row(&row)
189- Self {
190- id: self.id.to_owned(),
191- user_id: self.user_id.to_owned(),
192- community_id: self.community_id.to_owned(),
193- message_body: self.message_body.to_owned(),
194- }
195- }
196 }83 }
197 84
198-impl Into<common::message::Message> for Message {85+pub async fn delete(message_id: &str, db: &DB) -> Result<Message, Error> {
199- fn into(self) -> common::message::Message {86+ let mut rows = db
200- common::message::Message::new(87+ .query(
201- self.get_id().as_str(),88+ "DELETE FROM message WHERE id = ?1 RETURNING id, user_id, community_id, body",
202- self.get_user_id().as_str(),89+ (message_id,),
203- self.get_community_id().as_str(),
204- self.message_body.as_str(),
205 )90 )
206- }91+ .await?;
92+ let row = rows.next().await?.ok_or(Error::NotFound)?;
93+
94+ from_row(&row)
207 }95 }
208 96
209 #[cfg(test)]97 #[cfg(test)]
210 mod tests {98 mod tests {
211- use crate::{99+ use crate::{community, error::Error, message, test, user};
212- community::Community,
213- error::{Error, database},
214- message::Message,
215- test,
216- user::User,
217- };
218 100
219 #[tokio::test]101 #[tokio::test]
220 async fn create() {102 async fn create() {
221- let (database_connection, _temp_directory) = test::get_database().await;103+ let db = test::get_database().await;
222 104
223- let username = "Tahinli";105+ let user = user::create("Tahinli", &db).await.unwrap();
224- let name = username;106+ let community = community::create("Tahinli", &db).await.unwrap();
225-107+ let message = message::create(&user.id, &community.id, "Tahinli", &db)
226- let user = User::create(username, &database_connection).await.unwrap();
227- let community = Community::create(name, &database_connection).await.unwrap();
228-
229- let message_ = name;
230- let message = Message::create(&user, &community, message_, &database_connection)
231 .await108 .await
232 .unwrap();109 .unwrap();
233 110
234- assert_eq!(community.get_id(), message.get_community_id());111+ assert_eq!(community.id, message.community_id);
235- assert_eq!(user.get_id(), message.get_user_id());112+ assert_eq!(user.id, message.user_id);
236- assert_eq!(message_, message.get_message_body().as_str());113+ assert_eq!("Tahinli", message.body);
237 }114 }
238 115
239 #[tokio::test]116 #[tokio::test]
240 async fn read() {117 async fn read() {
241- let (database_connection, _temp_directory) = test::get_database().await;118+ let db = test::get_database().await;
242-
243- let username = "Tahinli";
244- let name = username;
245 119
246- let user = User::create(username, &database_connection).await.unwrap();120+ let user = user::create("Tahinli", &db).await.unwrap();
247- let community = Community::create(name, &database_connection).await.unwrap();121+ let community = community::create("Tahinli", &db).await.unwrap();
248-122+ let created_message = message::create(&user.id, &community.id, "Tahinli", &db)
249- let message_ = name;
250- let created_message = Message::create(&user, &community, message_, &database_connection)
251 .await123 .await
252 .unwrap();124 .unwrap();
253 125
254- let searched_message = Message::read(created_message.get_id(), &database_connection)126+ let searched_message = message::read(&created_message.id, &db).await.unwrap();
255- .await
256- .unwrap();
257 127
258 assert_eq!(created_message, searched_message);128 assert_eq!(created_message, searched_message);
259 }129 }
260 130
261 #[tokio::test]131 #[tokio::test]
262- async fn read_by_community_id() {132+ async fn read_page() {
263- let (database_connection, _temp_directory) = test::get_database().await;133+ let db = test::get_database().await;
264 134
265- let username = "Tahinli";135+ let user_1 = user::create("Tahinli", &db).await.unwrap();
266- let name = username;136+ let user_2 = user::create("Not Tahinli", &db).await.unwrap();
137+ let community = community::create("Tahinli", &db).await.unwrap();
267 138
268- let user_1 = User::create(username, &database_connection).await.unwrap();139+ let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &db)
269- let user_2 = User::create("Not Tahinli", &database_connection)
270 .await140 .await
271 .unwrap();141 .unwrap();
272- let community_1 = Community::create(name, &database_connection).await.unwrap();142+ let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &db)
273- let community_2 = Community::create("Not Tahinli", &database_connection)
274 .await143 .await
275 .unwrap();144 .unwrap();
276-145+ let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &db)
277- let message_ = name;
278- let created_message_1 =
279- Message::create(&user_1, &community_1, message_, &database_connection)
280- .await
281- .unwrap();
282- let created_message_2 =
283- Message::create(&user_2, &community_1, message_, &database_connection)
284- .await
285- .unwrap();
286- let _created_message_3 =
287- Message::create(&user_1, &community_2, message_, &database_connection)
288- .await
289- .unwrap();
290-
291- let expected_result = vec![created_message_1, created_message_2];
292-
293- let searched_messages =
294- Message::read_by_community_id(community_1.get_id(), &database_connection)
295- .await
296- .unwrap();
297-
298- assert_eq!(expected_result, searched_messages);
299- }
300-
301- #[tokio::test]
302- async fn read_by_community_id_with_marker_and_limit() {
303- let (database_connection, _temp_directory) = test::get_database().await;
304-
305- let username = "Tahinli";
306- let name = username;
307-
308- let user_1 = User::create(username, &database_connection).await.unwrap();
309- let user_2 = User::create("Not Tahinli", &database_connection)
310 .await146 .await
311 .unwrap();147 .unwrap();
312- let community = Community::create(name, &database_connection).await.unwrap();
313-
314- let message_ = name;
315- let created_message_1 =
316- Message::create(&user_1, &community, message_, &database_connection)
317- .await
318- .unwrap();
319- let created_message_2 =
320- Message::create(&user_2, &community, message_, &database_connection)
321- .await
322- .unwrap();
323-
324- let created_message_3 =
325- Message::create(&user_2, &community, message_, &database_connection)
326- .await
327- .unwrap();
328-
329- let created_message_2_id = created_message_2.get_id().to_owned();
330- let created_message_3_id = created_message_3.get_id().to_owned();
331-
332- let mut expected_result = vec![created_message_1, created_message_2, created_message_3];
333-
334- let searched_messages = Message::read_by_community_id_with_marker_and_limit(
335- community.get_id(),
336- &created_message_3_id,
337- 3,
338- &database_connection,
339- )
340- .await
341- .unwrap();
342-
343- assert_eq!(expected_result, searched_messages);
344-
345- expected_result.remove(0);
346-
347- let searched_messages = Message::read_by_community_id_with_marker_and_limit(
348- community.get_id(),
349- &created_message_3_id,
350- 2,
351- &database_connection,
352- )
353- .await
354- .unwrap();
355-
356- assert_eq!(expected_result, searched_messages);
357-
358- expected_result.pop();
359-
360- let searched_messages = Message::read_by_community_id_with_marker_and_limit(
361- community.get_id(),
362- &created_message_2_id,
363- 1,
364- &database_connection,
365- )
366- .await
367- .unwrap();
368 148
369- assert_eq!(expected_result, searched_messages);149+ let searched_messages = message::read_page(&community.id, &message_3.id, 3, &db)
370- }
371-
372- #[tokio::test]
373- async fn read_by_user_id() {
374- let (database_connection, _temp_directory) = test::get_database().await;
375-
376- let username = "Tahinli";
377- let name = username;
378-
379- let user_1 = User::create(username, &database_connection).await.unwrap();
380- let user_2 = User::create("Not Tahinli", &database_connection)
381- .await
382- .unwrap();
383- let community_1 = Community::create(name, &database_connection).await.unwrap();
384- let community_2 = Community::create("Not Tahinli", &database_connection)
385 .await150 .await
386 .unwrap();151 .unwrap();
387 152
388- let message_ = name;153+ assert_eq!(
389- let created_message_1 =154+ vec![message_1, message_2, message_3.clone()],
390- Message::create(&user_1, &community_1, message_, &database_connection)155+ searched_messages
391- .await156+ );
392- .unwrap();157+
393- let created_message_2 =158+ let searched_messages = message::read_page(&community.id, &message_3.id, 1, &db)
394- Message::create(&user_1, &community_2, message_, &database_connection)
395- .await
396- .unwrap();
397- let _created_message_3 =
398- Message::create(&user_2, &community_1, message_, &database_connection)
399- .await
400- .unwrap();
401-
402- let expected_result = vec![created_message_1, created_message_2];
403-
404- let searched_messages = Message::read_by_user_id(user_1.get_id(), &database_connection)
405 .await159 .await
406 .unwrap();160 .unwrap();
407 161
408- assert_eq!(expected_result, searched_messages);162+ assert_eq!(vec![message_3], searched_messages);
409 }163 }
410 164
411 #[tokio::test]165 #[tokio::test]
412 async fn update() {166 async fn update() {
413- let (database_connection, _temp_directory) = test::get_database().await;167+ let db = test::get_database().await;
414-
415- let username = "Tahinli";
416- let name = username;
417-
418- let user = User::create(username, &database_connection).await.unwrap();
419- let community = Community::create(name, &database_connection).await.unwrap();
420 168
421- let message_ = name;169+ let user = user::create("Tahinli", &db).await.unwrap();
422- let created_message = Message::create(&user, &community, message_, &database_connection)170+ let community = community::create("Tahinli", &db).await.unwrap();
171+ let created_message = message::create(&user.id, &community.id, "Tahinli", &db)
423 .await172 .await
424 .unwrap();173 .unwrap();
425 174
426- let created_message_id = created_message.get_id().to_owned();175+ let updated_message = message::update(&created_message.id, "Not Tahinli", &db)
427- let created_message_user_id = created_message.get_user_id().to_owned();
428- let created_message_community_id = created_message.get_community_id().to_owned();
429- let created_message_message = created_message.get_message_body().to_owned();
430-
431- let updated_message = created_message
432- .update("Not Tahinli", &database_connection)
433- .await
434- .unwrap();
435-
436- let searched_message = Message::read(updated_message.get_id(), &database_connection)
437 .await176 .await
438 .unwrap();177 .unwrap();
178+ let searched_message = message::read(&created_message.id, &db).await.unwrap();
439 179
440- assert_eq!(&created_message_id, updated_message.get_id());180+ assert_eq!(created_message.user_id, updated_message.user_id);
441- assert_eq!(181+ assert_eq!(created_message.community_id, updated_message.community_id);
442- &created_message_community_id,
443- updated_message.get_community_id()
444- );
445- assert_eq!(&created_message_user_id, updated_message.get_user_id());
446- assert_ne!(&created_message_message, updated_message.get_message_body());
447 assert_eq!(updated_message, searched_message);182 assert_eq!(updated_message, searched_message);
183+ assert_eq!("Not Tahinli", searched_message.body);
448 }184 }
449 185
450 #[tokio::test]186 #[tokio::test]
451- async fn update_on_unpersistent_message() {187+ async fn update_on_missing_message() {
452- let (database_connection, _temp_directory) = test::get_database().await;188+ let db = test::get_database().await;
453 189
454- let username = "Tahinli";190+ let updated_message = message::update("missing", "Tahinli", &db).await;
455- let name = username;
456 191
457- let user = User::create(username, &database_connection).await.unwrap();192+ assert!(matches!(updated_message, Err(Error::NotFound)));
458- let community = Community::create(name, &database_connection).await.unwrap();
459-
460- let message_ = name;
461- let unpersistent_message = Message::new(&user, &community, message_).await.unwrap();
462- let updated_message = unpersistent_message
463- .update(message_, &database_connection)
464- .await;
465-
466- assert!(matches!(
467- updated_message,
468- Err(Error::Database(database::Error::Update)),
469- ));
470 }193 }
471 194
472 #[tokio::test]195 #[tokio::test]
473 async fn delete() {196 async fn delete() {
474- let (database_connection, _temp_directory) = test::get_database().await;197+ let db = test::get_database().await;
475-
476- let username = "Tahinli";
477- let name = username;
478 198
479- let user = User::create(username, &database_connection).await.unwrap();199+ let user = user::create("Tahinli", &db).await.unwrap();
480- let community = Community::create(name, &database_connection).await.unwrap();200+ let community = community::create("Tahinli", &db).await.unwrap();
481-201+ let created_message = message::create(&user.id, &community.id, "Tahinli", &db)
482- let message_ = name;
483- let created_message = Message::create(&user, &community, message_, &database_connection)
484 .await202 .await
485 .unwrap();203 .unwrap();
486- let created_message_id = created_message.get_id().to_owned();
487- let created_message_user_id = created_message.get_user_id().to_owned();
488- let created_message_community_id = created_message.get_community_id().to_owned();
489- let created_message_message = created_message.get_message_body().to_owned();
490 204
491- let deleted_message = created_message.delete(&database_connection).await.unwrap();205+ let deleted_message = message::delete(&created_message.id, &db).await.unwrap();
492 206
493- assert_eq!(&created_message_id, deleted_message.get_id());207+ assert_eq!(created_message, deleted_message);
494- assert_eq!(
495- &created_message_community_id,
496- deleted_message.get_community_id()
497- );
498- assert_eq!(&created_message_user_id, deleted_message.get_user_id());
499- assert_eq!(&created_message_message, deleted_message.get_message_body());
500 }208 }
501 }209 }
crates/server/src/message/database.rsdeleted+0 -104
@@ -1,104 +0,0 @@
1-use crate::{
2- community::CommunityID,
3- database_::{DB, MESSAGE_TABLE},
4- error::{self, Error},
5- message::{Message, MessageID},
6- user::UserID,
7-};
8-
9-pub(super) async fn create(message: Message, database_connection: &DB) -> Result<Message, Error> {
10- let result = database_connection
11- .create(message.get_id().as_record_id())
12- .content(message)
13- .await?;
14-
15- result.ok_or_else(|| error::database::Error::Create.into())
16-}
17-
18-pub(super) async fn read(id: &MessageID, database_connection: &DB) -> Result<Message, Error> {
19- let result = database_connection.select(id.as_record_id()).await?;
20-
21- result.ok_or_else(|| error::database::Error::Read.into())
22-}
23-
24-pub(super) async fn read_by_community_id(
25- community_id: &CommunityID,
26- database_connection: &DB,
27-) -> Result<Vec<Message>, Error> {
28- let mut result = database_connection
29- .query(
30- "
31- SELECT * FROM type::table($table) WHERE community_id = $community_id;
32- ",
33- )
34- .bind(("table", MESSAGE_TABLE))
35- .bind(("community_id", community_id.as_record_id()))
36- .await?
37- .check()?;
38-
39- let result = result.take::<Vec<Message>>(0)?;
40-
41- Ok(result)
42-}
43-
44-pub(super) async fn read_by_community_id_with_marker_and_limit(
45- community_id: &CommunityID,
46- marker: &MessageID,
47- limit: usize,
48- database_connection: &DB,
49-) -> Result<Vec<Message>, Error> {
50- let query = "
51- SELECT * FROM type::table($table)
52- WHERE community_id = $community_id AND id <= $before
53- ORDER BY id DESC LIMIT $limit;
54- ";
55-
56- let mut result = database_connection
57- .query(query)
58- .bind(("table", MESSAGE_TABLE))
59- .bind(("community_id", community_id.as_record_id()))
60- .bind(("limit", limit))
61- .bind(("before", marker.as_record_id()))
62- .await?
63- .check()?;
64-
65- let mut result = result.take::<Vec<_>>(0)?;
66- result.reverse();
67-
68- Ok(result)
69-}
70-
71-pub(super) async fn read_by_user_id(
72- user_id: &UserID,
73- database_connection: &DB,
74-) -> Result<Vec<Message>, Error> {
75- let mut result = database_connection
76- .query(
77- "
78- SELECT * FROM type::table($table) WHERE user_id = $user_id;
79- ",
80- )
81- .bind(("table", MESSAGE_TABLE))
82- .bind(("user_id", user_id.as_record_id()))
83- .await?
84- .check()?;
85-
86- let result = result.take::<Vec<Message>>(0)?;
87-
88- Ok(result)
89-}
90-
91-pub(super) async fn update(message: Message, database_connection: &DB) -> Result<Message, Error> {
92- let result = database_connection
93- .update(message.get_id().as_record_id())
94- .content(message)
95- .await?;
96-
97- result.ok_or_else(|| error::database::Error::Update.into())
98-}
99-
100-pub(super) async fn delete(id: MessageID, database_connection: &DB) -> Result<Message, Error> {
101- let result = database_connection.delete(id.as_record_id()).await?;
102-
103- result.ok_or_else(|| error::database::Error::Delete.into())
104-}
crates/server/src/network.rsmodified+83 -136
@@ -1,35 +1,25 @@
1-use std::{1+use std::sync::Arc;
2- collections::HashMap,
3- sync::{
4- Arc,
5- atomic::{AtomicU64, Ordering},
6- },
7-};
8 2
9 use common::{3 use common::{
10- network::{AUTHENTICATION_MAX_READ_LENGHT, Network},4+ model::Message,
5+ network::{
6+ AUTHENTICATION_MAX_READ_LENGTH, REQUEST_MAX_READ_LENGTH, receive_request, send_message,
7+ send_response,
8+ },
11 request::Request,9 request::Request,
12 response::Response,10 response::Response,
13 };11 };
14 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};12 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};
15 use tokio::{sync::mpsc, task::JoinHandle};13 use tokio::{sync::mpsc, task::JoinHandle};
16-use tokio_stream::{StreamExt, wrappers::ReceiverStream};
17 14
18 use crate::{15 use crate::{
19- authentication::authenticate,16+ authentication::authenticate, database::DB, error::Error, request::handle_request,
20- community::{Community, CommunityID},17+ user_community,
21- database_::DB,
22- error::Error,
23- request::handle_request,
24- user::UserID,
25- user_community::users_in,
26 };18 };
27 19
28 const CHANNEL_LENGTH: usize = 2048;20 const CHANNEL_LENGTH: usize = 2048;
29 const SESSION_LENGTH: usize = 64;21 const SESSION_LENGTH: usize = 64;
30 22
31-static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(0);
32-
33 #[cfg(feature = "rcgen")]23 #[cfg(feature = "rcgen")]
34 fn config() -> quinn::ServerConfig {24 fn config() -> quinn::ServerConfig {
35 use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};25 use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
@@ -40,81 +30,64 @@ fn config() -> quinn::ServerConfig {
40 quinn::ServerConfig::with_single_cert(vec![certificate_der], certificate_key.into()).unwrap()30 quinn::ServerConfig::with_single_cert(vec![certificate_der], certificate_key.into()).unwrap()
41 }31 }
42 32
43-pub async fn serve(server_address: &str, database_connection: &DB) -> Result<(), Error> {33+pub async fn serve(server_address: &str, db: &DB) -> Result<(), Error> {
44 let endpoint = Endpoint::server(config(), server_address.parse()?)?;34 let endpoint = Endpoint::server(config(), server_address.parse()?)?;
45 35
46 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH);36 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH);
47- let database_connection_clone = || -> DB { database_connection.clone() };37+ tokio::spawn(the_actor(event_receiver, db.clone()));
48-
49- tokio::spawn(the_actor(event_receiver, database_connection_clone()));
50 38
51 while let Some(incoming) = endpoint.accept().await {39 while let Some(incoming) = endpoint.accept().await {
52- let database_connection = database_connection.clone();
53- let event_sender = event_sender.clone();
54-
55 tokio::spawn(handle_connection(40 tokio::spawn(handle_connection(
56 incoming,41 incoming,
57- event_sender,42+ event_sender.clone(),
58- database_connection,43+ db.clone(),
59 ));44 ));
60 }45 }
61 46
62 Ok(())47 Ok(())
63 }48 }
64 49
65-async fn handle_connection(50+async fn handle_connection(incoming: Incoming, event_sender: mpsc::Sender<Event>, db: DB) {
66- incoming: Incoming,
67- event_sender: mpsc::Sender<Event>,
68- database_connection: DB,
69-) {
70 match incoming.await {51 match incoming.await {
71 Ok(connection) => {52 Ok(connection) => {
72- if let Err(error_value) =53+ if let Err(error) = establish_connection(&connection, event_sender, &db).await {
73- establish_connection(&connection, event_sender, &database_connection).await54+ eprintln!("Error = Endpoint Accept | {error}");
74- {
75- eprintln!("Error = Endpoint Accept | {}", error_value.to_string());
76 connection.close(0u8.into(), b"kendine iyi bak");55 connection.close(0u8.into(), b"kendine iyi bak");
77 }56 }
78 }57 }
79- Err(error_value) => eprintln!("Error = Connection | {}", error_value.to_string()),58+ Err(error) => eprintln!("Error = Connection | {error}"),
80 }59 }
81 }60 }
82 61
83 async fn establish_connection(62 async fn establish_connection(
84 connection: &Connection,63 connection: &Connection,
85 event_sender: mpsc::Sender<Event>,64 event_sender: mpsc::Sender<Event>,
86- database_connection: &DB,65+ db: &DB,
87 ) -> Result<(), Error> {66 ) -> Result<(), Error> {
88 let (send_stream, receive_stream) = connection.accept_bi().await?;67 let (send_stream, receive_stream) = connection.accept_bi().await?;
89 68
90- let first_request =69+ let first_request = receive_request(receive_stream, AUTHENTICATION_MAX_READ_LENGTH).await?;
91- Network::receive_request(receive_stream, Some(AUTHENTICATION_MAX_READ_LENGHT)).await?;
92 70
93- if let Request::Authentication(authentication) = first_request {71+ if let Request::Authentication { token } = first_request {
94- let authentication_token = authentication.get_authentication_token();72+ let user = authenticate(&token, db).await?;
95- let user = authenticate(authentication_token, database_connection).await?;73+ let response = Response::Authentication(user.clone());
96- let response = Response::Authentication(common::user::User::new(
97- user.get_id().as_str(),
98- user.get_username().as_str(),
99- ));
100 74
101- let user_id = user.get_id().to_owned();
102 tokio::spawn(listen(75 tokio::spawn(listen(
103- user_id,76+ user.id.clone(),
104 connection.clone(),77 connection.clone(),
105 event_sender.clone(),78 event_sender.clone(),
106- database_connection.clone(),79+ db.clone(),
107 ));80 ));
108 81
109- Network::send_response(&response, send_stream).await?;82+ send_response(&response, send_stream).await?;
110 83
111 let send_stream = connection.open_uni().await?;84 let send_stream = connection.open_uni().await?;
112 let _ = event_sender85 let _ = event_sender
113- .send(Event::Joined(86+ .send(Event::Joined {
114- user.get_id().to_owned(),87+ user_id: user.id,
115 send_stream,88 send_stream,
116- connection.clone(),89+ connection: connection.clone(),
117- ))90+ })
118 .await;91 .await;
119 92
120 Ok(())93 Ok(())
@@ -124,130 +97,105 @@ async fn establish_connection(
124 }97 }
125 98
126 async fn listen(99 async fn listen(
127- user_id: UserID,100+ user_id: String,
128 connection: Connection,101 connection: Connection,
129 event_sender: mpsc::Sender<Event>,102 event_sender: mpsc::Sender<Event>,
130- database_connection: DB,103+ db: DB,
131 ) {104 ) {
132- let read_and_answer = async |user_id: UserID,
133- send_stream: SendStream,
134- receive_stream: RecvStream,
135- event_sender: mpsc::Sender<Event>,
136- database_connection: DB|
137- -> Result<(), Error> {
138- let request = Network::receive_request(receive_stream, None).await?;
139- let response = handle_request(user_id, request, &database_connection).await;
140-
141- if let Response::CreateMessage(message) = &response {
142- let _ = event_sender.send(Event::Sent(message.to_owned())).await;
143- }
144-
145- Network::send_response(&response, send_stream).await?;
146-
147- Ok(())
148- };
149-
150 while let Ok((send_stream, receive_stream)) = connection.accept_bi().await {105 while let Ok((send_stream, receive_stream)) = connection.accept_bi().await {
151- let database_connection = database_connection.clone();
152- let user_id = user_id.clone();
153-
154 tokio::spawn(read_and_answer(106 tokio::spawn(read_and_answer(
155- user_id,107+ user_id.clone(),
156 send_stream,108 send_stream,
157 receive_stream,109 receive_stream,
158 event_sender.clone(),110 event_sender.clone(),
159- database_connection,111+ db.clone(),
160 ));112 ));
161 }113 }
162 }114 }
163 115
164-enum Event {116+async fn read_and_answer(
165- Joined(UserID, SendStream, Connection),117+ user_id: String,
166- Sent(common::message::Message),118+ send_stream: SendStream,
167-}119+ receive_stream: RecvStream,
120+ event_sender: mpsc::Sender<Event>,
121+ db: DB,
122+) -> Result<(), Error> {
123+ let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?;
124+ let response = handle_request(&user_id, request, &db).await;
168 125
169-type SessionID = u64;126+ if let Response::CreateMessage(message) = &response {
127+ let _ = event_sender.send(Event::Sent(message.clone())).await;
128+ }
170 129
171-struct Session {130+ send_response(&response, send_stream).await?;
172- user_id: UserID,131+
173- connection: Connection,132+ Ok(())
174- message_sender: mpsc::Sender<Arc<common::message::Message>>,
175- writer: JoinHandle<()>,
176 }133 }
177 134
178-impl Session {135+enum Event {
179- fn new(136+ Joined {
180- user_id: UserID,137+ user_id: String,
138+ send_stream: SendStream,
181 connection: Connection,139 connection: Connection,
182- message_sender: mpsc::Sender<Arc<common::message::Message>>,140+ },
183- writer: JoinHandle<()>,141+ Sent(Message),
184- ) -> Self {142+}
185- Self {143+
186- user_id,144+struct Session {
187- connection,145+ pub user_id: String,
188- message_sender,146+ pub connection: Connection,
189- writer,147+ pub message_sender: mpsc::Sender<Arc<Message>>,
190- }148+ pub writer: JoinHandle<()>,
191- }
192 }149 }
193 150
194 async fn write_session(151 async fn write_session(
195- mut message_receiver: mpsc::Receiver<Arc<common::message::Message>>,152+ mut message_receiver: mpsc::Receiver<Arc<Message>>,
196 mut send_stream: SendStream,153 mut send_stream: SendStream,
197 ) {154 ) {
198 while let Some(message) = message_receiver.recv().await {155 while let Some(message) = message_receiver.recv().await {
199- if let Err(error_value) = Network::send_message(&message, &mut send_stream).await {156+ if let Err(error) = send_message(&message, &mut send_stream).await {
200- eprintln!("Error = Message | Session Write | {}", error_value);157+ eprintln!("Error = Message | Session Write | {error}");
201 break;158 break;
202 }159 }
203 }160 }
204 }161 }
205 162
206-async fn the_actor(event_receiver: mpsc::Receiver<Event>, database_connection: DB) {163+async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, db: DB) {
207- let mut sessions: HashMap<SessionID, Session> = HashMap::new();164+ let mut sessions: Vec<Session> = Vec::new();
208-
209- let mut events = ReceiverStream::new(event_receiver);
210 165
211- while let Some(event) = events.next().await {166+ while let Some(event) = event_receiver.recv().await {
212- sessions.retain(|_, session| {167+ sessions.retain(|session| {
213 !session.writer.is_finished() && session.connection.close_reason().is_none()168 !session.writer.is_finished() && session.connection.close_reason().is_none()
214 });169 });
215 170
216 match event {171 match event {
217- Event::Joined(user_id, send_stream, connection) => {172+ Event::Joined {
173+ user_id,
174+ send_stream,
175+ connection,
176+ } => {
218 let (message_sender, message_receiver) = mpsc::channel(SESSION_LENGTH);177 let (message_sender, message_receiver) = mpsc::channel(SESSION_LENGTH);
219 let writer = tokio::spawn(write_session(message_receiver, send_stream));178 let writer = tokio::spawn(write_session(message_receiver, send_stream));
220 179
221- sessions.insert(180+ sessions.push(Session {
222- NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed),181+ user_id,
223- Session::new(user_id, connection, message_sender, writer),182+ connection,
224- );183+ message_sender,
184+ writer,
185+ });
225 }186 }
226 Event::Sent(message) => {187 Event::Sent(message) => {
227- let Ok(community) = Community::read(188+ let Ok(users) = user_community::users_in(&message.community_id, &db).await else {
228- &CommunityID::from(message.get_community_id()),
229- &database_connection,
230- )
231- .await
232- else {
233- eprintln!(
234- "Error = Message | Community Read | {}",
235- message.get_community_id()
236- );
237- continue;
238- };
239-
240- let Ok(users) = users_in(&community, &database_connection).await else {
241 eprintln!(189 eprintln!(
242 "Error = Message | Community Member Read | {}",190 "Error = Message | Community Member Read | {}",
243- message.get_community_id()191+ message.community_id
244 );192 );
245 continue;193 continue;
246 };194 };
247 195
248 let message = Arc::new(message);196 let message = Arc::new(message);
249 197
250- sessions.retain(|session_id, session| {198+ sessions.retain(|session| {
251 if !users.contains(&session.user_id) {199 if !users.contains(&session.user_id) {
252 return true;200 return true;
253 }201 }
@@ -256,9 +204,8 @@ async fn the_actor(event_receiver: mpsc::Receiver<Event>, database_connection: D
256 Ok(()) => true,204 Ok(()) => true,
257 Err(mpsc::error::TrySendError::Full(_)) => {205 Err(mpsc::error::TrySendError::Full(_)) => {
258 eprintln!(206 eprintln!(
259- "Error = Message | Session Buffer is Full | {} | {}",207+ "Error = Message | Session Buffer is Full | {}",
260- session_id,208+ session.user_id
261- session.user_id.as_str()
262 );209 );
263 session.writer.abort();210 session.writer.abort();
264 false211 false
crates/server/src/request.rsmodified+100 -241
@@ -1,251 +1,110 @@
1 use common::{request::Request, response::Response};1 use common::{request::Request, response::Response};
2 2
3 use crate::{3 use crate::{
4- authentication::{authenticate, deauthenticate},4+ authentication::authenticate, community, database::DB, error::Error, message, user,
5- community::Community,5+ user_community,
6- database_::DB,
7- error::Error,
8- message::Message,
9- user::{User, UserID},
10- user_community::{JoinCommunity, LeaveCommunity, communitys_of, is_user_in, users_in},
11 };6 };
12 7
13-pub async fn handle_request(8+pub async fn handle_request(session_user_id: &str, request: Request, db: &DB) -> Response {
14- user_id: UserID,9+ match handle(session_user_id, request, db).await {
15- request: Request,10+ Ok(response) => response,
16- database_connection: &DB,11+ Err(error) => Response::Error(error.into()),
17-) -> Response {12+ }
18- let request_matcher = async || -> Result<Response, Error> {13+}
19- match request {
20- Request::Authentication(authentication) => {
21- let user = authenticate(
22- authentication.get_authentication_token(),
23- database_connection,
24- )
25- .await?;
26-
27- Ok(Response::Authentication(user.into()))
28- }
29- Request::Deauthentication(deauthentication) => {
30- let user = deauthenticate(
31- deauthentication.get_authentication_token(),
32- database_connection,
33- )
34- .await?;
35-
36- Ok(Response::Deauthentication(user.into()))
37- }
38- Request::CreateUser(create_user) => {
39- let user = User::create(create_user.get_username(), database_connection).await?;
40-
41- Ok(Response::CreateUser(user.into()))
42- }
43- Request::ReadUser(read_user) => {
44- let user = User::read(&read_user.get_user_id().into(), database_connection).await?;
45-
46- Ok(Response::ReadUser(user.into()))
47- }
48- Request::UpdateUser(update_user) => {
49- let user =
50- User::read(&update_user.get_user_id().into(), database_connection).await?;
51- let user = user
52- .update(update_user.get_username(), database_connection)
53- .await?;
54-
55- Ok(Response::UpdateUser(user.into()))
56- }
57- Request::DeleteUser(delete_user) => {
58- let user =
59- User::read(&delete_user.get_user_id().into(), database_connection).await?;
60- let user = user.delete(database_connection).await?;
61-
62- Ok(Response::DeleteUser(user.into()))
63- }
64- Request::CreateCommunity(create_community) => {
65- let community =
66- Community::create(create_community.get_community_name(), database_connection)
67- .await?;
68-
69- JoinCommunity::apply(&user_id, community.get_id(), database_connection).await?;
70- Ok(Response::CreateCommunity(community.into()))
71- }
72- Request::ReadCommunity(read_community) => {
73- let community = Community::read(
74- &read_community.get_community_id().into(),
75- database_connection,
76- )
77- .await?;
78-
79- Ok(Response::ReadCommunity(community.into()))
80- }
81- Request::UpdateCommunity(update_community) => {
82- let community = Community::read(
83- &update_community.get_community_id().into(),
84- database_connection,
85- )
86- .await?;
87-
88- let community = community
89- .update(update_community.get_community_name(), database_connection)
90- .await?;
91-
92- Ok(Response::UpdateCommunity(community.into()))
93- }
94- Request::DeleteCommunity(delete_community) => {
95- let community = Community::read(
96- &delete_community.get_community_id().into(),
97- database_connection,
98- )
99- .await?;
100-
101- let community = community.delete(database_connection).await?;
102-
103- Ok(Response::DeleteCommunity(community.into()))
104- }
105- Request::CreateMessage(create_message) => {
106- let user =
107- User::read(&create_message.get_user_id().into(), database_connection).await?;
108- let community = Community::read(
109- &create_message.get_community_id().into(),
110- database_connection,
111- )
112- .await?;
113- let message = create_message.get_message_body();
114- let message =
115- Message::create(&user, &community, &message, database_connection).await?;
116-
117- Ok(Response::CreateMessage(message.into()))
118- }
119- Request::ReadMessage(read_message) => {
120- let message =
121- Message::read(&read_message.get_message_id().into(), database_connection)
122- .await?;
123-
124- Ok(Response::ReadMessage(message.into()))
125- }
126- Request::UpdateMessage(update_message) => {
127- let message =
128- Message::read(&update_message.get_message_id().into(), database_connection)
129- .await?;
130-
131- let message = message
132- .update(update_message.get_message_body(), database_connection)
133- .await?;
134-
135- Ok(Response::UpdateMessage(message.into()))
136- }
137- Request::DeleteMessage(delete_message) => {
138- let message =
139- Message::read(&delete_message.get_message_id().into(), database_connection)
140- .await?;
141-
142- let message = message.delete(database_connection).await?;
143-
144- Ok(Response::DeleteMessage(message.into()))
145- }
146- Request::ReadMessageByCommunityIDWithMarkerAndLimit(
147- read_message_by_community_id_with_marker_and_limit,
148- ) => {
149- let messages = Message::read_by_community_id_with_marker_and_limit(
150- &read_message_by_community_id_with_marker_and_limit
151- .get_community_id()
152- .into(),
153- &read_message_by_community_id_with_marker_and_limit
154- .get_marker()
155- .into(),
156- read_message_by_community_id_with_marker_and_limit.get_limit(),
157- database_connection,
158- )
159- .await?;
160-
161- Ok(Response::ReadMessageByCommunityIDWithMarkerAndLimit(
162- messages.into_iter().map(Into::into).collect(),
163- ))
164- }
165- Request::JoinCommunity(join_community) => {
166- JoinCommunity::apply(
167- &join_community.get_user_id().into(),
168- &join_community.get_community_id().into(),
169- database_connection,
170- )
171- .await?;
172-
173- Ok(Response::JoinCommunity)
174- }
175- Request::LeaveCommunity(leave_community) => {
176- LeaveCommunity::apply(
177- &leave_community.get_user_id().into(),
178- &leave_community.get_community_id().into(),
179- database_connection,
180- )
181- .await?;
182-
183- let community = Community::read(
184- &leave_community.get_community_id().into(),
185- database_connection,
186- )
187- .await?;
188-
189- if users_in(&community, database_connection).await?.is_empty() {
190- community.delete(database_connection).await?;
191- }
192-
193- Ok(Response::LeaveCommunity)
194- }
195- Request::IsUserIn(is_user_in_) => {
196- let user =
197- User::read(&is_user_in_.get_user_id().into(), database_connection).await?;
198- let community =
199- Community::read(&is_user_in_.get_community_id().into(), database_connection)
200- .await?;
201-
202- let is_user_in = is_user_in(&user, &community, database_connection).await?;
203-
204- Ok(Response::IsUserIn(is_user_in))
205- }
206- Request::UsersIn(users_in_) => {
207- let community =
208- Community::read(&users_in_.get_community_id().into(), database_connection)
209- .await?;
210-
211- let users_in = users_in(&community, database_connection).await?;
212-
213- Ok(Response::UsersIn(
214- users_in
215- .iter()
216- .map(|user_id| user_id.as_str().to_string())
217- .collect(),
218- ))
219- }
220- Request::CommunityOf(community_of_) => {
221- let user =
222- User::read(&community_of_.get_user_id().into(), database_connection).await?;
223-
224- let community_of = communitys_of(&user, database_connection).await?;
225-
226- Ok(Response::CommunityOf(
227- community_of
228- .iter()
229- .map(|community_id| community_id.as_str().to_string())
230- .collect(),
231- ))
232- }
233- Request::SearchCommunity(search_community) => {
234- let communities = Community::read_by_name(
235- search_community.get_community_name(),
236- database_connection,
237- )
238- .await?;
239 14
240- Ok(Response::SearchCommunity(15+async fn handle(session_user_id: &str, request: Request, db: &DB) -> Result<Response, Error> {
241- communities.into_iter().map(Into::into).collect(),16+ let response = match request {
242- ))17+ Request::Authentication { token } => {
243- }18+ Response::Authentication(authenticate(&token, db).await?)
19+ }
20+ Request::Deauthentication { token } => {
21+ Response::Deauthentication(authenticate(&token, db).await?)
22+ }
23+ Request::CreateUser { username } => {
24+ Response::CreateUser(user::create(&username, db).await?)
25+ }
26+ Request::ReadUser { user_id } => Response::ReadUser(user::read(&user_id, db).await?),
27+ Request::UpdateUser { user_id, username } => {
28+ Response::UpdateUser(user::update(&user_id, &username, db).await?)
29+ }
30+ Request::DeleteUser { user_id } => Response::DeleteUser(user::delete(&user_id, db).await?),
31+ Request::CreateCommunity { name } => {
32+ let community = community::create(&name, db).await?;
33+ user_community::join(session_user_id, &community.id, db).await?;
34+ Response::CreateCommunity(community)
35+ }
36+ Request::ReadCommunity { community_id } => {
37+ Response::ReadCommunity(community::read(&community_id, db).await?)
38+ }
39+ Request::UpdateCommunity { community_id, name } => {
40+ Response::UpdateCommunity(community::update(&community_id, &name, db).await?)
41+ }
42+ Request::DeleteCommunity { community_id } => {
43+ Response::DeleteCommunity(community::delete(&community_id, db).await?)
44+ }
45+ Request::CreateMessage {
46+ user_id,
47+ community_id,
48+ body,
49+ } => {
50+ user::read(&user_id, db).await?;
51+ community::read(&community_id, db).await?;
52+ Response::CreateMessage(message::create(&user_id, &community_id, &body, db).await?)
53+ }
54+ Request::ReadMessage { message_id } => {
55+ Response::ReadMessage(message::read(&message_id, db).await?)
56+ }
57+ Request::UpdateMessage { message_id, body } => {
58+ Response::UpdateMessage(message::update(&message_id, &body, db).await?)
59+ }
60+ Request::DeleteMessage { message_id } => {
61+ Response::DeleteMessage(message::delete(&message_id, db).await?)
62+ }
63+ Request::ReadMessages {
64+ community_id,
65+ marker,
66+ limit,
67+ } => Response::ReadMessages(message::read_page(&community_id, &marker, limit, db).await?),
68+ Request::JoinCommunity {
69+ user_id,
70+ community_id,
71+ } => {
72+ user_community::join(&user_id, &community_id, db).await?;
73+ Response::JoinCommunity
74+ }
75+ Request::LeaveCommunity {
76+ user_id,
77+ community_id,
78+ } => {
79+ user_community::leave(&user_id, &community_id, db).await?;
80+ if user_community::users_in(&community_id, db)
81+ .await?
82+ .is_empty()
83+ {
84+ community::delete(&community_id, db).await?;
85+ }
86+ Response::LeaveCommunity
87+ }
88+ Request::IsUserIn {
89+ user_id,
90+ community_id,
91+ } => {
92+ user::read(&user_id, db).await?;
93+ community::read(&community_id, db).await?;
94+ Response::IsUserIn(user_community::is_user_in(&user_id, &community_id, db).await?)
95+ }
96+ Request::UsersIn { community_id } => {
97+ community::read(&community_id, db).await?;
98+ Response::UsersIn(user_community::users_in(&community_id, db).await?)
99+ }
100+ Request::CommunitiesOf { user_id } => {
101+ user::read(&user_id, db).await?;
102+ Response::CommunitiesOf(user_community::communities_of(&user_id, db).await?)
103+ }
104+ Request::SearchCommunity { name } => {
105+ Response::SearchCommunity(community::read_by_name(&name, db).await?)
244 }106 }
245 };107 };
246 108
247- match request_matcher().await {109+ Ok(response)
248- Ok(response) => response,
249- Err(error_value) => Response::Error(error_value.into()),
250- }
251 }110 }
crates/server/src/test.rsmodified+5 -22
@@ -1,25 +1,8 @@
1-#[cfg(test)]1+use crate::database::{self, DB};
2-use crate::{
3- ServerConfig,
4- database_::{self, DB},
5-};
6-use tempfile::TempDir;
7 2
8-pub async fn get_database() -> (DB, TempDir) {3+pub async fn get_database() -> DB {
9- let temp_directory = TempDir::new().unwrap();4+ let database = database::connect(":memory:").await.unwrap();
5+ database::migrate(&database).await.unwrap();
10 6
11- let server_config = ServerConfig {7+ database
12- database_prefix: "surrealkv".to_string(),
13- database_address: temp_directory.path().display().to_string(),
14- namespace: "yumush".to_string(),
15- database: "yumush".to_string(),
16- username: "".to_string(),
17- password: "".to_string(),
18- server_address: "127.0.0.1:2026".to_string(),
19- };
20-
21- let database_connection = database_::connect(&server_config).await.unwrap();
22- database_::migrate(&database_connection).await.unwrap();
23-
24- (database_connection, temp_directory)
25 }8 }
crates/server/src/user.rsmodified+83 -194
@@ -1,261 +1,150 @@
1-use std::sync::LazyLock;1+use common::{model::User, validate::validate_username};
2-2+use turso::Row;
3-use common::validate::validate_username;
4-use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
5-use tokio::sync::Mutex;
6-use ulid::Generator;
7 3
8 use crate::{4 use crate::{
9- database_::{DB, USER_TABLE},5+ database::{DB, new_id},
10 error::Error,6 error::Error,
11 };7 };
12 8
13-mod database;9+fn from_row(row: &Row) -> Result<User, Error> {
14-10+ Ok(User {
15-static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Generator::new().into());11+ id: row.get(0)?,
16-12+ username: row.get(1)?,
17-#[derive(Debug, Clone, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)]13+ })
18-pub struct UserID(RecordId);
19-
20-impl UserID {
21- async fn new() -> Self {
22- loop {
23- match ULID.lock().await.generate() {
24- Ok(ulid) => return Self(RecordId::new(USER_TABLE, ulid.to_string())),
25- Err(_) => continue,
26- }
27- }
28- }
29-
30- pub(crate) fn as_record_id(&self) -> RecordId {
31- self.0.clone()
32- }
33-
34- pub(crate) fn as_str(&self) -> &str {
35- match &self.0.key {
36- RecordIdKey::String(user_id) => user_id,
37- _ => unreachable!("We shouldn't be here"),
38- }
39- }
40-}
41-
42-impl From<&str> for UserID {
43- fn from(value: &str) -> Self {
44- Self(RecordId::new(USER_TABLE, value))
45- }
46 }14 }
47 15
48-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)]16+pub async fn create(username: &str, db: &DB) -> Result<User, Error> {
49-pub struct Username(String);17+ validate_username(username)?;
50 18
51-impl Username {19+ let mut rows = db
52- pub fn try_new(username: &str) -> Result<Self, Error> {20+ .query(
53- let username = username.to_string();21+ "INSERT INTO user (id, username) VALUES (?1, ?2) RETURNING id, username",
54- validate_username(&username)?;22+ (new_id(), username),
23+ )
24+ .await?;
25+ let row = rows.next().await?.ok_or(Error::NotFound)?;
55 26
56- Ok(Self(username))27+ from_row(&row)
57- }
58-
59- pub fn as_str(&self) -> &str {
60- &self.0
61- }
62 }28 }
63 29
64-impl ToOwned for Username {30+pub async fn read(user_id: &str, db: &DB) -> Result<User, Error> {
65- type Owned = Username;31+ let mut rows = db
32+ .query("SELECT id, username FROM user WHERE id = ?1", (user_id,))
33+ .await?;
34+ let row = rows.next().await?.ok_or(Error::NotFound)?;
66 35
67- fn to_owned(&self) -> Self::Owned {36+ from_row(&row)
68- Self(self.0.clone())
69- }
70-}
71-
72-#[derive(Debug, SurrealValue, PartialEq, PartialOrd, Eq, Ord, Hash)]
73-pub struct User {
74- id: UserID,
75- username: Username,
76 }37 }
77 38
78-impl User {39+pub async fn read_by_username(username: &str, db: &DB) -> Result<Vec<User>, Error> {
79- pub fn get_id(&self) -> &UserID {40+ let mut rows = db
80- &self.id41+ .query(
81- }42+ "SELECT id, username FROM user WHERE username = ?1 ORDER BY id",
82-43+ (username,),
83- pub fn get_username(&self) -> &Username {44+ )
84- &self.username45+ .await?;
85- }
86-
87- async fn new(username: &str) -> Result<User, Error> {
88- let username = Username::try_new(username)?;
89- let id = UserID::new().await;
90-
91- Ok(Self { id, username })
92- }
93-
94- fn update_username(mut self, username: &str) -> Result<User, Error> {
95- self.username = Username::try_new(username)?;
96-
97- Ok(self)
98- }
99-
100- pub async fn create(username: &str, database_connection: &DB) -> Result<User, Error> {
101- let user = Self::new(username).await?;
102-
103- database::create(user, database_connection).await
104- }
105 46
106- pub async fn read(id: &UserID, database_connection: &DB) -> Result<User, Error> {47+ let mut users = Vec::new();
107- database::read(id, database_connection).await48+ while let Some(row) = rows.next().await? {
49+ users.push(from_row(&row)?);
108 }50 }
109 51
110- pub async fn read_by_username(52+ Ok(users)
111- username: &str,53+}
112- database_connection: &DB,
113- ) -> Result<Vec<User>, Error> {
114- database::read_by_username(username, database_connection).await
115- }
116 54
117- pub async fn read_all(database_connection: &DB) -> Result<Vec<User>, Error> {55+pub async fn update(user_id: &str, username: &str, db: &DB) -> Result<User, Error> {
118- database::read_all(database_connection).await56+ validate_username(username)?;
119- }
120 57
121- pub async fn update(self, username: &str, database_connection: &DB) -> Result<User, Error> {58+ let mut rows = db
122- let user = self.update_username(username)?;59+ .query(
123- database::update(user, database_connection).await60+ "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username",
124- }61+ (user_id, username),
62+ )
63+ .await?;
64+ let row = rows.next().await?.ok_or(Error::NotFound)?;
125 65
126- pub async fn delete(self, database_connection: &DB) -> Result<User, Error> {66+ from_row(&row)
127- database::delete(self.id, database_connection).await
128- }
129 }67 }
130 68
131-impl Into<common::user::User> for User {69+pub async fn delete(user_id: &str, db: &DB) -> Result<User, Error> {
132- fn into(self) -> common::user::User {70+ let mut rows = db
133- common::user::User::new(self.get_id().as_str(), self.get_username().as_str())71+ .query(
134- }72+ "DELETE FROM user WHERE id = ?1 RETURNING id, username",
73+ (user_id,),
74+ )
75+ .await?;
76+ let row = rows.next().await?.ok_or(Error::NotFound)?;
77+
78+ from_row(&row)
135 }79 }
136 80
137 #[cfg(test)]81 #[cfg(test)]
138 mod tests {82 mod tests {
139- use crate::{83+ use crate::{error::Error, test, user};
140- error::{Error, database},
141- test,
142- user::User,
143- };
144 84
145 #[tokio::test]85 #[tokio::test]
146 async fn create() {86 async fn create() {
147- let (database_connection, _temp_directory) = test::get_database().await;87+ let db = test::get_database().await;
148 88
149- let username = "Tahinli";89+ let user = user::create("Tahinli", &db).await.unwrap();
150- let user = User::create(username, &database_connection).await;
151 90
152- assert_eq!(username, user.unwrap().get_username().as_str());91+ assert_eq!("Tahinli", user.username);
153 }92 }
154 93
155 #[tokio::test]94 #[tokio::test]
156 async fn read() {95 async fn read() {
157- let (database_connection, _temp_directory) = test::get_database().await;96+ let db = test::get_database().await;
158 97
159- let username = "Tahinli";98+ let created_user = user::create("Tahinli", &db).await.unwrap();
160- let created_user = User::create(username, &database_connection).await.unwrap();99+ let searched_user = user::read(&created_user.id, &db).await.unwrap();
161-
162- let searched_user = User::read(&created_user.get_id(), &database_connection)
163- .await
164- .unwrap();
165 100
166 assert_eq!(created_user, searched_user);101 assert_eq!(created_user, searched_user);
167 }102 }
168 103
169 #[tokio::test]104 #[tokio::test]
170 async fn read_by_username() {105 async fn read_by_username() {
171- let (database_connection, _temp_directory) = test::get_database().await;106+ let db = test::get_database().await;
172-
173- let username = "Tahinli";
174- let user_1 = User::create(username, &database_connection).await.unwrap();
175- let user_2 = User::create(username, &database_connection).await.unwrap();
176- let _user_3 = User::create("Not Tahinli", &database_connection)
177- .await
178- .unwrap();
179-
180- let expected_result = vec![user_1, user_2];
181-
182- let searched_users = User::read_by_username(username, &database_connection)
183- .await
184- .unwrap();
185-
186- assert_eq!(expected_result, searched_users);
187- }
188 107
189- #[tokio::test]108+ let user_1 = user::create("Tahinli", &db).await.unwrap();
190- async fn read_all() {109+ let user_2 = user::create("Tahinli", &db).await.unwrap();
191- let (database_connection, _temp_directory) = test::get_database().await;110+ let _user_3 = user::create("Not Tahinli", &db).await.unwrap();
192-
193- let username = "Tahinli";
194- let user_1 = User::create(username, &database_connection).await.unwrap();
195- let user_2 = User::create(username, &database_connection).await.unwrap();
196- let user_3 = User::create("Not Tahinli", &database_connection)
197- .await
198- .unwrap();
199 111
200- let expected_result = vec![user_1, user_2, user_3];112+ let searched_users = user::read_by_username("Tahinli", &db).await.unwrap();
201 113
202- let searched_users = User::read_all(&database_connection).await.unwrap();114+ assert_eq!(vec![user_1, user_2], searched_users);
203-
204- assert_eq!(expected_result, searched_users);
205 }115 }
206 116
207 #[tokio::test]117 #[tokio::test]
208 async fn update() {118 async fn update() {
209- let (database_connection, _temp_directory) = test::get_database().await;119+ let db = test::get_database().await;
210-
211- let username = "Tahinli";
212- let created_user = User::create(username, &database_connection).await.unwrap();
213- let created_id = created_user.get_id().to_owned();
214- let created_user_username = created_user.get_username().to_owned();
215 120
216- let updated_user = created_user121+ let created_user = user::create("Tahinli", &db).await.unwrap();
217- .update("Not Tahinli", &database_connection)122+ let updated_user = user::update(&created_user.id, "Not Tahinli", &db)
218 .await123 .await
219 .unwrap();124 .unwrap();
125+ let searched_user = user::read(&created_user.id, &db).await.unwrap();
220 126
221- let searched_user = User::read(updated_user.get_id(), &database_connection)127+ assert_eq!(created_user.id, searched_user.id);
222- .await
223- .unwrap();
224-
225- assert_eq!(&created_id, searched_user.get_id());
226- assert_ne!(&created_user_username, searched_user.get_username());
227 assert_eq!(updated_user, searched_user);128 assert_eq!(updated_user, searched_user);
129+ assert_eq!("Not Tahinli", searched_user.username);
228 }130 }
229 131
230 #[tokio::test]132 #[tokio::test]
231- async fn update_on_unpersistent_user() {133+ async fn update_on_missing_user() {
232- let (database_connection, _temp_directory) = test::get_database().await;134+ let db = test::get_database().await;
233-
234- let username = "Tahinli";
235- let unperistent_user = User::new(username).await.unwrap();
236 135
237- let updated_user = unperistent_user136+ let updated_user = user::update("missing", "Not Tahinli", &db).await;
238- .update("Not Tahinli", &database_connection)
239- .await;
240 137
241- assert!(matches!(138+ assert!(matches!(updated_user, Err(Error::NotFound)));
242- updated_user,
243- Err(Error::Database(database::Error::Update)),
244- ));
245 }139 }
246 140
247 #[tokio::test]141 #[tokio::test]
248 async fn delete() {142 async fn delete() {
249- let (database_connection, _temp_directory) = test::get_database().await;143+ let db = test::get_database().await;
250-
251- let username = "Tahinli";
252- let created_user = User::create(username, &database_connection).await.unwrap();
253- let created_id = created_user.get_id().to_owned();
254- let created_user_username = created_user.get_username().to_owned();
255 144
256- let deleted_user = created_user.delete(&database_connection).await.unwrap();145+ let created_user = user::create("Tahinli", &db).await.unwrap();
146+ let deleted_user = user::delete(&created_user.id, &db).await.unwrap();
257 147
258- assert_eq!(&created_id, deleted_user.get_id());148+ assert_eq!(created_user, deleted_user);
259- assert_eq!(&created_user_username, deleted_user.get_username());
260 }149 }
261 }150 }
crates/server/src/user/database.rsdeleted+0 -61
@@ -1,61 +0,0 @@
1-use crate::{
2- database_::{DB, USER_TABLE},
3- error::{self, Error},
4- user::{User, UserID},
5-};
6-
7-pub(super) async fn create(user: User, database_connection: &DB) -> Result<User, Error> {
8- let result = database_connection
9- .create(user.get_id().as_record_id())
10- .content(user)
11- .await?;
12-
13- result.ok_or_else(|| error::database::Error::Create.into())
14-}
15-
16-pub(super) async fn read(id: &UserID, database_connection: &DB) -> Result<User, Error> {
17- let result = database_connection.select(id.as_record_id()).await?;
18-
19- result.ok_or_else(|| error::database::Error::Read.into())
20-}
21-
22-pub(super) async fn read_by_username(
23- username: &str,
24- database_connection: &DB,
25-) -> Result<Vec<User>, Error> {
26- let mut result = database_connection
27- .query(
28- "
29- SELECT * FROM type::table($table) WHERE username = $username;
30- ",
31- )
32- .bind(("table", USER_TABLE))
33- .bind(("username", username.to_string()))
34- .await?
35- .check()?;
36-
37- let result = result.take::<Vec<User>>(0)?;
38-
39- Ok(result)
40-}
41-
42-pub(super) async fn read_all(database_connection: &DB) -> Result<Vec<User>, Error> {
43- let result = database_connection.select(USER_TABLE).await?;
44-
45- Ok(result)
46-}
47-
48-pub(super) async fn update(user: User, database_connection: &DB) -> Result<User, Error> {
49- let result = database_connection
50- .update(user.get_id().as_record_id())
51- .content(user)
52- .await?;
53-
54- result.ok_or_else(|| error::database::Error::Update.into())
55-}
56-
57-pub(super) async fn delete(id: UserID, database_connection: &DB) -> Result<User, Error> {
58- let result = database_connection.delete(id.as_record_id()).await?;
59-
60- result.ok_or_else(|| error::database::Error::Delete.into())
61-}
crates/server/src/user_community.rsmodified+110 -185
@@ -1,268 +1,193 @@
1-use crate::{1+use crate::{database::DB, error::Error};
2- community::{Community, CommunityID},
3- database_::DB,
4- error::Error,
5- user::{User, UserID},
6-};
7-
8-mod database;
9-
10-#[derive(Debug)]
11-pub enum CommunityEvent {
12- JoinCommunity(JoinCommunity),
13- LeaveCommunity(LeaveCommunity),
14-}
15-
16-#[derive(Debug)]
17-pub struct JoinCommunity {
18- user_id: UserID,
19- community_id: CommunityID,
20-}
21 2
22-impl JoinCommunity {3+pub async fn join(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> {
23- fn new(user_id: &UserID, community_id: &CommunityID) -> Self {4+ db.execute(
24- let user_id = user_id.to_owned();5+ "INSERT INTO user_community (user_id, community_id) VALUES (?1, ?2)",
25- let community_id = community_id.to_owned();6+ (user_id, community_id),
7+ )
8+ .await?;
26 9
27- Self {10+ Ok(())
28- user_id,11+}
29- community_id,
30- }
31- }
32 12
33- pub fn get_user_id(&self) -> &UserID {13+pub async fn leave(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> {
34- &self.user_id14+ let deleted = db
35- }15+ .execute(
16+ "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2",
17+ (user_id, community_id),
18+ )
19+ .await?;
36 20
37- pub fn get_community_id(&self) -> &CommunityID {21+ if deleted == 0 {
38- &self.community_id22+ return Err(Error::NotFound);
39 }23 }
40 24
41- pub async fn apply(25+ Ok(())
42- user_id: &UserID,
43- community_id: &CommunityID,
44- database_connection: &DB,
45- ) -> Result<(), Error> {
46- let join_community = Self::new(user_id, community_id);
47-
48- database::join(&join_community, database_connection).await
49- }
50 }26 }
51 27
52-#[derive(Debug)]28+pub async fn is_user_in(user_id: &str, community_id: &str, db: &DB) -> Result<bool, Error> {
53-pub struct LeaveCommunity {29+ let mut rows = db
54- user_id: UserID,30+ .query(
55- community_id: CommunityID,31+ "SELECT COUNT(*) FROM user_community WHERE user_id = ?1 AND community_id = ?2",
32+ (user_id, community_id),
33+ )
34+ .await?;
35+ let row = rows.next().await?.ok_or(Error::NotFound)?;
36+ let count: i64 = row.get(0)?;
37+
38+ Ok(count > 0)
56 }39 }
57 40
58-impl LeaveCommunity {41+pub async fn users_in(community_id: &str, db: &DB) -> Result<Vec<String>, Error> {
59- fn new(user_id: &UserID, community_id: &CommunityID) -> Self {42+ let mut rows = db
60- let user_id = user_id.to_owned();43+ .query(
61- let community_id = community_id.to_owned();44+ "SELECT user_id FROM user_community WHERE community_id = ?1 ORDER BY user_id",
62-45+ (community_id,),
63- Self {46+ )
64- user_id,47+ .await?;
65- community_id,48+
66- }49+ let mut user_ids = Vec::new();
50+ while let Some(row) = rows.next().await? {
51+ user_ids.push(row.get(0)?);
67 }52 }
68 53
69- pub fn get_user_id(&self) -> &UserID {54+ Ok(user_ids)
70- &self.user_id
71- }
72-
73- pub fn get_community_id(&self) -> &CommunityID {
74- &self.community_id
75- }
76-
77- pub async fn apply(
78- user_id: &UserID,
79- community_id: &CommunityID,
80- database_connection: &DB,
81- ) -> Result<(), Error> {
82- let leave_community = Self::new(user_id, community_id);
83-
84- database::leave(&leave_community, database_connection).await
85- }
86 }55 }
87 56
88-pub async fn is_user_in(57+pub async fn communities_of(user_id: &str, db: &DB) -> Result<Vec<String>, Error> {
89- user: &User,58+ let mut rows = db
90- community: &Community,59+ .query(
91- database_connection: &DB,60+ "SELECT community_id FROM user_community WHERE user_id = ?1 ORDER BY community_id",
92-) -> Result<bool, Error> {61+ (user_id,),
93- database::is_user_in(user, community, database_connection).await62+ )
94-}63+ .await?;
64+
65+ let mut community_ids = Vec::new();
66+ while let Some(row) = rows.next().await? {
67+ community_ids.push(row.get(0)?);
68+ }
95 69
96-pub async fn users_in(70+ Ok(community_ids)
97- community: &Community,
98- database_connection: &DB,
99-) -> Result<Vec<UserID>, Error> {
100- database::users_in(community, database_connection).await
101-}
102-pub async fn communitys_of(
103- user: &User,
104- database_connection: &DB,
105-) -> Result<Vec<CommunityID>, Error> {
106- database::communitys_of(user, database_connection).await
107 }71 }
108 72
109 #[cfg(test)]73 #[cfg(test)]
110 mod tests {74 mod tests {
111- use crate::{75+ use crate::{community, error::Error, test, user, user_community};
112- community::Community,
113- error::{Error, database},
114- test,
115- user::User,
116- user_community::{self, JoinCommunity, LeaveCommunity, is_user_in},
117- };
118 76
119 #[tokio::test]77 #[tokio::test]
120 async fn join() {78 async fn join() {
121- let (database_connection, _temp_directory) = test::get_database().await;79+ let db = test::get_database().await;
122 80
123- let user = User::create("Tahinli", &database_connection).await.unwrap();81+ let user = user::create("Tahinli", &db).await.unwrap();
124- let community = Community::create("The Community", &database_connection)82+ let community = community::create("The Community", &db).await.unwrap();
125- .await
126- .unwrap();
127-
128- let join =
129- JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection).await;
130 83
131- assert_eq!(true, join.is_ok());84+ user_community::join(&user.id, &community.id, &db)
132-
133- let is_user_in = is_user_in(&user, &community, &database_connection)
134 .await85 .await
135 .unwrap();86 .unwrap();
136 87
137- assert!(is_user_in);88+ assert!(
89+ user_community::is_user_in(&user.id, &community.id, &db)
90+ .await
91+ .unwrap()
92+ );
138 }93 }
139 94
140 #[tokio::test]95 #[tokio::test]
141 async fn join_again() {96 async fn join_again() {
142- let (database_connection, _temp_directory) = test::get_database().await;97+ let db = test::get_database().await;
143 98
144- let user = User::create("Tahinli", &database_connection).await.unwrap();99+ let user = user::create("Tahinli", &db).await.unwrap();
145- let community = Community::create("The Community", &database_connection)100+ let community = community::create("The Community", &db).await.unwrap();
146- .await
147- .unwrap();
148 101
149- JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection)102+ user_community::join(&user.id, &community.id, &db)
150 .await103 .await
151 .unwrap();104 .unwrap();
152 105
153- let join =106+ assert!(
154- JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection).await;107+ user_community::join(&user.id, &community.id, &db)
155-108+ .await
156- assert!(join.is_err());109+ .is_err()
110+ );
157 }111 }
158 112
159 #[tokio::test]113 #[tokio::test]
160 async fn leave() {114 async fn leave() {
161- let (database_connection, _temp_directory) = test::get_database().await;115+ let db = test::get_database().await;
162 116
163- let user = User::create("Tahinli", &database_connection).await.unwrap();117+ let user = user::create("Tahinli", &db).await.unwrap();
164- let community = Community::create("The Community", &database_connection)118+ let community = community::create("The Community", &db).await.unwrap();
165- .await119+ user_community::join(&user.id, &community.id, &db)
166- .unwrap();
167- JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection)
168 .await120 .await
169 .unwrap();121 .unwrap();
170 122
171- let leave =123+ user_community::leave(&user.id, &community.id, &db)
172- LeaveCommunity::apply(user.get_id(), community.get_id(), &database_connection).await;
173-
174- assert!(leave.is_ok());
175-
176- let is_user_in = is_user_in(&user, &community, &database_connection)
177 .await124 .await
178 .unwrap();125 .unwrap();
179 126
180- assert!(!is_user_in);127+ assert!(
128+ !user_community::is_user_in(&user.id, &community.id, &db)
129+ .await
130+ .unwrap()
131+ );
181 }132 }
182 133
183 #[tokio::test]134 #[tokio::test]
184 async fn leave_again() {135 async fn leave_again() {
185- let (database_connection, _temp_directory) = test::get_database().await;136+ let db = test::get_database().await;
186 137
187- let user = User::create("Tahinli", &database_connection).await.unwrap();138+ let user = user::create("Tahinli", &db).await.unwrap();
188- let community = Community::create("The Community", &database_connection)139+ let community = community::create("The Community", &db).await.unwrap();
140+ user_community::join(&user.id, &community.id, &db)
189 .await141 .await
190 .unwrap();142 .unwrap();
191- JoinCommunity::apply(user.get_id(), community.get_id(), &database_connection)143+ user_community::leave(&user.id, &community.id, &db)
192 .await144 .await
193 .unwrap();145 .unwrap();
194 146
195- LeaveCommunity::apply(user.get_id(), community.get_id(), &database_connection)147+ let leave = user_community::leave(&user.id, &community.id, &db).await;
196- .await
197- .unwrap();
198-
199- let leave =
200- LeaveCommunity::apply(user.get_id(), community.get_id(), &database_connection).await;
201 148
202- assert!(matches!(149+ assert!(matches!(leave, Err(Error::NotFound)));
203- leave,
204- Err(Error::Database(database::Error::Delete))
205- ));
206 }150 }
207 151
208 #[tokio::test]152 #[tokio::test]
209 async fn users_in() {153 async fn users_in() {
210- let (database_connection, _temp_directory) = test::get_database().await;154+ let db = test::get_database().await;
211 155
212- let user_1 = User::create("Tahinli", &database_connection).await.unwrap();156+ let user_1 = user::create("Tahinli", &db).await.unwrap();
213- let user_2 = User::create("Tahinli", &database_connection).await.unwrap();157+ let user_2 = user::create("Tahinli", &db).await.unwrap();
214- let _user_3 = User::create("Tahinli", &database_connection).await.unwrap();158+ let _user_3 = user::create("Tahinli", &db).await.unwrap();
215- let community = Community::create("The Community", &database_connection)159+ let community = community::create("The Community", &db).await.unwrap();
216- .await
217- .unwrap();
218 160
219- JoinCommunity::apply(user_1.get_id(), community.get_id(), &database_connection)161+ user_community::join(&user_1.id, &community.id, &db)
220 .await162 .await
221 .unwrap();163 .unwrap();
222-164+ user_community::join(&user_2.id, &community.id, &db)
223- JoinCommunity::apply(user_2.get_id(), community.get_id(), &database_connection)
224 .await165 .await
225 .unwrap();166 .unwrap();
226 167
227- let users_in = user_community::users_in(&community, &database_connection)168+ let users_in = user_community::users_in(&community.id, &db).await.unwrap();
228- .await
229- .unwrap();
230- let expected_result = vec![user_1.get_id().to_owned(), user_2.get_id().to_owned()];
231 169
232- assert_eq!(users_in, expected_result)170+ assert_eq!(vec![user_1.id, user_2.id], users_in);
233 }171 }
234 172
235 #[tokio::test]173 #[tokio::test]
236- async fn communitys_of() {174+ async fn communities_of() {
237- let (database_connection, _temp_directory) = test::get_database().await;175+ let db = test::get_database().await;
238 176
239- let user = User::create("Tahinli", &database_connection).await.unwrap();177+ let user = user::create("Tahinli", &db).await.unwrap();
240- let community_1 = Community::create("The Community", &database_connection)178+ let community_1 = community::create("The Community", &db).await.unwrap();
241- .await179+ let community_2 = community::create("The Community", &db).await.unwrap();
242- .unwrap();180+ let _community_3 = community::create("The Community", &db).await.unwrap();
243- let community_2 = Community::create("The Community", &database_connection)
244- .await
245- .unwrap();
246- let _community_3 = Community::create("The Community", &database_connection)
247- .await
248- .unwrap();
249 181
250- JoinCommunity::apply(user.get_id(), community_1.get_id(), &database_connection)182+ user_community::join(&user.id, &community_1.id, &db)
251 .await183 .await
252 .unwrap();184 .unwrap();
253-185+ user_community::join(&user.id, &community_2.id, &db)
254- JoinCommunity::apply(user.get_id(), community_2.get_id(), &database_connection)
255 .await186 .await
256 .unwrap();187 .unwrap();
257 188
258- let communitys_of = user_community::communitys_of(&user, &database_connection)189+ let communities_of = user_community::communities_of(&user.id, &db).await.unwrap();
259- .await
260- .unwrap();
261- let expected_result = vec![
262- community_1.get_id().to_owned(),
263- community_2.get_id().to_owned(),
264- ];
265 190
266- assert_eq!(communitys_of, expected_result)191+ assert_eq!(vec![community_1.id, community_2.id], communities_of);
267 }192 }
268 }193 }
crates/server/src/user_community/database.rsdeleted+0 -105
@@ -1,105 +0,0 @@
1-use surrealdb::types::Value;
2-
3-use crate::{
4- community::{Community, CommunityID},
5- database_::{COMMUNITY_TABLE, DB, USER_COMMUNITY_TABLE, USER_TABLE},
6- error::{Error, database},
7- user::{User, UserID},
8- user_community::{JoinCommunity, LeaveCommunity},
9-};
10-
11-pub(super) async fn join(
12- join_community: &JoinCommunity,
13- database_connection: &DB,
14-) -> Result<(), Error> {
15- let query = format!("RELATE $user_id->{USER_COMMUNITY_TABLE}-> $community_id;");
16- database_connection
17- .query(query)
18- .bind(("user_id", join_community.get_user_id().as_record_id()))
19- .bind((
20- "community_id",
21- join_community.get_community_id().as_record_id(),
22- ))
23- .await?
24- .check()?;
25-
26- Ok(())
27-}
28-
29-pub(super) async fn leave(
30- leave_community: &LeaveCommunity,
31- database_connection: &DB,
32-) -> Result<(), Error> {
33- let query =
34- format!("DELETE $user_id->{USER_COMMUNITY_TABLE} WHERE out = $community_id RETURN BEFORE;");
35- let mut result = database_connection
36- .query(query)
37- .bind(("user_id", leave_community.get_user_id().as_record_id()))
38- .bind((
39- "community_id",
40- leave_community.get_community_id().as_record_id(),
41- ))
42- .await?
43- .check()?;
44-
45- let deleted = result.take::<Vec<Value>>(0)?;
46- if deleted.is_empty() {
47- return Err(database::Error::Delete.into());
48- } else {
49- Ok(())
50- }
51-}
52-
53-pub(super) async fn is_user_in(
54- user: &User,
55- community: &Community,
56- database_connection: &DB,
57-) -> Result<bool, Error> {
58- let query = format!(
59- "RETURN count(SELECT 1 FROM {USER_COMMUNITY_TABLE} WHERE in = $user_id AND out = $community_id) > 0;"
60- );
61- let mut result = database_connection
62- .query(query)
63- .bind(("user_id", user.get_id().as_record_id()))
64- .bind(("community_id", community.get_id().as_record_id()))
65- .await?
66- .check()?;
67-
68- let result = result.take::<Option<bool>>(0)?;
69-
70- Ok(result.unwrap_or(false))
71-}
72-
73-pub(super) async fn users_in(
74- community: &Community,
75- database_connection: &DB,
76-) -> Result<Vec<UserID>, Error> {
77- let query = format!("RETURN $community_id<-{USER_COMMUNITY_TABLE}<-{USER_TABLE};");
78- let mut result = database_connection
79- .query(query)
80- .bind(("community_id", community.get_id().as_record_id()))
81- .await?
82- .check()?;
83-
84- let mut result = result.take::<Vec<UserID>>(0)?;
85- result.sort();
86-
87- Ok(result)
88-}
89-
90-pub(super) async fn communitys_of(
91- user: &User,
92- database_connection: &DB,
93-) -> Result<Vec<CommunityID>, Error> {
94- let query = format!("RETURN $user_id->{USER_COMMUNITY_TABLE}->{COMMUNITY_TABLE};");
95- let mut result = database_connection
96- .query(query)
97- .bind(("user_id", user.get_id().as_record_id()))
98- .await?
99- .check()?;
100-
101- let mut result = result.take::<Vec<CommunityID>>(0)?;
102- result.sort();
103-
104- Ok(result)
105-}